text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def description(self, value): """Fetches the translated description for the given datatype. The given value will be converted to a `numpy.dtype` object, matched against the supported datatypes and the description will be translated into the preferred language. (Usually a settings dialog should be available to change the language). If the conversion fails or no match can be found, `None` will be returned. Args: value (type|numpy.dtype): Any object or type. Returns: str: The translated description of the datatype None: If no match could be found or an error occured during convertion. """
# lists, tuples, dicts refer to numpy.object types and # return a 'text' description - working as intended or bug? try: value = np.dtype(value) except TypeError as e: return None for (dtype, string) in self._all: if dtype == value: return string # no match found return given value return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertTimestamps(column): """Convert a dtype of a given column to a datetime. This method tries to do this by brute force. Args: column (pandas.Series): A Series object with all rows. Returns: column: Converted to datetime if no errors occured, else the original column will be returned. """
tempColumn = column try: # Try to convert the first row and a random row instead of the complete # column, might be faster # tempValue = np.datetime64(column[0]) tempValue = np.datetime64(column[randint(0, len(column.index) - 1)]) tempColumn = column.apply(to_datetime) except Exception: pass return tempColumn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def superReadCSV(filepath, first_codec='UTF_8', usecols=None, low_memory=False, dtype=None, parse_dates=True, sep=',', chunksize=None, verbose=False, **kwargs): """ A wrap to pandas read_csv with mods to accept a dataframe or filepath. returns dataframe untouched, reads filepath and returns dataframe based on arguments. """
if isinstance(filepath, pd.DataFrame): return filepath assert isinstance(first_codec, str), "first_codec must be a string" codecs = ['UTF_8', 'ISO-8859-1', 'ASCII', 'UTF_16', 'UTF_32'] try: codecs.remove(first_codec) except ValueError as not_in_list: pass codecs.insert(0, first_codec) errors = [] for c in codecs: try: return pd.read_csv(filepath, usecols=usecols, low_memory=low_memory, encoding=c, dtype=dtype, parse_dates=parse_dates, sep=sep, chunksize=chunksize, **kwargs) # Need to catch `UnicodeError` here, not just `UnicodeDecodeError`, # because pandas 0.23.1 raises it when decoding with UTF_16 and the # file is not in that format: except (UnicodeError, UnboundLocalError) as e: errors.append(e) except Exception as e: errors.append(e) if 'tokenizing' in str(e): pass else: raise if verbose: [print(e) for e in errors] raise UnicodeDecodeError("Tried {} codecs and failed on all: \n CODECS: {} \n FILENAME: {}".format( len(codecs), codecs, os.path.basename(filepath)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dedupe_cols(frame): """ Need to dedupe columns that have the same name. """
cols = list(frame.columns) for i, item in enumerate(frame.columns): if item in frame.columns[:i]: cols[i] = "toDROP" frame.columns = cols return frame.drop("toDROP", 1, errors='ignore')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setEditorData(self, spinBox, index): """Sets the data to be displayed and edited by the editor from the data model item specified by the model index. Args: spinBox (BigIntSpinbox): editor widget. index (QModelIndex): model data index. """
if index.isValid(): value = index.model().data(index, QtCore.Qt.EditRole) spinBox.setValue(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createEditor(self, parent, option, index): """Creates an Editor Widget for the given index. Enables the user to manipulate the displayed data in place. An editor is created, which performs the change. The widget used will be a `QComboBox` with all available datatypes in the `pandas` project. Args: parent (QtCore.QWidget): Defines the parent for the created editor. option (QtGui.QStyleOptionViewItem): contains all the information that QStyle functions need to draw the items. index (QtCore.QModelIndex): The item/index which shall be edited. Returns: QtGui.QWidget: he widget used to edit the item specified by index for editing. """
combo = QtGui.QComboBox(parent) combo.addItems(SupportedDtypes.names()) combo.currentIndexChanged.connect(self.currentIndexChanged) return combo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setEditorData(self, editor, index): """Sets the current data for the editor. The data displayed has the same value as `index.data(Qt.EditRole)` (the translated name of the datatype). Therefor a lookup for all items of the combobox is made and the matching item is set as the currently displayed item. Signals emitted by the editor are blocked during exection of this method. Args: editor (QtGui.QComboBox): The current editor for the item. Should be a `QtGui.QComboBox` as defined in `createEditor`. index (QtCore.QModelIndex): The index of the current item. """
editor.blockSignals(True) data = index.data() dataIndex = editor.findData(data) # dataIndex = editor.findData(data, role=Qt.EditRole) editor.setCurrentIndex(dataIndex) editor.blockSignals(False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setModelData(self, editor, model, index): """Updates the model after changing data in the editor. Args: editor (QtGui.QComboBox): The current editor for the item. Should be a `QtGui.QComboBox` as defined in `createEditor`. model (ColumnDtypeModel): The model which holds the displayed data. index (QtCore.QModelIndex): The index of the current item of the model. """
model.setData(index, editor.itemText(editor.currentIndex()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accepted(self): """Successfully close the widget and emit an export signal. This method is also a `SLOT`. The dialog will be closed, when the `Export Data` button is pressed. If errors occur during the export, the status bar will show the error message and the dialog will not be closed. """
#return super(DataFrameExportDialog, self).accepted try: self._saveModel() except Exception as err: self._statusBar.showMessage(str(err)) raise else: self._resetWidgets() self.exported.emit(True) self.accept()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rejected(self): """Close the widget and reset its inital state. This method is also a `SLOT`. The dialog will be closed and all changes reverted, when the `cancel` button is pressed. """
self._resetWidgets() self.exported.emit(False) self.reject()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stepEnabled(self): """Virtual function that determines whether stepping up and down is legal at any given time. Returns: ored combination of StepUpEnabled | StepDownEnabled """
if self.value() > self.minimum() and self.value() < self.maximum(): return self.StepUpEnabled | self.StepDownEnabled elif self.value() <= self.minimum(): return self.StepUpEnabled elif self.value() >= self.maximum(): return self.StepDownEnabled
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setSingleStep(self, singleStep): """setter to _singleStep. converts negativ values to positiv ones. Args: singleStep (int): new _singleStep value. converts negativ values to positiv ones. Raises: TypeError: If the given argument is not an integer. Returns: int or long: the absolute value of the given argument. """
if not isinstance(singleStep, int): raise TypeError("Argument is not of type int") # don't use negative values self._singleStep = abs(singleStep) return self._singleStep
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setMinimum(self, minimum): """setter to _minimum. Args: minimum (int or long): new _minimum value. Raises: TypeError: If the given argument is not an integer. """
if not isinstance(minimum, int): raise TypeError("Argument is not of type int or long") self._minimum = minimum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setMaximum(self, maximum): """setter to _maximum. Args: maximum (int or long): new _maximum value """
if not isinstance(maximum, int): raise TypeError("Argument is not of type int or long") self._maximum = maximum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_file(self, filepath, save_as=None, keep_orig=False, **kwargs): """ Saves a DataFrameModel to a file. :param filepath: (str) The filepath of the DataFrameModel to save. :param save_as: (str, default None) The new filepath to save as. :param keep_orig: (bool, default False) True keeps the original filepath/DataFrameModel if save_as is specified. :param kwargs: pandas.DataFrame.to_excel(**kwargs) if .xlsx pandas.DataFrame.to_csv(**kwargs) otherwise. :return: None """
df = self._models[filepath].dataFrame() kwargs['index'] = kwargs.get('index', False) if save_as is not None: to_path = save_as else: to_path = filepath ext = os.path.splitext(to_path)[1].lower() if ext == ".xlsx": kwargs.pop('sep', None) df.to_excel(to_path, **kwargs) elif ext in ['.csv','.txt']: df.to_csv(to_path, **kwargs) else: raise NotImplementedError("Cannot save file of type {}".format(ext)) if save_as is not None: if keep_orig is False: # Re-purpose the original model # Todo - capture the DataFrameModelManager._updates too model = self._models.pop(filepath) model._filePath = to_path else: # Create a new model. model = DataFrameModel() model.setDataFrame(df, copyDataFrame=True, filePath=to_path) self._models[to_path] = model
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exception_format(): """ Convert exception info into a string suitable for display. """
return "".join(traceback.format_exception( sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2] ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_tk_image(filename): """ Load in an image file and return as a tk Image. :param filename: image filename to load :return: tk Image object """
if filename is None: return None if not os.path.isfile(filename): raise ValueError('Image file {} does not exist.'.format(filename)) tk_image = None filename = os.path.normpath(filename) _, ext = os.path.splitext(filename) try: pil_image = PILImage.open(filename) tk_image = PILImageTk.PhotoImage(pil_image) except: try: # Fallback if PIL isn't available tk_image = tk.PhotoImage(file=filename) except: msg = "Cannot load {}. Check to make sure it is an image file.".format(filename) try: _ = PILImage except: msg += "\nPIL library isn't installed. If it isn't installed, only .gif files can be used." raise ValueError(msg) return tk_image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setDataFrame(self, dataFrame): """setter function to _dataFrame. Holds all data. Note: It's not implemented with python properties to keep Qt conventions. Raises: TypeError: if dataFrame is not of type pandas.core.frame.DataFrame. Args: dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed. """
if not isinstance(dataFrame, pandas.core.frame.DataFrame): raise TypeError('Argument is not of type pandas.core.frame.DataFrame') self.layoutAboutToBeChanged.emit() self._dataFrame = dataFrame self.layoutChanged.emit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setEditable(self, editable): """setter to _editable. apply changes while changing dtype. Raises: TypeError: if editable is not of type bool. Args: editable (bool): apply changes while changing dtype. """
if not isinstance(editable, bool): raise TypeError('Argument is not of type bool') self._editable = editable
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self, index, role=Qt.DisplayRole): """Retrieve the data stored in the model at the given `index`. Args: index (QtCore.QModelIndex): The model index, which points at a data object. role (Qt.ItemDataRole, optional): Defaults to `Qt.DisplayRole`. You have to use different roles to retrieve different data for an `index`. Accepted roles are `Qt.DisplayRole`, `Qt.EditRole` and `DTYPE_ROLE`. Returns: None if an invalid index is given, the role is not accepted by the model or the column is greater than `1`. The column name will be returned if the given column number equals `0` and the role is either `Qt.DisplayRole` or `Qt.EditRole`. The datatype will be returned, if the column number equals `1`. The `Qt.DisplayRole` or `Qt.EditRole` return a human readable, translated string, whereas the `DTYPE_ROLE` returns the raw data type. """
# an index is invalid, if a row or column does not exist or extends # the bounds of self.columnCount() or self.rowCount() # therefor a check for col>1 is unnecessary. if not index.isValid(): return None col = index.column() #row = self._dataFrame.columns[index.column()] columnName = self._dataFrame.columns[index.row()] columnDtype = self._dataFrame[columnName].dtype if role == Qt.DisplayRole or role == Qt.EditRole: if col == 0: if columnName == index.row(): return index.row() return columnName elif col == 1: return SupportedDtypes.description(columnDtype) elif role == DTYPE_ROLE: if col == 1: return columnDtype else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setData(self, index, value, role=DTYPE_CHANGE_ROLE): """Updates the datatype of a column. The model must be initated with a dataframe already, since valid indexes are necessary. The `value` is a translated description of the data type. The translations can be found at `qtpandas.translation.DTypeTranslator`. If a datatype can not be converted, e.g. datetime to integer, a `NotImplementedError` will be raised. Args: index (QtCore.QModelIndex): The index of the column to be changed. value (str): The description of the new datatype, e.g. `positive kleine ganze Zahl (16 Bit)`. role (Qt.ItemDataRole, optional): The role, which accesses and changes data. Defaults to `DTYPE_CHANGE_ROLE`. Raises: NotImplementedError: If an error during conversion occured. Returns: bool: `True` if the datatype could be changed, `False` if not or if the new datatype equals the old one. """
if role != DTYPE_CHANGE_ROLE or not index.isValid(): return False if not self.editable(): return False self.layoutAboutToBeChanged.emit() dtype = SupportedDtypes.dtype(value) currentDtype = np.dtype(index.data(role=DTYPE_ROLE)) if dtype is not None: if dtype != currentDtype: # col = index.column() # row = self._dataFrame.columns[index.column()] columnName = self._dataFrame.columns[index.row()] try: if dtype == np.dtype('<M8[ns]'): if currentDtype in SupportedDtypes.boolTypes(): raise Exception("Can't convert a boolean value into a datetime value.") self._dataFrame[columnName] = self._dataFrame[columnName].apply(pandas.to_datetime) else: self._dataFrame[columnName] = self._dataFrame[columnName].astype(dtype) self.dtypeChanged.emit(index.row(), dtype) self.layoutChanged.emit() return True except Exception: message = 'Could not change datatype %s of column %s to datatype %s' % (currentDtype, columnName, dtype) self.changeFailed.emit(message, index, dtype) raise # self._dataFrame[columnName] = self._dataFrame[columnName].astype(currentDtype) # self.layoutChanged.emit() # self.dtypeChanged.emit(columnName) #raise NotImplementedError, "dtype changing not fully working, original error:\n{}".format(e) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self): """Applies the filter to the stored dataframe. A safe environment dictionary will be created, which stores all allowed functions and attributes, which may be used for the filter. If any object in the given `filterString` could not be found in the dictionary, the filter does not apply and returns `False`. Returns: tuple: A (indexes, success)-tuple, which indicates identified objects by applying the filter and if the operation was successful in general. """
# there should be a grammar defined and some lexer/parser. # instead of this quick-and-dirty implementation. safeEnvDict = { 'freeSearch': self.freeSearch, 'extentSearch': self.extentSearch, 'indexSearch': self.indexSearch } for col in self._dataFrame.columns: safeEnvDict[col] = self._dataFrame[col] try: searchIndex = eval(self._filterString, { '__builtins__': None}, safeEnvDict) except NameError: return [], False except SyntaxError: return [], False except ValueError: # the use of 'and'/'or' is not valid, need to use binary operators. return [], False except TypeError: # argument must be string or compiled pattern return [], False return searchIndex, True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freeSearch(self, searchString): """Execute a free text search for all columns in the dataframe. Parameters searchString (str): Any string which may be contained in a column. Returns ------- list: A list containing all indexes with filtered data. Matches will be `True`, the remaining items will be `False`. If the dataFrame is empty, an empty list will be returned. """
if not self._dataFrame.empty: # set question to the indexes of data and set everything to false. question = self._dataFrame.index == -9999 for column in self._dataFrame.columns: dfColumn = self._dataFrame[column] dfColumn = dfColumn.apply(str) question2 = dfColumn.str.contains(searchString, flags=re.IGNORECASE, regex=True, na=False) question = np.logical_or(question, question2) return question else: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extentSearch(self, xmin, ymin, xmax, ymax): """Filters the data by a geographical bounding box. The bounding box is given as lower left point coordinates and upper right point coordinates. Note: It's necessary that the dataframe has a `lat` and `lng` column in order to apply the filter. Check if the method could be removed in the future. (could be done via freeSearch) Returns ------- list: A list containing all indexes with filtered data. Matches will be `True`, the remaining items will be `False`. If the dataFrame is empty, an empty list will be returned. """
if not self._dataFrame.empty: try: questionMin = (self._dataFrame.lat >= xmin) & ( self._dataFrame.lng >= ymin) questionMax = (self._dataFrame.lat <= xmax) & ( self._dataFrame.lng <= ymax) return np.logical_and(questionMin, questionMax) except AttributeError: return [] else: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indexSearch(self, indexes): """Filters the data by a list of indexes. Args: indexes (list of int): List of index numbers to return. Returns: list: A list containing all indexes with filtered data. Matches will be `True`, the remaining items will be `False`. If the dataFrame is empty, an empty list will be returned. """
if not self._dataFrame.empty: filter0 = self._dataFrame.index == -9999 for index in indexes: filter1 = self._dataFrame.index == index filter0 = np.logical_or(filter0, filter1) return filter0 else: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_file(filepath, **kwargs): """ Read a data file into a DataFrameModel. :param filepath: The rows/columns filepath to read. :param kwargs: xls/x files - see pandas.read_excel(**kwargs) .csv/.txt/etc - see pandas.read_csv(**kwargs) :return: DataFrameModel """
return DataFrameModel(dataFrame=superReadFile(filepath, **kwargs), filePath=filepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setDataFrame(self, dataFrame, copyDataFrame=False, filePath=None): """ Setter function to _dataFrame. Holds all data. Note: It's not implemented with python properties to keep Qt conventions. Raises: TypeError: if dataFrame is not of type pandas.core.frame.DataFrame. Args: dataFrame (pandas.core.frame.DataFrame): assign dataFrame to _dataFrame. Holds all the data displayed. copyDataFrame (bool, optional): create a copy of dataFrame or use it as is. defaults to False. If you use it as is, you can change it from outside otherwise you have to reset the dataFrame after external changes. """
if not isinstance(dataFrame, pandas.core.frame.DataFrame): raise TypeError("not of type pandas.core.frame.DataFrame") self.layoutAboutToBeChanged.emit() if copyDataFrame: self._dataFrame = dataFrame.copy() else: self._dataFrame = dataFrame self._columnDtypeModel = ColumnDtypeModel(dataFrame) self._columnDtypeModel.dtypeChanged.connect(self.propagateDtypeChanges) self._columnDtypeModel.changeFailed.connect( lambda columnName, index, dtype: self.changingDtypeFailed.emit(columnName, index, dtype) ) if filePath is not None: self._filePath = filePath self.layoutChanged.emit() self.dataChanged.emit() self.dataFrameChanged.emit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timestampFormat(self, timestampFormat): """ Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime Raises: AssertionError: if timestampFormat is not of type unicode. Args: timestampFormat (unicode): assign timestampFormat to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime. Used in data method. """
if not isinstance(timestampFormat, str): raise TypeError('not of type unicode') #assert isinstance(timestampFormat, unicode) or timestampFormat.__class__.__name__ == "DateFormat", "not of type unicode" self._timestampFormat = timestampFormat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self, columnId, order=Qt.AscendingOrder): """ Sorts the model column After sorting the data in ascending or descending order, a signal `layoutChanged` is emitted. :param: columnId (int) the index of the column to sort on. :param: order (Qt::SortOrder, optional) descending(1) or ascending(0). defaults to Qt.AscendingOrder """
self.layoutAboutToBeChanged.emit() self.sortingAboutToStart.emit() column = self._dataFrame.columns[columnId] self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True) self.layoutChanged.emit() self.sortingFinished.emit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setFilter(self, search): """ Apply a filter and hide rows. The filter must be a `DataSearch` object, which evaluates a python expression. If there was an error while parsing the expression, the data will remain unfiltered. Args: search(qtpandas.DataSearch): data search object to use. Raises: TypeError: An error is raised, if the given parameter is not a `DataSearch` object. """
if not isinstance(search, DataSearch): raise TypeError('The given parameter must an `qtpandas.DataSearch` object') self._search = search self.layoutAboutToBeChanged.emit() if self._dataFrameOriginal is not None: self._dataFrame = self._dataFrameOriginal self._dataFrameOriginal = self._dataFrame.copy() self._search.setDataFrame(self._dataFrame) searchIndex, valid = self._search.search() if valid: self._dataFrame = self._dataFrame[searchIndex] self.layoutChanged.emit() else: self.clearFilter() self.layoutChanged.emit() self.dataFrameChanged.emit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clearFilter(self): """ Clear all filters. """
if self._dataFrameOriginal is not None: self.layoutAboutToBeChanged.emit() self._dataFrame = self._dataFrameOriginal self._dataFrameOriginal = None self.layoutChanged.emit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addDataFrameColumn(self, columnName, dtype=str, defaultValue=None): """ Adds a column to the dataframe as long as the model's editable property is set to True and the dtype is supported. :param columnName: str name of the column. :param dtype: qtpandas.models.SupportedDtypes option :param defaultValue: (object) to default the column's value to, should be the same as the dtype or None :return: (bool) True on success, False otherwise. """
if not self.editable or dtype not in SupportedDtypes.allTypes(): return False elements = self.rowCount() columnPosition = self.columnCount() newColumn = pandas.Series([defaultValue]*elements, index=self._dataFrame.index, dtype=dtype) self.beginInsertColumns(QtCore.QModelIndex(), columnPosition - 1, columnPosition - 1) try: self._dataFrame.insert(columnPosition, columnName, newColumn, allow_duplicates=False) except ValueError as e: # columnName does already exist return False self.endInsertColumns() self.propagateDtypeChanges(columnPosition, newColumn.dtype) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeDataFrameRows(self, rows): """ Removes rows from the dataframe. :param rows: (list) of row indexes to removes. :return: (bool) True on success, False on failure. """
if not self.editable: return False if rows: position = min(rows) count = len(rows) self.beginRemoveRows(QtCore.QModelIndex(), position, position + count - 1) removedAny = False for idx, line in self._dataFrame.iterrows(): if idx in rows: removedAny = True self._dataFrame.drop(idx, inplace=True) if not removedAny: return False self._dataFrame.reset_index(inplace=True, drop=True) self.endRemoveRows() return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self): """ Set the values of whatever attributes are recoverable from the pickle file. Populate the attributes (the __dict__) of the EgStore object from the attributes (the __dict__) of the pickled object. If the pickled object has attributes that have been initialized in the EgStore object, then those attributes of the EgStore object will be replaced by the values of the corresponding attributes in the pickled object. If the pickled object is missing some attributes that have been initialized in the EgStore object, then those attributes of the EgStore object will retain the values that they were initialized with. If the pickled object has some attributes that were not initialized in the EgStore object, then those attributes will be ignored. IN SUMMARY: After the recover() operation, the EgStore object will have all, and only, the attributes that it had when it was initialized. Where possible, those attributes will have values recovered from the pickled object. """
if not os.path.exists(self.filename): return self if not os.path.isfile(self.filename): return self try: with open(self.filename, "rb") as f: unpickledObject = pickle.load(f) for key in list(self.__dict__.keys()): default = self.__dict__[key] self.__dict__[key] = unpickledObject.__dict__.get(key, default) except: pass return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store(self): """ Save the attributes of the EgStore object to a pickle file. Note that if the directory for the pickle file does not already exist, the store operation will fail. """
with open(self.filename, "wb") as f: pickle.dump(self, f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None): """ Display a msg, a title, an image, and a set of buttons. The buttons are defined by the members of the choices list. :param str msg: the msg to be displayed :param str title: the window title :param list choices: a list or tuple of the choices to be displayed :param str image: Filename of image to display :param str default_choice: The choice you want highlighted when the gui appears :param str cancel_choice: If the user presses the 'X' close, which button should be pressed :return: the text of the button that the user selected """
global boxRoot, __replyButtonText, buttonsFrame # If default is not specified, select the first button. This matches old # behavior. if default_choice is None: default_choice = choices[0] # Initialize __replyButtonText to the first choice. # This is what will be used if the window is closed by the close button. __replyButtonText = choices[0] if root: root.withdraw() boxRoot = Toplevel(master=root) boxRoot.withdraw() else: boxRoot = Tk() boxRoot.withdraw() boxRoot.title(title) boxRoot.iconname('Dialog') boxRoot.geometry(st.rootWindowPosition) boxRoot.minsize(400, 100) # ------------- define the messageFrame --------------------------------- messageFrame = Frame(master=boxRoot) messageFrame.pack(side=TOP, fill=BOTH) # ------------- define the imageFrame --------------------------------- if image: tk_Image = None try: tk_Image = ut.load_tk_image(image) except Exception as inst: print(inst) if tk_Image: imageFrame = Frame(master=boxRoot) imageFrame.pack(side=TOP, fill=BOTH) label = Label(imageFrame, image=tk_Image) label.image = tk_Image # keep a reference! label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m') # ------------- define the buttonsFrame --------------------------------- buttonsFrame = Frame(master=boxRoot) buttonsFrame.pack(side=TOP, fill=BOTH) # -------------------- place the widgets in the frames ------------------- messageWidget = Message(messageFrame, text=msg, width=400) messageWidget.configure( font=(st.PROPORTIONAL_FONT_FAMILY, st.PROPORTIONAL_FONT_SIZE)) messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') __put_buttons_in_buttonframe(choices, default_choice, cancel_choice) # -------------- the action begins ----------- boxRoot.deiconify() boxRoot.mainloop() boxRoot.destroy() if root: root.deiconify() return __replyButtonText
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __buttonEvent(event=None, buttons=None, virtual_event=None): """ Handle an event that is generated by a person interacting with a button. It may be a button press or a key press. """
# TODO: Replace globals with tkinter variables global boxRoot, __replyButtonText # Determine window location and save to global m = re.match("(\d+)x(\d+)([-+]\d+)([-+]\d+)", boxRoot.geometry()) if not m: raise ValueError( "failed to parse geometry string: {}".format(boxRoot.geometry())) width, height, xoffset, yoffset = [int(s) for s in m.groups()] st.rootWindowPosition = '{0:+g}{1:+g}'.format(xoffset, yoffset) # print('{0}:{1}:{2}'.format(event, buttons, virtual_event)) if virtual_event == 'cancel': for button_name, button in list(buttons.items()): if 'cancel_choice' in button: __replyButtonText = button['original_text'] __replyButtonText = None boxRoot.quit() return if virtual_event == 'select': text = event.widget.config('text')[-1] if not isinstance(text, ut.str): text = ' '.join(text) for button_name, button in list(buttons.items()): if button['clean_text'] == text: __replyButtonText = button['original_text'] boxRoot.quit() return # Hotkeys if buttons: for button_name, button in list(buttons.items()): hotkey_pressed = event.keysym if event.keysym != event.char: # A special character hotkey_pressed = '<{}>'.format(event.keysym) if button['hotkey'] == hotkey_pressed: __replyButtonText = button_name boxRoot.quit() return print("Event not understood")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indexbox(msg="Shall I continue?", title=" ", choices=("Yes", "No"), image=None, default_choice='Yes', cancel_choice='No'): """ Display a buttonbox with the specified choices. :param str msg: the msg to be displayed :param str title: the window title :param list choices: a list or tuple of the choices to be displayed :param str image: Filename of image to display :param str default_choice: The choice you want highlighted when the gui appears :param str cancel_choice: If the user presses the 'X' close, which button should be pressed :return: the index of the choice selected, starting from 0 """
reply = bb.buttonbox(msg=msg, title=title, choices=choices, image=image, default_choice=default_choice, cancel_choice=cancel_choice) if reply is None: return None for i, choice in enumerate(choices): if reply == choice: return i msg = ("There is a program logic error in the EasyGui code " "for indexbox.\nreply={0}, choices={1}".format( reply, choices)) raise AssertionError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK", image=None, root=None): """ Display a message box :param str msg: the msg to be displayed :param str title: the window title :param str ok_button: text to show in the button :param str image: Filename of image to display :param tk_widget root: Top-level Tk widget :return: the text of the ok_button """
if not isinstance(ok_button, ut.str): raise AssertionError( "The 'ok_button' argument to msgbox must be a string.") return bb.buttonbox(msg=msg, title=title, choices=[ok_button], image=image, root=root, default_choice=ok_button, cancel_choice=ok_button)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multenterbox(msg="Fill in values for the fields.", title=" ", fields=(), values=()): r""" Show screen with multiple data entry fields. If there are fewer values than names, the list of values is padded with empty strings until the number of values is the same as the number of names. If there are more values than names, the list of values is truncated so that there are as many values as names. Returns a list of the values of the fields, or None if the user cancels the operation. Here is some example code, that shows how values returned from multenterbox can be checked for validity before they are accepted:: msg = "Enter your personal information" title = "Credit Card Application" fieldNames = ["Name","Street Address","City","State","ZipCode"] fieldValues = [] # we start with blanks for the values fieldValues = multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues is None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg += ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was: %s" % str(fieldValues)) :param str msg: the msg to be displayed. :param str title: the window title :param list fields: a list of fieldnames. :param list values: a list of field values :return: String """
return bb.__multfillablebox(msg, title, fields, values, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exceptionbox(msg=None, title=None): """ Display a box that gives information about an exception that has just been raised. The caller may optionally pass in a title for the window, or a msg to accompany the error information. Note that you do not need to (and cannot) pass an exception object as an argument. The latest exception will automatically be used. :param str msg: the msg to be displayed :param str title: the window title :return: None """
if title is None: title = "Error Report" if msg is None: msg = "An error (exception) has occurred in the program." codebox(msg, title, ut.exception_format())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codebox(msg="", title=" ", text=""): """ Display some text in a monospaced font, with no line wrapping. This function is suitable for displaying code and text that is formatted using spaces. The text parameter should be a string, or a list or tuple of lines to be displayed in the textbox. :param str msg: the msg to be displayed :param str title: the window title :param str text: what to display in the textbox """
return tb.textbox(msg, title, text, codebox=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculateEncodingKey(comparator): """Gets the first key of all available encodings where the corresponding value matches the comparator. Args: comparator (string): A view name for an encoding. Returns: str: A key for a specific encoding used by python. """
encodingName = None for k, v in list(_encodings.items()): if v == comparator: encodingName = k break return encodingName
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initUI(self): """Creates the inital layout with all subwidgets. The layout is a `QHBoxLayout`. Each time a radio button is selected or unselected, a slot `DelimiterSelectionWidget._delimiter` is called. Furthermore the `QLineEdit` widget has a custom regex validator `DelimiterValidator` enabled. """
#layout = QtGui.QHBoxLayout(self) self.semicolonRadioButton = QtGui.QRadioButton('Semicolon') self.commaRadioButton = QtGui.QRadioButton('Comma') self.tabRadioButton = QtGui.QRadioButton('Tab') self.otherRadioButton = QtGui.QRadioButton('Other') self.commaRadioButton.setChecked(True) self.otherSeparatorLineEdit = QtGui.QLineEdit(self) #TODO: Enable this or add BAR radio and option. self.otherSeparatorLineEdit.setEnabled(False) self.semicolonRadioButton.toggled.connect(self._delimiter) self.commaRadioButton.toggled.connect(self._delimiter) self.tabRadioButton.toggled.connect(self._delimiter) self.otherRadioButton.toggled.connect(self._enableLine) self.otherSeparatorLineEdit.textChanged.connect(lambda: self._delimiter(True)) self.otherSeparatorLineEdit.setValidator(DelimiterValidator(self)) currentLayout = self.layout() # unset and delete the current layout in order to set a new one if currentLayout is not None: del currentLayout layout = QtGui.QHBoxLayout() layout.addWidget(self.semicolonRadioButton) layout.addWidget(self.commaRadioButton) layout.addWidget(self.tabRadioButton) layout.addWidget(self.otherRadioButton) layout.addWidget(self.otherSeparatorLineEdit) self.setLayout(layout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def currentSelected(self): """Returns the currently selected delimiter character. Returns: str: One of `,`, `;`, `\t`, `*other*`. """
if self.commaRadioButton.isChecked(): return ',' elif self.semicolonRadioButton.isChecked(): return ';' elif self.tabRadioButton.isChecked(): return '\t' elif self.otherRadioButton.isChecked(): return self.otherSeparatorLineEdit.text() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _openFile(self): """Opens a file dialog and sets a value for the QLineEdit widget. This method is also a `SLOT`. """
file_types = "Comma Separated Values (*.csv);;Text files (*.txt);;All Files (*)" ret = QtGui.QFileDialog.getOpenFileName(self, self.tr('open file'), filter=file_types) if isinstance(ret, tuple): ret = ret[0] #PySide compatibility maybe? if ret: self._filenameLineEdit.setText(ret) self._updateFilename()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateFilename(self): """Calls several methods after the filename changed. This method is also a `SLOT`. It checks the encoding of the changed filename and generates a preview of the data. """
self._filename = self._filenameLineEdit.text() self._guessEncoding(self._filename) self._previewFile()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _guessEncoding(self, path): """Opens a file from the given `path` and checks the file encoding. The file must exists on the file system and end with the extension `.csv`. The file is read line by line until the encoding could be guessed. On a successfull identification, the widgets of this dialog will be updated. Args: path (string): Path to a csv file on the file system. """
if os.path.exists(path) and path.lower().endswith('csv'): # encoding = self._detector.detect(path) encoding = None if encoding is not None: if encoding.startswith('utf'): encoding = encoding.replace('-', '') encoding = encoding.replace('-','_') viewValue = _encodings.get(encoding) self._encodingKey = encoding index = self._encodingComboBox.findText(viewValue.upper()) self._encodingComboBox.setCurrentIndex(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateEncoding(self, index): """Changes the value of the encoding combo box to the value of given index. This method is also a `SLOT`. After the encoding is changed, the file will be reloaded and previewed. Args: index (int): An valid index of the combo box. """
encoding = self._encodingComboBox.itemText(index) encoding = encoding.lower() self._encodingKey = _calculateEncodingKey(encoding) self._previewFile()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _previewFile(self): """Updates the preview widgets with new models for both tab panes. """
dataFrame = self._loadCSVDataFrame() dataFrameModel = DataFrameModel(dataFrame, filePath=self._filename) dataFrameModel.enableEditing(True) self._previewTableView.setModel(dataFrameModel) columnModel = dataFrameModel.columnDtypeModel() columnModel.changeFailed.connect(self.updateStatusBar) self._datatypeTableView.setModel(columnModel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _loadCSVDataFrame(self): """Loads the given csv file with pandas and generate a new dataframe. The file will be loaded with the configured encoding, delimiter and header.git If any execptions will occur, an empty Dataframe is generated and a message will appear in the status bar. Returns: pandas.DataFrame: A dataframe containing all the available information of the csv file. """
if self._filename and os.path.exists(self._filename): # default fallback if no encoding was found/selected encoding = self._encodingKey or 'UTF_8' try: dataFrame = superReadFile(self._filename, sep=self._delimiter, first_codec=encoding, header=self._header) dataFrame = dataFrame.apply(fillNoneValues) dataFrame = dataFrame.apply(convertTimestamps) except Exception as err: self.updateStatusBar(str(err)) print(err) return pandas.DataFrame() self.updateStatusBar('Preview generated.') return dataFrame self.updateStatusBar('File could not be read.') return pandas.DataFrame()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accepted(self): """Successfully close the widget and return the loaded model. This method is also a `SLOT`. The dialog will be closed, when the `ok` button is pressed. If a `DataFrame` was loaded, it will be emitted by the signal `load`. """
model = self._previewTableView.model() if model is not None: df = model.dataFrame().copy() dfModel = DataFrameModel(df) self.load.emit(dfModel, self._filename) print(("Emitted model for {}".format(self._filename))) self._resetWidgets() self.accept()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_pin(self, pin, matrix=None): """Transform correct PIN according to the displayed matrix."""
if matrix is None: _, matrix = self.read_pin() return "".join([str(matrix.index(p) + 1) for p in pin])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _xdr_read_asset(unpacker): """Reads a stellar Asset from unpacker"""
asset = messages.StellarAssetType(type=unpacker.unpack_uint()) if asset.type == ASSET_TYPE_ALPHA4: asset.code = unpacker.unpack_fstring(4) asset.issuer = _xdr_read_address(unpacker) if asset.type == ASSET_TYPE_ALPHA12: asset.code = unpacker.unpack_fstring(12) asset.issuer = _xdr_read_address(unpacker) return asset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _crc16_checksum(bytes): """Returns the CRC-16 checksum of bytearray bytes Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html Initial value changed to 0x0000 to match Stellar configuration. """
crc = 0x0000 polynomial = 0x1021 for byte in bytes: for i in range(8): bit = (byte >> (7 - i) & 1) == 1 c15 = (crc >> 15 & 1) == 1 crc <<= 1 if c15 ^ bit: crc ^= polynomial return crc & 0xFFFF
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def b58encode(v): """ encode v, which is a string of bytes, to base58."""
long_value = 0 for c in v: long_value = long_value * 256 + c result = "" while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == 0: nPad += 1 else: break return (__b58chars[0] * nPad) + result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_nfc(txt): """ Normalize message to NFC and return bytes suitable for protobuf. This seems to be bitcoin-qt standard of doing things. """
if isinstance(txt, bytes): txt = txt.decode() return unicodedata.normalize("NFC", txt).encode()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_protocol(handle: Handle, want_v2: bool) -> Protocol: """Make a Protocol instance for the given handle. Each transport can have a preference for using a particular protocol version. This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable, which forces the library to use V1 anyways. As of 11/2018, no devices support V2, so we enforce V1 here. It is still possible to set `TREZOR_PROTOCOL_V1=0` and thus enable V2 protocol for transports that ask for it (i.e., USB transports for Trezor T). """
force_v1 = int(os.environ.get("TREZOR_PROTOCOL_V1", 1)) if want_v2 and not force_v1: return ProtocolV2(handle) else: return ProtocolV1(handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ping(self) -> bool: """Test if the device is listening."""
assert self.socket is not None resp = None try: self.socket.sendall(b"PINGPING") resp = self.socket.recv(8) except Exception: pass return resp == b"PONGPONG"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint: """Combine a list of Ed25519 points into a "global" CoSi key."""
P = [_ed25519.decodepoint(pk) for pk in pks] combine = reduce(_ed25519.edwards_add, P) return Ed25519PublicPoint(_ed25519.encodepoint(combine))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_sig( global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature] ) -> Ed25519Signature: """Combine a list of signatures into a single CoSi signature."""
S = [_ed25519.decodeint(si) for si in sigs] s = sum(S) % _ed25519.l sig = global_R + _ed25519.encodeint(s) return Ed25519Signature(sig)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_nonce( sk: Ed25519PrivateKey, data: bytes, ctr: int = 0 ) -> Tuple[int, Ed25519PublicPoint]: """Calculate CoSi nonces for given data. These differ from Ed25519 deterministic nonces in that there is a counter appended at end. Returns both the private point `r` and the partial signature `R`. `r` is returned for performance reasons: :func:`sign_with_privkey` takes it as its `nonce` argument so that it doesn't repeat the `get_nonce` call. `R` should be combined with other partial signatures through :func:`combine_keys` to obtain a "global commitment". """
# r = hash(hash(sk)[b .. 2b] + M + ctr) # R = rB h = _ed25519.H(sk) bytesize = _ed25519.b // 8 assert len(h) == bytesize * 2 r = _ed25519.Hint(h[bytesize:] + data + ctr.to_bytes(4, "big")) R = _ed25519.scalarmult(_ed25519.B, r) return r, Ed25519PublicPoint(_ed25519.encodepoint(R))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify( signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint ) -> None: """Verify Ed25519 signature. Raise exception if the signature is invalid."""
# XXX this *might* change to bool function _ed25519.checkvalid(signature, digest, pub_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign_with_privkey( digest: bytes, privkey: Ed25519PrivateKey, global_pubkey: Ed25519PublicPoint, nonce: int, global_commit: Ed25519PublicPoint, ) -> Ed25519Signature: """Create a CoSi signature of `digest` with the supplied private key. This function needs to know the global public key and global commitment. """
h = _ed25519.H(privkey) a = _ed25519.decodecoord(h) S = (nonce + _ed25519.Hint(global_commit + global_pubkey + digest) * a) % _ed25519.l return Ed25519Signature(_ed25519.encodeint(S))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _patch_prebuild(cls): """Patch a setuptools command to depend on `prebuild`"""
orig_run = cls.run def new_run(self): self.run_command("prebuild") orig_run(self) cls.run = new_run
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default_client(path=None, ui=None, **kwargs): """Get a client for a connected Trezor device. Returns a TrezorClient instance with minimum fuss. If no path is specified, finds first connected Trezor. Otherwise performs a prefix-search for the specified device. If no UI is supplied, instantiates the default CLI UI. """
from .transport import get_transport from .ui import ClickUI transport = get_transport(path, prefix_search=True) if ui is None: ui = ClickUI() return TrezorClient(transport, ui, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sel_entries(self): """Generator which returns all SEL entries."""
ENTIRE_RECORD = 0xff rsp = self.send_message_with_name('GetSelInfo') if rsp.entries == 0: return reservation_id = self.get_sel_reservation_id() next_record_id = 0 while True: req = create_request_by_name('GetSelEntry') req.reservation_id = reservation_id req.record_id = next_record_id req.offset = 0 self.max_req_len = ENTIRE_RECORD record_data = ByteBuffer() while True: req.length = self.max_req_len if (self.max_req_len != 0xff and (req.offset + req.length) > 16): req.length = 16 - req.offset rsp = self.send_message(req) if rsp.completion_code == constants.CC_CANT_RET_NUM_REQ_BYTES: if self.max_req_len == 0xff: self.max_req_len = 16 else: self.max_req_len -= 1 continue else: check_completion_code(rsp.completion_code) record_data.extend(rsp.record_data) req.offset = len(record_data) if len(record_data) >= 16: break next_record_id = rsp.next_record_id yield SelEntry(record_data) if next_record_id == 0xffff: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initiate_upgrade_action_and_wait(self, components_mask, action, timeout=2, interval=0.1): """ Initiate Upgrade Action and wait for long running command. """
try: self.initiate_upgrade_action(components_mask, action) except CompletionCodeError as e: if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS: self.wait_for_long_duration_command( constants.CMDID_HPM_INITIATE_UPGRADE_ACTION, timeout, interval) else: raise HpmError('initiate_upgrade_action CC=0x%02x' % e.cc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_binary(self, binary, timeout=2, interval=0.1): """ Upload all firmware blocks from binary and wait for long running command. """
block_number = 0 block_size = self._determine_max_block_size() for chunk in chunks(binary, block_size): try: self.upload_firmware_block(block_number, chunk) except CompletionCodeError as e: if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS: self.wait_for_long_duration_command( constants.CMDID_HPM_UPLOAD_FIRMWARE_BLOCK, timeout, interval) else: raise HpmError('upload_firmware_block CC=0x%02x' % e.cc) block_number += 1 block_number &= 0xff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish_upload_and_wait(self, component, length, timeout=2, interval=0.1): """ Finish the firmware upload process and wait for long running command. """
try: rsp = self.finish_firmware_upload(component, length) check_completion_code(rsp.completion_code) except CompletionCodeError as e: if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS: self.wait_for_long_duration_command( constants.CMDID_HPM_FINISH_FIRMWARE_UPLOAD, timeout, interval) else: raise HpmError('finish_firmware_upload CC=0x%02x' % e.cc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate_firmware_and_wait(self, rollback_override=None, timeout=2, interval=1): """ Activate the new uploaded firmware and wait for long running command. """
try: self.activate_firmware(rollback_override) except CompletionCodeError as e: if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS: self.wait_for_long_duration_command( constants.CMDID_HPM_ACTIVATE_FIRMWARE, timeout, interval) else: raise HpmError('activate_firmware CC=0x%02x' % e.cc) except IpmiTimeoutError: # controller is in reset and flashed new firmware pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_data(self, data): """`data` is array.array"""
self.major = data[0] if data[1] is 0xff: self.minor = data[1] elif data[1] <= 0x99: self.minor = int(data[1:2].tostring().decode('bcd+')) else: raise DecodingError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_routing(self, routing): """Set the path over which a target is reachable. The path is given as a list of tuples in the form (address, bridge_channel). Example #1: access to an ATCA blade in a chassis slave = 0x81, target = 0x82 routing = [(0x81,0x20,0),(0x20,0x82,None)] Example #2: access to an AMC in a uTCA chassis slave = 0x81, target = 0x72 routing = [(0x81,0x20,0),(0x20,0x82,7),(0x20,0x72,None)] uTCA - MCH AMC | ShMC | CM | | MMC | channel=0 | | | channel=7 | | | | | | | | | | | | Example #3: access to an AMC in a ATCA AMC carrier slave = 0x81, target = 0x72 routing = [(0x81,0x20,0),(0x20,0x8e,7),(0x20,0x80,None)] """
if is_string(routing): # if type(routing) in [unicode, str]: routing = ast.literal_eval(routing) self.routing = [Routing(*route) for route in routing]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_command(self, lun, netfn, raw_bytes): """Send the raw command data and return the raw response. lun: the logical unit number netfn: the network function raw_bytes: the raw message as bytestring Returns the response as bytestring. """
return self.interface.send_and_receive_raw(self.target, lun, netfn, raw_bytes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_and_receive(self, target, lun, netfn, cmdid, payload): """Send and receive data using RMCP interface. target: lun: netfn: cmdid: raw_bytes: IPMI message payload as bytestring Returns the received data as array. """
self._inc_sequence_number() header = IpmbHeaderReq() header.netfn = netfn header.rs_lun = lun header.rs_sa = target.ipmb_address header.rq_seq = self.next_sequence_number header.rq_lun = 0 header.rq_sa = self.slave_address header.cmd_id = cmdid # Bridge message if target.routing: tx_data = encode_bridged_message(target.routing, header, payload, self.next_sequence_number) else: tx_data = encode_ipmb_msg(header, payload) self._send_ipmi_msg(tx_data) received = False while received is False: if not self._q.empty(): rx_data = self._q.get() else: rx_data = self._receive_ipmi_msg() if array('B', rx_data)[5] == constants.CMDID_SEND_MESSAGE: rx_data = decode_bridged_message(rx_data) received = rx_filter(header, rx_data) if not received: self._q.put(rx_data) return rx_data[6:-1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_and_receive_raw(self, target, lun, netfn, raw_bytes): """Interface function to send and receive raw message. target: IPMI target lun: logical unit number netfn: network function raw_bytes: RAW bytes as bytestring Returns the IPMI message response bytestring. """
return self._send_and_receive(target=target, lun=lun, netfn=netfn, cmdid=array('B', raw_bytes)[0], payload=raw_bytes[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_and_receive(self, req): """Interface function to send and receive an IPMI message. target: IPMI target req: IPMI message request Returns the IPMI message response. """
rx_data = self._send_and_receive(target=req.target, lun=req.lun, netfn=req.netfn, cmdid=req.cmdid, payload=encode_message(req)) rsp = create_message(req.netfn + 1, req.cmdid, req.group_extension) decode_message(rsp, rx_data) return rsp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_sdr(self, record_id): """ Deletes the sensor record specified by 'record_id'. """
reservation_id = self.reserve_device_sdr_repository() rsp = self.send_message_with_name('DeleteSdr', reservation_id=reservation_id, record_id=record_id) return rsp.record_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sdr_data_helper(reserve_fn, get_fn, record_id, reservation_id=None): """Helper function to retrieve the sdr data using the specified functions. This can be used for SDRs from the Sensor Device or form the SDR repository. """
if reservation_id is None: reservation_id = reserve_fn() (next_id, data) = get_fn(reservation_id, record_id, 0, 5) header = ByteBuffer(data) record_id = header.pop_unsigned_int(2) record_version = header.pop_unsigned_int(1) record_type = header.pop_unsigned_int(1) record_payload_length = header.pop_unsigned_int(1) record_length = record_payload_length + 5 record_data = ByteBuffer(data) offset = len(record_data) max_req_len = 20 retry = 20 # now get the other record data while True: retry -= 1 if retry == 0: raise RetryError() length = max_req_len if (offset + length) > record_length: length = record_length - offset try: (next_id, data) = get_fn(reservation_id, record_id, offset, length) except CompletionCodeError as e: if e.cc == constants.CC_CANT_RET_NUM_REQ_BYTES: # reduce max lenght max_req_len -= 4 if max_req_len <= 0: retry = 0 else: raise CompletionCodeError(e.cc) record_data.extend(data[:]) offset = len(record_data) if len(record_data) >= record_length: break return (next_id, record_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_repository_helper(reserve_fn, clear_fn, retry=5, reservation=None): """Helper function to start repository erasure and wait until finish. This helper is used by clear_sel and clear_sdr_repository. """
if reservation is None: reservation = reserve_fn() # start erasure reservation = _clear_repository(reserve_fn, clear_fn, INITIATE_ERASE, retry, reservation) # give some time to clear time.sleep(0.5) # wait until finish reservation = _clear_repository(reserve_fn, clear_fn, GET_ERASE_STATUS, retry, reservation)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_ipmb_msg(header, data): """Encode an IPMB message. header: IPMB header object data: IPMI message data as bytestring Returns the message as bytestring. """
msg = array('B') msg.fromstring(header.encode()) if data is not None: a = array('B') a.fromstring(data) msg.extend(a) msg.append(checksum(msg[3:])) return msg.tostring()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_send_message(payload, rq_sa, rs_sa, channel, seq, tracking=1): """Encode a send message command and embedd the message to be send. payload: the message to be send as bytestring rq_sa: the requester source address rs_sa: the responder source address channel: the channel seq: the sequence number tracking: tracking Returns an encode send message as bytestring """
req = create_request_by_name('SendMessage') req.channel.number = channel req.channel.tracking = tracking data = encode_message(req) header = IpmbHeaderReq() header.netfn = req.__netfn__ header.rs_lun = 0 header.rs_sa = rs_sa header.rq_seq = seq header.rq_lun = 0 header.rq_sa = rq_sa header.cmd_id = req.__cmdid__ return encode_ipmb_msg(header, data + payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rx_filter(header, data): """Check if the message in rx_data matches to the information in header. The following checks are done: - Header checksum - Payload checksum - NetFn matching - LUN matching - Command Id matching header: the header to compare with data: the received message as bytestring """
rsp_header = IpmbHeaderRsp() rsp_header.decode(data) data = array('B', data) checks = [ (checksum(data[0:3]), 0, 'Header checksum failed'), (checksum(data[3:]), 0, 'payload checksum failed'), # rsp_header.rq_sa, header.rq_sa, 'slave address mismatch'), (rsp_header.netfn, header.netfn | 1, 'NetFn mismatch'), # rsp_header.rs_sa, header.rs_sa, 'target address mismatch'), # rsp_header.rq_lun, header.rq_lun, 'request LUN mismatch'), (rsp_header.rs_lun, header.rs_lun, 'responder LUN mismatch'), (rsp_header.rq_seq, header.rq_seq, 'sequence number mismatch'), (rsp_header.cmd_id, header.cmd_id, 'command id mismatch'), ] match = True for left, right, msg in checks: if left != right: log().debug('{:s}: {:d} {:d}'.format(msg, left, right)) match = False return match
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pack(self): """Pack the message and return an array."""
data = ByteBuffer() if not hasattr(self, '__fields__'): return data.array for field in self.__fields__: field.encode(self, data) return data.array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode(self): """Encode the message and return a bytestring."""
data = ByteBuffer() if not hasattr(self, '__fields__'): return data.tostring() for field in self.__fields__: field.encode(self, data) return data.tostring()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode(self, data): """Decode the bytestring message."""
if not hasattr(self, '__fields__'): raise NotImplementedError('You have to overwrite this method') data = ByteBuffer(data) cc = None for field in self.__fields__: try: field.decode(self, data) except CompletionCodeError as e: # stop decoding on completion code != 0 cc = e.cc break if (cc is None or cc == 0) and len(data) > 0: raise DecodingError('Data has extra bytes')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_and_receive(self, target, lun, netfn, cmdid, payload): """Send and receive data using aardvark interface. target: lun: netfn: cmdid: payload: IPMI message payload as bytestring Returns the received data as bytestring """
self._inc_sequence_number() # assemble IPMB header header = IpmbHeaderReq() header.netfn = netfn header.rs_lun = lun header.rs_sa = target.ipmb_address header.rq_seq = self.next_sequence_number header.rq_lun = 0 header.rq_sa = self.slave_address header.cmd_id = cmdid retries = 0 while retries < self.max_retries: try: self._send_raw(header, payload) rx_data = self._receive_raw(header) break except IpmiTimeoutError: log().warning('I2C transaction timed out'), retries += 1 else: raise IpmiTimeoutError() return rx_data.tostring()[5:-1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_device_sdr(self, record_id, reservation_id=None): """Collects all data from the sensor device to get the SDR specified by record id. `record_id` the Record ID. `reservation_id=None` can be set. if None the reservation ID will be determined. """
(next_id, record_data) = \ get_sdr_data_helper(self.reserve_device_sdr_repository, self._get_device_sdr_chunk, record_id, reservation_id) return sdr.SdrCommon.from_data(record_data, next_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sensor_reading(self, sensor_number, lun=0): """Returns the sensor reading at the assertion states for the given sensor number. `sensor_number` Returns a tuple with `raw reading`and `assertion states`. """
rsp = self.send_message_with_name('GetSensorReading', sensor_number=sensor_number, lun=lun) reading = rsp.sensor_reading if rsp.config.initial_update_in_progress: reading = None states = None if rsp.states1 is not None: states = rsp.states1 if rsp.states2 is not None: states |= (rsp.states2 << 8) return (reading, states)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_sensor_thresholds(self, sensor_number, lun=0, unr=None, ucr=None, unc=None, lnc=None, lcr=None, lnr=None): """Set the sensor thresholds that are not 'None' `sensor_number` `unr` for upper non-recoverable `ucr` for upper critical `unc` for upper non-critical `lnc` for lower non-critical `lcr` for lower critical `lnr` for lower non-recoverable """
req = create_request_by_name('SetSensorThresholds') req.sensor_number = sensor_number req.lun = lun thresholds = dict(unr=unr, ucr=ucr, unc=unc, lnc=lnc, lcr=lcr, lnr=lnr) for key, value in thresholds.items(): if value is not None: setattr(req.set_mask, key, 1) setattr(req.threshold, key, value) rsp = self.send_message(req) check_completion_code(rsp.completion_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_feature(feature_type, feature_size, signal_magnitude, thickness=1): """Generate features corresponding to signal Generate a single feature, that can be inserted into the signal volume. A feature is a region of activation with a specific shape such as cube or ring Parameters feature_type : str What shape signal is being inserted? Options are 'cube', 'loop' (aka ring), 'cavity' (aka hollow sphere), 'sphere'. feature_size : int How big is the signal in diameter? signal_magnitude : float Set the signal size, a value of 1 means the signal is one standard deviation of the noise thickness : int How thick is the surface of the loop/cavity Returns signal : 3 dimensional array The volume representing the signal """
# If the size is equal to or less than 2 then all features are the same if feature_size <= 2: feature_type = 'cube' # What kind of signal is it? if feature_type == 'cube': # Preset the size of the signal signal = np.ones((feature_size, feature_size, feature_size)) elif feature_type == 'loop': # First make a cube of zeros signal = np.zeros((feature_size, feature_size, feature_size)) # Make a mesh grid of the space seq = np.linspace(0, feature_size - 1, feature_size) xx, yy = np.meshgrid(seq, seq) # Make a disk corresponding to the whole mesh grid xxmesh = (xx - ((feature_size - 1) / 2)) ** 2 yymesh = (yy - ((feature_size - 1) / 2)) ** 2 disk = xxmesh + yymesh # What are the limits of the rings being made outer_lim = disk[int((feature_size - 1) / 2), 0] inner_lim = disk[int((feature_size - 1) / 2), thickness] # What is the outer disk outer = disk <= outer_lim # What is the inner disk inner = disk <= inner_lim # Subtract the two disks to get a loop loop = outer != inner # Check if the loop is a disk if np.all(inner is False): logger.warning('Loop feature reduces to a disk because the loop ' 'is too thick') # If there is complete overlap then make the signal just the # outer one if np.all(loop is False): loop = outer # store the loop signal[0:feature_size, 0:feature_size, int(np.round(feature_size / 2))] = loop elif feature_type == 'sphere' or feature_type == 'cavity': # Make a mesh grid of the space seq = np.linspace(0, feature_size - 1, feature_size) xx, yy, zz = np.meshgrid(seq, seq, seq) # Make a disk corresponding to the whole mesh grid signal = ((xx - ((feature_size - 1) / 2)) ** 2 + (yy - ((feature_size - 1) / 2)) ** 2 + (zz - ((feature_size - 1) / 2)) ** 2) # What are the limits of the rings being made outer_lim = signal[int((feature_size - 1) / 2), int((feature_size - 1) / 2), 0] inner_lim = signal[int((feature_size - 1) / 2), int((feature_size - 1) / 2), thickness] # Is the signal a sphere or a cavity? if feature_type == 'sphere': signal = signal <= outer_lim else: # Get the inner and outer sphere outer = signal <= outer_lim inner = signal <= inner_lim # Subtract the two disks to get a loop signal = outer != inner # Check if the cavity is a sphere if np.all(inner is False): logger.warning('Cavity feature reduces to a sphere because ' 'the cavity is too thick') # If there is complete overlap then make the signal just the # outer one if np.all(signal is False): signal = outer # Assign the signal magnitude signal = signal * signal_magnitude # Return the signal return signal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _insert_idxs(feature_centre, feature_size, dimensions): """Returns the indices of where to put the signal into the signal volume Parameters feature_centre : list, int List of coordinates for the centre location of the signal feature_size : list, int How big is the signal's diameter. dimensions : 3 length array, int What are the dimensions of the volume you wish to create Returns x_idxs : tuple The x coordinates of where the signal is to be inserted y_idxs : tuple The y coordinates of where the signal is to be inserted z_idxs : tuple The z coordinates of where the signal is to be inserted """
# Set up the indexes within which to insert the signal x_idx = [int(feature_centre[0] - (feature_size / 2)) + 1, int(feature_centre[0] - (feature_size / 2) + feature_size) + 1] y_idx = [int(feature_centre[1] - (feature_size / 2)) + 1, int(feature_centre[1] - (feature_size / 2) + feature_size) + 1] z_idx = [int(feature_centre[2] - (feature_size / 2)) + 1, int(feature_centre[2] - (feature_size / 2) + feature_size) + 1] # Check for out of bounds # Min Boundary if 0 > x_idx[0]: x_idx[0] = 0 if 0 > y_idx[0]: y_idx[0] = 0 if 0 > z_idx[0]: z_idx[0] = 0 # Max Boundary if dimensions[0] < x_idx[1]: x_idx[1] = dimensions[0] if dimensions[1] < y_idx[1]: y_idx[1] = dimensions[1] if dimensions[2] < z_idx[1]: z_idx[1] = dimensions[2] # Return the idxs for data return x_idx, y_idx, z_idx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_signal(dimensions, feature_coordinates, feature_size, feature_type, signal_magnitude=[1], signal_constant=1, ): """Generate volume containing signal Generate signal, of a specific shape in specific regions, for a single volume. This will then be convolved with the HRF across time Parameters dimensions : 1d array, ndarray What are the dimensions of the volume you wish to create feature_coordinates : multidimensional array What are the feature_coordinates of the signal being created. Be aware of clipping: features far from the centre of the brain will be clipped. If you wish to have multiple features then list these as a features x 3 array. To create a feature of a unique shape then supply all the individual feature_coordinates of the shape and set the feature_size to 1. feature_size : list, int How big is the signal. If feature_coordinates=1 then only one value is accepted, if feature_coordinates>1 then either one value must be supplied or m values feature_type : list, string What feature_type of signal is being inserted? Options are cube, loop, cavity, sphere. If feature_coordinates = 1 then only one value is accepted, if feature_coordinates > 1 then either one value must be supplied or m values signal_magnitude : list, float What is the (average) magnitude of the signal being generated? A value of 1 means that the signal is one standard deviation from the noise signal_constant : list, bool Is the signal constant across the feature (for univariate activity) or is it a random pattern of a given magnitude across the feature (for multivariate activity) Returns volume_signal : 3 dimensional array, float Creates a single volume containing the signal """
# Preset the volume volume_signal = np.zeros(dimensions) feature_quantity = round(feature_coordinates.shape[0]) # If there is only one feature_size value then make sure to duplicate it # for all signals if len(feature_size) == 1: feature_size = feature_size * feature_quantity # Do the same for feature_type if len(feature_type) == 1: feature_type = feature_type * feature_quantity if len(signal_magnitude) == 1: signal_magnitude = signal_magnitude * feature_quantity # Iterate through the signals and insert in the data for signal_counter in range(feature_quantity): # What is the centre of this signal if len(feature_size) > 1: feature_centre = np.asarray(feature_coordinates[signal_counter, ]) else: feature_centre = np.asarray(feature_coordinates)[0] # Generate the feature to be inserted in the volume signal = _generate_feature(feature_type[signal_counter], feature_size[signal_counter], signal_magnitude[signal_counter], ) # If the signal is a random noise pattern then multiply these ones by # a noise mask if signal_constant == 0: signal = signal * np.random.random([feature_size[signal_counter], feature_size[signal_counter], feature_size[signal_counter]]) # Pull out the idxs for where to insert the data x_idx, y_idx, z_idx = _insert_idxs(feature_centre, feature_size[signal_counter], dimensions) # Insert the signal into the Volume volume_signal[x_idx[0]:x_idx[1], y_idx[0]:y_idx[1], z_idx[0]:z_idx[ 1]] = signal return volume_signal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_stimfunction(onsets, event_durations, total_time, weights=[1], timing_file=None, temporal_resolution=100.0, ): """Return the function for the timecourse events When do stimuli onset, how long for and to what extent should you resolve the fMRI time course. There are two ways to create this, either by supplying onset, duration and weight information or by supplying a timing file (in the three column format used by FSL). Parameters onsets : list, int What are the timestamps (in s) for when an event you want to generate onsets? event_durations : list, int What are the durations (in s) of the events you want to generate? If there is only one value then this will be assigned to all onsets total_time : int How long (in s) is the experiment in total. weights : list, float What is the weight for each event (how high is the box car)? If there is only one value then this will be assigned to all onsets timing_file : string The filename (with path) to a three column timing file (FSL) to make the events. Still requires total_time to work temporal_resolution : float How many elements per second are you modeling for the timecourse. This is useful when you want to model the HRF at an arbitrarily high resolution (and then downsample to your TR later). Returns stim_function : 1 by timepoint array, float The time course of stimulus evoked activation. This has a temporal resolution of temporal resolution / 1.0 elements per second """
# If the timing file is supplied then use this to acquire the if timing_file is not None: # Read in text file line by line with open(timing_file) as f: text = f.readlines() # Pull out file as a an array # Preset onsets = list() event_durations = list() weights = list() # Pull out the onsets, weights and durations, set as a float for line in text: onset, duration, weight = line.strip().split() # Check if the onset is more precise than the temporal resolution upsampled_onset = float(onset) * temporal_resolution # Because of float precision, the upsampled values might # not round as expected . # E.g. float('1.001') * 1000 = 1000.99 if np.allclose(upsampled_onset, np.round(upsampled_onset)) == 0: warning = 'Your onset: ' + str(onset) + ' has more decimal ' \ 'points than the ' \ 'specified temporal ' \ 'resolution can ' \ 'resolve. This means' \ ' that events might' \ ' be missed. ' \ 'Consider increasing' \ ' the temporal ' \ 'resolution.' logger.warning(warning) onsets.append(float(onset)) event_durations.append(float(duration)) weights.append(float(weight)) # If only one duration is supplied then duplicate it for the length of # the onset variable if len(event_durations) == 1: event_durations = event_durations * len(onsets) if len(weights) == 1: weights = weights * len(onsets) # Check files if np.max(onsets) > total_time: raise ValueError('Onsets outside of range of total time.') # Generate the time course as empty, each element is a millisecond by # default stimfunction = np.zeros((int(round(total_time * temporal_resolution)), 1)) # Cycle through the onsets for onset_counter in list(range(len(onsets))): # Adjust for the resolution onset_idx = int(np.floor(onsets[onset_counter] * temporal_resolution)) # Adjust for the resolution offset_idx = int(np.floor((onsets[onset_counter] + event_durations[ onset_counter]) * temporal_resolution)) # Store the weights stimfunction[onset_idx:offset_idx, 0] = [weights[onset_counter]] return stimfunction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_3_column(stimfunction, filename, temporal_resolution=100.0 ): """ Output a tab separated three column timing file This produces a three column tab separated text file, with the three columns representing onset time (s), event duration (s) and weight, respectively. Useful if you want to run the simulated data through FEAT analyses. In a way, this is the reverse of generate_stimfunction Parameters stimfunction : timepoint by 1 array The stimulus function describing the time course of events. For instance output from generate_stimfunction. filename : str The name of the three column text file to be output temporal_resolution : float How many elements per second are you modeling with the stimfunction? """
# Iterate through the stim function stim_counter = 0 event_counter = 0 while stim_counter < stimfunction.shape[0]: # Is it an event? if stimfunction[stim_counter, 0] != 0: # When did the event start? event_onset = str(stim_counter / temporal_resolution) # The weight of the stimulus weight = str(stimfunction[stim_counter, 0]) # Reset event_duration = 0 # Is the event still ongoing? while stimfunction[stim_counter, 0] != 0 & stim_counter <= \ stimfunction.shape[0]: # Add one millisecond to each duration event_duration = event_duration + 1 # Increment stim_counter = stim_counter + 1 # How long was the event in seconds event_duration = str(event_duration / temporal_resolution) # Append this row to the data file with open(filename, "a") as file: file.write(event_onset + '\t' + event_duration + '\t' + weight + '\n') # Increment the number of events event_counter = event_counter + 1 # Increment stim_counter = stim_counter + 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_epoch_file(stimfunction, filename, tr_duration, temporal_resolution=100.0 ): """ Output an epoch file, necessary for some inputs into brainiak This takes in the time course of stimulus events and outputs the epoch file used in Brainiak. The epoch file is a way to structure the timing information in fMRI that allows you to flexibly input different stimulus sequences. This is a list with each entry a 3d matrix corresponding to a participant. The dimensions of the 3d matrix are condition by epoch by time. For the i-th condition, if its k-th epoch spans time points t_m to t_n-1, then [i, k, t_m:t_n] are 1 in the epoch file. Parameters stimfunction : list of timepoint by condition arrays The stimulus function describing the time course of events. Each list entry is from a different participant, each row is a different timepoint (with the given temporal precision), each column is a different condition. export_epoch_file is looking for differences in the value of stimfunction to identify the start and end of an epoch. If epochs in stimfunction are coded with the same weight and there is no time between blocks then export_epoch_file won't be able to label them as different epochs filename : str The name of the epoch file to be output tr_duration : float How long is each TR in seconds temporal_resolution : float How many elements per second are you modeling with the stimfunction? """
# Cycle through the participants, different entries in the list epoch_file = [0] * len(stimfunction) for ppt_counter in range(len(stimfunction)): # What is the time course for the participant (binarized) stimfunction_ppt = np.abs(stimfunction[ppt_counter]) > 0 # Down sample the stim function stride = tr_duration * temporal_resolution stimfunction_downsampled = stimfunction_ppt[::int(stride), :] # Calculates the number of event onsets. This uses changes in value # to reflect different epochs. This might be false in some cases (the # weight is non-uniform over an epoch or there is no break between # identically weighted epochs). epochs = 0 # Preset conditions = stimfunction_ppt.shape[1] for condition_counter in range(conditions): weight_change = (np.diff(stimfunction_downsampled[:, condition_counter], 1, 0) != 0) # If the first or last events are 'on' then make these # represent a epoch change if stimfunction_downsampled[0, condition_counter] == 1: weight_change[0] = True if stimfunction_downsampled[-1, condition_counter] == 1: weight_change[-1] = True epochs += int(np.max(np.sum(weight_change, 0)) / 2) # Get other information trs = stimfunction_downsampled.shape[0] # Make a timing file for this participant epoch_file[ppt_counter] = np.zeros((conditions, epochs, trs)) # Cycle through conditions epoch_counter = 0 # Reset and count across conditions tr_counter = 0 while tr_counter < stimfunction_downsampled.shape[0]: for condition_counter in range(conditions): # Is it an event? if tr_counter < stimfunction_downsampled.shape[0] and \ stimfunction_downsampled[ tr_counter, condition_counter] == 1: # Add a one for this TR epoch_file[ppt_counter][condition_counter, epoch_counter, tr_counter] = 1 # Find the next non event value end_idx = np.where(stimfunction_downsampled[tr_counter:, condition_counter] == 0)[ 0][0] tr_idxs = list(range(tr_counter, tr_counter + end_idx)) # Add ones to all the trs within this event time frame epoch_file[ppt_counter][condition_counter, epoch_counter, tr_idxs] = 1 # Start from this index tr_counter += end_idx # Increment epoch_counter += 1 # Increment the counter tr_counter += 1 # Convert to boolean epoch_file[ppt_counter] = epoch_file[ppt_counter].astype('bool') # Save the file np.save(filename, epoch_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _double_gamma_hrf(response_delay=6, undershoot_delay=12, response_dispersion=0.9, undershoot_dispersion=0.9, response_scale=1, undershoot_scale=0.035, temporal_resolution=100.0, ): """Create the double gamma HRF with the timecourse evoked activity. Default values are based on Glover, 1999 and Walvaert, Durnez, Moerkerke, Verdoolaege and Rosseel, 2011 Parameters response_delay : float How many seconds until the peak of the HRF undershoot_delay : float How many seconds until the trough of the HRF response_dispersion : float How wide is the rising peak dispersion undershoot_dispersion : float How wide is the undershoot dispersion response_scale : float How big is the response relative to the peak undershoot_scale :float How big is the undershoot relative to the trough scale_function : bool Do you want to scale the function to a range of 1 temporal_resolution : float How many elements per second are you modeling for the stimfunction Returns hrf : multi dimensional array A double gamma HRF to be used for convolution. """
hrf_length = 30 # How long is the HRF being created # How many seconds of the HRF will you model? hrf = [0] * int(hrf_length * temporal_resolution) # When is the peak of the two aspects of the HRF response_peak = response_delay * response_dispersion undershoot_peak = undershoot_delay * undershoot_dispersion for hrf_counter in list(range(len(hrf) - 1)): # Specify the elements of the HRF for both the response and undershoot resp_pow = math.pow((hrf_counter / temporal_resolution) / response_peak, response_delay) resp_exp = math.exp(-((hrf_counter / temporal_resolution) - response_peak) / response_dispersion) response_model = response_scale * resp_pow * resp_exp undershoot_pow = math.pow((hrf_counter / temporal_resolution) / undershoot_peak, undershoot_delay) undershoot_exp = math.exp(-((hrf_counter / temporal_resolution) - undershoot_peak / undershoot_dispersion)) undershoot_model = undershoot_scale * undershoot_pow * undershoot_exp # For this time point find the value of the HRF hrf[hrf_counter] = response_model - undershoot_model return hrf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_signal(signal_function, volume_signal, ): """Combine the signal volume with its timecourse Apply the convolution of the HRF and stimulus time course to the volume. Parameters signal_function : timepoint by timecourse array, float The timecourse of the signal over time. If there is only one column then the same timecourse is applied to all non-zero voxels in volume_signal. If there is more than one column then each column is paired with a non-zero voxel in the volume_signal (a 3d numpy array generated in generate_signal). volume_signal : multi dimensional array, float The volume containing the signal to be convolved with the same dimensions as the output volume. The elements in volume_signal indicate how strong each signal in signal_function are modulated by in the output volume Returns signal : multidimensional array, float The convolved signal volume with the same 3d as volume signal and the same 4th dimension as signal_function """
# How many timecourses are there within the signal_function timepoints = signal_function.shape[0] timecourses = signal_function.shape[1] # Preset volume signal = np.zeros([volume_signal.shape[0], volume_signal.shape[ 1], volume_signal.shape[2], timepoints]) # Find all the non-zero voxels in the brain idxs = np.where(volume_signal != 0) if timecourses == 1: # If there is only one time course supplied then duplicate it for # every voxel signal_function = np.matlib.repmat(signal_function, 1, len(idxs[0])) elif len(idxs[0]) != timecourses: raise IndexError('The number of non-zero voxels in the volume and ' 'the number of timecourses does not match. Aborting') # For each coordinate with a non zero voxel, fill in the timecourse for # that voxel for idx_counter in range(len(idxs[0])): x = idxs[0][idx_counter] y = idxs[1][idx_counter] z = idxs[2][idx_counter] # Pull out the function for this voxel signal_function_temp = signal_function[:, idx_counter] # Multiply the voxel value by the function timecourse signal[x, y, z, :] = volume_signal[x, y, z] * signal_function_temp return signal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calc_sfnr(volume, mask, ): """ Calculate the the SFNR of a volume Calculates the Signal to Fluctuation Noise Ratio, the mean divided by the detrended standard deviation of each brain voxel. Based on Friedman and Glover, 2006 Parameters volume : 4d array, float Take a volume time series mask : 3d array, binary A binary mask the same size as the volume Returns ------- snr : float
 The SFNR of the volume """
# Make a matrix of brain voxels by time brain_voxels = volume[mask > 0] # Take the means of each voxel over time mean_voxels = np.nanmean(brain_voxels, 1) # Detrend (second order polynomial) the voxels over time and then # calculate the standard deviation. order = 2 seq = np.linspace(1, brain_voxels.shape[1], brain_voxels.shape[1]) detrend_poly = np.polyfit(seq, brain_voxels.transpose(), order) # Detrend for each voxel detrend_voxels = np.zeros(brain_voxels.shape) for voxel in range(brain_voxels.shape[0]): trend = detrend_poly[0, voxel] * seq ** 2 + detrend_poly[1, voxel] * \ seq + detrend_poly[2, voxel] detrend_voxels[voxel, :] = brain_voxels[voxel, :] - trend std_voxels = np.nanstd(detrend_voxels, 1) # Calculate the sfnr of all voxels across the brain sfnr_voxels = mean_voxels / std_voxels # Return the average sfnr return np.mean(sfnr_voxels)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calc_snr(volume, mask, dilation=5, reference_tr=None, ): """ Calculate the the SNR of a volume Calculates the Signal to Noise Ratio, the mean of brain voxels divided by the standard deviation across non-brain voxels. Specify a TR value to calculate the mean and standard deviation for that TR. To calculate the standard deviation of non-brain voxels we can subtract any baseline structure away first, hence getting at deviations due to the system noise and not something like high baseline values in non-brain parts of the body. Parameters volume : 4d array, float Take a volume time series mask : 3d array, binary A binary mask the same size as the volume dilation : int How many binary dilations do you want to perform on the mask to determine the non-brain voxels. If you increase this the SNR increases and the non-brain voxels (after baseline subtraction) more closely resemble a gaussian reference_tr : int or list Specifies the TR to calculate the SNR for. If multiple are supplied then it will use the average of them. Returns ------- snr : float
 The SNR of the volume """
# If no TR is specified then take all of them if reference_tr is None: reference_tr = list(range(volume.shape[3])) # Dilate the mask in order to ensure that non-brain voxels are far from # the brain if dilation > 0: mask_dilated = ndimage.morphology.binary_dilation(mask, iterations=dilation) else: mask_dilated = mask # Make a matrix of brain and non_brain voxels, selecting the timepoint/s brain_voxels = volume[mask > 0][:, reference_tr] nonbrain_voxels = (volume[:, :, :, reference_tr]).astype('float64') # If you have multiple TRs if len(brain_voxels.shape) > 1: brain_voxels = np.mean(brain_voxels, 1) nonbrain_voxels = np.mean(nonbrain_voxels, 3) nonbrain_voxels = nonbrain_voxels[mask_dilated == 0] # Take the means of each voxel over time mean_voxels = np.nanmean(brain_voxels) # Find the standard deviation of the voxels std_voxels = np.nanstd(nonbrain_voxels) # Return the snr return mean_voxels / std_voxels