code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return DataFrameModel(dataFrame=superReadFile(filepath, **kwargs), filePath=filepath)
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
33.884445
26.779119
1.265331
# TODO: Decide if chunksize is worth keeping and how to handle? df = pandas.read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize=None) return DataFrameModel(df, filePath=filePath)
def read_sql(sql, con, filePath, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None)
Read SQL query or database table into a DataFrameModel. Provide a filePath argument in addition to the *args/**kwargs from pandas.read_sql and get a DataFrameModel. NOTE: The chunksize option is overridden to None always (for now). Reference: http://pandas.pydata.org/pandas-docs/version/0.18.1/gen...
4.733797
4.419419
1.071135
df = superReadFile(filepath, **kwargs) self.setDataFrame(df, filePath=filepath)
def setDataFrameFromFile(self, filepath, **kwargs)
Sets the model's dataFrame by reading a file. Accepted file formats: - .xlsx (sheet1 is read unless specified in kwargs) - .csv (comma separated unless specified in kwargs) - .txt (any separator) :param filepath: (str) The path to the file to be read. ...
10.449701
15.203395
0.687327
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 ...
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 dataFr...
2.901546
2.935378
0.988474
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
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 c...
5.531268
5.615349
0.985027
kwargs['inplace'] = True self.layoutAboutToBeChanged.emit() self._dataFrame.rename(index, columns, **kwargs) self.layoutChanged.emit() self.dataChanged.emit() self.dataFrameChanged.emit()
def rename(self, index=None, columns=None, **kwargs)
Renames the dataframe inplace calling appropriate signals. Wraps pandas.DataFrame.rename(*args, **kwargs) - overrides the inplace kwarg setting it to True. Example use: renames = {'colname1':'COLNAME_1', 'colname2':'COL2'} DataFrameModel.rename(columns=renames) :param a...
3.430074
3.297294
1.040269
assert callable(func), "function {} is not callable".format(func) self.layoutAboutToBeChanged.emit() df = func(self._dataFrame) assert isinstance(df, pandas.DataFrame), "function {} did not return a DataFrame.".format(func.__name__) self._dataFrame = df self.layo...
def applyFunction(self, func)
Applies a function to the dataFrame with appropriate signals. The function must return a dataframe. :param func: A function (or partial function) that accepts a dataframe as the first argument. :return: None :raise: AssertionError if the func is not callable. Asse...
2.936821
2.66279
1.102911
if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: try: label = self._dataFrame.columns.tolist()[section] if label == section: label = section return label except (Index...
def headerData(self, section, orientation, role=Qt.DisplayRole)
Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number. orientation (Qt::...
3.307702
3.1105
1.063399
if not index.isValid(): return None def convertValue(row, col, columnDtype): value = None if columnDtype == object: value = self._dataFrame.ix[row, col] elif columnDtype in self._floatDtypes: value = round(float(s...
def data(self, index, role=Qt.DisplayRole)
return data depending on index, Qt::ItemDataRole and data type of the column. Args: index (QtCore.QModelIndex): Index to define column and row you want to return role (Qt::ItemDataRole): Define which data you want to return. Returns: None if index is invalid ...
2.884593
2.590648
1.113464
flags = super(DataFrameModel, self).flags(index) if not self.editable: return flags col = self._dataFrame.columns[index.column()] if self._dataFrame[col].dtype == numpy.bool: flags |= Qt.ItemIsUserCheckable else: # if you want to hav...
def flags(self, index)
Returns the item flags for the given index as ored value, e.x.: Qt.ItemIsUserCheckable | Qt.ItemIsEditable If a combobox for bool values should pop up ItemIsEditable have to set for bool columns too. Args: index (QtCore.QModelIndex): Index to define column and row Returns: ...
4.128764
3.78281
1.091454
if not index.isValid() or not self.editable: return False if value != index.data(role): self.layoutAboutToBeChanged.emit() row = self._dataFrame.index[index.row()] col = self._dataFrame.columns[index.column()] #print 'before change:...
def setData(self, index, value, role=Qt.DisplayRole)
Set the value to the index position depending on Qt::ItemDataRole and data type of the column Args: index (QtCore.QModelIndex): Index to define column and row. value (object): new value. role (Qt::ItemDataRole): Use this role to specify what you want to do. Raises: ...
2.953882
3.01342
0.980242
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()
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....
3.014655
3.170145
0.950952
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._dataFrameOrigina...
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. R...
3.396196
2.886256
1.176679
if self._dataFrameOriginal is not None: self.layoutAboutToBeChanged.emit() self._dataFrame = self._dataFrameOriginal self._dataFrameOriginal = None self.layoutChanged.emit()
def clearFilter(self)
Clear all filters.
3.65839
3.468951
1.05461
self.editable = editable self._columnDtypeModel.setEditable(self.editable)
def enableEditing(self, editable=True)
Sets the DataFrameModel and columnDtypeModel's editable properties. :param editable: bool defaults to True, False disables most editing methods. :return: None
13.855651
4.895672
2.830184
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.beginInsertColumn...
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...
4.209489
3.662207
1.149441
if not self.editable: return False if columns: deleted = 0 errored = False for (position, name) in columns: position = position - deleted if position < 0: position = 0 self.begin...
def removeDataFrameColumns(self, columns)
Removes columns from the dataframe. :param columns: [(int, str)] :return: (bool) True on success, False on failure.
3.008504
2.891919
1.040314
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():...
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.
2.651847
2.745922
0.96574
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()): ...
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 ...
2.439671
2.354654
1.036106
with open(self.filename, "wb") as f: pickle.dump(self, f)
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.
3.440145
2.877946
1.195347
if os.path.isfile(self.filename): os.remove(self.filename) return
def kill(self)
Delete my persistent file (i.e. pickle file), if it exists.
4.090777
2.750826
1.487108
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 windo...
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 d...
2.977177
2.96237
1.004998
if msg and title: return "%s - %s" % (title, msg) if msg and not title: return str(msg) if title and not msg: return str(title) return None
def getFileDialogTitle(msg, title)
Create nicely-formatted string based on arguments msg and title :param msg: the msg to be displayed :param title: the window title :return: None
2.405647
2.708154
0.888298
localRoot = Tk() localRoot.withdraw() initialbase, initialfile, initialdir, filetypes = fileboxSetup( default, filetypes) # ------------------------------------------------------------ # if initialfile contains no wildcards; we don't want an # initial file. It won't be used anyway...
def fileopenbox(msg=None, title=None, default='*', filetypes=None, multiple=False)
A dialog to get a file name. **About the "default" argument** The "default" argument specifies a filepath that (normally) contains one or more wildcards. fileopenbox will display only files that match the default filepath. If omitted, defaults to "\*" (all files in the current directory). WIN...
4.554476
4.848936
0.939273
# 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...
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.
4.104078
4.043438
1.014997
global buttonsFrame, cancel_invoke # TODO: I'm using a dict to hold buttons, but this could all be cleaned up if I subclass Button to hold # all the event bindings, etc # TODO: Break __buttonEvent out into three: regular keyboard, default # select, and cancel select. unique_choices = ...
def __put_buttons_in_buttonframe(choices, default_choice, cancel_choice)
Put the buttons in the buttons frame
4.191381
4.169355
1.005283
return boolbox(msg=msg, title=title, choices=choices, image=image, default_choice=default_choice, cancel_choice=cancel_choice)
def ynbox(msg="Shall I continue?", title=" ", choices=("[<F1>]Yes", "[<F2>]No"), image=None, default_choice='[<F1>]Yes', cancel_choice='[<F2>]No')
Display a msgbox with choices of Yes and No. The returned value is calculated this way:: if the first choice ("Yes") is chosen, or if the dialog is cancelled: return True else: return False If invoked without a msg argument, displays a generic request for a confirm...
1.962515
2.951192
0.664991
return boolbox(msg=msg, title=title, choices=choices, image=image, default_choice=default_choice, cancel_choice=cancel_choice)
def ccbox(msg="Shall I continue?", title=" ", choices=("C[o]ntinue", "C[a]ncel"), image=None, default_choice='Continue', cancel_choice='Cancel')
Display a msgbox with choices of Continue and Cancel. The returned value is calculated this way:: if the first choice ("Continue") is chosen, or if the dialog is cancelled: return True else: return False If invoked without a msg argument, displays a generic ...
2.033135
2.939874
0.691572
if len(choices) != 2: raise AssertionError( 'boolbox takes exactly 2 choices! Consider using indexbox instead' ) reply = bb.buttonbox(msg=msg, title=title, choices=choices, image=image, ...
def boolbox(msg="Shall I continue?", title=" ", choices=("[Y]es", "[N]o"), image=None, default_choice='Yes', cancel_choice='No')
Display a boolean msgbox. The returned value is calculated this way:: if the first choice is chosen, or if the dialog is cancelled: returns True else: returns False :param str msg: the msg to be displayed :param str title: the window title :param list choices: ...
3.299753
3.61579
0.912596
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, ...
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 ...
3.385676
3.660075
0.925029
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, ...
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
3.436416
4.249269
0.808708
if not msg: msg = "Enter an integer between {0} and {1}".format( lowerbound, upperbound) # Validate the arguments for default, lowerbound and upperbound and # convert to integers exception_string = ( 'integerbox "{0}" must be an integer. It is >{1}< of type {2}') ...
def integerbox(msg="", title=" ", default="", lowerbound=0, upperbound=99, image=None, root=None)
Show a box in which a user can enter an integer. In addition to arguments for msg and title, this function accepts integer arguments for "default", "lowerbound", and "upperbound". The default argument may be None. When the user enters some text, the text is checked to verify that it can be conver...
2.4593
2.453855
1.002219
r return bb.__multfillablebox(msg, title, fields, values, None)
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 ...
37.288067
46.661152
0.799124
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())
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 au...
7.850254
8.765244
0.895612
return tb.textbox(msg, title, text, codebox=1)
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 :para...
11.703241
19.170031
0.610497
encodingName = None for k, v in list(_encodings.items()): if v == comparator: encodingName = k break return encodingName
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.
4.133039
4.928975
0.838519
#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.commaRadioB...
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.
2.764453
2.429872
1.137695
if self.commaRadioButton.isChecked(): return ',' elif self.semicolonRadioButton.isChecked(): return ';' elif self.tabRadioButton.isChecked(): return '\t' elif self.otherRadioButton.isChecked(): return self.otherSeparatorLineEdit.te...
def currentSelected(self)
Returns the currently selected delimiter character. Returns: str: One of `,`, `;`, `\t`, `*other*`.
3.066015
2.579163
1.188764
self.setModal(self._modal) self.setWindowTitle(self._windowTitle) layout = QtGui.QGridLayout() self._filenameLabel = QtGui.QLabel('Choose File', self) self._filenameLineEdit = QtGui.QLineEdit(self) self._filenameLineEdit.textEdited.connect(self._updateFilename)...
def _initUI(self)
Initiates the user interface with a grid layout and several widgets.
1.879278
1.869096
1.005447
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, tu...
def _openFile(self)
Opens a file dialog and sets a value for the QLineEdit widget. This method is also a `SLOT`.
4.515984
4.402486
1.02578
self._filename = self._filenameLineEdit.text() self._guessEncoding(self._filename) self._previewFile()
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.
9.722107
7.0507
1.378885
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('-', '') encodi...
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 upda...
4.851121
4.494348
1.079383
encoding = self._encodingComboBox.itemText(index) encoding = encoding.lower() self._encodingKey = _calculateEncodingKey(encoding) self._previewFile()
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.
7.198318
9.181344
0.784016
dataFrame = self._loadCSVDataFrame() dataFrameModel = DataFrameModel(dataFrame, filePath=self._filename) dataFrameModel.enableEditing(True) self._previewTableView.setModel(dataFrameModel) columnModel = dataFrameModel.columnDtypeModel() columnModel.changeFailed.co...
def _previewFile(self)
Updates the preview widgets with new models for both tab panes.
6.680849
6.084338
1.09804
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=enc...
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: pand...
6.832786
6.207193
1.100785
self._filenameLineEdit.setText('') self._encodingComboBox.setCurrentIndex(0) self._delimiterBox.reset() self._headerCheckBox.setChecked(False) self._statusBar.showMessage('') self._previewTableView.setModel(None) self._datatypeTableView.setModel(None)
def _resetWidgets(self)
Resets all widgets of this dialog to its inital state.
4.974104
4.755633
1.045939
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() ...
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`.
9.382601
6.589031
1.423973
self.setModal(self._modal) self.setWindowTitle(self._windowTitle) layout = QtGui.QGridLayout() self._filenameLabel = QtGui.QLabel('Output File', self) self._filenameLineEdit = QtGui.QLineEdit(self) chooseFileButtonIcon = QtGui.QIcon(QtGui.QPixmap(':/icons/docum...
def _initUI(self)
Initiates the user interface with a grid layout and several widgets.
1.798471
1.785424
1.007308
self._filenameLineEdit.setText('') self._encodingComboBox.setCurrentIndex(self._idx) self._delimiterBox.reset() self._headerCheckBox.setChecked(False) self._statusBar.showMessage('')
def _resetWidgets(self)
Resets all widgets of this dialog to its inital state.
7.003178
6.495459
1.078165
if matrix is None: _, matrix = self.read_pin() return "".join([str(matrix.index(p) + 1) for p in pin])
def encode_pin(self, pin, matrix=None)
Transform correct PIN according to the displayed matrix.
4.909753
4.28401
1.146065
final_bytes = bytearray() # version final_bytes.append(6 << 3) # public key final_bytes.extend(pk_bytes) # checksum final_bytes.extend(struct.pack("<H", _crc16_checksum(final_bytes))) return base64.b32encode(final_bytes).decode()
def address_from_public_key(pk_bytes)
Returns the base32-encoded version of pk_bytes (G...)
3.81562
3.324767
1.147635
tx = messages.StellarSignTx() unpacker = xdrlib.Unpacker(tx_bytes) tx.source_account = _xdr_read_address(unpacker) tx.fee = unpacker.unpack_uint() tx.sequence_number = unpacker.unpack_uhyper() # Timebounds is an optional field if unpacker.unpack_bool(): max_timebound = 2 ** 32...
def parse_transaction_bytes(tx_bytes)
Parses base64data into a map with the following keys: tx - a StellarSignTx describing the transaction header operations - an array of protobuf message objects for each operation
2.710489
2.674633
1.013406
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.iss...
def _xdr_read_asset(unpacker)
Reads a stellar Asset from unpacker
2.769726
2.709767
1.022127
# First 4 bytes are the address type address_type = unpacker.unpack_uint() if address_type != 0: raise ValueError("Unsupported address type") return address_from_public_key(unpacker.unpack_fopaque(32))
def _xdr_read_address(unpacker)
Reads a stellar address and returns the string representing the address This method assumes the encoded address is a public address (starting with G)
4.128845
3.860152
1.069607
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
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.
2.0224
1.931541
1.04704
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 li...
def b58encode(v)
encode v, which is a string of bytes, to base58.
1.522267
1.507564
1.009752
if isinstance(v, bytes): v = v.decode() for c in v: if c not in __b58chars: raise ValueError("invalid Base58 string") long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base ** i) result = b"" while long_value >= ...
def b58decode(v, length=None)
decode v into a string of len bytes.
1.595518
1.558475
1.023768
if not nstr: return [] n = nstr.split("/") # m/a/b/c => a/b/c if n[0] == "m": n = n[1:] # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c if n[0] in slip44: coin_id = slip44[n[0]] n[0:1] = ["44h", "{}h".format(coin_id)] def str_to_harden(x: str) -> int:...
def parse_path(nstr: str) -> Address
Convert BIP32 path string to list of uint32 integers with hardened flags. Several conventions are supported to set the hardened flag: -1, 1', 1h e.g.: "0/1h/1" -> [0, 0x80000001, 1] :param nstr: path string :return: list of integers
3.730394
3.590062
1.039089
if isinstance(txt, bytes): txt = txt.decode() return unicodedata.normalize("NFC", txt).encode()
def normalize_nfc(txt)
Normalize message to NFC and return bytes suitable for protobuf. This seems to be bitcoin-qt standard of doing things.
2.978637
2.943982
1.011771
force_v1 = int(os.environ.get("TREZOR_PROTOCOL_V1", 1)) if want_v2 and not force_v1: return ProtocolV2(handle) else: return ProtocolV1(handle)
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...
3.798059
2.654315
1.4309
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"
def _ping(self) -> bool
Test if the device is listening.
3.725009
3.43796
1.083494
while p > 0: x = x * x % q p -= 1 return x
def pow2(x: int, p: int) -> int
== pow(x, 2**p, q)
4.834807
2.467982
1.959012
# Adapted from curve25519_athlon.c in djb's Curve25519. z2 = z * z % q # 2 z9 = pow2(z2, 2) * z % q # 9 z11 = z9 * z2 % q # 11 z2_5_0 = (z11 * z11) % q * z9 % q # 31 == 2^5 - 2^0 z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % q # 2^10 - 2^0 z2_20_0 = pow2(z2_10_0, 10) * z2_10_0 % q # ... ...
def inv(z: int) -> int
$= z^{-1} mod q$, for z != 0
2.009836
1.939832
1.036087
h = H(sk) a = decodecoord(h) A = scalarmult_B(a) return encodepoint(A)
def publickey_unsafe(sk: bytes) -> bytes
Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only.
10.417894
10.19874
1.021488
h = H(sk) a = decodecoord(h) r = Hint(h[b // 8 : b // 4] + m) R = scalarmult_B(r) S = (r + Hint(encodepoint(R) + pk + m) * a) % l return encodepoint(R) + encodeint(S)
def signature_unsafe(m: bytes, sk: bytes, pk: bytes) -> bytes
Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only.
8.417513
8.48824
0.991668
P = [_ed25519.decodepoint(pk) for pk in pks] combine = reduce(_ed25519.edwards_add, P) return Ed25519PublicPoint(_ed25519.encodepoint(combine))
def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint
Combine a list of Ed25519 points into a "global" CoSi key.
3.346676
2.754
1.215205
S = [_ed25519.decodeint(si) for si in sigs] s = sum(S) % _ed25519.l sig = global_R + _ed25519.encodeint(s) return Ed25519Signature(sig)
def combine_sig( global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature] ) -> Ed25519Signature
Combine a list of signatures into a single CoSi signature.
3.883423
3.585877
1.082977
# 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))
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 ...
4.456587
4.775763
0.933168
# XXX this *might* change to bool function _ed25519.checkvalid(signature, digest, pub_key)
def verify( signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint ) -> None
Verify Ed25519 signature. Raise exception if the signature is invalid.
19.23102
14.634047
1.314129
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))
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.
4.830476
4.845895
0.996818
orig_run = cls.run def new_run(self): self.run_command("prebuild") orig_run(self) cls.run = new_run
def _patch_prebuild(cls)
Patch a setuptools command to depend on `prebuild`
3.552482
2.843651
1.249268
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)
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.
5.839297
3.961589
1.473978
''' strength - length of produced seed. One of 128, 192, 256 random - binary stream of random data from external HRNG ''' if strength not in (128, 192, 256): raise ValueError("Invalid strength") if not internal_entropy: raise ValueError("Internal entropy is not provided") i...
def generate_entropy(strength, internal_entropy, external_entropy)
strength - length of produced seed. One of 128, 192, 256 random - binary stream of random data from external HRNG
2.85253
1.873006
1.522969
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.rese...
def sel_entries(self)
Generator which returns all SEL entries.
3.671854
3.47155
1.057699
if action in (ACTION_UPLOAD_FOR_UPGRADE, ACTION_UPLOAD_FOR_COMPARE): if self._get_component_count(components_mask) != 1: raise HpmError("more than 1 component not support for action") self.send_message_with_name('InitiateUpgradeAction', ...
def initiate_upgrade_action(self, components_mask, action)
Initiate Upgrade Action components: action: ACTION_BACKUP_COMPONENT = 0x00 ACTION_PREPARE_COMPONENT = 0x01 ACTION_UPLOAD_FOR_UPGRADE = 0x02 ACTION_UPLOAD_FOR_COMPARE = 0x03
6.436626
4.102065
1.569119
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, ...
def initiate_upgrade_action_and_wait(self, components_mask, action, timeout=2, interval=0.1)
Initiate Upgrade Action and wait for long running command.
5.276267
5.721462
0.922189
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_PROGR...
def upload_binary(self, binary, timeout=2, interval=0.1)
Upload all firmware blocks from binary and wait for long running command.
5.364016
5.131408
1.04533
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( ...
def finish_upload_and_wait(self, component, length, timeout=2, interval=0.1)
Finish the firmware upload process and wait for long running command.
5.781366
5.44851
1.061091
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, ...
def activate_firmware_and_wait(self, rollback_override=None, timeout=2, interval=1)
Activate the new uploaded firmware and wait for long running command.
7.614571
7.872377
0.967252
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()
def _decode_data(self, data)
`data` is array.array
6.403962
6.010291
1.0655
if is_string(routing): # if type(routing) in [unicode, str]: routing = ast.literal_eval(routing) self.routing = [Routing(*route) for route in routing]
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: a...
4.878968
6.491597
0.751582
return self.interface.send_and_receive_raw(self.target, lun, netfn, raw_bytes)
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.
5.539193
6.474776
0.855503
password = self.session._auth_password if isinstance(password, str): password = str.encode(password) return password.ljust(16, b'\x00')
def _padd_password(self)
The password/key is 0 padded to 16-bytes for all specified authentication types.
4.563139
3.859191
1.182408
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 =...
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.
4.363703
4.395614
0.99274
return self._send_and_receive(target=target, lun=lun, netfn=netfn, cmdid=array('B', raw_bytes)[0], payload=raw_bytes[1:])
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.
4.015895
4.529492
0.88661
rx_data = self._send_and_receive(target=req.target, lun=req.lun, netfn=req.netfn, cmdid=req.cmdid, payload=encode_message(req)) rsp...
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.
5.514203
5.131903
1.074495
log().debug('Running ipmitool "%s"', cmd) child = Popen(cmd, shell=True, stdout=PIPE) output = child.communicate()[0] log().debug('return with rc=%d, output was:\n%s', child.returncode, output) return output, child.returncode
def _run_ipmitool(cmd)
Legacy call of ipmitool (will be removed in future).
4.399125
4.145459
1.061191
reservation_id = self.reserve_sdr_repository() record_id = 0 while True: s = self.get_repository_sdr(record_id, reservation_id) yield s if s.next_id == 0xffff: break record_id = s.next_id
def sdr_repository_entries(self)
A generator that returns the SDR list. Starting with ID=0x0000 and end when ID=0xffff is returned.
4.852272
3.810427
1.273419
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
def delete_sdr(self, record_id)
Deletes the sensor record specified by 'record_id'.
7.467259
7.354432
1.015341
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_payl...
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.
3.181266
3.230202
0.98485
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...
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.
4.497335
3.606786
1.246909
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()
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.
3.45591
3.578297
0.965797
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....
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 bytestri...
5.404803
5.887172
0.918064
# change header requester addresses for bridging header.rq_sa = routing[-1].rq_sa header.rs_sa = routing[-1].rs_sa tx_data = encode_ipmb_msg(header, payload) for bridge in reversed(routing[:-1]): tx_data = encode_send_message(tx_data, rq_sa=bridge...
def encode_bridged_message(routing, header, payload, seq)
Encode a (multi-)bridged command and embedd the message to be send. routing: payload: the message to be send as bytestring header: seq: the sequence number Returns the encoded send message as bytestring
5.401546
5.367306
1.006379
while array('B', rx_data)[5] == constants.CMDID_SEND_MESSAGE: rsp = create_message(constants.NETFN_APP + 1, constants.CMDID_SEND_MESSAGE, None) decode_message(rsp, rx_data[6:]) check_completion_code(rsp.completion_code) rx_data = rx_data[7:-1] ...
def decode_bridged_message(rx_data)
Decode a (multi-)bridged command. rx_data: the received message as bytestring Returns the decoded message as bytestring
6.869016
7.025088
0.977784
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...
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
3.901058
3.268467
1.193544
data = ByteBuffer() if not hasattr(self, '__fields__'): return data.array for field in self.__fields__: field.encode(self, data) return data.array
def _pack(self)
Pack the message and return an array.
5.896285
4.504706
1.308917
data = ByteBuffer() if not hasattr(self, '__fields__'): return data.tostring() for field in self.__fields__: field.encode(self, data) return data.tostring()
def _encode(self)
Encode the message and return a bytestring.
5.24969
4.33413
1.211244
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: ...
def _decode(self, data)
Decode the bytestring message.
5.469188
5.297925
1.032326
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_...
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
5.955173
5.883666
1.012153