id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
144,548 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/gui/qt_b26_export_dialog.py
|
gui.qt_b26_export_dialog.ExportDialog
|
class ExportDialog(QDialog, Ui_Dialog):
"""
LoadDialog(intruments, scripts, probes)
- type: either script, instrument or probe
- loaded_elements: dictionary that contains the loaded elements
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
"""
def __init__(self):
super(ExportDialog, self).__init__()
self.setupUi(self)
# create models for tree structures, the models reflect the data
self.list_script_model = QtGui.QStandardItemModel()
self.list_script.setModel(self.list_script_model)
self.error_array = {}
self.list_script.selectionModel().selectionChanged.connect(self.display_info)
self.cmb_select_type.currentIndexChanged.connect(self.class_type_changed)
#
# # connect the buttons
self.btn_open_source.clicked.connect(self.open_file_dialog)
self.btn_open_target.clicked.connect(self.open_file_dialog)
self.btn_select_all.clicked.connect(self.select_all)
self.btn_select_none.clicked.connect(self.select_none)
self.btn_export.clicked.connect(self.export)
self.source_path.setText(os.path.normpath(os.path.join(os.getcwd(), '..\\scripts')))
self.target_path.setText(os.path.normpath(os.path.join(os.getcwd(), '..\\..\\..\\user_data\\scripts_auto_generated')))
self.reset_avaliable(self.source_path.text())
def open_file_dialog(self):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtWidgets.QFileDialog
sender = self.sender()
if sender == self.btn_open_source:
textbox = self.source_path
elif sender == self.btn_open_target:
textbox = self.target_path
folder = dialog.getExistingDirectory(self, 'Select a file:', textbox.text(), options = QtWidgets.QFileDialog.ShowDirsOnly)
if str(folder) != '':
textbox.setText(folder)
# load elements from file and display in tree
if sender == self.btn_open_source:
self.reset_avaliable(folder)
def reset_avaliable(self, folder):
self.list_script_model.removeRows(0, self.list_script_model.rowCount())
if self.cmb_select_type.currentText() == 'Script':
self.avaliable = find_scripts_in_python_files(folder)
elif self.cmb_select_type.currentText() == 'Instrument':
self.avaliable = find_instruments_in_python_files(folder)
self.fill_list(self.list_script, self.avaliable.keys())
for key in self.avaliable.keys():
self.error_array.update({key: ''})
def class_type_changed(self):
if self.source_path.text():
self.reset_avaliable(self.source_path.text())
def fill_list(self, list, input_list):
"""
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns:
"""
for name in input_list:
# print(index, loaded_item, loaded_item_settings)
item = QtGui.QStandardItem(name)
item.setSelectable(True)
item.setEditable(False)
list.model().appendRow(item)
def select_none(self):
self.list_script.clearSelection()
def select_all(self):
self.list_script.selectAll()
def export(self):
selected_index = self.list_script.selectedIndexes()
for index in selected_index:
item = self.list_script.model().itemFromIndex(index)
name = str(item.text())
target_path = self.target_path.text()
try:
python_file_to_b26({name: self.avaliable[name]}, target_path, str(self.cmb_select_type.currentText()), raise_errors = True)
self.error_array.update({name: 'export successful!'})
item.setBackground(QtGui.QColor('green'))
except Exception:
self.error_array.update({name: str(traceback.format_exc())})
item.setBackground(QtGui.QColor('red'))
QtWidgets.QApplication.processEvents()
self.list_script.clearSelection()
def display_info(self):
sender = self.sender()
somelist = sender.parent()
index = somelist.selectedIndexes()
if index != []:
index = index[-1]
name = str(index.model().itemFromIndex(index).text())
self.text_error.setText(self.error_array[name])
if(self.avaliable[name]['info'] == None):
self.text_info.setText('No information avaliable')
else:
self.text_info.setText(self.avaliable[name]['info'])
|
class ExportDialog(QDialog, Ui_Dialog):
'''
LoadDialog(intruments, scripts, probes)
- type: either script, instrument or probe
- loaded_elements: dictionary that contains the loaded elements
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
'''
def __init__(self):
pass
def open_file_dialog(self):
'''
opens a file dialog to get the path to a file and
'''
pass
def reset_avaliable(self, folder):
pass
def class_type_changed(self):
pass
def fill_list(self, list, input_list):
'''
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns:
'''
pass
def select_none(self):
pass
def select_all(self):
pass
def export(self):
pass
def display_info(self):
pass
| 10 | 3 | 11 | 1 | 9 | 2 | 2 | 0.29 | 2 | 3 | 0 | 0 | 9 | 3 | 9 | 9 | 118 | 17 | 78 | 29 | 68 | 23 | 75 | 29 | 65 | 5 | 1 | 2 | 22 |
144,549 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/gui/qt_b26_gui.py
|
gui.qt_b26_gui.MatplotlibWidget
|
class MatplotlibWidget(Canvas):
"""
MatplotlibWidget inherits PyQt4.QtWidgets.QWidget
and matplotlib.backend_bases.FigureCanvasBase
Options: option_name (default_value)
-------
parent (None): parent widget
title (''): figure title
xlabel (''): X-axis label
ylabel (''): Y-axis label
xlim (None): X-axis limits ([min, max])
ylim (None): Y-axis limits ([min, max])
xscale ('linear'): X-axis scale
yscale ('linear'): Y-axis scale
width (4): width in inches
height (3): height in inches
dpi (100): resolution in dpi
hold (False): if False, figure will be cleared each time plot is called
Widget attributes:
-----------------
figure: instance of matplotlib.figure.Figure
axes: figure axes
Example:
-------
self.widget = MatplotlibWidget(self, yscale='log', hold=True)
from numpy import linspace
x = linspace(-10, 10)
self.widget.axes.plot(x, x**2)
self.wdiget.axes.plot(x, x**3)
"""
def __init__(self, parent=None):
self.figure = Figure(dpi=100)
Canvas.__init__(self, self.figure)
self.axes = self.figure.add_subplot(111)
self.canvas = self.figure.canvas
self.setParent(parent)
Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
Canvas.updateGeometry(self)
def sizeHint(self):
"""
gives qt a starting point for widget size during window resizing
"""
w, h = self.get_width_height()
return QtCore.QSize(w, h)
def minimumSizeHint(self):
"""
minimum widget size during window resizing
Returns: QSize object that specifies the size of widget
"""
return QtCore.QSize(10, 10)
|
class MatplotlibWidget(Canvas):
'''
MatplotlibWidget inherits PyQt4.QtWidgets.QWidget
and matplotlib.backend_bases.FigureCanvasBase
Options: option_name (default_value)
-------
parent (None): parent widget
title (''): figure title
xlabel (''): X-axis label
ylabel (''): Y-axis label
xlim (None): X-axis limits ([min, max])
ylim (None): Y-axis limits ([min, max])
xscale ('linear'): X-axis scale
yscale ('linear'): Y-axis scale
width (4): width in inches
height (3): height in inches
dpi (100): resolution in dpi
hold (False): if False, figure will be cleared each time plot is called
Widget attributes:
-----------------
figure: instance of matplotlib.figure.Figure
axes: figure axes
Example:
-------
self.widget = MatplotlibWidget(self, yscale='log', hold=True)
from numpy import linspace
x = linspace(-10, 10)
self.widget.axes.plot(x, x**2)
self.wdiget.axes.plot(x, x**3)
'''
def __init__(self, parent=None):
pass
def sizeHint(self):
'''
gives qt a starting point for widget size during window resizing
'''
pass
def minimumSizeHint(self):
'''
minimum widget size during window resizing
Returns: QSize object that specifies the size of widget
'''
pass
| 4 | 3 | 7 | 1 | 4 | 2 | 1 | 2.57 | 1 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 57 | 7 | 14 | 8 | 10 | 36 | 14 | 8 | 10 | 1 | 1 | 0 | 3 |
144,550 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/gui/qt_b26_widgets.py
|
gui.qt_b26_widgets.B26QTreeItem
|
class B26QTreeItem(QtWidgets.QTreeWidgetItem):
"""
Custom QTreeWidgetItem with Widgets
"""
def __init__(self, parent, name, value, valid_values, info, visible=None):
"""
Args:
name:
value:
valid_values:
info:
visible (optional):
Returns:
"""
super(B26QTreeItem, self ).__init__(parent)
self.ui_type = None
self.name = name
self.valid_values = valid_values
self._value = value
self.info = info
self._visible = visible
self.setData(0, 0, self.name)
if isinstance(self.valid_values, list):
self.ui_type = 'combo_box'
self.combo_box = QtWidgets.QComboBox()
for item in self.valid_values:
self.combo_box.addItem(str(item))
self.combo_box.setCurrentIndex(self.combo_box.findText(str(self.value)))
self.treeWidget().setItemWidget(self, 1, self.combo_box)
self.combo_box.currentIndexChanged.connect(lambda: self.setData(1, 2, self.combo_box))
self.combo_box.setFocusPolicy(QtCore.Qt.StrongFocus)
self._visible = False
elif self.valid_values is bool:
self.ui_type = 'checkbox'
self.checkbox = QtWidgets.QCheckBox()
self.checkbox.setChecked(self.value)
self.treeWidget().setItemWidget( self, 1, self.checkbox )
self.checkbox.stateChanged.connect(lambda: self.setData(1, 2, self.checkbox))
self._visible = False
elif isinstance(self.value, Parameter):
for key, value in self.value.items():
B26QTreeItem(self, key, value, self.value.valid_values[key], self.value.info[key])
elif isinstance(self.value, dict):
for key, value in self.value.items():
if self.valid_values == dict:
B26QTreeItem(self, key, value, type(value), '')
else:
B26QTreeItem(self, key, value, self.valid_values[key], self.info[key])
elif isinstance(self.value, Instrument):
index_top_level_item = self.treeWidget().indexOfTopLevelItem(self)
top_level_item = self.treeWidget().topLevelItem(index_top_level_item)
if top_level_item == self:
# instrument is on top level, thus we are in the instrument tab
for key, value in self.value.settings.items():
B26QTreeItem(self, key, value, self.value.settings.valid_values[key], self.value.settings.info[key])
else:
self.valid_values = [self.value.name]
self.value = self.value.name
self.combo_box = QtWidgets.QComboBox()
for item in self.valid_values:
self.combo_box.addItem(item)
self.combo_box.setCurrentIndex(self.combo_box.findText(str(self.value)))
self.treeWidget().setItemWidget(self, 1, self.combo_box)
self.combo_box.currentIndexChanged.connect(lambda: self.setData(1, 2, self.combo_box))
self.combo_box.setFocusPolicy(QtCore.Qt.StrongFocus)
elif isinstance(self.value, Script):
for key, value in self.value.settings.items():
B26QTreeItem(self, key, value, self.value.settings.valid_values[key], self.value.settings.info[key])
for key, value in self.value.instruments.items():
B26QTreeItem(self, key, self.value.instruments[key], type(self.value.instruments[key]), '')
for key, value in self.value.scripts.items():
B26QTreeItem(self, key, self.value.scripts[key], type(self.value.scripts[key]), '')
self.info = self.value.__doc__
else:
self.setData(1, 0, self.value)
self._visible = False
self.setToolTip(1, str(self.info if isinstance(self.info, str) else ''))
if self._visible is not None:
self.check_show = QtWidgets.QCheckBox()
self.check_show.setChecked(self.visible)
self.treeWidget().setItemWidget(self, 2, self.check_show)
self.setFlags(self.flags() | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
@property
def value(self):
"""
item value
"""
return self._value
@value.setter
def value(self, value):
if Parameter.is_valid(value, self.valid_values):
self._value = value
# check if there is a special case for setting such as a checkbox or combobox
if self.ui_type == 'checkbox':
self.checkbox.setChecked(value)
elif self.ui_type == 'combo_box':
self.combo_box.setCurrentIndex(self.combo_box.findText(str(self.value)))
else: # for standard values
self.setData(1, 0, value)
else:
if value is not None:
raise TypeError("wrong type {:s}, expected {:s}".format(str(type(value)), str(self.valid_values)))
@property
def visible(self):
"""
Returns: boolean (True: item is visible) (False: item is hidden)
"""
if self._visible is not None:
return self.check_show.isChecked()
elif isinstance(self._value, (Parameter, dict)):
# check if any of the children is visible
for i in range(self.childCount()):
if self.child(i).visible:
return True
# if none of the children is visible hide this parameter
return False
else:
return True
@visible.setter
def visible(self, value):
if self._visible is not None:
self._visible = value
self.check_show.setChecked(self._visible)
def setData(self, column, role, value):
"""
if value is valid sets the data to value
Args:
column: column of item
role: role of item (see Qt doc)
value: value to be set
"""
assert isinstance(column, int)
assert isinstance(role, int)
# make sure that the right row is selected, this is not always the case for checkboxes and
# combo boxes because they are items on top of the tree structure
if isinstance(value, (QtWidgets.QComboBox, QtWidgets.QCheckBox)):
self.treeWidget().setCurrentItem(self)
# if row 2 (editrole, value has been entered)
if role == 2 and column == 1:
if isinstance(value, str):
value = self.cast_type(value) # cast into same type as valid values
if isinstance(value, QtCore.QVariant):
value = self.cast_type(value.toString()) # cast into same type as valid values
if isinstance(value, QtWidgets.QComboBox):
value = self.cast_type(value.currentText())
if isinstance(value, QtWidgets.QCheckBox):
value = bool(int(value.checkState())) # checkState() gives 2 (True) and 0 (False)
# save value in internal variable
self.value = value
elif column == 0:
# labels should not be changed so we set it back
value = self.name
if value is None:
value = self.value
# 180327(asafira) --- why do we need to do the following lines? Why not just always call super or always
# emitDataChanged()?
if not isinstance(value, bool):
super(B26QTreeItem, self).setData(column, role, value)
else:
self.emitDataChanged()
def cast_type(self, var, cast_type=None):
"""
cast the value into the type typ
if type is not provided it is set to self.valid_values
Args:
var: variable to be cast
type: target type
Returns: the variable var csat into type typ
"""
if cast_type is None:
cast_type = self.valid_values
try:
if cast_type == int:
return int(var)
elif cast_type == float:
return float(var)
elif type == str:
return str(var)
elif isinstance(cast_type, list):
# cast var to be of the same type as those in the list
return type(cast_type[0])(var)
else:
return None
except ValueError:
return None
return var
def get_instrument(self):
"""
Returns: the instrument and the path to the instrument to which this item belongs
"""
if isinstance(self.value, Instrument):
instrument = self.value
path_to_instrument = []
else:
instrument = None
parent = self.parent()
path_to_instrument = [self.name]
while parent is not None:
if isinstance(parent.value, Instrument):
instrument = parent.value
parent = None
else:
path_to_instrument.append(parent.name)
parent = parent.parent()
return instrument, path_to_instrument
def get_script(self):
"""
Returns: the script and the path to the script to which this item belongs
"""
if isinstance(self.value, Script):
script = self.value
path_to_script = []
script_item = self
else:
script = None
parent = self.parent()
path_to_script = [self.name]
while parent is not None:
if isinstance(parent.value, Script):
script = parent.value
script_item = parent
parent = None
else:
path_to_script.append(parent.name)
parent = parent.parent()
return script, path_to_script, script_item
def get_subscript(self, sub_script_name):
"""
finds the item that contains the sub_script with name sub_script_name
Args:
sub_script_name: name of subscript
Returns: B26QTreeItem in QTreeWidget which is a script
"""
# get tree of item
tree = self.treeWidget()
items = tree.findItems(sub_script_name, QtCore.Qt.MatchExactly | QtCore.Qt.MatchRecursive)
if len(items) >= 1:
# identify correct script by checking that it is a sub_element of the current script
subscript_item = [sub_item for sub_item in items if isinstance(sub_item.value, Script)
and sub_item.parent() is self]
subscript_item = subscript_item[0]
else:
raise ValueError('several elements with name ' + sub_script_name)
return subscript_item
def is_point(self):
"""
figures out if item is a point, that is if it has two subelements of type float
Args:
self:
Returns: if item is a point (True) or not (False)
"""
if self.childCount() == 2:
if self.child(0).valid_values == float and self.child(1).valid_values == float:
return True
else:
return False
def to_dict(self):
"""
Returns: the tree item as a dictionary
"""
if self.childCount() > 0:
value = {}
for index in range(self.childCount()):
value.update(self.child(index).to_dict())
else:
value = self.value
return {self.name: value}
|
class B26QTreeItem(QtWidgets.QTreeWidgetItem):
'''
Custom QTreeWidgetItem with Widgets
'''
def __init__(self, parent, name, value, valid_values, info, visible=None):
'''
Args:
name:
value:
valid_values:
info:
visible (optional):
Returns:
'''
pass
@property
def value(self):
'''
item value
'''
pass
@value.setter
def value(self):
pass
@property
def visible(self):
'''
Returns: boolean (True: item is visible) (False: item is hidden)
'''
pass
@visible.setter
def visible(self):
pass
def setData(self, column, role, value):
'''
if value is valid sets the data to value
Args:
column: column of item
role: role of item (see Qt doc)
value: value to be set
'''
pass
def cast_type(self, var, cast_type=None):
'''
cast the value into the type typ
if type is not provided it is set to self.valid_values
Args:
var: variable to be cast
type: target type
Returns: the variable var csat into type typ
'''
pass
def get_instrument(self):
'''
Returns: the instrument and the path to the instrument to which this item belongs
'''
pass
def get_script(self):
'''
Returns: the script and the path to the script to which this item belongs
'''
pass
def get_subscript(self, sub_script_name):
'''
finds the item that contains the sub_script with name sub_script_name
Args:
sub_script_name: name of subscript
Returns: B26QTreeItem in QTreeWidget which is a script
'''
pass
def is_point(self):
'''
figures out if item is a point, that is if it has two subelements of type float
Args:
self:
Returns: if item is a point (True) or not (False)
'''
pass
def to_dict(self):
'''
Returns: the tree item as a dictionary
'''
pass
| 17 | 11 | 26 | 5 | 16 | 6 | 5 | 0.36 | 1 | 13 | 2 | 0 | 12 | 9 | 12 | 12 | 336 | 69 | 199 | 43 | 182 | 72 | 168 | 39 | 155 | 19 | 1 | 3 | 65 |
144,551 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/gui/compiled_ui_files/manual_fitting_ensemble.py
|
lib.pylabcontrol.gui.compiled_ui_files.manual_fitting_ensemble.FittingWindow
|
class FittingWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
def create_figures():
self.matplotlibwidget = MatplotlibWidget(self.plot)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.matplotlibwidget.sizePolicy().hasHeightForWidth())
self.matplotlibwidget.setSizePolicy(sizePolicy)
self.matplotlibwidget.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget.setObjectName(QtCore.QString.fromUtf8("matplotlibwidget"))
self.horizontalLayout_3.addWidget(self.matplotlibwidget)
self.mpl_toolbar = NavigationToolbar(self.matplotlibwidget.canvas, self.toolbar_space)
self.horizontalLayout_2.addWidget(self.mpl_toolbar)
self.peak_vals = None
def setup_connections():
self.btn_fit.clicked.connect(self.btn_clicked)
self.btn_clear.clicked.connect(self.btn_clicked)
self.btn_next.clicked.connect(self.btn_clicked)
self.matplotlibwidget.mpl_connect('button_press_event', self.plot_clicked)
self.btn_open.clicked.connect(self.open_file_dialog)
self.btn_run.clicked.connect(self.btn_clicked)
self.btn_goto.clicked.connect(self.btn_clicked)
self.btn_prev.clicked.connect(self.btn_clicked)
self.btn_skip.clicked.connect(self.btn_clicked)
create_figures()
setup_connections()
def btn_clicked(self):
sender = self.sender()
if sender is self.btn_run:
self.start_fitting()
elif sender is self.btn_next:
self.queue.put('next')
elif sender is self.btn_fit:
self.queue.put('fit')
elif sender is self.btn_clear:
while not self.peak_vals == []:
self.peak_vals.pop(-1)
self.queue.put('clear')
elif sender is self.btn_goto:
self.queue.put(int(self.input_next.text()))
elif sender is self.btn_prev:
self.queue.put('prev')
elif sender is self.btn_skip:
self.queue.put('skip')
def plot_clicked(self, mouse_event):
if type(self.peak_vals) is list:
self.peak_vals.append([mouse_event.xdata, mouse_event.ydata])
axes = self.matplotlibwidget.axes
# can't use patches, as they use data coordinates for radius but this is a high aspect ratio plot so the
# circle was extremely stretched
axes.plot(mouse_event.xdata, mouse_event.ydata, 'ro', markersize = 5)
self.matplotlibwidget.draw()
class do_fit(QObject):
finished = pyqtSignal() # signals the end of the script
status = pyqtSignal(str) # sends messages to update the statusbar
NUM_ESR_LINES = 8
def __init__(self, filepath, plotwidget, queue, peak_vals, interps):
QObject.__init__(self)
self.filepath = filepath
self.plotwidget = plotwidget
self.queue = queue
self.peak_vals = peak_vals
self.interps = interps
def save(self):
def freqs(index):
return self.frequencies[0] + (self.frequencies[-1]-self.frequencies[0])/(len(self.frequencies)-1)*index
save_path = os.path.join(self.filepath, 'line_data.csv')
data = list()
for i in range(0, self.NUM_ESR_LINES):
data.append(list())
for i in range(0, self.NUM_ESR_LINES):
indices = self.interps[i](self.x_range)
data[i] = [freqs(indices[j]) for j in range(0,len(self.x_range))]
df = pd.DataFrame(data)
df = df.transpose()
df.to_csv(save_path)
self.plotwidget.figure.savefig(self.filepath + './lines.jpg')
def run(self):
data_esr = []
for f in sorted(glob.glob(os.path.join(self.filepath, './data_subscripts/*'))):
data = Script.load_data(f)
data_esr.append(data['data'])
self.frequencies = data['frequency']
data_esr_norm = []
for d in data_esr:
data_esr_norm.append(d / np.mean(d))
self.x_range = list(range(0, len(data_esr_norm)))
self.status.emit('executing manual fitting')
index = 0
# for data in data_array:
while index < self.NUM_ESR_LINES:
#this must be after the draw command, otherwise plot doesn't display for some reason
self.status.emit('executing manual fitting NV #' + str(index))
self.plotwidget.axes.clear()
self.plotwidget.axes.imshow(data_esr_norm, aspect = 'auto', origin = 'lower')
if self.interps:
for f in self.interps:
self.plotwidget.axes.plot(f(self.x_range), self.x_range)
self.plotwidget.draw()
while(True):
if self.queue.empty():
time.sleep(.5)
else:
value = self.queue.get()
if value == 'next':
while not self.peak_vals == []:
self.peak_vals.pop(-1)
# if len(self.single_fit) == 1:
# self.fits[index] = self.single_fit
# else:
# self.fits[index] = [y for x in self.single_fit for y in x]
index += 1
self.interps.append(f)
break
elif value == 'clear':
self.plotwidget.axes.clear()
self.plotwidget.axes.imshow(data_esr_norm, aspect='auto', origin = 'lower')
if self.interps:
for f in self.interps:
self.plotwidget.axes.plot(f(self.x_range), self.x_range)
self.plotwidget.draw()
elif value == 'fit':
peak_vals = sorted(self.peak_vals, key = lambda tup: tup[1])
y,x = list(zip(*peak_vals))
f = UnivariateSpline(np.array(x),np.array(y))
x_range = list(range(0,len(data_esr_norm)))
self.plotwidget.axes.plot(f(x_range), x_range)
self.plotwidget.draw()
elif value == 'prev':
index -= 1
break
elif value == 'skip':
index += 1
break
elif type(value) is int:
index = int(value)
break
self.finished.emit()
self.status.emit('saving')
self.plotwidget.axes.clear()
self.plotwidget.axes.imshow(data_esr_norm, aspect='auto', origin = 'lower')
if self.interps:
for f in self.interps:
self.plotwidget.axes.plot(f(self.x_range), self.x_range)
self.save()
self.status.emit('saving finished')
def update_status(self, str):
self.statusbar.showMessage(str)
def start_fitting(self):
self.queue = queue.Queue()
self.peak_vals = []
self.interps = []
self.fit_thread = QThread() #must be assigned as an instance variable, not local, as otherwise thread is garbage
#collected immediately at the end of the function before it runs
self.fitobj = self.do_fit(str(self.data_filepath.text()), self.matplotlibwidget, self.queue, self.peak_vals, self.interps)
self.fitobj.moveToThread(self.fit_thread)
self.fit_thread.started.connect(self.fitobj.run)
self.fitobj.finished.connect(self.fit_thread.quit) # clean up. quit thread after script is finished
self.fitobj.status.connect(self.update_status)
self.fit_thread.start()
def open_file_dialog(self):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtGui.QFileDialog
filename = dialog.getExistingDirectory(self, 'Select a file:', self.data_filepath.text())
if str(filename)!='':
self.data_filepath.setText(filename)
|
class FittingWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
pass
def create_figures():
pass
def setup_connections():
pass
def btn_clicked(self):
pass
def plot_clicked(self, mouse_event):
pass
class do_fit(QObject):
def __init__(self):
pass
def save(self):
pass
def freqs(index):
pass
def run(self):
pass
def update_status(self, str):
pass
def start_fitting(self):
pass
def open_file_dialog(self):
'''
opens a file dialog to get the path to a file and
'''
pass
| 14 | 1 | 17 | 1 | 15 | 1 | 4 | 0.11 | 2 | 6 | 2 | 0 | 6 | 5 | 6 | 6 | 191 | 20 | 159 | 49 | 145 | 17 | 147 | 49 | 133 | 19 | 1 | 6 | 42 |
144,552 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/instruments/instrument_dummy.py
|
lib.pylabcontrol.instruments.instrument_dummy.DummyInstrument
|
class DummyInstrument(Instrument):
'''
Dummy instrument
a implementation of a dummy instrument
'''
_DEFAULT_SETTINGS = Parameter([
Parameter('test1', 0, int, 'some int parameter'),
Parameter('output probe2', 0, int, 'return value of probe 2 (int)'),
Parameter('test2',
[Parameter('test2_1', 'string', str, 'test parameter (str)'),
Parameter('test2_2', 0.0, float, 'test parameter (float)')
])
])
_PROBES = {'value1': 'this is some value from the instrument',
'value2': 'this is another',
'internal': 'gives the internal state variable',
'deep_internal': 'gives another internal state variable'
}
def __init__(self, name = None, settings = None):
self._test_variable = 1
super(DummyInstrument, self).__init__(name, settings)
self._internal_state = None
self._internal_state_deep = None
def update(self, settings):
'''
updates the internal dictionary and sends changed values to instrument
Args:
settings: parameters to be set
# mabe in the future:
# Returns: boolean that is true if update successful
'''
Instrument.update(self, settings)
for key, value in settings.items():
if key == 'test1':
self._internal_state = value
def read_probes(self, key):
"""
requestes value from the instrument and returns it
Args:
key: name of requested value
Returns: reads values from instrument
"""
assert key in list(self._PROBES.keys())
import random
if key == 'value1':
value = random.random()
elif key == 'value2':
value = self.settings['output probe2']
elif key == 'internal':
value = self._internal_state
elif key == 'deep_internal':
value = self._internal_state_deep
return value
@property
def is_connected(self):
'''
check if instrument is active and connected and return True in that case
:return: bool
'''
return self._is_connected
|
class DummyInstrument(Instrument):
'''
Dummy instrument
a implementation of a dummy instrument
'''
def __init__(self, name = None, settings = None):
pass
def update(self, settings):
'''
updates the internal dictionary and sends changed values to instrument
Args:
settings: parameters to be set
# mabe in the future:
# Returns: boolean that is true if update successful
'''
pass
def read_probes(self, key):
'''
requestes value from the instrument and returns it
Args:
key: name of requested value
Returns: reads values from instrument
'''
pass
@property
def is_connected(self):
'''
check if instrument is active and connected and return True in that case
:return: bool
'''
pass
| 6 | 4 | 12 | 2 | 6 | 4 | 3 | 0.54 | 1 | 2 | 0 | 0 | 4 | 3 | 4 | 19 | 75 | 15 | 39 | 14 | 32 | 21 | 24 | 13 | 18 | 5 | 2 | 2 | 10 |
144,553 |
LISE-B26/pylabcontrol
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/main_window.py
|
pylabcontrol.gui.windows_and_widgets.main_window.MainWindow
|
class MainWindow(QMainWindow, Ui_MainWindow):
application_path = os.path.abspath(os.path.join(
os.path.expanduser("~"), 'pylabcontrol_default_save_location'))
_DEFAULT_CONFIG = {
"data_folder": os.path.join(application_path, "data"),
"probes_folder": os.path.join(application_path, "probes_auto_generated"),
"instrument_folder": os.path.join(application_path, "instruments_auto_generated"),
"scripts_folder": os.path.join(application_path, "scripts_auto_generated"),
"probes_log_folder": os.path.join(application_path, "b26_tmp"),
"gui_settings": os.path.join(application_path, "pylabcontrol_config.b26")
}
startup_msg = '\n\n\
======================================================\n\
=============== Starting B26 Python LAB =============\n\
======================================================\n\n'
def __init__(self, filepath=None):
"""
MainWindow(intruments, scripts, probes)
- intruments: depth 1 dictionary where keys are instrument names and keys are instrument classes
- scripts: depth 1 dictionary where keys are script names and keys are script classes
- probes: depth 1 dictionary where to be decided....?
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
"""
print(self.startup_msg)
self.config_filepath = None
super(MainWindow, self).__init__()
self.setupUi(self)
def setup_trees():
# COMMENT_ME
# define data container
self.history = deque(maxlen=500) # history of executed commands
self.history_model = QtGui.QStandardItemModel(self.list_history)
self.list_history.setModel(self.history_model)
self.list_history.show()
self.tree_scripts.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_probes.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_settings.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_gui_settings.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_gui_settings.doubleClicked.connect(self.edit_tree_item)
self.current_script = None
self.probe_to_plot = None
# create models for tree structures, the models reflect the data
self.tree_dataset_model = QtGui.QStandardItemModel()
self.tree_dataset.setModel(self.tree_dataset_model)
self.tree_dataset_model.setHorizontalHeaderLabels(
['time', 'name (tag)', 'type (script)'])
# create models for tree structures, the models reflect the data
self.tree_gui_settings_model = QtGui.QStandardItemModel()
self.tree_gui_settings.setModel(self.tree_gui_settings_model)
self.tree_gui_settings_model.setHorizontalHeaderLabels(
['parameter', 'value'])
self.tree_scripts.header().setStretchLastSection(True)
def connect_controls():
# COMMENT_ME
# =============================================================
# ===== LINK WIDGETS TO FUNCTIONS =============================
# =============================================================
# link buttons to old_functions
self.btn_start_script.clicked.connect(self.btn_clicked)
self.btn_stop_script.clicked.connect(self.btn_clicked)
self.btn_skip_subscript.clicked.connect(self.btn_clicked)
self.btn_validate_script.clicked.connect(self.btn_clicked)
# self.btn_plot_script.clicked.connect(self.btn_clicked)
# self.btn_plot_probe.clicked.connect(self.btn_clicked)
self.btn_store_script_data.clicked.connect(self.btn_clicked)
# self.btn_plot_data.clicked.connect(self.btn_clicked)
self.btn_save_data.clicked.connect(self.btn_clicked)
self.btn_delete_data.clicked.connect(self.btn_clicked)
self.btn_save_gui.triggered.connect(self.btn_clicked)
self.btn_load_gui.triggered.connect(self.btn_clicked)
self.btn_about.triggered.connect(self.btn_clicked)
self.btn_exit.triggered.connect(self.close)
self.actionSave.triggered.connect(self.btn_clicked)
self.actionExport.triggered.connect(self.btn_clicked)
self.actionGo_to_pylabcontrol_GitHub_page.triggered.connect(
self.btn_clicked)
self.btn_load_instruments.clicked.connect(self.btn_clicked)
self.btn_load_scripts.clicked.connect(self.btn_clicked)
self.btn_load_probes.clicked.connect(self.btn_clicked)
# Helper function to make only column 1 editable
def onScriptParamClick(item, column):
tree = item.treeWidget()
if column == 1 and not isinstance(item.value, (Script, Instrument)) and not item.is_point():
# self.tree_scripts.editItem(item, column)
tree.editItem(item, column)
# tree structures
self.tree_scripts.itemClicked.connect(
lambda: onScriptParamClick(self.tree_scripts.currentItem(), self.tree_scripts.currentColumn()))
self.tree_scripts.itemChanged.connect(
lambda: self.update_parameters(self.tree_scripts))
self.tree_scripts.itemClicked.connect(self.btn_clicked)
# self.tree_scripts.installEventFilter(self)
# QtWidgets.QTreeWidget.installEventFilter(self)
self.tabWidget.currentChanged.connect(lambda: self.switch_tab())
self.tree_dataset.clicked.connect(lambda: self.btn_clicked())
self.tree_settings.itemClicked.connect(
lambda: onScriptParamClick(self.tree_settings.currentItem(), self.tree_settings.currentColumn()))
self.tree_settings.itemChanged.connect(
lambda: self.update_parameters(self.tree_settings))
self.tree_settings.itemExpanded.connect(
lambda: self.refresh_instruments())
# set the log_filename when checking loggin
self.chk_probe_log.toggled.connect(
lambda: self.set_probe_file_name(self.chk_probe_log.isChecked()))
self.chk_probe_plot.toggled.connect(self.btn_clicked)
self.chk_show_all.toggled.connect(self._show_hide_parameter)
self.create_figures()
# create a "delegate" --- an editor that uses our new Editor Factory when creating editors,
# and use that for tree_scripts
# needed to avoid rounding of numbers
delegate = QtWidgets.QStyledItemDelegate()
new_factory = CustomEditorFactory()
delegate.setItemEditorFactory(new_factory)
self.tree_scripts.setItemDelegate(delegate)
setup_trees()
connect_controls()
if filepath is None:
path_to_config = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir, 'save_config.json'))
if os.path.isfile(path_to_config) and os.access(path_to_config, os.R_OK):
print('path_to_config', path_to_config)
with open(path_to_config) as f:
config_data = json.load(f)
if 'last_save_path' in config_data.keys():
self.config_filepath = config_data['last_save_path']
self.log('Checking for previous save of GUI here: {0}'.format(
self.config_filepath))
else:
self.log('Starting with blank GUI; configuration files will be saved here: {0}'.format(
self._DEFAULT_CONFIG["gui_settings"]))
elif os.path.isfile(filepath) and os.access(filepath, os.R_OK):
self.config_filepath = filepath
elif not os.path.isfile(filepath):
self.log(
'Could not find file given to open --- starting with a blank GUI')
self.instruments = {}
self.scripts = {}
self.probes = {}
self.gui_settings = {'scripts_folder': '', 'data_folder': ''}
self.gui_settings_hidden = {'scripts_source_folder': ''}
self.load_config(self.config_filepath)
self.data_sets = {} # todo: load datasets from tmp folder
self.read_probes = ReadProbes(self.probes)
self.tabWidget.setCurrentIndex(0) # always show the script tab
# == create a thread for the scripts ==
self.script_thread = QThread()
# used to keep track of status updates, to block updates when they occur to often
self._last_progress_update = None
self.chk_show_all.setChecked(True)
self.actionSave.setShortcut(QtGui.QKeySequence.Save)
self.actionExport.setShortcut(self.tr('Ctrl+E'))
self.list_history.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
if self.config_filepath is None:
self.config_filepath = os.path.join(
self._DEFAULT_CONFIG["gui_settings"], 'gui.b26')
def closeEvent(self, event):
"""
things to be done when gui closes, like save the settings
"""
self.save_config(self.gui_settings['gui_settings'])
self.script_thread.quit()
self.read_probes.quit()
event.accept()
print('\n\n======================================================')
print('================= Closing B26 Python LAB =============')
print('======================================================\n\n')
def eventFilter(self, object, event):
"""
TEMPORARY / UNDER DEVELOPMENT
THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP
Args:
object:
event:
Returns:
"""
if (object is self.tree_scripts):
# print('XXXXXXX = event in scripts', event.type(),
# QtCore.QEvent.DragEnter, QtCore.QEvent.DragMove, QtCore.QEvent.DragLeave)
if (event.type() == QtCore.QEvent.ChildAdded):
item = self.tree_scripts.selectedItems()[0]
if not isinstance(item.value, Script):
print('ONLY SCRIPTS CAN BE DRAGGED')
return False
print(
('XXX ChildAdded', self.tree_scripts.selectedItems()[0].name))
# if event.mimeData().hasUrls():
# event.accept() # must accept the dragEnterEvent or else the dropEvent can't occur !!!
# print "accept"
# else:
# event.ignore()
# print "ignore"
if (event.type() == QtCore.QEvent.ChildRemoved):
print(
('XXX ChildRemoved', self.tree_scripts.selectedItems()[0].name))
if (event.type() == QtCore.QEvent.Drop):
print('XXX Drop')
# if event.mimeData().hasUrls(): # if file or link is dropped
# urlcount = len(event.mimeData().urls()) # count number of drops
# url = event.mimeData().urls()[0] # get first url
# object.setText(url.toString()) # assign first url to editline
# # event.accept() # doesnt appear to be needed
return False # lets the event continue to the edit
return False
def set_probe_file_name(self, checked):
"""
sets the filename to which the probe logging function will write
Args:
checked: boolean (True: opens file) (False: closes file)
"""
if checked:
file_name = os.path.join(self.gui_settings['probes_log_folder'], '{:s}_probes.csv'.format(
datetime.datetime.now().strftime('%y%m%d-%H_%M_%S')))
if os.path.isfile(file_name) == False:
self.probe_file = open(file_name, 'a')
new_values = self.read_probes.probes_values
header = ','.join(list(np.array([['{:s} ({:s})'.format(p, instr) for p in list(
p_dict.keys())] for instr, p_dict in new_values.items()]).flatten()))
self.probe_file.write('{:s}\n'.format(header))
else:
self.probe_file.close()
def switch_tab(self):
"""
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
"""
current_tab = str(self.tabWidget.tabText(
self.tabWidget.currentIndex()))
if self.current_script is None:
if current_tab == 'Probes':
self.read_probes.start()
self.read_probes.updateProgress.connect(self.update_probes)
else:
try:
self.read_probes.updateProgress.disconnect()
self.read_probes.quit()
except TypeError:
pass
if current_tab == 'Instruments':
self.refresh_instruments()
else:
self.log(
'updating probes / instruments disabled while script is running!')
def refresh_instruments(self):
"""
if self.tree_settings has been expanded, ask instruments for their actual values
"""
def list_access_nested_dict(dict, somelist):
"""
Allows one to use a list to access a nested dictionary, for example:
listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
Args:
dict:
somelist:
Returns:
"""
return reduce(operator.getitem, somelist, dict)
def update(item):
if item.isExpanded():
for index in range(item.childCount()):
child = item.child(index)
if child.childCount() == 0:
instrument, path_to_instrument = child.get_instrument()
path_to_instrument.reverse()
try: # check if item is in probes
value = instrument.read_probes(
path_to_instrument[-1])
except AssertionError: # if item not in probes, get value from settings instead
value = list_access_nested_dict(
instrument.settings, path_to_instrument)
child.value = value
else:
update(child)
# need to block signals during update so that tree.itemChanged doesn't fire and the gui doesn't try to
# reupdate the instruments to their current value
self.tree_settings.blockSignals(True)
for index in range(self.tree_settings.topLevelItemCount()):
instrument = self.tree_settings.topLevelItem(index)
update(instrument)
self.tree_settings.blockSignals(False)
def plot_clicked(self, mouse_event):
"""
gets activated when the user clicks on a plot
Args:
mouse_event:
"""
if isinstance(self.current_script, SelectPoints) and self.current_script.is_running:
if (not (mouse_event.xdata == None)):
if (mouse_event.button == 1):
pt = np.array([mouse_event.xdata, mouse_event.ydata])
self.current_script.toggle_NV(pt)
self.current_script.plot([self.matplotlibwidget_1.figure])
self.matplotlibwidget_1.draw()
item = self.tree_scripts.currentItem()
if item is not None:
if item.is_point():
# item_x = item.child(1)
item_x = item.child(0)
if mouse_event.xdata is not None:
self.tree_scripts.setCurrentItem(item_x)
item_x.value = float(mouse_event.xdata)
item_x.setText(1, '{:0.3f}'.format(
float(mouse_event.xdata)))
# item_y = item.child(0)
item_y = item.child(1)
if mouse_event.ydata is not None:
self.tree_scripts.setCurrentItem(item_y)
item_y.value = float(mouse_event.ydata)
item_y.setText(1, '{:0.3f}'.format(
float(mouse_event.ydata)))
# focus back on item
self.tree_scripts.setCurrentItem(item)
else:
if item.parent() is not None:
if item.parent().is_point():
if item == item.parent().child(1):
if mouse_event.xdata is not None:
item.setData(1, 2, float(mouse_event.xdata))
if item == item.parent().child(0):
if mouse_event.ydata is not None:
item.setData(1, 2, float(mouse_event.ydata))
def get_time(self):
"""
Returns: the current time as a formated string
"""
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
def log(self, msg):
"""
log function
Args:
msg: the text message to be logged
"""
time = self.get_time()
msg = "{:s}\t {:s}".format(time, msg)
self.history.append(msg)
self.history_model.insertRow(0, QtGui.QStandardItem(msg))
def create_figures(self):
"""
creates the maplotlib figures]
self.matplotlibwidget_1
self.matplotlibwidget_2
and toolbars
self.mpl_toolbar_1
self.mpl_toolbar_2
Returns:
"""
try:
self.horizontalLayout_14.removeWidget(self.matplotlibwidget_1)
self.matplotlibwidget_1.close()
except AttributeError:
pass
try:
self.horizontalLayout_15.removeWidget(self.matplotlibwidget_2)
self.matplotlibwidget_2.close()
except AttributeError:
pass
self.matplotlibwidget_2 = MatplotlibWidget(self.plot_2)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.matplotlibwidget_2.sizePolicy().hasHeightForWidth())
self.matplotlibwidget_2.setSizePolicy(sizePolicy)
self.matplotlibwidget_2.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget_2.setObjectName("matplotlibwidget_2")
self.horizontalLayout_16.addWidget(self.matplotlibwidget_2)
self.matplotlibwidget_1 = MatplotlibWidget(self.plot_1)
self.matplotlibwidget_1.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget_1.setObjectName("matplotlibwidget_1")
self.horizontalLayout_15.addWidget(self.matplotlibwidget_1)
self.matplotlibwidget_1.mpl_connect(
'button_press_event', self.plot_clicked)
self.matplotlibwidget_2.mpl_connect(
'button_press_event', self.plot_clicked)
# adds a toolbar to the plots
self.mpl_toolbar_1 = NavigationToolbar(
self.matplotlibwidget_1.canvas, self.toolbar_space_1)
self.mpl_toolbar_2 = NavigationToolbar(
self.matplotlibwidget_2.canvas, self.toolbar_space_2)
self.horizontalLayout_9.addWidget(self.mpl_toolbar_2)
self.horizontalLayout_14.addWidget(self.mpl_toolbar_1)
self.matplotlibwidget_1.figure.set_tight_layout(True)
self.matplotlibwidget_2.figure.set_tight_layout(True)
def load_scripts(self):
"""
opens file dialog to load scripts into gui
"""
# update scripts so that current settings do not get lost
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
self.update_script_from_item(script_item)
dialog = LoadDialog(elements_type="scripts", elements_old=self.scripts,
filename=self.gui_settings['scripts_folder'])
if dialog.exec_():
self.gui_settings['scripts_folder'] = str(
dialog.txt_probe_log_path.text())
scripts = dialog.get_values()
added_scripts = set(scripts.keys()) - set(self.scripts.keys())
removed_scripts = set(self.scripts.keys()) - set(scripts.keys())
if 'data_folder' in list(self.gui_settings.keys()) and os.path.exists(self.gui_settings['data_folder']):
data_folder_name = self.gui_settings['data_folder']
else:
data_folder_name = None
# create instances of new instruments/scripts
self.scripts, loaded_failed, self.instruments = Script.load_and_append(
script_dict={name: scripts[name] for name in added_scripts},
scripts=self.scripts,
instruments=self.instruments,
log_function=self.log,
data_path=data_folder_name,
raise_errors=False)
# delete instances of new instruments/scripts that have been deselected
for name in removed_scripts:
del self.scripts[name]
def btn_clicked(self):
"""
slot to which connect buttons
"""
sender = self.sender()
self.probe_to_plot = None
def start_button():
"""
starts the selected script
"""
item = self.tree_scripts.currentItem()
# BROKEN 20170109: repeatedly erases updates to gui
# self.expanded_items = []
# for index in range(self.tree_scripts.topLevelItemCount()):
# someitem = self.tree_scripts.topLevelItem(index)
# if someitem.isExpanded():
# self.expanded_items.append(someitem.name)
self.script_start_time = datetime.datetime.now()
if item is not None:
# get script and update settings from tree
self.running_item = item
script, path_to_script, script_item = item.get_script()
self.update_script_from_item(script_item)
self.log('starting {:s}'.format(script.name))
# put script onto script thread
print('================================================')
print(('===== starting {:s}'.format(script.name)))
print('================================================')
script_thread = self.script_thread
def move_to_worker_thread(script):
script.moveToThread(script_thread)
# move also the subscript to the worker thread
for subscript in list(script.scripts.values()):
move_to_worker_thread(subscript)
move_to_worker_thread(script)
# connect update signal of script to update slot of gui
script.updateProgress.connect(self.update_status)
# causes the script to start upon starting the thread
script_thread.started.connect(script.run)
# clean up. quit thread after script is finished
script.finished.connect(script_thread.quit)
# connect finished signal of script to finished slot of gui
script.finished.connect(self.script_finished)
# start thread, i.e. script
script_thread.start()
self.current_script = script
self.btn_start_script.setEnabled(False)
# self.tabWidget.setEnabled(False)
if isinstance(self.current_script, ScriptIterator):
self.btn_skip_subscript.setEnabled(True)
else:
self.log('User tried to run a script without one selected.')
def stop_button():
"""
stops the current script
"""
if self.current_script is not None and self.current_script.is_running:
self.current_script.stop()
else:
self.log(
'User clicked stop, but there isn\'t anything running...this is awkward. Re-enabling start button anyway.')
self.btn_start_script.setEnabled(True)
def skip_button():
"""
Skips to the next script if the current script is a Iterator script
"""
if self.current_script is not None and self.current_script.is_running and isinstance(self.current_script,
ScriptIterator):
self.current_script.skip_next()
else:
self.log(
'User clicked skip, but there isn\'t a iterator script running...this is awkward.')
def validate_button():
"""
validates the selected script
"""
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, script_item = item.get_script()
self.update_script_from_item(script_item)
script.is_valid()
script.plot_validate(
[self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
def store_script_data():
"""
updates the internal self.data_sets with selected script and updates tree self.fill_dataset_tree
"""
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, _ = item.get_script()
script_copy = script.duplicate()
time_tag = script.start_time.strftime('%y%m%d-%H_%M_%S')
self.data_sets.update({time_tag: script_copy})
self.fill_dataset_tree(self.tree_dataset, self.data_sets)
def save_data():
""""
saves the selected script (where is contained in the script itself)
"""
indecies = self.tree_dataset.selectedIndexes()
model = indecies[0].model()
rows = list(set([index.row()for index in indecies]))
for row in rows:
time_tag = str(model.itemFromIndex(model.index(row, 0)).text())
name_tag = str(model.itemFromIndex(model.index(row, 1)).text())
path = self.gui_settings['data_folder']
script = self.data_sets[time_tag]
script.update({'tag': name_tag, 'path': path})
script.save_data()
script.save_image_to_disk()
script.save_b26()
script.save_log()
def delete_data():
"""
deletes the data from the dataset
Returns:
"""
indecies = self.tree_dataset.selectedIndexes()
model = indecies[0].model()
rows = list(set([index.row()for index in indecies]))
for row in rows:
time_tag = str(model.itemFromIndex(model.index(row, 0)).text())
del self.data_sets[time_tag]
model.removeRows(row, 1)
def load_probes():
"""
opens file dialog to load probes into gui
"""
# if the probe has never been started it can not be disconnected so we catch that error
try:
self.read_probes.updateProgress.disconnect()
self.read_probes.quit()
# self.read_probes.stop()
except RuntimeError:
pass
dialog = LoadDialogProbes(
probes_old=self.probes, filename=self.gui_settings['probes_folder'])
if dialog.exec_():
self.gui_settings['probes_folder'] = str(
dialog.txt_probe_log_path.text())
probes = dialog.get_values()
added_instruments = list(
set(probes.keys()) - set(self.probes.keys()))
removed_instruments = list(
set(self.probes.keys()) - set(probes.keys()))
# create instances of new probes
self.probes, loaded_failed, self.instruments = Probe.load_and_append(
probe_dict=probes,
probes={},
instruments=self.instruments)
if not loaded_failed:
print(('WARNING following probes could not be loaded',
loaded_failed, len(loaded_failed)))
# restart the readprobes thread
del self.read_probes
self.read_probes = ReadProbes(self.probes)
self.read_probes.start()
self.tree_probes.clear() # clear tree because the probe might have changed
self.read_probes.updateProgress.connect(self.update_probes)
self.tree_probes.expandAll()
def load_instruments():
"""
opens file dialog to load instruments into gui
"""
if 'instrument_folder' in self.gui_settings:
dialog = LoadDialog(elements_type="instruments", elements_old=self.instruments,
filename=self.gui_settings['instrument_folder'])
else:
dialog = LoadDialog(elements_type="instruments",
elements_old=self.instruments)
if dialog.exec_():
self.gui_settings['instrument_folder'] = str(
dialog.txt_probe_log_path.text())
instruments = dialog.get_values()
added_instruments = set(
instruments.keys()) - set(self.instruments.keys())
removed_instruments = set(
self.instruments.keys()) - set(instruments.keys())
# print('added_instruments', {name: instruments[name] for name in added_instruments})
# create instances of new instruments
self.instruments, loaded_failed = Instrument.load_and_append(
{name: instruments[name] for name in added_instruments}, self.instruments)
if len(loaded_failed) > 0:
print(
('WARNING following instrument could not be loaded', loaded_failed))
# delete instances of new instruments/scripts that have been deselected
for name in removed_instruments:
del self.instruments[name]
def plot_data(sender):
"""
plots the data of the selected script
"""
if sender == self.tree_dataset:
index = self.tree_dataset.selectedIndexes()[0]
model = index.model()
time_tag = str(model.itemFromIndex(
model.index(index.row(), 0)).text())
script = self.data_sets[time_tag]
self.plot_script(script)
elif sender == self.tree_scripts:
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, _ = item.get_script()
# only plot if script has been selected but not if a parameter has been selected
if path_to_script == []:
self.plot_script(script)
def save():
self.save_config(self.gui_settings['gui_settings'])
if sender is self.btn_start_script:
start_button()
elif sender is self.btn_stop_script:
stop_button()
elif sender is self.btn_skip_subscript:
skip_button()
elif sender is self.btn_validate_script:
validate_button()
elif sender in (self.tree_dataset, self.tree_scripts):
plot_data(sender)
elif sender is self.btn_store_script_data:
store_script_data()
elif sender is self.btn_save_data:
save_data()
elif sender is self.btn_delete_data:
delete_data()
# elif sender is self.btn_plot_probe:
elif sender is self.chk_probe_plot:
if self.chk_probe_plot.isChecked():
item = self.tree_probes.currentItem()
if item is not None:
if item.name in self.probes:
# selected item is an instrument not a probe, maybe plot all the probes...
self.log(
'Can\'t plot, No probe selected. Select probe and try again!')
else:
instrument = item.parent().name
self.probe_to_plot = self.probes[instrument][item.name]
else:
self.log(
'Can\'t plot, No probe selected. Select probe and try again!')
else:
self.probe_to_plot = None
elif sender is self.btn_save_gui:
# get filename
filepath, _ = QtWidgets.QFileDialog.getSaveFileName(
self, 'Save gui settings to file', self.config_filepath, filter='*.b26')
# in case the user cancels during the prompt, check that the filepath is not an empty string
if filepath:
filename, file_extension = os.path.splitext(filepath)
if file_extension != '.b26':
filepath = filename + ".b26"
filepath = os.path.normpath(filepath)
self.save_config(filepath)
self.gui_settings['gui_settings'] = filepath
self.refresh_tree(self.tree_gui_settings, self.gui_settings)
elif sender is self.btn_load_gui:
# get filename
fname = QtWidgets.QFileDialog.getOpenFileName(
self, 'Load gui settings from file', self.gui_settings['data_folder'], filter='*.b26')
self.load_config(fname[0])
elif sender is self.btn_about:
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText(
"pylabcontrol: Laboratory Equipment Control for Scientific Experiments")
msg.setInformativeText("This software was developed by Arthur Safira, Jan Gieseler, and Aaron Kabcenell at"
"Harvard University. It is licensed under the LPGL licence. For more information,"
"visit the GitHub page at github.com/LISE-B26/pylabcontrol .")
msg.setWindowTitle("About")
# msg.setDetailedText("some stuff")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
# msg.buttonClicked.connect(msgbtn)
retval = msg.exec_()
# elif (sender is self.btn_load_instruments) or (sender is self.btn_load_scripts):
elif sender in (self.btn_load_instruments, self.btn_load_scripts, self.btn_load_probes):
if sender is self.btn_load_instruments:
load_instruments()
elif sender is self.btn_load_scripts:
self.load_scripts()
elif sender is self.btn_load_probes:
load_probes()
# refresh trees
self.refresh_tree(self.tree_scripts, self.scripts)
self.refresh_tree(self.tree_settings, self.instruments)
elif sender is self.actionSave:
self.save_config(self.gui_settings['gui_settings'])
elif sender is self.actionGo_to_pylabcontrol_GitHub_page:
webbrowser.open('https://github.com/LISE-B26/pylabcontrol')
elif sender is self.actionExport:
export_dialog = ExportDialog()
export_dialog.target_path.setText(
self.gui_settings['scripts_folder'])
if self.gui_settings_hidden['scripts_source_folder']:
export_dialog.source_path.setText(
self.gui_settings_hidden['scripts_source_folder'])
if export_dialog.source_path.text():
export_dialog.reset_avaliable(export_dialog.source_path.text())
# exec_() blocks while export dialog is used, subsequent code will run on dialog closing
export_dialog.exec_()
self.gui_settings.update(
{'scripts_folder': export_dialog.target_path.text()})
self.fill_treeview(self.tree_gui_settings, self.gui_settings)
self.gui_settings_hidden.update(
{'scripts_source_folder': export_dialog.source_path.text()})
def _show_hide_parameter(self):
"""
shows or hides parameters
Returns:
"""
assert isinstance(self.sender(
), QtWidgets.QCheckBox), 'this function should be connected to a check box'
if self.sender().isChecked():
self.tree_scripts.setColumnHidden(2, False)
iterator = QtWidgets.QTreeWidgetItemIterator(
self.tree_scripts, QtWidgets.QTreeWidgetItemIterator.Hidden)
item = iterator.value()
while item:
item.setHidden(False)
item = iterator.value()
iterator += 1
else:
self.tree_scripts.setColumnHidden(2, True)
iterator = QtWidgets.QTreeWidgetItemIterator(
self.tree_scripts, QtWidgets.QTreeWidgetItemIterator.NotHidden)
item = iterator.value()
while item:
if not item.visible:
item.setHidden(True)
item = iterator.value()
iterator += 1
self.tree_scripts.setColumnWidth(0, 200)
self.tree_scripts.setColumnWidth(1, 400)
self.tree_scripts.setColumnWidth(2, 50)
def update_parameters(self, treeWidget):
"""
updates the internal dictionaries for scripts and instruments with values from the respective trees
treeWidget: the tree from which to update
"""
if treeWidget == self.tree_settings:
item = treeWidget.currentItem()
instrument, path_to_instrument = item.get_instrument()
# build nested dictionary to update instrument
dictator = item.value
for element in path_to_instrument:
dictator = {element: dictator}
# get old value from instrument
old_value = instrument.settings
path_to_instrument.reverse()
for element in path_to_instrument:
old_value = old_value[element]
# send new value from tree to instrument
instrument.update(dictator)
new_value = item.value
if new_value is not old_value:
msg = "changed parameter {:s} from {:s} to {:s} on {:s}".format(item.name, str(old_value),
str(new_value), instrument.name)
else:
msg = "did not change parameter {:s} on {:s}".format(
item.name, instrument.name)
self.log(msg)
elif treeWidget == self.tree_scripts:
item = treeWidget.currentItem()
script, path_to_script, _ = item.get_script()
# check if changes value is from an instrument
instrument, path_to_instrument = item.get_instrument()
if instrument is not None:
new_value = item.value
msg = "changed parameter {:s} to {:s} in {:s}".format(item.name,
str(new_value),
script.name)
else:
new_value = item.value
msg = "changed parameter {:s} to {:s} in {:s}".format(item.name,
str(new_value),
script.name)
self.log(msg)
def plot_script(self, script):
"""
Calls the plot function of the script, and redraws both plots
Args:
script: script to be plotted
"""
script.plot([self.matplotlibwidget_1.figure,
self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
@pyqtSlot(int)
def update_status(self, progress):
"""
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
"""
# interval at which the gui will be updated, if requests come in faster than they will be ignored
update_interval = 0.2
now = datetime.datetime.now()
if not self._last_progress_update is None and now-self._last_progress_update < datetime.timedelta(seconds=update_interval):
return
self._last_progress_update = now
self.progressBar.setValue(progress)
script = self.current_script
# Estimate remaining time if progress has been made
if progress:
remaining_time = str(datetime.timedelta(
seconds=script.remaining_time.seconds))
self.lbl_time_estimate.setText(
'time remaining: {:s}'.format(remaining_time))
if script is not str(self.tabWidget.tabText(self.tabWidget.currentIndex())).lower() in ['scripts', 'instruments']:
self.plot_script(script)
@pyqtSlot()
def script_finished(self):
"""
waits for the script to emit the script_finshed signal
"""
script = self.current_script
script.updateProgress.disconnect(self.update_status)
self.script_thread.started.disconnect()
script.finished.disconnect()
self.current_script = None
self.plot_script(script)
self.progressBar.setValue(100)
self.btn_start_script.setEnabled(True)
self.btn_skip_subscript.setEnabled(False)
def plot_script_validate(self, script):
"""
checks the plottype of the script and plots it accordingly
Args:
script: script to be plotted
"""
script.plot_validate(
[self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
def update_probes(self, progress):
"""
update the probe tree
"""
new_values = self.read_probes.probes_values
probe_count = len(self.read_probes.probes)
if probe_count > self.tree_probes.topLevelItemCount():
# when run for the first time, there are no probes in the tree, so we have to fill it first
self.fill_treewidget(self.tree_probes, new_values)
else:
for x in range(probe_count):
topLvlItem = self.tree_probes.topLevelItem(x)
for child_id in range(topLvlItem.childCount()):
child = topLvlItem.child(child_id)
child.value = new_values[topLvlItem.name][child.name]
child.setText(1, str(child.value))
if self.probe_to_plot is not None:
self.probe_to_plot.plot(self.matplotlibwidget_1.axes)
self.matplotlibwidget_1.draw()
if self.chk_probe_log.isChecked():
data = ','.join(list(np.array([[str(p) for p in list(
p_dict.values())] for instr, p_dict in new_values.items()]).flatten()))
self.probe_file.write('{:s}\n'.format(data))
def update_script_from_item(self, item):
"""
updates the script based on the information provided in item
Args:
script: script to be updated
item: B26QTreeItem that contains the new settings of the script
"""
script, path_to_script, script_item = item.get_script()
# build dictionary
# get full information from script
# there is only one item in the dictionary
dictator = list(script_item.to_dict().values())[0]
for instrument in list(script.instruments.keys()):
# update instrument
script.instruments[instrument]['settings'] = dictator[instrument]['settings']
# remove instrument
del dictator[instrument]
for sub_script_name in list(script.scripts.keys()):
sub_script_item = script_item.get_subscript(sub_script_name)
self.update_script_from_item(sub_script_item)
del dictator[sub_script_name]
script.update(dictator)
# update datefolder path
script.data_path = self.gui_settings['data_folder']
def fill_treewidget(self, tree, parameters):
"""
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Returns:
"""
tree.clear()
assert isinstance(parameters, (dict, Parameter))
for key, value in parameters.items():
if isinstance(value, Parameter):
B26QTreeItem(tree, key, value,
parameters.valid_values[key], parameters.info[key])
else:
B26QTreeItem(tree, key, value, type(value), '')
def fill_treeview(self, tree, input_dict):
"""
fills a treeview with nested parameters
Args:
tree: QtWidgets.QTreeView
parameters: dictionary or Parameter object
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
def add_element(item, key, value):
child_name = QtWidgets.QStandardItem(key)
if isinstance(value, dict):
for key_child, value_child in value.items():
add_element(child_name, key_child, value_child)
item.appendRow(child_name)
else:
child_value = QtWidgets.QStandardItem(str(value))
item.appendRow([child_name, child_value])
for index, (key, value) in enumerate(input_dict.items()):
if isinstance(value, dict):
item = QtWidgets.QStandardItem(key)
for sub_key, sub_value in value.items():
add_element(item, sub_key, sub_value)
tree.model().appendRow(item)
elif isinstance(value, str):
item = QtGui.QStandardItem(key)
item_value = QtGui.QStandardItem(value)
item_value.setEditable(True)
item_value.setSelectable(True)
tree.model().appendRow([item, item_value])
def edit_tree_item(self):
"""
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath
this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
"""
def open_path_dialog_folder(path):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtWidgets.QFileDialog()
dialog.setFileMode(QtWidgets.QFileDialog.Directory)
dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
path = dialog.getExistingDirectory(self, 'Select a folder:', path)
return path
tree = self.sender()
if tree == self.tree_gui_settings:
index = tree.selectedIndexes()[0]
model = index.model()
if index.column() == 1:
path = model.itemFromIndex(index).text()
key = str(model.itemFromIndex(
model.index(index.row(), 0)).text())
if (key == 'gui_settings'):
path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, caption='Select a file:', directory=path, filter='*.b26')
if path:
name, extension = os.path.splitext(path)
if extension != '.b26':
path = name + ".b26"
else:
path = str(open_path_dialog_folder(path))
if path != "":
self.gui_settings.update(
{key: str(os.path.normpath(path))})
self.fill_treeview(tree, self.gui_settings)
def refresh_tree(self, tree, items):
"""
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones
"""
if tree == self.tree_scripts or tree == self.tree_settings:
tree.itemChanged.disconnect()
self.fill_treewidget(tree, items)
tree.itemChanged.connect(lambda: self.update_parameters(tree))
elif tree == self.tree_gui_settings:
self.fill_treeview(tree, items)
def fill_dataset_tree(self, tree, data_sets):
"""
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
for index, (time, script) in enumerate(data_sets.items()):
name = script.settings['tag']
type = script.name
item_time = QtGui.QStandardItem(str(time))
item_name = QtGui.QStandardItem(str(name))
item_type = QtGui.QStandardItem(str(type))
item_time.setSelectable(False)
item_time.setEditable(False)
item_type.setSelectable(False)
item_type.setEditable(False)
tree.model().appendRow([item_time, item_name, item_type])
def load_config(self, filepath=None):
"""
checks if the file is a valid config file
Args:
filepath:
"""
# load config or default if invalid
def load_settings(filepath):
"""
loads a old_gui settings file (a json dictionary)
- path_to_file: path to file that contains the dictionary
Returns:
- instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
- scripts: depth 1 dictionary where keys are script names and values are instances of scripts
- probes: depth 1 dictionary where to be decided....?
"""
instruments_loaded = {}
probes_loaded = {}
scripts_loaded = {}
if filepath and os.path.isfile(filepath):
in_data = load_b26_file(filepath)
instruments = in_data['instruments'] if 'instruments' in in_data else {
}
scripts = in_data['scripts'] if 'scripts' in in_data else {}
probes = in_data['probes'] if 'probes' in in_data else {}
try:
instruments_loaded, failed = Instrument.load_and_append(
instruments)
if len(failed) > 0:
print(
('WARNING! Following instruments could not be loaded: ', failed))
scripts_loaded, failed, instruments_loaded = Script.load_and_append(
script_dict=scripts,
instruments=instruments_loaded,
log_function=self.log,
data_path=self.gui_settings['data_folder'])
if len(failed) > 0:
print(
('WARNING! Following scripts could not be loaded: ', failed))
probes_loaded, failed, instruments_loadeds = Probe.load_and_append(
probe_dict=probes,
probes=probes_loaded,
instruments=instruments_loaded)
self.log('Successfully loaded from previous save.')
except ImportError:
self.log('Could not load instruments or scripts from file.')
self.log('Opening with blank GUI.')
return instruments_loaded, scripts_loaded, probes_loaded
config = None
try:
config = load_b26_file(filepath)
config_settings = config['gui_settings']
if config_settings['gui_settings'] != filepath:
print((
'WARNING path to settings file ({:s}) in config file is different from path of settings file ({:s})'.format(
config_settings['gui_settings'], filepath)))
config_settings['gui_settings'] = filepath
except Exception as e:
if filepath:
self.log(
'The filepath was invalid --- could not load settings. Loading blank GUI.')
config_settings = self._DEFAULT_CONFIG
for x in self._DEFAULT_CONFIG.keys():
if x in config_settings:
if not os.path.exists(config_settings[x]):
try:
os.makedirs(config_settings[x])
except Exception:
config_settings[x] = self._DEFAULT_CONFIG[x]
os.makedirs(config_settings[x])
print(('WARNING: failed validating or creating path: set to default path'.format(
config_settings[x])))
else:
config_settings[x] = self._DEFAULT_CONFIG[x]
os.makedirs(config_settings[x])
print(('WARNING: path {:s} not specified set to default {:s}'.format(
x, config_settings[x])))
# check if file_name is a valid filename
if filepath is not None and os.path.exists(os.path.dirname(filepath)):
config_settings['gui_settings'] = filepath
self.gui_settings = config_settings
if (config):
self.gui_settings_hidden = config['gui_settings_hidden']
else:
self.gui_settings_hidden['script_source_folder'] = ''
self.instruments, self.scripts, self.probes = load_settings(filepath)
self.refresh_tree(self.tree_gui_settings, self.gui_settings)
self.refresh_tree(self.tree_scripts, self.scripts)
self.refresh_tree(self.tree_settings, self.instruments)
self._hide_parameters(filepath)
def _hide_parameters(self, file_name):
"""
hide the parameters that had been hidden
Args:
file_name: config file that has the information about which parameters are hidden
"""
try:
in_data = load_b26_file(file_name)
except:
in_data = {}
def set_item_visible(item, is_visible):
if isinstance(is_visible, dict):
for child_id in range(item.childCount()):
child = item.child(child_id)
if child.name in is_visible:
set_item_visible(child, is_visible[child.name])
else:
item.visible = is_visible
if "scripts_hidden_parameters" in in_data:
# consistency check
if len(list(in_data["scripts_hidden_parameters"].keys())) == self.tree_scripts.topLevelItemCount():
for index in range(self.tree_scripts.topLevelItemCount()):
item = self.tree_scripts.topLevelItem(index)
# if item.name in in_data["scripts_hidden_parameters"]:
set_item_visible(
item, in_data["scripts_hidden_parameters"][item.name])
else:
print(
'WARNING: settings for hiding parameters does\'t seem to match other settings')
# else:
# print('WARNING: no settings for hiding parameters all set to default')
def save_config(self, filepath):
"""
saves gui configuration to out_file_name
Args:
filepath: name of file
"""
def get_hidden_parameter(item):
num_sub_elements = item.childCount()
if num_sub_elements == 0:
dictator = {item.name: item.visible}
else:
dictator = {item.name: {}}
for child_id in range(num_sub_elements):
dictator[item.name].update(
get_hidden_parameter(item.child(child_id)))
return dictator
print('JG tmp filepath', filepath)
try:
filepath = str(filepath)
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
self.log('ceated dir ' + os.path.dirname(filepath))
# build a dictionary for the configuration of the hidden parameters
dictator = {}
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
dictator.update(get_hidden_parameter(script_item))
dictator = {"gui_settings": self.gui_settings, "gui_settings_hidden":
self.gui_settings_hidden, "scripts_hidden_parameters": dictator}
# update the internal dictionaries from the trees in the gui
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
self.update_script_from_item(script_item)
dictator.update({'instruments': {}, 'scripts': {}, 'probes': {}})
for instrument in self.instruments.values():
dictator['instruments'].update(instrument.to_dict())
for script in self.scripts.values():
dictator['scripts'].update(script.to_dict())
for instrument, probe_dict in self.probes.items():
dictator['probes'].update(
{instrument: ','.join(list(probe_dict.keys()))})
with open(filepath, 'w') as outfile:
json.dump(dictator, outfile, indent=4)
self.log(
'Saved GUI configuration (location: {:s})'.format(filepath))
except Exception:
msg = QtWidgets.QMessageBox()
msg.setText("Saving to {:s} failed."
"Please use 'save as' to define a valid path for the gui.".format(filepath))
msg.exec_()
try:
save_config_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir, 'save_config.json'))
if os.path.isfile(save_config_path) and os.access(save_config_path, os.R_OK):
with open(save_config_path, 'w') as outfile:
json.dump({'last_save_path': filepath}, outfile, indent=4)
else:
with io.open(save_config_path, 'w') as save_config_file:
save_config_file.write(json.dumps(
{'last_save_path': filepath}))
self.log('Saved save_config.json')
except Exception:
msg = QtWidgets.QMessageBox()
msg.setText("Saving save_config.json failed (:s). Check if use has write access to this folder.".format(
save_config_path))
msg.exec_()
def save_dataset(self, out_file_name):
"""
saves current dataset to out_file_name
Args:
out_file_name: name of file
"""
for time_tag, script in self.data_sets.items():
script.save(os.path.join(out_file_name,
'{:s}.b26s'.format(time_tag)))
|
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, filepath=None):
'''
MainWindow(intruments, scripts, probes)
- intruments: depth 1 dictionary where keys are instrument names and keys are instrument classes
- scripts: depth 1 dictionary where keys are script names and keys are script classes
- probes: depth 1 dictionary where to be decided....?
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
'''
pass
def setup_trees():
pass
def connect_controls():
pass
def onScriptParamClick(item, column):
pass
def closeEvent(self, event):
'''
things to be done when gui closes, like save the settings
'''
pass
def eventFilter(self, object, event):
'''
TEMPORARY / UNDER DEVELOPMENT
THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP
Args:
object:
event:
Returns:
'''
pass
def set_probe_file_name(self, checked):
'''
sets the filename to which the probe logging function will write
Args:
checked: boolean (True: opens file) (False: closes file)
'''
pass
def switch_tab(self):
'''
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
'''
pass
def refresh_instruments(self):
'''
if self.tree_settings has been expanded, ask instruments for their actual values
'''
pass
def list_access_nested_dict(dict, somelist):
'''
Allows one to use a list to access a nested dictionary, for example:
listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
Args:
dict:
somelist:
Returns:
'''
pass
def update(item):
pass
def plot_clicked(self, mouse_event):
'''
gets activated when the user clicks on a plot
Args:
mouse_event:
'''
pass
def get_time(self):
'''
Returns: the current time as a formated string
'''
pass
def log(self, msg):
'''
log function
Args:
msg: the text message to be logged
'''
pass
def create_figures(self):
'''
creates the maplotlib figures]
self.matplotlibwidget_1
self.matplotlibwidget_2
and toolbars
self.mpl_toolbar_1
self.mpl_toolbar_2
Returns:
'''
pass
def load_scripts(self):
'''
opens file dialog to load scripts into gui
'''
pass
def btn_clicked(self):
'''
slot to which connect buttons
'''
pass
def start_button():
'''
starts the selected script
'''
pass
def move_to_worker_thread(script):
pass
def stop_button():
'''
stops the current script
'''
pass
def skip_button():
'''
Skips to the next script if the current script is a Iterator script
'''
pass
def validate_button():
'''
validates the selected script
'''
pass
def store_script_data():
'''
updates the internal self.data_sets with selected script and updates tree self.fill_dataset_tree
'''
pass
def save_data():
'''"
saves the selected script (where is contained in the script itself)
'''
pass
def delete_data():
'''
deletes the data from the dataset
Returns:
'''
pass
def load_probes():
'''
opens file dialog to load probes into gui
'''
pass
def load_instruments():
'''
opens file dialog to load instruments into gui
'''
pass
def plot_data(sender):
'''
plots the data of the selected script
'''
pass
def save_data():
pass
def _show_hide_parameter(self):
'''
shows or hides parameters
Returns:
'''
pass
def update_parameters(self, treeWidget):
'''
updates the internal dictionaries for scripts and instruments with values from the respective trees
treeWidget: the tree from which to update
'''
pass
def plot_script(self, script):
'''
Calls the plot function of the script, and redraws both plots
Args:
script: script to be plotted
'''
pass
@pyqtSlot(int)
def update_status(self, progress):
'''
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
'''
pass
@pyqtSlot()
def script_finished(self):
'''
waits for the script to emit the script_finshed signal
'''
pass
def plot_script_validate(self, script):
'''
checks the plottype of the script and plots it accordingly
Args:
script: script to be plotted
'''
pass
def update_probes(self, progress):
'''
update the probe tree
'''
pass
def update_script_from_item(self, item):
'''
updates the script based on the information provided in item
Args:
script: script to be updated
item: B26QTreeItem that contains the new settings of the script
'''
pass
def fill_treewidget(self, tree, parameters):
'''
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Returns:
'''
pass
def fill_treeview(self, tree, input_dict):
'''
fills a treeview with nested parameters
Args:
tree: QtWidgets.QTreeView
parameters: dictionary or Parameter object
Returns:
'''
pass
def add_element(item, key, value):
pass
def edit_tree_item(self):
'''
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath
this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
'''
pass
def open_path_dialog_folder(path):
'''
opens a file dialog to get the path to a file and
'''
pass
def refresh_tree(self, tree, items):
'''
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones
'''
pass
def fill_dataset_tree(self, tree, data_sets):
'''
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
'''
pass
def load_config(self, filepath=None):
'''
checks if the file is a valid config file
Args:
filepath:
'''
pass
def load_settings(filepath):
'''
loads a old_gui settings file (a json dictionary)
- path_to_file: path to file that contains the dictionary
Returns:
- instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
- scripts: depth 1 dictionary where keys are script names and values are instances of scripts
- probes: depth 1 dictionary where to be decided....?
'''
pass
def _hide_parameters(self, file_name):
'''
hide the parameters that had been hidden
Args:
file_name: config file that has the information about which parameters are hidden
'''
pass
def set_item_visible(item, is_visible):
pass
def save_config(self, filepath):
'''
saves gui configuration to out_file_name
Args:
filepath: name of file
'''
pass
def get_hidden_parameter(item):
pass
def save_dataset(self, out_file_name):
'''
saves current dataset to out_file_name
Args:
out_file_name: name of file
'''
pass
| 54 | 42 | 35 | 6 | 21 | 8 | 4 | 0.37 | 2 | 29 | 12 | 0 | 29 | 17 | 29 | 29 | 1,392 | 272 | 828 | 234 | 774 | 305 | 734 | 228 | 682 | 27 | 1 | 6 | 211 |
144,554 |
LISE-B26/pylabcontrol
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LISE-B26_pylabcontrol/build/lib/pylabcontrol/gui/windows_and_widgets/main_window.py
|
lib.pylabcontrol.gui.windows_and_widgets.main_window.MainWindow
|
class MainWindow(QMainWindow, Ui_MainWindow):
application_path = os.path.abspath(os.path.join(
os.path.expanduser("~"), 'pylabcontrol_default_save_location'))
_DEFAULT_CONFIG = {
"data_folder": os.path.join(application_path, "data"),
"probes_folder": os.path.join(application_path, "probes_auto_generated"),
"instrument_folder": os.path.join(application_path, "instruments_auto_generated"),
"scripts_folder": os.path.join(application_path, "scripts_auto_generated"),
"probes_log_folder": os.path.join(application_path, "b26_tmp"),
"gui_settings": os.path.join(application_path, "pylabcontrol_config.b26")
}
startup_msg = '\n\n\
======================================================\n\
=============== Starting B26 Python LAB =============\n\
======================================================\n\n'
def __init__(self, filepath=None):
"""
MainWindow(intruments, scripts, probes)
- intruments: depth 1 dictionary where keys are instrument names and keys are instrument classes
- scripts: depth 1 dictionary where keys are script names and keys are script classes
- probes: depth 1 dictionary where to be decided....?
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
"""
print(self.startup_msg)
self.config_filepath = None
super(MainWindow, self).__init__()
self.setupUi(self)
def setup_trees():
# COMMENT_ME
# define data container
self.history = deque(maxlen=500) # history of executed commands
self.history_model = QtGui.QStandardItemModel(self.list_history)
self.list_history.setModel(self.history_model)
self.list_history.show()
self.tree_scripts.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_probes.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_settings.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_gui_settings.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_gui_settings.doubleClicked.connect(self.edit_tree_item)
self.current_script = None
self.probe_to_plot = None
# create models for tree structures, the models reflect the data
self.tree_dataset_model = QtGui.QStandardItemModel()
self.tree_dataset.setModel(self.tree_dataset_model)
self.tree_dataset_model.setHorizontalHeaderLabels(
['time', 'name (tag)', 'type (script)'])
# create models for tree structures, the models reflect the data
self.tree_gui_settings_model = QtGui.QStandardItemModel()
self.tree_gui_settings.setModel(self.tree_gui_settings_model)
self.tree_gui_settings_model.setHorizontalHeaderLabels(
['parameter', 'value'])
self.tree_scripts.header().setStretchLastSection(True)
def connect_controls():
# COMMENT_ME
# =============================================================
# ===== LINK WIDGETS TO FUNCTIONS =============================
# =============================================================
# link buttons to old_functions
self.btn_start_script.clicked.connect(self.btn_clicked)
self.btn_stop_script.clicked.connect(self.btn_clicked)
self.btn_skip_subscript.clicked.connect(self.btn_clicked)
self.btn_validate_script.clicked.connect(self.btn_clicked)
# self.btn_plot_script.clicked.connect(self.btn_clicked)
# self.btn_plot_probe.clicked.connect(self.btn_clicked)
self.btn_store_script_data.clicked.connect(self.btn_clicked)
# self.btn_plot_data.clicked.connect(self.btn_clicked)
self.btn_save_data.clicked.connect(self.btn_clicked)
self.btn_delete_data.clicked.connect(self.btn_clicked)
self.btn_save_gui.triggered.connect(self.btn_clicked)
self.btn_load_gui.triggered.connect(self.btn_clicked)
self.btn_about.triggered.connect(self.btn_clicked)
self.btn_exit.triggered.connect(self.close)
self.actionSave.triggered.connect(self.btn_clicked)
self.actionExport.triggered.connect(self.btn_clicked)
self.actionGo_to_pylabcontrol_GitHub_page.triggered.connect(
self.btn_clicked)
self.btn_load_instruments.clicked.connect(self.btn_clicked)
self.btn_load_scripts.clicked.connect(self.btn_clicked)
self.btn_load_probes.clicked.connect(self.btn_clicked)
# Helper function to make only column 1 editable
def onScriptParamClick(item, column):
tree = item.treeWidget()
if column == 1 and not isinstance(item.value, (Script, Instrument)) and not item.is_point():
# self.tree_scripts.editItem(item, column)
tree.editItem(item, column)
# tree structures
self.tree_scripts.itemClicked.connect(
lambda: onScriptParamClick(self.tree_scripts.currentItem(), self.tree_scripts.currentColumn()))
self.tree_scripts.itemChanged.connect(
lambda: self.update_parameters(self.tree_scripts))
self.tree_scripts.itemClicked.connect(self.btn_clicked)
# self.tree_scripts.installEventFilter(self)
# QtWidgets.QTreeWidget.installEventFilter(self)
self.tabWidget.currentChanged.connect(lambda: self.switch_tab())
self.tree_dataset.clicked.connect(lambda: self.btn_clicked())
self.tree_settings.itemClicked.connect(
lambda: onScriptParamClick(self.tree_settings.currentItem(), self.tree_settings.currentColumn()))
self.tree_settings.itemChanged.connect(
lambda: self.update_parameters(self.tree_settings))
self.tree_settings.itemExpanded.connect(
lambda: self.refresh_instruments())
# set the log_filename when checking loggin
self.chk_probe_log.toggled.connect(
lambda: self.set_probe_file_name(self.chk_probe_log.isChecked()))
self.chk_probe_plot.toggled.connect(self.btn_clicked)
self.chk_show_all.toggled.connect(self._show_hide_parameter)
self.create_figures()
# create a "delegate" --- an editor that uses our new Editor Factory when creating editors,
# and use that for tree_scripts
# needed to avoid rounding of numbers
delegate = QtWidgets.QStyledItemDelegate()
new_factory = CustomEditorFactory()
delegate.setItemEditorFactory(new_factory)
self.tree_scripts.setItemDelegate(delegate)
setup_trees()
connect_controls()
if filepath is None:
path_to_config = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir, 'save_config.json'))
if os.path.isfile(path_to_config) and os.access(path_to_config, os.R_OK):
print('path_to_config', path_to_config)
with open(path_to_config) as f:
config_data = json.load(f)
if 'last_save_path' in config_data.keys():
self.config_filepath = config_data['last_save_path']
self.log('Checking for previous save of GUI here: {0}'.format(
self.config_filepath))
else:
self.log('Starting with blank GUI; configuration files will be saved here: {0}'.format(
self._DEFAULT_CONFIG["gui_settings"]))
elif os.path.isfile(filepath) and os.access(filepath, os.R_OK):
self.config_filepath = filepath
elif not os.path.isfile(filepath):
self.log(
'Could not find file given to open --- starting with a blank GUI')
self.instruments = {}
self.scripts = {}
self.probes = {}
self.gui_settings = {'scripts_folder': '', 'data_folder': ''}
self.gui_settings_hidden = {'scripts_source_folder': ''}
self.load_config(self.config_filepath)
self.data_sets = {} # todo: load datasets from tmp folder
self.read_probes = ReadProbes(self.probes)
self.tabWidget.setCurrentIndex(0) # always show the script tab
# == create a thread for the scripts ==
self.script_thread = QThread()
# used to keep track of status updates, to block updates when they occur to often
self._last_progress_update = None
self.chk_show_all.setChecked(True)
self.actionSave.setShortcut(QtGui.QKeySequence.Save)
self.actionExport.setShortcut(self.tr('Ctrl+E'))
self.list_history.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
if self.config_filepath is None:
self.config_filepath = os.path.join(
self._DEFAULT_CONFIG["gui_settings"], 'gui.b26')
def closeEvent(self, event):
"""
things to be done when gui closes, like save the settings
"""
self.save_config(self.gui_settings['gui_settings'])
self.script_thread.quit()
self.read_probes.quit()
event.accept()
print('\n\n======================================================')
print('================= Closing B26 Python LAB =============')
print('======================================================\n\n')
def eventFilter(self, object, event):
"""
TEMPORARY / UNDER DEVELOPMENT
THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP
Args:
object:
event:
Returns:
"""
if (object is self.tree_scripts):
# print('XXXXXXX = event in scripts', event.type(),
# QtCore.QEvent.DragEnter, QtCore.QEvent.DragMove, QtCore.QEvent.DragLeave)
if (event.type() == QtCore.QEvent.ChildAdded):
item = self.tree_scripts.selectedItems()[0]
if not isinstance(item.value, Script):
print('ONLY SCRIPTS CAN BE DRAGGED')
return False
print(
('XXX ChildAdded', self.tree_scripts.selectedItems()[0].name))
# if event.mimeData().hasUrls():
# event.accept() # must accept the dragEnterEvent or else the dropEvent can't occur !!!
# print "accept"
# else:
# event.ignore()
# print "ignore"
if (event.type() == QtCore.QEvent.ChildRemoved):
print(
('XXX ChildRemoved', self.tree_scripts.selectedItems()[0].name))
if (event.type() == QtCore.QEvent.Drop):
print('XXX Drop')
# if event.mimeData().hasUrls(): # if file or link is dropped
# urlcount = len(event.mimeData().urls()) # count number of drops
# url = event.mimeData().urls()[0] # get first url
# object.setText(url.toString()) # assign first url to editline
# # event.accept() # doesnt appear to be needed
return False # lets the event continue to the edit
return False
def set_probe_file_name(self, checked):
"""
sets the filename to which the probe logging function will write
Args:
checked: boolean (True: opens file) (False: closes file)
"""
if checked:
file_name = os.path.join(self.gui_settings['probes_log_folder'], '{:s}_probes.csv'.format(
datetime.datetime.now().strftime('%y%m%d-%H_%M_%S')))
if os.path.isfile(file_name) == False:
self.probe_file = open(file_name, 'a')
new_values = self.read_probes.probes_values
header = ','.join(list(np.array([['{:s} ({:s})'.format(p, instr) for p in list(
p_dict.keys())] for instr, p_dict in new_values.items()]).flatten()))
self.probe_file.write('{:s}\n'.format(header))
else:
self.probe_file.close()
def switch_tab(self):
"""
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
"""
current_tab = str(self.tabWidget.tabText(
self.tabWidget.currentIndex()))
if self.current_script is None:
if current_tab == 'Probes':
self.read_probes.start()
self.read_probes.updateProgress.connect(self.update_probes)
else:
try:
self.read_probes.updateProgress.disconnect()
self.read_probes.quit()
except TypeError:
pass
if current_tab == 'Instruments':
self.refresh_instruments()
else:
self.log(
'updating probes / instruments disabled while script is running!')
def refresh_instruments(self):
"""
if self.tree_settings has been expanded, ask instruments for their actual values
"""
def list_access_nested_dict(dict, somelist):
"""
Allows one to use a list to access a nested dictionary, for example:
listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
Args:
dict:
somelist:
Returns:
"""
return reduce(operator.getitem, somelist, dict)
def update(item):
if item.isExpanded():
for index in range(item.childCount()):
child = item.child(index)
if child.childCount() == 0:
instrument, path_to_instrument = child.get_instrument()
path_to_instrument.reverse()
try: # check if item is in probes
value = instrument.read_probes(
path_to_instrument[-1])
except AssertionError: # if item not in probes, get value from settings instead
value = list_access_nested_dict(
instrument.settings, path_to_instrument)
child.value = value
else:
update(child)
# need to block signals during update so that tree.itemChanged doesn't fire and the gui doesn't try to
# reupdate the instruments to their current value
self.tree_settings.blockSignals(True)
for index in range(self.tree_settings.topLevelItemCount()):
instrument = self.tree_settings.topLevelItem(index)
update(instrument)
self.tree_settings.blockSignals(False)
def plot_clicked(self, mouse_event):
"""
gets activated when the user clicks on a plot
Args:
mouse_event:
"""
if isinstance(self.current_script, SelectPoints) and self.current_script.is_running:
if (not (mouse_event.xdata == None)):
if (mouse_event.button == 1):
pt = np.array([mouse_event.xdata, mouse_event.ydata])
self.current_script.toggle_NV(pt)
self.current_script.plot([self.matplotlibwidget_1.figure])
self.matplotlibwidget_1.draw()
item = self.tree_scripts.currentItem()
if item is not None:
if item.is_point():
# item_x = item.child(1)
item_x = item.child(0)
if mouse_event.xdata is not None:
self.tree_scripts.setCurrentItem(item_x)
item_x.value = float(mouse_event.xdata)
item_x.setText(1, '{:0.3f}'.format(
float(mouse_event.xdata)))
# item_y = item.child(0)
item_y = item.child(1)
if mouse_event.ydata is not None:
self.tree_scripts.setCurrentItem(item_y)
item_y.value = float(mouse_event.ydata)
item_y.setText(1, '{:0.3f}'.format(
float(mouse_event.ydata)))
# focus back on item
self.tree_scripts.setCurrentItem(item)
else:
if item.parent() is not None:
if item.parent().is_point():
if item == item.parent().child(1):
if mouse_event.xdata is not None:
item.setData(1, 2, float(mouse_event.xdata))
if item == item.parent().child(0):
if mouse_event.ydata is not None:
item.setData(1, 2, float(mouse_event.ydata))
def get_time(self):
"""
Returns: the current time as a formated string
"""
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
def log(self, msg):
"""
log function
Args:
msg: the text message to be logged
"""
time = self.get_time()
msg = "{:s}\t {:s}".format(time, msg)
self.history.append(msg)
self.history_model.insertRow(0, QtGui.QStandardItem(msg))
def create_figures(self):
"""
creates the maplotlib figures]
self.matplotlibwidget_1
self.matplotlibwidget_2
and toolbars
self.mpl_toolbar_1
self.mpl_toolbar_2
Returns:
"""
try:
self.horizontalLayout_14.removeWidget(self.matplotlibwidget_1)
self.matplotlibwidget_1.close()
except AttributeError:
pass
try:
self.horizontalLayout_15.removeWidget(self.matplotlibwidget_2)
self.matplotlibwidget_2.close()
except AttributeError:
pass
self.matplotlibwidget_2 = MatplotlibWidget(self.plot_2)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.matplotlibwidget_2.sizePolicy().hasHeightForWidth())
self.matplotlibwidget_2.setSizePolicy(sizePolicy)
self.matplotlibwidget_2.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget_2.setObjectName("matplotlibwidget_2")
self.horizontalLayout_16.addWidget(self.matplotlibwidget_2)
self.matplotlibwidget_1 = MatplotlibWidget(self.plot_1)
self.matplotlibwidget_1.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget_1.setObjectName("matplotlibwidget_1")
self.horizontalLayout_15.addWidget(self.matplotlibwidget_1)
self.matplotlibwidget_1.mpl_connect(
'button_press_event', self.plot_clicked)
self.matplotlibwidget_2.mpl_connect(
'button_press_event', self.plot_clicked)
# adds a toolbar to the plots
self.mpl_toolbar_1 = NavigationToolbar(
self.matplotlibwidget_1.canvas, self.toolbar_space_1)
self.mpl_toolbar_2 = NavigationToolbar(
self.matplotlibwidget_2.canvas, self.toolbar_space_2)
self.horizontalLayout_9.addWidget(self.mpl_toolbar_2)
self.horizontalLayout_14.addWidget(self.mpl_toolbar_1)
self.matplotlibwidget_1.figure.set_tight_layout(True)
self.matplotlibwidget_2.figure.set_tight_layout(True)
def load_scripts(self):
"""
opens file dialog to load scripts into gui
"""
# update scripts so that current settings do not get lost
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
self.update_script_from_item(script_item)
dialog = LoadDialog(elements_type="scripts", elements_old=self.scripts,
filename=self.gui_settings['scripts_folder'])
if dialog.exec_():
self.gui_settings['scripts_folder'] = str(
dialog.txt_probe_log_path.text())
scripts = dialog.get_values()
added_scripts = set(scripts.keys()) - set(self.scripts.keys())
removed_scripts = set(self.scripts.keys()) - set(scripts.keys())
if 'data_folder' in list(self.gui_settings.keys()) and os.path.exists(self.gui_settings['data_folder']):
data_folder_name = self.gui_settings['data_folder']
else:
data_folder_name = None
# create instances of new instruments/scripts
self.scripts, loaded_failed, self.instruments = Script.load_and_append(
script_dict={name: scripts[name] for name in added_scripts},
scripts=self.scripts,
instruments=self.instruments,
log_function=self.log,
data_path=data_folder_name,
raise_errors=False)
# delete instances of new instruments/scripts that have been deselected
for name in removed_scripts:
del self.scripts[name]
def btn_clicked(self):
"""
slot to which connect buttons
"""
sender = self.sender()
self.probe_to_plot = None
def start_button():
"""
starts the selected script
"""
item = self.tree_scripts.currentItem()
# BROKEN 20170109: repeatedly erases updates to gui
# self.expanded_items = []
# for index in range(self.tree_scripts.topLevelItemCount()):
# someitem = self.tree_scripts.topLevelItem(index)
# if someitem.isExpanded():
# self.expanded_items.append(someitem.name)
self.script_start_time = datetime.datetime.now()
if item is not None:
# get script and update settings from tree
self.running_item = item
script, path_to_script, script_item = item.get_script()
self.update_script_from_item(script_item)
self.log('starting {:s}'.format(script.name))
# put script onto script thread
print('================================================')
print(('===== starting {:s}'.format(script.name)))
print('================================================')
script_thread = self.script_thread
def move_to_worker_thread(script):
script.moveToThread(script_thread)
# move also the subscript to the worker thread
for subscript in list(script.scripts.values()):
move_to_worker_thread(subscript)
move_to_worker_thread(script)
# connect update signal of script to update slot of gui
script.updateProgress.connect(self.update_status)
# causes the script to start upon starting the thread
script_thread.started.connect(script.run)
# clean up. quit thread after script is finished
script.finished.connect(script_thread.quit)
# connect finished signal of script to finished slot of gui
script.finished.connect(self.script_finished)
# start thread, i.e. script
script_thread.start()
self.current_script = script
self.btn_start_script.setEnabled(False)
# self.tabWidget.setEnabled(False)
if isinstance(self.current_script, ScriptIterator):
self.btn_skip_subscript.setEnabled(True)
else:
self.log('User tried to run a script without one selected.')
def stop_button():
"""
stops the current script
"""
if self.current_script is not None and self.current_script.is_running:
self.current_script.stop()
else:
self.log(
'User clicked stop, but there isn\'t anything running...this is awkward. Re-enabling start button anyway.')
self.btn_start_script.setEnabled(True)
def skip_button():
"""
Skips to the next script if the current script is a Iterator script
"""
if self.current_script is not None and self.current_script.is_running and isinstance(self.current_script,
ScriptIterator):
self.current_script.skip_next()
else:
self.log(
'User clicked skip, but there isn\'t a iterator script running...this is awkward.')
def validate_button():
"""
validates the selected script
"""
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, script_item = item.get_script()
self.update_script_from_item(script_item)
script.is_valid()
script.plot_validate(
[self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
def store_script_data():
"""
updates the internal self.data_sets with selected script and updates tree self.fill_dataset_tree
"""
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, _ = item.get_script()
script_copy = script.duplicate()
time_tag = script.start_time.strftime('%y%m%d-%H_%M_%S')
self.data_sets.update({time_tag: script_copy})
self.fill_dataset_tree(self.tree_dataset, self.data_sets)
def save_data():
""""
saves the selected script (where is contained in the script itself)
"""
indecies = self.tree_dataset.selectedIndexes()
model = indecies[0].model()
rows = list(set([index.row()for index in indecies]))
for row in rows:
time_tag = str(model.itemFromIndex(model.index(row, 0)).text())
name_tag = str(model.itemFromIndex(model.index(row, 1)).text())
path = self.gui_settings['data_folder']
script = self.data_sets[time_tag]
script.update({'tag': name_tag, 'path': path})
script.save_data()
script.save_image_to_disk()
script.save_b26()
script.save_log()
def delete_data():
"""
deletes the data from the dataset
Returns:
"""
indecies = self.tree_dataset.selectedIndexes()
model = indecies[0].model()
rows = list(set([index.row()for index in indecies]))
for row in rows:
time_tag = str(model.itemFromIndex(model.index(row, 0)).text())
del self.data_sets[time_tag]
model.removeRows(row, 1)
def load_probes():
"""
opens file dialog to load probes into gui
"""
# if the probe has never been started it can not be disconnected so we catch that error
try:
self.read_probes.updateProgress.disconnect()
self.read_probes.quit()
# self.read_probes.stop()
except RuntimeError:
pass
dialog = LoadDialogProbes(
probes_old=self.probes, filename=self.gui_settings['probes_folder'])
if dialog.exec_():
self.gui_settings['probes_folder'] = str(
dialog.txt_probe_log_path.text())
probes = dialog.get_values()
added_instruments = list(
set(probes.keys()) - set(self.probes.keys()))
removed_instruments = list(
set(self.probes.keys()) - set(probes.keys()))
# create instances of new probes
self.probes, loaded_failed, self.instruments = Probe.load_and_append(
probe_dict=probes,
probes={},
instruments=self.instruments)
if not loaded_failed:
print(('WARNING following probes could not be loaded',
loaded_failed, len(loaded_failed)))
# restart the readprobes thread
del self.read_probes
self.read_probes = ReadProbes(self.probes)
self.read_probes.start()
self.tree_probes.clear() # clear tree because the probe might have changed
self.read_probes.updateProgress.connect(self.update_probes)
self.tree_probes.expandAll()
def load_instruments():
"""
opens file dialog to load instruments into gui
"""
if 'instrument_folder' in self.gui_settings:
dialog = LoadDialog(elements_type="instruments", elements_old=self.instruments,
filename=self.gui_settings['instrument_folder'])
else:
dialog = LoadDialog(elements_type="instruments",
elements_old=self.instruments)
if dialog.exec_():
self.gui_settings['instrument_folder'] = str(
dialog.txt_probe_log_path.text())
instruments = dialog.get_values()
added_instruments = set(
instruments.keys()) - set(self.instruments.keys())
removed_instruments = set(
self.instruments.keys()) - set(instruments.keys())
# print('added_instruments', {name: instruments[name] for name in added_instruments})
# create instances of new instruments
self.instruments, loaded_failed = Instrument.load_and_append(
{name: instruments[name] for name in added_instruments}, self.instruments)
if len(loaded_failed) > 0:
print(
('WARNING following instrument could not be loaded', loaded_failed))
# delete instances of new instruments/scripts that have been deselected
for name in removed_instruments:
del self.instruments[name]
def plot_data(sender):
"""
plots the data of the selected script
"""
if sender == self.tree_dataset:
index = self.tree_dataset.selectedIndexes()[0]
model = index.model()
time_tag = str(model.itemFromIndex(
model.index(index.row(), 0)).text())
script = self.data_sets[time_tag]
self.plot_script(script)
elif sender == self.tree_scripts:
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, _ = item.get_script()
# only plot if script has been selected but not if a parameter has been selected
if path_to_script == []:
self.plot_script(script)
def save():
self.save_config(self.gui_settings['gui_settings'])
if sender is self.btn_start_script:
start_button()
elif sender is self.btn_stop_script:
stop_button()
elif sender is self.btn_skip_subscript:
skip_button()
elif sender is self.btn_validate_script:
validate_button()
elif sender in (self.tree_dataset, self.tree_scripts):
plot_data(sender)
elif sender is self.btn_store_script_data:
store_script_data()
elif sender is self.btn_save_data:
save_data()
elif sender is self.btn_delete_data:
delete_data()
# elif sender is self.btn_plot_probe:
elif sender is self.chk_probe_plot:
if self.chk_probe_plot.isChecked():
item = self.tree_probes.currentItem()
if item is not None:
if item.name in self.probes:
# selected item is an instrument not a probe, maybe plot all the probes...
self.log(
'Can\'t plot, No probe selected. Select probe and try again!')
else:
instrument = item.parent().name
self.probe_to_plot = self.probes[instrument][item.name]
else:
self.log(
'Can\'t plot, No probe selected. Select probe and try again!')
else:
self.probe_to_plot = None
elif sender is self.btn_save_gui:
# get filename
filepath, _ = QtWidgets.QFileDialog.getSaveFileName(
self, 'Save gui settings to file', self.config_filepath, filter='*.b26')
# in case the user cancels during the prompt, check that the filepath is not an empty string
if filepath:
filename, file_extension = os.path.splitext(filepath)
if file_extension != '.b26':
filepath = filename + ".b26"
filepath = os.path.normpath(filepath)
self.save_config(filepath)
self.gui_settings['gui_settings'] = filepath
self.refresh_tree(self.tree_gui_settings, self.gui_settings)
elif sender is self.btn_load_gui:
# get filename
fname = QtWidgets.QFileDialog.getOpenFileName(
self, 'Load gui settings from file', self.gui_settings['data_folder'], filter='*.b26')
self.load_config(fname[0])
elif sender is self.btn_about:
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText(
"pylabcontrol: Laboratory Equipment Control for Scientific Experiments")
msg.setInformativeText("This software was developed by Arthur Safira, Jan Gieseler, and Aaron Kabcenell at"
"Harvard University. It is licensed under the LPGL licence. For more information,"
"visit the GitHub page at github.com/LISE-B26/pylabcontrol .")
msg.setWindowTitle("About")
# msg.setDetailedText("some stuff")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
# msg.buttonClicked.connect(msgbtn)
retval = msg.exec_()
# elif (sender is self.btn_load_instruments) or (sender is self.btn_load_scripts):
elif sender in (self.btn_load_instruments, self.btn_load_scripts, self.btn_load_probes):
if sender is self.btn_load_instruments:
load_instruments()
elif sender is self.btn_load_scripts:
self.load_scripts()
elif sender is self.btn_load_probes:
load_probes()
# refresh trees
self.refresh_tree(self.tree_scripts, self.scripts)
self.refresh_tree(self.tree_settings, self.instruments)
elif sender is self.actionSave:
self.save_config(self.gui_settings['gui_settings'])
elif sender is self.actionGo_to_pylabcontrol_GitHub_page:
webbrowser.open('https://github.com/LISE-B26/pylabcontrol')
elif sender is self.actionExport:
export_dialog = ExportDialog()
export_dialog.target_path.setText(
self.gui_settings['scripts_folder'])
if self.gui_settings_hidden['scripts_source_folder']:
export_dialog.source_path.setText(
self.gui_settings_hidden['scripts_source_folder'])
if export_dialog.source_path.text():
export_dialog.reset_avaliable(export_dialog.source_path.text())
# exec_() blocks while export dialog is used, subsequent code will run on dialog closing
export_dialog.exec_()
self.gui_settings.update(
{'scripts_folder': export_dialog.target_path.text()})
self.fill_treeview(self.tree_gui_settings, self.gui_settings)
self.gui_settings_hidden.update(
{'scripts_source_folder': export_dialog.source_path.text()})
def _show_hide_parameter(self):
"""
shows or hides parameters
Returns:
"""
assert isinstance(self.sender(
), QtWidgets.QCheckBox), 'this function should be connected to a check box'
if self.sender().isChecked():
self.tree_scripts.setColumnHidden(2, False)
iterator = QtWidgets.QTreeWidgetItemIterator(
self.tree_scripts, QtWidgets.QTreeWidgetItemIterator.Hidden)
item = iterator.value()
while item:
item.setHidden(False)
item = iterator.value()
iterator += 1
else:
self.tree_scripts.setColumnHidden(2, True)
iterator = QtWidgets.QTreeWidgetItemIterator(
self.tree_scripts, QtWidgets.QTreeWidgetItemIterator.NotHidden)
item = iterator.value()
while item:
if not item.visible:
item.setHidden(True)
item = iterator.value()
iterator += 1
self.tree_scripts.setColumnWidth(0, 200)
self.tree_scripts.setColumnWidth(1, 400)
self.tree_scripts.setColumnWidth(2, 50)
def update_parameters(self, treeWidget):
"""
updates the internal dictionaries for scripts and instruments with values from the respective trees
treeWidget: the tree from which to update
"""
if treeWidget == self.tree_settings:
item = treeWidget.currentItem()
instrument, path_to_instrument = item.get_instrument()
# build nested dictionary to update instrument
dictator = item.value
for element in path_to_instrument:
dictator = {element: dictator}
# get old value from instrument
old_value = instrument.settings
path_to_instrument.reverse()
for element in path_to_instrument:
old_value = old_value[element]
# send new value from tree to instrument
instrument.update(dictator)
new_value = item.value
if new_value is not old_value:
msg = "changed parameter {:s} from {:s} to {:s} on {:s}".format(item.name, str(old_value),
str(new_value), instrument.name)
else:
msg = "did not change parameter {:s} on {:s}".format(
item.name, instrument.name)
self.log(msg)
elif treeWidget == self.tree_scripts:
item = treeWidget.currentItem()
script, path_to_script, _ = item.get_script()
# check if changes value is from an instrument
instrument, path_to_instrument = item.get_instrument()
if instrument is not None:
new_value = item.value
msg = "changed parameter {:s} to {:s} in {:s}".format(item.name,
str(new_value),
script.name)
else:
new_value = item.value
msg = "changed parameter {:s} to {:s} in {:s}".format(item.name,
str(new_value),
script.name)
self.log(msg)
def plot_script(self, script):
"""
Calls the plot function of the script, and redraws both plots
Args:
script: script to be plotted
"""
script.plot([self.matplotlibwidget_1.figure,
self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
@pyqtSlot(int)
def update_status(self, progress):
"""
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
"""
# interval at which the gui will be updated, if requests come in faster than they will be ignored
update_interval = 0.2
now = datetime.datetime.now()
if not self._last_progress_update is None and now-self._last_progress_update < datetime.timedelta(seconds=update_interval):
return
self._last_progress_update = now
self.progressBar.setValue(progress)
script = self.current_script
# Estimate remaining time if progress has been made
if progress:
remaining_time = str(datetime.timedelta(
seconds=script.remaining_time.seconds))
self.lbl_time_estimate.setText(
'time remaining: {:s}'.format(remaining_time))
if script is not str(self.tabWidget.tabText(self.tabWidget.currentIndex())).lower() in ['scripts', 'instruments']:
self.plot_script(script)
@pyqtSlot()
def script_finished(self):
"""
waits for the script to emit the script_finshed signal
"""
script = self.current_script
script.updateProgress.disconnect(self.update_status)
self.script_thread.started.disconnect()
script.finished.disconnect()
self.current_script = None
self.plot_script(script)
self.progressBar.setValue(100)
self.btn_start_script.setEnabled(True)
self.btn_skip_subscript.setEnabled(False)
def plot_script_validate(self, script):
"""
checks the plottype of the script and plots it accordingly
Args:
script: script to be plotted
"""
script.plot_validate(
[self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
def update_probes(self, progress):
"""
update the probe tree
"""
new_values = self.read_probes.probes_values
probe_count = len(self.read_probes.probes)
if probe_count > self.tree_probes.topLevelItemCount():
# when run for the first time, there are no probes in the tree, so we have to fill it first
self.fill_treewidget(self.tree_probes, new_values)
else:
for x in range(probe_count):
topLvlItem = self.tree_probes.topLevelItem(x)
for child_id in range(topLvlItem.childCount()):
child = topLvlItem.child(child_id)
child.value = new_values[topLvlItem.name][child.name]
child.setText(1, str(child.value))
if self.probe_to_plot is not None:
self.probe_to_plot.plot(self.matplotlibwidget_1.axes)
self.matplotlibwidget_1.draw()
if self.chk_probe_log.isChecked():
data = ','.join(list(np.array([[str(p) for p in list(
p_dict.values())] for instr, p_dict in new_values.items()]).flatten()))
self.probe_file.write('{:s}\n'.format(data))
def update_script_from_item(self, item):
"""
updates the script based on the information provided in item
Args:
script: script to be updated
item: B26QTreeItem that contains the new settings of the script
"""
script, path_to_script, script_item = item.get_script()
# build dictionary
# get full information from script
# there is only one item in the dictionary
dictator = list(script_item.to_dict().values())[0]
for instrument in list(script.instruments.keys()):
# update instrument
script.instruments[instrument]['settings'] = dictator[instrument]['settings']
# remove instrument
del dictator[instrument]
for sub_script_name in list(script.scripts.keys()):
sub_script_item = script_item.get_subscript(sub_script_name)
self.update_script_from_item(sub_script_item)
del dictator[sub_script_name]
script.update(dictator)
# update datefolder path
script.data_path = self.gui_settings['data_folder']
def fill_treewidget(self, tree, parameters):
"""
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Returns:
"""
tree.clear()
assert isinstance(parameters, (dict, Parameter))
for key, value in parameters.items():
if isinstance(value, Parameter):
B26QTreeItem(tree, key, value,
parameters.valid_values[key], parameters.info[key])
else:
B26QTreeItem(tree, key, value, type(value), '')
def fill_treeview(self, tree, input_dict):
"""
fills a treeview with nested parameters
Args:
tree: QtWidgets.QTreeView
parameters: dictionary or Parameter object
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
def add_element(item, key, value):
child_name = QtWidgets.QStandardItem(key)
if isinstance(value, dict):
for key_child, value_child in value.items():
add_element(child_name, key_child, value_child)
item.appendRow(child_name)
else:
child_value = QtWidgets.QStandardItem(str(value))
item.appendRow([child_name, child_value])
for index, (key, value) in enumerate(input_dict.items()):
if isinstance(value, dict):
item = QtWidgets.QStandardItem(key)
for sub_key, sub_value in value.items():
add_element(item, sub_key, sub_value)
tree.model().appendRow(item)
elif isinstance(value, str):
item = QtGui.QStandardItem(key)
item_value = QtGui.QStandardItem(value)
item_value.setEditable(True)
item_value.setSelectable(True)
tree.model().appendRow([item, item_value])
def edit_tree_item(self):
"""
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath
this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
"""
def open_path_dialog_folder(path):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtWidgets.QFileDialog()
dialog.setFileMode(QtWidgets.QFileDialog.Directory)
dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
path = dialog.getExistingDirectory(self, 'Select a folder:', path)
return path
tree = self.sender()
if tree == self.tree_gui_settings:
index = tree.selectedIndexes()[0]
model = index.model()
if index.column() == 1:
path = model.itemFromIndex(index).text()
key = str(model.itemFromIndex(
model.index(index.row(), 0)).text())
if (key == 'gui_settings'):
path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, caption='Select a file:', directory=path, filter='*.b26')
if path:
name, extension = os.path.splitext(path)
if extension != '.b26':
path = name + ".b26"
else:
path = str(open_path_dialog_folder(path))
if path != "":
self.gui_settings.update(
{key: str(os.path.normpath(path))})
self.fill_treeview(tree, self.gui_settings)
def refresh_tree(self, tree, items):
"""
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones
"""
if tree == self.tree_scripts or tree == self.tree_settings:
tree.itemChanged.disconnect()
self.fill_treewidget(tree, items)
tree.itemChanged.connect(lambda: self.update_parameters(tree))
elif tree == self.tree_gui_settings:
self.fill_treeview(tree, items)
def fill_dataset_tree(self, tree, data_sets):
"""
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
for index, (time, script) in enumerate(data_sets.items()):
name = script.settings['tag']
type = script.name
item_time = QtGui.QStandardItem(str(time))
item_name = QtGui.QStandardItem(str(name))
item_type = QtGui.QStandardItem(str(type))
item_time.setSelectable(False)
item_time.setEditable(False)
item_type.setSelectable(False)
item_type.setEditable(False)
tree.model().appendRow([item_time, item_name, item_type])
def load_config(self, filepath=None):
"""
checks if the file is a valid config file
Args:
filepath:
"""
# load config or default if invalid
def load_settings(filepath):
"""
loads a old_gui settings file (a json dictionary)
- path_to_file: path to file that contains the dictionary
Returns:
- instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
- scripts: depth 1 dictionary where keys are script names and values are instances of scripts
- probes: depth 1 dictionary where to be decided....?
"""
instruments_loaded = {}
probes_loaded = {}
scripts_loaded = {}
if filepath and os.path.isfile(filepath):
in_data = load_b26_file(filepath)
instruments = in_data['instruments'] if 'instruments' in in_data else {
}
scripts = in_data['scripts'] if 'scripts' in in_data else {}
probes = in_data['probes'] if 'probes' in in_data else {}
try:
instruments_loaded, failed = Instrument.load_and_append(
instruments)
if len(failed) > 0:
print(
('WARNING! Following instruments could not be loaded: ', failed))
scripts_loaded, failed, instruments_loaded = Script.load_and_append(
script_dict=scripts,
instruments=instruments_loaded,
log_function=self.log,
data_path=self.gui_settings['data_folder'])
if len(failed) > 0:
print(
('WARNING! Following scripts could not be loaded: ', failed))
probes_loaded, failed, instruments_loadeds = Probe.load_and_append(
probe_dict=probes,
probes=probes_loaded,
instruments=instruments_loaded)
self.log('Successfully loaded from previous save.')
except ImportError:
self.log('Could not load instruments or scripts from file.')
self.log('Opening with blank GUI.')
return instruments_loaded, scripts_loaded, probes_loaded
config = None
try:
config = load_b26_file(filepath)
config_settings = config['gui_settings']
if config_settings['gui_settings'] != filepath:
print((
'WARNING path to settings file ({:s}) in config file is different from path of settings file ({:s})'.format(
config_settings['gui_settings'], filepath)))
config_settings['gui_settings'] = filepath
except Exception as e:
if filepath:
self.log(
'The filepath was invalid --- could not load settings. Loading blank GUI.')
config_settings = self._DEFAULT_CONFIG
for x in self._DEFAULT_CONFIG.keys():
if x in config_settings:
if not os.path.exists(config_settings[x]):
try:
os.makedirs(config_settings[x])
except Exception:
config_settings[x] = self._DEFAULT_CONFIG[x]
os.makedirs(config_settings[x])
print(('WARNING: failed validating or creating path: set to default path'.format(
config_settings[x])))
else:
config_settings[x] = self._DEFAULT_CONFIG[x]
os.makedirs(config_settings[x])
print(('WARNING: path {:s} not specified set to default {:s}'.format(
x, config_settings[x])))
# check if file_name is a valid filename
if filepath is not None and os.path.exists(os.path.dirname(filepath)):
config_settings['gui_settings'] = filepath
self.gui_settings = config_settings
if (config):
self.gui_settings_hidden = config['gui_settings_hidden']
else:
self.gui_settings_hidden['script_source_folder'] = ''
self.instruments, self.scripts, self.probes = load_settings(filepath)
self.refresh_tree(self.tree_gui_settings, self.gui_settings)
self.refresh_tree(self.tree_scripts, self.scripts)
self.refresh_tree(self.tree_settings, self.instruments)
self._hide_parameters(filepath)
def _hide_parameters(self, file_name):
"""
hide the parameters that had been hidden
Args:
file_name: config file that has the information about which parameters are hidden
"""
try:
in_data = load_b26_file(file_name)
except:
in_data = {}
def set_item_visible(item, is_visible):
if isinstance(is_visible, dict):
for child_id in range(item.childCount()):
child = item.child(child_id)
if child.name in is_visible:
set_item_visible(child, is_visible[child.name])
else:
item.visible = is_visible
if "scripts_hidden_parameters" in in_data:
# consistency check
if len(list(in_data["scripts_hidden_parameters"].keys())) == self.tree_scripts.topLevelItemCount():
for index in range(self.tree_scripts.topLevelItemCount()):
item = self.tree_scripts.topLevelItem(index)
# if item.name in in_data["scripts_hidden_parameters"]:
set_item_visible(
item, in_data["scripts_hidden_parameters"][item.name])
else:
print(
'WARNING: settings for hiding parameters does\'t seem to match other settings')
# else:
# print('WARNING: no settings for hiding parameters all set to default')
def save_config(self, filepath):
"""
saves gui configuration to out_file_name
Args:
filepath: name of file
"""
def get_hidden_parameter(item):
num_sub_elements = item.childCount()
if num_sub_elements == 0:
dictator = {item.name: item.visible}
else:
dictator = {item.name: {}}
for child_id in range(num_sub_elements):
dictator[item.name].update(
get_hidden_parameter(item.child(child_id)))
return dictator
try:
filepath = str(filepath)
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
# build a dictionary for the configuration of the hidden parameters
dictator = {}
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
dictator.update(get_hidden_parameter(script_item))
dictator = {"gui_settings": self.gui_settings, "gui_settings_hidden":
self.gui_settings_hidden, "scripts_hidden_parameters": dictator}
# update the internal dictionaries from the trees in the gui
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
self.update_script_from_item(script_item)
dictator.update({'instruments': {}, 'scripts': {}, 'probes': {}})
for instrument in self.instruments.values():
dictator['instruments'].update(instrument.to_dict())
for script in self.scripts.values():
dictator['scripts'].update(script.to_dict())
for instrument, probe_dict in self.probes.items():
dictator['probes'].update(
{instrument: ','.join(list(probe_dict.keys()))})
with open(filepath, 'w') as outfile:
json.dump(dictator, outfile, indent=4)
save_config_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir, 'save_config.json'))
if os.path.isfile(save_config_path) and os.access(save_config_path, os.R_OK):
with open(save_config_path, 'w') as outfile:
json.dump({'last_save_path': filepath}, outfile, indent=4)
else:
with io.open(save_config_path, 'w') as save_config_file:
save_config_file.write(json.dumps(
{'last_save_path': filepath}))
self.log('Saved GUI configuration (location: {0}'.format(filepath))
except Exception:
msg = QtWidgets.QMessageBox()
msg.setText(
"Saving failed. Please use 'save as' to define a valid path for the gui.")
msg.exec_()
def save_dataset(self, out_file_name):
"""
saves current dataset to out_file_name
Args:
out_file_name: name of file
"""
for time_tag, script in self.data_sets.items():
script.save(os.path.join(out_file_name,
'{:s}.b26s'.format(time_tag)))
|
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, filepath=None):
'''
MainWindow(intruments, scripts, probes)
- intruments: depth 1 dictionary where keys are instrument names and keys are instrument classes
- scripts: depth 1 dictionary where keys are script names and keys are script classes
- probes: depth 1 dictionary where to be decided....?
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
'''
pass
def setup_trees():
pass
def connect_controls():
pass
def onScriptParamClick(item, column):
pass
def closeEvent(self, event):
'''
things to be done when gui closes, like save the settings
'''
pass
def eventFilter(self, object, event):
'''
TEMPORARY / UNDER DEVELOPMENT
THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP
Args:
object:
event:
Returns:
'''
pass
def set_probe_file_name(self, checked):
'''
sets the filename to which the probe logging function will write
Args:
checked: boolean (True: opens file) (False: closes file)
'''
pass
def switch_tab(self):
'''
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
'''
pass
def refresh_instruments(self):
'''
if self.tree_settings has been expanded, ask instruments for their actual values
'''
pass
def list_access_nested_dict(dict, somelist):
'''
Allows one to use a list to access a nested dictionary, for example:
listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
Args:
dict:
somelist:
Returns:
'''
pass
def update(item):
pass
def plot_clicked(self, mouse_event):
'''
gets activated when the user clicks on a plot
Args:
mouse_event:
'''
pass
def get_time(self):
'''
Returns: the current time as a formated string
'''
pass
def log(self, msg):
'''
log function
Args:
msg: the text message to be logged
'''
pass
def create_figures(self):
'''
creates the maplotlib figures]
self.matplotlibwidget_1
self.matplotlibwidget_2
and toolbars
self.mpl_toolbar_1
self.mpl_toolbar_2
Returns:
'''
pass
def load_scripts(self):
'''
opens file dialog to load scripts into gui
'''
pass
def btn_clicked(self):
'''
slot to which connect buttons
'''
pass
def start_button():
'''
starts the selected script
'''
pass
def move_to_worker_thread(script):
pass
def stop_button():
'''
stops the current script
'''
pass
def skip_button():
'''
Skips to the next script if the current script is a Iterator script
'''
pass
def validate_button():
'''
validates the selected script
'''
pass
def store_script_data():
'''
updates the internal self.data_sets with selected script and updates tree self.fill_dataset_tree
'''
pass
def save_data():
'''"
saves the selected script (where is contained in the script itself)
'''
pass
def delete_data():
'''
deletes the data from the dataset
Returns:
'''
pass
def load_probes():
'''
opens file dialog to load probes into gui
'''
pass
def load_instruments():
'''
opens file dialog to load instruments into gui
'''
pass
def plot_data(sender):
'''
plots the data of the selected script
'''
pass
def save_data():
pass
def _show_hide_parameter(self):
'''
shows or hides parameters
Returns:
'''
pass
def update_parameters(self, treeWidget):
'''
updates the internal dictionaries for scripts and instruments with values from the respective trees
treeWidget: the tree from which to update
'''
pass
def plot_script(self, script):
'''
Calls the plot function of the script, and redraws both plots
Args:
script: script to be plotted
'''
pass
@pyqtSlot(int)
def update_status(self, progress):
'''
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
'''
pass
@pyqtSlot()
def script_finished(self):
'''
waits for the script to emit the script_finshed signal
'''
pass
def plot_script_validate(self, script):
'''
checks the plottype of the script and plots it accordingly
Args:
script: script to be plotted
'''
pass
def update_probes(self, progress):
'''
update the probe tree
'''
pass
def update_script_from_item(self, item):
'''
updates the script based on the information provided in item
Args:
script: script to be updated
item: B26QTreeItem that contains the new settings of the script
'''
pass
def fill_treewidget(self, tree, parameters):
'''
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Returns:
'''
pass
def fill_treeview(self, tree, input_dict):
'''
fills a treeview with nested parameters
Args:
tree: QtWidgets.QTreeView
parameters: dictionary or Parameter object
Returns:
'''
pass
def add_element(item, key, value):
pass
def edit_tree_item(self):
'''
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath
this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
'''
pass
def open_path_dialog_folder(path):
'''
opens a file dialog to get the path to a file and
'''
pass
def refresh_tree(self, tree, items):
'''
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones
'''
pass
def fill_dataset_tree(self, tree, data_sets):
'''
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
'''
pass
def load_config(self, filepath=None):
'''
checks if the file is a valid config file
Args:
filepath:
'''
pass
def load_settings(filepath):
'''
loads a old_gui settings file (a json dictionary)
- path_to_file: path to file that contains the dictionary
Returns:
- instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
- scripts: depth 1 dictionary where keys are script names and values are instances of scripts
- probes: depth 1 dictionary where to be decided....?
'''
pass
def _hide_parameters(self, file_name):
'''
hide the parameters that had been hidden
Args:
file_name: config file that has the information about which parameters are hidden
'''
pass
def set_item_visible(item, is_visible):
pass
def save_config(self, filepath):
'''
saves gui configuration to out_file_name
Args:
filepath: name of file
'''
pass
def get_hidden_parameter(item):
pass
def save_dataset(self, out_file_name):
'''
saves current dataset to out_file_name
Args:
out_file_name: name of file
'''
pass
| 54 | 42 | 34 | 6 | 21 | 8 | 4 | 0.37 | 2 | 29 | 12 | 0 | 29 | 17 | 29 | 29 | 1,380 | 269 | 819 | 234 | 765 | 305 | 726 | 228 | 674 | 27 | 1 | 6 | 210 |
144,555 |
LISE-B26/pylabcontrol
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/gui/qt_b26_gui.py
|
gui.qt_b26_gui.ControlMainWindow
|
class ControlMainWindow(QMainWindow, Ui_MainWindow):
# application_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# application_path = os.path.dirname(application_path) # go one level lower
application_path = os.path.abspath(os.path.curdir)
_DEFAULT_CONFIG = {
# "tmp_folder": "../../b26_tmp",
"data_folder": os.path.join(application_path, "user_data", "data"),
"probes_folder": os.path.join(application_path, "user_data", "probes_auto_generated"),
"instrument_folder": os.path.join(application_path, "user_data", "instruments_auto_generated"),
"scripts_folder": os.path.join(application_path, "user_data", "scripts_auto_generated"),
"probes_log_folder": os.path.join(application_path, "user_data", "b26_tmp"),
"settings_file": os.path.join(application_path, "user_data", "pythonlab_config")
}
startup_msg = '\n\n\
======================================================\n\
=============== Starting B26 Python LAB =============\n\
======================================================\n\n'
def __init__(self, filename=None):
"""
MainWindow(intruments, scripts, probes)
- intruments: depth 1 dictionary where keys are instrument names and keys are instrument classes
- scripts: depth 1 dictionary where keys are script names and keys are script classes
- probes: depth 1 dictionary where to be decided....?
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
"""
print((self.startup_msg))
self.config_filename = None
super(ControlMainWindow, self).__init__()
self.setupUi(self)
def setup_trees():
# COMMENT_ME
# define data container
self.history = deque(maxlen=500) # history of executed commands
self.history_model = QtGui.QStandardItemModel(self.list_history)
self.list_history.setModel(self.history_model)
self.list_history.show()
self.tree_scripts.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_probes.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_settings.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_gui_settings.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self.tree_gui_settings.doubleClicked.connect(self.edit_tree_item)
self.current_script = None
self.probe_to_plot = None
# create models for tree structures, the models reflect the data
self.tree_dataset_model = QtGui.QStandardItemModel()
self.tree_dataset.setModel(self.tree_dataset_model)
self.tree_dataset_model.setHorizontalHeaderLabels(
['time', 'name (tag)', 'type (script)'])
# create models for tree structures, the models reflect the data
self.tree_gui_settings_model = QtGui.QStandardItemModel()
self.tree_gui_settings.setModel(self.tree_gui_settings_model)
self.tree_gui_settings_model.setHorizontalHeaderLabels(
['parameter', 'value'])
self.tree_scripts.header().setStretchLastSection(True)
def connect_controls():
# COMMENT_ME
# =============================================================
# ===== LINK WIDGETS TO FUNCTIONS =============================
# =============================================================
# link buttons to old_functions
self.btn_start_script.clicked.connect(self.btn_clicked)
self.btn_stop_script.clicked.connect(self.btn_clicked)
self.btn_skip_subscript.clicked.connect(self.btn_clicked)
self.btn_validate_script.clicked.connect(self.btn_clicked)
# self.btn_plot_script.clicked.connect(self.btn_clicked)
# self.btn_plot_probe.clicked.connect(self.btn_clicked)
self.btn_store_script_data.clicked.connect(self.btn_clicked)
# self.btn_plot_data.clicked.connect(self.btn_clicked)
self.btn_save_data.clicked.connect(self.btn_clicked)
self.btn_delete_data.clicked.connect(self.btn_clicked)
self.btn_save_gui.triggered.connect(self.btn_clicked)
self.btn_load_gui.triggered.connect(self.btn_clicked)
self.btn_about.triggered.connect(self.btn_clicked)
self.btn_exit.triggered.connect(self.close)
self.actionSave.triggered.connect(self.btn_clicked)
self.actionGo_to_pylabcontrol_GitHub_page.triggered.connect(
self.btn_clicked)
self.btn_load_instruments.clicked.connect(self.btn_clicked)
self.btn_load_scripts.clicked.connect(self.btn_clicked)
self.btn_load_probes.clicked.connect(self.btn_clicked)
# Helper function to make only column 1 editable
def onScriptParamClick(item, column):
tree = item.treeWidget()
if column == 1 and not isinstance(item.value, (Script, Instrument)) and not item.is_point():
# self.tree_scripts.editItem(item, column)
tree.editItem(item, column)
# tree structures
self.tree_scripts.itemClicked.connect(
lambda: onScriptParamClick(self.tree_scripts.currentItem(), self.tree_scripts.currentColumn()))
self.tree_scripts.itemChanged.connect(
lambda: self.update_parameters(self.tree_scripts))
self.tree_scripts.itemClicked.connect(self.btn_clicked)
# self.tree_scripts.installEventFilter(self)
# QtWidgets.QTreeWidget.installEventFilter(self)
self.tabWidget.currentChanged.connect(lambda: self.switch_tab())
self.tree_dataset.clicked.connect(lambda: self.btn_clicked())
self.tree_settings.itemClicked.connect(
lambda: onScriptParamClick(self.tree_settings.currentItem(), self.tree_settings.currentColumn()))
self.tree_settings.itemChanged.connect(
lambda: self.update_parameters(self.tree_settings))
self.tree_settings.itemExpanded.connect(
lambda: self.refresh_instruments())
# set the log_filename when checking loggin
self.chk_probe_log.toggled.connect(
lambda: self.set_probe_file_name(self.chk_probe_log.isChecked()))
self.chk_probe_plot.toggled.connect(self.btn_clicked)
self.chk_show_all.toggled.connect(self._show_hide_parameter)
self.create_figures()
# create a "delegate" --- an editor that uses our new Editor Factory when creating editors,
# and use that for tree_scripts
# needed to avoid rounding of numbers
delegate = QtWidgets.QStyledItemDelegate()
new_factory = CustomEditorFactory()
delegate.setItemEditorFactory(new_factory)
self.tree_scripts.setItemDelegate(delegate)
setup_trees()
connect_controls()
if not os.path.exists(filename):
dialog_dir = ''
# set path to home path
for x in ['HOME', 'HOMEPATH']:
if x in os.environ:
dialog_dir = os.environ[x]
# set to path of requested file
if os.path.exists(os.path.dirname(filename)):
dialog_dir = filename
# we use the save dialog here so that we can also create a new file (the default config)
# however, as a consequence if the user selects a file that already exists, such as a valid config file
# the dialog asks if the file should be over-written (I guess that is ok, because this is what happens
# when you close the gui)
filename = str(QtWidgets.QFileDialog.getSaveFileName(self, 'Unvalid Config File. Select Config.',
dialog_dir, 'b26 files (*.b26)')[0])
if filename == '':
# todo: create all the settings outside of init and only then start loading the gui!
raise ValueError
# started to work on custom dialog, but this is not finished yet
# keep the code for now:
# === begin custom dialog ====
# dialog = QtWidgets.QFileDialog(self)
# dialog.setNameFilter('b26 files (*.b26)')
# dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)
# dialog.setDirectory(dialog_dir)
# dialog.setWindowTitle('Unvalid Config File. Select Config.')
# dialog.setParent(self)
# filename = str(dialog.open())
# print(filename)
# === end custom dialog ====
self.instruments = {}
self.scripts = {}
self.probes = {}
self.gui_settings = {'scripts_folder': '', 'data_folder': ''}
self.config_filename = filename
self.load_config(self.config_filename)
self.data_sets = {} # todo: load datasets from tmp folder
self.read_probes = ReadProbes(self.probes)
self.tabWidget.setCurrentIndex(0) # always show the script tab
# == create a thread for the scripts ==
self.script_thread = QThread()
# used to keep track of status updates, to block updates when they occur to often
self._last_progress_update = None
self.chk_show_all.setChecked(True)
self.actionSave.setShortcut(QtGui.QKeySequence.Save)
self.list_history.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
def closeEvent(self, event):
"""
things to be done when gui closes, like save the settings
"""
self.script_thread.quit()
self.read_probes.quit()
if self.config_filename:
fname = self.config_filename
self.save_config(fname)
event.accept()
print('\n\n======================================================')
print('================= Closing B26 Python LAB =============')
print('======================================================\n\n')
def eventFilter(self, object, event):
"""
TEMPORARY / UNDER DEVELOPMENT
THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP
Args:
object:
event:
Returns:
"""
if (object is self.tree_scripts):
# print('XXXXXXX = event in scripts', event.type(),
# QtCore.QEvent.DragEnter, QtCore.QEvent.DragMove, QtCore.QEvent.DragLeave)
if (event.type() == QtCore.QEvent.ChildAdded):
item = self.tree_scripts.selectedItems()[0]
if not isinstance(item.value, Script):
print('ONLY SCRIPTS CAN BE DRAGGED')
return False
print(
('XXX ChildAdded', self.tree_scripts.selectedItems()[0].name))
# if event.mimeData().hasUrls():
# event.accept() # must accept the dragEnterEvent or else the dropEvent can't occur !!!
# print "accept"
# else:
# event.ignore()
# print "ignore"
if (event.type() == QtCore.QEvent.ChildRemoved):
print(
('XXX ChildRemoved', self.tree_scripts.selectedItems()[0].name))
if (event.type() == QtCore.QEvent.Drop):
print('XXX Drop')
# if event.mimeData().hasUrls(): # if file or link is dropped
# urlcount = len(event.mimeData().urls()) # count number of drops
# url = event.mimeData().urls()[0] # get first url
# object.setText(url.toString()) # assign first url to editline
# # event.accept() # doesnt appear to be needed
return False # lets the event continue to the edit
return False
def set_probe_file_name(self, checked):
"""
sets the filename to which the probe logging function will write
Args:
checked: boolean (True: opens file) (False: closes file)
"""
if checked:
file_name = os.path.join(self.gui_settings['probes_log_folder'], '{:s}_probes.csv'.format(
datetime.datetime.now().strftime('%y%m%d-%H_%M_%S')))
if os.path.isfile(file_name) == False:
self.probe_file = open(file_name, 'a')
new_values = self.read_probes.probes_values
header = ','.join(list(np.array([['{:s} ({:s})'.format(p, instr) for p in list(
p_dict.keys())] for instr, p_dict in new_values.items()]).flatten()))
self.probe_file.write('{:s}\n'.format(header))
else:
self.probe_file.close()
def switch_tab(self):
"""
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
"""
current_tab = str(self.tabWidget.tabText(
self.tabWidget.currentIndex()))
if self.current_script is None:
if current_tab == 'Probes':
self.read_probes.start()
self.read_probes.updateProgress.connect(self.update_probes)
else:
try:
self.read_probes.updateProgress.disconnect()
self.read_probes.quit()
except TypeError:
pass
if current_tab == 'Instruments':
self.refresh_instruments()
else:
self.log(
'updating probes / instruments disabled while script is running!')
def refresh_instruments(self):
"""
if self.tree_settings has been expanded, ask instruments for their actual values
"""
def list_access_nested_dict(dict, somelist):
"""
Allows one to use a list to access a nested dictionary, for example:
listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
Args:
dict:
somelist:
Returns:
"""
return reduce(operator.getitem, somelist, dict)
def update(item):
if item.isExpanded():
for index in range(item.childCount()):
child = item.child(index)
if child.childCount() == 0:
instrument, path_to_instrument = child.get_instrument()
path_to_instrument.reverse()
try: # check if item is in probes
value = instrument.read_probes(
path_to_instrument[-1])
except AssertionError: # if item not in probes, get value from settings instead
value = list_access_nested_dict(
instrument.settings, path_to_instrument)
child.value = value
else:
update(child)
# need to block signals during update so that tree.itemChanged doesn't fire and the gui doesn't try to
# reupdate the instruments to their current value
self.tree_settings.blockSignals(True)
for index in range(self.tree_settings.topLevelItemCount()):
instrument = self.tree_settings.topLevelItem(index)
update(instrument)
self.tree_settings.blockSignals(False)
def plot_clicked(self, mouse_event):
"""
gets activated when the user clicks on a plot
Args:
mouse_event:
"""
if isinstance(self.current_script, SelectPoints) and self.current_script.is_running:
if (not (mouse_event.xdata == None)):
if (mouse_event.button == 1):
pt = np.array([mouse_event.xdata, mouse_event.ydata])
self.current_script.toggle_NV(pt)
self.current_script.plot([self.matplotlibwidget_1.figure])
self.matplotlibwidget_1.draw()
item = self.tree_scripts.currentItem()
if item is not None:
if item.is_point():
item_x = item.child(1)
if mouse_event.xdata is not None:
self.tree_scripts.setCurrentItem(item_x)
item_x.value = float(mouse_event.xdata)
item_x.setText(1, '{:0.3f}'.format(
float(mouse_event.xdata)))
item_y = item.child(0)
if mouse_event.ydata is not None:
self.tree_scripts.setCurrentItem(item_y)
item_y.value = float(mouse_event.ydata)
item_y.setText(1, '{:0.3f}'.format(
float(mouse_event.ydata)))
# focus back on item
self.tree_scripts.setCurrentItem(item)
else:
if item.parent() is not None:
if item.parent().is_point():
if item == item.parent().child(1):
if mouse_event.xdata is not None:
item.setData(1, 2, float(mouse_event.xdata))
if item == item.parent().child(0):
if mouse_event.ydata is not None:
item.setData(1, 2, float(mouse_event.ydata))
def get_time(self):
"""
Returns: the current time as a formated string
"""
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
def log(self, msg):
"""
log function
Args:
msg: the text message to be logged
"""
time = self.get_time()
msg = "{:s}\t {:s}".format(time, msg)
self.history.append(msg)
self.history_model.insertRow(0, QtGui.QStandardItem(msg))
def create_figures(self):
"""
creates the maplotlib figures]
self.matplotlibwidget_1
self.matplotlibwidget_2
and toolbars
self.mpl_toolbar_1
self.mpl_toolbar_2
Returns:
"""
try:
self.horizontalLayout_14.removeWidget(self.matplotlibwidget_1)
self.matplotlibwidget_1.close()
except AttributeError:
pass
try:
self.horizontalLayout_15.removeWidget(self.matplotlibwidget_2)
self.matplotlibwidget_2.close()
except AttributeError:
pass
self.matplotlibwidget_2 = MatplotlibWidget(self.plot_2)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.matplotlibwidget_2.sizePolicy().hasHeightForWidth())
self.matplotlibwidget_2.setSizePolicy(sizePolicy)
self.matplotlibwidget_2.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget_2.setObjectName("matplotlibwidget_2")
self.horizontalLayout_16.addWidget(self.matplotlibwidget_2)
self.matplotlibwidget_1 = MatplotlibWidget(self.plot_1)
self.matplotlibwidget_1.setMinimumSize(QtCore.QSize(200, 200))
self.matplotlibwidget_1.setObjectName("matplotlibwidget_1")
self.horizontalLayout_15.addWidget(self.matplotlibwidget_1)
self.matplotlibwidget_1.mpl_connect(
'button_press_event', self.plot_clicked)
self.matplotlibwidget_2.mpl_connect(
'button_press_event', self.plot_clicked)
# adds a toolbar to the plots
self.mpl_toolbar_1 = NavigationToolbar(
self.matplotlibwidget_1.canvas, self.toolbar_space_1)
self.mpl_toolbar_2 = NavigationToolbar(
self.matplotlibwidget_2.canvas, self.toolbar_space_2)
self.horizontalLayout_9.addWidget(self.mpl_toolbar_2)
self.horizontalLayout_14.addWidget(self.mpl_toolbar_1)
self.matplotlibwidget_1.figure.set_tight_layout(True)
self.matplotlibwidget_2.figure.set_tight_layout(True)
def load_scripts(self):
"""
opens file dialog to load scripts into gui
"""
# update scripts so that current settings do not get lost
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
self.update_script_from_item(script_item)
dialog = LoadDialog(elements_type="scripts", elements_old=self.scripts,
filename=self.gui_settings['scripts_folder'])
if dialog.exec_():
self.gui_settings['scripts_folder'] = str(
dialog.txt_probe_log_path.text())
scripts = dialog.get_values()
added_scripts = set(scripts.keys()) - set(self.scripts.keys())
removed_scripts = set(self.scripts.keys()) - set(scripts.keys())
if 'data_folder' in list(self.gui_settings.keys()) and os.path.exists(self.gui_settings['data_folder']):
data_folder_name = self.gui_settings['data_folder']
else:
data_folder_name = None
# create instances of new instruments/scripts
self.scripts, loaded_failed, self.instruments = Script.load_and_append(
script_dict={name: scripts[name] for name in added_scripts},
scripts=self.scripts,
instruments=self.instruments,
log_function=self.log,
data_path=data_folder_name)
# delete instances of new instruments/scripts that have been deselected
for name in removed_scripts:
del self.scripts[name]
def btn_clicked(self):
"""
slot to which connect buttons
"""
sender = self.sender()
self.probe_to_plot = None
def start_button():
"""
starts the selected script
"""
item = self.tree_scripts.currentItem()
# BROKEN 20170109: repeatedly erases updates to gui
# self.expanded_items = []
# for index in range(self.tree_scripts.topLevelItemCount()):
# someitem = self.tree_scripts.topLevelItem(index)
# if someitem.isExpanded():
# self.expanded_items.append(someitem.name)
self.script_start_time = datetime.datetime.now()
if item is not None:
# get script and update settings from tree
self.running_item = item
script, path_to_script, script_item = item.get_script()
self.update_script_from_item(script_item)
self.log('starting {:s}'.format(script.name))
# put script onto script thread
print('================================================')
print(('===== starting {:s}'.format(script.name)))
print('================================================')
script_thread = self.script_thread
def move_to_worker_thread(script):
script.moveToThread(script_thread)
# move also the subscript to the worker thread
for subscript in list(script.scripts.values()):
move_to_worker_thread(subscript)
move_to_worker_thread(script)
# connect update signal of script to update slot of gui
script.updateProgress.connect(self.update_status)
# causes the script to start upon starting the thread
script_thread.started.connect(script.run)
# clean up. quit thread after script is finished
script.finished.connect(script_thread.quit)
# connect finished signal of script to finished slot of gui
script.finished.connect(self.script_finished)
# start thread, i.e. script
script_thread.start()
self.current_script = script
self.btn_start_script.setEnabled(False)
# self.tabWidget.setEnabled(False)
if isinstance(self.current_script, ScriptIterator):
self.btn_skip_subscript.setEnabled(True)
else:
self.log('User tried to run a script without one selected.')
def stop_button():
"""
stops the current script
"""
if self.current_script is not None and self.current_script.is_running:
self.current_script.stop()
else:
self.log(
'User clicked stop, but there isn\'t anything running...this is awkward. Re-enabling start button anyway.')
self.btn_start_script.setEnabled(True)
def skip_button():
"""
Skips to the next script if the current script is a Iterator script
"""
if self.current_script is not None and self.current_script.is_running and isinstance(self.current_script,
ScriptIterator):
self.current_script.skip_next()
else:
self.log(
'User clicked skip, but there isn\'t a iterator script running...this is awkward.')
def validate_button():
"""
validates the selected script
"""
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, script_item = item.get_script()
self.update_script_from_item(script_item)
script.is_valid()
script.plot_validate(
[self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
def store_script_data():
"""
updates the internal self.data_sets with selected script and updates tree self.fill_dataset_tree
"""
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, _ = item.get_script()
script_copy = script.duplicate()
time_tag = script.start_time.strftime('%y%m%d-%H_%M_%S')
self.data_sets.update({time_tag: script_copy})
self.fill_dataset_tree(self.tree_dataset, self.data_sets)
def save_data():
""""
saves the selected script (where is contained in the script itself)
"""
indecies = self.tree_dataset.selectedIndexes()
model = indecies[0].model()
rows = list(set([index.row()for index in indecies]))
for row in rows:
time_tag = str(model.itemFromIndex(model.index(row, 0)).text())
name_tag = str(model.itemFromIndex(model.index(row, 1)).text())
path = self.gui_settings['data_folder']
script = self.data_sets[time_tag]
script.update({'tag': name_tag, 'path': path})
script.save_data()
script.save_image_to_disk()
script.save_b26()
script.save_log()
def delete_data():
"""
deletes the data from the dataset
Returns:
"""
indecies = self.tree_dataset.selectedIndexes()
model = indecies[0].model()
rows = list(set([index.row()for index in indecies]))
for row in rows:
time_tag = str(model.itemFromIndex(model.index(row, 0)).text())
del self.data_sets[time_tag]
model.removeRows(row, 1)
def load_probes():
"""
opens file dialog to load probes into gui
"""
# if the probe has never been started it can not be disconnected so we catch that error
try:
self.read_probes.updateProgress.disconnect()
self.read_probes.quit()
# self.read_probes.stop()
except RuntimeError:
pass
dialog = LoadDialogProbes(
probes_old=self.probes, filename=self.gui_settings['probes_folder'])
if dialog.exec_():
self.gui_settings['probes_folder'] = str(
dialog.txt_probe_log_path.text())
probes = dialog.getValues()
added_instruments = list(
set(probes.keys()) - set(self.probes.keys()))
removed_instruments = list(
set(self.probes.keys()) - set(probes.keys()))
# create instances of new probes
self.probes, loaded_failed, self.instruments = Probe.load_and_append(
probe_dict=probes,
probes={},
instruments=self.instruments)
if not loaded_failed:
print(('WARNING following probes could not be loaded',
loaded_failed, len(loaded_failed)))
# restart the readprobes thread
del self.read_probes
self.read_probes = ReadProbes(self.probes)
self.read_probes.start()
self.tree_probes.clear() # clear tree because the probe might have changed
self.read_probes.updateProgress.connect(self.update_probes)
self.tree_probes.expandAll()
def load_instruments():
"""
opens file dialog to load instruments into gui
"""
if 'instrument_folder' in self.gui_settings:
dialog = LoadDialog(elements_type="instruments", elements_old=self.instruments,
filename=self.gui_settings['instrument_folder'])
else:
dialog = LoadDialog(elements_type="instruments",
elements_old=self.instruments)
if dialog.exec_():
self.gui_settings['instrument_folder'] = str(
dialog.txt_probe_log_path.text())
instruments = dialog.get_values()
added_instruments = set(
instruments.keys()) - set(self.instruments.keys())
removed_instruments = set(
self.instruments.keys()) - set(instruments.keys())
# print('added_instruments', {name: instruments[name] for name in added_instruments})
# create instances of new instruments
self.instruments, loaded_failed = Instrument.load_and_append(
{name: instruments[name] for name in added_instruments}, self.instruments)
if len(loaded_failed) > 0:
print(
('WARNING following instrument could not be loaded', loaded_failed))
# delete instances of new instruments/scripts that have been deselected
for name in removed_instruments:
del self.instruments[name]
def plot_data(sender):
"""
plots the data of the selected script
"""
if sender == self.tree_dataset:
index = self.tree_dataset.selectedIndexes()[0]
model = index.model()
time_tag = str(model.itemFromIndex(
model.index(index.row(), 0)).text())
script = self.data_sets[time_tag]
self.plot_script(script)
elif sender == self.tree_scripts:
item = self.tree_scripts.currentItem()
if item is not None:
script, path_to_script, _ = item.get_script()
# only plot if script has been selected but not if a parameter has been selected
if path_to_script == []:
self.plot_script(script)
def save():
self.save_config(self.config_filename)
if sender is self.btn_start_script:
start_button()
elif sender is self.btn_stop_script:
stop_button()
elif sender is self.btn_skip_subscript:
skip_button()
elif sender is self.btn_validate_script:
validate_button()
elif sender in (self.tree_dataset, self.tree_scripts):
plot_data(sender)
elif sender is self.btn_store_script_data:
store_script_data()
elif sender is self.btn_save_data:
save_data()
elif sender is self.btn_delete_data:
delete_data()
# elif sender is self.btn_plot_probe:
elif sender is self.chk_probe_plot:
if self.chk_probe_plot.isChecked():
item = self.tree_probes.currentItem()
if item is not None:
if item.name in self.probes:
# selected item is an instrument not a probe, maybe plot all the probes...
self.log(
'Can\'t plot, No probe selected. Select probe and try again!')
else:
instrument = item.parent().name
self.probe_to_plot = self.probes[instrument][item.name]
else:
self.log(
'Can\'t plot, No probe selected. Select probe and try again!')
else:
self.probe_to_plot = None
elif sender is self.btn_save_gui:
# get filename
fname = QtWidgets.QFileDialog.getSaveFileName(
self, 'Save gui settings to file', self.gui_settings['data_folder']) # filter = '.b26gui'
self.save_config(fname[0])
elif sender is self.btn_load_gui:
# get filename
fname = QtWidgets.QFileDialog.getOpenFileName(
self, 'Load gui settings from file', self.gui_settings['data_folder'])
# self.load_settings(fname)
self.load_config(fname[0])
elif sender is self.btn_about:
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText(
"pylabcontrol: Laboratory Equipment Control for Scientific Experiments")
msg.setInformativeText("This software was developed by Arthur Safira, Jan Gieseler, and Aaron Kabcenell at"
"Harvard University. It is licensed under the LPGL licence. For more information,"
"visit the GitHub page at github.com/LISE-B26/pylabcontrol .")
msg.setWindowTitle("About")
# msg.setDetailedText("some stuff")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
# msg.buttonClicked.connect(msgbtn)
retval = msg.exec_()
# elif (sender is self.btn_load_instruments) or (sender is self.btn_load_scripts):
elif sender in (self.btn_load_instruments, self.btn_load_scripts, self.btn_load_probes):
if sender is self.btn_load_instruments:
load_instruments()
elif sender is self.btn_load_scripts:
self.load_scripts()
elif sender is self.btn_load_probes:
load_probes()
# refresh trees
self.refresh_tree(self.tree_scripts, self.scripts)
self.refresh_tree(self.tree_settings, self.instruments)
elif sender is self.actionSave:
if self.config_filename:
self.save_config(self.config_filename)
elif sender is self.actionGo_to_pylabcontrol_GitHub_page:
webbrowser.open('https://github.com/LISE-B26/pylabcontrol')
def _show_hide_parameter(self):
"""
shows or hides parameters
Returns:
"""
assert isinstance(self.sender(
), QtWidgets.QCheckBox), 'this function should be connected to a check box'
if self.sender().isChecked():
self.tree_scripts.setColumnHidden(2, False)
iterator = QtWidgets.QTreeWidgetItemIterator(
self.tree_scripts, QtWidgets.QTreeWidgetItemIterator.Hidden)
item = iterator.value()
while item:
item.setHidden(False)
item = iterator.value()
iterator += 1
else:
self.tree_scripts.setColumnHidden(2, True)
iterator = QtWidgets.QTreeWidgetItemIterator(
self.tree_scripts, QtWidgets.QTreeWidgetItemIterator.NotHidden)
item = iterator.value()
while item:
if not item.visible:
item.setHidden(True)
item = iterator.value()
iterator += 1
self.tree_scripts.setColumnWidth(0, 200)
self.tree_scripts.setColumnWidth(1, 400)
self.tree_scripts.setColumnWidth(2, 50)
def update_parameters(self, treeWidget):
"""
updates the internal dictionaries for scripts and instruments with values from the respective trees
treeWidget: the tree from which to update
"""
if treeWidget == self.tree_settings:
item = treeWidget.currentItem()
instrument, path_to_instrument = item.get_instrument()
# build nested dictionary to update instrument
dictator = item.value
for element in path_to_instrument:
dictator = {element: dictator}
# get old value from instrument
old_value = instrument.settings
path_to_instrument.reverse()
for element in path_to_instrument:
old_value = old_value[element]
# send new value from tree to instrument
instrument.update(dictator)
new_value = item.value
if new_value is not old_value:
msg = "changed parameter {:s} from {:s} to {:s} on {:s}".format(item.name, str(old_value),
str(new_value), instrument.name)
else:
msg = "did not change parameter {:s} on {:s}".format(
item.name, instrument.name)
self.log(msg)
elif treeWidget == self.tree_scripts:
item = treeWidget.currentItem()
script, path_to_script, _ = item.get_script()
# check if changes value is from an instrument
instrument, path_to_instrument = item.get_instrument()
if instrument is not None:
new_value = item.value
msg = "changed parameter {:s} to {:s} in {:s}".format(item.name,
str(new_value),
script.name)
else:
new_value = item.value
msg = "changed parameter {:s} to {:s} in {:s}".format(item.name,
str(new_value),
script.name)
self.log(msg)
def plot_script(self, script):
"""
Calls the plot function of the script, and redraws both plots
Args:
script: script to be plotted
"""
script.plot([self.matplotlibwidget_1.figure,
self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
@pyqtSlot(int)
def update_status(self, progress):
"""
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
"""
# interval at which the gui will be updated, if requests come in faster than they will be ignored
update_interval = 0.2
now = datetime.datetime.now()
if not self._last_progress_update is None and now-self._last_progress_update < datetime.timedelta(seconds=update_interval):
return
self._last_progress_update = now
self.progressBar.setValue(progress)
script = self.current_script
# Estimate remaining time if progress has been made
if progress:
remaining_time = str(datetime.timedelta(
seconds=script.remaining_time.seconds))
self.lbl_time_estimate.setText(
'time remaining: {:s}'.format(remaining_time))
if script is not str(self.tabWidget.tabText(self.tabWidget.currentIndex())).lower() in ['scripts', 'instruments']:
self.plot_script(script)
@pyqtSlot()
def script_finished(self):
"""
waits for the script to emit the script_finshed signal
"""
script = self.current_script
script.updateProgress.disconnect(self.update_status)
self.script_thread.started.disconnect()
script.finished.disconnect()
self.current_script = None
self.plot_script(script)
self.progressBar.setValue(100)
self.btn_start_script.setEnabled(True)
self.btn_skip_subscript.setEnabled(False)
def plot_script_validate(self, script):
"""
checks the plottype of the script and plots it accordingly
Args:
script: script to be plotted
"""
script.plot_validate(
[self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])
self.matplotlibwidget_1.draw()
self.matplotlibwidget_2.draw()
def update_probes(self, progress):
"""
update the probe tree
"""
new_values = self.read_probes.probes_values
probe_count = len(self.read_probes.probes)
if probe_count > self.tree_probes.topLevelItemCount():
# when run for the first time, there are no probes in the tree, so we have to fill it first
self.fill_treewidget(self.tree_probes, new_values)
else:
for x in range(probe_count):
topLvlItem = self.tree_probes.topLevelItem(x)
for child_id in range(topLvlItem.childCount()):
child = topLvlItem.child(child_id)
child.value = new_values[topLvlItem.name][child.name]
child.setText(1, str(child.value))
if self.probe_to_plot is not None:
self.probe_to_plot.plot(self.matplotlibwidget_1.axes)
self.matplotlibwidget_1.draw()
if self.chk_probe_log.isChecked():
data = ','.join(list(np.array([[str(p) for p in list(
p_dict.values())] for instr, p_dict in new_values.items()]).flatten()))
self.probe_file.write('{:s}\n'.format(data))
def update_script_from_item(self, item):
"""
updates the script based on the information provided in item
Args:
script: script to be updated
item: B26QTreeItem that contains the new settings of the script
"""
script, path_to_script, script_item = item.get_script()
# build dictionary
# get full information from script
# there is only one item in the dictionary
dictator = list(script_item.to_dict().values())[0]
for instrument in list(script.instruments.keys()):
# update instrument
script.instruments[instrument]['settings'] = dictator[instrument]['settings']
# remove instrument
del dictator[instrument]
for sub_script_name in list(script.scripts.keys()):
sub_script_item = script_item.get_subscript(sub_script_name)
self.update_script_from_item(sub_script_item)
del dictator[sub_script_name]
script.update(dictator)
# update datefolder path
script.data_path = self.gui_settings['data_folder']
def fill_treewidget(self, tree, parameters):
"""
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Returns:
"""
tree.clear()
assert isinstance(parameters, (dict, Parameter))
for key, value in parameters.items():
if isinstance(value, Parameter):
B26QTreeItem(tree, key, value,
parameters.valid_values[key], parameters.info[key])
else:
B26QTreeItem(tree, key, value, type(value), '')
def fill_treeview(self, tree, input_dict):
"""
fills a treeview with nested parameters
Args:
tree: QtWidgets.QTreeView
parameters: dictionary or Parameter object
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
def add_elemet(item, key, value):
child_name = QtWidgets.QStandardItem(key)
# child_name.setDragEnabled(False)
# child_name.setSelectable(False)
# child_name.setEditable(False)
if isinstance(value, dict):
for key_child, value_child in value.items():
add_elemet(child_name, key_child, value_child)
item.appendRow(child_name)
else:
child_value = QtWidgets.QStandardItem(str(value))
# child_value.setDragEnabled(False)
# child_value.setSelectable(False)
# child_value.setEditable(False)
item.appendRow([child_name, child_value])
for index, (key, value) in enumerate(input_dict.items()):
if isinstance(value, dict):
item = QtWidgets.QStandardItem(key)
for sub_key, sub_value in value.items():
add_elemet(item, sub_key, sub_value)
tree.model().appendRow(item)
elif isinstance(value, str):
item = QtGui.QStandardItem(key)
item_value = QtGui.QStandardItem(value)
item_value.setEditable(True)
item_value.setSelectable(True)
tree.model().appendRow([item, item_value])
def edit_tree_item(self):
"""
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath
this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
"""
def open_path_dialog(path):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtWidgets.QFileDialog()
dialog.setFileMode(QtWidgets.QFileDialog.Directory)
dialog.setOption(QtWidgets.QFileDialog.ShowDirsOnly, True)
path = dialog.getExistingDirectory(self, 'Select a folder:', path)
return path
tree = self.sender()
if tree == self.tree_gui_settings:
index = tree.selectedIndexes()[0]
model = index.model()
if index.column() == 1:
path = model.itemFromIndex(index).text()
path = str(open_path_dialog(path))
key = str(model.itemFromIndex(
model.index(index.row(), 0)).text())
if path != "":
self.gui_settings.update({key: str(path)})
self.fill_treeview(tree, self.gui_settings)
def refresh_tree(self, tree, items):
"""
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones
"""
if tree == self.tree_scripts or tree == self.tree_settings:
tree.itemChanged.disconnect()
self.fill_treewidget(tree, items)
tree.itemChanged.connect(lambda: self.update_parameters(tree))
elif tree == self.tree_gui_settings:
self.fill_treeview(tree, items)
def fill_dataset_tree(self, tree, data_sets):
"""
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
for index, (time, script) in enumerate(data_sets.items()):
name = script.settings['tag']
type = script.name
item_time = QtGui.QStandardItem(str(time))
item_name = QtGui.QStandardItem(str(name))
item_type = QtGui.QStandardItem(str(type))
item_time.setSelectable(False)
item_time.setEditable(False)
item_type.setSelectable(False)
item_type.setEditable(False)
tree.model().appendRow([item_time, item_name, item_type])
def load_config(self, file_name):
"""
checks if the file is a valid config file
Args:
file_name:
"""
# load config or default if invalid
def load_settings(file_name):
"""
loads a old_gui settings file (a json dictionary)
- path_to_file: path to file that contains the dictionary
Returns:
- instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
- scripts: depth 1 dictionary where keys are script names and values are instances of scripts
- probes: depth 1 dictionary where to be decided....?
"""
instruments_loaded = {}
probes_loaded = {}
scripts_loaded = {}
if os.path.isfile(file_name):
in_data = load_b26_file(file_name)
instruments = in_data['instruments'] if 'instruments' in in_data else {
}
scripts = in_data['scripts'] if 'scripts' in in_data else {}
probes = in_data['probes'] if 'probes' in in_data else {}
instruments_loaded, failed = Instrument.load_and_append(
instruments)
if len(failed) > 0:
print(
('WARNING! Following instruments could not be loaded: ', failed))
scripts_loaded, failed, instruments_loaded = Script.load_and_append(
script_dict=scripts,
instruments=instruments_loaded,
log_function=self.log,
data_path=self.gui_settings['data_folder'])
if len(failed) > 0:
print(('WARNING! Following scripts could not be loaded: ', failed))
probes_loaded, failed, instruments_loadeds = Probe.load_and_append(
probe_dict=probes,
probes=probes_loaded,
instruments=instruments_loaded)
return instruments_loaded, scripts_loaded, probes_loaded
print(
('loading script/instrument/probes config from {:s}'.format(file_name)))
try:
config = load_b26_file(file_name)['gui_settings']
if config['settings_file'] != file_name:
print((
'WARNING path to settings file ({:s}) in config file is different from path of settings file ({:s})'.format(
config['settings_file'], file_name)))
config['settings_file'] = file_name
print(('loading of {:s} successful'.format(file_name)))
except Exception:
print(('WARNING path to settings file ({:s}) invalid use default settings'.format(
file_name)))
config = self._DEFAULT_CONFIG
for x in list(self._DEFAULT_CONFIG.keys()):
if x in config:
if not os.path.exists(config[x]):
try:
os.makedirs(config[x])
except Exception:
config[x] = self._DEFAULT_CONFIG[x]
os.makedirs(config[x])
print(('WARNING: failed validating or creating path: set to default path'.format(
config[x])))
else:
config[x] = self._DEFAULT_CONFIG[x]
os.makedirs(config[x])
print(
('WARNING: path {:s} not specified set to default {:s}'.format(x, config[x])))
# check if file_name is a valid filename
if os.path.exists(os.path.dirname(file_name)):
config['settings_file'] = file_name
self.gui_settings = config
self.instruments, self.scripts, self.probes = load_settings(file_name)
self.refresh_tree(self.tree_gui_settings, self.gui_settings)
self.refresh_tree(self.tree_scripts, self.scripts)
self.refresh_tree(self.tree_settings, self.instruments)
self._hide_parameters(file_name)
def _hide_parameters(self, file_name):
"""
hide the parameters that had been hidden
Args:
file_name: config file that has the information about which parameters are hidden
"""
try:
in_data = load_b26_file(file_name)
except:
in_data = {}
def set_item_visible(item, is_visible):
if isinstance(is_visible, dict):
for child_id in range(item.childCount()):
child = item.child(child_id)
if child.name in is_visible:
set_item_visible(child, is_visible[child.name])
else:
item.visible = is_visible
if "scripts_hidden_parameters" in in_data:
# consistency check
if len(list(in_data["scripts_hidden_parameters"].keys())) == self.tree_scripts.topLevelItemCount():
for index in range(self.tree_scripts.topLevelItemCount()):
item = self.tree_scripts.topLevelItem(index)
# if item.name in in_data["scripts_hidden_parameters"]:
set_item_visible(
item, in_data["scripts_hidden_parameters"][item.name])
else:
print(
'WARNING: settings for hiding parameters does\'t seem to match other settings')
else:
print('WARNING: no settings for hiding parameters all set to default')
def save_config(self, out_file_name):
"""
saves gui configuration to out_file_name
Args:
out_file_name: name of file
"""
def get_hidden_parameter(item):
numer_of_sub_elements = item.childCount()
if numer_of_sub_elements == 0:
dictator = {item.name: item.visible}
else:
dictator = {item.name: {}}
for child_id in range(numer_of_sub_elements):
dictator[item.name].update(
get_hidden_parameter(item.child(child_id)))
return dictator
out_file_name = str(out_file_name)
if not os.path.exists(os.path.dirname(out_file_name)):
os.makedirs(os.path.dirname(out_file_name))
# build a dictionary for the configuration of the hidden parameters
dictator = {}
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
dictator.update(get_hidden_parameter(script_item))
dictator = {"gui_settings": self.gui_settings,
"scripts_hidden_parameters": dictator}
# update the internal dictionaries from the trees in the gui
for index in range(self.tree_scripts.topLevelItemCount()):
script_item = self.tree_scripts.topLevelItem(index)
self.update_script_from_item(script_item)
dictator.update({'instruments': {}, 'scripts': {}, 'probes': {}})
for instrument in self.instruments.values():
dictator['instruments'].update(instrument.to_dict())
for script in self.scripts.values():
dictator['scripts'].update(script.to_dict())
for instrument, probe_dict in self.probes.items():
dictator['probes'].update(
{instrument: ','.join(list(probe_dict.keys()))})
with open(out_file_name, 'w') as outfile:
tmp = json.dump(dictator, outfile, indent=4)
def save_dataset(self, out_file_name):
"""
saves current dataset to out_file_name
Args:
out_file_name: name of file
"""
for time_tag, script in self.data_sets.items():
script.save(os.path.join(out_file_name,
'{:s}.b26s'.format(time_tag)))
|
class ControlMainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, filename=None):
'''
MainWindow(intruments, scripts, probes)
- intruments: depth 1 dictionary where keys are instrument names and keys are instrument classes
- scripts: depth 1 dictionary where keys are script names and keys are script classes
- probes: depth 1 dictionary where to be decided....?
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
'''
pass
def setup_trees():
pass
def connect_controls():
pass
def onScriptParamClick(item, column):
pass
def closeEvent(self, event):
'''
things to be done when gui closes, like save the settings
'''
pass
def eventFilter(self, object, event):
'''
TEMPORARY / UNDER DEVELOPMENT
THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP
Args:
object:
event:
Returns:
'''
pass
def set_probe_file_name(self, checked):
'''
sets the filename to which the probe logging function will write
Args:
checked: boolean (True: opens file) (False: closes file)
'''
pass
def switch_tab(self):
'''
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
'''
pass
def refresh_instruments(self):
'''
if self.tree_settings has been expanded, ask instruments for their actual values
'''
pass
def list_access_nested_dict(dict, somelist):
'''
Allows one to use a list to access a nested dictionary, for example:
listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1
Args:
dict:
somelist:
Returns:
'''
pass
def update(item):
pass
def plot_clicked(self, mouse_event):
'''
gets activated when the user clicks on a plot
Args:
mouse_event:
'''
pass
def get_time(self):
'''
Returns: the current time as a formated string
'''
pass
def log(self, msg):
'''
log function
Args:
msg: the text message to be logged
'''
pass
def create_figures(self):
'''
creates the maplotlib figures]
self.matplotlibwidget_1
self.matplotlibwidget_2
and toolbars
self.mpl_toolbar_1
self.mpl_toolbar_2
Returns:
'''
pass
def load_scripts(self):
'''
opens file dialog to load scripts into gui
'''
pass
def btn_clicked(self):
'''
slot to which connect buttons
'''
pass
def start_button():
'''
starts the selected script
'''
pass
def move_to_worker_thread(script):
pass
def stop_button():
'''
stops the current script
'''
pass
def skip_button():
'''
Skips to the next script if the current script is a Iterator script
'''
pass
def validate_button():
'''
validates the selected script
'''
pass
def store_script_data():
'''
updates the internal self.data_sets with selected script and updates tree self.fill_dataset_tree
'''
pass
def save_data():
'''"
saves the selected script (where is contained in the script itself)
'''
pass
def delete_data():
'''
deletes the data from the dataset
Returns:
'''
pass
def load_probes():
'''
opens file dialog to load probes into gui
'''
pass
def load_instruments():
'''
opens file dialog to load instruments into gui
'''
pass
def plot_data(sender):
'''
plots the data of the selected script
'''
pass
def save_data():
pass
def _show_hide_parameter(self):
'''
shows or hides parameters
Returns:
'''
pass
def update_parameters(self, treeWidget):
'''
updates the internal dictionaries for scripts and instruments with values from the respective trees
treeWidget: the tree from which to update
'''
pass
def plot_script(self, script):
'''
Calls the plot function of the script, and redraws both plots
Args:
script: script to be plotted
'''
pass
@pyqtSlot(int)
def update_status(self, progress):
'''
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
'''
pass
@pyqtSlot()
def script_finished(self):
'''
waits for the script to emit the script_finshed signal
'''
pass
def plot_script_validate(self, script):
'''
checks the plottype of the script and plots it accordingly
Args:
script: script to be plotted
'''
pass
def update_probes(self, progress):
'''
update the probe tree
'''
pass
def update_script_from_item(self, item):
'''
updates the script based on the information provided in item
Args:
script: script to be updated
item: B26QTreeItem that contains the new settings of the script
'''
pass
def fill_treewidget(self, tree, parameters):
'''
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Returns:
'''
pass
def fill_treeview(self, tree, input_dict):
'''
fills a treeview with nested parameters
Args:
tree: QtWidgets.QTreeView
parameters: dictionary or Parameter object
Returns:
'''
pass
def add_elemet(item, key, value):
pass
def edit_tree_item(self):
'''
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath
this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
'''
pass
def open_path_dialog(path):
'''
opens a file dialog to get the path to a file and
'''
pass
def refresh_tree(self, tree, items):
'''
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all parameters, if false only selected ones
'''
pass
def fill_dataset_tree(self, tree, data_sets):
'''
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
'''
pass
def load_config(self, file_name):
'''
checks if the file is a valid config file
Args:
file_name:
'''
pass
def load_settings(file_name):
'''
loads a old_gui settings file (a json dictionary)
- path_to_file: path to file that contains the dictionary
Returns:
- instruments: depth 1 dictionary where keys are instrument names and values are instances of instruments
- scripts: depth 1 dictionary where keys are script names and values are instances of scripts
- probes: depth 1 dictionary where to be decided....?
'''
pass
def _hide_parameters(self, file_name):
'''
hide the parameters that had been hidden
Args:
file_name: config file that has the information about which parameters are hidden
'''
pass
def set_item_visible(item, is_visible):
pass
def save_config(self, out_file_name):
'''
saves gui configuration to out_file_name
Args:
out_file_name: name of file
'''
pass
def get_hidden_parameter(item):
pass
def save_dataset(self, out_file_name):
'''
saves current dataset to out_file_name
Args:
out_file_name: name of file
'''
pass
| 54 | 42 | 34 | 6 | 20 | 8 | 4 | 0.43 | 2 | 25 | 8 | 0 | 29 | 16 | 29 | 29 | 1,348 | 266 | 767 | 224 | 713 | 329 | 680 | 221 | 628 | 23 | 1 | 6 | 198 |
144,556 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/core/probe.py
|
pylabcontrol.core.probe.Probe
|
class Probe(object):
def __init__(self, instrument, probe_name, name = None, info = None, buffer_length = 100):
"""
creates a probe...
Args:
name (optinal): name of probe, if not provided take name of function
settings (optinal): a Parameter object that contains all the information needed in the script
"""
assert isinstance(instrument, Instrument)
assert isinstance(probe_name, str)
assert probe_name in instrument._PROBES
if name is None:
name = probe_name
assert isinstance(name, str)
if info is None:
info = ''
assert isinstance(info, str)
self.name = name
self.info = info
self.instrument = instrument
self.probe_name = probe_name
self.buffer = deque(maxlen = buffer_length)
@property
def value(self):
"""
reads the value from the instrument
"""
value = getattr(self.instrument, self.probe_name)
self.buffer.append(value)
return value
def __str__(self):
output_string = '{:s} (class type: {:s})\n'.format(self.name, self.__class__.__name__)
return output_string
@property
def name(self):
return self._name
@name.setter
def name(self, value):
assert isinstance(value, str)
self._name = value
def plot(self, axes):
axes.plot(self.buffer)
axes.hold(False)
def to_dict(self):
"""
Returns: itself as a dictionary
"""
# dictator = {self.name: {'probe_name': self.probe_name, 'instrument_name': self.instrument.name}}
dictator = {self.instrument.name: self.probe_name}
return dictator
def save(self, filename):
"""
save the instrument to path as a .b26 file
Args:
filename: path of file
"""
save_b26_file( filename, probes=self.to_dict())
@staticmethod
def load_and_append(probe_dict, probes, instruments={}):
"""
load probes from probe_dict and append to probes, if additional instruments are required create them and add them to instruments
Args:
probe_dict: dictionary of form
probe_dict = {
instrument1_name : probe1_of_instrument1, probe2_of_instrument1, ...
instrument2_name : probe1_of_instrument2, probe2_of_instrument2, ...
}
where probe1_of_instrument1 is a valid name of a probe in instrument of class instrument1_name
# optional arguments (as key value pairs):
# probe_name
# instrument_name
# probe_info
# buffer_length
#
#
# or
# probe_dict = {
# name_of_probe_1 : instrument_class_1
# name_of_probe_2 : instrument_class_2
# ...
# }
probes: dictionary of form
probe_dict = {
instrument1_name:
{name_of_probe_1_of_instrument1 : probe_1_instance,
name_of_probe_2_instrument1 : probe_2_instance
}
, ...}
instruments: dictionary of form
instruments = {
name_of_instrument_1 : instance_of_instrument_1,
name_of_instrument_2 : instance_of_instrument_2,
...
}
Returns:
updated_probes = { name_of_probe_1 : probe_1_instance, name_of_probe_2 : probe_2_instance, ...}
loaded_failed = {name_of_probe_1: exception_1, name_of_probe_2: exception_2, ....}
updated_instruments
"""
loaded_failed = {}
updated_probes = {}
updated_probes.update(probes)
updated_instruments = {}
updated_instruments.update(instruments)
# ===== load new instruments =======
new_instruments = list(set(probe_dict.keys())-set(probes.keys()))
if new_instruments != []:
updated_instruments, failed = Instrument.load_and_append({instrument_name: instrument_name for instrument_name in new_instruments}, instruments)
if failed != []:
# if loading an instrument fails all the probes that depend on that instrument also fail
# ignore the failed instrument that did exist already because they failed because they did exist
for failed_instrument in set(failed) - set(instruments.keys()):
for probe_name in probe_dict[failed_instrument]:
loaded_failed[probe_name] = ValueError('failed to load instrument {:s} already exists. Did not load!'.format(failed_instrument))
del probe_dict[failed_instrument]
# ===== now we are sure that all the instruments that we need for the probes already exist
for instrument_name, probe_names in probe_dict.items():
if not instrument_name in updated_probes:
updated_probes.update({instrument_name:{}})
for probe_name in probe_names.split(','):
if probe_name in updated_probes[instrument_name]:
loaded_failed[probe_name] = ValueError('failed to load probe {:s} already exists. Did not load!'.format(probe_name))
else:
probe_instance = Probe(updated_instruments[instrument_name], probe_name)
updated_probes[instrument_name].update({probe_name: probe_instance})
return updated_probes, loaded_failed, updated_instruments
|
class Probe(object):
def __init__(self, instrument, probe_name, name = None, info = None, buffer_length = 100):
'''
creates a probe...
Args:
name (optinal): name of probe, if not provided take name of function
settings (optinal): a Parameter object that contains all the information needed in the script
'''
pass
@property
def value(self):
'''
reads the value from the instrument
'''
pass
def __str__(self):
pass
@property
def name(self):
pass
@name.setter
def name(self):
pass
def plot(self, axes):
pass
def to_dict(self):
'''
Returns: itself as a dictionary
'''
pass
def save(self, filename):
'''
save the instrument to path as a .b26 file
Args:
filename: path of file
'''
pass
@staticmethod
def load_and_append(probe_dict, probes, instruments={}):
'''
load probes from probe_dict and append to probes, if additional instruments are required create them and add them to instruments
Args:
probe_dict: dictionary of form
probe_dict = {
instrument1_name : probe1_of_instrument1, probe2_of_instrument1, ...
instrument2_name : probe1_of_instrument2, probe2_of_instrument2, ...
}
where probe1_of_instrument1 is a valid name of a probe in instrument of class instrument1_name
# optional arguments (as key value pairs):
# probe_name
# instrument_name
# probe_info
# buffer_length
#
#
# or
# probe_dict = {
# name_of_probe_1 : instrument_class_1
# name_of_probe_2 : instrument_class_2
# ...
# }
probes: dictionary of form
probe_dict = {
instrument1_name:
{name_of_probe_1_of_instrument1 : probe_1_instance,
name_of_probe_2_instrument1 : probe_2_instance
}
, ...}
instruments: dictionary of form
instruments = {
name_of_instrument_1 : instance_of_instrument_1,
name_of_instrument_2 : instance_of_instrument_2,
...
}
Returns:
updated_probes = { name_of_probe_1 : probe_1_instance, name_of_probe_2 : probe_2_instance, ...}
loaded_failed = {name_of_probe_1: exception_1, name_of_probe_2: exception_2, ....}
updated_instruments
'''
pass
| 14 | 5 | 17 | 4 | 7 | 7 | 2 | 0.97 | 1 | 5 | 1 | 0 | 8 | 5 | 9 | 9 | 168 | 42 | 64 | 31 | 50 | 62 | 59 | 27 | 49 | 9 | 1 | 4 | 19 |
144,557 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/scripts/script_dummy.py
|
scripts.script_dummy.ScriptDummy
|
class ScriptDummy(Script):
"""
Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.
"""
_DEFAULT_SETTINGS = [
Parameter('count', 3, int),
Parameter('name', 'this is a counter'),
Parameter('wait_time', 0.1, float),
Parameter('point2',
[Parameter('x', 0.1, float, 'x-coordinate'),
Parameter('y', 0.1, float, 'y-coordinate')
]),
Parameter('plot_style', 'main', ['main', 'aux', '2D', 'two'])
]
_INSTRUMENTS = {}
_SCRIPTS = {}
def __init__(self, name=None, settings=None, log_function = None, data_path = None):
"""
Example of a script
Args:
name (optional): name of script, if empty same as class name
settings (optional): settings for this script, if empty same as default settings
"""
Script.__init__(self, name, settings, log_function= log_function, data_path = data_path)
def _function(self):
"""
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
"""
# some generic function
import time
import random
self.data['random data'] = None
self.data['image data'] = None
count = self.settings['count']
name = self.settings['name']
wait_time = self.settings['wait_time']
data = []
self.log('I ({:s}) am a test function counting to {:d} and creating random values'.format(self.name, count))
for i in range(count):
time.sleep(wait_time)
self.log('{:s} count {:02d}'.format(self.name, i))
data.append(random.random())
self.data = {'random data': data}
self.progress = 100. * (i + 1) / count
self.updateProgress.emit(self.progress)
self.data = {'random data':data}
# create image data
Nx = int(np.sqrt(len(self.data['random data'])))
img = np.array(self.data['random data'][0:Nx ** 2])
img = img.reshape((Nx, Nx))
self.data.update({'image data': img})
def _plot(self, axes_list, data = None):
"""
plots the data only the axes objects that are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
data: data to be plotted if empty take self.data
Returns: None
"""
plot_type = self.settings['plot_style']
if data is None:
data = self.data
if data is not None and data is not {}:
if plot_type in ('main', 'two'):
if not data['random data'] is None:
axes_list[0].plot(data['random data'])
axes_list[0].hold(False)
if plot_type in ('aux', 'two', '2D'):
if not data['random data'] is None:
axes_list[1].plot(data['random data'])
axes_list[1].hold(False)
if plot_type == '2D':
if 'image data' in data and not data['image data'] is None:
fig = axes_list[0].get_figure()
implot = axes_list[0].imshow(data['image data'], cmap='pink', interpolation="nearest", extent=[-1,1,1,-1])
fig.colorbar(implot, label='kcounts/sec')
def _update(self, axes_list):
"""
updates the data in already existing plots. the axes objects are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
Returns: None
"""
plot_type = self.settings['plot_style']
if plot_type == '2D':
# we expect exactely one image in the axes object (see ScriptDummy.plot)
implot = axes_list[1].get_images()[0]
# now update the data
implot.set_data(self.data['random data'])
colorbar = implot.colorbar
if not colorbar is None:
colorbar.update_bruteforce(implot)
else:
# fall back to default behaviour
Script._update(self, axes_list)
|
class ScriptDummy(Script):
'''
Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.
'''
def __init__(self, name=None, settings=None, log_function = None, data_path = None):
'''
Example of a script
Args:
name (optional): name of script, if empty same as class name
settings (optional): settings for this script, if empty same as default settings
'''
pass
def _function(self):
'''
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
'''
pass
def _plot(self, axes_list, data = None):
'''
plots the data only the axes objects that are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
data: data to be plotted if empty take self.data
Returns: None
'''
pass
def _update(self, axes_list):
'''
updates the data in already existing plots. the axes objects are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
Returns: None
'''
pass
| 5 | 5 | 24 | 4 | 13 | 7 | 4 | 0.48 | 1 | 2 | 0 | 0 | 4 | 2 | 4 | 53 | 119 | 23 | 65 | 25 | 58 | 31 | 55 | 25 | 48 | 9 | 2 | 3 | 15 |
144,558 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/scripts/script_dummy.py
|
scripts.script_dummy.ScriptDummyWrapper
|
class ScriptDummyWrapper(Script):
"""
Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.
"""
_DEFAULT_SETTINGS = []
_INSTRUMENTS = {}
_SCRIPTS = {'ScriptDummy': ScriptDummy}
def __init__(self, instruments = None, scripts = None, name=None, settings=None, log_function = None, data_path = None):
"""
Example of a script
Args:
name (optional): name of script, if empty same as class name
settings (optional): settings for this script, if empty same as default settings
"""
super(ScriptDummyWrapper, self).__init__(self, name, settings, log_function= log_function, data_path=data_path)
def _function(self):
"""
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
"""
self.scripts['ScriptDummy'].run()
def _plot(self, axes_list, data = None):
"""
plots the data only the axes objects that are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
data: data to be plotted if empty take self.data
Returns: None
"""
self.scripts['ScriptDummy']._plot(axes_list)
def _update(self, axes_list):
"""
updates the data in already existing plots. the axes objects are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
Returns: None
"""
self.scripts['ScriptDummy']._update(axes_list)
|
class ScriptDummyWrapper(Script):
'''
Example Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.
'''
def __init__(self, instruments = None, scripts = None, name=None, settings=None, log_function = None, data_path = None):
'''
Example of a script
Args:
name (optional): name of script, if empty same as class name
settings (optional): settings for this script, if empty same as default settings
'''
pass
def _function(self):
'''
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
'''
pass
def _plot(self, axes_list, data = None):
'''
plots the data only the axes objects that are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
data: data to be plotted if empty take self.data
Returns: None
'''
pass
def _update(self, axes_list):
'''
updates the data in already existing plots. the axes objects are provided in axes_list
Args:
axes_list: a list of axes objects, this should be implemented in each subscript
Returns: None
'''
pass
| 5 | 5 | 9 | 1 | 2 | 6 | 1 | 2.17 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 53 | 50 | 12 | 12 | 8 | 7 | 26 | 12 | 8 | 7 | 1 | 2 | 0 | 4 |
144,559 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/scripts/select_points.py
|
pylabcontrol.scripts.select_points.SelectPoints
|
class SelectPoints(Script):
"""
Script to select points on an image. The selected points are saved and can be used in a superscript to iterate over.
"""
_DEFAULT_SETTINGS = [
Parameter('patch_size', 0.003),
Parameter('type', 'free', ['free', 'square', 'line', 'ring', 'arc']),
Parameter('Nx', 5, int, 'number of points along x (type: square) along line (type: line)'),
Parameter('Ny', 5, int, 'number of points along y (type: square)'),
Parameter('randomize', False, bool, 'Determines if points should be randomized')
]
_INSTRUMENTS = {}
_SCRIPTS = {}
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None):
"""
Select points by clicking on an image
"""
Script.__init__(self, name, settings = settings, instruments = instruments, scripts = scripts, log_function= log_function, data_path = data_path)
self.text = []
self.patch_collection = None
self.plot_settings = {}
def _function(self):
"""
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
"""
self.data = {'nv_locations': [], 'image_data': None, 'extent': None}
self.progress = 50
self.updateProgress.emit(self.progress)
# keep script alive while NVs are selected
while not self._abort:
time.sleep(1)
def plot(self, figure_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
# if there is not image data get it from the current plot
if not self.data == {} and self.data['image_data'] is None:
axes = figure_list[0].axes[0]
if len(axes.images)>0:
self.data['image_data'] = np.array(axes.images[0].get_array())
self.data['extent'] = np.array(axes.images[0].get_extent())
self.plot_settings['cmap'] = axes.images[0].get_cmap().name
self.plot_settings['xlabel'] = axes.get_xlabel()
self.plot_settings['ylabel'] = axes.get_ylabel()
self.plot_settings['title'] = axes.get_title()
self.plot_settings['interpol'] = axes.images[0].get_interpolation()
Script.plot(self, figure_list)
#must be passed figure with galvo plot on first axis
def _plot(self, axes_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
axes = axes_list[0]
if self.plot_settings:
axes.imshow(self.data['image_data'], cmap=self.plot_settings['cmap'], interpolation=self.plot_settings['interpol'], extent=self.data['extent'])
axes.set_xlabel(self.plot_settings['xlabel'])
axes.set_ylabel(self.plot_settings['ylabel'])
axes.set_title(self.plot_settings['title'])
self._update(axes_list)
def _update(self, axes_list):
#note: may be able to use blit to make things faster
axes = axes_list[0]
patch_size = self.settings['patch_size']
# first clear all old patches (circles and numbers), then redraw all
if self.patch_collection:
try:
self.patch_collection.remove()
for text in self.text:
text.remove()
except ValueError:
pass
patch_list = []
if(self.data['nv_locations'] is not None):
for index, pt in enumerate(self.data['nv_locations']):
circ = patches.Circle((pt[0], pt[1]), patch_size, fc='b')
patch_list.append(circ)
#cap number of drawn numbers at 400 since drawing text is extremely slow and they're all so close together
#as to be unreadable anyways
if len(self.data['nv_locations']) <= 400:
text = axes.text(pt[0], pt[1], '{:d}'.format(index),
horizontalalignment='center',
verticalalignment='center',
color='white'
)
self.text.append(text)
#patch collection used here instead of adding individual patches for speed
self.patch_collection = matplotlib.collections.PatchCollection(patch_list)
axes.add_collection(self.patch_collection)
def toggle_NV(self, pt):
'''
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If
there is, removes that point from the selected list.
Args:
pt: the point to add or remove from the selected list
Poststate: updates selected list
'''
if not self.data['nv_locations']: #if self.data is empty so this is the first point
self.data['nv_locations'].append(pt)
self.data['image_data'] = None # clear image data
else:
# use KDTree to find NV closest to mouse click
tree = scipy.spatial.KDTree(self.data['nv_locations'])
#does a search with k=1, that is a search for the nearest neighbor, within distance_upper_bound
d, i = tree.query(pt,k = 1, distance_upper_bound = self.settings['patch_size'])
# removes NV if previously selected
if d is not np.inf:
self.data['nv_locations'].pop(i)
# adds NV if not previously selected
else:
self.data['nv_locations'].append(pt)
# randomize
if self.settings['randomize']:
self.log('warning! randomize not avalable when manually selecting points')
# if type is not free we calculate the total points of locations from the first selected points
if self.settings['type'] == 'square' and len(self.data['nv_locations'])>1:
# here we create a rectangular grid, where pts a and be define the top left and bottom right corner of the rectangle
Nx, Ny = self.settings['Nx'], self.settings['Ny']
pta = self.data['nv_locations'][0]
ptb = self.data['nv_locations'][1]
tmp = np.array([[[pta[0] + 1.0*i*(ptb[0]-pta[0])/(Nx-1), pta[1] + 1.0*j*(ptb[1]-pta[1])/(Ny-1)] for i in range(Nx)] for j in range(Ny)])
nv_pts = np.reshape(tmp, (Nx * Ny, 2))
# randomize
if self.settings['randomize']:
random.shuffle(nv_pts) # shuffles in place
self.data['nv_locations'] = nv_pts
self.stop()
elif self.settings['type'] == 'line' and len(self.data['nv_locations'])>1:
# here we create a straight line between points a and b
N = self.settings['Nx']
pta = self.data['nv_locations'][0]
ptb = self.data['nv_locations'][1]
nv_pts = [np.array([pta[0] + 1.0*i*(ptb[0]-pta[0])/(N-1), pta[1] + 1.0*i*(ptb[1]-pta[1])/(N-1)]) for i in range(N)]
# randomize
if self.settings['randomize']:
random.shuffle(nv_pts) # shuffles in place
self.data['nv_locations'] = nv_pts
self.stop()
elif self.settings['type'] == 'ring' and len(self.data['nv_locations'])>1:
# here we create a circular grid, where pts a and be define the center and the outermost ring
Nx, Ny = self.settings['Nx'], self.settings['Ny']
pt_center = self.data['nv_locations'][0] # center
pt_outer = self.data['nv_locations'][1] # outermost ring
# radius of outermost ring:
rmax = np.sqrt((pt_center[0] - pt_outer[0]) ** 2 + (pt_center[1] - pt_outer[1]) ** 2)
# angles
angles = np.linspace(0, 2 * np.pi, Nx+1)[0:-1]
# create points on rings
nv_pts = []
for r in np.linspace(rmax, 0, Ny + 1)[0:-1]:
for theta in angles:
nv_pts += [[r * np.sin(theta)+pt_center[0], r * np.cos(theta)+pt_center[1]]]
# randomize
if self.settings['randomize']:
coarray = list(zip(nv_pts, angles))
random.shuffle(coarray) # shuffles in place
nv_pts, angles = zip(*coarray)
self.data['nv_locations'] = np.array(nv_pts)
self.data['angles'] = np.array(angles)* 180 / np.pi
self.data['ring_data'] = [pt_center, pt_outer]
self.stop()
elif self.settings['type'] == 'arc' and len(self.data['nv_locations']) > 3:
# here we create a circular grid, where pts a and be define the center and the outermost ring
Nx, Ny = self.settings['Nx'], self.settings['Ny']
pt_center = self.data['nv_locations'][0] # center
pt_start = self.data['nv_locations'][1] # arc point one (radius)
pt_dir = self.data['nv_locations'][2] # arc point two (direction)
pt_end = self.data['nv_locations'][3] # arc point three (angle)
# radius of outermost ring:
rmax = np.sqrt((pt_center[0] - pt_start[0]) ** 2 + (pt_center[1] - pt_start[1]) ** 2)
angle_start = np.arctan((pt_start[1] - pt_center[1]) / (pt_start[0] - pt_center[0]))
# arctan always returns between -pi/2 and pi/2, so adjust to allow full range of angles
if ((pt_start[0] - pt_center[0]) < 0):
angle_start += np.pi
angle_end = np.arctan((pt_end[1] - pt_center[1]) / (pt_end[0] - pt_center[0]))
# arctan always returns between -pi/2 and pi/2, so adjust to allow full range of angles
if ((pt_end[0] - pt_center[0]) < 0):
angle_end += np.pi
if pt_dir[0] < pt_start[0]:
# counter-clockwise: invert the order of the angles
angle_start, angle_end = angle_end, angle_start
if angle_start > angle_end:
# make sure that start is the smaller
# (e.g. angle_start= 180 deg and angle_end =10, we want to got from 180 to 370 deg)
angle_end += 2 * np.pi
# create points on arcs
nv_pts = []
for r in np.linspace(rmax, 0, Ny + 1)[0:-1]:
for theta in np.linspace(angle_start, angle_end, Nx, endpoint=True):
nv_pts += [[r * np.cos(theta) + pt_center[0], r * np.sin(theta) + pt_center[1]]]
# randomize
if self.settings['randomize']:
coarray = list(zip(nv_pts, np.linspace(angle_start, angle_end, Nx, endpoint=True)))
random.shuffle(coarray) # shuffles in place
nv_pts, angles = zip(*coarray)
else:
angles = np.linspace(angle_start, angle_end, Nx, endpoint=True)
self.data['nv_locations'] = np.array(nv_pts)
self.data['arc_data'] = [pt_center, pt_start, pt_end]
self.data['angles'] = np.array(angles) * 180 / np.pi
self.stop()
|
class SelectPoints(Script):
'''
Script to select points on an image. The selected points are saved and can be used in a superscript to iterate over.
'''
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None):
'''
Select points by clicking on an image
'''
pass
def _function(self):
'''
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
'''
pass
def plot(self, figure_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
pass
def _plot(self, axes_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
pass
def _update(self, axes_list):
pass
def toggle_NV(self, pt):
'''
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If
there is, removes that point from the selected list.
Args:
pt: the point to add or remove from the selected list
Poststate: updates selected list
'''
pass
| 7 | 6 | 36 | 4 | 23 | 12 | 6 | 0.51 | 1 | 5 | 0 | 0 | 6 | 5 | 6 | 55 | 230 | 22 | 146 | 43 | 139 | 74 | 130 | 43 | 123 | 20 | 2 | 3 | 35 |
144,560 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/scripts/script_wait.py
|
scripts.script_wait.Wait
|
class Wait(Script):
"""
Script that waits. This is useful to execute scripts in a loop at given intervals.
There are two modes of operation:
wait_mode = absolute: the script waits the time defined in wait_time
wait_mode = loop_interval: the script waits as long such that the loop time equals the time defined in wait_time
"""
_DEFAULT_SETTINGS = [
Parameter('wait_time', 1.0, float, 'time to wait in seconds'),
Parameter('wait_mode', 'absolute', ['absolute', 'loop_interval'], 'absolute: wait for wait_time, loop_interval: wait such that this script is executed every wait_time')
]
_INSTRUMENTS = {}
_SCRIPTS = {}
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None):
"""
Select points by clicking on an image
"""
Script.__init__(self, name, settings = settings, instruments = instruments, scripts = scripts, log_function= log_function, data_path = data_path)
self.last_execution = None
def _function(self):
"""
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
"""
start_time = datetime.datetime.now()
# calculate stop time
if self.settings['wait_mode'] == 'absolute':
stop_time = start_time + datetime.timedelta(seconds= self.settings['wait_time'])
elif self.settings['wait_mode'] == 'loop_interval':
if self.last_execution is None:
stop_time = start_time
else:
loop_time = start_time - self.last_execution
wait_time = datetime.timedelta(seconds= self.settings['wait_time'])
if wait_time.total_seconds() <0:
stop_time = start_time
else:
stop_time = start_time + wait_time
else:
TypeError('unknown wait_mode')
current_time = start_time
while current_time<stop_time:
if self._abort:
break
current_time = datetime.datetime.now()
time.sleep(1)
self.progress = 100.*(current_time- start_time).total_seconds() / (stop_time - start_time).total_seconds()
self.updateProgress.emit(int(self.progress))
if self.settings['wait_mode'] == 'absolute':
self.last_execution = None
else:
self.last_execution = start_time
|
class Wait(Script):
'''
Script that waits. This is useful to execute scripts in a loop at given intervals.
There are two modes of operation:
wait_mode = absolute: the script waits the time defined in wait_time
wait_mode = loop_interval: the script waits as long such that the loop time equals the time defined in wait_time
'''
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None):
'''
Select points by clicking on an image
'''
pass
def _function(self):
'''
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
'''
pass
| 3 | 3 | 23 | 4 | 16 | 4 | 5 | 0.34 | 1 | 4 | 0 | 0 | 2 | 2 | 2 | 51 | 61 | 10 | 38 | 13 | 35 | 13 | 30 | 13 | 27 | 8 | 2 | 3 | 9 |
144,561 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/load_dialog_probes.py
|
pylabcontrol.gui.windows_and_widgets.load_dialog_probes.LoadDialogProbes
|
class LoadDialogProbes(QDialog, Ui_Dialog):
"""
LoadDialog(intruments, scripts, probes)
- type: either script, instrument or probe
- loaded_elements: dictionary that contains the loaded elements
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
"""
def __init__(self, probes_old={}, filename=None):
super(LoadDialogProbes, self).__init__()
self.setupUi(self)
if filename is None:
filename = ''
self.txt_probe_log_path.setText(filename)
# create models for tree structures, the models reflect the data
self.tree_infile_model = QtGui.QStandardItemModel()
self.tree_infile.setModel(self.tree_infile_model)
QtGui.QStandardItemModel().reset()
self.tree_infile_model.setHorizontalHeaderLabels(['Instrument', 'Probe'])
self.tree_loaded_model = QtGui.QStandardItemModel()
self.tree_loaded.setModel(self.tree_loaded_model)
self.tree_loaded_model.setHorizontalHeaderLabels(['Instrument', 'Probe'])
# connect the buttons
self.btn_open.clicked.connect(self.open_file_dialog)
# create the dictionaries that hold the data
# - elements_old: the old elements (scripts, instruments) that have been passed to the dialog
# - elements_from_file: the elements from the file that had been opened
print(('adsada', probes_old))
self.elements_selected = {}
for instrument_name, p in probes_old.items():
self.elements_selected.update( {instrument_name: ','.join(list(p.keys()))})
if os.path.isfile(filename):
self.elements_from_file = self.load_elements(filename)
else:
self.elements_from_file = {}
# fill trees with the data
self.fill_tree(self.tree_loaded, self.elements_selected)
self.fill_tree(self.tree_infile, self.elements_from_file)
self.tree_infile.selectionModel().selectionChanged.connect(self.show_info)
self.tree_loaded.selectionModel().selectionChanged.connect(self.show_info)
self.tree_infile_model.itemChanged.connect(self.item_dragged_and_dropped)
self.tree_loaded_model.itemChanged.connect(self.item_dragged_and_dropped)
def item_dragged_and_dropped(self):
"""
adds and removes probes from the trees when they are dragged and dropped
"""
index = None
self.tree_infile_model.itemChanged.disconnect()
self.tree_loaded_model.itemChanged.disconnect()
index_infile = self.tree_infile.selectedIndexes()
index_loaded = self.tree_loaded.selectedIndexes()
if index_infile != []:
index = index_infile[0]
dict_target = self.elements_selected
dict_source = self.elements_from_file
elif index_loaded != []:
index = index_loaded[0]
dict_source = self.elements_selected
dict_target= self.elements_from_file
if index is not None:
parent = index.model().itemFromIndex(index).parent()
if parent is None:
instrument_name = str(index.model().itemFromIndex(index).text())
probe_names = [str(index.model().itemFromIndex(index).child(i).text()) for i in range(index.model().itemFromIndex(index).rowCount())]
else:
instrument_name = str(parent.text())
probe_names = [str(index.model().itemFromIndex(index).text())]
if not instrument_name in list(dict_target.keys()):
dict_target.update({instrument_name: ','.join(probe_names)})
dict_source[instrument_name] = ','.join(set(dict_source[instrument_name].split(',')) - set(probe_names))
else:
dict_target[instrument_name] = ','.join(set(dict_target[instrument_name].split(',') + probe_names))
dict_source[instrument_name] = ','.join(set(dict_source[instrument_name].split(',')) - set(probe_names))
if instrument_name in dict_source and dict_source[instrument_name] == '':
del dict_source[instrument_name]
if instrument_name in dict_target and dict_target[instrument_name] == '':
del dict_target[instrument_name]
else:
# this case should never happen but if it does raise an error
raise TypeError
self.fill_tree(self.tree_loaded, self.elements_selected)
self.fill_tree(self.tree_infile, self.elements_from_file)
self.tree_infile_model.itemChanged.connect(self.item_dragged_and_dropped)
self.tree_loaded_model.itemChanged.connect(self.item_dragged_and_dropped)
def show_info(self):
"""
displays the doc string of the selected element
"""
sender = self.sender()
tree = sender.parent()
index = tree.selectedIndexes()
info = ''
if index != []:
index = index[0]
name = str(index.model().itemFromIndex(index).text())
if name in set(list(self.elements_from_file.keys()) + list(self.elements_selected.keys())):
probe_name = None
instrument_name = name
else:
instrument_name = str(index.model().itemFromIndex(index).parent().text())
probe_name = name
module = __import__('pylabcontrol.instruments', fromlist=[instrument_name])
if probe_name is None:
info = getattr(module, instrument_name).__doc__
else:
if probe_name in list(getattr(module, instrument_name)._PROBES.keys()):
info = getattr(module, instrument_name)._PROBES[probe_name]
if info is not None:
self.lbl_info.setText(info)
def open_file_dialog(self):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtGui.QFileDialog
filename = dialog.getOpenFileName(self, 'Select a file:', self.txt_probe_log_path.text())
if str(filename)!='':
self.txt_probe_log_path.setText(filename)
# load elements from file and display in tree
elements_from_file = self.load_elements(filename)
self.fill_tree(self.tree_infile, elements_from_file)
# append new elements to internal dictionary
self.elements_from_file.update(elements_from_file)
def load_elements(self, filename):
"""
loads the elements from file filename
"""
input_data = load_b26_file(filename)
if isinstance(input_data, dict) and 'probes' in input_data:
return input_data['probes']
else:
return {}
def fill_tree(self, tree, input_dict):
"""
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns:
"""
def removeAll(tree):
if tree.model().rowCount() > 0:
for i in range(0, tree.model().rowCount()):
item = tree.model().item(i)
del item
tree.model().removeRows(0, tree.model().rowCount())
tree.model().reset()
def add_probe(tree, instrument, probes):
item = QtGui.QStandardItem(instrument)
item.setEditable(False)
for probe in probes.split(','):
child_name = QtGui.QStandardItem(probe)
child_name.setDragEnabled(True)
child_name.setSelectable(True)
child_name.setEditable(False)
item.appendRow(child_name)
tree.model().appendRow(item)
removeAll(tree)
for index, (instrument, probes) in enumerate(input_dict.items()):
add_probe(tree, instrument, probes)
# tree.setFirstColumnSpanned(index, self.tree_infile.rootIndex(), True)
tree.expandAll()
def getValues(self):
"""
Returns: the selected elements
"""
print(('self.elements_selected', self.elements_selected))
return self.elements_selected
|
class LoadDialogProbes(QDialog, Ui_Dialog):
'''
LoadDialog(intruments, scripts, probes)
- type: either script, instrument or probe
- loaded_elements: dictionary that contains the loaded elements
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
'''
def __init__(self, probes_old={}, filename=None):
pass
def item_dragged_and_dropped(self):
'''
adds and removes probes from the trees when they are dragged and dropped
'''
pass
def show_info(self):
'''
displays the doc string of the selected element
'''
pass
def open_file_dialog(self):
'''
opens a file dialog to get the path to a file and
'''
pass
def load_elements(self, filename):
'''
loads the elements from file filename
'''
pass
def fill_tree(self, tree, input_dict):
'''
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns:
'''
pass
def removeAll(tree):
pass
def add_probe(tree, instrument, probes):
pass
def getValues(self):
'''
Returns: the selected elements
'''
pass
| 10 | 7 | 23 | 4 | 16 | 4 | 3 | 0.31 | 2 | 8 | 0 | 0 | 7 | 4 | 7 | 7 | 207 | 39 | 128 | 41 | 118 | 40 | 120 | 41 | 110 | 8 | 1 | 3 | 30 |
144,562 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/load_dialog.py
|
pylabcontrol.gui.windows_and_widgets.load_dialog.LoadDialog
|
class LoadDialog(QDialog, Ui_Dialog):
"""
LoadDialog(intruments, scripts, probes)
- type: either script, instrument or probe
- loaded_elements: dictionary that contains the loaded elements
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
"""
def __init__(self, elements_type, elements_old=None, filename=''):
super(LoadDialog, self).__init__()
self.setupUi(self)
self.elements_type = elements_type
self.txt_probe_log_path.setText(filename)
# create models for tree structures, the models reflect the data
self.tree_infile_model = QtGui.QStandardItemModel()
self.tree_infile.setModel(self.tree_infile_model)
self.tree_infile_model.setHorizontalHeaderLabels([self.elements_type, 'Value'])
self.tree_loaded_model = QtGui.QStandardItemModel()
self.tree_loaded.setModel(self.tree_loaded_model)
self.tree_loaded_model.setHorizontalHeaderLabels([self.elements_type, 'Value'])
self.tree_script_sequence_model = QtGui.QStandardItemModel()
self.tree_script_sequence.setModel(self.tree_script_sequence_model)
self.tree_script_sequence_model.setHorizontalHeaderLabels([self.elements_type, 'Value'])
# connect the buttons
self.btn_open.clicked.connect(self.open_file_dialog)
self.btn_script_sequence.clicked.connect(self.add_script_sequence)
# create the dictionaries that hold the data
# - elements_old: the old elements (scripts, instruments) that have been passed to the dialog
# - elements_from_file: the elements from the file that had been opened
if elements_old is None:
self.elements_old = {}
else:
self.elements_old = elements_old
self.elements_selected = {}
for element_name, element in self.elements_old.items():
self.elements_selected.update( {element_name: {'class': element.__class__.__name__ , 'settings':element.settings}})
if os.path.isfile(filename):
self.elements_from_file = self.load_elements(filename)
else:
self.elements_from_file = {}
# fill trees with the data
self.fill_tree(self.tree_loaded, self.elements_selected)
self.fill_tree(self.tree_infile, self.elements_from_file)
self.tree_infile.selectionModel().selectionChanged.connect(self.show_info)
self.tree_loaded.selectionModel().selectionChanged.connect(self.show_info)
self.tree_script_sequence.selectionModel().selectionChanged.connect(self.show_info)
self.tree_infile.selectionModel().selectionChanged.connect(self.show_info)
self.tree_infile_model.itemChanged.connect(self.name_changed)
self.tree_loaded_model.itemChanged.connect(self.name_changed)
self.cmb_looping_variable.addItems(['Loop', 'Parameter Sweep'])
def name_changed(self, changed_item):
"""
checks if name has been changed and ignores the name change if the changed_item is an existing script
Args:
changed_item:
"""
name = str(changed_item.text())
# if the item has been moved we ignore this because the item only went from one tree to the other without changing names
if name != '':
if name != self.selected_element_name:
self.elements_from_file[name] = self.elements_from_file[self.selected_element_name]
del self.elements_from_file[self.selected_element_name]
self.selected_element_name = name
def show_info(self):
"""
displays the doc string of the selected element
"""
sender = self.sender()
tree = sender.parent()
index = tree.selectedIndexes()
info = ''
if index != []:
index = index[0]
name = str(index.model().itemFromIndex(index).text())
self.selected_element_name = name
if name in self.elements_old:
info = self.elements_old[name].__doc__
#TODO: check if this is portable
elif name in self.elements_from_file:
class_name = self.elements_from_file[name]['class']
if 'filepath' in self.elements_from_file[name]:
filepath = self.elements_from_file[name]['filepath']
if 'info' in self.elements_from_file[name]:
info = self.elements_from_file[name]['info']
#
# path_to_src_scripts = filepath[:filepath.find('\\pylabcontrol\\scripts\\')]
# module_name = path_to_src_scripts[path_to_src_scripts.rfind('\\')+1:]
# module = __import__('{:s}.pylabcontrol.{:s}'.format(module_name, self.elements_type), fromlist=[class_name])
# info = getattr(module, class_name).__doc__
if info is None:
info = name
if tree == self.tree_infile:
self.lbl_info.setText(info)
self.tree_loaded.clearSelection()
elif tree == self.tree_loaded:
self.lbl_info.setText(info)
self.tree_infile.clearSelection()
def open_file_dialog(self):
"""
opens a file dialog to get the path to a file and
"""
dialog = QtWidgets.QFileDialog
filename, _ = dialog.getOpenFileName(self, 'Select a file:', self.txt_probe_log_path.text())
if str(filename) != '':
self.txt_probe_log_path.setText(filename)
# load elements from file and display in tree
elements_from_file = self.load_elements(filename)
self.fill_tree(self.tree_infile, elements_from_file)
# append new elements to internal dictionary
self.elements_from_file.update(elements_from_file)
def load_elements(self, filename):
"""
loads the elements from file filename
"""
input_data = load_b26_file(filename)
if isinstance(input_data, dict) and self.elements_type in input_data:
return input_data[self.elements_type]
else:
return {}
def fill_tree(self, tree, input_dict):
"""
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns:
"""
def add_element(item, key, value):
child_name = QtGui.QStandardItem(key)
child_name.setDragEnabled(False)
child_name.setSelectable(False)
child_name.setEditable(False)
if isinstance(value, dict):
for ket_child, value_child in value.items():
add_element(child_name, ket_child, value_child)
child_value = QtGui.QStandardItem('')
else:
child_value = QtGui.QStandardItem(str(value))
child_value.setData(value)
child_value.setDragEnabled(False)
child_value.setSelectable(False)
child_value.setEditable(False)
item.appendRow([child_name, child_value])
for index, (loaded_item, loaded_item_settings) in enumerate(input_dict.items()):
# print(index, loaded_item, loaded_item_settings)
item = QtGui.QStandardItem(loaded_item)
for key, value in loaded_item_settings['settings'].items():
add_element(item, key, value)
value = QtGui.QStandardItem('')
tree.model().appendRow([item, value])
if tree == self.tree_loaded:
item.setEditable(False)
tree.setFirstColumnSpanned(index, self.tree_infile.rootIndex(), True)
def get_values(self):
"""
Returns: the selected instruments
"""
elements_selected = {}
for index in range(self.tree_loaded_model.rowCount()):
element_name = str(self.tree_loaded_model.item(index).text())
if element_name in self.elements_old:
elements_selected.update({element_name: self.elements_old[element_name]})
elif element_name in self.elements_from_file:
elements_selected.update({element_name: self.elements_from_file[element_name]})
return elements_selected
def add_script_sequence(self):
"""
creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree
self.tree_loaded
"""
def empty_tree(tree_model):
# COMMENT_ME
def add_children_to_list(item, somelist):
if item.hasChildren():
for rownum in range(0, item.rowCount()):
somelist.append(str(item.child(rownum, 0).text()))
output_list = []
root = tree_model.invisibleRootItem()
add_children_to_list(root, output_list)
tree_model.clear()
return output_list
name = str(self.txt_script_sequence_name.text())
new_script_list = empty_tree(self.tree_script_sequence_model)
new_script_dict = {}
for script in new_script_list:
if script in self.elements_old:
new_script_dict.update({script: self.elements_old[script]})
elif script in self.elements_from_file:
new_script_dict.update({script: self.elements_from_file[script]})
new_script_parameter_dict = {}
for index, script in enumerate(new_script_list):
new_script_parameter_dict.update({script: index})
# QtGui.QTextEdit.toPlainText()
# get the module of the current dialogue
package = get_python_package(inspect.getmodule(self).__file__)
assert package is not None # check that we actually find a module
# class_name = Script.set_up_dynamic_script(factory_scripts, new_script_parameter_list, self.cmb_looping_variable.currentText() == 'Parameter Sweep')
new_script_dict = {name: {'class': 'ScriptIterator', 'package': package, 'scripts': new_script_dict,
'info': str(self.txt_info.toPlainText()),
'settings': {'script_order': new_script_parameter_dict,
'iterator_type': str(self.cmb_looping_variable.currentText())}}}
self.selected_element_name = name
self.fill_tree(self.tree_loaded, new_script_dict)
self.elements_from_file.update(new_script_dict)
|
class LoadDialog(QDialog, Ui_Dialog):
'''
LoadDialog(intruments, scripts, probes)
- type: either script, instrument or probe
- loaded_elements: dictionary that contains the loaded elements
MainWindow(settings_file)
- settings_file is the path to a json file that contains all the settings for the old_gui
Returns:
'''
def __init__(self, elements_type, elements_old=None, filename=''):
pass
def name_changed(self, changed_item):
'''
checks if name has been changed and ignores the name change if the changed_item is an existing script
Args:
changed_item:
'''
pass
def show_info(self):
'''
displays the doc string of the selected element
'''
pass
def open_file_dialog(self):
'''
opens a file dialog to get the path to a file and
'''
pass
def load_elements(self, filename):
'''
loads the elements from file filename
'''
pass
def fill_tree(self, tree, input_dict):
'''
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView
parameters: dictionary or Parameter object
Returns:
'''
pass
def add_element(item, key, value):
pass
def get_values(self):
'''
Returns: the selected instruments
'''
pass
def add_script_sequence(self):
'''
creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree
self.tree_loaded
'''
pass
def empty_tree(tree_model):
pass
def add_children_to_list(item, somelist):
pass
| 12 | 8 | 25 | 4 | 16 | 5 | 4 | 0.38 | 2 | 5 | 0 | 0 | 8 | 8 | 8 | 8 | 257 | 52 | 149 | 52 | 137 | 57 | 138 | 52 | 126 | 9 | 1 | 3 | 40 |
144,563 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/gui/windows_and_widgets/export_dialog.py
|
pylabcontrol.gui.windows_and_widgets.export_dialog.ExportDialog
|
class ExportDialog(QDialog, Ui_Dialog):
"""
This launches a dialog to allow exporting of scripts to .b26 files.
QDialog, Ui_Dialog: Define the UI and PyQt files to be used to define the dialog box
"""
def __init__(self):
super(ExportDialog, self).__init__()
self.setupUi(self)
# create models for tree structures, the models reflect the data
self.list_script_model = QtGui.QStandardItemModel()
self.list_script.setModel(self.list_script_model)
self.error_array = {}
self.list_script.selectionModel().selectionChanged.connect(self.display_info)
self.cmb_select_type.currentIndexChanged.connect(self.class_type_changed)
#
# # connect the buttons
self.btn_open_source.clicked.connect(self.open_file_dialog)
self.btn_open_target.clicked.connect(self.open_file_dialog)
self.btn_select_all.clicked.connect(self.select_all)
self.btn_select_none.clicked.connect(self.select_none)
self.btn_export.clicked.connect(self.export)
# package = get_python_package(os.getcwd())
# package, path = module_name_from_path(os.getcwd())
# self.source_path.setText(os.path.normpath(os.path.join(path + '\\' + package.split('.')[0] + '\\scripts')))
# self.target_path.setText(os.path.normpath(os.path.join(path + '\\' + package.split('.')[0] + '\\user_data\\scripts_auto_generated')))
# self.reset_avaliable(self.source_path.text())
def open_file_dialog(self):
"""
Opens a file dialog to get the path to a file and put tha tpath in the correct textbox
"""
dialog = QtWidgets.QFileDialog
sender = self.sender()
if sender == self.btn_open_source:
textbox = self.source_path
elif sender == self.btn_open_target:
textbox = self.target_path
folder = dialog.getExistingDirectory(self, 'Select a file:', textbox.text(), options = QtWidgets.QFileDialog.ShowDirsOnly)
if str(folder) != '':
textbox.setText(folder)
# load elements from file and display in tree
if sender == self.btn_open_source:
self.reset_avaliable(folder)
def reset_avaliable(self, folder):
"""
Resets the dialog box by finding all avaliable scripts that can be imported in the input folder
:param folder: folder in which to find scripts
"""
try:
self.list_script_model.removeRows(0, self.list_script_model.rowCount())
if self.cmb_select_type.currentText() == 'Script':
self.avaliable = find_scripts_in_python_files(folder)
elif self.cmb_select_type.currentText() == 'Instrument':
self.avaliable = find_instruments_in_python_files(folder)
sorted_keys = sorted(self.avaliable.keys())
self.fill_list(self.list_script, sorted_keys)
for key in sorted_keys:
self.error_array.update({key: ''})
except Exception:
msg = QtWidgets.QMessageBox()
msg.setText("Unable to parse all of the files in this folder to find possible scripts and instruments. There are non-python files or python files that are unreadable. Please select a folder that contains only pylabcontrol style python files.")
msg.exec_()
def class_type_changed(self):
"""
Forces a reset if the class type is changed from instruments to scripts or vice versa
"""
if self.source_path.text():
self.reset_avaliable(self.source_path.text())
def fill_list(self, list, input_list):
"""
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView to fill
parameters: dictionary or Parameter object which contains the information to use to fill
"""
for name in input_list:
# print(index, loaded_item, loaded_item_settings)
item = QtGui.QStandardItem(name)
item.setSelectable(True)
item.setEditable(False)
list.model().appendRow(item)
def select_none(self):
"""
Clears all selected values
"""
self.list_script.clearSelection()
def select_all(self):
"""
Selects all values
"""
self.list_script.selectAll()
def export(self):
"""
Exports the selected instruments or scripts to .b26 files. If successful, script is highlighted in green. If
failed, script is highlighted in red and error is printed to the error box.
"""
if not self.source_path.text() or not self.target_path.text():
msg = QtWidgets.QMessageBox()
msg.setText("Please set a target path for this export.")
msg.exec_()
return
selected_index = self.list_script.selectedIndexes()
for index in selected_index:
item = self.list_script.model().itemFromIndex(index)
name = str(item.text())
target_path = self.target_path.text()
try:
python_file_to_b26({name: self.avaliable[name]}, target_path, str(self.cmb_select_type.currentText()), raise_errors = True)
self.error_array.update({name: 'export successful!'})
item.setBackground(QtGui.QColor('green'))
except Exception:
self.error_array.update({name: str(traceback.format_exc())})
item.setBackground(QtGui.QColor('red'))
QtWidgets.QApplication.processEvents()
self.list_script.clearSelection()
def display_info(self):
"""
Displays the script info and, if it has been attempted to be exported, the error for a given script. Creates
hyperlinks in the traceback to the appropriate .py files (to be opened in the default .py editor).
"""
sender = self.sender()
somelist = sender.parent()
index = somelist.selectedIndexes()
if index != []:
index = index[-1]
name = str(index.model().itemFromIndex(index).text())
self.text_error.setText(self.error_array[name])
# self.text_error.setText('')
# self.text_error.setOpenExternalLinks(True)
# split_errors = self.error_array[name].split("\"")
# #displays error message with HTML link to file where error occured, which opens in default python editor
# for error in split_errors:
# if error[-3:] == '.py':
# error = error.replace("\\", "/") #format paths to be opened
# # sets up hyperlink error with filepath as displayed text in hyperlink
# # in future, can use anchorClicked signal to call python function when link clicked
# self.text_error.insertHtml("<a href = \"" + error + "\">" + error + "</a>")
# else:
# error = error.replace("\n", "<br>") #format newlines for HTML
# # would like to use insertPlainText here, but this is broken and ends up being inserted as more
# # HTML linked to the previous insertHtml, so need to insert this as HTML instead
# self.text_error.insertHtml(error)
if(self.avaliable[name]['info'] == None):
self.text_info.setText('No information avaliable')
else:
self.text_info.setText(self.avaliable[name]['info'])
|
class ExportDialog(QDialog, Ui_Dialog):
'''
This launches a dialog to allow exporting of scripts to .b26 files.
QDialog, Ui_Dialog: Define the UI and PyQt files to be used to define the dialog box
'''
def __init__(self):
pass
def open_file_dialog(self):
'''
Opens a file dialog to get the path to a file and put tha tpath in the correct textbox
'''
pass
def reset_avaliable(self, folder):
'''
Resets the dialog box by finding all avaliable scripts that can be imported in the input folder
:param folder: folder in which to find scripts
'''
pass
def class_type_changed(self):
'''
Forces a reset if the class type is changed from instruments to scripts or vice versa
'''
pass
def fill_list(self, list, input_list):
'''
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView to fill
parameters: dictionary or Parameter object which contains the information to use to fill
'''
pass
def select_none(self):
'''
Clears all selected values
'''
pass
def select_all(self):
'''
Selects all values
'''
pass
def export(self):
'''
Exports the selected instruments or scripts to .b26 files. If successful, script is highlighted in green. If
failed, script is highlighted in red and error is printed to the error box.
'''
pass
def display_info(self):
'''
Displays the script info and, if it has been attempted to be exported, the error for a given script. Creates
hyperlinks in the traceback to the appropriate .py files (to be opened in the default .py editor).
'''
pass
| 10 | 9 | 16 | 1 | 9 | 6 | 3 | 0.69 | 2 | 3 | 0 | 0 | 9 | 3 | 9 | 9 | 161 | 16 | 86 | 32 | 76 | 59 | 83 | 32 | 73 | 5 | 1 | 2 | 24 |
144,564 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/gui/compiled_ui_files/load_dialog.py
|
pylabcontrol.gui.compiled_ui_files.load_dialog.Ui_Dialog
|
class Ui_Dialog():
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(857, 523)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(509, 476, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.horizontalLayoutWidget = QtWidgets.QWidget(Dialog)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(9, 436, 841, 31))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
self.horizontalLayout.setContentsMargins(1, 4, 0, 4)
self.horizontalLayout.setSpacing(7)
self.horizontalLayout.setObjectName("horizontalLayout")
self.tree_infile = QtWidgets.QTreeView(Dialog)
self.tree_infile.setGeometry(QtCore.QRect(270, 30, 256, 261))
self.tree_infile.setAcceptDrops(True)
self.tree_infile.setDragEnabled(True)
self.tree_infile.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.tree_infile.setDefaultDropAction(QtCore.Qt.MoveAction)
self.tree_infile.setUniformRowHeights(True)
self.tree_infile.setWordWrap(True)
self.tree_infile.setObjectName("tree_infile")
self.tree_loaded = QtWidgets.QTreeView(Dialog)
self.tree_loaded.setGeometry(QtCore.QRect(10, 30, 256, 261))
self.tree_loaded.setAcceptDrops(True)
self.tree_loaded.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.tree_loaded.setFrameShadow(QtWidgets.QFrame.Sunken)
self.tree_loaded.setDragEnabled(True)
self.tree_loaded.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.tree_loaded.setDefaultDropAction(QtCore.Qt.MoveAction)
self.tree_loaded.setWordWrap(True)
self.tree_loaded.setObjectName("tree_loaded")
self.lbl_info = QtWidgets.QLabel(Dialog)
self.lbl_info.setGeometry(QtCore.QRect(540, 30, 311, 261))
self.lbl_info.setFrameShape(QtWidgets.QFrame.Box)
self.lbl_info.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.lbl_info.setWordWrap(True)
self.lbl_info.setObjectName("lbl_info")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(20, 10, 241, 16))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(280, 10, 241, 16))
self.label_2.setObjectName("label_2")
self.btn_open = QtWidgets.QPushButton(Dialog)
self.btn_open.setGeometry(QtCore.QRect(774, 440, 75, 23))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.btn_open.sizePolicy().hasHeightForWidth())
self.btn_open.setSizePolicy(sizePolicy)
self.btn_open.setObjectName("btn_open")
self.lbl_probe_log_path = QtWidgets.QLabel(Dialog)
self.lbl_probe_log_path.setGeometry(QtCore.QRect(10, 440, 22, 23))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lbl_probe_log_path.sizePolicy().hasHeightForWidth())
self.lbl_probe_log_path.setSizePolicy(sizePolicy)
self.lbl_probe_log_path.setObjectName("lbl_probe_log_path")
self.txt_probe_log_path = QtWidgets.QLineEdit(Dialog)
self.txt_probe_log_path.setGeometry(QtCore.QRect(39, 440, 728, 23))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.txt_probe_log_path.sizePolicy().hasHeightForWidth())
self.txt_probe_log_path.setSizePolicy(sizePolicy)
self.txt_probe_log_path.setObjectName("txt_probe_log_path")
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(20, 290, 241, 16))
self.label_3.setObjectName("label_3")
self.tree_script_sequence = QtWidgets.QTreeView(Dialog)
self.tree_script_sequence.setGeometry(QtCore.QRect(10, 310, 261, 121))
self.tree_script_sequence.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.tree_script_sequence.setAcceptDrops(True)
self.tree_script_sequence.setDragEnabled(True)
self.tree_script_sequence.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.tree_script_sequence.setDefaultDropAction(QtCore.Qt.MoveAction)
self.tree_script_sequence.setObjectName("tree_script_sequence")
self.btn_script_sequence = QtWidgets.QPushButton(Dialog)
self.btn_script_sequence.setGeometry(QtCore.QRect(280, 380, 111, 41))
self.btn_script_sequence.setObjectName("btn_script_sequence")
self.cmb_looping_variable = QtWidgets.QComboBox(Dialog)
self.cmb_looping_variable.setGeometry(QtCore.QRect(280, 350, 111, 22))
self.cmb_looping_variable.setObjectName("cmb_looping_variable")
self.txt_info = QtWidgets.QTextEdit(Dialog)
self.txt_info.setGeometry(QtCore.QRect(540, 300, 301, 131))
self.txt_info.setObjectName("txt_info")
self.txt_script_sequence_name = QtWidgets.QLineEdit(Dialog)
self.txt_script_sequence_name.setGeometry(QtCore.QRect(280, 320, 113, 20))
self.txt_script_sequence_name.setObjectName("txt_script_sequence_name")
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(Dialog.accept)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Loading..."))
self.lbl_info.setText(_translate("Dialog", "info"))
self.label.setText(_translate("Dialog", "Selected"))
self.label_2.setText(_translate("Dialog", "Not Selected"))
self.btn_open.setText(_translate("Dialog", "open"))
self.lbl_probe_log_path.setText(_translate("Dialog", "Path"))
self.txt_probe_log_path.setText(_translate("Dialog", "Z:\\Lab\\Cantilever\\Measurements"))
self.label_3.setText(_translate("Dialog", "Script Sequence"))
self.btn_script_sequence.setText(_translate("Dialog", "Add Script Sequence"))
self.txt_info.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Enter docstring here</span></p></body></html>"))
self.txt_script_sequence_name.setText(_translate("Dialog", "DefaultName"))
|
class Ui_Dialog():
def setupUi(self, Dialog):
pass
def retranslateUi(self, Dialog):
pass
| 3 | 0 | 58 | 1 | 58 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 17 | 2 | 2 | 118 | 2 | 116 | 22 | 113 | 0 | 112 | 22 | 109 | 1 | 0 | 0 | 2 |
144,565 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/gui/compiled_ui_files/basic_application_window.py
|
pylabcontrol.gui.compiled_ui_files.basic_application_window.Ui_MainWindow
|
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1733, 926)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.verticalLayout_10 = QtWidgets.QVBoxLayout()
self.verticalLayout_10.setObjectName("verticalLayout_10")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
self.tabWidget.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(11)
self.tabWidget.setFont(font)
self.tabWidget.setAutoFillBackground(True)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
self.tabWidget.setTabsClosable(False)
self.tabWidget.setObjectName("tabWidget")
self.tab_scripts = QtWidgets.QWidget()
self.tab_scripts.setObjectName("tab_scripts")
self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.tab_scripts)
self.verticalLayout_6.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_6.setObjectName("verticalLayout_6")
self.verticalLayout_4 = QtWidgets.QVBoxLayout()
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.btn_store_script_data = QtWidgets.QPushButton(self.tab_scripts)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_store_script_data.setFont(font)
self.btn_store_script_data.setObjectName("btn_store_script_data")
self.horizontalLayout_4.addWidget(self.btn_store_script_data)
self.btn_load_scripts = QtWidgets.QPushButton(self.tab_scripts)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_load_scripts.setFont(font)
self.btn_load_scripts.setObjectName("btn_load_scripts")
self.horizontalLayout_4.addWidget(self.btn_load_scripts)
self.chk_show_all = QtWidgets.QCheckBox(self.tab_scripts)
self.chk_show_all.setToolTip("")
self.chk_show_all.setObjectName("chk_show_all")
self.horizontalLayout_4.addWidget(self.chk_show_all)
self.verticalLayout_4.addLayout(self.horizontalLayout_4)
self.tree_scripts = QtWidgets.QTreeWidget(self.tab_scripts)
self.tree_scripts.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tree_scripts.sizePolicy().hasHeightForWidth())
self.tree_scripts.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(10)
self.tree_scripts.setFont(font)
self.tree_scripts.setAutoFillBackground(False)
self.tree_scripts.setLineWidth(1)
self.tree_scripts.setMidLineWidth(0)
self.tree_scripts.setEditTriggers(QtWidgets.QAbstractItemView.AllEditTriggers)
self.tree_scripts.setAlternatingRowColors(True)
self.tree_scripts.setWordWrap(True)
self.tree_scripts.setHeaderHidden(False)
self.tree_scripts.setObjectName("tree_scripts")
item_0 = QtWidgets.QTreeWidgetItem(self.tree_scripts)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item_0.setFont(0, font)
item_0.setCheckState(0, QtCore.Qt.Checked)
item_0 = QtWidgets.QTreeWidgetItem(self.tree_scripts)
item_0.setCheckState(0, QtCore.Qt.Checked)
item_1 = QtWidgets.QTreeWidgetItem(item_0)
self.tree_scripts.header().setDefaultSectionSize(300)
self.tree_scripts.header().setHighlightSections(True)
self.verticalLayout_4.addWidget(self.tree_scripts)
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.btn_start_script = QtWidgets.QPushButton(self.tab_scripts)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_start_script.setFont(font)
self.btn_start_script.setObjectName("btn_start_script")
self.horizontalLayout_5.addWidget(self.btn_start_script)
self.btn_stop_script = QtWidgets.QPushButton(self.tab_scripts)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_stop_script.setFont(font)
self.btn_stop_script.setObjectName("btn_stop_script")
self.horizontalLayout_5.addWidget(self.btn_stop_script)
self.btn_skip_subscript = QtWidgets.QPushButton(self.tab_scripts)
self.btn_skip_subscript.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_skip_subscript.setFont(font)
self.btn_skip_subscript.setObjectName("btn_skip_subscript")
self.horizontalLayout_5.addWidget(self.btn_skip_subscript)
self.btn_validate_script = QtWidgets.QPushButton(self.tab_scripts)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_validate_script.setFont(font)
self.btn_validate_script.setObjectName("btn_validate_script")
self.horizontalLayout_5.addWidget(self.btn_validate_script)
self.progressBar = QtWidgets.QProgressBar(self.tab_scripts)
font = QtGui.QFont()
font.setPointSize(12)
self.progressBar.setFont(font)
self.progressBar.setToolTip("")
self.progressBar.setStatusTip("")
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.horizontalLayout_5.addWidget(self.progressBar)
self.verticalLayout_4.addLayout(self.horizontalLayout_5)
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
spacerItem1 = QtWidgets.QSpacerItem(138, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem1)
self.lbl_time_estimate = QtWidgets.QLabel(self.tab_scripts)
self.lbl_time_estimate.setObjectName("lbl_time_estimate")
self.horizontalLayout_6.addWidget(self.lbl_time_estimate)
spacerItem2 = QtWidgets.QSpacerItem(268, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem2)
self.horizontalLayout_6.setStretch(0, 1)
self.horizontalLayout_6.setStretch(1, 1)
self.horizontalLayout_6.setStretch(2, 1)
self.verticalLayout_4.addLayout(self.horizontalLayout_6)
self.verticalLayout_6.addLayout(self.verticalLayout_4)
self.tabWidget.addTab(self.tab_scripts, "")
self.tab_probes = QtWidgets.QWidget()
self.tab_probes.setObjectName("tab_probes")
self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.tab_probes)
self.verticalLayout_7.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_7.setObjectName("verticalLayout_7")
self.verticalLayout_5 = QtWidgets.QVBoxLayout()
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.btn_plot_probe = QtWidgets.QPushButton(self.tab_probes)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_plot_probe.setFont(font)
self.btn_plot_probe.setObjectName("btn_plot_probe")
self.horizontalLayout_2.addWidget(self.btn_plot_probe)
self.btn_load_probes = QtWidgets.QPushButton(self.tab_probes)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_load_probes.setFont(font)
self.btn_load_probes.setObjectName("btn_load_probes")
self.horizontalLayout_2.addWidget(self.btn_load_probes)
self.chk_probe_plot = QtWidgets.QCheckBox(self.tab_probes)
font = QtGui.QFont()
font.setPointSize(10)
self.chk_probe_plot.setFont(font)
self.chk_probe_plot.setObjectName("chk_probe_plot")
self.horizontalLayout_2.addWidget(self.chk_probe_plot)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.chk_probe_log = QtWidgets.QCheckBox(self.tab_probes)
font = QtGui.QFont()
font.setPointSize(10)
self.chk_probe_log.setFont(font)
self.chk_probe_log.setObjectName("chk_probe_log")
self.horizontalLayout.addWidget(self.chk_probe_log)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
self.verticalLayout_5.addLayout(self.horizontalLayout_2)
self.tree_probes = QtWidgets.QTreeWidget(self.tab_probes)
self.tree_probes.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tree_probes.sizePolicy().hasHeightForWidth())
self.tree_probes.setSizePolicy(sizePolicy)
self.tree_probes.setEditTriggers(QtWidgets.QAbstractItemView.AllEditTriggers)
self.tree_probes.setHeaderHidden(False)
self.tree_probes.setObjectName("tree_probes")
self.tree_probes.header().setDefaultSectionSize(150)
self.tree_probes.header().setHighlightSections(True)
self.verticalLayout_5.addWidget(self.tree_probes)
self.verticalLayout_7.addLayout(self.verticalLayout_5)
self.tabWidget.addTab(self.tab_probes, "")
self.tab_settings = QtWidgets.QWidget()
self.tab_settings.setObjectName("tab_settings")
self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.tab_settings)
self.verticalLayout_8.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_8.setObjectName("verticalLayout_8")
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem3)
self.btn_load_instruments = QtWidgets.QPushButton(self.tab_settings)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_load_instruments.setFont(font)
self.btn_load_instruments.setObjectName("btn_load_instruments")
self.horizontalLayout_3.addWidget(self.btn_load_instruments)
self.verticalLayout_3.addLayout(self.horizontalLayout_3)
self.tree_settings = QtWidgets.QTreeWidget(self.tab_settings)
self.tree_settings.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tree_settings.sizePolicy().hasHeightForWidth())
self.tree_settings.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(10)
self.tree_settings.setFont(font)
self.tree_settings.setEditTriggers(QtWidgets.QAbstractItemView.AllEditTriggers)
self.tree_settings.setHeaderHidden(False)
self.tree_settings.setObjectName("tree_settings")
self.tree_settings.header().setDefaultSectionSize(200)
self.tree_settings.header().setHighlightSections(True)
self.verticalLayout_3.addWidget(self.tree_settings)
self.verticalLayout_8.addLayout(self.verticalLayout_3)
self.tabWidget.addTab(self.tab_settings, "")
self.tab_data = QtWidgets.QWidget()
self.tab_data.setObjectName("tab_data")
self.horizontalLayout_13 = QtWidgets.QHBoxLayout(self.tab_data)
self.horizontalLayout_13.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_13.setObjectName("horizontalLayout_13")
self.horizontalLayout_12 = QtWidgets.QHBoxLayout()
self.horizontalLayout_12.setObjectName("horizontalLayout_12")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
self.horizontalLayout_10.setObjectName("horizontalLayout_10")
self.btn_save_data = QtWidgets.QPushButton(self.tab_data)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_save_data.setFont(font)
self.btn_save_data.setObjectName("btn_save_data")
self.horizontalLayout_10.addWidget(self.btn_save_data)
self.btn_delete_data = QtWidgets.QPushButton(self.tab_data)
font = QtGui.QFont()
font.setPointSize(10)
self.btn_delete_data.setFont(font)
self.btn_delete_data.setObjectName("btn_delete_data")
self.horizontalLayout_10.addWidget(self.btn_delete_data)
self.verticalLayout.addLayout(self.horizontalLayout_10)
self.tree_dataset = QtWidgets.QTreeView(self.tab_data)
self.tree_dataset.setDragEnabled(True)
self.tree_dataset.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
self.tree_dataset.setDefaultDropAction(QtCore.Qt.MoveAction)
self.tree_dataset.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.tree_dataset.setUniformRowHeights(True)
self.tree_dataset.setObjectName("tree_dataset")
self.verticalLayout.addWidget(self.tree_dataset)
self.horizontalLayout_12.addLayout(self.verticalLayout)
self.horizontalLayout_13.addLayout(self.horizontalLayout_12)
self.tabWidget.addTab(self.tab_data, "")
self.verticalLayout_10.addWidget(self.tabWidget)
self.tabWidget_2 = QtWidgets.QTabWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tabWidget_2.sizePolicy().hasHeightForWidth())
self.tabWidget_2.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(11)
self.tabWidget_2.setFont(font)
self.tabWidget_2.setObjectName("tabWidget_2")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.tab)
self.verticalLayout_9.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_9.setObjectName("verticalLayout_9")
self.list_history = QtWidgets.QListView(self.tab)
font = QtGui.QFont()
font.setPointSize(10)
self.list_history.setFont(font)
self.list_history.setAlternatingRowColors(True)
self.list_history.setWordWrap(True)
self.list_history.setObjectName("list_history")
self.verticalLayout_9.addWidget(self.list_history)
self.tabWidget_2.addTab(self.tab, "")
self.tab_settings_2 = QtWidgets.QWidget()
self.tab_settings_2.setObjectName("tab_settings_2")
self.horizontalLayout_11 = QtWidgets.QHBoxLayout(self.tab_settings_2)
self.horizontalLayout_11.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_11.setObjectName("horizontalLayout_11")
self.verticalLayout_11 = QtWidgets.QVBoxLayout()
self.verticalLayout_11.setObjectName("verticalLayout_11")
self.tree_gui_settings = QtWidgets.QTreeView(self.tab_settings_2)
font = QtGui.QFont()
font.setPointSize(10)
self.tree_gui_settings.setFont(font)
self.tree_gui_settings.setEditTriggers(QtWidgets.QAbstractItemView.DoubleClicked|QtWidgets.QAbstractItemView.EditKeyPressed)
self.tree_gui_settings.setAlternatingRowColors(True)
self.tree_gui_settings.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.tree_gui_settings.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectItems)
self.tree_gui_settings.setIndentation(0)
self.tree_gui_settings.setUniformRowHeights(True)
self.tree_gui_settings.setItemsExpandable(True)
self.tree_gui_settings.setSortingEnabled(True)
self.tree_gui_settings.setExpandsOnDoubleClick(True)
self.tree_gui_settings.setObjectName("tree_gui_settings")
self.tree_gui_settings.header().setDefaultSectionSize(200)
self.tree_gui_settings.header().setSortIndicatorShown(True)
self.verticalLayout_11.addWidget(self.tree_gui_settings)
self.horizontalLayout_11.addLayout(self.verticalLayout_11)
self.tabWidget_2.addTab(self.tab_settings_2, "")
self.verticalLayout_10.addWidget(self.tabWidget_2)
self.horizontalLayout_7.addLayout(self.verticalLayout_10)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.toolbar_space_1 = QtWidgets.QWidget(self.centralwidget)
self.toolbar_space_1.setObjectName("toolbar_space_1")
self.horizontalLayout_9.addWidget(self.toolbar_space_1)
self.verticalLayout_2.addLayout(self.horizontalLayout_9)
self.horizontalLayout_16 = QtWidgets.QHBoxLayout()
self.horizontalLayout_16.setObjectName("horizontalLayout_16")
self.plot_1 = QtWidgets.QWidget(self.centralwidget)
self.plot_1.setObjectName("plot_1")
self.horizontalLayout_16.addWidget(self.plot_1)
self.verticalLayout_2.addLayout(self.horizontalLayout_16)
self.horizontalLayout_14 = QtWidgets.QHBoxLayout()
self.horizontalLayout_14.setObjectName("horizontalLayout_14")
self.toolbar_space_2 = QtWidgets.QWidget(self.centralwidget)
self.toolbar_space_2.setObjectName("toolbar_space_2")
self.horizontalLayout_14.addWidget(self.toolbar_space_2)
self.verticalLayout_2.addLayout(self.horizontalLayout_14)
self.horizontalLayout_15 = QtWidgets.QHBoxLayout()
self.horizontalLayout_15.setObjectName("horizontalLayout_15")
self.plot_2 = QtWidgets.QWidget(self.centralwidget)
self.plot_2.setObjectName("plot_2")
self.horizontalLayout_15.addWidget(self.plot_2)
self.verticalLayout_2.addLayout(self.horizontalLayout_15)
self.verticalLayout_2.setStretch(0, 1)
self.verticalLayout_2.setStretch(1, 8)
self.verticalLayout_2.setStretch(2, 1)
self.verticalLayout_2.setStretch(3, 26)
self.horizontalLayout_7.addLayout(self.verticalLayout_2)
self.horizontalLayout_7.setStretch(0, 8)
self.horizontalLayout_7.setStretch(1, 12)
self.horizontalLayout_8.addLayout(self.horizontalLayout_7)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1733, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setEnabled(True)
self.menuFile.setAcceptDrops(True)
self.menuFile.setObjectName("menuFile")
self.menuHelp = QtWidgets.QMenu(self.menubar)
self.menuHelp.setObjectName("menuHelp")
MainWindow.setMenuBar(self.menubar)
self.btn_exit = QtWidgets.QAction(MainWindow)
self.btn_exit.setObjectName("btn_exit")
self.btn_load_gui = QtWidgets.QAction(MainWindow)
self.btn_load_gui.setObjectName("btn_load_gui")
self.btn_save_gui = QtWidgets.QAction(MainWindow)
self.btn_save_gui.setObjectName("btn_save_gui")
self.btn_about = QtWidgets.QAction(MainWindow)
self.btn_about.setObjectName("btn_about")
self.btn_test_2 = QtWidgets.QAction(MainWindow)
self.btn_test_2.setObjectName("btn_test_2")
self.actionSave = QtWidgets.QAction(MainWindow)
self.actionSave.setObjectName("actionSave")
self.actionExport = QtWidgets.QAction(MainWindow)
self.actionExport.setObjectName("actionExport")
self.actionGo_to_pylabcontrol_GitHub_page = QtWidgets.QAction(MainWindow)
self.actionGo_to_pylabcontrol_GitHub_page.setObjectName("actionGo_to_pylabcontrol_GitHub_page")
self.menuFile.addAction(self.actionExport)
self.menuFile.addAction(self.actionSave)
self.menuFile.addAction(self.btn_save_gui)
self.menuFile.addAction(self.btn_load_gui)
self.menuFile.addSeparator()
self.menuFile.addAction(self.btn_exit)
self.menuHelp.addAction(self.btn_about)
self.menuHelp.addAction(self.actionGo_to_pylabcontrol_GitHub_page)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
self.tabWidget_2.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Lukin Lab - B26 GUI"))
self.btn_store_script_data.setText(_translate("MainWindow", "send to Datasets"))
self.btn_load_scripts.setText(_translate("MainWindow", "import script"))
self.chk_show_all.setText(_translate("MainWindow", "show all"))
self.tree_scripts.headerItem().setText(0, _translate("MainWindow", "Parameter/Script "))
self.tree_scripts.headerItem().setText(1, _translate("MainWindow", "Value"))
self.tree_scripts.headerItem().setText(2, _translate("MainWindow", "show"))
__sortingEnabled = self.tree_scripts.isSortingEnabled()
self.tree_scripts.setSortingEnabled(False)
self.tree_scripts.topLevelItem(0).setText(0, _translate("MainWindow", "New Item"))
self.tree_scripts.topLevelItem(1).setText(0, _translate("MainWindow", "New Item"))
self.tree_scripts.topLevelItem(1).child(0).setText(0, _translate("MainWindow", "New Subitem"))
self.tree_scripts.setSortingEnabled(__sortingEnabled)
self.btn_start_script.setText(_translate("MainWindow", "start"))
self.btn_stop_script.setText(_translate("MainWindow", "stop"))
self.btn_skip_subscript.setText(_translate("MainWindow", "skip"))
self.btn_validate_script.setText(_translate("MainWindow", "validate"))
self.lbl_time_estimate.setText(_translate("MainWindow", "time remaining:"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_scripts), _translate("MainWindow", "Scripts"))
self.btn_plot_probe.setText(_translate("MainWindow", "plot probe"))
self.btn_load_probes.setText(_translate("MainWindow", "load probe"))
self.chk_probe_plot.setText(_translate("MainWindow", "plotting on"))
self.chk_probe_log.setText(_translate("MainWindow", "logging on"))
self.tree_probes.headerItem().setText(0, _translate("MainWindow", "Parameter"))
self.tree_probes.headerItem().setText(1, _translate("MainWindow", "Value"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_probes), _translate("MainWindow", "Probes"))
self.btn_load_instruments.setText(_translate("MainWindow", "import instrument"))
self.tree_settings.headerItem().setText(0, _translate("MainWindow", "Instrument"))
self.tree_settings.headerItem().setText(1, _translate("MainWindow", "Value"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_settings), _translate("MainWindow", "Instruments"))
self.btn_save_data.setText(_translate("MainWindow", "save selected"))
self.btn_delete_data.setText(_translate("MainWindow", "delete selected"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_data), _translate("MainWindow", "Datasets"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab), _translate("MainWindow", "History"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_settings_2), _translate("MainWindow", "GUI Settings"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuHelp.setTitle(_translate("MainWindow", "Help"))
self.btn_exit.setText(_translate("MainWindow", "Exit"))
self.btn_load_gui.setText(_translate("MainWindow", "Load"))
self.btn_save_gui.setText(_translate("MainWindow", "Save as"))
self.btn_about.setText(_translate("MainWindow", "about"))
self.btn_test_2.setText(_translate("MainWindow", "test"))
self.actionSave.setText(_translate("MainWindow", "Save"))
self.actionExport.setText(_translate("MainWindow", "Convert script or instrument .py files to .b26 files"))
self.actionGo_to_pylabcontrol_GitHub_page.setText(_translate("MainWindow", "Go to pylabcontrol GitHub page"))
|
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
pass
def retranslateUi(self, MainWindow):
pass
| 3 | 0 | 220 | 1 | 219 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 73 | 2 | 2 | 441 | 2 | 439 | 86 | 436 | 0 | 439 | 86 | 436 | 1 | 1 | 0 | 2 |
144,566 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/scripts/script_dummy.py
|
scripts.script_dummy.ScriptMinimalDummy
|
class ScriptMinimalDummy(Script):
"""
Minimal Example Script that has only a single parameter (execution time)
"""
_DEFAULT_SETTINGS = [
Parameter('execution_time', 0.1, float, 'execution time of script (s)')
]
_INSTRUMENTS = {}
_SCRIPTS = {}
def __init__(self, name=None, settings=None,
log_function = None, data_path = None):
"""
Example of a script
Args:
name (optional): name of script, if empty same as class name
settings (optional): settings for this script, if empty same as default settings
"""
Script.__init__(self, name, settings, log_function= log_function, data_path = data_path)
def _function(self):
"""
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
"""
import time
time.sleep(self.settings['execution_time'])
|
class ScriptMinimalDummy(Script):
'''
Minimal Example Script that has only a single parameter (execution time)
'''
def __init__(self, name=None, settings=None,
log_function = None, data_path = None):
'''
Example of a script
Args:
name (optional): name of script, if empty same as class name
settings (optional): settings for this script, if empty same as default settings
'''
pass
def _function(self):
'''
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
'''
pass
| 3 | 3 | 8 | 0 | 3 | 5 | 1 | 1.08 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 51 | 30 | 5 | 12 | 8 | 7 | 13 | 9 | 7 | 5 | 1 | 2 | 0 | 2 |
144,567 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_tools.py
|
tests.test_tools.TestHelperFunctions
|
class TestHelperFunctions(TestCase):
# def __init__(self):
# self.filename = inspect.getmodule(ScriptDummy).__file__
def test_export_script(self):
source_folders = os.path.dirname(inspect.getmodule(ExampleScript).__file__)
tmp_folder = os.path.normpath('./tmp-testing-/')
os.makedirs(tmp_folder)
# export(tmp_folder, source_folders=source_folders, class_type='scripts', raise_errors=False)
print('adas')
shutil.rmtree(tmp_folder, ignore_errors=False, onerror=None)
|
class TestHelperFunctions(TestCase):
def test_export_script(self):
pass
| 2 | 0 | 11 | 4 | 6 | 1 | 1 | 0.43 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 17 | 7 | 7 | 4 | 5 | 3 | 7 | 4 | 5 | 1 | 2 | 0 | 1 |
144,568 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_script_iterator.py
|
tests.test_script_iterator.TestScriptIterator
|
class TestScriptIterator(TestCase):
def test_loading_and_saving(self):
path_to_script_file = inspect.getmodule(ExampleScript).__file__.replace('.pyc', '.py')
script_info = {'iter_script':
{'info': 'Enter docstring here',
'scripts': {'ScriptDummy':
{
'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ',
'settings': {'count': 3, 'name': 'this is a counter', 'wait_time': 0.1,
'point2': {'y': 0.1, 'x': 0.1}, 'tag': 'scriptdummy',
'path': '', 'save': False, 'plot_style': 'main'},
'class': 'ScriptDummy',
'filepath': path_to_script_file}},
'class': 'ScriptIterator',
'settings': {'script_order': {'ScriptDummy': 0}, 'iterator_type': 'Loop'},
'package': 'pylabcontrol'}}
si = ScriptIterator.create_dynamic_script_class(script_info['iter_script'], verbose=True)
print(si)
def test_get_script_iterator(self):
# test get_script_iterator
package = 'pylabcontrol'
package = 'b26_toolkit'
script_iterator = ScriptIterator.get_script_iterator(package, verbose=False)
print(('script_iterator', script_iterator))
def test_create_dynamic_script_class(self):
from pylabcontrol.scripts.example_scripts import ExampleScript
path_to_script_file = inspect.getmodule(ExampleScript).__file__.replace('.pyc', '.py')
package = 'pylabcontrol' #
iterator_type = 'Loop' #
# package = 'b26_toolkit' #
# iterator_type = 'Iter test' #
script_info = {'iter_script':
{'info': 'Enter docstring here',
'scripts': {'ScriptDummy':
{
'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ',
'settings': {'count': 3, 'name': 'this is a counter', 'wait_time': 0.1,
'point2': {'y': 0.1, 'x': 0.1}, 'tag': 'scriptdummy',
'path': '', 'save': False, 'plot_style': 'main'},
'class': 'ScriptDummy',
'filepath': path_to_script_file}},
'class': 'ScriptIterator',
'settings': {'script_order': {'ScriptDummy': 0}, 'iterator_type': iterator_type},
'package': package}}
si = ScriptIterator.create_dynamic_script_class(script_info['iter_script'], verbose=True)
print('================================================================================')
print(si)
def test_XX(self):
from pylabcontrol.core import Script
script_info = {'info': 'Enter docstring here', 'scripts': {'ScriptDummy': {
'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ',
'settings': {'count': 3, 'name': 'this is a counter', 'wait_time': 0.1, 'point2': {'y': 0.1, 'x': 0.1},
'tag': 'scriptdummy', 'path': '', 'save': False, 'plot_style': 'main'}, 'class': 'ScriptDummy',
'filepath': '/Users/rettentulla/PycharmProjects/pylabcontrol/pylabcontrol/scripts/example_scripts.py'}},
'class': 'ScriptIterator', 'settings': {'script_order': {'ScriptDummy': 0}, 'iterator_type': 'Loop'},
'package': 'b26_toolkit'}
script_info2 = {'info': 'Enter docstring here', 'scripts':
{'ScriptDummy': {
'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ',
'settings': {'count': 3, 'name': 'this is a counter', 'wait_time': 0.1, 'point2': {'y': 0.1, 'x': 0.1},
'tag': 'scriptdummy', 'path': '', 'save': False, 'plot_style': 'main'},
'class': 'ScriptDummy',
'filepath': '/Users/rettentulla/PycharmProjects/pylabcontrol/pylabcontrol/scripts/example_scripts.py'}
},
'class': 'dynamic_script_iterator0',
'settings': {'script_order': {'ScriptDummy': 0}, 'run_all_first': True,'script_execution_freq': {'ScriptDummy': 1}, 'N': 0},
'package': 'b26_toolkit'}
print('============================================================')
module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information(script_info)
print((module, package, script_class_name))
script_info3, _ = ScriptIterator.create_dynamic_script_class(script_info)
print('============================================================')
module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information(script_info2)
print((module, package, script_class_name))
module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information(script_info3)
print((module, package, script_class_name))
|
class TestScriptIterator(TestCase):
def test_loading_and_saving(self):
pass
def test_get_script_iterator(self):
pass
def test_create_dynamic_script_class(self):
pass
def test_XX(self):
pass
| 5 | 0 | 24 | 5 | 18 | 1 | 1 | 0.07 | 1 | 3 | 3 | 0 | 4 | 0 | 4 | 76 | 104 | 28 | 73 | 21 | 66 | 5 | 33 | 21 | 26 | 1 | 2 | 0 | 4 |
144,569 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/pylabcontrol/core/read_probes.py
|
pylabcontrol.core.read_probes.ReadProbes
|
class ReadProbes(QThread):
#This is the signal that will be emitted during the processing.
#By including int as an argument, it lets the signal know to expect
#an integer argument when emitting.
# updateProgress = QtCore.Signal(int)
_DEFAULT_SETTINGS = None
updateProgress = pyqtSignal(int)
def __init__(self, probes, refresh_interval = 2.0 ):
"""
probes: dictionary of probes where keys are instrument names and values are dictonaries where key is probe name and value is Probe objects
refresh_interval: time between reads in s
"""
assert isinstance(probes, dict)
assert isinstance(refresh_interval, float)
self.refresh_interval = refresh_interval
self._running = False
self.probes = probes
self.probes_values = None
QThread.__init__(self)
def run(self):
"""
this is the actual execution of the ReadProbes thread: continuously read values from the probes
"""
if self.probes is None:
self._stop = True
while True:
if self._stop:
break
self.probes_values = {
instrument_name:
{probe_name: probe_instance.value for probe_name, probe_instance in probe.items()}
for instrument_name, probe in self.probes.items()
}
self.updateProgress.emit(1)
self.msleep(int(1e3*self.refresh_interval))
def start(self, *args, **kwargs):
"""
start the read_probe thread
"""
self._stop = False
super(ReadProbes, self).start(*args, **kwargs)
def quit(self, *args, **kwargs): # real signature unknown
"""
quit the read_probe thread
"""
self._stop = True
super(ReadProbes, self).quit(*args, **kwargs)
|
class ReadProbes(QThread):
def __init__(self, probes, refresh_interval = 2.0 ):
'''
probes: dictionary of probes where keys are instrument names and values are dictonaries where key is probe name and value is Probe objects
refresh_interval: time between reads in s
'''
pass
def run(self):
'''
this is the actual execution of the ReadProbes thread: continuously read values from the probes
'''
pass
def start(self, *args, **kwargs):
'''
start the read_probe thread
'''
pass
def quit(self, *args, **kwargs):
'''
quit the read_probe thread
'''
pass
| 5 | 4 | 12 | 2 | 7 | 4 | 2 | 0.6 | 1 | 4 | 0 | 0 | 4 | 5 | 4 | 4 | 61 | 14 | 30 | 12 | 25 | 18 | 26 | 12 | 21 | 4 | 1 | 2 | 7 |
144,570 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_qt_widgets.py
|
tests.test_qt_widgets.UI
|
class UI(QtGui.QMainWindow):
def __init__(self, parameters = None, parent=None):
## Init:
super(UI, self).__init__( parent )
# ----------------
# Create Simple UI with QTreeWidget
# ----------------
self.centralwidget = QtGui.QWidget(self)
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.parameters = parameters
self.treeWidget = QtGui.QTreeWidget(self.centralwidget)
self.verticalLayout.addWidget(self.treeWidget)
self.setCentralWidget(self.centralwidget)
fill_tree(self.treeWidget, self.parameters)
# ----------------
# Set TreeWidget Headers
# ----------------
HEADERS = ( "parameter", "value" )
self.treeWidget.setColumnCount( len(HEADERS) )
self.treeWidget.setHeaderLabels( HEADERS )
# ----------------
# Add Custom QTreeWidgetItem
# ----------------
self.treeWidget.itemChanged.connect(lambda: self.update_parameters(self.treeWidget, self.parameters))
# shot down
print('close')
self.close()
|
class UI(QtGui.QMainWindow):
def __init__(self, parameters = None, parent=None):
pass
| 2 | 0 | 35 | 9 | 15 | 11 | 1 | 0.69 | 1 | 1 | 0 | 0 | 1 | 4 | 1 | 1 | 37 | 10 | 16 | 7 | 14 | 11 | 16 | 7 | 14 | 1 | 1 | 0 | 1 |
144,571 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_qt_widgets.py
|
tests.test_qt_widgets.TestB26QTreeWidget
|
class TestB26QTreeWidget(TestCase):
def test_create_widget_parameters(self):
parameters = Parameter([
Parameter('test1', 0, int, 'test parameter (int)'),
Parameter('test2' ,
[Parameter('test2_1', 'string', str, 'test parameter (str)'),
Parameter('test2_2', 0.0, float, 'test parameter (float)'),
Parameter('test2_3', 'a', ['a', 'b', 'c'], 'test parameter (list)'),
Parameter('test2_4', False, bool, 'test parameter (bool)')
]),
Parameter('test3', 'aa', ['aa', 'bb', 'cc'], 'test parameter (list)'),
Parameter('test4', False, bool, 'test parameter (bool)')
])
app = QtGui.QApplication(sys.argv)
ex = UI(parameters)
# sys.exit(app.exec_())
def test_create_widget_parameters(self):
parameters = {
'test1':0,
'test2':{'test2_1':'ss', 'test3':4},
'test4':0
}
app = QtGui.QApplication(sys.argv)
ex = UI(parameters)
|
class TestB26QTreeWidget(TestCase):
def test_create_widget_parameters(self):
pass
def test_create_widget_parameters(self):
pass
| 3 | 0 | 14 | 3 | 11 | 0 | 1 | 0.04 | 1 | 5 | 1 | 0 | 2 | 0 | 2 | 74 | 33 | 9 | 23 | 9 | 20 | 1 | 9 | 9 | 6 | 1 | 2 | 0 | 2 |
144,572 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_probe.py
|
tests.test_probe.TestProbe
|
class TestProbe(TestCase):
def test_init(self):
from src.core import instantiate_instruments
instruments = {'inst_dummy': 'DummyInstrument'}
instrument = instantiate_instruments(instruments)['inst_dummy']
p = Probe(instrument, 'value1', 'random')
print((instruments['inst_dummy']))
print((p.name))
print((p.value))
print((p.value))
|
class TestProbe(TestCase):
def test_init(self):
pass
| 2 | 0 | 13 | 4 | 9 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 15 | 5 | 10 | 6 | 7 | 0 | 10 | 6 | 7 | 1 | 2 | 0 | 1 |
144,573 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_instrument.py
|
tests.test_instrument.TestInstrument
|
class TestInstrument(TestCase):
# def test_init(self):
# '''
# initiallize instance in all possible ways
# :return:
# '''
#
#
# test = Instrument()
#
#
# test = Instrument('test inst', {'test1':2020})
# self.assertEqual(test.settings, {'test1': 2020, 'test2': {'test2_1': 'string', 'test2_2': 0.0}})
# test = Instrument('test inst', { 'test2': {'test2_1': 'new string', 'test2_2': 0.2}})
# self.assertEqual(test.settings, {'test1': 0, 'test2': {'test2_1': 'new string', 'test2_2': 0.2}})
# test = Instrument('test inst', { 'test2': {'test2_1': 'new string'}})
# self.assertEqual(test.settings, {'test1': 0, 'test2': {'test2_1': 'new string', 'test2_2': 0.0}})
#
# def test_update(self):
# '''
# test all possible ways to update a parameter
# :return:
# '''
# test = Instrument()
#
# test.settings['test1'] = 222
# self.assertEqual(test.settings, {'test1': 222, 'test2': {'test2_1': 'string', 'test2_2': 0.0}})
#
# test.settings.update({'test1':200})
# self.assertEqual(test.settings, {'test1': 200, 'test2': {'test2_1': 'string', 'test2_2': 0.0}})
#
# test.settings.update({'test2': {'test2_1': 'new string', 'test2_2': 0.2}})
# self.assertEqual(test.settings, {'test1': 200, 'test2': {'test2_1': 'new string', 'test2_2': 0.2}})
#
# test.settings['test2']['test2_1'] = 'hello'
# self.assertEqual(test.settings, {'test1': 200, 'test2': {'test2_1': 'hello', 'test2_2': 0.2}})
#
#
# print(test.settings['test2'])
#
# print(test.settings)
#
# print(type(test.settings))
# print(type(test.settings['test2']))
#
# def test_tes(self):
# test = Instrument('my inst')
#
# with self.assertRaises(AssertionError):
# # request variable that is not in values
# test.test4
#
# a = test.value1
# self.assertEqual(a, None)
#
# def Ttest_QString(self):
# from PyQt4 import QtCore
# test = Instrument()
#
# test.update_parameters(Parameter('test1', QtCore.QString(unicode('10'))))
#
# test.update_parameters({'test1': QtCore.QString(unicode('10'))} )
#
#
#
# def Ttest_dynamic_setter(self):
# test = Instrument()
# new_val = 30
# #test.test1 = 30
# test.update_parameters(Parameter('test1', 30))
# if get_elemet('test1', test.settings).value != test.test1:
# #print(test.parameters)
# self.fail('setter function doesn\'t work')
def test_loading_and_saving(self):
from src.core.read_write_functions import load_b26_file
filename = "Z:\Lab\Cantilever\Measurements\\__tmp\\XX.b26"
data = load_b26_file(filename)
inst = {}
instruments, instruments_failed = Instrument.load_and_append(data['instruments'], instruments=inst)
|
class TestInstrument(TestCase):
def test_loading_and_saving(self):
pass
| 2 | 0 | 7 | 1 | 6 | 0 | 1 | 10.29 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 81 | 2 | 7 | 7 | 4 | 72 | 7 | 7 | 4 | 1 | 2 | 0 | 1 |
144,574 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_helper_functions.py
|
tests.test_helper_functions.TestHelperFunctions
|
class TestHelperFunctions(TestCase):
# def __init__(self):
# self.filename = inspect.getmodule(ScriptDummy).__file__
def test_module_name_from_path_1(self):
package_name = 'pylabcontrol'
filename = inspect.getmodule(ExampleScript).__file__
# check that file actually exists
assert os.path.isfile(filename)
module, path = module_name_from_path(filename, verbose=False)
assert module == 'pylabcontrol.scripts.script_dummy'
assert path == os.path.normpath(filename.split(package_name)[0])
|
class TestHelperFunctions(TestCase):
def test_module_name_from_path_1(self):
pass
| 2 | 0 | 14 | 6 | 7 | 1 | 1 | 0.38 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 20 | 9 | 8 | 5 | 6 | 3 | 8 | 5 | 6 | 1 | 2 | 0 | 1 |
144,575 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/src/scripts/select_points.py
|
scripts.select_points.SelectPoints
|
class SelectPoints(Script):
"""
Script to select points on an image. The selected points are saved and can be used in a superscript to iterate over.
"""
_DEFAULT_SETTINGS = [
Parameter('patch_size', 0.003),
Parameter('type', 'free', ['free', 'square', 'line', 'ring']),
Parameter('Nx', 5, int, 'number of points along x (type: square) along line (type: line)'),
Parameter('Ny', 5, int, 'number of points along y (type: square)')
]
_INSTRUMENTS = {}
_SCRIPTS = {}
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None):
"""
Select points by clicking on an image
"""
Script.__init__(self, name, settings = settings, instruments = instruments, scripts = scripts, log_function= log_function, data_path = data_path)
self.patches = []
self.plot_settings = {}
def _function(self):
"""
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
"""
self.data = {'nv_locations': [], 'image_data': None, 'extent': None}
self.progress = 50
self.updateProgress.emit(self.progress)
# keep script alive while NVs are selected
while not self._abort:
time.sleep(1)
def plot(self, figure_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
# if there is not image data get it from the current plot
if not self.data == {} and self.data['image_data'] is None:
axes = figure_list[0].axes[0]
if len(axes.images)>0:
self.data['image_data'] = np.array(axes.images[0].get_array())
self.data['extent'] = np.array(axes.images[0].get_extent())
self.plot_settings['cmap'] = axes.images[0].get_cmap().name
self.plot_settings['xlabel'] = axes.get_xlabel()
self.plot_settings['ylabel'] = axes.get_ylabel()
self.plot_settings['title'] = axes.get_title()
self.plot_settings['interpol'] = axes.images[0].get_interpolation()
Script.plot(self, figure_list)
#must be passed figure with galvo plot on first axis
def _plot(self, axes_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
axes = axes_list[0]
if self.plot_settings:
axes.imshow(self.data['image_data'], cmap=self.plot_settings['cmap'], interpolation=self.plot_settings['interpol'], extent=self.data['extent'])
axes.set_xlabel(self.plot_settings['xlabel'])
axes.set_ylabel(self.plot_settings['ylabel'])
axes.set_title(self.plot_settings['title'])
self._update(axes_list)
def _update(self, axes_list):
axes = axes_list[0]
patch_size = self.settings['patch_size']
#first clear all old patches (circles and numbers), then redraw all
if not self.patches == []:
try: #catch case where plot has been cleared, so old patches no longer exist. Then skip clearing step.
for patch in self.patches:
patch.remove()
except ValueError:
pass
self.patches = []
for index, pt in enumerate(self.data['nv_locations']):
# axes.plot(pt, fc='b')
circ = patches.Circle((pt[0], pt[1]), patch_size, fc='b')
axes.add_patch(circ)
self.patches.append(circ)
text = axes.text(pt[0], pt[1], '{:d}'.format(index),
horizontalalignment='center',
verticalalignment='center',
color='white'
)
self.patches.append(text)
def toggle_NV(self, pt):
'''
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If
there is, removes that point from the selected list.
Args:
pt: the point to add or remove from the selected list
Poststate: updates selected list
'''
if not self.data['nv_locations']: #if self.data is empty so this is the first point
self.data['nv_locations'].append(pt)
self.data['image_data'] = None # clear image data
else:
# use KDTree to find NV closest to mouse click
tree = scipy.spatial.KDTree(self.data['nv_locations'])
#does a search with k=1, that is a search for the nearest neighbor, within distance_upper_bound
d, i = tree.query(pt,k = 1, distance_upper_bound = self.settings['patch_size'])
# removes NV if previously selected
if d is not np.inf:
self.data['nv_locations'].pop(i)
# adds NV if not previously selected
else:
self.data['nv_locations'].append(pt)
# if type is not free we calculate the total points of locations from the first selected points
if self.settings['type'] == 'square' and len(self.data['nv_locations'])>1:
# here we create a rectangular grid, where pts a and be define the top left and bottom right corner of the rectangle
Nx, Ny = self.settings['Nx'], self.settings['Ny']
pta = self.data['nv_locations'][0]
ptb = self.data['nv_locations'][1]
tmp = np.array([[[pta[0] + 1.0*i*(ptb[0]-pta[0])/(Nx-1), pta[1] + 1.0*j*(ptb[1]-pta[1])/(Ny-1)] for i in range(Nx)] for j in range(Ny)])
self.data['nv_locations'] = np.reshape(tmp, (Nx * Ny, 2))
self.stop()
elif self.settings['type'] == 'line' and len(self.data['nv_locations'])>1:
# here we create a straight line between points a and b
N = self.settings['Nx']
pta = self.data['nv_locations'][0]
ptb = self.data['nv_locations'][1]
self.data['nv_locations'] = [np.array([pta[0] + 1.0*i*(ptb[0]-pta[0])/(N-1), pta[1] + 1.0*i*(ptb[1]-pta[1])/(N-1)]) for i in range(N)]
self.stop()
elif self.settings['type'] == 'ring' and len(self.data['nv_locations'])>1:
# here we create a circular grid, where pts a and be define the center and the outermost ring
Nx, Ny = self.settings['Nx'], self.settings['Ny']
pta = self.data['nv_locations'][0] # center
ptb = self.data['nv_locations'][1] # outermost ring
# radius of outermost ring:
rmax = np.sqrt((pta[0] - ptb[0]) ** 2 + (pta[1] - ptb[1]) ** 2)
# create points on rings
tmp = []
for r in np.linspace(rmax, 0, Ny + 1)[0:-1]:
for theta in np.linspace(0, 2 * np.pi, Nx+1)[0:-1]:
tmp += [[r * np.sin(theta)+pta[0], r * np.cos(theta)+pta[1]]]
self.data['nv_locations'] = np.array(tmp)
self.stop()
|
class SelectPoints(Script):
'''
Script to select points on an image. The selected points are saved and can be used in a superscript to iterate over.
'''
def __init__(self, instruments = None, scripts = None, name = None, settings = None, log_function = None, data_path = None):
'''
Select points by clicking on an image
'''
pass
def _function(self):
'''
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
'''
pass
def plot(self, figure_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
pass
def _plot(self, axes_list):
'''
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are
listed.
Precondition: must have an existing image in figure_list[0] to plot over
Args:
figure_list:
'''
pass
def _update(self, axes_list):
pass
def toggle_NV(self, pt):
'''
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If
there is, removes that point from the selected list.
Args:
pt: the point to add or remove from the selected list
Poststate: updates selected list
'''
pass
| 7 | 6 | 26 | 5 | 14 | 8 | 4 | 0.53 | 1 | 3 | 0 | 0 | 6 | 4 | 6 | 55 | 174 | 35 | 94 | 32 | 87 | 50 | 81 | 32 | 74 | 8 | 2 | 3 | 21 |
144,576 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/tests/test_script.py
|
tests.test_script.TestInstrument
|
class TestInstrument(TestCase):
def test_loading_and_saving(self):
from pylabcontrol.core.read_write_functions import load_b26_file
filename = "Z:\Lab\Cantilever\Measurements\\__tmp\\XYX.b26"
scripts, loaded_failed, instruments = Script.load_and_append({"some script": 'ScriptDummyWithInstrument'})
script = scripts['some script']
script.save_b26(filename)
data = load_b26_file(filename)
scripts = {}
instruments = {}
scripts, scripts_failed, instruments_2 = Script.load_and_append(data['scripts'], scripts, instruments)
def test_load_and_append(self):
filepath = 'C:\\Users\\Experiment\\PycharmProjects\\pylabcontrol\\pylabcontrol\\scripts\\example_scripts.py'
script_dict = {'DefaultName': {'info': 'Enter docstring here', 'scripts': {'ScriptDummy': {'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ',
'settings': {'count': 3, 'name': 'this is a counter', 'wait_time': 0.1, 'point2': {'y': 0.1, 'x': 0.1}, 'tag': 'scriptdummy', 'path': '', 'save': False, 'plot_style': 'main'},
'class': 'ScriptDummy',
'filepath': filepath}},
'class': 'ScriptIterator',
'settings': {'script_order': {'ScriptDummy': 0},
'iterator_type': 'Loop'},
'package': 'b26_toolkit'}}
scripts = {}
instruments = {}
scripts, loaded_failed, instruments = Script.load_and_append(
script_dict=script_dict,
scripts=scripts,
instruments=instruments, raise_errors = True)
print(('scripts', scripts))
print(('loaded_failed',loaded_failed))
print(('instruments', instruments))
print('----x')
print((scripts['DefaultName'].__class__.__name__))
print('----x')
print((scripts['DefaultName'].__class__.__name__.split('.')[0], script_dict['DefaultName']['package']))
assert scripts['DefaultName'].__class__.__name__.split('.')[0] == script_dict['DefaultName']['package']
print((type(scripts['DefaultName'].__module__)))
module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information(
script_dict['DefaultName'])
print(module)
print(script_class_name)
def test_get_module_1(self):
filepath = 'C:\\Users\\Experiment\\PycharmProjects\\pylabcontrol\\pylabcontrol\\scripts\\example_scripts.py'
print(' ===== start test_get_module_1 =======')
script_info ={'info': 'Enter docstring here', 'scripts': {'ScriptDummy': {'info': '\nExample Script that has all different types of parameters (integer, str, fload, point, list of parameters). Plots 1D and 2D data.\n ', 'settings': {'count': 3, 'name': 'this is a counter', 'wait_time': 0.1, 'point2': {'y': 0.1, 'x': 0.1}, 'tag': 'scriptdummy', 'path': '', 'save': False, 'plot_style': 'main'}, 'class': 'ScriptDummy',
'filepath': filepath}},
'class': 'ScriptIterator', 'settings': {'script_order': {'ScriptDummy': 0},
'iterator_type': 'Iter test'}, 'package': 'b26_toolkit'}
module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information(
script_info)
print(('script_class_name', script_class_name))
print(('module', module))
print(('package', package))
assert script_class_name == 'ScriptIterator'
print(' ===== end test_get_module_1 ========')
def test_load_and_append_from_file(self):
from pylabcontrol.core.read_write_functions import load_b26_file
filename = 'C:\\Users\Experiment\PycharmProjects\\user_data\pythonlab_config_lev_test.b26'
in_data = load_b26_file(filename)
instruments = in_data['instruments'] if 'instruments' in in_data else {}
scripts = in_data['scripts'] if 'scripts' in in_data else {}
probes = in_data['probes'] if 'probes' in in_data else {}
script_info = list(scripts.values())[0]
module, script_class_name, script_settings, script_instruments, script_sub_scripts, script_doc, package = Script.get_script_information(script_info)
print(('module', module.__name__.split('.')[0]))
print(('script_class_name', script_class_name))
print(('package', script_info['package']))
assert module.__name__.split('.')[0] == script_info['package']
instruments_loaded, failed = Instrument.load_and_append(instruments)
if len(failed) > 0:
print(('WARNING! Following instruments could not be loaded: ', failed))
print('========================================================================\n\n')
scripts_loaded, failed, instruments_loaded = Script.load_and_append(
script_dict=scripts,
instruments=instruments_loaded)
|
class TestInstrument(TestCase):
def test_loading_and_saving(self):
pass
def test_load_and_append(self):
pass
def test_get_module_1(self):
pass
def test_load_and_append_from_file(self):
pass
| 5 | 0 | 26 | 8 | 18 | 0 | 2 | 0 | 1 | 4 | 2 | 0 | 4 | 0 | 4 | 76 | 111 | 37 | 74 | 30 | 67 | 0 | 57 | 30 | 50 | 5 | 2 | 1 | 8 |
144,577 |
LISE-B26/pylabcontrol
|
LISE-B26_pylabcontrol/build/lib/pylabcontrol/gui/windows_and_widgets/export_dialog.py
|
lib.pylabcontrol.gui.windows_and_widgets.export_dialog.ExportDialog
|
class ExportDialog(QDialog, Ui_Dialog):
"""
This launches a dialog to allow exporting of scripts to .b26 files.
QDialog, Ui_Dialog: Define the UI and PyQt files to be used to define the dialog box
"""
def __init__(self):
super(ExportDialog, self).__init__()
self.setupUi(self)
# create models for tree structures, the models reflect the data
self.list_script_model = QtGui.QStandardItemModel()
self.list_script.setModel(self.list_script_model)
self.error_array = {}
self.list_script.selectionModel().selectionChanged.connect(self.display_info)
self.cmb_select_type.currentIndexChanged.connect(self.class_type_changed)
#
# # connect the buttons
self.btn_open_source.clicked.connect(self.open_file_dialog)
self.btn_open_target.clicked.connect(self.open_file_dialog)
self.btn_select_all.clicked.connect(self.select_all)
self.btn_select_none.clicked.connect(self.select_none)
self.btn_export.clicked.connect(self.export)
# package = get_python_package(os.getcwd())
# package, path = module_name_from_path(os.getcwd())
# self.source_path.setText(os.path.normpath(os.path.join(path + '\\' + package.split('.')[0] + '\\scripts')))
# self.target_path.setText(os.path.normpath(os.path.join(path + '\\' + package.split('.')[0] + '\\user_data\\scripts_auto_generated')))
# self.reset_avaliable(self.source_path.text())
def open_file_dialog(self):
"""
Opens a file dialog to get the path to a file and put tha tpath in the correct textbox
"""
dialog = QtWidgets.QFileDialog
sender = self.sender()
if sender == self.btn_open_source:
textbox = self.source_path
elif sender == self.btn_open_target:
textbox = self.target_path
folder = dialog.getExistingDirectory(self, 'Select a file:', textbox.text(), options = QtWidgets.QFileDialog.ShowDirsOnly)
if str(folder) != '':
textbox.setText(folder)
# load elements from file and display in tree
if sender == self.btn_open_source:
self.reset_avaliable(folder)
def reset_avaliable(self, folder):
"""
Resets the dialog box by finding all avaliable scripts that can be imported in the input folder
:param folder: folder in which to find scripts
"""
try:
self.list_script_model.removeRows(0, self.list_script_model.rowCount())
if self.cmb_select_type.currentText() == 'Script':
self.avaliable = find_scripts_in_python_files(folder)
elif self.cmb_select_type.currentText() == 'Instrument':
self.avaliable = find_instruments_in_python_files(folder)
self.fill_list(self.list_script, self.avaliable.keys())
for key in self.avaliable.keys():
self.error_array.update({key: ''})
except Exception:
msg = QtWidgets.QMessageBox()
msg.setText("Unable to parse all of the files in this folder to find possible scripts and instruments. There are non-python files or python files that are unreadable. Please select a folder that contains only pylabcontrol style python files.")
msg.exec_()
def class_type_changed(self):
"""
Forces a reset if the class type is changed from instruments to scripts or vice versa
"""
if self.source_path.text():
self.reset_avaliable(self.source_path.text())
def fill_list(self, list, input_list):
"""
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView to fill
parameters: dictionary or Parameter object which contains the information to use to fill
"""
for name in input_list:
# print(index, loaded_item, loaded_item_settings)
item = QtGui.QStandardItem(name)
item.setSelectable(True)
item.setEditable(False)
list.model().appendRow(item)
def select_none(self):
"""
Clears all selected values
"""
self.list_script.clearSelection()
def select_all(self):
"""
Selects all values
"""
self.list_script.selectAll()
def export(self):
"""
Exports the selected instruments or scripts to .b26 files. If successful, script is highlighted in green. If
failed, script is highlighted in red and error is printed to the error box.
"""
if not self.source_path.text() or not self.target_path.text():
msg = QtWidgets.QMessageBox()
msg.setText("Please set a target path for this export.")
msg.exec_()
return
selected_index = self.list_script.selectedIndexes()
for index in selected_index:
item = self.list_script.model().itemFromIndex(index)
name = str(item.text())
target_path = self.target_path.text()
try:
python_file_to_b26({name: self.avaliable[name]}, target_path, str(self.cmb_select_type.currentText()), raise_errors = True)
self.error_array.update({name: 'export successful!'})
item.setBackground(QtGui.QColor('green'))
except Exception:
self.error_array.update({name: str(traceback.format_exc())})
item.setBackground(QtGui.QColor('red'))
QtWidgets.QApplication.processEvents()
self.list_script.clearSelection()
def display_info(self):
"""
Displays the script info and, if it has been attempted to be exported, the error for a given script. Creates
hyperlinks in the traceback to the appropriate .py files (to be opened in the default .py editor).
"""
sender = self.sender()
somelist = sender.parent()
index = somelist.selectedIndexes()
if index != []:
index = index[-1]
name = str(index.model().itemFromIndex(index).text())
self.text_error.setText(self.error_array[name])
# self.text_error.setText('')
# self.text_error.setOpenExternalLinks(True)
# split_errors = self.error_array[name].split("\"")
# #displays error message with HTML link to file where error occured, which opens in default python editor
# for error in split_errors:
# if error[-3:] == '.py':
# error = error.replace("\\", "/") #format paths to be opened
# # sets up hyperlink error with filepath as displayed text in hyperlink
# # in future, can use anchorClicked signal to call python function when link clicked
# self.text_error.insertHtml("<a href = \"" + error + "\">" + error + "</a>")
# else:
# error = error.replace("\n", "<br>") #format newlines for HTML
# # would like to use insertPlainText here, but this is broken and ends up being inserted as more
# # HTML linked to the previous insertHtml, so need to insert this as HTML instead
# self.text_error.insertHtml(error)
if(self.avaliable[name]['info'] == None):
self.text_info.setText('No information avaliable')
else:
self.text_info.setText(self.avaliable[name]['info'])
|
class ExportDialog(QDialog, Ui_Dialog):
'''
This launches a dialog to allow exporting of scripts to .b26 files.
QDialog, Ui_Dialog: Define the UI and PyQt files to be used to define the dialog box
'''
def __init__(self):
pass
def open_file_dialog(self):
'''
Opens a file dialog to get the path to a file and put tha tpath in the correct textbox
'''
pass
def reset_avaliable(self, folder):
'''
Resets the dialog box by finding all avaliable scripts that can be imported in the input folder
:param folder: folder in which to find scripts
'''
pass
def class_type_changed(self):
'''
Forces a reset if the class type is changed from instruments to scripts or vice versa
'''
pass
def fill_list(self, list, input_list):
'''
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView to fill
parameters: dictionary or Parameter object which contains the information to use to fill
'''
pass
def select_none(self):
'''
Clears all selected values
'''
pass
def select_all(self):
'''
Selects all values
'''
pass
def export(self):
'''
Exports the selected instruments or scripts to .b26 files. If successful, script is highlighted in green. If
failed, script is highlighted in red and error is printed to the error box.
'''
pass
def display_info(self):
'''
Displays the script info and, if it has been attempted to be exported, the error for a given script. Creates
hyperlinks in the traceback to the appropriate .py files (to be opened in the default .py editor).
'''
pass
| 10 | 9 | 15 | 0 | 9 | 6 | 3 | 0.69 | 2 | 3 | 0 | 0 | 9 | 3 | 9 | 9 | 159 | 15 | 85 | 31 | 75 | 59 | 82 | 31 | 72 | 5 | 1 | 2 | 24 |
144,578 |
LIVVkit/LIVVkit
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.test_el_base_templates_as_class_attribute.ClassAttribute
|
class ClassAttribute(elements.BaseElement):
"""Class to test attribute definition of _*_template"""
_html_template = truth
_latex_template = truth
|
class ClassAttribute(elements.BaseElement):
'''Class to test attribute definition of _*_template'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 3 | 3 | 2 | 1 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,579 |
LIVVkit/LIVVkit
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.test_el_base_templates_as_instance_attribute.HTMLInstanceAttribute
|
class HTMLInstanceAttribute(elements.BaseElement):
"""Class to test instance attribute definition of _*_template"""
def __init__(self, html):
self._html_template = html
super(HTMLInstanceAttribute, self).__init__()
@property
def _latex_template(self):
return truth
|
class HTMLInstanceAttribute(elements.BaseElement):
'''Class to test instance attribute definition of _*_template'''
def __init__(self, html):
pass
@property
def _latex_template(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.14 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 9 | 1 | 7 | 5 | 3 | 1 | 6 | 4 | 3 | 1 | 1 | 0 | 2 |
144,580 |
LIVVkit/LIVVkit
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.test_el_base_templates_as_instance_attribute.LatexInstanceAttribute
|
class LatexInstanceAttribute(elements.BaseElement):
def __init__(self, latex):
self._latex_template = latex
super(LatexInstanceAttribute, self).__init__()
@property
def _html_template(self):
return truth
|
class LatexInstanceAttribute(elements.BaseElement):
def __init__(self, latex):
pass
@property
def _html_template(self):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 8 | 1 | 7 | 5 | 3 | 0 | 6 | 4 | 3 | 1 | 1 | 0 | 2 |
144,581 |
LIVVkit/LIVVkit
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.test_el_base_templates_as_method.HTMLMethod
|
class HTMLMethod(elements.BaseElement):
"""Class to test method definition of _*_template"""
def _html_template(self):
return truth
@property
def _latex_template(self):
return truth
|
class HTMLMethod(elements.BaseElement):
'''Class to test method definition of _*_template'''
def _html_template(self):
pass
@property
def _latex_template(self):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.17 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 8 | 1 | 6 | 4 | 2 | 1 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
144,582 |
LIVVkit/LIVVkit
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.test_el_base_templates_as_method.LatexMethod
|
class LatexMethod(elements.BaseElement):
"""Class to test method definition of _*_template"""
@property
def _html_template(self):
return truth
def _latex_template(self):
return truth
|
class LatexMethod(elements.BaseElement):
'''Class to test method definition of _*_template'''
@property
def _html_template(self):
pass
def _latex_template(self):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.17 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 8 | 1 | 6 | 4 | 2 | 1 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
144,583 |
LIVVkit/LIVVkit
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.test_el_base_templates_as_property.Property
|
class Property(elements.BaseElement):
"""Class to test property definition of _*_template"""
@property
def _html_template(self):
return truth
@property
def _latex_template(self):
return truth
|
class Property(elements.BaseElement):
'''Class to test property definition of _*_template'''
@property
def _html_template(self):
pass
@property
def _latex_template(self):
pass
| 5 | 1 | 2 | 0 | 2 | 0 | 1 | 0.14 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 9 | 1 | 7 | 5 | 2 | 1 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
144,584 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.Image
|
class Image(BaseElement):
"""A LIVVkit Image element
The Image element produces an image/figure in the report.
"""
_html_template = 'image.html'
_latex_template = 'image.tex'
def __init__(self, title, desc, image_file, group=None, height=None, relative_to=None):
"""Initialize a Section element
Args:
title: The title of the image
desc: A description of the image which in most report forms will be
figure caption
image_file: The path to the image to display. Note: this should resolve
to a path inside the report output directory
group: Group the images into a JavaScript Lightbox with this name
(default: None). Note: this is only relevant for an HTML report
height: The height of the image in pixels
relative_to: Transform the image path to be relative to this
directory. By default, the image will assumed to be in the
directory, or a subdirectory, of the page it's displayed on.
"""
super(Image, self).__init__()
self.title = title
self.desc = desc
self.path, self.name = os.path.split(image_file)
# FIXME: This assumes that images are images are always located in a
# subdirectory of the current page if a relative path start
# location isn't specified
if relative_to is None:
relative_to = os.path.dirname(self.path)
self.path = os.path.relpath(self.path, relative_to)
self.group = group
self.height = height
def _repr_latex(self):
template = _latex_env.get_template(self._latex_template)
data = self.__dict__
data['path'] = self.path.lstrip('/')
return template.render(data=data)
|
class Image(BaseElement):
'''A LIVVkit Image element
The Image element produces an image/figure in the report.
'''
def __init__(self, title, desc, image_file, group=None, height=None, relative_to=None):
'''Initialize a Section element
Args:
title: The title of the image
desc: A description of the image which in most report forms will be
figure caption
image_file: The path to the image to display. Note: this should resolve
to a path inside the report output directory
group: Group the images into a JavaScript Lightbox with this name
(default: None). Note: this is only relevant for an HTML report
height: The height of the image in pixels
relative_to: Transform the image path to be relative to this
directory. By default, the image will assumed to be in the
directory, or a subdirectory, of the page it's displayed on.
'''
pass
def _repr_latex(self):
pass
| 3 | 2 | 17 | 1 | 8 | 9 | 2 | 1.11 | 1 | 1 | 0 | 2 | 2 | 6 | 2 | 28 | 42 | 4 | 18 | 12 | 15 | 20 | 18 | 12 | 15 | 2 | 5 | 1 | 3 |
144,585 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.Gallery
|
class Gallery(CompositeElement):
"""A LIVVkit Gallery element
The Gallery element is a super element intended to group LIVVkit Image
elements into a gallery. It also will allow for the generation of other
(experimental!) Report types (e.g., LaTeX), where the "Gallery" meaning
might be better interpreted as a figure "subsection".
"""
_html_template = 'gallery.html'
_latex_template = 'gallery.tex'
def __init__(self, title, elements):
"""Initialize a Gallery element
Args:
title: The title of the image gallery
elements: A list of LIVVkit Image elements to display within the
gallery
"""
super(Gallery, self).__init__(elements)
self.title = title
|
class Gallery(CompositeElement):
'''A LIVVkit Gallery element
The Gallery element is a super element intended to group LIVVkit Image
elements into a gallery. It also will allow for the generation of other
(experimental!) Report types (e.g., LaTeX), where the "Gallery" meaning
might be better interpreted as a figure "subsection".
'''
def __init__(self, title, elements):
'''Initialize a Gallery element
Args:
title: The title of the image gallery
elements: A list of LIVVkit Image elements to display within the
gallery
'''
pass
| 2 | 2 | 10 | 1 | 3 | 6 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 31 | 21 | 3 | 6 | 5 | 4 | 12 | 6 | 5 | 4 | 1 | 6 | 0 | 1 |
144,586 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.Section
|
class Section(CompositeElement):
"""A LIVVkit Section element
The Section element is a super element intended to logically separate elements
into titled sections. It also will allow for the generation of other
(experimental!) Report types (e.g., LaTeX), where the "section" meaning might
be better interpreted as a "subsection".
"""
_html_template = 'section.html'
_latex_template = 'section.tex'
def __init__(self, title, elements):
"""Initialize a Section element
Args:
title: The title of the section
elements: A list of LIVVkit elements to display within the section
"""
super(Section, self).__init__(elements)
self.title = title
|
class Section(CompositeElement):
'''A LIVVkit Section element
The Section element is a super element intended to logically separate elements
into titled sections. It also will allow for the generation of other
(experimental!) Report types (e.g., LaTeX), where the "section" meaning might
be better interpreted as a "subsection".
'''
def __init__(self, title, elements):
'''Initialize a Section element
Args:
title: The title of the section
elements: A list of LIVVkit elements to display within the section
'''
pass
| 2 | 2 | 9 | 1 | 3 | 5 | 1 | 1.83 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 31 | 20 | 3 | 6 | 5 | 4 | 11 | 6 | 5 | 4 | 1 | 6 | 0 | 1 |
144,587 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.Table
|
class Table(BaseElement):
"""A LIVVkit Table element
The Table element will produce a table in the analysis report.
"""
_html_template = 'table.html'
_latex_template = 'table.tex'
def __init__(self, title, data, index=False, transpose=False):
"""Initialize a Section element
Args:
title: The title of the table
data: The data to display in the table in the form of either
a pandas DataFrame or a dictionary of the form
{column1:[row1, row2...],... } where each (key, value)
item is a table column, with the key being the column
header and the value being a list of that's columns' row
values.
index: The index to include in the table. If False, no index
will be included. If True, a numbered index beginning at
zero will be included in the table. If a collection of
values the same length as the data rows, the collection
will be used to label the rows.
transpose: A boolean (default: False) which will flip the
table (headers become the index, index becomes the header).
"""
super(Table, self).__init__()
self.title = title
if isinstance(data, pd.DataFrame):
self.data = data.to_dict(orient='list')
self.index = data.index.to_list()
else:
self.data = data
self.index = None
self.rows = len(next(iter(self.data.values())))
if index is True and self.index is None:
self.index = range(self.rows)
elif isinstance(index, collections.abc.Collection):
if len(index) != self.rows:
raise IndexError('Table index must be the same length as the table. '
'Table rows: {}, index length: {}.'.format(self.rows, len(index)))
self.index = index
if transpose:
self._html_template = 'table_transposed.html'
self._latex_template = 'table_transposed.tex'
def _repr_html(self):
"""Represent this element as HTML
Using the jinja2 template defined by ``self._html_template``, return an
HTML representation of this element
Returns:
str: The HTML representation of this element
"""
template = _html_env.get_template(self._html_template)
return template.render(data=self.__dict__, rows=self.rows, index=self.index)
def _repr_latex(self):
"""Represent this element as LaTeX
Using the jinja2 template defined by ``self._latex_template``, return an
LaTeX representation of this element
Returns:
str: The LaTeX representation of this element
"""
template = _latex_env.get_template(self._latex_template)
return template.render(data=self.__dict__, rows=self.rows, index=self.index)
|
class Table(BaseElement):
'''A LIVVkit Table element
The Table element will produce a table in the analysis report.
'''
def __init__(self, title, data, index=False, transpose=False):
'''Initialize a Section element
Args:
title: The title of the table
data: The data to display in the table in the form of either
a pandas DataFrame or a dictionary of the form
{column1:[row1, row2...],... } where each (key, value)
item is a table column, with the key being the column
header and the value being a list of that's columns' row
values.
index: The index to include in the table. If False, no index
will be included. If True, a numbered index beginning at
zero will be included in the table. If a collection of
values the same length as the data rows, the collection
will be used to label the rows.
transpose: A boolean (default: False) which will flip the
table (headers become the index, index becomes the header).
'''
pass
def _repr_html(self):
'''Represent this element as HTML
Using the jinja2 template defined by ``self._html_template``, return an
HTML representation of this element
Returns:
str: The HTML representation of this element
'''
pass
def _repr_latex(self):
'''Represent this element as LaTeX
Using the jinja2 template defined by ``self._latex_template``, return an
LaTeX representation of this element
Returns:
str: The LaTeX representation of this element
'''
pass
| 4 | 4 | 21 | 3 | 9 | 10 | 3 | 1.1 | 1 | 3 | 0 | 0 | 3 | 5 | 3 | 29 | 74 | 13 | 29 | 13 | 25 | 32 | 26 | 12 | 22 | 6 | 5 | 2 | 8 |
144,588 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.Tabs
|
class Tabs(NamedCompositeElement):
"""A LIVVkit Tabs element
The Tabs element is a super element intended to logically separate elements
into clickable tabs on the output website. It also will allow for the
generation of other (experimental!) Report types (e.g., LaTeX), where the
"tabs" meaning might be better interpreted as a "subsection".
"""
_html_template = 'tabs.html'
_latex_template = 'tabs.tex'
def __init__(self, tabs):
"""Initialize a Tabs element
Args:
tabs: A dictionary where each (key, value) item represents a tab.
Keys will become the tab text and values should be lists of
LIVVkit elements to display within the tab
"""
super(Tabs, self).__init__(tabs)
|
class Tabs(NamedCompositeElement):
'''A LIVVkit Tabs element
The Tabs element is a super element intended to logically separate elements
into clickable tabs on the output website. It also will allow for the
generation of other (experimental!) Report types (e.g., LaTeX), where the
"tabs" meaning might be better interpreted as a "subsection".
'''
def __init__(self, tabs):
'''Initialize a Tabs element
Args:
tabs: A dictionary where each (key, value) item represents a tab.
Keys will become the tab text and values should be lists of
LIVVkit elements to display within the tab
'''
pass
| 2 | 2 | 9 | 1 | 2 | 6 | 1 | 2.4 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 31 | 20 | 3 | 5 | 4 | 3 | 12 | 5 | 4 | 3 | 1 | 6 | 0 | 1 |
144,589 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/util/LIVVDict.py
|
livvkit.util.LIVVDict.LIVVDict
|
class LIVVDict(dict):
"""
Extension of the dictionary data structure to allow for auto nesting.
"""
def __getitem__(self, item):
"""
Tries to get the item, and if it's not found creates it
Credit to: http://tiny.cc/qerr7x
"""
try:
return dict.__getitem__(self, item)
except KeyError:
tmp = type(self)()
self[item] = tmp
return tmp
def nested_insert(self, item_list):
""" Create a series of nested LIVVDicts given a list """
if len(item_list) == 1:
self[item_list[0]] = LIVVDict()
elif len(item_list) > 1:
if item_list[0] not in self:
self[item_list[0]] = LIVVDict()
self[item_list[0]].nested_insert(item_list[1:])
def nested_assign(self, key_list, value):
""" Set the value of nested LIVVDicts given a list """
if len(key_list) == 1:
self[key_list[0]] = value
elif len(key_list) > 1:
if key_list[0] not in self:
self[key_list[0]] = LIVVDict()
self[key_list[0]].nested_assign(key_list[1:], value)
|
class LIVVDict(dict):
'''
Extension of the dictionary data structure to allow for auto nesting.
'''
def __getitem__(self, item):
'''
Tries to get the item, and if it's not found creates it
Credit to: http://tiny.cc/qerr7x
'''
pass
def nested_insert(self, item_list):
''' Create a series of nested LIVVDicts given a list '''
pass
def nested_assign(self, key_list, value):
''' Set the value of nested LIVVDicts given a list '''
pass
| 4 | 4 | 9 | 0 | 7 | 2 | 3 | 0.41 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 30 | 33 | 2 | 22 | 5 | 18 | 9 | 20 | 5 | 16 | 4 | 2 | 2 | 10 |
144,590 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/util/bib.py
|
livvkit.util.bib.HTMLBackend
|
class HTMLBackend(HTMLBaseBackend):
def __init__(self, *args, **kwargs):
super(HTMLBackend, self).__init__(*args, **kwargs)
self._html = ''
def output(self, html):
self._html += html
def format_protected(self, text):
if text[:4] == 'http':
return self.format_href(text, text)
else:
return r'<span class="bibtex-protected">{}</span>'.format(text)
def write_prologue(self):
self.output('<div class="bibliography"><h2>References</h2>'
'<p>LIVVkit is an open source project licensed under a BSD 3-clause License. '
'We ask that you please acknowledge LIVVkit in any work it is used or supports. '
'In any corresponding published work, please cite: </p><dl>')
def write_epilogue(self):
self.output('</dl></div>')
def _repr_html(self, formatted_bibliography):
self.write_prologue()
for entry in formatted_bibliography:
self.write_entry(entry.key, entry.label, entry.text.render(self))
self.write_epilogue()
return self._html.replace('\n', ' ').replace('\\url <a', '<a')
|
class HTMLBackend(HTMLBaseBackend):
def __init__(self, *args, **kwargs):
pass
def output(self, html):
pass
def format_protected(self, text):
pass
def write_prologue(self):
pass
def write_epilogue(self):
pass
def _repr_html(self, formatted_bibliography):
pass
| 7 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 6 | 1 | 6 | 6 | 30 | 6 | 24 | 9 | 17 | 0 | 20 | 9 | 13 | 2 | 1 | 1 | 8 |
144,591 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/util/bib.py
|
livvkit.util.bib.LatexBackend
|
class LatexBackend(LatexBaseBackend):
def __init__(self, *args, **kwargs):
super(LatexBackend, self).__init__(*args, **kwargs)
def _repr_html(self, formatted_bibliography):
stream = io.StringIO()
self.write_to_stream(formatted_bibliography, stream)
return stream.getvalue()
|
class LatexBackend(LatexBaseBackend):
def __init__(self, *args, **kwargs):
pass
def _repr_html(self, formatted_bibliography):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 8 | 1 | 7 | 4 | 4 | 0 | 7 | 4 | 4 | 1 | 1 | 0 | 2 |
144,592 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/util/functions.py
|
livvkit.util.functions.TempSysPath
|
class TempSysPath(object):
"""Add a path to the PYTHONPATH temporarily"""
def __init__(self, path):
self.path = path
def __enter__(self):
sys.path.insert(0, self.path)
def __exit__(self, *args):
sys.path.remove(self.path)
|
class TempSysPath(object):
'''Add a path to the PYTHONPATH temporarily'''
def __init__(self, path):
pass
def __enter__(self):
pass
def __exit__(self, *args):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.14 | 1 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 10 | 2 | 7 | 5 | 3 | 1 | 7 | 5 | 3 | 1 | 1 | 0 | 3 |
144,593 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.NAImage
|
class NAImage(Image):
"""A NAImage element
A dummy Image that can be used to indicate a missing image
"""
def __init__(self, title, description, page_path):
"""Initialize a dummy NAImage element
Args:
title: The title of the image
description: A description of the image which in most report forms
will be figure caption
page_path: The path to the page on which the dummy image will be
displayed
"""
image_file = os.path.join(livvkit.output_dir, 'imgs', 'na.png')
super(NAImage, self).__init__(title, description,
image_file=image_file,
relative_to=page_path,
height=50, group='na')
|
class NAImage(Image):
'''A NAImage element
A dummy Image that can be used to indicate a missing image
'''
def __init__(self, title, description, page_path):
'''Initialize a dummy NAImage element
Args:
title: The title of the image
description: A description of the image which in most report forms
will be figure caption
page_path: The path to the page on which the dummy image will be
displayed
'''
pass
| 2 | 2 | 16 | 2 | 6 | 8 | 1 | 1.57 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 29 | 21 | 3 | 7 | 3 | 5 | 11 | 4 | 3 | 2 | 1 | 6 | 0 | 1 |
144,594 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.FileDiff
|
class FileDiff(BaseElement):
"""A LIVVkit FileDiff element
The FilleDiff element will compare two text files and produce a git-diff
style diff of the files.
"""
_html_template = 'diff.html'
_latex_template = 'diff.tex'
def __init__(self, title, from_file, to_file, context=3):
"""Initialize a FileDiff element
Args:
title: The title of the diff
from_file: A path to the file which will be compared against
to_file: A path to the file which which to compare
context: An positive int indicating the number of lines of context
to display on either side of each difference found
"""
super(FileDiff, self).__init__()
self.title = title
self.from_file = from_file
self.to_file = to_file
self.diff, self.diff_status = self.diff_files(context=context)
def diff_files(self, context=3):
"""Perform the file diff
Args:
context: An positive int indicating the number of lines of context
to display on either side of each difference found
Returns:
(tuple): Tuple containing:
difference: A str containing either a git-style diff of the
files if a difference was found or the original file in
full
diff_status: A boolean indicating whether any differences were
found
"""
with open(self.from_file) as from_, open(self.to_file) as to_:
fromlines = from_.read().splitlines()
tolines = to_.read().splitlines()
if context is None:
context = max(len(fromlines), len(tolines))
diff = list(difflib.unified_diff(fromlines, tolines,
n=context, lineterm=''))
diff_status = True
if not diff:
diff_status = False
diff = fromlines
return diff, diff_status
|
class FileDiff(BaseElement):
'''A LIVVkit FileDiff element
The FilleDiff element will compare two text files and produce a git-diff
style diff of the files.
'''
def __init__(self, title, from_file, to_file, context=3):
'''Initialize a FileDiff element
Args:
title: The title of the diff
from_file: A path to the file which will be compared against
to_file: A path to the file which which to compare
context: An positive int indicating the number of lines of context
to display on either side of each difference found
'''
pass
def diff_files(self, context=3):
'''Perform the file diff
Args:
context: An positive int indicating the number of lines of context
to display on either side of each difference found
Returns:
(tuple): Tuple containing:
difference: A str containing either a git-style diff of the
files if a difference was found or the original file in
full
diff_status: A boolean indicating whether any differences were
found
'''
pass
| 3 | 3 | 22 | 3 | 10 | 10 | 2 | 1.09 | 1 | 2 | 0 | 0 | 2 | 5 | 2 | 28 | 54 | 8 | 22 | 14 | 19 | 24 | 21 | 13 | 18 | 3 | 5 | 2 | 4 |
144,595 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.Error
|
class Error(BaseElement):
"""A LIVVkit Error element
The Error element will produce an error message in the analysis report.
"""
_html_template = 'err.html'
_latex_template = 'err.tex'
def __init__(self, title, message):
"""Initialize a LIVVkit Error element
Args:
title: The title of the error
message: The error message to display
"""
super(Error, self).__init__()
self.title = title
self.message = message
|
class Error(BaseElement):
'''A LIVVkit Error element
The Error element will produce an error message in the analysis report.
'''
def __init__(self, title, message):
'''Initialize a LIVVkit Error element
Args:
title: The title of the error
message: The error message to display
'''
pass
| 2 | 2 | 10 | 1 | 4 | 5 | 1 | 1.14 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 27 | 18 | 3 | 7 | 6 | 5 | 8 | 7 | 6 | 5 | 1 | 5 | 0 | 1 |
144,596 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.BitForBit
|
class BitForBit(CompositeElement):
"""A LIVVkit BitForBit element
The BitForBit element will produce a table in the analysis report indicating
bit-for-bit statuses with a difference image shown in the final column of
the table.
"""
_html_template = 'bit4bit.html'
_latex_template = 'bit4bit.tex'
def __init__(self, title, data, imgs):
"""Initialize a BitForBit element
Args:
title: The title of the bit-for-bit comparisons
data: The data to display in the table in the form of either
a pandas DataFrame or a dictionary of the form
{column1:[row1, row2...],... } where each (key, value)
item is a table column, with the key being the column
header and the value being a list of that's columns' row
values
imgs: A list of LIVVkit Image elements to display in an additional
final column of the bit-for-bit table. Note: The list must be
same length as the number of rows in the table data
"""
super(BitForBit, self).__init__(imgs)
self.title = title
if isinstance(data, pd.DataFrame):
self.data = data.to_dict(orient='list')
else:
self.data = data
self.rows = len(next(iter(self.data.values())))
if len(imgs) != self.rows:
raise IndexError('Imgs must be the same length as the table. '
'Table rows: {}, imgs length: {}.'.format(self.rows, len(imgs)))
def _repr_html(self):
"""Represent this element as HTML
Using the jinja2 template defined by ``self._html_template``, return an
HTML representation of this element
Returns:
str: The HTML representation of this element
"""
imgs_repr = [img._repr_html() for img in self.elements]
template = _html_env.get_template(self._html_template)
return template.render(data=self.__dict__, rows=self.rows, b4b_imgs=imgs_repr)
def _repr_latex(self):
"""Represent this element as LaTeX
Using the jinja2 template defined by ``self._latex_template``, return an
LaTeX representation of this element
Returns:
str: The LaTeX representation of this element
"""
imgs_repr = [img._repr_latex() for img in self.elements]
template = _latex_env.get_template(self._latex_template)
return template.render(data=self.__dict__, rows=self.rows, b4b_imgs=imgs_repr)
|
class BitForBit(CompositeElement):
'''A LIVVkit BitForBit element
The BitForBit element will produce a table in the analysis report indicating
bit-for-bit statuses with a difference image shown in the final column of
the table.
'''
def __init__(self, title, data, imgs):
'''Initialize a BitForBit element
Args:
title: The title of the bit-for-bit comparisons
data: The data to display in the table in the form of either
a pandas DataFrame or a dictionary of the form
{column1:[row1, row2...],... } where each (key, value)
item is a table column, with the key being the column
header and the value being a list of that's columns' row
values
imgs: A list of LIVVkit Image elements to display in an additional
final column of the bit-for-bit table. Note: The list must be
same length as the number of rows in the table data
'''
pass
def _repr_html(self):
'''Represent this element as HTML
Using the jinja2 template defined by ``self._html_template``, return an
HTML representation of this element
Returns:
str: The HTML representation of this element
'''
pass
def _repr_latex(self):
'''Represent this element as LaTeX
Using the jinja2 template defined by ``self._latex_template``, return an
LaTeX representation of this element
Returns:
str: The LaTeX representation of this element
'''
pass
| 4 | 4 | 17 | 2 | 6 | 8 | 2 | 1.36 | 1 | 2 | 0 | 0 | 3 | 4 | 3 | 33 | 63 | 11 | 22 | 14 | 18 | 30 | 20 | 13 | 16 | 3 | 6 | 1 | 5 |
144,597 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.B4BImage
|
class B4BImage(Image):
"""A B4BImage element
A dummy Image that can be used by the BitForBit element indicating a
bit-for-bit verification result.
"""
def __init__(self, title, description, page_path):
"""Initialize a dummy B4BImage element
Args:
title: The title of the image
description: A description of the image which in most report forms
will be figure caption
page_path: The path to the page on which the dummy image will be
displayed
"""
image_file = os.path.join(livvkit.output_dir, 'imgs', 'b4b.png')
super(B4BImage, self).__init__(title, description,
image_file=image_file,
relative_to=page_path,
height=50, group='b4b')
|
class B4BImage(Image):
'''A B4BImage element
A dummy Image that can be used by the BitForBit element indicating a
bit-for-bit verification result.
'''
def __init__(self, title, description, page_path):
'''Initialize a dummy B4BImage element
Args:
title: The title of the image
description: A description of the image which in most report forms
will be figure caption
page_path: The path to the page on which the dummy image will be
displayed
'''
pass
| 2 | 2 | 16 | 2 | 6 | 8 | 1 | 1.71 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 29 | 22 | 3 | 7 | 3 | 5 | 12 | 4 | 3 | 2 | 1 | 6 | 0 | 1 |
144,598 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/bundles/CISM_glissade/numerics.py
|
livvkit.bundles.CISM_glissade.numerics.RotatedGrid
|
class RotatedGrid:
"""
For the ISMIP-HOM f tests, CISM computes the flow of a glacier down an
inclined plane:
::
z
^
|
* .
. .
. .
* .
| . .
| . ICE .
| . .
| . .
| BED . .
| . *
| . .
| . .
| . .
| *
| |
| |
| |
0------------------------------------->x
The origin is at point 0 in the above figure, and the topmost point of the
glacier is at x=0, z=7 (in km). The slope is 3 degrees. The ice is 1000 m
tall and flows down the inclined plane.
ISMIP-HOM, however, defines the coordinate system with the origin located at
the topmost point of the glacier (0,7) with the x' axis pointing down slope
and z' pointing perpendicular to the slope. So the coordinate system is
shifted, and rotated by a=3 degrees from the CISM glissade grid.
An additional complication is that the surface is computed in CISM on the
standard grid, but velocities are computed on a staggered, grid.
This class converts the CISM_glissade coordinate system to the ISMIP-HOM
coordinate system.
"""
def __init__(self, alpha, data):
self.alpha = alpha
self.y0 = data.variables['y0'][:]
self.x0 = data.variables['x0'][:]
self.usurf_ustag = data.variables['usurf'][-1,:,:]
self.usurf_stag = ( self.usurf_ustag[1: , 1: ] + self.usurf_ustag[1: , :-1]
+ self.usurf_ustag[:-1, :-1] + self.usurf_ustag[:-1, 1: ]) / 4.0
self.usurf = -(self.x0)*math.sin(alpha) + (self.usurf_stag-7000.0)*math.cos(alpha)
self.uvel_stag = data.variables['uvel'][-1,0,:,:]
self.vvel_stag = data.variables['uvel'][-1,0,:,:]
try:
self.wvel_ustag = data.variables['wvel_ho'][-1,0,:,:]
except:
self.wvel_ustag = data.variables['wvel'][-1,0,:,:]
self.wvel_stag = ( self.wvel_ustag[1: , 1: ] + self.wvel_ustag[1: , :-1]
+ self.wvel_ustag[:-1, :-1] + self.wvel_ustag[:-1, 1: ]) / 4.0
self.uvel = self.uvel_stag*math.cos(alpha) + self.wvel_stag*math.sin(alpha)
self.vvel = -self.uvel_stag*math.sin(alpha) + self.wvel_stag*math.cos(alpha)
self.x = (self.x0*math.cos(alpha)
+ (self.usurf_stag[20,:]-7000.0)*math.sin(alpha)
)/1000.0 - 50.0
self.y = self.y0/1000.0 - 50.0
|
class RotatedGrid:
'''
For the ISMIP-HOM f tests, CISM computes the flow of a glacier down an
inclined plane:
::
z
^
|
* .
. .
. .
* .
| . .
| . ICE .
| . .
| . .
| BED . .
| . *
| . .
| . .
| . .
| *
| |
| |
| |
0------------------------------------->x
The origin is at point 0 in the above figure, and the topmost point of the
glacier is at x=0, z=7 (in km). The slope is 3 degrees. The ice is 1000 m
tall and flows down the inclined plane.
ISMIP-HOM, however, defines the coordinate system with the origin located at
the topmost point of the glacier (0,7) with the x' axis pointing down slope
and z' pointing perpendicular to the slope. So the coordinate system is
shifted, and rotated by a=3 degrees from the CISM glissade grid.
An additional complication is that the surface is computed in CISM on the
standard grid, but velocities are computed on a staggered, grid.
This class converts the CISM_glissade coordinate system to the ISMIP-HOM
coordinate system.
'''
def __init__(self, alpha, data):
pass
| 2 | 1 | 28 | 6 | 22 | 0 | 2 | 1.61 | 0 | 0 | 0 | 0 | 1 | 14 | 1 | 1 | 73 | 13 | 23 | 16 | 21 | 37 | 19 | 16 | 17 | 2 | 0 | 1 | 2 |
144,599 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/bundles/CISM_glissade/numerics.py
|
livvkit.bundles.CISM_glissade.numerics.DataGrid
|
class DataGrid:
"""
Class to handle the CISM_glissade grids, which are cell-centered grids.
"""
def __init__(self, data):
self.y = data.variables['y1']
self.ny = self.y[:].shape[0]
self.dy = self.y[1] - self.y[0]
# NOTE: cell centered grids, hence the dy.
self.Ly = self.y[-1] - self.y[0] + self.dy
self.x = data.variables['x1']
self.nx = self.x[:].shape[0]
self.dx = self.x[1] - self.x[0]
# NOTE: cell centered grids, hence the dx.
self.Lx = self.x[-1] - self.x[0] + self.dx
self.y_hat = (self.y[:] + self.y[0])/self.Ly
self.x_hat = (self.x[:] + self.x[0])/self.Lx
|
class DataGrid:
'''
Class to handle the CISM_glissade grids, which are cell-centered grids.
'''
def __init__(self, data):
pass
| 2 | 1 | 17 | 4 | 11 | 2 | 1 | 0.42 | 0 | 0 | 0 | 0 | 1 | 10 | 1 | 1 | 21 | 4 | 12 | 12 | 10 | 5 | 12 | 12 | 10 | 1 | 0 | 0 | 1 |
144,600 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/tests/test_elements.py
|
test_elements.LIVVkitOutput
|
class LIVVkitOutput(ContextDecorator):
"""Decorator to set the required livvkit variable `livvkit.output_dir`"""
def __enter__(self):
livvkit.output_dir = 'vv_test'
def __exit__(self, exc_type, exc_val, exc_tb):
livvkit.output_dir = None
|
class LIVVkitOutput(ContextDecorator):
'''Decorator to set the required livvkit variable `livvkit.output_dir`'''
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.2 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 4 | 7 | 1 | 5 | 3 | 2 | 1 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
144,601 |
LIVVkit/LIVVkit
|
LIVVkit_LIVVkit/livvkit/elements/elements.py
|
livvkit.elements.elements.RawHTML
|
class RawHTML(BaseElement):
"""A LIVVkit RawHTML element
The RawHTML element will directly display the contained HTML in the analysis
report. For an HTML report (default) this will be directly written onto the
page so is a potential security hole and should be used with caution. For the
experimental report types (e.g., LaTeX) the contained HTML will be written to
report in a code display block or as a raw string.
"""
_html_template = 'raw.html'
_latex_template = 'raw.tex'
def __init__(self, html):
"""Initialize a LIVVkit RawHTML element
Args:
html: An HTML str
"""
super(RawHTML, self).__init__()
self.html = html
|
class RawHTML(BaseElement):
'''A LIVVkit RawHTML element
The RawHTML element will directly display the contained HTML in the analysis
report. For an HTML report (default) this will be directly written onto the
page so is a potential security hole and should be used with caution. For the
experimental report types (e.g., LaTeX) the contained HTML will be written to
report in a code display block or as a raw string.
'''
def __init__(self, html):
'''Initialize a LIVVkit RawHTML element
Args:
html: An HTML str
'''
pass
| 2 | 2 | 8 | 1 | 3 | 4 | 1 | 1.83 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 27 | 20 | 3 | 6 | 5 | 4 | 11 | 6 | 5 | 4 | 1 | 5 | 0 | 1 |
144,602 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.TLSFileType
|
class TLSFileType(Enum):
KEY = "key"
CERT = "cert"
CA = "ca"
|
class TLSFileType(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
144,603 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.TLSFileBundle
|
class TLSFileBundle:
"""Maintains information that is shared by a set of TLSFiles"""
def __init__(
self,
common_name,
files=None,
x509s=None,
serial=0,
is_ca=False,
parent_ca="",
signees=None,
):
self.record = {}
self.record["serial"] = serial
self.record["is_ca"] = is_ca
self.record["parent_ca"] = parent_ca
self.record["signees"] = signees
for t in TLSFileType:
setattr(self, t.value, None)
files = files or {}
x509s = x509s or {}
self._setup_tls_files(files)
self.save_x509s(x509s)
def _setup_tls_files(self, files):
"""Initiates TLSFIle objects with the paths given to this bundle"""
for file_type in TLSFileType:
if file_type.value in files:
file_path = files[file_type.value]
setattr(self, file_type.value, TLSFile(file_path, file_type=file_type))
def save_x509s(self, x509s):
"""Saves the x509 objects to the paths known by this bundle"""
for file_type in TLSFileType:
if file_type.value in x509s:
x509 = x509s[file_type.value]
if file_type is not TLSFileType.CA:
# persist this key or cert to disk
tlsfile = getattr(self, file_type.value)
if tlsfile:
tlsfile.save(x509)
def load_all(self):
"""Utility to load bring all files into memory"""
for t in TLSFileType:
self[t.value].load()
return self
def is_ca(self):
"""Is this bundle for a CA certificate"""
return self.record["is_ca"]
def to_record(self):
"""Create a CertStore record from this TLSFileBundle"""
tf_list = [getattr(self, k, None) for k in [_.value for _ in TLSFileType]]
# If a cert isn't defined in this bundle, remove it
tf_list = filter(lambda x: x, tf_list)
files = {tf.file_type.value: tf.file_path for tf in tf_list}
self.record["files"] = files
return self.record
def from_record(self, record):
"""Build a bundle from a CertStore record"""
self.record = record
self._setup_tls_files(self.record["files"])
return self
|
class TLSFileBundle:
'''Maintains information that is shared by a set of TLSFiles'''
def __init__(
self,
common_name,
files=None,
x509s=None,
serial=0,
is_ca=False,
parent_ca="",
signees=None,
):
pass
def _setup_tls_files(self, files):
'''Initiates TLSFIle objects with the paths given to this bundle'''
pass
def save_x509s(self, x509s):
'''Saves the x509 objects to the paths known by this bundle'''
pass
def load_all(self):
'''Utility to load bring all files into memory'''
pass
def is_ca(self):
'''Is this bundle for a CA certificate'''
pass
def to_record(self):
'''Create a CertStore record from this TLSFileBundle'''
pass
def from_record(self, record):
'''Build a bundle from a CertStore record'''
pass
| 8 | 7 | 9 | 1 | 7 | 1 | 2 | 0.18 | 0 | 3 | 2 | 0 | 7 | 1 | 7 | 7 | 73 | 13 | 51 | 27 | 34 | 9 | 42 | 18 | 34 | 5 | 0 | 4 | 15 |
144,604 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.CertNotFoundError
|
class CertNotFoundError(Exception):
def __init__(self, message, errors=None):
super().__init__(message)
self.errors = errors
|
class CertNotFoundError(Exception):
def __init__(self, message, errors=None):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 11 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 3 | 0 | 1 |
144,605 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.CertStore
|
class CertStore:
"""Maintains records of certificates created by Certipy
Minimally, each record keyed by common name needs:
- file
- path
- type
- serial number
- parent CA
- signees
Common names, for the sake of simplicity, are assumed to be unique.
If a pair of certs need to be valid for the same IP/DNS address (ex:
localhost), that information can be specified in the Subject Alternative
Name field.
"""
def __init__(
self, containing_dir="out", store_file="certipy.json", remove_existing=False
):
self.store = {}
self.containing_dir = containing_dir
self.store_file_path = os.path.join(containing_dir, store_file)
try:
if remove_existing:
shutil.rmtree(containing_dir)
os.stat(containing_dir)
self.load()
except FileNotFoundError:
os.makedirs(containing_dir, mode=0o755, exist_ok=True)
finally:
os.chmod(containing_dir, mode=0o755)
def save(self):
"""Write the store dict to a file specified by store_file_path"""
with open(self.store_file_path, "w") as fh:
fh.write(json.dumps(self.store, indent=4))
def load(self):
"""Read the store dict from file"""
with open(self.store_file_path, "r") as fh:
self.store = json.loads(fh.read())
def get_record(self, common_name):
"""Return the record associated with this common name
In most cases, all that's really needed to use an existing cert are
the file paths to the files that make up that cert. This method
returns just that and doesn't bother loading the associated files.
"""
try:
record = self.store[common_name]
return record
except KeyError as e:
raise CertNotFoundError(
"Unable to find record of {name}".format(name=common_name), errors=e
)
def get_files(self, common_name):
"""Return a bundle of TLS files associated with a common name"""
record = self.get_record(common_name)
return TLSFileBundle(common_name).from_record(record)
def add_record(
self,
common_name,
serial=0,
parent_ca="",
signees=None,
files=None,
record=None,
is_ca=False,
overwrite=False,
):
"""Manually create a record of certs
Generally, Certipy can be left to manage certificate locations and
storage, but it is occasionally useful to keep track of a set of
certs that were created externally (for example, let's encrypt)
"""
if not overwrite:
try:
self.get_record(common_name)
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add.".format(name=common_name)
)
except CertNotFoundError:
pass
record = record or {
"serial": serial,
"is_ca": is_ca,
"parent_ca": parent_ca,
"signees": signees,
"files": files,
}
self.store[common_name] = record
self.save()
def add_files(
self,
common_name,
x509s,
files=None,
parent_ca="",
is_ca=False,
signees=None,
serial=0,
overwrite=False,
):
"""Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these files to disk and automatically calls save
on all TLSFiles that it creates (and where it makes sense to).
"""
if common_name in self.store and not overwrite:
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add.".format(name=common_name)
)
elif common_name in self.store and overwrite:
record = self.get_record(common_name)
serial = int(record["serial"])
record["serial"] = serial + 1
TLSFileBundle(common_name).from_record(record).save_x509s(x509s)
else:
file_base_tmpl = "{prefix}/{cn}/{cn}"
file_base = file_base_tmpl.format(
prefix=self.containing_dir, cn=common_name
)
try:
ca_record = self.get_record(parent_ca)
ca_file = ca_record["files"]["cert"]
except CertNotFoundError:
ca_file = ""
files = files or {
"key": file_base + ".key",
"cert": file_base + ".crt",
"ca": ca_file,
}
bundle = TLSFileBundle(
common_name,
files=files,
x509s=x509s,
is_ca=is_ca,
serial=serial,
parent_ca=parent_ca,
signees=signees,
)
self.store[common_name] = bundle.to_record()
self.save()
def add_sign_link(self, ca_name, signee_name):
"""Adds to the CA signees and a parent ref to the signee"""
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record["signees"] or {}
signees = Counter(signees)
if signee_name not in signees:
signees[signee_name] = 1
ca_record["signees"] = signees
signee_record["parent_ca"] = ca_name
self.save()
def remove_sign_link(self, ca_name, signee_name):
"""Removes signee_name to the signee list for ca_name"""
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record["signees"] or {}
signees = Counter(signees)
if signee_name in signees:
signees[signee_name] = 0
ca_record["signees"] = signees
signee_record["parent_ca"] = ""
self.save()
def update_record(self, common_name, **fields):
"""Update fields in an existing record"""
record = self.get_record(common_name)
if fields is not None:
for field, value in fields:
record[field] = value
self.save()
return record
def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record["signees"]))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
"Authority {name} has signed {x} certificates".format(
name=common_name, x=num_signees
)
)
try:
ca_name = bundle.record["parent_ca"]
self.get_record(ca_name)
self.remove_sign_link(ca_name, common_name)
except CertNotFoundError:
pass
record_copy = dict(self.store[common_name])
del self.store[common_name]
self.save()
return record_copy
def remove_files(self, common_name, delete_dir=False):
"""Delete files and record associated with this common name"""
record = self.remove_record(common_name)
if delete_dir:
delete_dirs = []
if "files" in record:
key_containing_dir = os.path.dirname(record["files"]["key"])
delete_dirs.append(key_containing_dir)
cert_containing_dir = os.path.dirname(record["files"]["cert"])
if key_containing_dir != cert_containing_dir:
delete_dirs.append(cert_containing_dir)
for d in delete_dirs:
shutil.rmtree(d)
return record
|
class CertStore:
'''Maintains records of certificates created by Certipy
Minimally, each record keyed by common name needs:
- file
- path
- type
- serial number
- parent CA
- signees
Common names, for the sake of simplicity, are assumed to be unique.
If a pair of certs need to be valid for the same IP/DNS address (ex:
localhost), that information can be specified in the Subject Alternative
Name field.
'''
def __init__(
self, containing_dir="out", store_file="certipy.json", remove_existing=False
):
pass
def save(self):
'''Write the store dict to a file specified by store_file_path'''
pass
def load(self):
'''Read the store dict from file'''
pass
def get_record(self, common_name):
'''Return the record associated with this common name
In most cases, all that's really needed to use an existing cert are
the file paths to the files that make up that cert. This method
returns just that and doesn't bother loading the associated files.
'''
pass
def get_files(self, common_name):
'''Return a bundle of TLS files associated with a common name'''
pass
def add_record(
self,
common_name,
serial=0,
parent_ca="",
signees=None,
files=None,
record=None,
is_ca=False,
overwrite=False,
):
'''Manually create a record of certs
Generally, Certipy can be left to manage certificate locations and
storage, but it is occasionally useful to keep track of a set of
certs that were created externally (for example, let's encrypt)
'''
pass
def add_files(
self,
common_name,
x509s,
files=None,
parent_ca="",
is_ca=False,
signees=None,
serial=0,
overwrite=False,
):
'''Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these files to disk and automatically calls save
on all TLSFiles that it creates (and where it makes sense to).
'''
pass
def add_sign_link(self, ca_name, signee_name):
'''Adds to the CA signees and a parent ref to the signee'''
pass
def remove_sign_link(self, ca_name, signee_name):
'''Removes signee_name to the signee list for ca_name'''
pass
def update_record(self, common_name, **fields):
'''Update fields in an existing record'''
pass
def remove_record(self, common_name):
'''Delete the record associated with this common name'''
pass
def remove_files(self, common_name, delete_dir=False):
'''Delete files and record associated with this common name'''
pass
| 13 | 12 | 17 | 1 | 14 | 2 | 3 | 0.21 | 0 | 9 | 4 | 0 | 12 | 3 | 12 | 12 | 232 | 28 | 168 | 66 | 133 | 36 | 111 | 41 | 98 | 5 | 0 | 3 | 30 |
144,606 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.CertificateAuthorityInUseError
|
class CertificateAuthorityInUseError(Exception):
def __init__(self, message, errors=None):
super().__init__(message)
self.errors = errors
|
class CertificateAuthorityInUseError(Exception):
def __init__(self, message, errors=None):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 11 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 3 | 0 | 1 |
144,607 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.Certipy
|
class Certipy:
def __init__(
self, store_dir="out", store_file="certipy.json", remove_existing=False
):
self.store = CertStore(
containing_dir=store_dir,
store_file=store_file,
remove_existing=remove_existing,
)
def create_key_pair(self, cert_type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of KeyType (currently only 'rsa')
bits - Number of bits to use in the key
Returns: The cryptography private_key keypair object
"""
if isinstance(cert_type, int):
warnings.warn(
"Certipy support for PyOpenSSL is deprecated. Use `cert_type='rsa'",
DeprecationWarning,
stacklevel=2,
)
if cert_type == 6:
cert_type = KeyType.rsa
elif cert_type == 116:
raise ValueError("DSA keys are no longer supported. Use 'rsa'.")
# this will raise on unrecognized values
key_type = KeyType(cert_type)
if key_type == KeyType.rsa:
key = rsa.generate_private_key(
public_exponent=65537,
key_size=bits,
)
else:
raise ValueError(f"Only cert_type='rsa' is supported, not {cert_type!r}")
return key
def create_request(self, pkey, digest="sha256", **name):
"""
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is
sha256
**name - The name of the subject of the request, possible
arguments are:
C - Country name
ST - State or province name
L - Locality name
O - Organization name
OU - Organizational unit name
CN - Common name
emailAddress - E-mail address
Returns: The certificate request in an X509Req object
"""
csr = x509.CertificateSigningRequestBuilder()
if name is not None:
name_attrs = [
x509.NameAttribute(_name_oid_map[key], value)
for key, value in name.items()
]
csr = csr.subject_name(x509.Name(name_attrs))
algorithm = getattr(hashes, digest.upper())()
return csr.sign(pkey, algorithm)
def sign(
self,
req,
issuer_cert_key,
validity_period,
digest="sha256",
extensions=None,
serial=0,
):
"""
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
issuer_key - The private key of the issuer
not_before - Timestamp (relative to now) when the
certificate starts being valid
not_after - Timestamp (relative to now) when the
certificate stops being valid
digest - Digest method to use for signing,
default is sha256
Returns: The signed certificate in an X509 object
"""
issuer_cert, issuer_key = issuer_cert_key
not_before, not_after = validity_period
now = datetime.now(timezone.utc)
if not isinstance(not_before, datetime):
# backward-compatibility: integer seconds from now
not_before = now + timedelta(seconds=not_before)
if not isinstance(not_after, datetime):
not_after = now + timedelta(seconds=not_after)
cert_builder = (
x509.CertificateBuilder()
.subject_name(req.subject)
.serial_number(serial or x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.issuer_name(issuer_cert.subject)
.public_key(req.public_key())
)
if extensions:
for ext, critical in extensions:
cert_builder = cert_builder.add_extension(ext, critical=critical)
algorithm = getattr(hashes, digest.upper())()
cert = cert_builder.sign(issuer_key, algorithm=algorithm)
return cert
def create_ca_bundle_for_names(self, bundle_name, names):
"""Create a CA bundle to trust only certs defined in names"""
records = [rec for name, rec in self.store.store.items() if name in names]
return self.create_bundle(bundle_name, names=[r["parent_ca"] for r in records])
def create_ca_bundle(self, bundle_name, ca_names=None):
"""
Create a bundle of CA public certs for trust distribution
Deprecated: 0.1.2
Arguments: ca_names - The names of CAs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file
"""
return self.create_bundle(bundle_name, names=ca_names)
def create_bundle(self, bundle_name, names=None, ca_only=True):
"""Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file
"""
if not names:
if ca_only:
names = []
for name, record in self.store.store.items():
if record["is_ca"]:
names.append(name)
else:
names = self.store.store.keys()
out_file_path = os.path.join(self.store.containing_dir, bundle_name)
with open(out_file_path, "w") as fh:
for name in names:
bundle = self.store.get_files(name)
bundle.cert.load()
fh.write(str(bundle.cert))
return out_file_path
def trust_from_graph(self, graph):
"""Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict component:list(components)
Returns: dict component:trust bundle file path
"""
# Ensure there are CAs backing all graph components
def distinct_components(graph):
"""Return a set of components from the provided graph."""
components = set(graph.keys())
for trusts in graph.values():
components |= set(trusts)
return components
# Default to creating a CA (incapable of signing intermediaries) to
# identify a component not known to Certipy
for component in distinct_components(graph):
try:
self.store.get_record(component)
except CertNotFoundError:
self.create_ca(component)
# Build bundles from the graph
trust_files = {}
for component, trusts in graph.items():
file_name = component + "_trust.crt"
trust_files[component] = self.create_bundle(
file_name, names=trusts, ca_only=False
)
return trust_files
def create_ca(
self,
name,
ca_name="",
cert_type=KeyType.rsa,
bits=2048,
alt_names=None,
years=5,
serial=0,
pathlen=0,
overwrite=False,
):
"""
Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of the cert. Always 'rsa'.
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new CA
"""
cakey = self.create_key_pair(cert_type, bits)
req = self.create_request(cakey, CN=name)
signing_key = cakey
signing_cert = req
if pathlen is not None and pathlen < 0:
warnings.warn(
"negative pathlen is deprecated. Use pathlen=None",
DeprecationWarning,
stacklevel=2,
)
pathlen = None
parent_ca = ""
if ca_name:
ca_bundle = self.store.get_files(ca_name)
signing_key = ca_bundle.key.load()
signing_cert = ca_bundle.cert.load()
parent_ca = ca_bundle.cert.file_path
extensions = [
(x509.BasicConstraints(True, pathlen), True),
(
x509.KeyUsage(
key_cert_sign=True,
crl_sign=True,
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
),
True,
),
(
x509.ExtendedKeyUsage(
[
x509.ExtendedKeyUsageOID.SERVER_AUTH,
x509.ExtendedKeyUsageOID.CLIENT_AUTH,
]
),
True,
),
(x509.SubjectKeyIdentifier.from_public_key(cakey.public_key()), False),
(
x509.AuthorityKeyIdentifier.from_issuer_public_key(
signing_cert.public_key()
),
False,
),
]
if alt_names:
extensions.append(
(
x509.SubjectAlternativeName([_altname(name) for name in alt_names]),
False,
)
)
# TODO: start time before today for clock skew?
cacert = self.sign(
req,
(signing_cert, signing_key),
(0, 60 * 60 * 24 * 365 * years),
extensions=extensions,
serial=serial,
)
x509s = {"key": cakey, "cert": cacert, "ca": cacert}
self.store.add_files(
name,
x509s,
overwrite=overwrite,
parent_ca=parent_ca,
is_ca=True,
serial=serial,
)
if ca_name:
self.store.add_sign_link(ca_name, name)
return self.store.get_record(name)
def create_signed_pair(
self,
name,
ca_name,
cert_type=KeyType.rsa,
bits=2048,
years=5,
alt_names=None,
serial=0,
overwrite=False,
):
"""
Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. Always 'rsa'
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new signed pair
"""
key = self.create_key_pair(cert_type, bits)
req = self.create_request(key, CN=name)
extensions = [
(
x509.ExtendedKeyUsage(
[
x509.ExtendedKeyUsageOID.SERVER_AUTH,
x509.ExtendedKeyUsageOID.CLIENT_AUTH,
]
),
True,
),
]
if alt_names:
extensions.append(
(
x509.SubjectAlternativeName([_altname(name) for name in alt_names]),
False,
)
)
ca_bundle = self.store.get_files(ca_name)
cacert = ca_bundle.cert.load()
cakey = ca_bundle.key.load()
now = datetime.now(timezone.utc)
eol = now + timedelta(days=years * 365)
cert = self.sign(
req, (cacert, cakey), (now, eol), extensions=extensions, serial=serial
)
x509s = {"key": key, "cert": cert, "ca": None}
self.store.add_files(
name, x509s, parent_ca=ca_name, overwrite=overwrite, serial=serial
)
# Relate these certs as being parent and child
self.store.add_sign_link(ca_name, name)
return self.store.get_record(name)
|
class Certipy:
def __init__(
self, store_dir="out", store_file="certipy.json", remove_existing=False
):
pass
def create_key_pair(self, cert_type, bits):
'''
Create a public/private key pair.
Arguments: type - Key type, must be one of KeyType (currently only 'rsa')
bits - Number of bits to use in the key
Returns: The cryptography private_key keypair object
'''
pass
def create_request(self, pkey, digest="sha256", **name):
'''
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is
sha256
**name - The name of the subject of the request, possible
arguments are:
C - Country name
ST - State or province name
L - Locality name
O - Organization name
OU - Organizational unit name
CN - Common name
emailAddress - E-mail address
Returns: The certificate request in an X509Req object
'''
pass
def sign(
self,
req,
issuer_cert_key,
validity_period,
digest="sha256",
extensions=None,
serial=0,
):
'''
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
issuer_key - The private key of the issuer
not_before - Timestamp (relative to now) when the
certificate starts being valid
not_after - Timestamp (relative to now) when the
certificate stops being valid
digest - Digest method to use for signing,
default is sha256
Returns: The signed certificate in an X509 object
'''
pass
def create_ca_bundle_for_names(self, bundle_name, names):
'''Create a CA bundle to trust only certs defined in names'''
pass
def create_ca_bundle_for_names(self, bundle_name, names):
'''
Create a bundle of CA public certs for trust distribution
Deprecated: 0.1.2
Arguments: ca_names - The names of CAs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file
'''
pass
def create_bundle(self, bundle_name, names=None, ca_only=True):
'''Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file
'''
pass
def trust_from_graph(self, graph):
'''Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict component:list(components)
Returns: dict component:trust bundle file path
'''
pass
def distinct_components(graph):
'''Return a set of components from the provided graph.'''
pass
def create_ca_bundle_for_names(self, bundle_name, names):
'''
Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of the cert. Always 'rsa'.
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new CA
'''
pass
def create_signed_pair(
self,
name,
ca_name,
cert_type=KeyType.rsa,
bits=2048,
years=5,
alt_names=None,
serial=0,
overwrite=False,
):
'''
Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. Always 'rsa'
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new signed pair
'''
pass
| 12 | 10 | 33 | 3 | 22 | 8 | 3 | 0.35 | 0 | 11 | 3 | 0 | 10 | 1 | 10 | 10 | 372 | 46 | 242 | 86 | 199 | 84 | 111 | 54 | 99 | 6 | 0 | 4 | 34 |
144,608 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.KeyType
|
class KeyType(Enum):
"""Enum for available key types"""
rsa = "rsa"
|
class KeyType(Enum):
'''Enum for available key types'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 1 | 2 | 2 | 1 | 1 | 2 | 2 | 1 | 0 | 4 | 0 | 0 |
144,609 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.TLSFile
|
class TLSFile:
"""Describes basic information about files used for TLS"""
def __init__(
self,
file_path,
encoding=serialization.Encoding.PEM,
file_type=TLSFileType.CERT,
x509=None,
):
if isinstance(encoding, int):
warnings.warn(
"OpenSSL.crypto.TYPE_* encoding arguments are deprecated. Use cryptography.hazmat.primitives.serialization.Encoding enum or string 'PEM'",
DeprecationWarning,
stacklevel=2,
)
# match values in OpenSSL.crypto
if encoding == 1:
# PEM
encoding = serialization.Encoding.PEM
elif encoding == 2:
# ASN / DER
encoding = serialization.Encoding.DER
self.file_path = file_path
self.containing_dir = os.path.dirname(self.file_path)
self.encoding = serialization.Encoding(encoding)
self.file_type = file_type
self.x509 = x509
def __str__(self):
data = ""
if not self.x509:
self.load()
if self.file_type is TLSFileType.KEY:
data = self.x509.private_bytes(
encoding=self.encoding,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
else:
data = self.x509.public_bytes(self.encoding)
return data.decode("utf-8")
def get_extension_value(self, ext_name):
if self.is_private():
return
if not self.x509:
self.load()
if isinstance(ext_name, str):
# string name, lookup OID
ext_oid = _ext_oid_map[ext_name]
elif hasattr(ext_name, "oid"):
# given ExtensionType, get OID
ext_oid = ext_name.oid
else:
# otherwise, assume given OID
ext_oid = ext_name
try:
return self.x509.extensions.get_extension_for_oid(ext_oid).value
except x509.ExtensionNotFound:
return None
def is_ca(self):
if self.is_private():
return False
if not self.x509:
self.load()
try:
basic_constraints = self.x509.get_extension_for_class(x509.BasicConstraints)
except x509.ExtensionNotFound:
return False
else:
return basic_constraints.ca
def is_private(self):
"""Is this a private key"""
return True if self.file_type is TLSFileType.KEY else False
def load(self):
"""Load from a file and return an x509 object"""
private = self.is_private()
if private:
if self.encoding == serialization.Encoding.DER:
load = serialization.load_der_private_key
else:
load = serialization.load_pem_private_key
load = partial(load, password=None)
else:
if self.encoding == serialization.Encoding.DER:
load = x509.load_der_x509_certificate
else:
load = x509.load_pem_x509_certificate
with open_tls_file(self.file_path, "rb", private=private) as fh:
self.x509 = load(fh.read())
return self.x509
def save(self, x509):
"""Persist this x509 object to disk"""
self.x509 = x509
with open_tls_file(self.file_path, "w", private=self.is_private()) as fh:
fh.write(str(self))
|
class TLSFile:
'''Describes basic information about files used for TLS'''
def __init__(
self,
file_path,
encoding=serialization.Encoding.PEM,
file_type=TLSFileType.CERT,
x509=None,
):
pass
def __str__(self):
pass
def get_extension_value(self, ext_name):
pass
def is_ca(self):
pass
def is_private(self):
'''Is this a private key'''
pass
def load(self):
'''Load from a file and return an x509 object'''
pass
def save(self, x509):
'''Persist this x509 object to disk'''
pass
| 8 | 4 | 15 | 1 | 12 | 1 | 3 | 0.12 | 0 | 5 | 1 | 0 | 7 | 5 | 7 | 7 | 111 | 17 | 84 | 26 | 70 | 10 | 63 | 18 | 55 | 6 | 0 | 2 | 24 |
144,610 |
LLNL/certipy
|
certipy/certipy.py
|
certipy.certipy.CertExistsError
|
class CertExistsError(Exception):
def __init__(self, message, errors=None):
super().__init__(message)
self.errors = errors
|
class CertExistsError(Exception):
def __init__(self, message, errors=None):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 11 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 3 | 0 | 1 |
144,611 |
LLNL/scraper
|
LLNL_scraper/scraper/tfs/models.py
|
scraper.tfs.models.TFSProject
|
class TFSProject:
def __init__(self, projectInfo, collectionInfo):
self.projectInfo = projectInfo
self.collectionInfo = collectionInfo
self.projectCreateInfo = {}
self.projectLastUpdateInfo = {}
self.gitInfo = []
self.tfvcInfo = []
|
class TFSProject:
def __init__(self, projectInfo, collectionInfo):
pass
| 2 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 6 | 1 | 1 | 8 | 0 | 8 | 8 | 6 | 0 | 8 | 8 | 6 | 1 | 0 | 0 | 1 |
144,612 |
LLNL/scraper
|
LLNL_scraper/scraper/github/queryManager.py
|
scraper.github.queryManager.GitHubQueryManager
|
class GitHubQueryManager:
"""GitHub query API manager."""
def __init__(self, apiToken=None, maxRetry=10, retryDelay=3):
"""Initialize the GitHubQueryManager object.
Note:
If no apiToken argument is provided,
the environment variable 'GITHUB_API_TOKEN' must be set.
Args:
apiToken (Optional[str]): A string representing a GitHub API
token. Defaults to None.
maxRetry (Optional[int]): A limit on how many times to
automatically retry requests. Defaults to 10.
retryDelay (Optional[int]): Number of seconds to wait between
automatic request retries. Defaults to 3.
Raises:
TypeError: If no GitHub API token is provided either via
argument or environment variable 'GITHUB_API_TOKEN'.
"""
# Get GitHub API token
if apiToken:
self.__githubApiToken = apiToken
else:
try:
self.__githubApiToken = os.environ["GITHUB_API_TOKEN"]
except KeyError as error:
raise TypeError(
"Requires either a string argument or environment variable 'GITHUB_API_TOKEN'."
) from error
# Check token validity
print("Checking GitHub API token... ", end="", flush=True)
basicCheck = self._submitQuery("query { viewer { login } }")
if basicCheck["statusNum"] == 401:
print("FAILED.")
raise ValueError(
"GitHub API token is not valid.\n%s %s"
% (basicCheck["statusTxt"], basicCheck["result"])
)
print("Token validated.")
# Initialize private variables
self.__query = None #: Cached query string
self.__queryPath = None #: Path to query file
self.__queryTimestamp = None #: When query file was last modified
# Initialize public variables
self.maxRetry = maxRetry
self.retryDelay = retryDelay
self.data = {}
"""Dict: Working data."""
@property
def maxRetry(self):
"""int: A limit on how many times to automatically retry requests.
Must be a whole integer greater than 0.
"""
return self.__maxRetry
@maxRetry.setter
def maxRetry(self, maxRetry):
numIn = int(maxRetry)
numIn = 1 if numIn <= 0 else numIn
self.__maxRetry = numIn
print("Auto-retry limit for requests set to %d." % (self.maxRetry))
@property
def retryDelay(self):
"""int: Number of seconds to wait between automatic request retries.
Must be a whole integer greater than 0.
"""
return self.__retryDelay
@retryDelay.setter
def retryDelay(self, retryDelay):
numIn = int(retryDelay)
numIn = 1 if numIn <= 0 else numIn
self.__retryDelay = numIn
print("Auto-retry delay set to %dsec." % (self.retryDelay))
def _readGQL(self, filePath, verbose=False):
"""Read a 'pretty' formatted GraphQL query file into a one-line string.
Removes line breaks and comments. Condenses white space.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
File may use comments and multi-line formatting.
.. _GitHub GraphQL Explorer:
https://developer.github.com/v4/explorer/
verbose (Optional[bool]): If False, prints will be suppressed.
Defaults to False.
Returns:
str: A single line GraphQL query.
"""
if not os.path.isfile(filePath):
raise RuntimeError("Query file '%s' does not exist." % (filePath))
lastModified = os.path.getmtime(filePath)
absPath = os.path.abspath(filePath)
if absPath == self.__queryPath and lastModified == self.__queryTimestamp:
_vPrint(
verbose,
"Using cached query '%s'" % (os.path.basename(self.__queryPath)),
)
query_in = self.__query
else:
_vPrint(verbose, "Reading '%s' ... " % (filePath), end="", flush=True)
with open(filePath, "r", encoding="utf-8") as q:
# Strip comments.
query_in = re.sub(r"#.*(\n|\Z)", "\n", q.read())
# Condense whitespace.
query_in = re.sub(r"\s+", " ", query_in)
# Remove leading and trailing whitespace.
query_in = query_in.strip()
_vPrint(verbose, "File read!")
self.__queryPath = absPath
self.__queryTimestamp = lastModified
self.__query = query_in
return query_in
def queryGitHubFromFile(self, filePath, gitvars=None, verbosity=0, **kwargs):
"""Submit a GitHub GraphQL query from a file.
Can only be used with GraphQL queries.
For REST queries, see the 'queryGitHub' method.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
File may use comments and multi-line formatting.
.. _GitHub GraphQL Explorer:
https://developer.github.com/v4/explorer/
gitvars (Optional[Dict]): All query variables.
Defaults to None.
GraphQL Only.
verbosity (Optional[int]): Changes output verbosity levels.
If < 0, all extra printouts are suppressed.
If == 0, normal print statements are displayed.
If > 0, additional status print statements are displayed.
Defaults to 0.
**kwargs: Keyword arguments for the 'queryGitHub' method.
Returns:
Dict: A JSON style dictionary.
"""
if not gitvars:
gitvars = {}
gitquery = self._readGQL(filePath, verbose=(verbosity >= 0))
return self.queryGitHub(
gitquery, gitvars=gitvars, verbosity=verbosity, **kwargs
)
def queryGitHub(
self,
gitquery,
gitvars=None,
verbosity=0,
paginate=False,
cursorVar=None,
keysToList=None,
rest=False,
requestCount=0,
pageNum=0,
headers=None,
):
"""Submit a GitHub query.
Args:
gitquery (str): The query or endpoint itself.
Examples:
query: 'query { viewer { login } }'
endpoint: '/user'
gitvars (Optional[Dict]): All query variables.
Defaults to None.
GraphQL Only.
verbosity (Optional[int]): Changes output verbosity levels.
If < 0, all extra printouts are suppressed.
If == 0, normal print statements are displayed.
If > 0, additional status print statements are displayed.
Defaults to 0.
paginate (Optional[bool]): Pagination will be completed
automatically if True. Defaults to False.
cursorVar (Optional[str]): Key in 'gitvars' that represents the
pagination cursor. Defaults to None.
GraphQL Only.
keysToList (Optional[List[str]]): Ordered list of keys needed to
retrieve the list in the query results to be extended by
pagination. Defaults to None.
Example:
['data', 'viewer', 'repositories', 'nodes']
GraphQL Only.
rest (Optional[bool]): If True, uses the REST API instead
of GraphQL. Defaults to False.
requestCount (Optional[int]): Counter for repeated requests.
pageNum (Optional[int]): Counter for pagination.
For user readable log messages only, does not affect data.
headers (Optional[Dict]): Additional headers.
Defaults to None.
Returns:
Dict: A JSON style dictionary.
"""
if not gitvars:
gitvars = {}
if not keysToList:
keysToList = []
if not headers:
headers = {}
requestCount += 1
pageNum = 0 if pageNum < 0 else pageNum # no negative page numbers
pageNum += 1
if paginate:
_vPrint((verbosity >= 0), "Page %d" % (pageNum))
_vPrint(
(verbosity >= 0), "Sending %s query..." % ("REST" if rest else "GraphQL")
)
response = self._submitQuery(
gitquery,
gitvars=gitvars,
verbose=(verbosity > 0),
rest=rest,
headers=headers,
)
_vPrint((verbosity >= 0), "Checking response...")
_vPrint((verbosity >= 0), "HTTP STATUS %s" % (response["statusTxt"]))
statusNum = response["statusNum"]
# Decrement page count before error checks to properly reflect any repeated queries
pageNum -= 1
# Make sure the query limit didn't run out
try:
apiStatus = {
"limit": int(response["headDict"]["X-RateLimit-Limit"]),
"remaining": int(response["headDict"]["X-RateLimit-Remaining"]),
"reset": int(response["headDict"]["X-RateLimit-Reset"]),
}
_vPrint((verbosity >= 0), "API Status %s" % (json.dumps(apiStatus)))
if apiStatus["remaining"] <= 0:
_vPrint((verbosity >= 0), "API rate limit exceeded.")
self._awaitReset(apiStatus["reset"])
_vPrint((verbosity >= 0), "Repeating query...")
return self.queryGitHub(
gitquery,
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=(requestCount - 1), # not counted against retries
pageNum=pageNum,
headers=headers,
)
except KeyError: # Handles error responses without X-RateLimit data
_vPrint((verbosity >= 0), "Failed to check API Status.")
# Check for explicit API rate limit error responses
if statusNum in (403, 429):
_vPrint((verbosity >= 0), "API rate limit exceeded.")
if requestCount >= self.maxRetry:
raise RuntimeError(
"Query attempted but failed %d times.\n%s\n%s"
% (
self.maxRetry,
response["statusTxt"],
response["result"],
)
)
try: # Use explicit wait time if available
waitTime = int(response["headDict"]["Retry-After"])
self._countdown(
waitTime,
printString="Waiting %*d seconds...",
verbose=(verbosity >= 0),
)
except KeyError: # Handles missing Retry-After header
self._countdown(
# wait at least 1 min, longer on continued failure (recommended best practice)
60 * requestCount,
printString="Waiting %*d seconds...",
verbose=(verbosity >= 0),
)
_vPrint((verbosity >= 0), "Repeating query...")
return self.queryGitHub(
gitquery,
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=(requestCount),
pageNum=pageNum,
headers=headers,
)
# Check for accepted but not yet processed, usually due to un-cached data
if statusNum == 202:
if requestCount >= self.maxRetry:
raise RuntimeError(
"Query attempted but failed %d times.\n%s\n%s"
% (
self.maxRetry,
response["statusTxt"],
response["result"],
)
)
self._countdown(
self.retryDelay,
printString="Query accepted but not yet processed. Trying again in %*d seconds...",
verbose=(verbosity >= 0),
)
return self.queryGitHub(
gitquery,
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=requestCount,
pageNum=pageNum,
headers=headers,
)
# Check for server error responses
if statusNum in (502, 503):
if requestCount >= self.maxRetry:
raise RuntimeError(
"Query attempted but failed %d times.\n%s\n%s"
% (
self.maxRetry,
response["statusTxt"],
response["result"],
)
)
self._countdown(
self.retryDelay,
printString="Server error. Trying again in %*d seconds...",
verbose=(verbosity >= 0),
)
return self.queryGitHub(
gitquery,
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=requestCount,
pageNum=pageNum,
headers=headers,
)
# Check for other error responses
if statusNum >= 400 or statusNum == 204:
raise RuntimeError(
"Request got an Error response.\n%s\n%s"
% (response["statusTxt"], response["result"])
)
_vPrint((verbosity >= 0), "Data received!")
outObj = json.loads(response["result"])
# Check for GraphQL API errors (e.g. repo not found)
if not rest and "errors" in outObj:
if requestCount >= self.maxRetry:
raise RuntimeError(
"Query attempted but failed %d times.\n%s\n%s"
% (
self.maxRetry,
response["statusTxt"],
response["result"],
)
)
if len(outObj["errors"]) == 1 and len(outObj["errors"][0]) == 1:
# Poorly defined error type, usually intermittent, try again.
_vPrint(
(verbosity >= 0),
"GraphQL API error.\n%s" % (json.dumps(outObj["errors"])),
)
self._countdown(
self.retryDelay,
printString="Unknown API error. Trying again in %*d seconds...",
verbose=(verbosity >= 0),
)
return self.queryGitHub(
gitquery,
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=requestCount,
pageNum=pageNum,
headers=headers,
)
raise RuntimeError(
"GraphQL API error.\n%s" % (json.dumps(outObj["errors"]))
)
# Re-increment page count before the next page query
pageNum += 1
# Pagination
if paginate:
if rest and response["linkDict"]:
if "next" in response["linkDict"]:
nextObj = self.queryGitHub(
response["linkDict"]["next"],
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=0,
pageNum=pageNum,
headers=headers,
)
outObj.extend(nextObj)
elif not rest:
if not cursorVar:
raise ValueError(
"Must specify argument 'cursorVar' to use GraphQL auto-pagination."
)
if not len(keysToList) > 0:
raise ValueError(
"Must specify argument 'keysToList' as a non-empty list to use GraphQL auto-pagination."
)
aPage = outObj
for key in keysToList[0:-1]:
aPage = aPage[key]
gitvars[cursorVar] = aPage["pageInfo"]["endCursor"]
if aPage["pageInfo"]["hasNextPage"]:
nextObj = self.queryGitHub(
gitquery,
gitvars=gitvars,
verbosity=verbosity,
paginate=paginate,
cursorVar=cursorVar,
keysToList=keysToList,
rest=rest,
requestCount=0,
pageNum=pageNum,
headers=headers,
)
newPage = nextObj
for key in keysToList[0:-1]:
newPage = newPage[key]
aPage[keysToList[-1]].extend(newPage[keysToList[-1]])
aPage.pop("pageInfo", None)
return outObj
def _submitQuery(
self, gitquery, gitvars=None, verbose=False, rest=False, headers=None
):
"""Send a curl request to GitHub.
Args:
gitquery (str): The query or endpoint itself.
Examples:
query: 'query { viewer { login } }'
endpoint: '/user'
gitvars (Optional[Dict]): All query variables.
Defaults to None.
verbose (Optional[bool]): If False, stderr prints will be
suppressed. Defaults to False.
rest (Optional[bool]): If True, uses the REST API instead
of GraphQL. Defaults to False.
headers (Optional[Dict]): Additional headers.
Defaults to None.
Returns:
{
'statusNum' (int): The HTTP status code.
'statusTxt' (str): The HTTP status message.
'headDict' (Dict[str]): The response headers.
'linkDict' (Dict[int]): Link based pagination data.
'result' (str): The body of the response.
}
"""
if not gitvars:
gitvars = {}
if not headers:
headers = {}
authhead = {"Authorization": "bearer " + self.__githubApiToken}
if not rest:
gitqueryJSON = json.dumps(
{"query": gitquery, "variables": json.dumps(gitvars)}
)
fullResponse = requests.post(
"https://api.github.com/graphql",
data=gitqueryJSON,
headers={**authhead, **headers},
timeout=DEFAULT_REQUESTS_TIMEOUTS,
)
else:
fullResponse = requests.get(
"https://api.github.com" + gitquery,
headers={**authhead, **headers},
timeout=DEFAULT_REQUESTS_TIMEOUTS,
)
_vPrint(
verbose,
"\n%s\n%s"
% (json.dumps(dict(fullResponse.headers), indent=2), fullResponse.text),
)
result = fullResponse.text
headDict = fullResponse.headers
statusNum = int(fullResponse.status_code)
statusTxt = "%d %s" % (statusNum, fullResponse.reason)
# Parse any Link headers even further
linkDict = None
if "Link" in headDict:
linkProperties = headDict["Link"].split(", ")
propDict = {}
for item in linkProperties:
divided = re.split(r'<https://api.github.com|>; rel="|"', item)
propDict[divided[2]] = divided[1]
linkDict = propDict
return {
"statusNum": statusNum,
"statusTxt": statusTxt,
"headDict": headDict,
"linkDict": linkDict,
"result": result,
}
def _awaitReset(self, utcTimeStamp, verbose=True):
"""Wait until the given UTC timestamp.
Args:
utcTimeStamp (int): A UTC format timestamp.
verbose (Optional[bool]): If False, all extra printouts will be
suppressed. Defaults to True.
"""
resetTime = pytz.utc.localize(datetime.utcfromtimestamp(utcTimeStamp))
_vPrint(verbose, "--- Current Timestamp")
_vPrint(verbose, " %s" % (time.strftime("%c")))
now = pytz.utc.localize(datetime.utcnow())
waitTime = round((resetTime - now).total_seconds()) + 1
_vPrint(verbose, "--- Current UTC Timestamp")
_vPrint(verbose, " %s" % (now.strftime("%c")))
_vPrint(verbose, "--- GITHUB NEEDS A BREAK Until UTC Timestamp")
_vPrint(verbose, " %s" % (resetTime.strftime("%c")))
self._countdown(
waitTime, printString="--- Waiting %*d seconds...", verbose=verbose
)
_vPrint(verbose, "--- READY!")
def _countdown(
self, waitTime=0, printString="Waiting %*d seconds...", verbose=True
):
"""Prints a message and waits.
Args:
waitTime (Optional[int]): Number of seconds to wait. Defaults to 0.
printString (Optional[str]): A counter message to display.
Defaults to "Waiting %*d seconds...".
verbose (Optional[bool]): If False, all extra printouts will be
suppressed. Defaults to True.
"""
if waitTime <= 0:
waitTime = self.retryDelay
_vPrint(verbose, printString % (len(str(waitTime)), waitTime))
time.sleep(waitTime)
|
class GitHubQueryManager:
'''GitHub query API manager.'''
def __init__(self, apiToken=None, maxRetry=10, retryDelay=3):
'''Initialize the GitHubQueryManager object.
Note:
If no apiToken argument is provided,
the environment variable 'GITHUB_API_TOKEN' must be set.
Args:
apiToken (Optional[str]): A string representing a GitHub API
token. Defaults to None.
maxRetry (Optional[int]): A limit on how many times to
automatically retry requests. Defaults to 10.
retryDelay (Optional[int]): Number of seconds to wait between
automatic request retries. Defaults to 3.
Raises:
TypeError: If no GitHub API token is provided either via
argument or environment variable 'GITHUB_API_TOKEN'.
'''
pass
@property
def maxRetry(self):
'''int: A limit on how many times to automatically retry requests.
Must be a whole integer greater than 0.
'''
pass
@maxRetry.setter
def maxRetry(self):
pass
@property
def retryDelay(self):
'''int: Number of seconds to wait between automatic request retries.
Must be a whole integer greater than 0.
'''
pass
@retryDelay.setter
def retryDelay(self):
pass
def _readGQL(self, filePath, verbose=False):
'''Read a 'pretty' formatted GraphQL query file into a one-line string.
Removes line breaks and comments. Condenses white space.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
File may use comments and multi-line formatting.
.. _GitHub GraphQL Explorer:
https://developer.github.com/v4/explorer/
verbose (Optional[bool]): If False, prints will be suppressed.
Defaults to False.
Returns:
str: A single line GraphQL query.
'''
pass
def queryGitHubFromFile(self, filePath, gitvars=None, verbosity=0, **kwargs):
'''Submit a GitHub GraphQL query from a file.
Can only be used with GraphQL queries.
For REST queries, see the 'queryGitHub' method.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
File may use comments and multi-line formatting.
.. _GitHub GraphQL Explorer:
https://developer.github.com/v4/explorer/
gitvars (Optional[Dict]): All query variables.
Defaults to None.
GraphQL Only.
verbosity (Optional[int]): Changes output verbosity levels.
If < 0, all extra printouts are suppressed.
If == 0, normal print statements are displayed.
If > 0, additional status print statements are displayed.
Defaults to 0.
**kwargs: Keyword arguments for the 'queryGitHub' method.
Returns:
Dict: A JSON style dictionary.
'''
pass
def queryGitHubFromFile(self, filePath, gitvars=None, verbosity=0, **kwargs):
'''Submit a GitHub query.
Args:
gitquery (str): The query or endpoint itself.
Examples:
query: 'query { viewer { login } }'
endpoint: '/user'
gitvars (Optional[Dict]): All query variables.
Defaults to None.
GraphQL Only.
verbosity (Optional[int]): Changes output verbosity levels.
If < 0, all extra printouts are suppressed.
If == 0, normal print statements are displayed.
If > 0, additional status print statements are displayed.
Defaults to 0.
paginate (Optional[bool]): Pagination will be completed
automatically if True. Defaults to False.
cursorVar (Optional[str]): Key in 'gitvars' that represents the
pagination cursor. Defaults to None.
GraphQL Only.
keysToList (Optional[List[str]]): Ordered list of keys needed to
retrieve the list in the query results to be extended by
pagination. Defaults to None.
Example:
['data', 'viewer', 'repositories', 'nodes']
GraphQL Only.
rest (Optional[bool]): If True, uses the REST API instead
of GraphQL. Defaults to False.
requestCount (Optional[int]): Counter for repeated requests.
pageNum (Optional[int]): Counter for pagination.
For user readable log messages only, does not affect data.
headers (Optional[Dict]): Additional headers.
Defaults to None.
Returns:
Dict: A JSON style dictionary.
'''
pass
def _submitQuery(
self, gitquery, gitvars=None, verbose=False, rest=False, headers=None
):
'''Send a curl request to GitHub.
Args:
gitquery (str): The query or endpoint itself.
Examples:
query: 'query { viewer { login } }'
endpoint: '/user'
gitvars (Optional[Dict]): All query variables.
Defaults to None.
verbose (Optional[bool]): If False, stderr prints will be
suppressed. Defaults to False.
rest (Optional[bool]): If True, uses the REST API instead
of GraphQL. Defaults to False.
headers (Optional[Dict]): Additional headers.
Defaults to None.
Returns:
{
'statusNum' (int): The HTTP status code.
'statusTxt' (str): The HTTP status message.
'headDict' (Dict[str]): The response headers.
'linkDict' (Dict[int]): Link based pagination data.
'result' (str): The body of the response.
}
'''
pass
def _awaitReset(self, utcTimeStamp, verbose=True):
'''Wait until the given UTC timestamp.
Args:
utcTimeStamp (int): A UTC format timestamp.
verbose (Optional[bool]): If False, all extra printouts will be
suppressed. Defaults to True.
'''
pass
def _countdown(
self, waitTime=0, printString="Waiting %*d seconds...", verbose=True
):
'''Prints a message and waits.
Args:
waitTime (Optional[int]): Number of seconds to wait. Defaults to 0.
printString (Optional[str]): A counter message to display.
Defaults to "Waiting %*d seconds...".
verbose (Optional[bool]): If False, all extra printouts will be
suppressed. Defaults to True.
'''
pass
| 16 | 10 | 52 | 4 | 35 | 14 | 5 | 0.41 | 0 | 8 | 0 | 0 | 11 | 7 | 11 | 11 | 594 | 59 | 387 | 72 | 355 | 157 | 181 | 50 | 169 | 29 | 0 | 4 | 53 |
144,613 |
LLNL/scraper
|
LLNL_scraper/scraper/github/queryManager.py
|
scraper.github.queryManager.DataManager
|
class DataManager:
"""JSON data manager."""
def __init__(self, filePath=None, loadData=False):
"""Initialize the DataManager object.
Args:
filePath (Optional[str]): Relative or absolute path to a JSON
data file. Defaults to None.
loadData (Optional[bool]): Loads data from the given file path
if True. Defaults to False.
"""
self.data = {}
"""Dict: Working data."""
self.filePath = filePath
if loadData:
self.fileLoad(updatePath=False)
@property
def filePath(self):
"""str: Absolute path to a JSON format data file.
Can accept relative paths, but will always convert them to
the absolute path.
"""
if not self.__filePath:
raise ValueError("Internal variable filePath has not been set.")
return self.__filePath
@filePath.setter
def filePath(self, filePath):
if filePath:
if not os.path.isfile(filePath):
print(
"Data file '%s' does not currently exist. Saving data will create a new file."
% (filePath)
)
self.__filePath = os.path.abspath(filePath)
print("Stored new data file path '%s'" % (self.filePath))
else:
self.__filePath = None
def dataReset(self):
"""Reset the internal JSON data dictionary."""
self.data = {}
print("Stored data has been reset.")
def fileLoad(self, filePath=None, updatePath=True):
"""Load a JSON data file into the internal JSON data dictionary.
Current internal data will be overwritten.
If no file path is provided, the stored data file path will be used.
Args:
filePath (Optional[str]): A relative or absolute path to a
'.json' file. Defaults to None.
updatePath (Optional[bool]): Specifies whether or not to update
the stored data file path. Defaults to True.
"""
if not filePath:
filePath = self.filePath
if not os.path.isfile(filePath):
raise FileNotFoundError("Data file '%s' does not exist." % (filePath))
print(
"Importing existing data file '%s' ... " % (filePath),
end="",
flush=True,
)
with open(filePath, "r", encoding="utf-8") as q:
data_raw = q.read()
print("Imported!")
self.data = json.loads(data_raw)
if updatePath:
self.filePath = filePath
def fileSave(self, filePath=None, updatePath=False, newline=None):
"""Write the internal JSON data dictionary to a JSON data file.
If no file path is provided, the stored data file path will be used.
Args:
filePath (Optional[str]): A relative or absolute path to a
'.json' file. Defaults to None.
updatePath (Optional[bool]): Specifies whether or not to update
the stored data file path. Defaults to False.
newline (Optional[str]): Specifies the line endings to use when
writing the file. Defaults to system default line separator.
"""
if not filePath:
filePath = self.filePath
if not os.path.isfile(filePath):
print("Data file '%s' does not exist, will create new file." % (filePath))
if not os.path.exists(os.path.split(filePath)[0]):
os.makedirs(os.path.split(filePath)[0])
dataJsonString = json.dumps(self.data, indent=4, sort_keys=True)
print("Writing to file '%s' ... " % (filePath), end="", flush=True)
with open(filePath, "w", encoding="utf-8", newline=newline) as fileout:
fileout.write(dataJsonString)
print("Wrote file!")
if updatePath:
self.filePath = filePath
|
class DataManager:
'''JSON data manager.'''
def __init__(self, filePath=None, loadData=False):
'''Initialize the DataManager object.
Args:
filePath (Optional[str]): Relative or absolute path to a JSON
data file. Defaults to None.
loadData (Optional[bool]): Loads data from the given file path
if True. Defaults to False.
'''
pass
@property
def filePath(self):
'''str: Absolute path to a JSON format data file.
Can accept relative paths, but will always convert them to
the absolute path.
'''
pass
@filePath.setter
def filePath(self):
pass
def dataReset(self):
'''Reset the internal JSON data dictionary.'''
pass
def fileLoad(self, filePath=None, updatePath=True):
'''Load a JSON data file into the internal JSON data dictionary.
Current internal data will be overwritten.
If no file path is provided, the stored data file path will be used.
Args:
filePath (Optional[str]): A relative or absolute path to a
'.json' file. Defaults to None.
updatePath (Optional[bool]): Specifies whether or not to update
the stored data file path. Defaults to True.
'''
pass
def fileSave(self, filePath=None, updatePath=False, newline=None):
'''Write the internal JSON data dictionary to a JSON data file.
If no file path is provided, the stored data file path will be used.
Args:
filePath (Optional[str]): A relative or absolute path to a
'.json' file. Defaults to None.
updatePath (Optional[bool]): Specifies whether or not to update
the stored data file path. Defaults to False.
newline (Optional[str]): Specifies the line endings to use when
writing the file. Defaults to system default line separator.
'''
pass
| 9 | 6 | 16 | 2 | 9 | 5 | 3 | 0.59 | 0 | 2 | 0 | 0 | 6 | 2 | 6 | 6 | 104 | 15 | 56 | 15 | 47 | 33 | 46 | 11 | 39 | 5 | 0 | 2 | 17 |
144,614 |
LLNL/scraper
|
LLNL_scraper/scraper/code_gov/models.py
|
scraper.code_gov.models.Project
|
class Project(dict):
"""
Python representation of Code.gov Metadata Schema
For details: https://code.gov/#/policy-guide/docs/compliance/inventory-code
"""
def __init__(self):
# -- REQUIRED FIELDS --
# *name: [string] The name of the release
self["name"] = ""
# repository: [string] The URL of the public project repository
self["repositoryURL"] = ""
# *description: [string] A description of the project
self["description"] = ""
# *permissions: [object] A description of the usage/restrictions regarding the release
# * licenses: [null or array of objects] An object containing license details, if available. If not, null should be used.
# URL: [string] The URL of the release license, if available
# name: [string] An abbreviation for the name of the license
# * usageType: [enum]
# openSource: Open source
# governmentWideReuse: Government-wide reuse.
# exemptByLaw: The sharing of the source code is restricted by law or regulation, including—but not limited to—patent or intellectual property law, the Export Asset Regulations, the International Traffic in Arms Regulation, and the Federal laws and regulations governing classified information.
# exemptByNationalSecurity: The sharing of the source code would create an identifiable risk to the detriment of national security, confidentiality of Government information, or individual privacy.
# exemptByAgencySystem: The sharing of the source code would create an identifiable risk to the stability, security, or integrity of the agency’s systems or personnel.
# exemptByAgencyMission: The sharing of the source code would create an identifiable risk to agency mission, programs, or operations.
# exemptByCIO: The CIO believes it is in the national interest to exempt sharing the source code.
# exemptByPolicyDate: The release was created prior to the M-16-21 policy (August 8, 2016).
# exemptionText: [null or string]
self["permissions"] = {"licenses": None, "usageType": "", "exemptionText": None}
# *laborHours: [number]: An estimate of total labor hours spent by your organization/component across all versions of this release. This includes labor performed by federal employees and contractors.
self["laborHours"] = 0
# *tags: [array] An array of keywords that will be helpful in discovering and searching for the release.
self["tags"] = []
# *contact: [object] Information about contacting the project.
# *email: [string] An email address to contact the project.
# name: [string] The name of a contact or department for the project
# twitter: [string] The username of the project's Twitter account
# phone: [string] The phone number to contact a project.
self["contact"] = {"email": ""}
# TODO: Currently, the GSA Harvester requires these fields to not be present if they are empty
# 'name': '',
# 'URL': '',
# 'phone': '',
# }
# -- OPTIONAL FIELDS --
# version: [string] The version for this release. For example, "1.0.0."
# self['version'] = ''
# organization: [string] The organization or component within the agency that the releases listed belong to. For example, "18F" or "Navy."
# self['organization'] = ''
# status: [string] The development status of the project
# "Ideation" - brainstorming phase.
# "Development" - a release is still in development.
# "Alpha" - initial prototyping phase and internal testing.
# "Beta" - a project is being tested in public.
# "Release Candidate" - a release is nearly ready for production.
# "Production" - finished project, with development and maintenance ongoing.
# "Archival" - finished project, but no longer actively maintained.
# self['status'] = ''
# vcs: [string] A lowercase string with the name of the Version Control System in use on the project.
# self['vcs'] = ''
# homepageURL: [string] The URL of the public release homepage.
# self['homepageURL'] = ''
# downloadURL: [string] The URL where a distribution of the release can be found.
# self['downloadURL'] = ''
# disclaimerText: [string] Short paragraph that includes disclaimer language to accompany the release.
# self['disclaimerText'] = ''
# disclaimerURL: [string] The URL where disclaimer language regarding the release can be found.
# self['disclaimerURL'] = ''
# languages: [array] A list of strings with the names of the programming languages in use on the release.
# self['languages'] = []
# partners: [array] An array of objects including an acronym for each agency partnering on the release and the contact email at such agency.
# name: [string] The acronym describing the partner agency.
# email: [string] The email address for the point of contact at the partner agency.
# self['partners'] = []
# relatedCode: [array] An array of affiliated government repositories that may be a part of the same project. For example, relatedCode for 'code-gov-web' would include 'code-gov-api' and 'code-gov-tools'.
# name: [string] The name of the code repository, project, library or release.
# URL: [string] The URL where the code repository, project, library or release can be found.
# isGovernmentRepo: [boolean] True or False. Is the code repository owned or managed by a federal agency?
# self['relatedCode'] = []
# reusedCode: [array] An array of government source code, libraries, frameworks, APIs, platforms or other software used in this release. For example: US Web Design Standards, cloud.gov, Federalist, Digital Services Playbook, Analytics Reporter.
# name: [string] The name of the software used in this release.
# URL: [string] The URL where the software can be found.
# self['reusedCode'] = []
# date: [object] A date object describing the release.
# created: [string] The date the release was originally created, in YYYY-MM-DD or ISO 8601 format.
# lastModified: [string] The date the release was modified, in YYYY-MM-DD or ISO 8601 format.
# metadataLastUpdated: [string] The date the metadata of the release was last updated, in YYYY-MM-DD or ISO 8601 format.
# self['date'] = {
# 'created': '',
# 'lastModified': '',
# 'metadataLastUpdated': ''
# }
@classmethod
def from_github3(klass, repository, labor_hours=True):
"""
Create CodeGovProject object from github3 Repository object
"""
if not isinstance(repository, github3.repos.repo._Repository):
raise TypeError("Repository must be a github3 Repository object")
logger.info("Processing: %s", repository.full_name)
project = klass()
logger.debug("GitHub3: repository=%s", repository)
# -- REQUIRED FIELDS --
project["name"] = repository.name
project["repositoryURL"] = repository.clone_url
project["description"] = repository.description
try:
repo_license = repository.license()
except github3.exceptions.NotFoundError:
logger.debug("no license found for repo=%s", repository)
repo_license = None
if repo_license:
license_obj = repo_license.license
if license_obj:
logger.debug(
"license spdx=%s; url=%s", license_obj.spdx_id, license_obj.url
)
if license_obj.url is None:
project["permissions"]["licenses"] = [{"name": license_obj.spdx_id}]
else:
project["permissions"]["licenses"] = [
{"URL": license_obj.url, "name": license_obj.spdx_id}
]
else:
project["permissions"]["licenses"] = None
public_server = repository.html_url.startswith("https://github.com")
if not repository.private and public_server:
project["permissions"]["usageType"] = "openSource"
elif date_parse(repository.created_at) < POLICY_START_DATE:
project["permissions"]["usageType"] = "exemptByPolicyDate"
if labor_hours:
project["laborHours"] = labor_hours_from_url(project["repositoryURL"])
else:
project["laborHours"] = 0
project["tags"] = ["github"]
old_accept = repository.session.headers["Accept"]
repository.session.headers["Accept"] = (
"application/vnd.github.mercy-preview+json"
)
topics = repository._get(repository.url + "/topics").json()
project["tags"].extend(topics.get("names", []))
repository.session.headers["Accept"] = old_accept
# Hacky way to get an Organization object back with GitHub3.py >= 1.2.0
owner_url = repository.owner.url
owner_api_response = repository._get(owner_url)
organization = repository._json(owner_api_response, 200)
project["contact"]["email"] = organization["email"]
project["contact"]["URL"] = organization["html_url"]
# -- OPTIONAL FIELDS --
# project['version'] = ''
project["organization"] = organization["name"]
# TODO: Currently, can't be an empty string, see: https://github.com/GSA/code-gov-web/issues/370
project["status"] = "Development"
project["vcs"] = "git"
project["homepageURL"] = repository.html_url
project["downloadURL"] = repository.downloads_url
project["languages"] = [lang for lang, _ in repository.languages()]
# project['partners'] = []
# project['relatedCode'] = []
# project['reusedCode'] = []
# date: [object] A date object describing the release.
# created: [string] The date the release was originally created, in YYYY-MM-DD or ISO 8601 format.
# lastModified: [string] The date the release was modified, in YYYY-MM-DD or ISO 8601 format.
# metadataLastUpdated: [string] The date the metadata of the release was last updated, in YYYY-MM-DD or ISO 8601 format.
try:
created_at = repository.created_at.date()
except AttributeError:
created_at = date_parse(repository.created_at).date()
try:
updated_at = repository.updated_at.date()
except AttributeError:
updated_at = date_parse(repository.updated_at).date()
project["date"] = {
"created": created_at.isoformat(),
"lastModified": updated_at.isoformat(),
"metadataLastUpdated": "",
}
_prune_dict_null_str(project)
return project
@classmethod
def from_gitlab(klass, repository, labor_hours=True, fetch_languages=False):
"""
Create CodeGovProject object from GitLab Repository
"""
if not isinstance(repository, gitlab.v4.objects.Project):
raise TypeError("Repository must be a gitlab Repository object")
project = klass()
logger.debug(
"GitLab: repository_id=%d path_with_namespace=%s",
repository.id,
repository.path_with_namespace,
)
# -- REQUIRED FIELDS --
project["name"] = repository.name
project["repositoryURL"] = repository.http_url_to_repo
project["description"] = repository.description
# TODO: Update licenses from GitLab API
project["permissions"]["licenses"] = None
web_url = repository.web_url
public_server = web_url.startswith("https://gitlab.com")
if repository.visibility in ("public") and public_server:
project["permissions"]["usageType"] = "openSource"
elif date_parse(repository.created_at) < POLICY_START_DATE:
project["permissions"]["usageType"] = "exemptByPolicyDate"
if labor_hours:
project["laborHours"] = labor_hours_from_url(project["repositoryURL"])
else:
project["laborHours"] = 0
project["tags"] = ["gitlab"] + repository.tag_list
project["contact"] = {"email": "", "URL": web_url}
# -- OPTIONAL FIELDS --
# project['version'] = ''
project["organization"] = repository.namespace["name"]
# TODO: Currently, can't be an empty string, see: https://github.com/GSA/code-gov-web/issues/370
project["status"] = "Development"
project["vcs"] = "git"
project["homepageURL"] = repository.web_url
api_url = repository.manager.gitlab._url
archive_suffix = "/projects/%s/repository/archive" % repository.get_id()
project["downloadURL"] = api_url + archive_suffix
# project['languages'] = [lang for lang, _ in repository.languages()]
if fetch_languages:
project["languages"] = [*repository.languages()]
# project['partners'] = []
# project['relatedCode'] = []
# project['reusedCode'] = []
project["date"] = {
"created": date_parse(repository.created_at).date().isoformat(),
"lastModified": date_parse(repository.last_activity_at).date().isoformat(),
"metadataLastUpdated": "",
}
_prune_dict_null_str(project)
return project
@classmethod
def from_stashy(klass, repository, labor_hours=True):
"""
Handles crafting Code.gov Project for Bitbucket Server repositories
"""
# if not isinstance(repository, stashy.repos.Repository):
# raise TypeError('Repository must be a stashy Repository object')
if not isinstance(repository, dict):
raise TypeError("Repository must be a dict")
project = klass()
logger.debug(
"Stashy: project_key=%s repository_slug=%s",
repository["name"],
repository["project"]["key"],
)
# -- REQUIRED FIELDS --
project["name"] = repository["name"]
clone_urls = [clone["href"] for clone in repository["links"]["clone"]]
for url in clone_urls:
# Only rely on SSH Urls for repository urls
if url.startswith("ssh://"):
project["repositoryURL"] = url
break
description = repository["project"].get("description", "")
if description:
project["description"] = "Project description: %s" % description
project["permissions"]["licenses"] = None
web_url = repository["links"]["self"][0]["href"]
public_server = web_url.startswith("https://bitbucket.org")
if repository["public"] and public_server:
project["permissions"]["usageType"] = "openSource"
if labor_hours:
project["laborHours"] = labor_hours_from_url(project["repositoryURL"])
else:
project["laborHours"] = 0
project["tags"] = ["bitbucket"]
project["contact"]["email"] = ""
project["contact"]["URL"] = repository["links"]["self"][0]["href"]
# -- OPTIONAL FIELDS --
# project['version'] = ''
# project['organization'] = organization.name
# TODO: Currently, can't be an empty string, see: https://github.com/GSA/code-gov-web/issues/370
project["status"] = "Development"
project["vcs"] = repository["scmId"]
project["homepageURL"] = repository["links"]["self"][0]["href"]
# project['downloadURL'] =
# project['languages'] =
# project['partners'] = []
# project['relatedCode'] = []
# project['reusedCode'] = []
# date: [object] A date object describing the release. Empty if repo has no commits.
# created: [string] The date the release was originally created, in YYYY-MM-DD or ISO 8601 format.
# lastModified: [string] The date the release was modified, in YYYY-MM-DD or ISO 8601 format.
if repository.get("created", None):
project["date"] = {
"created": repository["created"],
"lastModified": repository["lastModified"],
}
_prune_dict_null_str(project)
return project
@classmethod
def from_doecode(klass, record):
"""
Create CodeGovProject object from DOE CODE record
Handles crafting Code.gov Project
"""
if not isinstance(record, dict):
raise TypeError("`record` must be a dict")
project = klass()
# -- REQUIRED FIELDS --
project["name"] = record["software_title"]
logger.debug('DOE CODE: software_title="%s"', record["software_title"])
link = record.get("repository_link", "")
if not link:
link = record.get("landing_page")
logger.warning("DOE CODE: No repositoryURL, using landing_page: %s", link)
project["repositoryURL"] = link
project["description"] = record["description"]
licenses = set(record["licenses"])
licenses.discard(None)
logger.debug("DOE CODE: licenses=%s", licenses)
license_objects = []
if "Other" in licenses:
licenses.remove("Other")
license_objects = [{"name": "Other", "URL": record["proprietary_url"]}]
if licenses:
license_objects.extend(
[_license_obj(license_name) for license_name in licenses]
)
project["permissions"]["licenses"] = license_objects
if record["open_source"]:
usage_type = "openSource"
else:
usage_type = "exemptByLaw"
project["permissions"][
"exemptionText"
] = "This source code is restricted by patent and / or intellectual property law."
project["permissions"]["usageType"] = usage_type
labor_hours = record.get("labor_hours")
if labor_hours is not None:
project["laborHours"] = labor_hours
else:
project["laborHours"] = 0
project["tags"] = ["DOE CODE"]
lab_name = record.get("lab_display_name")
if lab_name is not None:
project["tags"].append(lab_name)
project["contact"]["email"] = record["owner"]
# project['contact']['URL'] = ''
# project['contact']['name'] = ''
# project['contact']['phone'] = ''
# -- OPTIONAL FIELDS --
if "version_number" in record and record["version_number"]:
project["version"] = record["version_number"]
if lab_name is not None:
project["organization"] = lab_name
# Currently, can't be an empty string, see: https://github.com/GSA/code-gov-web/issues/370
status = record.get("ever_announced")
if status is None:
raise ValueError('DOE CODE: Unable to determine "ever_announced" value!')
project["status"] = "Production" if status else "Development"
vcs = None
link = project["repositoryURL"]
if "github.com" in link:
vcs = "git"
if vcs is None:
logger.debug(
'DOE CODE: Unable to determine vcs for: name="%s", repositoryURL=%s',
project["name"],
link,
)
vcs = ""
if vcs:
project["vcs"] = vcs
url = record.get("landing_page", "")
if url:
project["homepageURL"] = url
# record['downloadURL'] = ''
# self['disclaimerText'] = ''
# self['disclaimerURL'] = ''
if "programming_languages" in record:
project["languages"] = record["programming_languages"]
# self['partners'] = []
# TODO: Look into using record['contributing_organizations']
# self['relatedCode'] = []
# self['reusedCode'] = []
# date: [object] A date object describing the release.
# created: [string] The date the release was originally created, in YYYY-MM-DD or ISO 8601 format.
# lastModified: [string] The date the release was modified, in YYYY-MM-DD or ISO 8601 format.
# metadataLastUpdated: [string] The date the metadata of the release was last updated, in YYYY-MM-DD or ISO 8601 format.
if "date_record_added" in record and "date_record_updated" in record:
project["date"] = {
"created": record["date_record_added"],
# 'lastModified': '',
"metadataLastUpdated": record["date_record_updated"],
}
return project
@classmethod
def from_tfs(klass, tfs_project, labor_hours=True):
"""
Creates CodeGovProject object from TFS/VSTS/AzureDevOps Instance
"""
project = klass()
project_web_url = ""
# -- REQUIRED FIELDS --
project["name"] = tfs_project.projectInfo.name
if "web" in tfs_project.projectInfo._links.additional_properties:
if "href" in tfs_project.projectInfo._links.additional_properties["web"]:
# URL Encodes spaces that are in the Project Name for the Project Web URL
project_web_url = requote_uri(
tfs_project.projectInfo._links.additional_properties["web"]["href"]
)
project["repositoryURL"] = project_web_url
project["homepageURL"] = project_web_url
project["description"] = tfs_project.projectInfo.description
project["vcs"] = "TFS/AzureDevOps"
project["permissions"]["license"] = None
project["tags"] = []
if labor_hours:
logger.debug("Sorry labor hour calculation not currently supported.")
# project['laborHours'] = labor_hours_from_url(project['repositoryURL'])
else:
project["laborHours"] = 0
if tfs_project.projectCreateInfo.last_update_time < POLICY_START_DATE:
project["permissions"]["usageType"] = "exemptByPolicyDate"
else:
project["permissions"]["usageType"] = "exemptByAgencyMission"
project["permissions"][
"exemptionText"
] = "This source code resides on a private server and has not been properly evaluated for releaseability."
project["contact"] = {"email": "", "URL": project_web_url}
project["date"] = {
"lastModified": tfs_project.projectLastUpdateInfo.last_update_time.date().isoformat(),
"created": tfs_project.projectCreateInfo.last_update_time.date().isoformat(),
"metadataLastUpdated": "",
}
_prune_dict_null_str(project)
return project
|
class Project(dict):
'''
Python representation of Code.gov Metadata Schema
For details: https://code.gov/#/policy-guide/docs/compliance/inventory-code
'''
def __init__(self):
pass
@classmethod
def from_github3(klass, repository, labor_hours=True):
'''
Create CodeGovProject object from github3 Repository object
'''
pass
@classmethod
def from_gitlab(klass, repository, labor_hours=True, fetch_languages=False):
'''
Create CodeGovProject object from GitLab Repository
'''
pass
@classmethod
def from_stashy(klass, repository, labor_hours=True):
'''
Handles crafting Code.gov Project for Bitbucket Server repositories
'''
pass
@classmethod
def from_doecode(klass, record):
'''
Create CodeGovProject object from DOE CODE record
Handles crafting Code.gov Project
'''
pass
@classmethod
def from_tfs(klass, tfs_project, labor_hours=True):
'''
Creates CodeGovProject object from TFS/VSTS/AzureDevOps Instance
'''
pass
| 12 | 6 | 82 | 21 | 45 | 17 | 8 | 0.57 | 1 | 4 | 0 | 0 | 1 | 0 | 6 | 33 | 578 | 148 | 274 | 47 | 262 | 156 | 214 | 41 | 207 | 18 | 2 | 3 | 49 |
144,615 |
LLNL/scraper
|
LLNL_scraper/scripts/get_year_commits.py
|
get_year_commits.GitHub_LLNL_Year_Commits
|
class GitHub_LLNL_Year_Commits:
def __init__(self):
self.commits_dict_list = []
self.commits = {}
self.sorted_weeks = []
def get_year_commits(
self, username="", password="", organization="llnl", force=True
):
"""
Does setup such as login, printing API info, and waiting for GitHub to
build the commit statistics. Then gets the last year of commits and
prints them to file.
"""
file_path = "year_commits.csv"
if force or not os.path.isfile(file_path):
my_github.login(username, password)
calls_beginning = self.logged_in_gh.ratelimit_remaining + 1
print("Rate Limit: " + str(calls_beginning))
my_github.get_org(organization)
my_github.repos(building_stats=True)
print("Letting GitHub build statistics.")
time.sleep(30)
print("Trying again.")
my_github.repos(building_stats=False)
my_github.calc_total_commits(starting_commits=35163)
my_github.write_to_file()
calls_remaining = self.logged_in_gh.ratelimit_remaining
calls_used = calls_beginning - calls_remaining
print(
"Rate Limit Remaining: "
+ str(calls_remaining)
+ "\nUsed "
+ str(calls_used)
+ " API calls."
)
def login(self, username="", password=""):
"""
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
"""
try:
token = ""
id = ""
if not os.path.isfile("CREDENTIALS_FILE"):
if username == "" or password == "":
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
note = "GitHub Organization Stats App"
note_url = "http://software.llnl.gov/"
scopes = ["user", "repo"]
auth = github3.authorize(
username,
password,
scopes,
note,
note_url,
two_factor_callback=self.prompt_2fa,
)
token = auth.token
id = auth.id
with open("CREDENTIALS_FILE", "w+") as fd:
fd.write(token + "\n")
fd.write(str(id))
fd.close()
else:
with open("CREDENTIALS_FILE", "r") as fd:
token = fd.readline().strip()
id = fd.readline().strip()
fd.close()
print("Logging in.")
self.logged_in_gh = github3.login(
token=token, two_factor_callback=self.prompt_2fa
)
self.logged_in_gh.user().to_json()
except (ValueError, AttributeError, github3.models.GitHubError):
print("Bad credentials. Try again.")
self.login()
def prompt_2fa(self):
"""
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
"""
code = ""
while not code:
code = raw_input("Enter 2FA code: ")
return code
def get_org(self, organization_name=""):
"""
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
"""
if organization_name == "":
organization_name = raw_input("Organization: ")
print("Getting organization.")
self.org_retrieved = self.logged_in_gh.organization(organization_name)
def repos(self, building_stats=False):
"""
Retrieves the last year of commits for the organization and stores them
in weeks (UNIX time) associated with number of commits that week.
"""
print("Getting repos.")
for repo in self.org_retrieved.iter_repos():
for activity in repo.iter_commit_activity():
if not building_stats:
self.commits_dict_list.append(activity)
def calc_total_commits(self, starting_commits=0):
"""
Uses the weekly commits and traverses back through the last
year, each week subtracting the weekly commits and storing them. It
needs an initial starting commits number, which should be taken from
the most up to date number from github_stats.py output.
"""
for week_of_commits in self.commits_dict_list:
try:
self.commits[week_of_commits["week"]] -= week_of_commits["total"]
except KeyError:
total = self.commits[week_of_commits["week"]] = -week_of_commits[
"total"
]
self.sorted_weeks = sorted(self.commits)
# reverse because lower numbered weeks are older in time.
# we traverse from most recent to oldest
for week in reversed(self.sorted_weeks):
self.commits[week] = self.commits[week] + starting_commits
starting_commits = self.commits[week]
def write_to_file(self):
"""
Writes the weeks with associated commits to file.
"""
with open("../github_stats_output/last_year_commits.csv", "w+") as output:
output.write(
"date,organization,repos,members,teams,"
+ "unique_contributors,total_contributors,forks,"
+ "stargazers,pull_requests,open_issues,has_readme,"
+ "has_license,pull_requests_open,pull_requests_closed,"
+ "commits\n"
)
# no reverse this time to print oldest first
previous_commits = 0
for week in self.sorted_weeks:
if str(self.commits[week]) != previous_commits: # delete dups
week_formatted = datetime.datetime.utcfromtimestamp(week).strftime(
"%Y-%m-%d"
)
output.write(
week_formatted
+ ",llnl,0,0,0,0,0,0,0,0,0,0,0,0,0,"
+ str(self.commits[week])
+ "\n"
)
previous_commits = str(self.commits[week])
|
class GitHub_LLNL_Year_Commits:
def __init__(self):
pass
def get_year_commits(
self, username="", password="", organization="llnl", force=True
):
'''
Does setup such as login, printing API info, and waiting for GitHub to
build the commit statistics. Then gets the last year of commits and
prints them to file.
'''
pass
def login(self, username="", password=""):
'''
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
'''
pass
def prompt_2fa(self):
'''
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
'''
pass
def get_org(self, organization_name=""):
'''
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
'''
pass
def repos(self, building_stats=False):
'''
Retrieves the last year of commits for the organization and stores them
in weeks (UNIX time) associated with number of commits that week.
'''
pass
def calc_total_commits(self, starting_commits=0):
'''
Uses the weekly commits and traverses back through the last
year, each week subtracting the weekly commits and storing them. It
needs an initial starting commits number, which should be taken from
the most up to date number from github_stats.py output.
'''
pass
def write_to_file(self):
'''
Writes the weeks with associated commits to file.
'''
pass
| 9 | 7 | 19 | 0 | 15 | 5 | 3 | 0.31 | 0 | 6 | 0 | 0 | 8 | 5 | 8 | 8 | 162 | 8 | 118 | 36 | 107 | 37 | 85 | 32 | 76 | 4 | 0 | 3 | 22 |
144,616 |
LLNL/scraper
|
LLNL_scraper/scripts/my_repo.py
|
my_repo.My_Repo
|
class My_Repo:
def __init__(self):
self.date = datetime.date.today()
self.name = "N/A"
self.organization = "N/A"
self.contributors = 0
self.forks = 0
self.stargazers = 0
self.pull_requests = 0
self.pull_requests_open = 0
self.pull_requests_closed = 0
self.issues = 0
self.open_issues = 0
self.closed_issues = 0
self.languages = []
self.readme = "MISS"
self.license = "MISS"
self.commits = 0
|
class My_Repo:
def __init__(self):
pass
| 2 | 0 | 17 | 0 | 17 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 16 | 1 | 1 | 18 | 0 | 18 | 18 | 16 | 0 | 18 | 18 | 16 | 1 | 0 | 0 | 1 |
144,617 |
LLNL/scraper
|
LLNL_scraper/scripts/github_stats.py
|
github_stats.GitHub_LLNL_Stats
|
class GitHub_LLNL_Stats:
def __init__(self):
print("Initalizing.")
self.unique_contributors = defaultdict(list)
self.languages = {}
self.languages_size = {}
self.all_repos = []
self.total_repos = 0
self.total_contributors = 0
self.total_forks = 0
self.total_stars = 0
self.total_pull_reqs = 0
self.total_pull_reqs_open = 0
self.total_pull_reqs_closed = 0
self.total_open_issues = 0
self.total_closed_issues = 0
self.total_issues = 0
self.total_readmes = 0
self.total_licenses = 0
self.total_commits = 0
self.search_limit = 0
self.previous_language = ""
# JSON vars
self.repos_json = {}
self.members_json = {}
self.teams_json = {}
self.contributors_json = defaultdict(list)
self.pull_requests_json = defaultdict(list)
self.issues_json = defaultdict(list)
self.languages_json = defaultdict(dict)
self.commits_json = defaultdict(list)
def get_stats(
self,
username="",
password="",
organization="llnl",
force=True,
repo_type="public",
):
"""
Retrieves the statistics from the given organization with the given
credentials. Will not retreive data if file exists and force hasn't been
set to True. This is to save GH API requests.
"""
date = str(datetime.date.today())
file_path = (
"../github_stats_output/" + date[:4] + "/" + date[:7] + "/" + date + ".csv"
)
if force or not os.path.isfile(file_path):
my_github.login(username, password)
calls_beginning = self.logged_in_gh.ratelimit_remaining + 1
print("Rate Limit: " + str(calls_beginning))
my_github.get_org(organization)
count_members = my_github.get_mems_of_org()
count_teams = my_github.get_teams_of_org()
my_github.repos(repo_type=repo_type, organization=organization)
# Write JSON
my_github.write_org_json(
dict_to_write=self.members_json,
path_ending_type="members",
is_list=True,
)
my_github.write_org_json(
dict_to_write={"singleton": self.org_retrieved.to_json()},
path_ending_type="organization",
)
my_github.write_org_json(
dict_to_write=self.teams_json, path_ending_type="teams", is_list=True
)
my_github.write_repo_json(
dict_to_write=self.repos_json, path_ending_type="repo"
)
my_github.write_repo_json(
dict_to_write=self.contributors_json,
path_ending_type="contributors",
is_list=True,
)
my_github.write_repo_json(
dict_to_write=self.pull_requests_json,
path_ending_type="pull-requests",
is_list=True,
)
my_github.write_repo_json(
dict_to_write=self.issues_json, path_ending_type="issues", is_list=True
)
my_github.write_repo_json(
dict_to_write=self.languages_json,
path_ending_type="languages",
is_dict=True,
)
my_github.write_repo_json(
dict_to_write=self.commits_json,
path_ending_type="commits",
is_list=True,
)
# Write CSV
my_github.write_to_file(
file_path, date, organization, count_members, count_teams
)
calls_remaining = self.logged_in_gh.ratelimit_remaining
calls_used = calls_beginning - calls_remaining
print(
"Rate Limit Remaining: "
+ str(calls_remaining)
+ "\nUsed "
+ str(calls_used)
+ " API calls."
)
def login(self, username="", password=""):
"""
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
"""
try:
self.token = ""
id = ""
if not os.path.isfile("CREDENTIALS_FILE"):
if username == "" or password == "":
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
note = "GitHub Organization Stats App"
note_url = "http://software.llnl.gov/"
scopes = ["user", "repo"]
auth = github3.authorize(
username,
password,
scopes,
note,
note_url,
two_factor_callback=self.prompt_2fa,
)
self.token = auth.token
id = auth.id
with open("CREDENTIALS_FILE", "w+") as fd:
fd.write(self.token + "\n")
fd.write(str(id))
fd.close()
else:
with open("CREDENTIALS_FILE", "r") as fd:
self.token = fd.readline().strip()
id = fd.readline().strip()
fd.close()
print("Logging in.")
self.logged_in_gh = github3.login(
token=self.token, two_factor_callback=self.prompt_2fa
)
self.logged_in_gh.user().to_json()
except (ValueError, AttributeError, github3.models.GitHubError):
print("Bad credentials. Try again.")
self.login()
def prompt_2fa(self):
"""
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
"""
code = ""
while not code:
code = raw_input("Enter 2FA code: ")
return code
def get_org(self, organization_name=""):
"""
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
"""
if organization_name == "":
organization_name = raw_input("Organization: ")
print("Getting organization.")
self.org_retrieved = self.logged_in_gh.organization(organization_name)
def get_mems_of_org(self):
"""
Retrieves the number of members of the organization.
"""
print("Getting members.")
counter = 0
for member in self.org_retrieved.iter_members():
self.members_json[member.id] = member.to_json()
counter += 1
return counter
def get_teams_of_org(self):
"""
Retrieves the number of teams of the organization.
"""
print("Getting teams.")
counter = 0
for team in self.org_retrieved.iter_teams():
self.teams_json[team.id] = team.to_json()
counter += 1
return counter
def repos(self, repo_type="public", organization="llnl"):
"""
Retrieves info about the repos of the current organization.
"""
print("Getting repos.")
for repo in self.org_retrieved.iter_repos(type=repo_type):
# JSON
json = repo.to_json()
self.repos_json[repo.name] = json
# CSV
temp_repo = my_repo.My_Repo()
temp_repo.name = repo.full_name
self.total_repos += 1
temp_repo.contributors = my_github.get_total_contributors(repo)
self.total_contributors += temp_repo.contributors
temp_repo.forks = repo.forks_count
self.total_forks += temp_repo.forks
temp_repo.stargazers = repo.stargazers
self.total_stars += temp_repo.stargazers
(
temp_repo.pull_requests_open,
temp_repo.pull_requests_closed,
) = my_github.get_pull_reqs(repo)
temp_repo.pull_requests = (
temp_repo.pull_requests_open + temp_repo.pull_requests_closed
)
self.total_pull_reqs += temp_repo.pull_requests_open
self.total_pull_reqs += temp_repo.pull_requests_closed
self.total_pull_reqs_open += temp_repo.pull_requests_open
self.total_pull_reqs_closed += temp_repo.pull_requests_closed
temp_repo.open_issues = repo.open_issues_count
self.total_open_issues += temp_repo.open_issues
temp_repo.closed_issues = my_github.get_issues(
repo, organization=organization
)
temp_repo.issues = temp_repo.closed_issues + temp_repo.open_issues
self.total_closed_issues += temp_repo.closed_issues
self.total_issues += temp_repo.issues
my_github.get_languages(repo, temp_repo)
temp_repo.readme = my_github.get_readme(repo)
# temp_repo.license = my_github.get_license(repo)
temp_repo.commits = self.get_commits(repo=repo, organization=organization)
self.total_commits += temp_repo.commits
self.all_repos.append(temp_repo)
def get_total_contributors(self, repo):
"""
Retrieves the number of contributors to a repo in the organization.
Also adds to unique contributor list.
"""
repo_contributors = 0
for contributor in repo.iter_contributors():
repo_contributors += 1
self.unique_contributors[contributor.id].append(repo.name)
self.contributors_json[repo.name].append(contributor.to_json())
return repo_contributors
def get_pull_reqs(self, repo):
"""
Retrieves the number of pull requests on a repo in the organization.
"""
pull_reqs_open = 0
pull_reqs_closed = 0
for pull_request in repo.iter_pulls(state="all"):
self.pull_requests_json[repo.name].append(pull_request.to_json())
if pull_request.closed_at is not None:
pull_reqs_closed += 1
else:
pull_reqs_open += 1
return pull_reqs_open, pull_reqs_closed
def get_issues(self, repo, organization="llnl"):
"""
Retrieves the number of closed issues.
"""
# JSON
path = "../github-data/" + organization + "/" + repo.name + "/issues"
is_only_today = False
if not os.path.exists(path): # no previous path, get all issues
all_issues = repo.iter_issues(state="all")
is_only_today = True
else:
files = os.listdir(path)
date = str(files[-1][:-5])
if date == str(datetime.date.today()):
# most recent date is actually today, get previous most recent date
if len(files) > 2:
date = str(files[-2][:-5])
else:
# This means there is only one file, today. Retrieve every issue
all_issues = repo.iter_issues(state="all")
is_only_today = True
if not is_only_today: # there's a previous saved JSON that's not today
all_issues = repo.iter_issues(since=date, state="all")
for issue in all_issues:
self.issues_json[repo.name].append(issue.to_json())
# CSV
closed_issues = 0
for issue in repo.iter_issues(state="closed"):
if issue is not None:
closed_issues += 1
return closed_issues
def get_languages(self, repo, temp_repo):
"""
Retrieves the languages used in the repo and increments the respective
counts of those languages. Only increments languages that have names.
Anything else is not incremented (i.e. numbers).
"""
try:
self.languages[repo.language] += 1
except KeyError:
count = self.languages[repo.language] = 1
for repo_languages in repo.iter_languages():
self.languages_json[repo.name][repo_languages[0]] = repo_languages[1]
for language in repo_languages:
if isinstance(language, basestring): # is language
temp_repo.languages.append(language)
self.previous_language = language
else: # record size bytes of language
try:
self.languages_size[self.previous_language] += language
except KeyError:
size = self.languages_size[self.previous_language] = language
def get_readme(self, repo):
"""
Checks to see if the given repo has a ReadMe. MD means it has a correct
Readme recognized by GitHub.
"""
readme_contents = repo.readme()
if readme_contents is not None:
self.total_readmes += 1
return "MD"
if self.search_limit >= 28:
print("Hit search limit. Sleeping for 60 sec.")
time.sleep(60)
self.search_limit = 0
self.search_limit += 1
search_results = self.logged_in_gh.search_code(
"readme" + "in:path repo:" + repo.full_name
)
try:
for result in search_results:
path = result.path[1:]
if "/" not in path and "readme" in path.lower():
self.total_readmes += 1
return path
return "MISS"
except (github3.models.GitHubError, StopIteration):
return "MISS"
def get_license(self, repo):
"""
Checks to see if the given repo has a top level LICENSE file.
"""
if self.search_limit >= 28:
print("Hit search limit. Sleeping for 60 sec.")
time.sleep(60)
self.search_limit = 0
self.search_limit += 1
search_results = self.logged_in_gh.search_code(
"license" + "in:path repo:" + repo.full_name
)
try:
for result in search_results:
path = result.path[1:]
if "/" not in path and "license" in path.lower():
self.total_licenses += 1
return path
return "MISS"
except StopIteration:
return "MISS"
def get_commits(self, repo, organization="llnl"):
"""
Retrieves the number of commits to a repo in the organization. If it is
the first time getting commits for a repo, it will get all commits and
save them to JSON. If there are previous commits saved, it will only get
commits that have not been saved to disk since the last date of commits.
"""
# JSON
path = "../github-data/" + organization + "/" + repo.name + "/commits"
is_only_today = False
if not os.path.exists(path): # no previous path, get all commits
all_commits = repo.iter_commits()
is_only_today = True
else:
files = os.listdir(path)
date = str(files[-1][:-5])
if date == str(datetime.date.today()):
# most recent date is actually today, get previous most recent date
if len(files) > 2:
date = str(files[-2][:-5])
else:
# This means there is only one file, today. Retrieve every commit
all_commits = repo.iter_commits()
is_only_today = True
if not is_only_today: # there's a previous saved JSON that's not today
all_commits = repo.iter_commits(since=date)
for commit in all_commits:
self.commits_json[repo.name].append(commit.to_json())
# for csv
count = 0
for commit in repo.iter_commits():
count += 1
return count
def write_org_json(
self,
date=(datetime.date.today()),
organization="llnl",
dict_to_write={},
path_ending_type="",
is_list=False,
):
"""
Writes stats from the organization to JSON.
"""
path = (
"../github-data/"
+ organization
+ "-org/"
+ path_ending_type
+ "/"
+ str(date)
+ ".json"
)
self.checkDir(path)
with open(path, "w") as out_clear: # clear old data
out_clear.close()
with open(path, "a") as out:
if is_list: # used for list of items
out.write("[")
for item in dict_to_write:
out.write(
json.dumps(
dict_to_write[item],
sort_keys=True,
indent=4,
separators=(",", ": "),
)
+ ","
)
out.seek(-1, os.SEEK_END) # kill last comma
out.truncate()
if is_list:
out.write("]")
out.close()
def write_repo_json(
self,
date=(datetime.date.today()),
organization="llnl",
dict_to_write={},
path_ending_type="",
is_list=False,
is_dict=False,
):
"""
#Writes repo specific data to JSON.
"""
for repo in dict_to_write:
path = (
"../github-data/"
+ organization
+ "/"
+ repo
+ "/"
+ path_ending_type
+ "/"
+ str(date)
+ ".json"
)
self.checkDir(path)
with open(path, "w") as out:
if is_list:
out.write("[")
for value in dict_to_write[repo]:
if is_dict:
for inner_dict in value:
out.write(
json.dumps(
inner_dict,
sort_keys=True,
indent=4,
separators=(",", ": "),
)
+ ","
)
else:
out.write(
json.dumps(
value,
sort_keys=True,
indent=4,
separators=(",", ": "),
)
+ ","
)
out.seek(-1, os.SEEK_END) # kill last comma
out.truncate()
out.write("]")
else:
out.write(
json.dumps(
dict_to_write[repo],
sort_keys=True,
indent=4,
separators=(",", ": "),
)
)
out.close()
def write_to_file(
self,
file_path="",
date=str(datetime.date.today()),
organization="N/A",
members=0,
teams=0,
):
"""
Writes the current organization information to file (csv).
"""
self.checkDir(file_path)
with open(file_path, "w+") as output:
output.write(
"date,organization,members,teams,unique_contributors,"
+ "repository,contributors,forks,stargazers,pull_requests,"
+ "open_issues,has_readme,has_license,languages,pull_requests_open,"
+ "pull_requests_closed,commits,closed_issues,issues\n"
+ date
+ ","
+ organization
+ ","
+ str(members)
+ ","
+ str(teams)
+ ","
+ str(len(self.unique_contributors))
+ "\n"
)
for repo in self.all_repos:
output.write(
",,,,,"
+ repo.name
+ ","
+ str(repo.contributors)
+ ","
+ str(repo.forks)
+ ","
+ str(repo.stargazers)
+ ","
+ str(repo.pull_requests)
+ ","
+ str(repo.open_issues)
+ ","
+ str(repo.readme)
+ ","
+ str(repo.license)
+ ","
+ " ".join(sorted(repo.languages))
+ ","
+ str(repo.pull_requests_open)
+ ","
+ str(repo.pull_requests_closed)
+ ","
+ str(repo.commits)
+ ","
+ str(repo.closed_issues)
+ ","
+ str(repo.issues)
+ "\n"
)
output.write(
",,,,total,"
+ str(self.total_repos)
+ ","
+ str(self.total_contributors)
+ ","
+ str(self.total_forks)
+ ","
+ str(self.total_stars)
+ ","
+ str(self.total_pull_reqs)
+ ","
+ str(self.total_open_issues)
+ ","
+ str(self.total_readmes)
+ ","
+ str(self.total_licenses)
+ ",,"
+ str(self.total_pull_reqs_open)
+ ","
+ str(self.total_pull_reqs_closed)
+ ","
+ str(self.total_commits)
+ ","
+ str(self.total_closed_issues)
+ ","
+ str(self.total_issues)
)
output.close()
# Update total
self.write_totals(
file_path="../github_stats_output/total.csv",
date=date,
organization=organization,
members=members,
teams=teams,
)
# Update language sizes
self.write_languages(
file_path="../github_stats_output/languages.csv", date=date
)
def write_totals(
self,
file_path="",
date=str(datetime.date.today()),
organization="N/A",
members=0,
teams=0,
):
"""
Updates the total.csv file with current data.
"""
total_exists = os.path.isfile(file_path)
with open(file_path, "a") as out_total:
if not total_exists:
out_total.write(
"date,organization,repos,members,teams,"
+ "unique_contributors,total_contributors,forks,"
+ "stargazers,pull_requests,open_issues,has_readme,"
+ "has_license,pull_requests_open,pull_requests_closed,"
+ "commits,id,closed_issues,issues\n"
)
self.delete_last_line(date=date, file_path=file_path)
out_total.close()
with open(file_path, "r") as file_read:
row_count = sum(1 for row in file_read) - 1
file_read.close()
with open(file_path, "a") as out_total:
out_total.write(
date
+ ","
+ organization
+ ","
+ str(self.total_repos)
+ ","
+ str(members)
+ ","
+ str(teams)
+ ","
+ str(len(self.unique_contributors))
+ ","
+ str(self.total_contributors)
+ ","
+ str(self.total_forks)
+ ","
+ str(self.total_stars)
+ ","
+ str(self.total_pull_reqs)
+ ","
+ str(self.total_open_issues)
+ ","
+ str(self.total_readmes)
+ ","
+ str(self.total_licenses)
+ ","
+ str(self.total_pull_reqs_open)
+ ","
+ str(self.total_pull_reqs_closed)
+ ","
+ str(self.total_commits)
+ ","
+ str(row_count)
+ ","
+ str(self.total_closed_issues)
+ ","
+ str(self.total_issues)
+ "\n"
)
out_total.close()
def write_languages(self, file_path="", date=str(datetime.date.today())):
"""
Updates languages.csv file with current data.
"""
self.remove_date(file_path=file_path, date=date)
languages_exists = os.path.isfile(file_path)
with open(file_path, "a") as out_languages:
if not languages_exists:
out_languages.write("date,language,count,size,size_log\n")
languages_sorted = sorted(self.languages_size)
# self.delete_last_line(date=date, file_path=file_path)
for language in languages_sorted:
try:
out_languages.write(
date
+ ","
+ language
+ ","
+ str(self.languages[language])
+ ","
+ str(self.languages_size[language])
+ ","
+ str(math.log10(int(self.languages_size[language])))
+ "\n"
)
except (TypeError, KeyError):
out_languages.write(
date
+ ","
+ language
+ ","
+ str(0)
+ ","
+ str(self.languages_size[language])
+ ","
+ str(math.log10(int(self.languages_size[language])))
+ "\n"
)
def checkDir(self, file_path=""):
"""
Checks if a directory exists. If not, it creates one with the specified
file_path.
"""
if not os.path.exists(os.path.dirname(file_path)):
try:
os.makedirs(os.path.dirname(file_path))
except OSError as e:
if e.errno != errno.EEXIST:
raise
def remove_date(self, file_path="", date=str(datetime.date.today())):
"""
Removes all rows of the associated date from the given csv file.
Defaults to today.
"""
languages_exists = os.path.isfile(file_path)
if languages_exists:
with open(file_path, "rb") as inp, open("temp.csv", "wb") as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[0] != date:
writer.writerow(row)
inp.close()
out.close()
os.remove(file_path)
os.rename("temp.csv", file_path)
def delete_last_line(self, file_path="", date=str(datetime.date.today())):
"""
The following code was modified from
http://stackoverflow.com/a/10289740 &
http://stackoverflow.com/a/17309010
It essentially will check if the total for the current date already
exists in total.csv. If it does, it just removes the last line.
This is so the script could be run more than once a day and not
create many entries in the total.csv file for the same date.
"""
deleted_line = False
if os.path.isfile(file_path):
with open(file_path, "r+") as file:
reader = csv.reader(file, delimiter=",")
for row in reader:
if date == row[0]:
file.seek(0, os.SEEK_END)
pos = file.tell() - 1
while pos > 0 and file.read(1) != "\n":
pos -= 1
file.seek(pos, os.SEEK_SET)
if pos > 0:
file.seek(pos, os.SEEK_SET)
file.truncate()
deleted_line = True
break
if deleted_line:
file.write("\n")
file.close()
|
class GitHub_LLNL_Stats:
def __init__(self):
pass
def get_stats(
self,
username="",
password="",
organization="llnl",
force=True,
repo_type="public",
):
'''
Retrieves the statistics from the given organization with the given
credentials. Will not retreive data if file exists and force hasn't been
set to True. This is to save GH API requests.
'''
pass
def login(self, username="", password=""):
'''
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
'''
pass
def prompt_2fa(self):
'''
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
'''
pass
def get_org(self, organization_name=""):
'''
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
'''
pass
def get_mems_of_org(self):
'''
Retrieves the number of members of the organization.
'''
pass
def get_teams_of_org(self):
'''
Retrieves the number of teams of the organization.
'''
pass
def repos(self, repo_type="public", organization="llnl"):
'''
Retrieves info about the repos of the current organization.
'''
pass
def get_total_contributors(self, repo):
'''
Retrieves the number of contributors to a repo in the organization.
Also adds to unique contributor list.
'''
pass
def get_pull_reqs(self, repo):
'''
Retrieves the number of pull requests on a repo in the organization.
'''
pass
def get_issues(self, repo, organization="llnl"):
'''
Retrieves the number of closed issues.
'''
pass
def get_languages(self, repo, temp_repo):
'''
Retrieves the languages used in the repo and increments the respective
counts of those languages. Only increments languages that have names.
Anything else is not incremented (i.e. numbers).
'''
pass
def get_readme(self, repo):
'''
Checks to see if the given repo has a ReadMe. MD means it has a correct
Readme recognized by GitHub.
'''
pass
def get_license(self, repo):
'''
Checks to see if the given repo has a top level LICENSE file.
'''
pass
def get_commits(self, repo, organization="llnl"):
'''
Retrieves the number of commits to a repo in the organization. If it is
the first time getting commits for a repo, it will get all commits and
save them to JSON. If there are previous commits saved, it will only get
commits that have not been saved to disk since the last date of commits.
'''
pass
def write_org_json(
self,
date=(datetime.date.today()),
organization="llnl",
dict_to_write={},
path_ending_type="",
is_list=False,
):
'''
Writes stats from the organization to JSON.
'''
pass
def write_repo_json(
self,
date=(datetime.date.today()),
organization="llnl",
dict_to_write={},
path_ending_type="",
is_list=False,
is_dict=False,
):
'''
#Writes repo specific data to JSON.
'''
pass
def write_to_file(
self,
file_path="",
date=str(datetime.date.today()),
organization="N/A",
members=0,
teams=0,
):
'''
Writes the current organization information to file (csv).
'''
pass
def write_totals(
self,
file_path="",
date=str(datetime.date.today()),
organization="N/A",
members=0,
teams=0,
):
'''
Updates the total.csv file with current data.
'''
pass
def write_languages(self, file_path="", date=str(datetime.date.today())):
'''
Updates languages.csv file with current data.
'''
pass
def checkDir(self, file_path=""):
'''
Checks if a directory exists. If not, it creates one with the specified
file_path.
'''
pass
def remove_date(self, file_path="", date=str(datetime.date.today())):
'''
Removes all rows of the associated date from the given csv file.
Defaults to today.
'''
pass
def delete_last_line(self, file_path="", date=str(datetime.date.today())):
'''
The following code was modified from
http://stackoverflow.com/a/10289740 &
http://stackoverflow.com/a/17309010
It essentially will check if the total for the current date already
exists in total.csv. If it does, it just removes the last line.
This is so the script could be run more than once a day and not
create many entries in the total.csv file for the same date.
'''
pass
| 24 | 22 | 33 | 0 | 28 | 5 | 4 | 0.18 | 0 | 12 | 1 | 0 | 23 | 30 | 23 | 23 | 784 | 25 | 653 | 169 | 593 | 116 | 353 | 122 | 329 | 8 | 0 | 6 | 87 |
144,618 |
LLNL/scraper
|
LLNL_scraper/scripts/get_users_emails.py
|
get_users_emails.GitHub_Users_Emails
|
class GitHub_Users_Emails:
def __init__(self):
self.emails = {}
self.logins_lower = {}
def get_stats(self, username="", password="", organization="llnl", force=True):
"""
Retrieves the emails for the users of the given organization.
"""
file_path = "../github_stats_output/users_emails.csv"
if force or not os.path.isfile(file_path):
my_github.login(username, password)
calls_beginning = self.logged_in_gh.ratelimit_remaining + 1
print("Rate Limit: " + str(calls_beginning))
my_github.get_org(organization)
count_members = my_github.get_mems_of_org()
my_github.write_to_file(file_path)
calls_remaining = self.logged_in_gh.ratelimit_remaining
calls_used = calls_beginning - calls_remaining
print(
"Rate Limit Remaining: "
+ str(calls_remaining)
+ "\nUsed "
+ str(calls_used)
+ " API calls."
)
def login(self, username="", password=""):
"""
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
"""
try:
token = ""
id = ""
if not os.path.isfile("CREDENTIALS_FILE"):
if username == "" or password == "":
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
note = "GitHub Organization Stats App"
note_url = "http://software.llnl.gov/"
scopes = ["user", "repo"]
auth = github3.authorize(
username,
password,
scopes,
note,
note_url,
two_factor_callback=self.prompt_2fa,
)
token = auth.token
id = auth.id
with open("CREDENTIALS_FILE", "w+") as fd:
fd.write(token + "\n")
fd.write(str(id))
fd.close()
else:
with open("CREDENTIALS_FILE", "r") as fd:
token = fd.readline().strip()
id = fd.readline().strip()
fd.close()
print("Logging in.")
self.logged_in_gh = github3.login(
token=token, two_factor_callback=self.prompt_2fa
)
self.logged_in_gh.user().to_json()
except (ValueError, AttributeError, github3.models.GitHubError):
print("Bad credentials. Try again.")
self.login()
def prompt_2fa(self):
"""
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
"""
code = ""
while not code:
code = raw_input("Enter 2FA code: ")
return code
def get_org(self, organization_name=""):
"""
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
"""
if organization_name == "":
organization_name = raw_input("Organization: ")
print("Getting organization.")
self.org_retrieved = self.logged_in_gh.organization(organization_name)
def get_mems_of_org(self):
"""
Retrieves the emails of the members of the organization. Note this Only
gets public emails. Private emails would need authentication for each
user.
"""
print("Getting members' emails.")
for member in self.org_retrieved.iter_members():
login = member.to_json()["login"]
user_email = self.logged_in_gh.user(login).to_json()["email"]
if user_email is not None:
self.emails[login] = user_email
else: # user has no public email
self.emails[login] = "none"
# used for sorting regardless of case
self.logins_lower[login.lower()] = login
def write_to_file(self, file_path=""):
"""
Writes the user emails to file.
"""
with open(file_path, "w+") as out:
out.write("user, email\n")
sorted_names = sorted(self.logins_lower) # sort based on lowercase
for login in sorted_names:
out.write(
self.logins_lower[login]
+ ","
+ self.emails[self.logins_lower[login]]
+ "\n"
)
out.close()
|
class GitHub_Users_Emails:
def __init__(self):
pass
def get_stats(self, username="", password="", organization="llnl", force=True):
'''
Retrieves the emails for the users of the given organization.
'''
pass
def login(self, username="", password=""):
'''
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
'''
pass
def prompt_2fa(self):
'''
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
'''
pass
def get_org(self, organization_name=""):
'''
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
'''
pass
def get_mems_of_org(self):
'''
Retrieves the emails of the members of the organization. Note this Only
gets public emails. Private emails would need authentication for each
user.
'''
pass
def write_to_file(self, file_path=""):
'''
Writes the user emails to file.
'''
pass
| 8 | 6 | 17 | 0 | 13 | 4 | 2 | 0.32 | 0 | 3 | 0 | 0 | 7 | 4 | 7 | 7 | 125 | 6 | 92 | 30 | 84 | 29 | 70 | 28 | 62 | 4 | 0 | 3 | 16 |
144,619 |
LLNL/scraper
|
LLNL_scraper/scripts/get_stargazers.py
|
get_stargazers.GitHub_Stargazers
|
class GitHub_Stargazers:
def __init__(self):
self.repos = {}
self.stargazers = {}
self.total_count = 0
def get_stats(self, username="", password="", organization="llnl", force=True):
"""
Retrieves the traffic for the users of the given organization.
Requires organization admin credentials token to access the data.
"""
stargazers_file_path = "../github_stats_output/stargazers.csv"
if force or not os.path.isfile(file_path):
my_github.login(username, password)
calls_beginning = self.logged_in_gh.ratelimit_remaining + 1
print("Rate Limit: " + str(calls_beginning))
my_github.get_org(organization)
my_github.get_repos()
my_github.write_to_file(file_path=stargazers_file_path)
# my_github.write_to_file(file_path=stargazers_file_path)
calls_remaining = self.logged_in_gh.ratelimit_remaining
calls_used = calls_beginning - calls_remaining
print(
"Rate Limit Remaining: "
+ str(calls_remaining)
+ "\nUsed "
+ str(calls_used)
+ " API calls."
)
def login(self, username="", password=""):
"""
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
"""
try:
self.token = ""
id = ""
if not os.path.isfile("CREDENTIALS_FILE"):
if username == "" or password == "":
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
note = "GitHub Organization Stats App"
note_url = "http://software.llnl.gov/"
scopes = ["user", "repo"]
auth = github3.authorize(
username,
password,
scopes,
note,
note_url,
two_factor_callback=self.prompt_2fa,
)
self.token = auth.token
id = auth.id
with open("CREDENTIALS_FILE", "w+") as fd:
fd.write(self.token + "\n")
fd.write(str(id))
fd.close()
else:
with open("CREDENTIALS_FILE", "r") as fd:
self.token = fd.readline().strip()
id = fd.readline().strip()
fd.close()
print("Logging in.")
self.logged_in_gh = github3.login(
token=self.token, two_factor_callback=self.prompt_2fa
)
self.logged_in_gh.user().to_json()
except (ValueError, AttributeError, github3.models.GitHubError):
print("Bad credentials. Try again.")
self.login()
def prompt_2fa(self):
"""
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
"""
code = ""
while not code:
code = raw_input("Enter 2FA code: ")
return code
def get_org(self, organization_name=""):
"""
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
"""
self.organization_name = organization_name
if organization_name == "":
self.organization_name = raw_input("Organization: ")
print("Getting organization.")
self.org_retrieved = self.logged_in_gh.organization(organization_name)
def get_repos(self):
"""
Gets the repos for the organization and builds the URL/headers for
getting timestamps of stargazers.
"""
print("Getting repos.")
# Uses the developer API. Note this could change.
headers = {
"Accept": "application/vnd.github.v3.star+json",
"Authorization": "token " + self.token,
}
temp_count = 0
for repo in self.org_retrieved.iter_repos():
temp_count += 1
url = (
"https://api.github.com/repos/"
+ self.organization_name
+ "/"
+ repo.name
)
self.repos[repo.name] = self.get_stargazers(url=url, headers=headers)
self.calc_stargazers(start_count=650)
print("total count: \t" + str(self.total_count))
print(str(temp_count) + " repos")
def get_stargazers(self, url, headers={}):
"""
Return a list of the stargazers of a GitHub repo
Includes both the 'starred_at' and 'user' data.
param: url
url is the 'stargazers_url' of the form:
https://api.github.com/repos/LLNL/spack/stargazers
"""
url = url + "/stargazers?per_page=100&page=%s"
page = 1
gazers = []
json_data = requests.get(url % page, headers=headers).json()
while json_data:
gazers.extend(json_data)
page += 1
json_data = requests.get(url % page, headers=headers).json()
return gazers
def calc_stargazers(self, date=(datetime.date.today()), start_count=0):
for repo_json in self.repos:
for stargazer in self.repos[repo_json]:
print(stargazer)
date = stargazer["starred_at"][:10]
try:
self.stargazers[date] += 1
except KeyError:
count = self.stargazers[date] = 1
sorted_stargazers = sorted(self.stargazers)
for stargazer in reversed(sorted_stargazers):
number_starred = self.stargazers[stargazer]
self.stargazers[stargazer] = start_count - number_starred
start_count = start_count - number_starred
def write_to_file(
self, file_path="", date=(datetime.date.today()), organization="llnl"
):
"""
Writes stargazers data to file.
"""
with open(file_path, "w+") as out:
out.write("date,organization,stargazers\n")
sorted_stargazers = sorted(self.stargazers) # sort based on lowercase
for star in sorted_stargazers:
out.write(star + "," + str(self.stargazers[star]) + "\n")
out.close()
|
class GitHub_Stargazers:
def __init__(self):
pass
def get_stats(self, username="", password="", organization="llnl", force=True):
'''
Retrieves the traffic for the users of the given organization.
Requires organization admin credentials token to access the data.
'''
pass
def login(self, username="", password=""):
'''
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
'''
pass
def prompt_2fa(self):
'''
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
'''
pass
def get_org(self, organization_name=""):
'''
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
'''
pass
def get_repos(self):
'''
Gets the repos for the organization and builds the URL/headers for
getting timestamps of stargazers.
'''
pass
def get_stargazers(self, url, headers={}):
'''
Return a list of the stargazers of a GitHub repo
Includes both the 'starred_at' and 'user' data.
param: url
url is the 'stargazers_url' of the form:
https://api.github.com/repos/LLNL/spack/stargazers
'''
pass
def calc_stargazers(self, date=(datetime.date.today()), start_count=0):
pass
def write_to_file(
self, file_path="", date=(datetime.date.today()), organization="llnl"
):
'''
Writes stargazers data to file.
'''
pass
| 10 | 7 | 18 | 1 | 14 | 4 | 2 | 0.29 | 0 | 6 | 0 | 0 | 9 | 7 | 9 | 9 | 172 | 13 | 124 | 44 | 112 | 36 | 98 | 40 | 88 | 5 | 0 | 3 | 22 |
144,620 |
LLNL/scraper
|
LLNL_scraper/scraper/code_gov/models.py
|
scraper.code_gov.models.Metadata
|
class Metadata(dict):
"""
Defines the entire contents of a Code.gov 's code.json file
For details: https://code.gov/#/policy-guide/docs/compliance/inventory-code
"""
def __init__(self, agency, method, other_method=""):
# *version: [string] The Code.gov metadata schema version
self["version"] = "2.0.0"
# *agency: [string] The agency acronym for Clinger Cohen Act agency, e.g. "GSA" or "DOD"
self["agency"] = agency.upper()
# *measurementType: [object] The description of the open source measurement method
# *method [enum]: An enumerated list of methods for measuring the open source requirement
# cost: Cost of software development.
# systems: System certification and accreditation boundaries.
# projects: A complete software solution / project.
# modules: A self-contained module from a software solution.
# linesOfCode: Source lines of code.
# other: Another measurement method not referenced above.
# ifOther: [string] A one- or two- sentence description of the measurement type used, if 'other' is selected as the value of 'method' field.
self["measurementType"] = {"method": method}
if method == "other":
self["measurementType"]["ifOther"] = other_method
# The list of source code releases
self["releases"] = []
def to_json(self):
return json.dumps(self, indent=4, sort_keys=True, ensure_ascii=False)
|
class Metadata(dict):
'''
Defines the entire contents of a Code.gov 's code.json file
For details: https://code.gov/#/policy-guide/docs/compliance/inventory-code
'''
def __init__(self, agency, method, other_method=""):
pass
def to_json(self):
pass
| 3 | 1 | 12 | 2 | 5 | 6 | 2 | 1.6 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 29 | 32 | 6 | 10 | 3 | 7 | 16 | 10 | 3 | 7 | 2 | 2 | 1 | 3 |
144,621 |
LLNL/scraper
|
LLNL_scraper/scripts/get_traffic.py
|
get_traffic.GitHub_Traffic
|
class GitHub_Traffic:
def __init__(self):
self.referrers = {}
self.referrers_lower = {}
self.views = {}
self.clones = {}
self.referrers_json = {}
self.views_json = {}
self.clones_json = {}
self.releases_json = {}
def get_stats(self, username="", password="", organization="llnl", force=True):
"""
Retrieves the traffic for the users of the given organization.
Requires organization admin credentials token to access the data.
"""
referrers_file_path = "../github_stats_output/referrers.csv"
views_file_path = "../github_stats_output/views.csv"
clones_file_path = "../github_stats_output/clones.csv"
if force or not os.path.isfile(file_path):
my_github.login(username, password)
calls_beginning = self.logged_in_gh.ratelimit_remaining + 1
print("Rate Limit: " + str(calls_beginning))
my_github.get_org(organization)
my_github.get_traffic()
views_row_count = my_github.check_data_redundancy(
file_path=views_file_path, dict_to_check=self.views
)
clones_row_count = my_github.check_data_redundancy(
file_path=clones_file_path, dict_to_check=self.clones
)
my_github.write_to_file(
referrers_file_path=referrers_file_path,
views_file_path=views_file_path,
clones_file_path=clones_file_path,
views_row_count=views_row_count,
clones_row_count=clones_row_count,
)
my_github.write_json(
dict_to_write=self.referrers_json,
path_ending_type="traffic_popular_referrers",
)
my_github.write_json(
dict_to_write=self.views_json, path_ending_type="traffic_views"
)
my_github.write_json(
dict_to_write=self.clones_json, path_ending_type="traffic_clones"
)
my_github.write_json(
dict_to_write=self.releases_json, path_ending_type="releases"
)
calls_remaining = self.logged_in_gh.ratelimit_remaining
calls_used = calls_beginning - calls_remaining
print(
"Rate Limit Remaining: "
+ str(calls_remaining)
+ "\nUsed "
+ str(calls_used)
+ " API calls."
)
def login(self, username="", password=""):
"""
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
"""
try:
self.token = ""
id = ""
if not os.path.isfile("CREDENTIALS_FILE_ADMIN"):
if username == "" or password == "":
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
note = "GitHub Organization Stats App"
note_url = "http://software.llnl.gov/"
scopes = ["user", "repo"]
auth = github3.authorize(
username,
password,
scopes,
note,
note_url,
two_factor_callback=self.prompt_2fa,
)
self.token = auth.token
id = auth.id
with open("CREDENTIALS_FILE_ADMIN", "w+") as fd:
fd.write(self.token + "\n")
fd.write(str(id))
fd.close()
else:
with open("CREDENTIALS_FILE_ADMIN", "r") as fd:
self.token = fd.readline().strip()
id = fd.readline().strip()
fd.close()
print("Logging in.")
self.logged_in_gh = github3.login(
token=self.token, two_factor_callback=self.prompt_2fa
)
self.logged_in_gh.user().to_json()
except (ValueError, AttributeError, github3.models.GitHubError):
print("Bad credentials. Try again.")
self.login()
def prompt_2fa(self):
"""
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
"""
code = ""
while not code:
code = raw_input("Enter 2FA code: ")
return code
def get_org(self, organization_name=""):
"""
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
"""
self.organization_name = organization_name
if organization_name == "":
self.organization_name = raw_input("Organization: ")
print("Getting organization.")
self.org_retrieved = self.logged_in_gh.organization(organization_name)
def get_traffic(self):
"""
Retrieves the traffic for the repositories of the given organization.
"""
print("Getting traffic.")
# Uses the developer API. Note this could change.
headers = {
"Accept": "application/vnd.github.spiderman-preview",
"Authorization": "token " + self.token,
}
headers_release = {"Authorization": "token " + self.token}
for repo in self.org_retrieved.iter_repos(type="public"):
url = (
"https://api.github.com/repos/"
+ self.organization_name
+ "/"
+ repo.name
)
self.get_referrers(url=url, headers=headers, repo_name=repo.name)
self.get_paths(url=url, headers=headers)
self.get_data(
url=url,
headers=headers,
dict_to_store=self.views,
type="views",
repo_name=repo.name,
)
self.get_data(
url=url,
headers=headers,
dict_to_store=self.clones,
type="clones",
repo_name=repo.name,
)
self.get_releases(url=url, headers=headers_release, repo_name=repo.name)
def get_releases(self, url="", headers={}, repo_name=""):
"""
Retrieves the releases for the given repo in JSON.
"""
url_releases = url + "/releases"
r = requests.get(url_releases, headers=headers)
self.releases_json[repo_name] = r.json()
def get_referrers(self, url="", headers={}, repo_name=""):
"""
Retrieves the total referrers and unique referrers of all repos in json
and then stores it in a dict.
"""
# JSON
url_referrers = url + "/traffic/popular/referrers"
r1 = requests.get(url_referrers, headers=headers)
referrers_json = r1.json()
self.referrers_json[repo_name] = referrers_json
# CSV
for referrer in referrers_json:
ref_name = referrer["referrer"]
try:
tuple_in = (referrer["count"], referrer["uniques"]) # curr vals
tuple = (
self.referrers[ref_name][0] + tuple_in[0], # cal new vals
self.referrers[ref_name][1] + tuple_in[1],
)
self.referrers[ref_name] = tuple # record new vals
except KeyError:
tuple = self.referrers[ref_name] = (
referrer["count"],
referrer["uniques"],
)
self.referrers_lower[ref_name.lower()] = ref_name
def get_paths(self, url="", headers={}):
"""
Retrieves the popular paths information in json and then stores it in a
dict.
"""
url_paths = url + "/traffic/popular/paths"
# r2 = requests.get(url_paths, headers=headers)
# print 'PATHS ' + str(r2.json())
def get_data(
self,
url="",
headers={},
date=str(datetime.date.today()),
dict_to_store={},
type="",
repo_name="",
):
"""
Retrieves data from json and stores it in the supplied dict. Accepts
'clones' or 'views' as type.
"""
# JSON
url = url + "/traffic/" + type
r3 = requests.get(url, headers=headers)
json = r3.json()
if type == "views":
self.views_json[repo_name] = json
elif type == "clones":
self.clones_json[repo_name] = json
# CSV
for day in json[type]:
timestamp_seconds = day["timestamp"] / 1000
try:
date_timestamp = datetime.datetime.utcfromtimestamp(
timestamp_seconds
).strftime("%Y-%m-%d")
# do not add todays date, some views might not be recorded yet
if date_timestamp != date:
tuple_in = (day["count"], day["uniques"])
tuple = (
dict_to_store[timestamp_seconds][0] + tuple_in[0],
dict_to_store[timestamp_seconds][1] + tuple_in[1],
)
dict_to_store[timestamp_seconds] = tuple
except KeyError:
tuple = dict_to_store[timestamp_seconds] = (
day["count"],
day["uniques"],
)
def write_json(
self,
date=(datetime.date.today()),
organization="llnl",
dict_to_write={},
path_ending_type="",
):
"""
Writes all traffic data to file in JSON form.
"""
for repo in dict_to_write:
if len(dict_to_write[repo]) != 0: # don't need to write out empty lists
path = (
"../github-data/"
+ organization
+ "/"
+ repo
+ "/"
+ path_ending_type
+ "/"
+ str(date)
+ ".json"
)
self.checkDir(path)
with open(path, "w") as out:
out.write(
json.dumps(
dict_to_write[repo],
sort_keys=True,
indent=4,
separators=(",", ": "),
)
)
out.close()
def write_to_file(
self,
referrers_file_path="",
views_file_path="",
clones_file_path="",
date=(datetime.date.today()),
organization="llnl",
views_row_count=0,
clones_row_count=0,
):
"""
Writes all traffic data to file.
"""
self.write_referrers_to_file(file_path=referrers_file_path)
self.write_data_to_file(
file_path=views_file_path,
dict_to_write=self.views,
name="views",
row_count=views_row_count,
)
self.write_data_to_file(
file_path=clones_file_path,
dict_to_write=self.clones,
name="clones",
row_count=clones_row_count,
)
def check_data_redundancy(self, file_path="", dict_to_check={}):
"""
Checks the given csv file against the json data scraped for the given
dict. It will remove all data retrieved that has already been recorded
so we don't write redundant data to file. Returns count of rows from
file.
"""
count = 0
exists = os.path.isfile(file_path)
previous_dates = {}
if exists:
with open(file_path, "r") as input:
input.readline() # skip header line
for row in csv.reader(input):
timestamp = calendar.timegm(time.strptime(row[0], "%Y-%m-%d"))
if timestamp in dict_to_check: # our date is already recorded
del dict_to_check[timestamp]
# calc current id max
count += 1
input.close()
return count
def write_data_to_file(
self,
file_path="",
date=str(datetime.date.today()),
organization="llnl",
dict_to_write={},
name="",
row_count=0,
):
"""
Writes given dict to file.
"""
exists = os.path.isfile(file_path)
with open(file_path, "a") as out:
if not exists:
out.write("date,organization," + name + ",unique_" + name + ",id\n")
sorted_dict = sorted(dict_to_write)
for day in sorted_dict:
day_formatted = datetime.datetime.utcfromtimestamp(day).strftime(
"%Y-%m-%d"
)
out.write(
day_formatted
+ ","
+ organization
+ ","
+ str(dict_to_write[day][0])
+ ","
+ str(dict_to_write[day][1])
+ ","
+ str(row_count)
+ "\n"
)
row_count += 1
def write_referrers_to_file(
self, file_path="", date=str(datetime.date.today()), organization="llnl"
):
"""
Writes the referrers data to file.
"""
self.remove_date(file_path=file_path, date=date)
referrers_exists = os.path.isfile(file_path)
with open(file_path, "a") as out:
if not referrers_exists:
out.write(
"date,organization,referrer,count,count_log,uniques,"
+ "uniques_logged\n"
)
sorted_referrers = sorted(self.referrers_lower) # sort based on lowercase
for referrer in sorted_referrers:
ref_name = self.referrers_lower[referrer] # grab real name from
count = self.referrers[ref_name][0]
uniques = self.referrers[ref_name][1]
if count == 1: # so we don't display 0 for count of 1
count = 1.5
if uniques == 1:
uniques = 1.5
count_logged = math.log(count)
uniques_logged = math.log(uniques)
out.write(
date
+ ","
+ organization
+ ","
+ ref_name
+ ","
+ str(count)
+ ","
+ str(count_logged)
+ ","
+ str(uniques)
+ ","
+ str(uniques_logged)
+ "\n"
)
out.close()
def remove_date(self, file_path="", date=str(datetime.date.today())):
"""
Removes all rows of the associated date from the given csv file.
Defaults to today.
"""
languages_exists = os.path.isfile(file_path)
if languages_exists:
with open(file_path, "rb") as inp, open("temp.csv", "wb") as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[0] != date:
writer.writerow(row)
inp.close()
out.close()
os.remove(file_path)
os.rename("temp.csv", file_path)
def checkDir(self, file_path=""):
"""
Checks if a directory exists. If not, it creates one with the specified
file_path.
"""
if not os.path.exists(os.path.dirname(file_path)):
try:
os.makedirs(os.path.dirname(file_path))
except OSError as e:
if e.errno != errno.EEXIST:
raise
|
class GitHub_Traffic:
def __init__(self):
pass
def get_stats(self, username="", password="", organization="llnl", force=True):
'''
Retrieves the traffic for the users of the given organization.
Requires organization admin credentials token to access the data.
'''
pass
def login(self, username="", password=""):
'''
Performs a login and sets the Github object via given credentials. If
credentials are empty or incorrect then prompts user for credentials.
Stores the authentication token in a CREDENTIALS_FILE used for future
logins. Handles Two Factor Authentication.
'''
pass
def prompt_2fa(self):
'''
Taken from
http://github3py.readthedocs.io/en/master/examples/two_factor_auth.html
Prompts a user for their 2FA code and returns it.
'''
pass
def get_org(self, organization_name=""):
'''
Retrieves an organization via given org name. If given
empty string, prompts user for an org name.
'''
pass
def get_traffic(self):
'''
Retrieves the traffic for the repositories of the given organization.
'''
pass
def get_releases(self, url="", headers={}, repo_name=""):
'''
Retrieves the releases for the given repo in JSON.
'''
pass
def get_referrers(self, url="", headers={}, repo_name=""):
'''
Retrieves the total referrers and unique referrers of all repos in json
and then stores it in a dict.
'''
pass
def get_paths(self, url="", headers={}):
'''
Retrieves the popular paths information in json and then stores it in a
dict.
'''
pass
def get_data(
self,
url="",
headers={},
date=str(datetime.date.today()),
dict_to_store={},
type="",
repo_name="",
):
'''
Retrieves data from json and stores it in the supplied dict. Accepts
'clones' or 'views' as type.
'''
pass
def write_json(
self,
date=(datetime.date.today()),
organization="llnl",
dict_to_write={},
path_ending_type="",
):
'''
Writes all traffic data to file in JSON form.
'''
pass
def write_to_file(
self,
referrers_file_path="",
views_file_path="",
clones_file_path="",
date=(datetime.date.today()),
organization="llnl",
views_row_count=0,
clones_row_count=0,
):
'''
Writes all traffic data to file.
'''
pass
def check_data_redundancy(self, file_path="", dict_to_check={}):
'''
Checks the given csv file against the json data scraped for the given
dict. It will remove all data retrieved that has already been recorded
so we don't write redundant data to file. Returns count of rows from
file.
'''
pass
def write_data_to_file(
self,
file_path="",
date=str(datetime.date.today()),
organization="llnl",
dict_to_write={},
name="",
row_count=0,
):
'''
Writes given dict to file.
'''
pass
def write_referrers_to_file(
self, file_path="", date=str(datetime.date.today()), organization="llnl"
):
'''
Writes the referrers data to file.
'''
pass
def remove_date(self, file_path="", date=str(datetime.date.today())):
'''
Removes all rows of the associated date from the given csv file.
Defaults to today.
'''
pass
def checkDir(self, file_path=""):
'''
Checks if a directory exists. If not, it creates one with the specified
file_path.
'''
pass
| 18 | 16 | 25 | 0 | 21 | 5 | 3 | 0.23 | 0 | 7 | 0 | 0 | 17 | 12 | 17 | 17 | 441 | 17 | 352 | 125 | 301 | 81 | 191 | 86 | 173 | 6 | 0 | 4 | 48 |
144,622 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/providers/pushover/push.py
|
LPgenerator_django-db-mailer.dbmail.providers.pushover.push.PushOverError
|
class PushOverError(Exception):
pass
|
class PushOverError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
144,623 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailBaseTemplate
|
class MailBaseTemplate(models.Model):
name = models.CharField(_('Name'), max_length=100, unique=True)
message = HTMLField(
_('Body'), help_text=_(
'Basic template for mail messages. {{content}} tag for msg.'))
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail base template')
verbose_name_plural = _('Mail base templates')
|
class MailBaseTemplate(models.Model):
def __str__(self):
pass
class Meta:
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 14 | 2 | 12 | 9 | 9 | 0 | 10 | 9 | 7 | 1 | 1 | 0 | 1 |
144,624 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailGroup
|
class MailGroup(models.Model):
name = models.CharField(_('Group name'), max_length=100)
slug = models.SlugField(_('Slug'), unique=True)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
def clean_cache(self):
cache.delete(self.slug, version=4)
@classmethod
def get_emails(cls, slug):
emails = cache.get(slug, version=4)
if emails is not None:
return emails
emails = MailGroupEmail.objects.values_list(
'email', flat=True).filter(group__slug=slug)
cache.set(slug, emails, timeout=CACHE_TTL, version=4)
return emails
def save(self, *args, **kwargs):
self.slug = re.sub(r'[^0-9a-zA-Z._-]', '', self.slug)
super(MailGroup, self).save(*args, **kwargs)
self.clean_cache()
def delete(self, using=None):
self.clean_cache()
super(MailGroup, self).delete(using)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail group')
verbose_name_plural = _('Mail groups')
|
class MailGroup(models.Model):
def clean_cache(self):
pass
@classmethod
def get_emails(cls, slug):
pass
def save(self, *args, **kwargs):
pass
def delete(self, using=None):
pass
def __str__(self):
pass
class Meta:
| 8 | 0 | 4 | 1 | 4 | 0 | 1 | 0 | 1 | 3 | 1 | 0 | 4 | 0 | 5 | 5 | 37 | 9 | 28 | 15 | 20 | 0 | 26 | 14 | 19 | 2 | 1 | 1 | 6 |
144,625 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailFromEmailCredential
|
class MailFromEmailCredential(models.Model):
host = models.CharField(_('Host'), max_length=50)
port = models.PositiveIntegerField(_('Port'))
username = models.CharField(
_('Username'), max_length=50, null=True, blank=True)
password = models.CharField(
_('Password'), max_length=50, null=True, blank=True)
use_tls = models.BooleanField(_('Use TLS'), default=False)
fail_silently = models.BooleanField(_('Fail silently'), default=False)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
def _clean_cache(self):
for obj in MailFromEmail.objects.filter(credential=self):
obj._clean_template_cache()
def delete(self, using=None):
self._clean_cache()
super(MailFromEmailCredential, self).delete(using)
def save(self, *args, **kwargs):
super(MailFromEmailCredential, self).save(*args, **kwargs)
self._clean_cache()
def __str__(self):
return '%s/%s' % (self.username, self.host)
class Meta:
verbose_name = _('Mail auth settings')
verbose_name_plural = _('Mail auth settings')
|
class MailFromEmailCredential(models.Model):
def _clean_cache(self):
pass
def delete(self, using=None):
pass
def save(self, *args, **kwargs):
pass
def __str__(self):
pass
class Meta:
| 6 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 4 | 30 | 5 | 25 | 17 | 19 | 0 | 23 | 17 | 17 | 2 | 1 | 1 | 5 |
144,626 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailFromEmail
|
class MailFromEmail(models.Model):
name = models.CharField(_('Name'), max_length=100)
email = models.CharField(
_('Email'), max_length=75, unique=True,
help_text=_('For sms/tts/push you must specify name or number'))
credential = models.ForeignKey(
MailFromEmailCredential, verbose_name=_('Auth credentials'),
blank=True, null=True, default=None, on_delete=models.CASCADE)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
@property
def get_mail_from(self):
return u'%s <%s>' % (self.name, self.email)
def _clean_template_cache(self):
MailTemplate.clean_cache(from_email=self)
def get_auth(self):
if self.credential:
return dict(
host=self.credential.host,
port=self.credential.port,
username=str(self.credential.username),
password=str(self.credential.password),
use_tls=self.credential.use_tls,
fail_silently=self.credential.fail_silently
)
def delete(self, using=None):
self._clean_template_cache()
super(MailFromEmail, self).delete(using)
def save(self, *args, **kwargs):
super(MailFromEmail, self).save(*args, **kwargs)
self._clean_template_cache()
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail from')
verbose_name_plural = _('Mail from')
|
class MailFromEmail(models.Model):
@property
def get_mail_from(self):
pass
def _clean_template_cache(self):
pass
def get_auth(self):
pass
def delete(self, using=None):
pass
def save(self, *args, **kwargs):
pass
def __str__(self):
pass
class Meta:
| 9 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 4 | 1 | 0 | 6 | 0 | 6 | 6 | 43 | 7 | 36 | 16 | 27 | 0 | 24 | 15 | 16 | 2 | 1 | 1 | 7 |
144,627 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailFile
|
class MailFile(models.Model):
template = models.ForeignKey(
MailTemplate, verbose_name=_('Template'), related_name='files',
on_delete=models.CASCADE)
name = models.CharField(_('Name'), max_length=100)
filename = models.FileField(_('File'), upload_to=_upload_mail_file)
def _clean_cache(self):
MailTemplate.clean_cache(pk=self.template.pk)
def save(self, *args, **kwargs):
super(MailFile, self).save(*args, **kwargs)
self._clean_cache()
def delete(self, using=None):
self._clean_cache()
super(MailFile, self).delete(using)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail file')
verbose_name_plural = _('Mail files')
|
class MailFile(models.Model):
def _clean_cache(self):
pass
def save(self, *args, **kwargs):
pass
def delete(self, using=None):
pass
def __str__(self):
pass
class Meta:
| 6 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 4 | 24 | 5 | 19 | 11 | 13 | 0 | 17 | 11 | 11 | 1 | 1 | 0 | 4 |
144,628 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailCategory
|
class MailCategory(models.Model):
name = models.CharField(_('Category'), max_length=25, unique=True)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail category')
verbose_name_plural = _('Mail categories')
|
class MailCategory(models.Model):
def __str__(self):
pass
class Meta:
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 11 | 2 | 9 | 8 | 6 | 0 | 9 | 8 | 6 | 1 | 1 | 0 | 1 |
144,629 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/views.py
|
LPgenerator_django-db-mailer.dbmail.views.SafariLogView
|
class SafariLogView(PostCSRFMixin):
def post(self, request, version):
err = json.loads(request.body)
signals.safari_error_log.send(self.__class__, instance=self, err=err)
return HttpResponse()
|
class SafariLogView(PostCSRFMixin):
def post(self, request, version):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 2 | 5 | 0 | 5 | 4 | 3 | 0 | 5 | 3 | 3 | 1 | 2 | 0 | 1 |
144,630 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/views.py
|
LPgenerator_django-db-mailer.dbmail.views.PushSubscriptionView
|
class PushSubscriptionView(View):
http_method_names = ['post', 'delete']
def _process(self, request, signal, **kwargs):
try:
kwargs.update(json.loads(request.body))
signal.send(self.__class__, instance=self, **kwargs)
return HttpResponse()
except ValueError:
return HttpResponseBadRequest()
def post(self, request, **kwargs):
return self._process(request, signals.push_subscribe, **kwargs)
def delete(self, request, **kwargs):
return self._process(request, signals.push_unsubscribe, **kwargs)
|
class PushSubscriptionView(View):
def _process(self, request, signal, **kwargs):
pass
def post(self, request, **kwargs):
pass
def delete(self, request, **kwargs):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 3 | 16 | 3 | 13 | 6 | 9 | 0 | 13 | 5 | 9 | 2 | 1 | 1 | 4 |
144,631 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/translation.py
|
LPgenerator_django-db-mailer.dbmail.translation.MailTemplateTranslationOptions
|
class MailTemplateTranslationOptions(TranslationOptions):
fields = ('subject', 'message',)
|
class MailTemplateTranslationOptions(TranslationOptions):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
144,632 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/translation.py
|
LPgenerator_django-db-mailer.dbmail.translation.MailBaseTemplateTranslationOptions
|
class MailBaseTemplateTranslationOptions(TranslationOptions):
fields = ('message',)
|
class MailBaseTemplateTranslationOptions(TranslationOptions):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
144,633 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/test_cases.py
|
LPgenerator_django-db-mailer.dbmail.test_cases.TemplateTestCase
|
class TemplateTestCase(TestCase):
def __create_template(self):
return MailTemplate.objects.create(
name="Site welcome template",
subject="Welcome",
message="Welcome to our site. We are glad to see you.",
slug="welcome",
is_html=False,
id=1,
)
def __retrieve_named_template_and_check_num_queries(self, num):
with self.assertNumQueries(num):
template = MailTemplate.get_template("welcome")
self.assertEqual(template.pk, 1)
return template
###########################################################################
def test_retrieve_named_template(self):
""" create template and check queries """
self.__create_template()
self.__retrieve_named_template_and_check_num_queries(3)
def test_retrieve_named_template_cached(self):
""" check num of queries for cached template """
self.test_retrieve_named_template()
self.__retrieve_named_template_and_check_num_queries(0)
def test_retrieve_named_template_with_cache_invalidation(self):
""" invalidate cached template """
self.test_retrieve_named_template_cached()
template = MailTemplate.get_template("welcome")
self.assertEquals(template.subject, "Welcome")
template.subject = "Hello"
template.save()
self.__retrieve_named_template_and_check_num_queries(3)
self.assertEquals(template.subject, "Hello")
def test_retrieve_named_template_with_cache_invalidation_cache(self):
""" check num of queries for cached template after invalidation """
self.test_retrieve_named_template_with_cache_invalidation()
template = self.__retrieve_named_template_and_check_num_queries(0)
self.assertEquals(template.subject, "Hello")
###########################################################################
def test_retrieve_bcc(self):
""" create template and check bcc """
self.__create_template()
template = self.__retrieve_named_template_and_check_num_queries(3)
self.assertEquals(template.bcc_list, [])
def test_retrieve_bcc_cached(self):
""" create template and bcc cache """
self.test_retrieve_bcc()
self.__retrieve_named_template_and_check_num_queries(0)
def test_retrieve_bcc_cached_invalidation(self):
""" invalidate cached bcc and add new bcc email """
self.test_retrieve_bcc_cached()
bcc = MailBcc.objects.create(email="root@local.host")
template = MailTemplate.get_template("welcome")
template.bcc_email.add(bcc)
template.save()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.bcc_list, ["root@local.host"])
def test_retrieve_bcc_cached_invalidation_cache(self):
""" check cached bcc with email """
self.test_retrieve_bcc_cached_invalidation()
with self.assertNumQueries(0):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.bcc_list, ["root@local.host"])
def test_retrieve_bcc_delete(self):
""" invalidate cached template when object was removed """
self.test_retrieve_bcc_cached_invalidation_cache()
for bcc in MailBcc.objects.all():
bcc.delete()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.bcc_list, [])
self.__retrieve_named_template_and_check_num_queries(0)
###########################################################################
def test_retrieve_from(self):
""" create template and check default email from """
self.__create_template()
template = self.__retrieve_named_template_and_check_num_queries(3)
self.assertEquals(template.from_email, None)
def test_retrieve_from_cached(self):
""" create template and check email from cache """
self.test_retrieve_from()
self.__retrieve_named_template_and_check_num_queries(0)
def test_retrieve_from_cached_invalidation(self):
""" invalidate cached from and add new email from """
self.test_retrieve_from_cached()
mail_from = MailFromEmail.objects.create(
name="root", email="r@loc.hs", pk=1)
template = MailTemplate.get_template("welcome")
template.from_email = mail_from
template.save()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(
template.from_email.get_mail_from, "root <r@loc.hs>")
def test_retrieve_from_cached_invalidation_cache(self):
""" check cached from with email """
self.test_retrieve_from_cached_invalidation()
with self.assertNumQueries(0):
template = MailTemplate.get_template("welcome")
self.assertEquals(
template.from_email.get_mail_from, "root <r@loc.hs>")
def test_retrieve_from_delete(self):
""" invalidate cached template when object was removed """
self.test_retrieve_from_cached_invalidation_cache()
mail_from = MailFromEmail.objects.get(pk=1)
mail_from.delete()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.from_email, None)
self.__retrieve_named_template_and_check_num_queries(0)
###########################################################################
def test_retrieve_file(self):
self.__create_template()
template = self.__retrieve_named_template_and_check_num_queries(3)
self.assertEquals(template.files_list, [])
def test_retrieve_file_cached(self):
self.test_retrieve_file()
self.__retrieve_named_template_and_check_num_queries(0)
def test_retrieve_file_cached_invalidation(self):
self.test_retrieve_file_cached()
attachment = MailFile.objects.create(
template_id=1, name="report.xls", filename="", pk=1)
attachment.save()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.files_list, [attachment])
def test_retrieve_file_cached_invalidation_cache(self):
self.test_retrieve_file_cached_invalidation()
with self.assertNumQueries(0):
template = MailTemplate.get_template("welcome")
self.assertEquals(len(template.files_list), 1)
def test_retrieve_file_delete(self):
self.test_retrieve_file_cached_invalidation_cache()
attachment = MailFile.objects.get(pk=1)
attachment.delete()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.files_list, [])
self.__retrieve_named_template_and_check_num_queries(0)
###########################################################################
def test_retrieve_auth(self):
self.__create_template()
template = self.__retrieve_named_template_and_check_num_queries(3)
self.assertEquals(template.auth_credentials, None)
def test_retrieve_auth_cached(self):
self.test_retrieve_auth()
self.__retrieve_named_template_and_check_num_queries(0)
def test_retrieve_auth_cached_invalidation(self):
self.test_retrieve_auth_cached()
credentials = MailFromEmailCredential.objects.create(
host="localhost", port=25, id=1)
credentials.save()
mail_from = MailFromEmail.objects.create(
name="root", email="r@loc.hs", credential=credentials)
template = MailTemplate.get_template("welcome")
template.from_email = mail_from
template.save()
with self.assertNumQueries(4):
template = MailTemplate.get_template("welcome")
self.assertEquals(len(template.auth_credentials), 6)
self.assertEquals(template.auth_credentials['port'], 25)
def test_retrieve_auth_cached_invalidation_cache(self):
self.test_retrieve_auth_cached_invalidation()
with self.assertNumQueries(0):
template = MailTemplate.get_template("welcome")
self.assertEquals(len(template.auth_credentials), 6)
self.assertEquals(template.auth_credentials['port'], 25)
def test_retrieve_auth_cached_invalidation_parent(self):
self.test_retrieve_auth_cached_invalidation_cache()
credentials = MailFromEmailCredential.objects.get(pk=1)
credentials.port = 587
credentials.save()
with self.assertNumQueries(4):
template = MailTemplate.get_template("welcome")
self.assertEquals(len(template.auth_credentials), 6)
self.assertEquals(template.auth_credentials['port'], 587)
def test_retrieve_auth_cached_invalidation_parent_cached(self):
self.test_retrieve_auth_cached_invalidation_parent()
with self.assertNumQueries(0):
template = MailTemplate.get_template("welcome")
self.assertEquals(len(template.auth_credentials), 6)
self.assertEquals(template.auth_credentials['port'], 587)
def test_retrieve_auth_cached_delete(self):
self.test_retrieve_auth_cached_invalidation_parent_cached()
credentials = MailFromEmailCredential.objects.get(pk=1)
credentials.delete()
with self.assertNumQueries(3):
template = MailTemplate.get_template("welcome")
self.assertEquals(template.auth_credentials, None)
self.assertEquals(template.from_email, None)
|
class TemplateTestCase(TestCase):
def __create_template(self):
pass
def __retrieve_named_template_and_check_num_queries(self, num):
pass
def test_retrieve_named_template(self):
''' create template and check queries '''
pass
def test_retrieve_named_template_cached(self):
''' check num of queries for cached template '''
pass
def test_retrieve_named_template_with_cache_invalidation(self):
''' invalidate cached template '''
pass
def test_retrieve_named_template_with_cache_invalidation_cache(self):
''' check num of queries for cached template after invalidation '''
pass
def test_retrieve_bcc(self):
''' create template and check bcc '''
pass
def test_retrieve_bcc_cached(self):
''' create template and bcc cache '''
pass
def test_retrieve_bcc_cached_invalidation(self):
''' invalidate cached bcc and add new bcc email '''
pass
def test_retrieve_bcc_cached_invalidation_cache(self):
''' check cached bcc with email '''
pass
def test_retrieve_bcc_delete(self):
''' invalidate cached template when object was removed '''
pass
def test_retrieve_from(self):
''' create template and check default email from '''
pass
def test_retrieve_from_cached(self):
''' create template and check email from cache '''
pass
def test_retrieve_from_cached_invalidation(self):
''' invalidate cached from and add new email from '''
pass
def test_retrieve_from_cached_invalidation_cache(self):
''' check cached from with email '''
pass
def test_retrieve_from_delete(self):
''' invalidate cached template when object was removed '''
pass
def test_retrieve_file(self):
pass
def test_retrieve_file_cached(self):
pass
def test_retrieve_file_cached_invalidation(self):
pass
def test_retrieve_file_cached_invalidation_cache(self):
pass
def test_retrieve_file_delete(self):
pass
def test_retrieve_auth(self):
pass
def test_retrieve_auth_cached(self):
pass
def test_retrieve_auth_cached_invalidation(self):
pass
def test_retrieve_auth_cached_invalidation_cache(self):
pass
def test_retrieve_auth_cached_invalidation_parent(self):
pass
def test_retrieve_auth_cached_invalidation_parent_cached(self):
pass
def test_retrieve_auth_cached_delete(self):
pass
| 29 | 14 | 8 | 1 | 6 | 1 | 1 | 0.11 | 1 | 5 | 5 | 0 | 28 | 0 | 28 | 28 | 253 | 62 | 172 | 60 | 143 | 19 | 159 | 60 | 130 | 2 | 1 | 1 | 29 |
144,634 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/signals.py
|
LPgenerator_django-db-mailer.dbmail.signals.SignalReceiver
|
class SignalReceiver(object):
def __init__(self, sender, **kwargs):
self.sender = sender
self.kwargs = kwargs
self._kwargs = kwargs.copy()
self.site = Site.objects.get_current()
self.instance = kwargs.get('instance')
self.pk = self.instance and self.instance.pk or None
self.signal = None
self.signal_pk = self.kwargs.pop('signal_pk', None)
self.kwargs['old_instance'] = self.get_old_instance()
self.kwargs['users'] = self.get_users()
self.kwargs['date'] = datetime.date.today()
self.kwargs['date_time'] = datetime.datetime.now()
def get_signal_list(self):
if not hasattr(self.sender._meta, 'module_name'):
return Signal.objects.filter(
model__model=self.sender._meta.model_name,
is_active=True
)
return Signal.objects.filter(
model__model=self.sender._meta.module_name,
is_active=True
)
def get_email_list(self):
if self.signal.group:
return self.signal.group.slug
email_list = Template(self.signal.rules).render(Context(self.kwargs))
self.kwargs.pop('users', None)
return email_list.strip().replace('\r', '').replace('\n', '')
def get_interval(self):
options = dict()
if self.signal.interval >= 0 and not self.signal_pk:
options['send_after'] = self.signal.interval
return options
@staticmethod
def get_users():
if ENABLE_USERS:
return User.objects.filter(
is_active=True, is_staff=False, is_superuser=False)
return []
def get_old_instance(self):
try:
instance = self.kwargs.get('instance')
if instance and instance.pk:
return self.sender.objects.get(
pk=self.kwargs['instance'].pk)
except ObjectDoesNotExist:
pass
def get_current_instance(self):
try:
if self.instance and self.instance.pk and self.signal.update_model:
obj = self.instance._default_manager.get(pk=self.instance.pk)
self.kwargs['current_instance'] = obj
except ObjectDoesNotExist:
pass
def send_mail(self):
from dbmail import send_db_mail
email_list = self.get_email_list()
if email_list and not self.signal.is_sent(self.pk):
for email in email_list.split(","):
email = email.strip()
if email:
send_db_mail(
self.signal.template.slug, email, self.site,
self.kwargs, self.instance, queue=SIGNALS_MAIL_QUEUE,
**self.get_interval()
)
self.signal.mark_as_sent(self.pk)
def _dispatch_deferred_task(self):
self._kwargs['signal_pk'] = self.signal.pk
if SIGNAL_DEFERRED_DISPATCHER == 'celery':
from dbmail import tasks
tasks.deferred_signal.apply_async(
args=[self.sender], kwargs=self._kwargs,
default_retry_delay=SEND_RETRY_DELAY,
max_retries=SEND_RETRY,
queue=SIGNALS_QUEUE,
countdown=self.signal.interval
)
else:
SignalDeferredDispatch.add_task(
args=[self.sender], kwargs=self._kwargs,
params=dict(
default_retry_delay=SEND_RETRY_DELAY,
max_retries=SEND_RETRY,
queue=SIGNALS_QUEUE
), interval=self.signal.interval
)
def _run(self):
if self.signal.interval:
self._dispatch_deferred_task()
else:
self.send_mail()
def run(self):
for self.signal in self.get_signal_list():
self._run()
def run_deferred(self):
try:
self.signal = Signal.objects.get(pk=self.signal_pk, is_active=True)
self.get_current_instance()
self.send_mail()
except ObjectDoesNotExist:
pass
|
class SignalReceiver(object):
def __init__(self, sender, **kwargs):
pass
def get_signal_list(self):
pass
def get_email_list(self):
pass
def get_interval(self):
pass
@staticmethod
def get_users():
pass
def get_old_instance(self):
pass
def get_current_instance(self):
pass
def send_mail(self):
pass
def _dispatch_deferred_task(self):
pass
def _run(self):
pass
def run(self):
pass
def run_deferred(self):
pass
| 14 | 0 | 9 | 1 | 9 | 0 | 2 | 0 | 1 | 5 | 2 | 0 | 11 | 8 | 12 | 12 | 121 | 17 | 104 | 30 | 88 | 0 | 76 | 29 | 61 | 4 | 1 | 3 | 27 |
144,635 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailBcc
|
class MailBcc(models.Model):
email = models.EmailField(_('Email'), unique=True)
is_active = models.BooleanField(_('Is active'), default=True)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
def __clean_cache(self):
MailTemplate.clean_cache(bcc_email=self)
def save(self, *args, **kwargs):
super(MailBcc, self).save(*args, **kwargs)
self.__clean_cache()
def delete(self, using=None):
self.__clean_cache()
super(MailBcc, self).delete(using)
def __str__(self):
return self.email
class Meta:
verbose_name = _('Mail Bcc')
verbose_name_plural = _('Mail Bcc')
|
class MailBcc(models.Model):
def __clean_cache(self):
pass
def save(self, *args, **kwargs):
pass
def delete(self, using=None):
pass
def __str__(self):
pass
class Meta:
| 6 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 4 | 23 | 5 | 18 | 12 | 12 | 0 | 18 | 12 | 12 | 1 | 1 | 0 | 4 |
144,636 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailSubscription
|
class MailSubscription(MailSubscriptionAbstract):
class Meta:
verbose_name = _('Mail Subscription')
verbose_name_plural = _('Mail Subscriptions')
def __str__(self):
if self.user:
return self.user.username
return self.address
|
class MailSubscription(MailSubscriptionAbstract):
class Meta:
def __str__(self):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 12 | 9 | 1 | 8 | 5 | 5 | 0 | 8 | 5 | 5 | 2 | 2 | 1 | 2 |
144,637 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.ApiKey
|
class ApiKey(models.Model):
name = models.CharField(_('Name'), max_length=25)
api_key = models.CharField(_('Api key'), max_length=32, unique=True)
is_active = models.BooleanField(_('Is active'), default=True)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
def _clean_cache(self):
cache.delete(self.api_key)
@classmethod
def clean_cache(cls):
for api in cls.objects.all():
api._clean_cache()
def save(self, *args, **kwargs):
super(ApiKey, self).save(*args, **kwargs)
self._clean_cache()
def delete(self, using=None):
self._clean_cache()
super(ApiKey, self).delete(using)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail API')
verbose_name_plural = _('Mail API')
|
class ApiKey(models.Model):
def _clean_cache(self):
pass
@classmethod
def clean_cache(cls):
pass
def save(self, *args, **kwargs):
pass
def delete(self, using=None):
pass
def __str__(self):
pass
class Meta:
| 8 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 5 | 5 | 29 | 6 | 23 | 16 | 15 | 0 | 22 | 15 | 15 | 2 | 1 | 1 | 6 |
144,638 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0015_auto_20180926_1206.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0015_auto_20180926_1206.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0014_auto_20170801_1206'),
]
operations = [
migrations.AlterField(
model_name='mailgroupemail',
name='email',
field=models.CharField(help_text='For sms/tts you must specify number', max_length=75, verbose_name='Email'),
),
migrations.AlterField(
model_name='maillog',
name='backend',
field=models.CharField(choices=[('bot', 'dbmail.backends.bot'), ('mail', 'dbmail.backends.mail'), ('push', 'dbmail.backends.push'), ('sms', 'dbmail.backends.sms'), ('tts', 'dbmail.backends.tts')], db_index=True, default='mail', editable=False, max_length=25, verbose_name='Backend'),
),
migrations.AlterField(
model_name='maillogemail',
name='mail_type',
field=models.CharField(choices=[('cc', 'CC'), ('bcc', 'BCC'), ('to', 'TO')], max_length=3, verbose_name='Mail type'),
),
migrations.AlterField(
model_name='mailsubscription',
name='data',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='mailsubscription',
name='end_hour',
field=models.CharField(default='23:59', max_length=5, verbose_name='End hour'),
),
migrations.AlterField(
model_name='mailsubscription',
name='start_hour',
field=models.CharField(default='00:00', max_length=5, verbose_name='Start hour'),
),
migrations.AlterField(
model_name='mailtemplate',
name='bcc_email',
field=models.ManyToManyField(blank=True, help_text='Blind carbon copy', to='dbmail.MailBcc', verbose_name='Bcc'),
),
migrations.AlterField(
model_name='mailtemplate',
name='category',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dbmail.MailCategory', verbose_name='Category'),
),
migrations.AlterField(
model_name='mailtemplate',
name='from_email',
field=models.ForeignKey(blank=True, default=None, help_text='If not specified, then used default.', null=True, on_delete=django.db.models.deletion.SET_NULL, to='dbmail.MailFromEmail', verbose_name='Message from'),
),
migrations.AlterField(
model_name='signal',
name='rules',
field=models.TextField(blank=True, default='{{ instance.email }}', help_text='Template should return email to send message. Example:{% if instance.is_active %}{{ instance.email }}{% endif %}.You can return a multiple emails separated by commas.', null=True, verbose_name='Rules'),
),
migrations.AlterField(
model_name='signal',
name='signal',
field=models.CharField(choices=[('pre_save', 'pre_save'), ('post_save', 'post_save'), ('pre_delete', 'pre_delete'), ('post_delete', 'post_delete'), ('m2m_changed', 'm2m_changed')], default='post_save', max_length=15, verbose_name='Signal'),
),
migrations.AlterField(
model_name='signal',
name='interval',
field=models.PositiveIntegerField(help_text='Specify interval to send messages after sometime. That very helpful for mailing on enterprise products.Interval must be set in the seconds.', verbose_name='Send interval', default=0),
),
migrations.AlterField(
model_name='mailtemplate',
name='interval',
field=models.PositiveIntegerField(help_text='\n Specify interval to send messages after sometime.\n Interval must be set in the seconds.\n ', verbose_name='Send interval', default=0),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 73 | 2 | 71 | 3 | 70 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,639 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0014_auto_20170801_1206.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0014_auto_20170801_1206.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0013_auto_20160923_2201'),
]
operations = [
migrations.AlterField(
model_name='maillog',
name='backend',
field=models.CharField(choices=SORTED_BACKEND_CHOICES, db_index=True, default=b'mail', editable=False, max_length=25, verbose_name='Backend'),
),
migrations.AlterField(
model_name='mailsubscription',
name='address',
field=models.CharField(db_index=True, help_text='Must be phone number/email/token', max_length=350, verbose_name='Address'),
),
migrations.AlterField(
model_name='mailsubscription',
name='backend',
field=models.CharField(choices=BACKENDS_MODEL_CHOICES, default=BACKEND.get('mail'), max_length=50, verbose_name='Backend'),
),
migrations.AlterField(
model_name='mailsubscription',
name='data',
field=SubscriptionDataField(blank=True, default=dict, null=True),
),
migrations.AlterField(
model_name='mailsubscription',
name='title',
field=models.CharField(blank=True, max_length=350, null=True),
),
migrations.AlterField(
model_name='mailtemplate',
name='category',
field=models.ForeignKey(blank=True, default=2, null=True, on_delete=django.db.models.deletion.CASCADE, to='dbmail.MailCategory', verbose_name='Category'),
),
migrations.AlterField(
model_name='mailtemplate',
name='from_email',
field=models.ForeignKey(blank=True, default=2, help_text='If not specified, then used default.', null=True, on_delete=django.db.models.deletion.SET_NULL, to='dbmail.MailFromEmail', verbose_name='Message from'),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 43 | 2 | 41 | 3 | 40 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,640 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0013_auto_20160923_2201.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0013_auto_20160923_2201.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0012_auto_20160915_1340'),
]
operations = [
migrations.AddField(
model_name='maillogexception',
name='ignore',
field=models.BooleanField(default=False, verbose_name='Ignore'),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,641 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0012_auto_20160915_1340.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0012_auto_20160915_1340.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0011_auto_20160803_1024'),
]
operations = [
migrations.AlterField(
model_name='maillogemail',
name='email',
field=models.CharField(max_length=350, verbose_name='Recipient'),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,642 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0011_auto_20160803_1024.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0011_auto_20160803_1024.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0010_auto_20160728_1645'),
]
operations = [
migrations.AlterField(
model_name='mailsubscription',
name='address',
field=models.CharField(help_text='Must be phone number/email/token', max_length=255, verbose_name='Address', db_index=True),
),
migrations.AlterField(
model_name='mailsubscription',
name='title',
field=models.CharField(max_length=255, null=True, blank=True),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 18 | 2 | 16 | 3 | 15 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,643 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0010_auto_20160728_1645.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0010_auto_20160728_1645.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0009_auto_20160311_0918'),
]
operations = [
migrations.AddField(
model_name='mailsubscription',
name='data',
field=models.TextField(null=True, blank=True),
),
migrations.AddField(
model_name='mailsubscription',
name='title',
field=models.CharField(max_length=100, null=True, blank=True),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 18 | 2 | 16 | 3 | 15 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,644 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/migrations/0009_auto_20160311_0918.py
|
LPgenerator_django-db-mailer.dbmail.migrations.0009_auto_20160311_0918.Migration
|
class Migration(migrations.Migration):
dependencies = [
('dbmail', '0008_auto_20151007_1918'),
]
operations = [
migrations.AlterField(
model_name='mailsubscription',
name='address',
field=models.CharField(help_text='Must be phone number/email/token', max_length=60, verbose_name='Address', db_index=True),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
144,645 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailSubscriptionAbstract
|
class MailSubscriptionAbstract(models.Model):
title = models.CharField(null=True, max_length=350, blank=True)
user = models.ForeignKey(
AUTH_USER_MODEL, verbose_name=_('User'), null=True, blank=True,
on_delete=models.CASCADE)
backend = models.CharField(
_('Backend'), choices=BACKENDS_MODEL_CHOICES, max_length=50,
default=BACKEND.get('mail'))
start_hour = models.CharField(
_('Start hour'), default='00:00', max_length=5)
end_hour = models.CharField(_('End hour'), default='23:59', max_length=5)
is_enabled = models.BooleanField(
_('Is enabled'), default=True, db_index=True)
is_checked = models.BooleanField(
_('Is checked'), default=False, db_index=True)
defer_at_allowed_hours = models.BooleanField(
_('Defer at allowed hours'), default=False)
address = models.CharField(
_('Address'), max_length=350, db_index=True,
help_text=_('Must be phone number/email/token'))
data = SubscriptionDataField(null=True, blank=True)
def send_confirmation_link(
self, slug='subs-confirmation', *args, **kwargs):
from dbmail import db_sender
kwargs['backend'] = self.backend
db_sender(slug, self.address, *args, **kwargs)
@staticmethod
def get_now():
d = timezone.now()
if d.tzinfo:
return timezone.localtime(timezone.now())
return d
@staticmethod
def get_current_hour():
current = MailSubscriptionAbstract.get_now()
return datetime.timedelta(hours=current.hour, minutes=current.minute)
@staticmethod
def convert_to_date(value):
hour, minute = value.split(':')
return datetime.timedelta(hours=int(hour), minutes=int(minute))
@classmethod
def mix_hour_with_date(cls, value):
return datetime.datetime.strptime(
cls.get_now().strftime('%Y-%m-%d ') + value, '%Y-%m-%d %H:%M')
@classmethod
def get_notification_list(cls, user_id, **kwargs):
kwargs.update({
'is_enabled': True,
'is_checked': True,
})
if user_id is not None:
kwargs.update({
'user_id': user_id,
})
return cls.objects.filter(**kwargs)
@classmethod
def notify(cls, slug, user_id=None, sub_filter=None, **kwargs):
from dbmail import db_sender
now_hour = cls.get_current_hour()
context_dict = kwargs.pop('context', {})
context_instance = kwargs.pop('context_instance', None)
sub_filter = sub_filter if isinstance(sub_filter, dict) else {}
for method_id in cls.get_notification_list(
user_id, **sub_filter).values_list('pk', flat=True):
method = cls.objects.get(pk=method_id)
method_kwargs = kwargs.copy()
method_kwargs['send_at_date'] = None
start_hour = cls.convert_to_date(method.start_hour)
end_hour = cls.convert_to_date(method.end_hour)
if not (start_hour <= now_hour <= end_hour):
if (method.defer_at_allowed_hours and
method_kwargs['use_celery']):
method_kwargs['send_at_date'] = cls.mix_hour_with_date(
method.start_hour)
else:
continue
method_kwargs['backend'] = method.backend
method_kwargs = method.update_notify_kwargs(**method_kwargs)
use_slug = method.get_final_slug(slug, method.get_short_type())
db_sender(use_slug, method.address, context_dict,
context_instance, **method_kwargs)
def update_notify_kwargs(self, **kwargs):
return kwargs
def get_final_slug(self, slug, _):
for extra_slug in self.get_extra_slugs(slug):
try:
if MailTemplate.get_template(slug=extra_slug):
slug = extra_slug
break
except MailTemplate.DoesNotExist:
pass
return slug
def get_extra_slugs(self, slug):
return [
u'{}-{}'.format(slug, self.get_short_type()),
]
def get_short_type(self):
return self.backend.split('.')[-1]
class Meta:
abstract = True
|
class MailSubscriptionAbstract(models.Model):
def send_confirmation_link(
self, slug='subs-confirmation', *args, **kwargs):
pass
@staticmethod
def get_now():
pass
@staticmethod
def get_current_hour():
pass
@staticmethod
def convert_to_date(value):
pass
@classmethod
def mix_hour_with_date(cls, value):
pass
@classmethod
def get_notification_list(cls, user_id, **kwargs):
pass
@classmethod
def notify(cls, slug, user_id=None, sub_filter=None, **kwargs):
pass
def update_notify_kwargs(self, **kwargs):
pass
def get_final_slug(self, slug, _):
pass
def get_extra_slugs(self, slug):
pass
def get_short_type(self):
pass
class Meta:
| 19 | 0 | 8 | 1 | 6 | 0 | 2 | 0 | 1 | 5 | 1 | 1 | 5 | 0 | 11 | 11 | 126 | 26 | 100 | 46 | 78 | 0 | 70 | 39 | 55 | 5 | 1 | 3 | 20 |
144,646 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.MailTemplate
|
class MailTemplate(models.Model):
name = models.CharField(_('Template name'), max_length=100, db_index=True)
subject = models.CharField(_('Subject'), max_length=100)
from_email = models.ForeignKey(
MailFromEmail, null=True, blank=True,
verbose_name=_('Message from'), default=DEFAULT_FROM_EMAIL,
help_text=_('If not specified, then used default.'),
on_delete=models.SET_NULL)
bcc_email = models.ManyToManyField(
MailBcc, verbose_name=_('Bcc'), blank=True,
help_text='Blind carbon copy')
message = HTMLField(_('Body'))
slug = models.SlugField(
_('Slug'), unique=True,
help_text=_('Unique slug to use in code.'))
num_of_retries = models.PositiveIntegerField(
_('Number of retries'), default=1)
priority = models.SmallIntegerField(
_('Priority'), default=DEFAULT_PRIORITY, choices=PRIORITY_STEPS)
is_html = models.BooleanField(
_('Is html'), default=True,
help_text=_('For sms/tts/push must be text not html'))
is_admin = models.BooleanField(_('For admin'), default=False)
is_active = models.BooleanField(_('Is active'), default=True)
enable_log = models.BooleanField(_('Logging enabled'), default=True)
category = models.ForeignKey(
MailCategory, null=True, blank=True,
verbose_name=_('Category'), default=DEFAULT_CATEGORY,
on_delete=models.CASCADE)
base = models.ForeignKey(
MailBaseTemplate, null=True, blank=True,
verbose_name=_('Basic template'), on_delete=models.CASCADE)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
context_note = models.TextField(
_('Context note'), null=True, blank=True,
help_text=_(
'This is simple note field for context variables with description.'
)
)
interval = models.PositiveIntegerField(
_('Send interval'), default=0,
help_text=_(
"""
Specify interval to send messages after sometime.
Interval must be set in the seconds.
"""
))
def _clean_cache(self):
cache.delete(self.slug, version=1)
@classmethod
def clean_cache(cls, **kwargs):
for template in cls.objects.filter(**kwargs):
template._clean_cache()
def _clean_non_html(self):
if not self.is_html:
self.message = strip_tags(self.message)
if hasattr(settings, 'MODELTRANSLATION_LANGUAGES'):
for lang in settings.MODELTRANSLATION_LANGUAGES:
message = strip_tags(getattr(self, 'message_%s' % lang))
if message:
setattr(self, 'message_%s' % lang, message)
def _premailer_transform(self):
if self.is_html:
self.message = premailer_transform(self.message)
@classmethod
def get_template(cls, slug):
obj = cache.get(slug, version=1)
if obj is not None:
return obj
obj = cls.objects.select_related('from_email', 'base').get(slug=slug)
bcc_list = [o.email for o in obj.bcc_email.filter(is_active=1)]
files_list = list(obj.files.all())
auth_credentials = obj.from_email and obj.from_email.get_auth()
obj.__dict__['bcc_list'] = bcc_list
obj.__dict__['files_list'] = files_list
obj.__dict__['auth_credentials'] = auth_credentials
cache.set(slug, obj, timeout=CACHE_TTL, version=1)
return obj
def save(self, *args, **kwargs):
self._premailer_transform()
self._clean_non_html()
self.slug = re.sub(r'[^0-9a-zA-Z._-]', '', self.slug)
super(MailTemplate, self).save(*args, **kwargs)
self._clean_cache()
def delete(self, using=None):
self._clean_cache()
super(MailTemplate, self).delete(using)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail template')
verbose_name_plural = _('Mail templates')
|
class MailTemplate(models.Model):
def _clean_cache(self):
pass
@classmethod
def clean_cache(cls, **kwargs):
pass
def _clean_non_html(self):
pass
def _premailer_transform(self):
pass
@classmethod
def get_template(cls, slug):
pass
def save(self, *args, **kwargs):
pass
def delete(self, using=None):
pass
def __str__(self):
pass
class Meta:
| 12 | 0 | 6 | 1 | 5 | 0 | 2 | 0 | 1 | 3 | 0 | 0 | 6 | 0 | 8 | 8 | 107 | 14 | 93 | 39 | 81 | 0 | 62 | 37 | 52 | 5 | 1 | 4 | 15 |
144,647 |
LPgenerator/django-db-mailer
|
LPgenerator_django-db-mailer/dbmail/models.py
|
LPgenerator_django-db-mailer.dbmail.models.Signal
|
class Signal(models.Model):
SIGNALS = (
'pre_save',
'post_save',
'pre_delete',
'post_delete',
'm2m_changed',
)
name = models.CharField(_('Name'), max_length=100)
model = models.ForeignKey(
'contenttypes.ContentType', verbose_name=_('Model'),
on_delete=models.CASCADE)
signal = models.CharField(
_('Signal'), choices=zip(SIGNALS, SIGNALS),
max_length=15, default='post_save')
template = models.ForeignKey(MailTemplate, verbose_name=_('Template'),
on_delete=models.CASCADE)
group = models.ForeignKey(
MailGroup, verbose_name=_('Email group'), blank=True, null=True,
help_text=_('You can use group email or rules for recipients.'),
on_delete=models.CASCADE)
rules = models.TextField(
help_text=_(
'Template should return email to send message. Example:'
'{% if instance.is_active %}{{ instance.email }}{% endif %}.'
'You can return a multiple emails separated by commas.'
), default='{{ instance.email }}', verbose_name=_('Rules'),
null=True, blank=True
)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True)
is_active = models.BooleanField(_('Is active'), default=True)
receive_once = models.BooleanField(
_('Receive once'), default=True,
help_text=_('Signal will be receive and send once for new db row.'))
interval = models.PositiveIntegerField(
_('Send interval'), default=0,
help_text=_(
'Specify interval to send messages after sometime. '
'That very helpful for mailing on enterprise products.'
'Interval must be set in the seconds.'
))
update_model = models.BooleanField(
_('Update model state'), default=False,
help_text=_(
"""
If you are using interval and want to update object state,
you can use this flag and refer to the variable
{{current_instance}}
"""))
def is_sent(self, pk):
if pk is not None:
if self.receive_once is True:
return SignalLog.objects.filter(
model=self.model, model_pk=pk, signal=self).exists()
return False
def mark_as_sent(self, pk):
if pk is not None:
SignalLog.objects.create(
model=self.model, model_pk=pk, signal=self
)
def __str__(self):
return self.name
class Meta:
verbose_name = _('Mail signal')
verbose_name_plural = _('Mail signals')
|
class Signal(models.Model):
def is_sent(self, pk):
pass
def mark_as_sent(self, pk):
pass
def __str__(self):
pass
class Meta:
| 5 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 3 | 70 | 4 | 66 | 20 | 61 | 0 | 27 | 20 | 22 | 3 | 1 | 2 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.