Best Python code snippet using pytest
def_procedures.py
Source:def_procedures.py
1import subprocess2import pathlib3from pathlib import Path4import sys5import os, shutil6import tkinter as tk7from tkinter import messagebox8import tkinterGUI9import config_sessions10import def_functions11import def_queryfunctions12from config_paths import *13#14def SetPathsFirst(varget):15 global checkexist_otherfunc, checkSetPathsFirst16 try:17 tmp=checkexist_otherfunc18 except NameError:19 checkexist_otherfunc=False20 if not checkexist_otherfunc:21 checkexist_otherfunc = True22 while True:23 try:24 tmp=checkSetPathsFirst25 except NameError:26 checkSetPathsFirst=False27 else:28 if checkSetPathsFirst:29 break30 else:31 pathflag = 032 while True:33 flag = 034 checkSetPathsFirst=True35 if varget == 'EN':36 titletext = 'ANSA/META executable file selection'37 labeltext = "\n Enter full paths: \t\t\t\t\t\t\t\n"38 if varget == 'ZH':39 titletext = 'ANSA / METAå¯æ§è¡æ件éæ©'40 labeltext = "\n è¾å
¥å®æ´è·¯å¾: \t\t\t\t\t\t\t\n" 41 42 entrytext = ['ANSA', 'META']43 tkinterGUI.MainApplication.TopLevelWindow_MultiEntry(titletext, labeltext, entrytext)44 contSingle = tkinterGUI.MainApplication.check2cont45 if contSingle == None:46 break47 fieldValues = tkinterGUI.MainApplication.EntryValues48 textall=""49 if varget == 'EN':50 pathtext="You selected the following paths:"51 if varget == 'ZH':52 pathtext="æ¨éæ©äºä»¥ä¸è·¯å¾ï¼"53 if fieldValues==[None]*2:54 break55 else:56 if len(fieldValues[0])!=0:57 if Path(fieldValues[0]).exists()==False:58 if varget == 'EN':59 textall = textall + "invalid path for ANSA" + "\n"60 if varget == 'ZH':61 textall = textall + "ANSAçæ æè·¯å¾" + "\n"62 flag = 163 else:64 AnsaExePath = Path(fieldValues[0])65 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'AnsaExePath', 'to', '\n', fieldValues[0])66 pathtext = pathtext + str(AnsaExePath) + "\n"67 pathflag=168 if len(fieldValues[1])!=0:69 if Path(fieldValues[1]).exists()==False:70 if varget == 'EN':71 textall = textall + "invalid path for META" + "\n"72 if varget == 'ZH':73 textall = textall + "META Postçæ æè·¯å¾" + "\n"74 flag = 175 else:76 MetaExePath = Path(fieldValues[1])77 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'MetaExePath', 'to', '\n', fieldValues[1])78 pathtext = pathtext + str(MetaExePath) + "\n"79 pathflag=180 if flag == 1:81 if varget == 'EN':82 textall=textall+"\nDo you want to continue?"83 cont = tk.messagebox.askyesno("Warning",textall)84 if varget == 'ZH':85 textall=textall+"\nä½ æ³ç»§ç»åï¼"86 cont = tk.messagebox.askyesno("è¦å",textall) 87 if cont:88 checkSetPathsFirst=False89 continue90 else:91 break92 if pathflag==1:93 if varget == 'EN':94 tk.messagebox.showwarning("Information", pathtext)95 if varget == 'ZH':96 tk.messagebox.showwarning("ä¿¡æ¯", pathtext)97 else:98 if varget == 'EN':99 tk.messagebox.showwarning("Information", "No Paths are re-assigned")100 if varget == 'ZH':101 tk.messagebox.showwarning("ä¿¡æ¯", "没æè·¯å¾è¢«éæ°åé
")102 break103 checkSetPathsFirst=False104 checkexist_otherfunc = False105def CreateDeckInfo_Mass(varget):106 global checkexist_otherfunc, checkCreateDeckInfo_Mass107 try:108 tmp=checkexist_otherfunc109 except NameError:110 checkexist_otherfunc=False111 if not checkexist_otherfunc:112 checkexist_otherfunc = True113 while True:114 try:115 tmp=checkCreateDeckInfo_Mass116 except NameError:117 checkCreateDeckInfo_Mass=False118 else:119 if checkCreateDeckInfo_Mass:120 break121 else: 122 checkANSAexist = True123 AnsaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'AnsaExePath', 'to'))124 if AnsaExePath.exists()==False:125 def_functions.ModifyExecutablePathsFile()126 AnsaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'AnsaExePath', 'to'))127 if AnsaExePath.exists()==False:128 checkANSAexist = False129 if varget == 'EN':130 text="Please select your ANSA executable path"131 warningtext = "ANSA executable path is invalid! \nPlease set a correct path to proceed."132 abort = tk.messagebox.askquestion ("Warning", warningtext)133 if varget == 'ZH':134 text="请éæ©æ¨çANSAå¯æ§è¡æ件路å¾"135 warningtext = "ANSAå¯æ§è¡æ件路å¾æ æï¼\n请设置æ£ç¡®çè·¯å¾ä»¥ç»§ç»ã"136 abort = tk.messagebox.askquestion ("è¦å", warningtext)137 if abort == 'yes':138 filetypestr = (("bat files","*.bat"),) 139 AnsaExePathtmp = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)140 else:141 break142 if not AnsaExePathtmp:143 if varget == 'EN':144 tk.messagebox.showerror ("Warning", warningtext)145 if varget == 'ZH':146 tk.messagebox.showerror("è¦å", warningtext)147 break148 else:149 while True:150 filename_with_path, file_extension = os.path.splitext(AnsaExePathtmp) # /a/b/x y151 filepath, filename_with_extension = os.path.split(AnsaExePathtmp) # /a/b/ x.y152 if file_extension=='.bat':153 AnsaExePath = Path(AnsaExePathtmp)154 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'AnsaExePath', 'to', '\n', AnsaExePathtmp)155 checkANSAexist = True156 break157 else:158 if varget == 'EN':159 tk.messagebox.showwarning("Warning", "Please select an appropriate ANSA batch file")160 if varget == 'ZH':161 tk.messagebox.showwarning("è¦å", "请éæ©éå½çANSAæ¹å¤çæ件")162 filetypestr = (("bat files","*.bat"),) 163 AnsaExePathtmp = def_queryfunctions.PathQuery(text,AnsaExePathtmp, filetypestr, varget)164 if not AnsaExePathtmp:165 if varget == 'EN':166 tk.messagebox.showwarning("Warning", warningtext)167 if varget == 'ZH':168 tk.messagebox.showwarning("è¦å", warningtext)169 break170 if checkANSAexist:171 AnsaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'AnsaExePath', 'to'))172 checkCreateDeckInfo_Mass=True173 while True:174 if varget == 'EN':175 text="Select the ANSA model to create Deck Info"176 if varget == 'ZH':177 text="éæ©ANSA模å以å建Deck Info"178 filetypestr = (("key files","*.key"),("k files","*.k"),("dyn files","*.dyn"),("ANSA files","*.ansa"))179 File2Open = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)180 if File2Open:181 filename_with_path, file_extension = os.path.splitext(File2Open) # /a/b/x y182 if file_extension=='.key' or file_extension=='.k' or file_extension=='.ansa': 183 try:184 workingdir, filename_with_extension = os.path.split(File2Open) # /a/b/ x.y185 stringexec = r'-exec "load_script: '186 AnsaExeStatement = stringexec + "'" + str(AnsaDeckInfoScriptFilePath) + "'" + '" -exec "main(\"'+str(File2Open)+"\",\""+str(File2Open)+"\",\""+str(File2Open)+'\")"'187 def_functions.OpenANSA(AnsaExePath,AnsaExeStatement, workingdir)188 except OSError:189 if varget == 'EN':190 tk.messagebox.showwarning("Warning", "Errors encountered")191 if varget == 'ZH':192 tk.messagebox.showwarning("è¦å", "ä¸æ¯ææçMETA Postå¯æ§è¡è·¯å¾ï¼è¯·é¦å
å®ä¹ææè·¯å¾")193 break194 break195 else:196 if varget == 'EN':197 tk.messagebox.showwarning("Warning", "d3plot file must be selected!")198 if varget == 'ZH':199 tk.messagebox.showwarning("è¦å", "å¿
é¡»éæ©d3plotæ件ï¼")200 else:201 break202 break 203 else:204 break205 checkCreateDeckInfo_Mass = False206 checkexist_otherfunc = False207 return True208def CompareModelsFirst(varget):209 global checkexist_otherfunc, checkCompareModelsFirst210 try:211 tmp=checkexist_otherfunc212 except NameError:213 checkexist_otherfunc=False214 if not checkexist_otherfunc:215 checkexist_otherfunc = True216 while True:217 try:218 tmp=checkCompareModelsFirst219 except NameError:220 checkCompareModelsFirst=False221 else:222 if checkCompareModelsFirst:223 break224 else:225 AnsaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'AnsaExePath', 'to'))226 checkANSAexist = True227 if AnsaExePath.exists()==False:228 def_functions.ModifyExecutablePathsFile()229 AnsaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'AnsaExePath', 'to'))230 if AnsaExePath.exists()==False:231 checkANSAexist = False232 if varget == 'EN':233 text="Please select your ANSA executable path"234 warningtext = "ANSA executable path is invalid! \nPlease set a correct path to proceed."235 abort = tk.messagebox.askquestion ("Warning", warningtext)236 if varget == 'ZH':237 text="请éæ©æ¨çANSAå¯æ§è¡æ件路å¾"238 warningtext = "ANSAå¯æ§è¡æ件路å¾æ æï¼\n请设置æ£ç¡®çè·¯å¾ä»¥ç»§ç»ã"239 abort = tk.messagebox.askquestion ("è¦å", warningtext)240 if abort == 'yes':241 filetypestr = (("bat files","*.bat"),)242 AnsaExePathtmp = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)243 else:244 break245 if not AnsaExePathtmp:246 if varget == 'EN':247 tk.messagebox.showerror("Warning", warningtext)248 if varget == 'ZH':249 tk.messagebox.showerror("è¦å", warningtext)250 else:251 while True:252 filename_with_path, file_extension = os.path.splitext(AnsaExePathtmp) # /a/b/x y253 filepath, filename_with_extension = os.path.split(AnsaExePathtmp) # /a/b/ x.y254 if file_extension=='.bat':255 AnsaExePath = Path(AnsaExePathtmp)256 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'AnsaExePath', 'to', '\n', AnsaExePathtmp)257 checkANSAexist = True258 break259 else:260 if varget == 'EN':261 tk.messagebox.showwarning("Warning", "Please select an appropriate ANSA batch file")262 if varget == 'ZH':263 tk.messagebox.showwarning("è¦å", "请éæ©éå½çANSAæ¹å¤çæ件")264 filetypestr = (("bat files","*.bat"),)265 AnsaExePathtmp = def_queryfunctions.PathQuery(text,AnsaExePathtmp,filetypestr, varget)266 if not AnsaExePathtmp:267 if varget == 'EN':268 tk.messagebox.showwarning("Warning", warningtext)269 if varget == 'ZH':270 tk.messagebox.showwarning("è¦å", warningtext)271 break272 if checkANSAexist:273 AnsaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'AnsaExePath', 'to'))274 text1 = ""275 text2 = ""276 text3 = ""277 checkCompareModelsFirst=True278 if varget == 'EN':279 contCompareModels = tk.messagebox.askokcancel("Warning", "Select the models for ANSA based model comparison (geometrically)")280 if varget == 'ZH':281 contCompareModels = tk.messagebox.askokcancel("è¦å", "éæ©ç¨äºåºäºANSAç模åæ¯è¾ç模åï¼å¨å ä½ä¸ï¼")282 if contCompareModels:283 flag=0284 if varget == 'EN':285 titletext = 'Model file selection'286 labeltext = " Enter the full paths \t\t\t\t\t\t\t\n"287 entrytext = ["1. model path", "2. model path", "output directory"]288 if varget == 'ZH':289 titletext = '模åæ件éæ©'290 labeltext = " è¾å
¥å®æ´è·¯å¾ \t\t\t\t\t\t\t\n"291 entrytext = ["1.模åè·¯å¾", "2.模åè·¯å¾", "è¾åºç®å½"]292 tkinterGUI.MainApplication.TopLevelWindow_MultiEntry(titletext, labeltext, entrytext)293 contSingle = tkinterGUI.MainApplication.check2cont294 if contSingle == None:295 break296 fieldValues = tkinterGUI.MainApplication.EntryValues297 if fieldValues!=[None] * 3:298 path1 = Path(fieldValues[0])299 path2 = Path(fieldValues[1])300 exporting_directory = Path(fieldValues[2])301 try:302 if path1.exists()==False or len(fieldValues[0])==0 or not os.path.isfile(path1):303 if varget == 'EN':304 text1="invalid path for model 1"305 if varget == 'ZH':306 text1="模å1çè·¯å¾æ æ"307 flag = 1308 if path2.exists()==False or len(fieldValues[1])==0 or not os.path.isfile(path2):309 if varget == 'EN':310 text2="invalid path for model 2"311 if varget == 'ZH':312 text2="模å2çè·¯å¾æ æ"313 flag = 1314 if exporting_directory.exists()==False or len(fieldValues[2])==0 or not os.path.isdir(exporting_directory):315 if varget == 'EN':316 text3="invalid directory for output"317 if varget == 'ZH':318 text3="æ æçè¾åºç®å½"319 flag = 1320 except:321 if varget == 'EN':322 text1="invalid path string entered"323 if varget == 'ZH':324 text1="模å1çè·¯å¾æ æ"325 flag = 1326 if flag ==1:327 text4=""328 if len(text1)!=0:329 text4=text4+text1+"\n"330 if len(text2)!=0:331 text4=text4+text2+"\n"332 if len(text3)!=0:333 text4=text4+text3+"\n"334 if varget == 'EN':335 text4=text4+"\nDo you want to continue?"336 cont2 = tk.messagebox.askyesno("Warning",text4)337 if varget == 'ZH':338 text4=text4+"\nä½ æ³ç»§ç»åï¼"339 cont2 = tk.messagebox.askyesno("è¦å",text4)340 if cont2:341 checkCompareModelsFirst=False342 continue343 else:344 break345 else:346 try:347 stringexec = r'-exec "load_script: '348 AnsaExeStatement = stringexec + "'" + str(AnsaCompareScriptFilePath) + "'" + '" -exec "main(\"'+str(path1)+"\",\""+str(path2)+"\",\""+str(exporting_directory)+'\")"'349 def_functions.OpenANSA(AnsaExePath,AnsaExeStatement, exporting_directory)350 except OSError:351 if varget == 'EN':352 tk.messagebox.showwarning("Warning", "Errors encountered")353 if varget == 'ZH':354 tk.messagebox.showwarning("è¦å", "ä¸æ¯ææçMETA Postå¯æ§è¡è·¯å¾ï¼è¯·é¦å
å®ä¹ææè·¯å¾")355 break356 else:357 break358 else:359 break360 else:361 break362 checkCompareModelsFirst=False363 checkexist_otherfunc = False364 return True365def Convert2MetaDB(varget):366 global checkexist_otherfunc, checkConvert2MetaDB367 try:368 tmp=checkexist_otherfunc369 except NameError:370 checkexist_otherfunc=False371 if not checkexist_otherfunc:372 checkexist_otherfunc = True373 while True:374 try:375 tmp=checkConvert2MetaDB376 except NameError:377 checkConvert2MetaDB=False378 else:379 if checkConvert2MetaDB:380 break381 else: 382 MetaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'MetaExePath', 'to'))383 if MetaExePath.exists()==False:384 def_functions.ModifyExecutablePathsFile()385 MetaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'MetaExePath', 'to'))386 if MetaExePath.exists()==False:387 if varget == 'EN':388 text="Please select your META executable path"389 warningtext = """META executable path is invalid!\nPlease set a correct path to proceed.390 \nHint: Alternatively, set the META executable path on the program menu.\n"""391 abort = tk.messagebox.askquestion ("Warning", warningtext)392 if varget == 'ZH':393 text="请éæ©æ¨çMETAå¯æ§è¡æ件路å¾"394 warningtext = """META Postå¯æ§è¡è·¯å¾æ æï¼\n请设置æ£ç¡®çè·¯å¾ä»¥ç»§ç»ã395 \n æ示ï¼æè
ï¼å¨ç¨åºèåä¸è®¾ç½®â META Postâå¯æ§è¡è·¯å¾ã\n"""396 abort = tk.messagebox.askquestion ("è¦å", warningtext)397 if abort == 'yes':398 filetypestr = (("bat files","*.bat"),)399 MetaExePathtmp = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)400 else:401 break402 if not MetaExePathtmp:403 if varget == 'EN':404 tk.messagebox.showerror ("Warning", warningtext)405 if varget == 'ZH':406 tk.messagebox.showerror("è¦å", warningtext)407 break408 else:409 while True:410 filename_with_path, file_extension = os.path.splitext(MetaExePathtmp) # /a/b/x y411 if file_extension=='.bat':412 MetaExePath = Path(MetaExePathtmp)413 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'MetaExePath', 'to', '\n', MetaExePathtmp)414 break415 else:416 if varget == 'EN':417 tk.messagebox.showwarning("Warning", "Please select an appropriate META batch file")418 if varget == 'ZH':419 tk.messagebox.showwarning("è¦å", "请éæ©éå½çMETA Postå¯æ§è¡æ件")420 filetypestr = (("bat files","*.bat"),)421 MetaExePathtmp = def_queryfunctions.PathQuery(text,MetaExePathtmp,filetypestr, varget)422 if not MetaExePathtmp:423 if varget == 'EN':424 tk.messagebox.showwarning("Warning", warningtext)425 if varget == 'ZH':426 tk.messagebox.showwarning("è¦å", warningtext)427 break428 429 if not MetaExePathtmp:430 break431 checkConvert2MetaDB = True432 while True:433 if varget == 'EN':434 text="Please select the d3plot file to be converted"435 if varget == 'ZH':436 text="请éæ©è¦è½¬æ¢çd3plotæ件"437 filetypestr = (("d3plot files","*d3plot"),)438 File2Open = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)439 if File2Open:440 checkext = config_sessions.CreateSessionFile2Convert2MetaDB (SaveMetaDataBaseSessionFilePath, File2Open)441 if checkext:442 #OpenMETA(MetaExePath,tmpconvert2MetaDBsessionfilename)443 try:444 workingdir, filename_with_extension = os.path.split(File2Open) # /a/b/ x.y445 def_functions.OpenbatchmodeMETA(MetaExePath,tmpconvert2MetaDBsessionfilename, workingdir) #in batch mode446 except OSError:447 if varget == 'EN':448 tk.messagebox.showwarning("Warning", "not a valid METAPost executable path, define a valid path first")449 if varget == 'ZH':450 tk.messagebox.showwarning("è¦å", "ä¸æ¯ææçMETA Postå¯æ§è¡è·¯å¾ï¼è¯·é¦å
å®ä¹ææè·¯å¾")451 break452 break453 else:454 if varget == 'EN':455 tk.messagebox.showwarning("Warning", "d3plot file must be selected!")456 if varget == 'ZH':457 tk.messagebox.showwarning("è¦å", "å¿
é¡»éæ©d3plotæ件ï¼")458 else:459 break460 break461 checkConvert2MetaDB = False462 checkexist_otherfunc = False463 return True464def SingleVariant(varget):465 global checkexist_otherfunc, checkSingleVariant, checkreadparam466 try:467 tmp=checkexist_otherfunc468 except NameError:469 checkexist_otherfunc=False470 if not checkexist_otherfunc:471 checkexist_otherfunc = True472 while True:473 try:474 tmp=checkSingleVariant475 except NameError:476 checkSingleVariant=False477 else:478 if checkSingleVariant:479 break480 else:481 checkSingleVariant = True482 singleVarcheck = True483 checkMETAexist = True484 MetaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'MetaExePath', 'to'))485 if MetaExePath.exists()==False:486 def_functions.ModifyExecutablePathsFile()487 MetaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'MetaExePath', 'to'))488 if MetaExePath.exists()==False:489 checkMETAexist = False490 if varget == 'EN':491 text="Please select your META executable path"492 warningtext = """META executable path is invalid!\nPlease set a correct path to proceed.493 \nHint: Alternatively, set the META executable path on the program menu.\n"""494 abort = tk.messagebox.askquestion ("Warning", warningtext)495 if varget == 'ZH':496 text="请éæ©æ¨çMETAå¯æ§è¡æ件路å¾"497 warningtext = """META Postå¯æ§è¡è·¯å¾æ æï¼\n请设置æ£ç¡®çè·¯å¾ä»¥ç»§ç»ã498 \n æ示ï¼æè
ï¼å¨ç¨åºèåä¸è®¾ç½®â META Postâå¯æ§è¡è·¯å¾ã\n"""499 abort = tk.messagebox.askquestion ("è¦å", warningtext)500 if abort == 'yes':501 filetypestr = (("bat files","*.bat"),) 502 MetaExePathtmp = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)503 else:504 break505 if not MetaExePathtmp:506 if varget == 'EN':507 tk.messagebox.showerror ("Warning", warningtext)508 if varget == 'ZH':509 tk.messagebox.showerror("è¦å", warningtext)510 break511 else:512 while True:513 filename_with_path, file_extension = os.path.splitext(MetaExePathtmp) # /a/b/x y514 if file_extension=='.bat':515 MetaExePath = Path(MetaExePathtmp)516 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'MetaExePath', 'to', '\n', MetaExePathtmp)517 checkMETAexist = True518 break519 else:520 if varget == 'EN':521 tk.messagebox.showwarning("Warning", "Please select an appropriate META batch file")522 if varget == 'ZH':523 tk.messagebox.showwarning("è¦å", "请éæ©éå½çMETA Postå¯æ§è¡æ件")524 filetypestr = (("bat files","*.bat"),) 525 MetaExePathtmp = def_queryfunctions.PathQuery(text,MetaExePathtmp,filetypestr, varget)526 if not MetaExePathtmp:527 if varget == 'EN':528 tk.messagebox.showwarning("Warning", warningtext)529 if varget == 'ZH':530 tk.messagebox.showwarning("è¦å", warningtext)531 break532 if checkMETAexist:533 if varget == 'EN':534 inittxt = 'Selected Model'535 if varget == 'ZH':536 inittxt = 'éå®åå·'537 tmpstrfolderpath,tmpoutputfolderpath, File2Open, paramfile2Open, checkMETAexit, checkreadparam = def_queryfunctions.InteractQuery (MetaExePath, inittxt, varget)538 if not checkMETAexit and not checkreadparam:539 try:540 shutil.rmtree (tmpstrfolderpath, ignore_errors=True)541 except:542 pass543 def_functions.RemoveEmptyFolder([tmpoutputfolderpath])544 break545 else:546 def_queryfunctions.EvalQuery(MetaExePath, File2Open, tmpstrfolderpath, paramfile2Open, checkreadparam, singleVarcheck, varget)547 break548 else:549 break550 checkSingleVariant = False551 checkexist_otherfunc = False552 return True553def CompareVariants(varget):554 global checkexist_otherfunc, checkCompareVariants, checkreadparam555 try:556 tmp=checkexist_otherfunc557 except NameError:558 checkexist_otherfunc=False559 if not checkexist_otherfunc:560 checkexist_otherfunc = True561 while True:562 try:563 tmp=checkCompareVariants564 except NameError:565 checkCompareVariants=False566 else:567 if checkCompareVariants:568 break569 else:570 checkCompareVariants = True571 singleVarcheck = False572 checkMETAexist = True573 MetaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'MetaExePath', 'to')) 574 if MetaExePath.exists()==False:575 def_functions.ModifyExecutablePathsFile()576 MetaExePath = Path(def_functions.FindExtractString_fromFile (str(ExecutablePaths), 'MetaExePath', 'to')) 577 if MetaExePath.exists()==False:578 checkMETAexist = False579 if varget == 'EN':580 text="Please select your META executable path"581 warningtext = """META executable path is invalid!\nPlease set a correct path to proceed.582 \nHint: Alternatively, set the META executable path on the program menu.\n"""583 abort = tk.messagebox.askquestion ("Warning", warningtext)584 if varget == 'ZH':585 text="请éæ©æ¨çMETAå¯æ§è¡æ件路å¾"586 warningtext = """META Postå¯æ§è¡è·¯å¾æ æï¼\n请设置æ£ç¡®çè·¯å¾ä»¥ç»§ç»ã587 \n æ示ï¼æè
ï¼å¨ç¨åºèåä¸è®¾ç½®â META Postâå¯æ§è¡è·¯å¾ã\n"""588 abort = tk.messagebox.askquestion ("è¦å", warningtext)589 if abort == 'yes':590 filetypestr = (("bat files","*.bat"),) 591 MetaExePathtmp = def_queryfunctions.PathQuery(text,currentdir,filetypestr, varget)592 else:593 break594 if not MetaExePathtmp:595 if varget == 'EN':596 tk.messagebox.showerror ("Warning", warningtext)597 if varget == 'ZH':598 tk.messagebox.showerror("è¦å", warningtext)599 break600 else:601 while True:602 filename_with_path, file_extension = os.path.splitext(MetaExePathtmp) # /a/b/x y603 if file_extension=='.bat':604 MetaExePath = Path(MetaExePathtmp)605 def_functions.FindReplaceString_inFile (str(ExecutablePaths),'MetaExePath', 'to', '\n', MetaExePathtmp)606 checkMETAexist = True607 break608 else:609 if varget == 'EN':610 tk.messagebox.showwarning("Warning", "Please select an appropriate META batch file")611 if varget == 'ZH':612 tk.messagebox.showwarning("è¦å", "请éæ©éå½çMETA Postå¯æ§è¡æ件")613 filetypestr = (("bat files","*.bat"),)614 MetaExePathtmp = def_queryfunctions.PathQuery(text,MetaExePathtmp,filetypestr, varget)615 if not MetaExePathtmp:616 if varget == 'EN':617 tk.messagebox.showwarning("Warning", warningtext)618 if varget == 'ZH':619 tk.messagebox.showwarning("è¦å", warningtext)620 break621 if checkMETAexist:622 if varget == 'EN':623 inittxt = 'Base Model'624 if varget == 'ZH':625 inittxt = 'åºæ¬åå·'626 tmpstrfolderpath,tmpoutputfolderpath, File2Open, paramfile2Open, checkMETAexit, checkreadparam = def_queryfunctions.InteractQuery (MetaExePath, inittxt, varget)627 if not checkMETAexit and not checkreadparam:628 try:629 shutil.rmtree (tmpstrfolderpath, ignore_errors=True)630 except:631 pass632 def_functions.RemoveEmptyFolder([tmpoutputfolderpath])633 break634 else:635 def_queryfunctions.EvalQuery(MetaExePath, File2Open, tmpstrfolderpath, paramfile2Open, checkreadparam, singleVarcheck, varget)636 break637 else:638 break639 checkCompareVariants = False640 checkexist_otherfunc = False641 return True642def exit_Func():643 pyID = str(os.getpid())644 pidfile = os.path.join(TemporaryFilesDirectoryPath, 'CurrentprocessID.pid')645 with open(pidfile, "r") as f:646 lines = f.readlines()647 with open(pidfile, "w") as f:648 for line in lines:649 if line.strip("\n") != pyID:650 f.write(line)...
injrecanalysis.py
Source:injrecanalysis.py
1import pandas as pd2import numpy as np3import seaborn4import matplotlib.pyplot as plt5import copy6def wrap_characterization_of_flares(injrec, flares, ampl_bins=None, dur_bins=None,7 flares_per_bin=None):8 """Take injection-recovery results for a data set9 and the corresponding flare table. Determine10 recovery probability, ED ratio, amplitude ratio,11 duration ratio, and the respective standard deviation.12 Count on how many synthetic flares the results are based.13 Parameters:14 -----------15 injrec : DataFrame16 table with injection-recovery results from AltaiPony17 flares : DataFrame18 table with flare candidates detected by AltaiPony19 ampl_bins : int20 number of bins in amplitude21 dur_bins : int22 number of bins in duration23 Return:24 --------25 DataFrame : flares and injrec merged with the characteristics26 listed above.27 """28 # define observed flare duration29 flares["dur"] = flares.tstop - flares.tstart30 31 ampl_bins, dur_bins = setup_bins(injrec, flares, ampl_bins=ampl_bins, 32 dur_bins=dur_bins,33 flares_per_bin=flares_per_bin)34 flares = flares.dropna(subset=["ed_rec"])35 injrec.ed_rec = injrec.ed_rec.fillna(0)36 injrec['rec'] = injrec.ed_rec.astype(bool).astype(float)37 flcc, dscc = characterize_flares(flares, injrec, otherfunc="count",38 amplrec="ampl_rec", durrec="dur",39 amplinj="amplitude", durinj="duration_d",40 ampl_bins=ampl_bins,41 dur_bins=dur_bins)42 fl, ds = characterize_flares(flares, injrec, otherfunc="std",43 amplrec="ampl_rec", durrec="dur",44 amplinj="amplitude", durinj="duration_d",45 ampl_bins=ampl_bins,46 dur_bins=dur_bins)47 fl = fl.merge(flcc)48 fl["ed_corr_err"] = np.sqrt(fl.ed_rec_err**2 + fl.ed_corr**2 * fl.ed_ratio_std**2)49 fl["amplitude_corr_err"] = fl.amplitude_corr * fl.amplitude_ratio_std / fl.amplitude_ratio50 fl["duration_corr_err"] = fl.duration_corr * fl.duration_ratio_std / fl.duration_ratio51 return fl52def characterize_flares(flares, df, otherfunc="count",53 amplrec="ampl_rec", durrec="dur",54 amplinj="amplitude", durinj="duration_d",55 **kwargs):56 """Assign ED recovery ratios, and57 recovery probability to all flares58 whose recovered parameters are covered59 by the synthetic data.60 Parameters:61 -----------62 flares : DataFrame63 flare table64 df : DataFrame65 injection-recovery table66 otherfunc : str67 additional column for statistical analysis.68 Can accept "count", "std", and other simple69 pandas methods that work on Groupby objects.70 amplrec : str71 column name for recovered amplitude72 durrec : str73 column name for recovered duration74 amplinj: str75 column name for injected amplitude76 durrec : str77 column name for injected duration78 kwargs : dict79 Keyword arguments to pass to tile_up_injection_recovery80 Return:81 -------82 DataFrame: flares with additional columns83 """84 # define observed flare duration85 if "dur" not in flares.columns:86 flares["dur"] = flares.tstop - flares.tstart87 if "dur" not in df.columns:88 df["dur"] = df.tstop - df.tstart89 ds =dict()90 # calculate inj-rec ratio for ED, amplitude, and duration91 for typ in ["ed_ratio", "amplitude_ratio", "duration_ratio"]:92 d, val = tile_up_injection_recovery(df, typ, otherfunc=otherfunc,93 ampl=amplrec, dur=durrec, **kwargs)94 d = d.dropna(how="all", axis=0)95 ds[typ] = d96 helper = lambda x: multiindex_into_df_with_nans(x, d,97 i1="ampl_rec",98 i2="dur", i3=val)99 flares[typ] = flares.apply(helper, axis=1)100 helper = lambda x: multiindex_into_df_with_nans(x, d,101 i1="ampl_rec",102 i2="dur", i3=otherfunc)103 flares["{}_{}".format(typ, otherfunc)] = flares.apply(helper, axis=1)104 # calculate recovery probability from corrected values105 flares["amplitude_corr"] = flares[amplrec] / flares.amplitude_ratio106 flares["duration_corr"] = flares[durrec] / flares.duration_ratio107 flares["ed_corr"] = flares["ed_rec"] / flares.ed_ratio108 d, val = tile_up_injection_recovery(df, "recovery_probability",109 otherfunc=otherfunc, ampl=amplinj,110 dur=durinj, **kwargs)111 d = d.dropna(how="all", axis=0)112 ds["recovery_probability"] = d113 helper = lambda x: multiindex_into_df_with_nans(x, d,114 i1="amplitude_corr",115 i2="duration_corr", i3=val)116 flares["recovery_probability"] = flares.apply(helper, axis=1)117 helper = lambda x: multiindex_into_df_with_nans(x, d,118 i1="amplitude_corr",119 i2="duration_corr", i3=otherfunc)120 flares["{}_{}".format("recovery_probability", otherfunc)] = flares.apply(helper, axis=1)121 return flares, ds122def tile_up_injection_recovery(df, typ, ampl="amplitude", dur="duration_d",123 otherfunc = "count",124 ampl_bins=np.arange(0, .5, 0.025),125 dur_bins=np.arange(0, .2, 5e-3)):126 """Tile up the injection recovery data into127 amplitude and duration bins. Return a multiindexed128 matrix that can be accessed to assign recovered129 ED/amplitude/duration ratio or recovery probability130 to a given observation (AMPL, DUR)131 or its recovery corrected form.132 Parameters:133 ------------134 df : DataFrame135 injection recovery table136 typ: str137 type of inj-rec parameter to obtain138 Can be "recovery_probability",139 "ed_ratio",140 "amplitude_ratio",141 "duration_ratio".142 ampl: str143 column name used to bin on one parameter axis144 dur : str145 column name used to bin on the other axis146 otherfunc : pandas groupby applicable function string147 "std", "count", "mean" ...148 Use this to get another statistic on the desired149 inj-rec parameter that is not median150 ampl_bins : numpy array151 bins for one axis, should cover both152 injected and recovered range153 dur_bins : numpy array154 bins for the other axis, should cover both155 injected and recovered range156 Return:157 -------158 multiindexed DataFrame, str :159 tiled injection-recovery dataset,160 column name for relevant parameter161 """162 # Calculate helpful columns163 if "rec" not in df.columns:164 df["rec"] = df.ed_rec.fillna(0).astype(bool).astype(int)165 if "dur" not in df.columns:166 df["dur"] = df.tstop - df.tstart167 168 169 d1 = df.assign(Amplitude=pd.cut(df[ampl], ampl_bins),170 Duration=pd.cut(df[dur], dur_bins))171 types = {"ed_ratio":("ed_rec","ed_inj","edrat"),172 "amplitude_ratio":("ampl_rec","amplitude","amplrat"),173 "duration_ratio":("dur","duration_d","durrat"),174 }175 if typ == "recovery_probability":176 grouped = d1.groupby(["Amplitude","Duration"])177 d2 = grouped.rec.sum() / grouped.rec.count()178 d3 = getattr(grouped.rec, otherfunc)()179 val = "rec"180 else:181 d1["rel"] = d1[types[typ][0]] / d1[types[typ][1]]182 grouped = d1.groupby(["Amplitude","Duration"])183 d2 = grouped.rel.median()184 d3 = getattr(grouped.rel, otherfunc)()185 val = types[typ][2]186 return pd.DataFrame({val : d2, otherfunc : d3}), val187def multiindex_into_df_with_nans(x, df, i1="ampl_rec", i2="dur", i3="edrat"):188 """Helps with indexing in multiindexed tables189 that also have NaNs.190 Parameter:191 ---------192 x : Series193 row from the flare detection table194 df : DataFrame195 multiindexed table with NaNs196 i1, i2, i3: str, str, str197 name of 1st index, 2nd index and value column198 in df199 Return:200 -------201 float : value at index given by x202 """203 try:204 return df.loc[(x[i1], x[i2]), i3]205 except KeyError:206 return np.nan207def percentile(x, q):208 """Calculate percentile q in Series x.209 Parameters:210 ------------211 x : pandas Series212 distribution213 q : float214 desired percentile (0,100)215 Return:216 --------217 float218 """219 if (np.isnan(x.values).all() | np.isnan(q)):220 return np.nan221 else:222 return np.percentile(x.dropna(), q=q)223def _heatmap(flcd, typ, ampl_bins, dur_bins, flares_per_bin, **kwargs):224 """Create a heatmap for either recovery probability or ED ratio.225 226 Parameters:227 -----------228 flcd : FlareLightCurve229 typ : string230 Either "recovery_probability" or "ed_ratio"231 ampl_bins : int or array232 bins for amplitudes233 dur_bins : int or array234 bins for duration or FWHM235 flares_per_bin : int236 number of flares per bin237 """238 if not bool(flcd.fake_flares.shape[0] > 0):239 raise AttributeError("Missing injection-recovery data. "240 "Use `FLC.load_injrec_data(path)` to fetch "241 "some, or run `FLC.sample_flare_recovery()`.")242 #print(flcd.fake_flares)243 #print(flcd.flares)244 # define observed flare duration245 flcd.flares["dur"] = flcd.flares.tstop - flcd.flares.tstart246 flcd.fake_flares["dur"] = flcd.fake_flares.tstop - flcd.fake_flares.tstart247 248 ampl_bins, dur_bins = setup_bins(flcd.fake_flares, flcd.flares, 249 ampl_bins=ampl_bins, dur_bins=dur_bins,250 flares_per_bin=flares_per_bin)251 252 # Tile up the inj-rec table using the bins.253 dff, val = tile_up_injection_recovery(flcd.fake_flares, 254 typ,255 ampl_bins=ampl_bins,256 dur_bins=dur_bins,)257 258 # Map internal keywords to human-readable ones:259 typ_map = {"recovery_probability" : 260 ["injected", "FWHM", "recovery probability"],261 "ed_ratio" : 262 ["recovered", "duration", "ED ratio"]}263 # Create a heatmap264 fig = plot_heatmap(dff, val, ID=flcd.targetid, label=typ_map[typ][2],265 ylabel=f"{typ_map[typ][0]} amplitude", 266 xlabel=f"{typ_map[typ][0]} {typ_map[typ][1]} [d]", **kwargs);267 268 return fig269 270 271def plot_heatmap(df, val, label=None,272 ID=None, valcbr=(0.,1.),273 ovalcbr=(0,50), xlabel="duration [d]",274 ylabel="amplitude", cmap="viridis",275 font_scale=1.5, interpolate=False):276 """Plot a heatmap from the "fake_flares" table. 277 278 Parameters:279 ------------280 df : DataFrame281 fake_flares attribute or equivalent table282 val : str283 column name in df to map284 label: str285 human-readable version of "val"286 ID : int or str287 target id288 valcbr : tuple289 value range for "val"290 xlabel : str or "duration [d]"291 xlabel for plot292 ylabel : str or "amplitude"293 ylabel for plot 294 cmap : colormap295 default "viridis"296 font_scale : float297 set the size of tick labels, and bar label298 299 Return:300 -------301 matplotlib.figure.Figure 302 """303 # configure Seaborn304 seaborn.set(font_scale=font_scale)305 # Find the midpoint of the interval to use as ticks306 df = df.reset_index()307 df.Amplitude = df.Amplitude.apply(lambda x: x.mid)308 df.Duration = df.Duration.apply(lambda x: x.mid)309 310 # Init figure311 fig, ax = plt.subplots(nrows=1, ncols=1, figsize = (9,7))312 313 # Some layout stuff314 if label is None:315 label = val316 317 # Create heatmap data format 318 heatmap1_data = pd.pivot_table(df, values=val, 319 index=['Amplitude'], 320 columns=['Duration'])321 if interpolate==True:322 heatmap1_data.iloc[:,:] = (heatmap1_data.bfill(axis=0).values +323 heatmap1_data.ffill(axis=0).values +324 heatmap1_data.bfill(axis=1).values +325 heatmap1_data.ffill(axis=1).values) / 4 326 heatmap1_data = heatmap1_data.bfill(axis=0).ffill(axis=0).bfill(axis=1).ffill(axis=1)327 try:328 heatmap = seaborn.heatmap(heatmap1_data.values,cbar_kws={'label': label},329 vmin=valcbr[0], vmax=valcbr[1], annot=False, ax=ax,330 yticklabels=["{:.2e}".format(x) for x in heatmap1_data.index.values],331 xticklabels=["{:.2e}".format(x) for x in heatmap1_data.columns.values])332 except AttributeError:333 heatmap = seaborn.heatmap(heatmap1_data.values, cbar_kws={'label': label},334 vmin=valcbr[0], vmax=valcbr[1], annot=False, ax=ax,335 yticklabels=["{:.2e}".format(x) for x in heatmap1_data.index.values.categories.values.mid.values],336 xticklabels=["{:.2e}".format(x) for x in heatmap1_data.columns.values.categories.values.mid.values])337 338 fig = heatmap.get_figure()339 340 # Do some layout stuff341 342 fig.tight_layout()343 for label in ax.xaxis.get_ticklabels()[::2]:344 label.set_visible(False)345 for label in ax.yaxis.get_ticklabels()[::2]:346 label.set_visible(False) 347 ax.set_xlabel(xlabel, fontsize=16)348 ax.set_ylabel(ylabel, fontsize=16)349 ax.set_title(ID, fontsize=16)350 return fig351def setup_bins(injrec, flares, ampl_bins=None, dur_bins=None, flares_per_bin=None):352 """Get amplitude and duration bins.353 354 Parameters:355 ------------356 """357 # Did the user give appropriate bins?358 bins = np.array([bool(ampl_bins is not None), bool(dur_bins is not None)])359 360 # If only one or no bin is given explicitly, make dure flares_per_bin is set361 if ((~bins.all()) & (flares_per_bin is None)):362 raise ValueError("Give either ampl_bins and dur_bins, or either of "363 "the two together with flares_per_bin, or neither of"364 " the two but flares_per_bin.")365 # If only one out of [ampl_bins, dur_bins] is specified366 # specify the other by fixing the `flares_per_bin`367 if ((bins.any()) & (~bins.all())):368 369 # Which one is not defined?370 if ampl_bins is None:371 b = copy.copy(dur_bins)372 elif dur_bins is None:373 b = copy.copy(ampl_bins)374 375 # If defined bins are given as array, find length376 if (isinstance(b, float) | isinstance(b, int)):377 l = b378 else:379 l = len(b) 380 # Define the other bins accordingly381 if ampl_bins is None:382 ampl_bins = int(np.rint(injrec.shape[0] / l / flares_per_bin))383 elif dur_bins is None:384 dur_bins = int(np.rint(injrec.shape[0] / l / flares_per_bin))385 386 # If no bins are specified, choose bins of equal size387 # with approximately `flares_per_bin` in each bin:388 elif ~bins.any():389 bins = int(np.rint(np.sqrt(injrec.shape[0] / flares_per_bin)))390 ampl_bins, dur_bins = bins, bins391 392 # If no flares are given, substitute with fake flares393 if flares.shape[0] == 0:394 flares = injrec395 396 # Set bins according to data397 if isinstance(ampl_bins, int):398 ampl_bins = np.linspace(min(injrec.ampl_rec.min(),399 flares.ampl_rec.min(), 400 injrec.amplitude.min()),401 max(injrec.ampl_rec.max(),402 flares.ampl_rec.max(),403 injrec.amplitude.max()), 404 ampl_bins)405 406 if isinstance(dur_bins, int):407 dur_bins = np.linspace(min(injrec.dur.min(),408 flares.dur.min(), 409 injrec.duration_d.min()),410 max(injrec.dur.max(),411 flares.dur.max(),412 injrec.duration_d.max()), 413 dur_bins)...
Calculator.py
Source:Calculator.py
1from tkinter import *2import math3op=["",""]4sign=""5hist=""6i=07window=Tk()8window.title("Scientific Calculator")9l1=Label(text="SCIENTIFIC CALCULATOR")10l1.grid(row=0,columnspan=10)11t2=Text(window,height=1,width=49)12t2.grid(row=1,columnspan=9)13t1=Text(window,height=1,width=49)14t1.grid(row=2,column=0,columnspan=9)15t1.config(state=DISABLED)16t2.config(state=DISABLED)17def Number(number):18 if (number==1):19 t1.config(state=NORMAL)20 t1.insert(END,"1")21 charproc("1")22 t1.config(state=DISABLED)23 elif (number==2):24 t1.config(state=NORMAL)25 t1.insert(END,"2")26 charproc("2")27 t1.config(state=DISABLED)28 elif (number==3):29 t1.config(state=NORMAL)30 t1.insert(END,"3")31 charproc("3")32 t1.config(state=DISABLED)33 elif (number==4):34 t1.config(state=NORMAL)35 t1.insert(END,"4")36 charproc("4")37 t1.config(state=DISABLED)38 elif (number==5):39 t1.config(state=NORMAL)40 t1.insert(END,"5")41 charproc("5")42 t1.config(state=DISABLED)43 elif (number==6):44 t1.config(state=NORMAL)45 t1.insert(END,"6")46 charproc("6")47 t1.config(state=DISABLED)48 elif (number==7):49 t1.config(state=NORMAL)50 t1.insert(END,"7")51 charproc("7")52 t1.config(state=DISABLED)53 elif (number==8):54 t1.config(state=NORMAL)55 t1.insert(END,"8")56 charproc("8")57 t1.config(state=DISABLED)58 elif (number==9):59 t1.config(state=NORMAL)60 t1.insert(END,"9")61 charproc("9")62 t1.config(state=DISABLED)63 elif (number==0):64 t1.config(state=NORMAL)65 t1.insert(END,"0")66 charproc("0")67 t1.config(state=DISABLED)68 elif (number=="dec"):69 t1.config(state=NORMAL)70 t1.insert(END,".")71 charproc("dec")72 t1.config(state=DISABLED)73 elif (number=="+"):74 t1.config(state=NORMAL)75 t1.insert(END,"+")76 charproc("+")77 t1.config(state=DISABLED)78 elif (number=="-"):79 t1.config(state=NORMAL)80 t1.insert(END,"-")81 charproc("-")82 t1.config(state=DISABLED)83 elif (number=="x"):84 t1.config(state=NORMAL)85 t1.insert(END,"x")86 charproc("x")87 t1.config(state=DISABLED)88 elif (number=="/"):89 t1.config(state=NORMAL)90 t1.insert(END,"/")91 charproc("/")92 t1.config(state=DISABLED)93 elif (number=="="):94 charproc("=")95 elif (number=="clr"):96 t1.config(state=NORMAL)97 t2.config(state=NORMAL)98 t1.delete(1.0,END)99 t2.delete(1.0,END)100 charproc("clr")101 t1.config(state=DISABLED)102 t2.config(state=DISABLED)103 elif (number=="del"):104 charproc("del")105106def charproc(ch):107 global i108 global op109 global sign110 global hist111 if ch in ["+","-","x","/","="]:112 if (ch!="="):113 sign+=ch114 if (len(sign)>1 or ch=="="):115 if (ch!="="):116 t2.config(state=NORMAL)117 t2.insert(END,hist+str(op[1]))118 t2.config(state=DISABLED)119 if (sign[0]=="+"):120 op[0]=float(op[0])+float(op[1])121 elif (sign[0]=="-"):122 op[0]=float(op[0])-float(op[1])123 elif (sign[0]=="x"):124 op[0]=float(op[0])*float(op[1])125 elif (sign[0]=="/"):126 op[0]=float(op[0])/float(op[1])127 i=1128 if (ch=="="):129 ch=""130 hist=ch131 op[1]=""132 t1.config(state=NORMAL)133 t1.delete(1.0,END)134 t1.insert(END,str(op[0])+ch)135 t1.config(state=DISABLED)136 sign=ch137 else :138 i=1139 hist=str(op[0])+ch140 elif (ch.isdigit()==TRUE):141 op[i]+=ch142 elif (ch=="dec"):143 op[i]+="."144 elif (ch=="sin"):145 op[i]=math.sin(float(op[i]))146 Otherfunc("sin",i,hist,op[i])147 elif (ch=="cos"):148 op[i]=math.cos(float(op[i]))149 Otherfunc("cos",i,hist,op[i])150 elif (ch=="tan"):151 op[i]=math.tan(float(op[i]))152 Otherfunc("tan",i,hist,op[i])153 elif (ch=="exp"):154 op[i]=math.exp(float(op[i]))155 Otherfunc("exp",i,hist,op[i])156 elif (ch=="divx"):157 op[i]=1/float(op[i])158 Otherfunc("divx",i,hist,op[i])159 elif (ch=="pi"):160 op[i]=3.14159161 Otherfunc("pi",i,hist,op[i])162 elif (ch=="log"):163 op[i]=math.log10(float(op[i]))164 Otherfunc("exp",i,hist,op[i])165 elif (ch=="fact"):166 op[i]=math.factorial(float(op[i]))167 Otherfunc("exp",i,hist,op[i])168 elif (ch=="sqrt"):169 op[i]=math.sqrt(float(op[i]))170 Otherfunc("exp",i,hist,op[i])171 elif (ch=="clr"):172 op[0]=""173 op[1]=""174 sign=""175 i=0176 hist=""177 elif (ch=="del"):178 if (t1.get("1.end-1c").isdigit()==TRUE):179 op[i]=op[i][0:len(op[i])-1]180 print(op[i])181 t1.config(state=NORMAL)182 t1.delete("1.end-1c")183 t1.config(state=DISABLED)184 elif t1.get("1.end -1c") in ["+","-","x","/"]:185 sign=sign[0:len(sign)-1]186 t1.config(state=NORMAL)187 t1.delete("1.end-1c")188 t1.config(state=DISABLED)189def Otherfunc(f,i,s,h):190 if (i==0):191 t1.config(state=NORMAL)192 t1.delete(1.0,END)193 t1.insert(END,h)194 t1.config(state=DISABLED)195 if (i==1):196 t1.config(state=NORMAL)197 t1.delete(1.0,END)198 t1.insert(END,s+str(h))199 t1.config(state=DISABLED)200def Basu():201 t1.config(state=NORMAL)202 t2.config(state=NORMAL)203 t2.insert(END,"Crafted by")204 t1.insert(END,"Arnab Basu")205 t1.config(state=DISABLED)206 t2.config(state=DISABLED)207bclr=Button(window,text="CLR",width=5,height=1,command=lambda:Number("clr"))208bclr.grid(row=1,column=9)209bdel=Button(window,text="DEL",width=5,height=1,command=lambda:Number("del"))210bdel.grid(row=2,column=9)211b1=Button(window,text="1",width=5,height=2,command=lambda:Number(1))212b1.grid(row=3,column=6)213b2=Button(window,text="2",width=5,height=2,command=lambda:Number(2))214b2.grid(row=3,column=7)215b3=Button(window,text="3",width=5,height=2,command=lambda:Number(3))216b3.grid(row=3,column=8)217b4=Button(window,text="4",width=5,height=2,command=lambda:Number(4))218b4.grid(row=4,column=6)219b5=Button(window,text="5",width=5,height=2,command=lambda:Number(5))220b5.grid(row=4,column=7)221b6=Button(window,text="6",width=5,height=2,command=lambda:Number(6))222b6.grid(row=4,column=8)223b7=Button(window,text="7",width=5,height=2,command=lambda:Number(7))224b7.grid(row=5,column=6)225b8=Button(window,text="8",width=5,height=2,command=lambda:Number(8))226b8.grid(row=5,column=7)227b9=Button(window,text="9",width=5,height=2,command=lambda:Number(9))228b9.grid(row=5,column=8)229bdec=Button(window,text=".",width=5,height=2,command=lambda:Number("dec"))230bdec.grid(row=6,column=6)231b0=Button(window,text="0",width=5,height=2,command=lambda:Number(0))232b0.grid(row=6,column=7)233beq=Button(window,text="=",width=5,height=2,command=lambda:Number("="))234beq.grid(row=6,column=8)235badd=Button(window,text="+",width=5,height=2,command=lambda:Number("+"))236badd.grid(row=3,column=9)237bsub=Button(window,text="-",width=5,height=2,command=lambda:Number("-"))238bsub.grid(row=4,column=9)239bmul=Button(window,text="x",width=5,height=2,command=lambda:Number("x"))240bmul.grid(row=5,column=9)241bdiv=Button(window,text="/",width=5,height=2,command=lambda:Number("/"))242bdiv.grid(row=6,column=9)243244bpow=Button(window,text="x^y",width=5,height=2)245bpow.grid(row=3,column=0)246bsin=Button(window,text="sin",width=5,height=2,command=lambda:charproc("sin"))247bsin.grid(row=4,column=0)248bisin=Button(window,text="inv(sin)",width=5,height=2)249bisin.grid(row=5,column=0)250b=Button(window,text="",width=5,height=2,command=Basu)251b.grid(row=6,column=0)252253bsqrt=Button(window,text="root(x)",width=5,height=2,command=lambda:charproc("sqrt"))254bsqrt.grid(row=3,column=1)255bcos=Button(window,text="cos",width=5,height=2,command=lambda:charproc("cos"))256bcos.grid(row=4,column=1)257bicos=Button(window,text="inv(cos)",width=5,height=2)258bicos.grid(row=5,column=1)259bpi=Button(window,text="pi",width=5,height=2,command=lambda:charproc("pi"))260bpi.grid(row=6,column=1)261262blog=Button(window,text="log(x)",width=5,height=2,command=lambda:charproc("log"))263blog.grid(row=3,column=2)264btan=Button(window,text="tan",width=5,height=2,command=lambda:charproc("tan"))265btan.grid(row=4,column=2)266bitan=Button(window,text="inv(tan)",width=5,height=2)267bitan.grid(row=5,column=2)268bneg=Button(window,text="-ve",width=5,height=2)269bneg.grid(row=6,column=2)270271bexp=Button(window,text="e^x",width=5,height=2,command=lambda: charproc("exp"))272bexp.grid(row=3,column=3)273bdivx=Button(window,text="1/x",width=5,height=2,command=lambda:charproc("divx"))274bdivx.grid(row=4,column=3)275bfact=Button(window,text="x !",width=5,height=2,command=lambda:charproc("fact"))276bfact.grid(row=5,column=3)277bmod=Button(window,text="%",width=5,height=2)278bmod.grid(row=6,column=3)279280l2=Label(text=" ")281l2.grid(row=3,column=4,rowspan=4,columnspan=1)282l2=Label(text=" ")283l2.grid(row=3,column=5,rowspan=4,columnspan=1)
...
failure_demo.py
Source:failure_demo.py
1from py.test import raises2import py34def otherfunc(a,b):5 assert a==b67def somefunc(x,y):8 otherfunc(x,y)910def otherfunc_multi(a,b): 11 assert (a == 12 b) 1314class TestFailing(object):15 def test_simple(self):16 def f():17 return 4218 def g():19 return 432021 assert f() == g()22
...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!