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/generated/pandas.read_sql.html
pandas.read_sql(sql, con, index_col=None, coerce_float=True,
params=None, parse_dates=None, columns=None, chunksize=None)
:return: DataFrameModel | 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.
:param kwargs:
pandas.read_csv(**kwargs) or pandas.read_excel(**kwargs)
:return: None | 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
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() | 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. | 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 conversion of timestamps to QtCore.QDateTime. Used in data method. | 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 args:
see pandas.DataFrame.rename
:param kwargs:
see pandas.DataFrame.rename
:return:
None | 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.layoutChanged.emit()
self.dataChanged.emit()
self.dataFrameChanged.emit() | 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.
AssertionError if the func does not return a DataFrame. | 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 (IndexError, ):
return None
elif orientation == Qt.Vertical:
return section | 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::Orientations):
role (Qt::ItemDataRole):
Returns:
None if not Qt.DisplayRole
_dataFrame.columns.tolist()[section] if orientation == Qt.Horizontal
section if orientation == Qt.Vertical
None if horizontal orientation and section raises IndexError | 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(self._dataFrame.ix[row, col]), self._float_precisions[str(columnDtype)])
elif columnDtype in self._intDtypes:
value = int(self._dataFrame.ix[row, col])
elif columnDtype in self._boolDtypes:
# TODO this will most likely always be true
# See: http://stackoverflow.com/a/715455
# well no: I am mistaken here, the data is already in the dataframe
# so its already converted to a bool
value = bool(self._dataFrame.ix[row, col])
elif columnDtype in self._dateDtypes:
#print numpy.datetime64(self._dataFrame.ix[row, col])
value = pandas.Timestamp(self._dataFrame.ix[row, col])
value = QtCore.QDateTime.fromString(str(value), self.timestampFormat)
#print value
# else:
# raise TypeError, "returning unhandled data type"
return value
row = self._dataFrame.index[index.row()]
col = self._dataFrame.columns[index.column()]
columnDtype = self._dataFrame[col].dtype
if role == Qt.DisplayRole:
# return the value if you wanne show True/False as text
if columnDtype == numpy.bool:
result = self._dataFrame.ix[row, col]
else:
result = convertValue(row, col, columnDtype)
elif role == Qt.EditRole:
result = convertValue(row, col, columnDtype)
elif role == Qt.CheckStateRole:
if columnDtype == numpy.bool_:
if convertValue(row, col, columnDtype):
result = Qt.Checked
else:
result = Qt.Unchecked
else:
result = None
elif role == DATAFRAME_ROLE:
result = self._dataFrame.ix[row, col]
else:
result = None
return result | 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
None if role is none of: DisplayRole, EditRole, CheckStateRole, DATAFRAME_ROLE
if role DisplayRole:
unmodified _dataFrame value if column dtype is object (string or unicode).
_dataFrame value as int or long if column dtype is in _intDtypes.
_dataFrame value as float if column dtype is in _floatDtypes. Rounds to defined precision (look at: _float16_precision, _float32_precision).
None if column dtype is in _boolDtypes.
QDateTime if column dtype is numpy.timestamp64[ns]. Uses timestampFormat as conversion template.
if role EditRole:
unmodified _dataFrame value if column dtype is object (string or unicode).
_dataFrame value as int or long if column dtype is in _intDtypes.
_dataFrame value as float if column dtype is in _floatDtypes. Rounds to defined precision (look at: _float16_precision, _float32_precision).
_dataFrame value as bool if column dtype is in _boolDtypes.
QDateTime if column dtype is numpy.timestamp64[ns]. Uses timestampFormat as conversion template.
if role CheckStateRole:
Qt.Checked or Qt.Unchecked if dtype is numpy.bool_ otherwise None for all other dtypes.
if role DATAFRAME_ROLE:
unmodified _dataFrame value.
raises TypeError if an unhandled dtype is found in column. | 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 have a combobox for bool columns set this
flags |= Qt.ItemIsEditable
return flags | 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:
if column dtype is not boolean Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable
if column dtype is boolean Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | 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: ', index.data().toUTC(), self._dataFrame.iloc[row][col]
columnDtype = self._dataFrame[col].dtype
if columnDtype == object:
pass
elif columnDtype in self._intDtypes:
dtypeInfo = numpy.iinfo(columnDtype)
if value < dtypeInfo.min:
value = dtypeInfo.min
elif value > dtypeInfo.max:
value = dtypeInfo.max
elif columnDtype in self._floatDtypes:
value = numpy.float64(value).astype(columnDtype)
elif columnDtype in self._boolDtypes:
value = numpy.bool_(value)
elif columnDtype in self._dateDtypes:
# convert the given value to a compatible datetime object.
# if the conversation could not be done, keep the original
# value.
if isinstance(value, QtCore.QDateTime):
value = value.toString(self.timestampFormat)
try:
value = pandas.Timestamp(value)
except Exception:
raise Exception("Can't convert '{0}' into a datetime".format(value))
# return False
else:
raise TypeError("try to set unhandled data type")
self._dataFrame.set_value(row, col, value)
#print 'after change: ', value, self._dataFrame.iloc[row][col]
self.layoutChanged.emit()
return True
else:
return False | 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:
TypeError: If the value could not be converted to a known datatype.
Returns:
True if value is changed. Calls layoutChanged after update.
False if value is not different from original value. | 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.AscendingOrder | 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._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() | 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. | 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.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 | 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. | 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.beginRemoveColumns(QtCore.QModelIndex(), position, position)
try:
self._dataFrame.drop(name, axis=1, inplace=True)
except ValueError as e:
errored = True
continue
self.endRemoveColumns()
deleted += 1
self.dataChanged.emit()
if errored:
return False
else:
return True
return False | 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():
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 | 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()):
default = self.__dict__[key]
self.__dict__[key] = unpickledObject.__dict__.get(key, default)
except:
pass
return self | 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. | 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 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 | 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 | 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.
# Also: if initialbase is simply "*", we don't want an
# initialfile; it is not doing any useful work.
# ------------------------------------------------------------
if (initialfile.find("*") < 0) and (initialfile.find("?") < 0):
initialfile = None
elif initialbase == "*":
initialfile = None
func = ut.tk_FileDialog.askopenfilenames if multiple else ut.tk_FileDialog.askopenfilename
ret_val = func(parent=localRoot, title=getFileDialogTitle(msg, title), initialdir=initialdir, initialfile=initialfile, filetypes=filetypes
)
if multiple:
f = [os.path.normpath(x) for x in localRoot.tk.splitlist(ret_val)]
else:
f = os.path.normpath(ret_val)
localRoot.destroy()
if not f:
return None
return f | 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).
WINDOWS EXAMPLE::
...default="c:/myjunk/*.py"
will open in directory c:\\myjunk\\ and show all Python files.
WINDOWS EXAMPLE::
...default="c:/myjunk/test*.py"
will open in directory c:\\myjunk\\ and show all Python files
whose names begin with "test".
Note that on Windows, fileopenbox automatically changes the path
separator to the Windows path separator (backslash).
**About the "filetypes" argument**
If specified, it should contain a list of items,
where each item is either:
- a string containing a filemask # e.g. "\*.txt"
- a list of strings, where all of the strings except the last one
are filemasks (each beginning with "\*.",
such as "\*.txt" for text files, "\*.py" for Python files, etc.).
and the last string contains a filetype description
EXAMPLE::
filetypes = ["*.css", ["*.htm", "*.html", "HTML files"] ]
.. note:: If the filetypes list does not contain ("All files","*"), it will be added.
If the filetypes list does not contain a filemask that includes
the extension of the "default" argument, it will be added.
For example, if default="\*abc.py"
and no filetypes argument was specified, then
"\*.py" will automatically be added to the filetypes argument.
:param str msg: the msg to be displayed.
:param str title: the window title
:param str default: filepath with wildcards
:param object filetypes: filemasks that a user can choose, e.g. "\*.txt"
:param bool multiple: If true, more than one file can be selected
:return: the name of a file, or None if user chose to cancel | 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.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") | 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 = ut.uniquify_list_of_strings(choices)
# Create buttons dictionary and Tkinter widgets
buttons = dict()
for button_text, unique_button_text in zip(choices, unique_choices):
this_button = dict()
this_button['original_text'] = button_text
this_button['clean_text'], this_button[
'hotkey'], hotkey_position = ut.parse_hotkey(button_text)
this_button['widget'] = Button(buttonsFrame,
takefocus=1,
text=this_button['clean_text'],
underline=hotkey_position)
this_button['widget'].pack(
expand=YES, side=LEFT, padx='1m', pady='1m', ipadx='2m', ipady='1m')
buttons[unique_button_text] = this_button
# Bind arrows, Enter, Escape
for this_button in list(buttons.values()):
bindArrows(this_button['widget'])
for selectionEvent in st.STANDARD_SELECTION_EVENTS:
this_button['widget'].bind("<{}>".format(selectionEvent),
lambda e: __buttonEvent(
e, buttons, virtual_event='select'),
add=True)
# Assign default and cancel buttons
if cancel_choice in buttons:
buttons[cancel_choice]['cancel_choice'] = True
boxRoot.bind_all('<Escape>', lambda e: __buttonEvent(
e, buttons, virtual_event='cancel'), add=True)
boxRoot.protocol('WM_DELETE_WINDOW', lambda: __buttonEvent(
None, buttons, virtual_event='cancel'))
if default_choice in buttons:
buttons[default_choice]['default_choice'] = True
buttons[default_choice]['widget'].focus_force()
# Bind hotkeys
for hk in [button['hotkey'] for button in list(buttons.values()) if button['hotkey']]:
boxRoot.bind_all(hk, lambda e: __buttonEvent(e, buttons), add=True)
return | 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 confirmation
that the user wishes to continue. So it can be used this way::
if ynbox():
pass # continue
else:
sys.exit(0) # exit the program
:param msg: the msg to be displayed
:type msg: str
: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: True if 'Yes' or dialog is cancelled, False if 'No' | 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
request for a confirmation
that the user wishes to continue. So it can be used this way::
if ccbox():
pass # continue
else:
sys.exit(0) # exit the program
: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: True if 'Continue' or dialog is cancelled, False if 'Cancel' | 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,
default_choice=default_choice,
cancel_choice=cancel_choice)
if reply == choices[0]:
return True
else:
return False | 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: 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: True if first button pressed or dialog is cancelled, False if
second button is pressed | 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, 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) | 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 | 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,
root=root,
default_choice=ok_button,
cancel_choice=ok_button) | 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}')
if default:
try:
default = int(default)
except ValueError:
raise ValueError(
exception_string.format('default', default, type(default)))
try:
lowerbound = int(lowerbound)
except ValueError:
raise ValueError(
exception_string.format('lowerbound',
lowerbound, type(lowerbound)))
try:
upperbound = int(upperbound)
except ValueError:
raise ValueError(
exception_string.format('upperbound',
upperbound, type(upperbound)))
while True:
reply = enterbox(msg, title, str(default), image=image, root=root)
if reply is None:
return None
try:
reply = int(reply)
except:
msgbox('The value that you entered:\n\t"{}"\nis not an integer.'
.format(reply), "Error")
continue
if reply < lowerbound:
msgbox('The value that you entered is less than the lower '
'bound of {}.'.format(lowerbound), "Error")
continue
if reply > upperbound:
msgbox('The value that you entered is greater than the upper bound'
' of {}.'.format(
upperbound), "Error")
continue
# reply has passed all validation checks.
# It is an integer between the specified bounds.
return reply | 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 converted to an integer between the lowerbound and upperbound.
If it can be, the integer (not the text) is returned.
If it cannot, then an error msg is displayed, and the integerbox is
redisplayed.
If the user cancels the operation, None is returned.
:param str msg: the msg to be displayed
:param str title: the window title
:param str default: The default value to return
:param int lowerbound: The lower-most value allowed
:param int upperbound: The upper-most value allowed
:param str image: Filename of image to display
:param tk_widget root: Top-level Tk widget
:return: the integer value entered by the user | 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 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 | 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 automatically be used.
:param str msg: the msg to be displayed
:param str title: the window title
:return: None | 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
:param str title: the window title
:param str text: what to display in the textbox | 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.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) | 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.text()
return | 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)
chooseFileButtonIcon = QtGui.QIcon(QtGui.QPixmap(':/icons/document-open.png'))
self._chooseFileAction = QtGui.QAction(self)
self._chooseFileAction.setIcon(chooseFileButtonIcon)
self._chooseFileAction.triggered.connect(self._openFile)
self._chooseFileButton = QtGui.QToolButton(self)
self._chooseFileButton.setDefaultAction(self._chooseFileAction)
layout.addWidget(self._filenameLabel, 0, 0)
layout.addWidget(self._filenameLineEdit, 0, 1, 1, 2)
layout.addWidget(self._chooseFileButton, 0, 3)
self._encodingLabel = QtGui.QLabel('File Encoding', self)
encoding_names = list([x.upper() for x in sorted(list(set(_encodings.values())))])
self._encodingComboBox = QtGui.QComboBox(self)
self._encodingComboBox.addItems(encoding_names)
self._encodingComboBox.activated.connect(self._updateEncoding)
layout.addWidget(self._encodingLabel, 1, 0)
layout.addWidget(self._encodingComboBox, 1, 1, 1, 1)
self._hasHeaderLabel = QtGui.QLabel('Header Available?', self)
self._headerCheckBox = QtGui.QCheckBox(self)
self._headerCheckBox.toggled.connect(self._updateHeader)
layout.addWidget(self._hasHeaderLabel, 2, 0)
layout.addWidget(self._headerCheckBox, 2, 1)
self._delimiterLabel = QtGui.QLabel('Column Delimiter', self)
self._delimiterBox = DelimiterSelectionWidget(self)
self._delimiter = self._delimiterBox.currentSelected()
self._delimiterBox.delimiter.connect(self._updateDelimiter)
layout.addWidget(self._delimiterLabel, 3, 0)
layout.addWidget(self._delimiterBox, 3, 1, 1, 3)
self._tabWidget = QtGui.QTabWidget(self)
self._previewTableView = QtGui.QTableView(self)
self._datatypeTableView = QtGui.QTableView(self)
self._tabWidget.addTab(self._previewTableView, 'Preview')
self._tabWidget.addTab(self._datatypeTableView, 'Change Column Types')
layout.addWidget(self._tabWidget, 4, 0, 3, 4)
self._datatypeTableView.horizontalHeader().setDefaultSectionSize(200)
self._datatypeTableView.setItemDelegateForColumn(1, DtypeComboDelegate(self._datatypeTableView))
self._loadButton = QtGui.QPushButton('Load Data', self)
#self.loadButton.setAutoDefault(False)
self._cancelButton = QtGui.QPushButton('Cancel', self)
# self.cancelButton.setDefault(False)
# self.cancelButton.setAutoDefault(True)
self._buttonBox = QtGui.QDialogButtonBox(self)
self._buttonBox.addButton(self._loadButton, QtGui.QDialogButtonBox.AcceptRole)
self._buttonBox.addButton(self._cancelButton, QtGui.QDialogButtonBox.RejectRole)
self._buttonBox.accepted.connect(self.accepted)
self._buttonBox.rejected.connect(self.rejected)
layout.addWidget(self._buttonBox, 9, 2, 1, 2)
self._loadButton.setDefault(False)
self._filenameLineEdit.setFocus()
self._statusBar = QtGui.QStatusBar(self)
self._statusBar.setSizeGripEnabled(False)
self._headerCheckBox.setChecked(True)
layout.addWidget(self._statusBar, 8, 0, 1, 4)
self.setLayout(layout) | 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, tuple):
ret = ret[0] #PySide compatibility maybe?
if ret:
self._filenameLineEdit.setText(ret)
self._updateFilename() | 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('-', '')
encoding = encoding.replace('-','_')
viewValue = _encodings.get(encoding)
self._encodingKey = encoding
index = self._encodingComboBox.findText(viewValue.upper())
self._encodingComboBox.setCurrentIndex(index) | 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. | 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.connect(self.updateStatusBar)
self._datatypeTableView.setModel(columnModel) | 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=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() | 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. | 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()
self.accept() | 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/document-save-as.png'))
self._chooseFileAction = QtGui.QAction(self)
self._chooseFileAction.setIcon(chooseFileButtonIcon)
self._chooseFileAction.triggered.connect(self._createFile)
self._chooseFileButton = QtGui.QToolButton(self)
self._chooseFileButton.setDefaultAction(self._chooseFileAction)
layout.addWidget(self._filenameLabel, 0, 0)
layout.addWidget(self._filenameLineEdit, 0, 1, 1, 2)
layout.addWidget(self._chooseFileButton, 0, 3)
self._encodingLabel = QtGui.QLabel('File Encoding', self)
encoding_names = list(map(lambda x: x.upper(), sorted(list(set(_encodings.values())))))
self._encodingComboBox = QtGui.QComboBox(self)
self._encodingComboBox.addItems(encoding_names)
self._idx = encoding_names.index('UTF_8')
self._encodingComboBox.setCurrentIndex(self._idx)
#self._encodingComboBox.activated.connect(self._updateEncoding)
layout.addWidget(self._encodingLabel, 1, 0)
layout.addWidget(self._encodingComboBox, 1, 1, 1, 1)
self._hasHeaderLabel = QtGui.QLabel('Header Available?', self)
self._headerCheckBox = QtGui.QCheckBox(self)
#self._headerCheckBox.toggled.connect(self._updateHeader)
layout.addWidget(self._hasHeaderLabel, 2, 0)
layout.addWidget(self._headerCheckBox, 2, 1)
self._delimiterLabel = QtGui.QLabel('Column Delimiter', self)
self._delimiterBox = DelimiterSelectionWidget(self)
layout.addWidget(self._delimiterLabel, 3, 0)
layout.addWidget(self._delimiterBox, 3, 1, 1, 3)
self._exportButton = QtGui.QPushButton('Export Data', self)
self._cancelButton = QtGui.QPushButton('Cancel', self)
self._buttonBox = QtGui.QDialogButtonBox(self)
self._buttonBox.addButton(self._exportButton, QtGui.QDialogButtonBox.AcceptRole)
self._buttonBox.addButton(self._cancelButton, QtGui.QDialogButtonBox.RejectRole)
self._buttonBox.accepted.connect(self.accepted)
self._buttonBox.rejected.connect(self.rejected)
layout.addWidget(self._buttonBox, 5, 2, 1, 2)
self._exportButton.setDefault(False)
self._filenameLineEdit.setFocus()
self._statusBar = QtGui.QStatusBar(self)
self._statusBar.setSizeGripEnabled(False)
layout.addWidget(self._statusBar, 4, 0, 1, 4)
self.setLayout(layout) | 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 - 1 # max unsigned 32-bit int
# (trezor does not support the full 64-bit time value)
tx.timebounds_start = unpacker.unpack_uhyper()
tx.timebounds_end = unpacker.unpack_uhyper()
if tx.timebounds_start > max_timebound or tx.timebounds_start < 0:
raise ValueError(
"Starting timebound out of range (must be between 0 and "
+ max_timebound
)
if tx.timebounds_end > max_timebound or tx.timebounds_end < 0:
raise ValueError(
"Ending timebound out of range (must be between 0 and " + max_timebound
)
# memo type determines what optional fields are set
tx.memo_type = unpacker.unpack_uint()
# text
if tx.memo_type == MEMO_TYPE_TEXT:
tx.memo_text = unpacker.unpack_string()
# id (64-bit uint)
if tx.memo_type == MEMO_TYPE_ID:
tx.memo_id = unpacker.unpack_uhyper()
# hash / return are the same structure (32 bytes representing a hash)
if tx.memo_type == MEMO_TYPE_HASH or tx.memo_type == MEMO_TYPE_RETURN:
tx.memo_hash = unpacker.unpack_fopaque(32)
tx.num_operations = unpacker.unpack_uint()
operations = []
for _ in range(tx.num_operations):
operations.append(_parse_operation_bytes(unpacker))
return tx, operations | 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.issuer = _xdr_read_address(unpacker)
return asset | 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 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 | 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 >= 256:
div, mod = divmod(long_value, 256)
result = struct.pack("B", mod) + result
long_value = div
result = struct.pack("B", long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]:
nPad += 1
else:
break
result = b"\x00" * nPad + result
if length is not None and len(result) != length:
return None
return result | 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:
if x.startswith("-"):
return H_(abs(int(x)))
elif x.endswith(("h", "'")):
return H_(int(x[:-1]))
else:
return int(x)
try:
return [str_to_harden(x) for x in n]
except Exception:
raise ValueError("Invalid BIP32 path", nstr) | 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 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). | 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 # ...
z2_40_0 = pow2(z2_20_0, 20) * z2_20_0 % q
z2_50_0 = pow2(z2_40_0, 10) * z2_10_0 % q
z2_100_0 = pow2(z2_50_0, 50) * z2_50_0 % q
z2_200_0 = pow2(z2_100_0, 100) * z2_100_0 % q
z2_250_0 = pow2(z2_200_0, 50) * z2_50_0 % q # 2^250 - 2^0
return pow2(z2_250_0, 5) * z11 % 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 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". | 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")
if len(internal_entropy) < 32:
raise ValueError("Internal entropy too short")
if not external_entropy:
raise ValueError("External entropy is not provided")
if len(external_entropy) < 32:
raise ValueError("External entropy too short")
entropy = hashlib.sha256(internal_entropy + external_entropy).digest()
entropy_stripped = entropy[:strength // 8]
if len(entropy_stripped) * 8 != strength:
raise ValueError("Entropy length mismatch")
return entropy_stripped | 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.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 | 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',
components=components_mask, action=action) | 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,
timeout, interval)
else:
raise HpmError('initiate_upgrade_action CC=0x%02x' % e.cc) | 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_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 | 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(
constants.CMDID_HPM_FINISH_FIRMWARE_UPLOAD,
timeout, interval)
else:
raise HpmError('finish_firmware_upload CC=0x%02x' % e.cc) | 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,
timeout, interval)
else:
raise HpmError('activate_firmware CC=0x%02x' % e.cc)
except IpmiTimeoutError:
# controller is in reset and flashed new firmware
pass | 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: 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 | |
81 ------------| 0x20 |0x82 0x20 |-------------| 0x72 |
| | | | |
| | | | |
| `-----------| | |
`-------------------´ `--------´
`------------´ `---´ `---------------´
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)] | 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 = 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] | 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 = create_message(req.netfn + 1, req.cmdid, req.group_extension)
decode_message(rsp, rx_data)
return 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_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) | 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_repository(reserve_fn, clear_fn,
GET_ERASE_STATUS, retry, reservation) | 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.rq_sa = rq_sa
header.cmd_id = req.__cmdid__
return encode_ipmb_msg(header, data + payload) | 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 | 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.rq_sa,
rs_sa=bridge.rs_sa,
channel=bridge.channel,
seq=seq)
return tx_data | 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]
if len(rx_data) < 6:
break
return rx_data | 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.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 | 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:
# 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') | 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_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] | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.