Best Python code snippet using avocado_python
options.py
Source:options.py
1#!/usr/bin/env python2from __future__ import print_function3import sys, os, re4from util import import_qt_modules5import_qt_modules (globals ())6from util import findColor, findIcon, use_new_api, use_new_qt, qstring_to_str, variant_to_str, setResizeMode7import util8from prop import ObjectBrowser9# --------------------------------------------------------------------------10class OptionsBox (QWidget) :11 def __init__ (self) :12 super (OptionsBox, self).__init__ ()13 self.tab_layout = QVBoxLayout ()14 self.setLayout (self.tab_layout)15 def addWidgetItem (self, widget) :16 self.tab_layout.addWidget (widget)17 def addLayoutItem (self, layout) :18 self.tab_layout.addLayout (layout)19# --------------------------------------------------------------------------20class OptionsLineEditBox (QHBoxLayout) :21 def __init__ (self, win, dlg, settings_id, title, default_value, file_dialog = False) :22 super (OptionsLineEditBox, self).__init__ ()23 self.win = win24 self.settings_id = settings_id25 self.label = QLabel ()26 self.label.setText (title)27 self.edit = QLineEdit ()28 self.addWidget (self.label)29 self.addWidget (self.edit)30 self.button = None31 if file_dialog :32 self.button = QPushButton ()33 self.button.setText ("...")34 self.addWidget (self.button)35 self.button.clicked.connect (self.buttonClick)36 # recall value37 value = self.win.settings.string (settings_id)38 if value == "" :39 value = default_value40 self.win.settings.setValue (settings_id, value) # write default value to .ini file41 self.edit.setText (value)42 dlg.accepted.connect (self.storeValue)43 def buttonClick (self) :44 value = str (QFileDialog.getOpenFileName ())45 if value != "" :46 self.edit.setText (value)47 def storeValue (self) :48 value = str (self.edit.text ())49 value = value.strip ()50 self.win.settings.setValue (self.settings_id, value)51# --------------------------------------------------------------------------52class OptionDialog (QDialog) :53 def __init__ (self, win) :54 super (OptionDialog, self).__init__ (win)55 self.win = win56 self.page_count = 057 self.current_tab = None58 "toolBar with buttons"59 self.toolBar = QToolBar ()60 self.toolBar.setOrientation (Qt.Vertical)61 "stackWidget for option pages"62 self.stackWidget = QStackedWidget ()63 "toolBar and stackWidget - central dialog area"64 self.hlayout = QHBoxLayout ()65 self.hlayout.addWidget (self.toolBar)66 self.hlayout.addWidget (self.stackWidget)67 self.buttonBox = QDialogButtonBox (QDialogButtonBox.Ok | QDialogButtonBox.Cancel)68 self.buttonBox.accepted.connect (self.accept)69 self.buttonBox.rejected.connect (self.reject)70 "ok and cancel at the bottom"71 self.vlayout = QVBoxLayout ()72 self.vlayout.addLayout (self.hlayout)73 self.vlayout.addWidget (self.buttonBox)74 self.setLayout (self.vlayout)75 def addPage (self, name, icon, widget, create_widget = None) :76 if isinstance (icon, str) :77 icon = findIcon (icon)78 if widget != None :79 self.stackWidget.addWidget (widget)80 button = QPushButton ()81 button.setText (name)82 if icon != None :83 button.setIcon (icon)84 button.setIconSize (QSize (24, 24))85 button.setMinimumSize (80, 80)86 button.widget = widget87 button.create_widget = create_widget88 button.clicked.connect (lambda param, self=self, button=button: self.openPage (button))89 self.toolBar.addWidget (button)90 def openPage (self, button) :91 if button.create_widget != None :92 if button.widget == None :93 button.widget = button.create_widget ()94 self.stackWidget.addWidget (button.widget)95 else :96 self.stackWidget.setCurrentWidget (button.widget) # show empty page97 self.show ()98 button.create_widget (button.widget)99 button.create_widget = None # do not call again100 self.stackWidget.setCurrentWidget (button.widget)101 def addSimplePage (self, name, icon) :102 box = OptionsBox ()103 box.win = self.win104 self.addPage (name, icon, box)105 self.current_page = None106 self.current_tab = box107 return box108 def addTabPage (self, name, icon) :109 page = QTabWidget ()110 self.addPage (name, icon, page)111 self.current_page = page112 self.current_tab = None113 return page114 def addTab (self, name) :115 box = OptionsBox ()116 box.win = self.win117 self.current_page.addTab (box, name)118 self.current_tab = box119 return box120 def addLineEdit (self, settings_id, title, default_value, file_dialog = False) :121 layout = OptionsLineEditBox (self.win, self, settings_id, title, default_value, file_dialog)122 self.current_tab.tab_layout.addLayout (layout)123# --------------------------------------------------------------------------124class Options (OptionDialog) :125 def __init__ (self, win) :126 super (Options, self).__init__ (win)127 self.setWindowTitle ("Options")128 self.examplePage1 ()129 self.examplePage2 ()130 def examplePage1 (self) :131 page = self.addTabPage ("edit", "edit-undo")132 tab1 = self.addTab ("first")133 edit = QLineEdit ()134 tab1.addWidgetItem (edit)135 checkBox = QCheckBox ()136 checkBox.setText ("something")137 tab1.addWidgetItem (checkBox)138 tab2 = self.addTab ("second")139 def examplePage2 (self) :140 page = self.addSimplePage ("other", "folder-new")141# --------------------------------------------------------------------------142class Notes (OptionDialog) :143 def __init__ (self, win) :144 super (Notes, self).__init__ (win)145 self.setWindowTitle ("Notes")146 self.buttonBox.setStandardButtons (QDialogButtonBox.Cancel)147 self.shortcutPage ()148 self.colorCachePage ()149 self.colorNamesPage ()150 self.iconCachePage ()151 self.pathPage ()152 self.modulePage ()153 self.toolIniPage ()154 self.iniPage ("view.ini", "clementine", self.win.settings)155 self.iniPage ("edit.ini", "tellico", self.win.session)156 # -----------------------------------------------------------------------157 def pathPage (self) :158 listView = QListWidget ()159 self.addPage ("sys path", "rosegarden", listView)160 for item in sys.path :161 listView.addItem (item)162 def modulePage (self) :163 listView = QListWidget ()164 self.addPage ("modules", "kdf", listView)165 # for item in self.win.loaded_modules :166 # listView.addItem (item)167 for item in sorted (sys.modules) :168 listView.addItem (item)169 listView.itemDoubleClicked.connect (self.showModule)170 listView.itemClicked.connect (self.alternativeShowModule)171 def showModule (self, item) :172 name = item.text ()173 ObjectBrowser (self.win, sys.modules [name])174 def alternativeShowModule (self, item) :175 mask = Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier176 mod = int (QApplication.keyboardModifiers () & mask)177 if mod == Qt.ControlModifier :178 # print ("CTRL CLICK")179 self.showModule (item)180 # -----------------------------------------------------------------------181 def resizeFirstColumn (self, treeView) :182 setResizeMode (treeView.header(), 0, QHeaderView.ResizeToContents)183 def resizeSecondColumn (self, treeView) :184 setResizeMode (treeView.header(), 1, QHeaderView.ResizeToContents)185 def colorCachePage (self) :186 treeView = QTreeWidget (self)187 treeView.setHeaderLabels (["Name", "Value"])188 self.resizeFirstColumn (treeView)189 self.addPage ("color cache", "color-management", treeView)190 for name in util.color_cache :191 self.displayColor (treeView, name, util.color_cache [name])192 treeView.sortByColumn (0, Qt.AscendingOrder)193 def colorNamesPage (self) :194 treeView = QTreeWidget (self)195 treeView.setHeaderLabels (["Name", "Value"])196 self.resizeFirstColumn (treeView)197 self.addPage ("color names", "gimp", treeView)198 for name in util.color_map :199 self.displayColor (treeView, name, util.color_map [name])200 treeView.sortByColumn (0, Qt.AscendingOrder)201 def displayColor (self, branch, name, color) :202 node = QTreeWidgetItem (branch)203 node.setText (0, name)204 node.setToolTip (0, name)205 if color.lightness () < 220 and color.alpha () != 0 :206 node.setForeground (0, color)207 node.setData (0, Qt.DecorationRole, color)208 node.setText (1, str (color.red ()) + ", " + str (color.green ())+ ", " + str (color.blue ()))209 # -----------------------------------------------------------------------210 def iconCachePage (self) :211 treeView = QTreeWidget (self)212 self.addPage ("icon cache", "choqok", treeView)213 for name in util.icon_cache :214 icon = util.icon_cache [name]215 self.displayIcon (treeView, name, icon)216 treeView.sortByColumn (0, Qt.AscendingOrder)217 def displayIcon (self, branch, name, icon) :218 node = QTreeWidgetItem (branch)219 node.setText (0, name)220 node.setToolTip (0, name)221 node.setIcon (0, icon)222 # -----------------------------------------------------------------------223 def iniPage (self, name, icon, ini) :224 treeView = QTreeWidget (self)225 treeView.setHeaderLabels (["Name", "Value"])226 self.resizeFirstColumn (treeView)227 self.addPage (name, icon, treeView)228 for group in ini.childGroups () :229 branch = QTreeWidgetItem (treeView)230 branch.setText (0, "[" + group + "]")231 branch.setIcon (0, findIcon ("folder"))232 ini.beginGroup (group)233 for key in ini.childKeys () :234 value = ini.value (key)235 item = QTreeWidgetItem (branch)236 item.setText (0, key)237 item.setText (1, variant_to_str (value))238 ini.endGroup ()239 # -----------------------------------------------------------------------240 def toolIniPage (self) :241 treeView = QTreeWidget (self)242 treeView.setHeaderLabels (["Name", "Value"])243 self.resizeFirstColumn (treeView)244 self.addPage ("tools.ini", "tools-wizard", treeView)245 ini = self.win.commands246 section = None247 start = ""248 for group in ini.childGroups () :249 m = re.match ("(\w\w*)-.*", group)250 if m :251 new_start = m.group (1)252 if new_start != start :253 start = new_start254 section = QTreeWidgetItem (treeView)255 section.setText (0, start);256 section.setIcon (0, findIcon ("folder-yellow"))257 branch = QTreeWidgetItem (section)258 else :259 start = ""260 section = None261 branch = QTreeWidgetItem (treeView)262 branch.setText (0, "[" + group + "]")263 branch.setIcon (0, findIcon ("folder"))264 ini.beginGroup (group)265 for key in ini.childKeys () :266 value = ini.value (key)267 item = QTreeWidgetItem (branch)268 item.setText (0, key)269 item.setText (1, variant_to_str (value))270 ini.endGroup ()271# --------------------------------------------------------------------------272 def shortcutPage (self) :273 treeView = QTreeWidget ()274 treeView.setHeaderLabels (["Name", "Shortcut", "Invisible"])275 self.name_column = 0276 self.key_column = 1277 self.invisible_column = 2278 self.resizeFirstColumn (treeView)279 self.resizeSecondColumn (treeView)280 header = treeView.header ()281 header.hideSection (self.invisible_column)282 # name_column = 0283 # header.setSectionResizeMode (name_column, QHeaderView.ResizeToContents)284 self.addPage ("shortcuts", "key-enter", treeView)285 for item in self.win.menuBar().actions() :286 self.displayMainMenuAction (treeView, item)287 prefix = "Menu " + item.text () + " / "288 for action in item.menu().actions() :289 self.displayAction (treeView, action, prefix)290 for action in self.win.actions() :291 self.showItem (branch, action)292 for item in self.win.children() :293 if isinstance (item, QShortcut) :294 self.displayShortcut (treeView, item)295 inx = treeView.topLevelItemCount () - 1296 while inx > 0 :297 item = treeView.topLevelItem (inx)298 if item.text (1) == "" :299 treeView.takeTopLevelItem (inx)300 inx = inx - 1301 self.setKeys (treeView)302 treeView.sortByColumn (self.invisible_column, Qt.AscendingOrder)303 def displayMainMenuAction (self, treeView, item) :304 node = QTreeWidgetItem (treeView)305 text = str (item.text ())306 node.setText (self.name_column, "Menu " +text)307 inx = text.find ('&')308 if inx >= 0 and inx+1 < len (text) :309 c = text [inx+1]310 node.setText (1, "Alt+" + c.upper ())311 icon = item.icon ()312 node.setIcon (self.name_column, icon)313 def displayAction (self, treeView, action, prefix = "") :314 for shortcut in action.shortcuts () :315 node = QTreeWidgetItem (treeView)316 node.setText (self.name_column, prefix + action.text())317 node.setIcon (self.name_column, action.icon ())318 node.setText (self.key_column, self.keySequenceToString (shortcut))319 def displayShortcut (self, treeView, shortcut) :320 node = QTreeWidgetItem (treeView)321 node.setText (self.name_column, shortcut.objectName ())322 node.setText (self.key_column, self.keySequenceToString (shortcut.key()))323 def keySequenceToString (self, shortcut) :324 text = shortcut.toString ()325 text = qstring_to_str (text)326 text = text.replace ("Meta+", "Win+")327 return text328 def setKeys (self, treeView) :329 cnt = treeView.topLevelItemCount ()330 for inx in range (cnt) :331 item = treeView.topLevelItem (inx)332 text = str (item.text (self.key_column))333 key = "T"334 if text == "" :335 key = "Z"336 if text.startswith ("Win+") :337 key = key + "W"338 text = text [4:]339 else :340 key = key + "Z"341 if text.startswith ("Alt+") :342 key = key + "A"343 text = text [4:]344 else :345 key = key + "Z"346 if text.startswith ("Ctrl+") :347 key = key + "C"348 text = text [5:]349 else :350 key = key + "Z"351 if text.startswith ("Shift+") :352 key = key + "S"353 text = text [6:]354 else :355 key = key + "Z"356 if text == "Left" :357 key = key + "a"358 elif text == "Right" :359 key = key + "b"360 elif text == "Up" :361 key = key + "c"362 elif text == "Down" :363 key = key + "d"364 elif text == "Ins" :365 key = key + "e"366 elif text == "Del" :367 key = key + "f"368 elif text == "Home" :369 key = key + "g"370 elif text == "End" :371 key = key + "h"372 elif text == "PgUp" :373 key = key + "i"374 elif text == "PgDown" :375 key = key + "j"376 elif text.startswith ("F") and len (text) > 1 :377 if len (text) == 2 :378 key = key + "l"379 else :380 key = key + "m"381 elif len (text) > 1 :382 key = key + "k" # before F1 and F10383 elif text >= "0" and text <= "9":384 key = key + "o"385 elif text >= "A" and text <= "Z":386 key = key + "p"387 else:388 key = key + "n" # before digits389 key = key + text390 item.setText (self.invisible_column, key)391# --------------------------------------------------------------------------...
vcf_to_matrix.py
Source:vcf_to_matrix.py
...7from unittest.mock import patch, Mock8import logging9logger = logging.getLogger(__name__)10logger.addHandler(logging.StreamHandler())11def variant_to_str(variant):12 return f"{variant.CHROM}:{variant.start + 1}-{variant.end + 1}"13def decide_missing_query(variant: vcf.model._Record, source_vcf_reader: vcf.Reader):14 """15 Sees if a given variant (reported as missing is the evaluation vcf) is present in a given source vcf, with a missing or HOM_REF gt.16 This also throws an error if the given variant is called in the source vcf.17 """18 looked_up_variants = list(source_vcf_reader.fetch(variant.CHROM, variant.start, variant.end - 1))19 if len(looked_up_variants) == 0:20 #set_truth_zero += 121 return 022 elif len(looked_up_variants) == 1:23 if looked_up_variants[0].samples[0].gt_type == 0:24 return 025 elif looked_up_variants[0].samples[0].gt_type is None:26 return 327 else:28 raise Exception(f"variant {variant_to_str(variant)}"29 f" is not genotyped in the evaluation vcf, but is in {source_vcf_reader.filename}")30 else:31 raise Exception(f"More than one variant found with position {variant_to_str(variant)} in {source_vcf_reader.filename}")32 # because we remove/merge multiallelics from truth33def get_dosage_matrix_entry(variants, truth_vcf, query_vcf):34 pass35def decide_missing_truth(truth_data: vcf.model._Call.data, variant: vcf.model._Record):36 if truth_data.GT ==".":37 return 338 elif truth_data.GT == "0/0":39 return 040 else:41 raise Exception(f"variant {variant_to_str(variant)} has no decision in truth, but is neither ./. nor 0/0")42def get_dosage_matrix(eval_vcf: str, truth_vcf: str, query_vcf: str) -> List[List[int]]:43 """44 Creates 4*4 matrix with the query vcf dosages as rows and truth vcf as columns (0 indexed).45 The last column and row also represents uncalled genotypes.46 NOTE: the eval vcf must be the result of `rtg vcfeval` using the output mode of ga4gh.47 """48 matrix = [[0]*4 for _ in range(4)]49 vcf_eval_dosage = 050 set_truth_zero = 051 many_reprs = 052 eval_vcf_reader = vcf.Reader(filename=eval_vcf)53 truth_vcf_reader = vcf.Reader(filename=truth_vcf)54 query_vcf_reader = vcf.Reader(filename=query_vcf)55 for variants in chunk_by(eval_vcf_reader, lambda x: x.INFO['BS'] if 'BS' in x.INFO.keys() else x.POS):56 def increment_matrix(truth_dosage, query_dosage):57 """58 Increments the result matrix.59 NOTE: `None` represents no genotype recorded60 """61 logger.debug(f"Setting truth={truth_dosage} query={query_dosage} for variants {list(map(variant_to_str, variants))}")62 if truth_dosage is None:63 truth_dosage = 364 if query_dosage is None:65 query_dosage = 366 # Matrix has rows of test dosages and columns of truth dosages67 matrix[query_dosage][truth_dosage] += 168 assert len(variants) != 069 if len(variants) == 1:70 variant = variants[0]71 truth = variant.genotype("TRUTH")72 truth_eval = truth.data.BD73 truth_dosage = truth.gt_type74 query = variant.genotype("QUERY")75 query_eval = query.data.BD76 query_dosage = query.gt_type77 if truth_eval is not None and query_eval is not None:78 vcf_eval_dosage += 179 increment_matrix(truth_dosage, query_dosage)80 elif truth_eval is None and query_eval is not None:81 increment_matrix(decide_missing_truth(truth.data, variant), query_dosage)82 elif truth_eval is not None and query_eval is None:83 increment_matrix(truth_dosage, decide_missing_query(variant, query_vcf_reader))84 else:85 increment_matrix(decide_missing_truth(truth.data, variant), decide_missing_query(variant, query_vcf_reader))86 elif len(variants) == 2:87 bds = list(map(88 lambda x: variants[x[0]].genotype(x[1]).data.BD,89 itertools.product((1, 0), ("TRUTH", "QUERY"))90 ))91 gt_types = list(map(92 lambda x: variants[x[0]].genotype(x[1]).gt_type,93 itertools.product((1, 0), ("TRUTH", "QUERY"))94 ))95 if not (96 (bds[0], bds[3]) == (None, None) and None not in (bds[1], bds[2]) or97 (bds[1], bds[2]) == (None, None) and None not in (bds[0], bds[3])98 ):99 #raise Exception(f"Invalid double variant record at {variant_to_str(variants[0])} and {variant_to_str(variants[1])}")100 logger.debug(f"Invalid double variant record at {variant_to_str(variants[0])} and {variant_to_str(variants[1])}") #nearby SNPs have the same BS as well101 truth_dosage = gt_types[0] if gt_types[2] is None else gt_types[2]102 query_dosage = gt_types[1] if gt_types[3] is None else gt_types[3]103 many_reprs += 1104 increment_matrix(truth_dosage, query_dosage)105 else:106 raise Exception(f"Many variants with the same postions. First one is at {variant_to_str(variants[0])}")107 print(f"vcf_eval_dosage: {vcf_eval_dosage}, set_truth_zero: {set_truth_zero}, many_reprs: {many_reprs}")108 return matrix109x = TypeVar("x")110def chunk_by(iterable: Iterable[x], predicate: Callable[[x], Any]) -> Iterable[List[x]]:111 iterator = iter(iterable)112 chunk = [next(iterator)]113 chunk_property = predicate(chunk[0])114 for entry in iterator:115 current_property = predicate(entry)116 if chunk_property == current_property:117 chunk.append(entry)118 else:119 yield chunk120 chunk = [entry]...
file_tree.py
Source:file_tree.py
1import sys2from PyQt5.QtCore import *3from PyQt5.QtGui import *4from PyQt5.QtWidgets import *5def variant_to_str (v) :6 if sys.version_info >= (3, 0) :7 return v8 else :9 v.toString ()10def bytes_to_str (data) :11 if sys.version_info >= (3, 0) :12 return str (data, "latin1")13 else:14 return str (data)15class Window (QMainWindow) :16 def __init__ (self, parent = None) :17 super (Window, self).__init__ (parent)18 self.tree = QTreeWidget ()19 self.tree.itemDoubleClicked.connect (self.itemClick)20 self.tab = QTabWidget ()21 splitter = QSplitter (self)22 splitter.addWidget (self.tree)23 splitter.addWidget (self.tab)24 self.setCentralWidget (splitter)25 self.displayDir (self.tree, "..")26 def displayDir (self, target, path) :27 localDir = QDir (path)28 directory = QDir (localDir.absolutePath ())29 item = QTreeWidgetItem (target)30 item.setText (0, directory.dirName ())31 item.setToolTip (0, directory.absolutePath ())32 item.setData (0, Qt.UserRole, directory.absolutePath ())33 item.setForeground (0, QColor ("red"))34 infoList = directory.entryInfoList (QDir.Files | QDir.Dirs |35 QDir.NoDotAndDotDot)36 for info in infoList :37 if info.isDir () :38 self.displayDir (item, info.filePath ())39 else :40 node = QTreeWidgetItem (item)41 node.setText (0, info.fileName ())42 node.setToolTip (0, info.filePath ())43 node.setData (0, Qt.UserRole, info.filePath ())44 node.setForeground (0, QColor ("blue"))45 def itemClick (self, item, column) :46 path = variant_to_str (item.data (0, Qt.UserRole))47 info = QFileInfo (path)48 ext = "." + info.completeSuffix ()49 widget = None50 if ext in [ ".h", ".cpp", ".py" ] :51 widget = QTextEdit ()52 f = QFile (path)53 if f.open (QFile.ReadOnly) :54 data = bytes_to_str (f.readAll ())55 widget.setText (data)56 if widget != None :57 self.tab.addTab (widget, info.fileName ())58if __name__ == "__main__" :59 app = QApplication (sys.argv)60 win = Window ()61 win.show ()...
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!!