Best Python code snippet using autotest_python
app.py
Source:app.py
1"""2This module contains the UI parts for the mg2tiledexr toolset3In Maya running this script without a selection will show all file nodes in4scene. If a selection is made, it will filter and show all file nodes in your5selection.6"""7from avalon.vendor.Qt import QtWidgets, QtCore, QtGui8import os9# Workaround to PyCharm not autocompleting, without mucking in Qt.py source.10# if False: from PyQt5 import QtWidgets, QtCore, QtGui11from . import mayalib12# reload(mayalib)13class CustomListModel(QtCore.QAbstractListModel):14 """15 Custom model for our listview that shows an icon and node name16 """17 def __init__(self, data, parent=None):18 super(CustomListModel, self).__init__(parent)19 self.items = data20 index = QtCore.QModelIndex()21 self.beginInsertRows(index, 0, len(data))22 for item in data:23 self.beginInsertRows(index, 0, 0)24 pass25 self.endInsertRows()26 self.icons = []27 app_path = os.path.dirname(os.path.realpath(__file__))28 self.icons.append(QtGui.QIcon(os.path.join(app_path, 'res/not_converted.png')))29 self.icons.append(QtGui.QIcon(os.path.join(app_path, 'res/source.png')))30 self.icons.append(QtGui.QIcon(os.path.join(app_path, 'res/exr.png')))31 # self.icons.append(QtGui.QIcon('res/not_converted.png'))32 # self.icons.append(QtGui.QIcon('res/source.png'))33 # self.icons.append(QtGui.QIcon('res/exr.png'))34 def rowCount(self, parent=None, *args, **kwargs):35 return len(self.items)36 def data(self, index, role=None):37 if not index.isValid() or not (38 0 <= index.row() < len(self.items)): return QtCore.QVariant()39 if role == QtCore.Qt.DisplayRole:40 return self.items[index.row()][1]41 elif role == QtCore.Qt.DecorationRole:42 return self.icons[self.items[index.row()][0]]43 elif role == QtCore.Qt.UserRole:44 return self.items[index.row()]45 # def addItems(self):46 # for key in self.modelDict:47 # index=QtCore.QModelIndex()48 # self.beginInsertRows(index, 0, 0)49 # self.items.append(key)50 # self.endInsertRows()51# class CustomList(QtWidgets.QListView):52# def __init__(self, parent=None):53# super(CustomList, self).__init__(parent)54class App(QtWidgets.QWidget):55 """Main application for tiled EXR conversion"""56 file_nodes = []57 def __init__(self, parent=None):58 #QtWidgets.QWidget.__init__(self, parent)59 super(App, self).__init__(parent)60 self.setObjectName("convertImg2TiledEXR")61 self.setWindowTitle("Image to tiled EXR converter")62 self.setWindowFlags(QtCore.Qt.Window)63 # self.setFixedSize(250, 500)64 self.resize(480, 800)65 self.setup_ui()66 self.setup_connections()67 self.postfix_value.setText("_tiled")68 self.preserve_filter_value.setText('NORMAL,NORMALS,GLOSS,BUMP,AO,OPACITY,DEPTH,ROUGHNESS')69 self.create_compression_options()70 self.create_linearcolor_options()71 self.populate_file_list()72 self.executable_filename.setText(mayalib.get_tiled_exr_exe_dir())73 def setup_ui(self):74 """Build the initial UI"""75 layout = QtWidgets.QVBoxLayout(self)76 # region executable77 executable_grp = QtWidgets.QGroupBox("Executable")78 executable_vlayout = QtWidgets.QVBoxLayout()79 executable_hlayout = QtWidgets.QHBoxLayout()80 executable_filename = QtWidgets.QLineEdit()81 executable_button = QtWidgets.QPushButton()82 executable_button.setIcon(self.style().standardIcon(83 getattr(QtWidgets.QStyle, 'SP_DialogOpenButton')))84 executable_hlayout.addWidget(executable_filename)85 executable_hlayout.addWidget(executable_button)86 executable_vlayout.addLayout(executable_hlayout)87 executable_grp.setLayout(executable_vlayout)88 # endregion executable89 # region options90 options_grp = QtWidgets.QGroupBox("Options")91 options_vlayout = QtWidgets.QVBoxLayout()92 postfix_hlayout = QtWidgets.QHBoxLayout()93 postfix_label = QtWidgets.QLabel("Postfix")94 postfix_value = QtWidgets.QLineEdit()95 postfix_hlayout.addWidget(postfix_label)96 postfix_hlayout.addWidget(postfix_value)97 compression_hlayout = QtWidgets.QHBoxLayout()98 compression_label = QtWidgets.QLabel("Compression")99 compression_value = QtWidgets.QComboBox()100 compression_hlayout.addWidget(compression_label)101 compression_hlayout.addWidget(compression_value)102 linear_hlayout = QtWidgets.QHBoxLayout()103 linear_label = QtWidgets.QLabel("Linear Conversion")104 linear_value = QtWidgets.QComboBox()105 linear_hlayout.addWidget(linear_label)106 linear_hlayout.addWidget(linear_value)107 tilesize_hlayout = QtWidgets.QHBoxLayout()108 tilesize_label = QtWidgets.QLabel("Tile Size")109 tilesize_value = QtWidgets.QSpinBox()110 tilesize_value.setValue(64)111 tilesize_hlayout.addWidget(tilesize_label)112 tilesize_hlayout.addWidget(tilesize_value)113 overwrite_hlayout = QtWidgets.QHBoxLayout()114 overwrite_label = QtWidgets.QLabel("Overwrite")115 overwrite_value = QtWidgets.QCheckBox()116 overwrite_value.setChecked(False)117 overwrite_hlayout.addWidget(overwrite_label)118 overwrite_hlayout.addWidget(overwrite_value)119 preserve_hlayout = QtWidgets.QHBoxLayout()120 preserve_label = QtWidgets.QLabel("Preserve Color Space ")121 preserve_value = QtWidgets.QCheckBox()122 preserve_value.setChecked(True)123 preserve_hlayout.addWidget(preserve_label)124 preserve_hlayout.addWidget(preserve_value)125 126 preserve_filter_hlayout = QtWidgets.QHBoxLayout()127 preserve_filter_label = QtWidgets.QLabel("Preserver Filter")128 preserve_filter_value = QtWidgets.QLineEdit()129 preserve_filter_hlayout.addWidget(preserve_filter_label)130 preserve_filter_hlayout.addWidget(preserve_filter_value)131 options_vlayout.addLayout(postfix_hlayout)132 options_vlayout.addLayout(compression_hlayout)133 options_vlayout.addLayout(linear_hlayout)134 options_vlayout.addLayout(tilesize_hlayout)135 options_vlayout.addLayout(overwrite_hlayout)136 options_vlayout.addLayout(preserve_hlayout)137 options_vlayout.addLayout(preserve_filter_hlayout)138 options_grp.setLayout(options_vlayout)139 # endregion options140 # Group box for type of machine list141 list_type_grp = QtWidgets.QGroupBox("File Texture Nodes")142 list_type_hlayout = QtWidgets.QVBoxLayout()143 refresh_button = QtWidgets.QPushButton("Refresh")144 refresh_button.setToolTip("Refresh texture lists")145 refresh_button.setIcon(self.style().standardIcon(146 getattr(QtWidgets.QStyle, 'SP_BrowserReload')))147 # region file node list148 file_node_hlayout = QtWidgets.QVBoxLayout()149 file_node_hlayout.setSpacing(2)150 file_node_list = QtWidgets.QListView()151 file_node_list.setAlternatingRowColors(True)152 file_node_list.setSelectionBehavior(153 QtWidgets.QAbstractItemView.SelectRows)154 file_node_list.setSelectionMode(155 QtWidgets.QAbstractItemView.MultiSelection)156 # endregion157 # conversion buttons158 button_vlayout = QtWidgets.QHBoxLayout()159 button_vlayout.setAlignment(QtCore.Qt.AlignCenter)160 button_vlayout.setSpacing(4)161 convert_button = QtWidgets.QPushButton("Convert")162 exr_button = QtWidgets.QPushButton("Show EXR")163 source_button = QtWidgets.QPushButton("Show Source")164 set_source_button = QtWidgets.QPushButton("Set new source")165 set_source_button.setDisabled(True)166 button_vlayout.addWidget(convert_button)167 button_vlayout.addWidget(exr_button)168 button_vlayout.addWidget(source_button)169 button_vlayout.addWidget(set_source_button)170 file_node_hlayout.addWidget(file_node_list)171 file_node_hlayout.addLayout(button_vlayout)172 list_type_hlayout.addWidget(refresh_button)173 list_type_hlayout.addLayout(file_node_hlayout)174 list_type_grp.setLayout(list_type_hlayout)175 layout.addWidget(executable_grp)176 layout.addWidget(options_grp)177 layout.addWidget(list_type_grp)178 layout.addLayout(file_node_hlayout)179 # Enable access for all methods180 self.file_node_list = file_node_list181 self.postfix_value = postfix_value182 self.compression_value = compression_value183 self.linear_value = linear_value184 self.tilesize_value = tilesize_value185 self.executable_filename = executable_filename186 self.exr_button = exr_button187 self.source_button = source_button188 self.convert_button = convert_button189 self.refresh_button = refresh_button190 self.overwritevalue = overwrite_value191 self.preserve_value = preserve_value192 self.preserve_filter_value = preserve_filter_value193 self.setLayout(layout)194 def setup_connections(self):195 self.refresh_button.clicked.connect(self.refresh)196 self.exr_button.clicked.connect(self.show_exr)197 self.source_button.clicked.connect(self.show_source)198 self.convert_button.clicked.connect(self.convert)199 def create_compression_options(self):200 compressions = ['none', 'rle', 'zip', 'zips', 'piz', 'pxr24', 'b44',201 'b44a', 'dwaa', 'dwab']202 for compression in compressions:203 self.compression_value.addItem(compression)204 self.compression_value.setCurrentIndex(3)205 def create_linearcolor_options(self):206 choices = ['auto', 'on', 'off']207 for choise in choices:208 self.linear_value.addItem(choise)209 self.linear_value.setCurrentIndex(2)210 def populate_file_list(self):211 self.file_nodes = mayalib.get_file_texture_model_data()212 self.file_node_list.reset()213 table_model = CustomListModel(self.file_nodes)214 self.file_node_list.setModel(table_model)215 def refresh(self):216 # self.create_compression_options()217 # self.create_linearcolor_options()218 print('refreshing')219 self.populate_file_list()220 def show_exr(self):221 self.show_source(False)222 def show_source(self, source=True):223 indices = self.file_node_list.selectedIndexes()224 nodes = []225 indices = self.file_node_list.selectedIndexes()226 for id in indices:227 nodes.append(self.file_node_list.model().index(id.row()).data(role=QtCore.Qt.UserRole))228 mayalib.revert_nodes(nodes, self.postfix_value.text(), source, self.preserve_value.isChecked(), self.preserve_filter_value.text())229 self.refresh()230 # for index in indices:231 # self.file_node_list.selectionModel().select(index,232 # QtCore.QItemSelectionModel.Select)233 def convert(self):234 nodes = []235 indices = self.file_node_list.selectedIndexes()236 for id in indices:237 nodes.append(self.file_node_list.model().index(id.row()).data(role=QtCore.Qt.UserRole))238 self.convert_button.setDisabled(True)239 self.source_button.setDisabled(True)240 self.exr_button.setDisabled(True)241 #self.set_source_button.setDisabled(True)242 try:243 mayalib.convert_files(self.executable_filename.text(), nodes,244 preserve = self.preserve_value.isChecked(),245 threads=8,246 overwrite=self.overwritevalue.isChecked(),247 compression=self.compression_value.currentText(),248 linear=self.linear_value.currentText(),249 postfix=self.postfix_value.text(),250 tile_size=self.tilesize_value.value(),251 preserver_filter=self.preserve_filter_value.text())252 except Exception as e:253 raise e254 finally:255 self.convert_button.setDisabled(False)256 self.source_button.setDisabled(False)257 self.exr_button.setDisabled(False)258 self.refresh()259def launch():260 global application261 toplevel_widgets = QtWidgets.QApplication.topLevelWidgets()262 mainwindow = next(widget for widget in toplevel_widgets if263 widget.objectName() == "MayaWindow")264 application = App(parent=mainwindow)265 application.show()266if __name__ == '__main__':267 import sys268 app = QtWidgets.QApplication(sys.argv)269 test = App()270 test.show()...
yaml.py
Source:yaml.py
1import os2import yaml3class YamlParser:4 def __init__(self, file_path, delimiter='=', comment_prefix='#', preserve_value=None):5 self.file_path = file_path6 self.delimiter = delimiter7 self.comment_prefix = comment_prefix8 self.preserve_value = preserve_value9 self.data = {}10 self.dirty = False11 self.changes = []12 if os.path.exists(file_path):13 self.read()14 def read(self):15 with open(self.file_path, mode='r', encoding='utf-8') as config_file:16 self.data = yaml.safe_load(config_file)17 def get_data(self):18 if not self.data:19 self.read()20 return self.data21 def set_key(self, attributes, value):22 parents, key = attributes23 if not value:24 return25 keys = parents.split('.')26 child = self.data27 found = True28 while keys and found:29 found = False30 k = keys.pop(0)31 if isinstance(child, dict):32 child = child[k]33 found = True34 elif isinstance(child, list):35 for c in child:36 if isinstance(c, dict) and k in c:37 child = c[k]38 found = True39 if not found:40 print('Entry not found')41 return42 if isinstance(child, dict):43 old_value = child[key]44 if old_value != self.preserve_value or self.preserve_value is None:45 if old_value != value:46 self.dirty = True47 child[key] = value48 self.changes.append((old_value, value))49 elif isinstance(child, list):50 for entry in child:51 if key in entry and isinstance(entry, dict):52 old_value = entry[key]53 if old_value != self.preserve_value or self.preserve_value is None:54 if old_value != value:55 self.dirty = True56 entry[key] = value57 self.changes.append((old_value, value))58 def get_key(self, attributes):59 parents, key = attributes60 keys = parents.split('.')61 child = self.data62 found = True63 while keys and found:64 found = False65 k = keys.pop(0)66 if isinstance(child, dict):67 child = child[k]68 found = True69 elif isinstance(child, list):70 for c in child:71 if isinstance(c, dict) and k in c:72 child = c[k]73 found = True74 if not found:75 print('Entry not found')76 return77 if isinstance(child, dict):78 old_value = child[key]79 if old_value != self.preserve_value or self.preserve_value is None:80 return child[key]81 elif isinstance(child, list):82 for entry in child:83 if key in entry and isinstance(entry, dict):84 old_value = entry[key]85 if old_value != self.preserve_value or self.preserve_value is None:86 return entry[key]87 def dry_run(self):88 print(f'Modifications to be applied in {self.file_path}:')89 if self.dirty:90 for old, new in self.changes:91 print(f' {old} -> {new}')92 else:93 print(' no modification to apply')94 def write(self, overrides=None):95 if self.dirty:96 with open(self.file_path, mode='w') as config_file:97 yaml.dump(self.data, config_file, version=(1, 1), explicit_start=True)98 def write_to(self, output):99 with open(output, mode='w') as config_file:100 yaml.dump(self.data, config_file, version=(1, 1), explicit_start=True)101if __name__ == '__main__':102 import json103 fp = '../config-files/suricata.yaml'104 kv = YamlParser(fp, preserve_value='default')105 kv.read()106 # print(json.dumps(kv.get_data(), indent=2, sort_keys=True))107 kv.set_key(('af-packet', 'interface'), 'wlan0')108 print(json.dumps(kv.get_data(), indent=2, sort_keys=True))109 # print(kv.get_data())110 kv.dry_run()...
ini.py
Source:ini.py
1import os.path2from configparser import ConfigParser3class IniParser:4 def __init__(self, file_path, delimiter='=', comment_prefix='#', preserve_value=None):5 self.file_path = file_path6 self.delimiter = delimiter7 self.comment_prefix = comment_prefix8 self.preserve_value = preserve_value9 self.data = ConfigParser()10 self.changes = []11 if os.path.exists(file_path):12 self.read()13 def read(self):14 self.data.read(self.file_path)15 def get_data(self):16 if not self.data.sections():17 self.read()18 tmp = {}19 for s, e in self.data.items():20 for k, v in e.items():21 tmp[f'{s}>{k}'] = v22 return tmp23 def set_key(self, attributes, value):24 section = attributes.split('>')[0]25 key = attributes.split('>')[1]26 if value:27 if section not in self.data:28 self.data[section] = {}29 old_value = self.data.get(section, key, fallback=None)30 if old_value != self.preserve_value or self.preserve_value is None:31 self.data[section][key] = value32 self.changes.append((old_value, value))33 def dry_run(self):34 print(f'Modifications to be applied in {self.file_path}:')35 for old, new in self.changes:36 print(f' {old} -> {new}')37 def write(self, overrides=None):38 with open(self.file_path, 'w') as configuration_file:39 self.data.write(configuration_file)40if __name__ == '__main__':41 fp = '../config-files/pirogue.conf'42 kv = IniParser(fp)43 kv.read()44 print(kv.get_data())45 # kv.set_key(('security', 'admin_password'), 'PiRogue34')46 kv.dry_run()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!