Best Python code snippet using lisa_python
main.py
Source:main.py
1import math2def get_address(address):3 total = 04 t = len(address) - 15 for i in address:6 total += int(i, 16) * math.pow(16, t)7 t = t - 18 return int(total)9def output1(a, size, asc, bs, wp, ap):10 print("***CACHE SETTINGS***")11 if a == '0':12 print("Unified I- D-cache")13 print("Size:", size)14 else:15 print("Split I- D-cache")16 print("I-cache size:", int(size[0]))17 print("D-cache size:", int(size[2]))18 print("Associativity:", asc)19 print("Block size:", bs)20 if wp == 'wb':21 print("Write policy: WRITE BACK")22 else:23 print("Write policy: WRITE THROUGH")24 if ap == "wa":25 print("Allocation policy: WRITE ALLOCATE")26 else:27 print("Allocation policy: WRITE NO ALLOCATE")28 print()29def output2(acs, miss, replace, iacs, imiss, ireplace, word, copies, wt, wa):30 print("***CACHE STATISTICS***")31 print("INSTRUCTIONS")32 print("accesses:", iacs)33 print("misses:", imiss)34 if iacs != 0:35 i_miss_rate = round((imiss/iacs), 4)36 print("miss rate: %.4f" % i_miss_rate, "(hit rate %.4f)" % (1 - i_miss_rate))37 if iacs == 0:38 print("miss rate: 0.0000 (hit rate 0.0000)")39 print("replace:", ireplace)40 print("DATA")41 print("accesses:", acs)42 print("misses:", miss)43 if acs != 0:44 d_miss_rate = round((miss/acs), 4)45 print("miss rate: %.4f" % d_miss_rate, "(hit rate %.4f)" % (1 - d_miss_rate))46 else:47 print("miss rate:", 0.0000, "(hit rate 0.0000)")48 # print("miss rate: %.4f" % d_miss_rate, "(hit rate %.4f)" % (1 - d_miss_rate))49 print("replace:", replace)50 print("TRAFFIC (in words)")51 if writing_policy == 'wb' and allocation == 'wa':52 print("demand fetch:", int((imiss + miss) * word), "\ncopies back:", int(word * copies))53 if writing_policy == 'wt':54 print("demand fetch:", int((imiss + miss - wa) * word), "\ncopies back:", wt)55 if allocation == 'nw' and writing_policy == 'wb':56 print("demand fetch:", int((imiss + miss - wa) * word), "\ncopies back:", wa + int(copies * word))57def creating_cache(w, h):58 c = [['x' for x in range(w)] for y in range(h)]59 return c60def check_lru(lru, tag):61 for i in lru:62 if tag in i:63 return True64 return False65def unified_cache(info, c_size, associativity_no):66 i_miss = 067 i_hit = 068 d_hit = 069 d_miss = 070 i_replace = 071 d_replace = 072 copy_back = 073 wt = 074 wa = 075 nw = 076 blocksize = int(info[0])77 words = blocksize / 478 set_no = int(c_size / (blocksize * associativity_no))79 # cache = creating_cache(associativity_no, set_no)80 # print(*cache)81 lru = []82 for k in range(set_no):83 temp = []84 lru.append(temp)85 inp = input()86 while inp != "":87 request = inp.split()88 tag = int(get_address(request[1]) / block_size)89 set_address = int(tag % set_no)90 d = 'c'91 if check_lru(lru[set_address], str(tag)):92 for i in lru[set_address][:]:93 for i in lru[set_address][:]:94 if str(tag) in i:95 d = i.get(str(tag))96 lru[set_address].remove(i)97 if request[0] == '1' and writing_policy == 'wb':98 d = 'd'99 lru[set_address].append({str(tag): d})100 # print("hit")101 if request[0] == '0' or request[0] == '1':102 d_hit += 1103 if request[0] == '1' and writing_policy == 'wt':104 wt += 1105 elif request[0] == '2':106 i_hit += 1107 # print(lru)108 else:109 cell = {str(tag): 'c'}110 if len(lru[set_address]) < associativity_no:111 if request[0] == '1':112 if allocation == 'wa':113 lru[set_address].append({str(tag): 'd'})114 if request[0] == '0' or request[0] == '2':115 lru[set_address].append(cell)116 # print("miss")117 if request[0] == '0' or request[0] == '1':118 d_miss += 1119 if request[0] == '1':120 wt += 1121 if allocation == "nw":122 wa += 1123 elif request[0] == '2':124 i_miss += 1125 # print(lru)126 # print("allocation:", wa)127 else:128 if allocation != 'nw' or request[0] != '1':129 t = lru[set_address].pop(0)130 li = list(t.values())131 # print(li)132 if li[0] == 'd':133 copy_back += 1134 if request[0] == '1':135 if allocation == "wa":136 lru[set_address].append({str(tag): 'd'})137 if request[0] == '2' or request[0] == '0':138 lru[set_address].append(cell)139 # print("miss")140 if request[0] == '0' or request[0] == '1':141 d_miss += 1142 d_replace += 1143 if request[0] == '1' and writing_policy == 'wt':144 wt += 1145 if allocation == "nw":146 wa += 1147 elif request[0] == '2':148 i_miss += 1149 i_replace += 1150 else:151 d_miss += 1152 wa += 1153 wt += 1154 # print(lru)155 # print("allocation:", wa)156 inp = input()157 # print(*lru)158 # if allocation == 'wa':159 for i in lru:160 for j in i:161 l = list(j.values())162 # print(l, l.count('d'))163 copy_back += l.count('d')164 output1(cache_info[2], cache_size, int(cache_info[4]), block_size, cache_info[6], cache_info[8])165 output2(d_hit + d_miss, d_miss, d_replace, i_miss + i_hit, i_miss, i_replace, words, copy_back, wt, wa)166def split_cache(info, c_size, associativity_no):167 i_miss = 0168 i_hit = 0169 d_hit = 0170 d_miss = 0171 i_replace = 0172 d_replace = 0173 copy_back = 0174 wt = 0175 wa = 0176 blocksize = int(info[0])177 words = blocksize / 4178 set_no1 = int(int(c_size[2]) / (blocksize * associativity_no))179 set_no2 = int(int(c_size[0]) / (blocksize * associativity_no))180 lru1 = []181 lru2 = []182 for k in range(set_no1):183 temp = []184 lru1.append(temp)185 for k in range(set_no2):186 temp = []187 lru2.append(temp)188 inp = input()189 while inp != "":190 request = inp.split()191 if request[0] == '0' or request[0] == '1':192 tag = int(get_address(request[1]) / block_size)193 set_address = int(tag % set_no1)194 d = 'x'195 if check_lru(lru1[set_address], str(tag)):196 for i in lru1[set_address][:]:197 for i in lru1[set_address][:]:198 if str(tag) in i:199 d = i.get(str(tag))200 lru1[set_address].remove(i)201 if request[0] == '1' and writing_policy == 'wb':202 d = 'd'203 lru1[set_address].append({str(tag): d})204 # print("hit")205 if request[0] == '0' or request[0] == '1':206 d_hit += 1207 if request[0] == '1':208 wt += 1209 # print(lru)210 else:211 cell = {str(tag): 'c'}212 if len(lru1[set_address]) < associativity_no:213 if request[0] == '1':214 if allocation == 'wa':215 lru1[set_address].append({str(tag): 'd'})216 elif request[0] == '0':217 lru1[set_address].append(cell)218 # print("miss")219 if request[0] == '0' or request[0] == '1':220 d_miss += 1221 if request[0] == '1':222 wt += 1223 if allocation == 'nw':224 wa += 1225 # print(lru)226 else:227 t = lru1[set_address].pop(0)228 li = list(t.values())229 if li[0] == 'd':230 copy_back += 1231 if request[0] == '1':232 if allocation == 'wa':233 lru1[set_address].append({str(tag): 'd'})234 else:235 lru1[set_address].append(cell)236 # print("miss")237 if request[0] == '0' or request[0] == '1':238 d_miss += 1239 d_replace += 1240 if request[0] == '1':241 wt += 1242 if allocation == 'nw':243 wa += 1244 # print(lru)245 elif request[0] == '2':246 tag = int(get_address(request[1]) / block_size)247 set_address = int(tag % set_no2)248 if str(tag) in lru2[set_address]:249 for i in lru2[set_address][:]:250 for i in lru2[set_address][:]:251 if i == str(tag):252 lru2[set_address].remove(i)253 # lru[set_address].remove(str(tag))254 lru2[set_address].append(str(tag))255 # print("hit")256 i_hit += 1257 else:258 if len(lru2[set_address]) < associativity_no:259 lru2[set_address].append(str(tag))260 # print("miss1")261 i_miss += 1262 # print(lru[set_address])263 else:264 lru2[set_address].pop(0)265 lru2[set_address].append(str(tag))266 # print("miss2")267 i_miss += 1268 i_replace += 1269 # print(lru[set_address])270 inp = input()271 for i in lru1:272 for j in i:273 l = list(j.values())274 copy_back += l.count('d')275 output1(cache_info[2], c_size, int(cache_info[4]), block_size, cache_info[6], cache_info[8])276 output2(d_hit + d_miss, d_miss, d_replace, i_miss + i_hit, i_miss, i_replace, words, copy_back, wt, wa)277input1 = input()278cache_size = input()279cache_split = cache_size.split()280cache_info = input1.split()281block_size = int(cache_info[0])282associativity = int(cache_info[4])283writing_policy = cache_info[6]284allocation = cache_info[8]285split = int(cache_info[2])286# if associativity == 1:287# direct_mapped(cache_info, cache_size)288# else:289if len(cache_split) == 1:290 unified_cache(cache_info, int(cache_split[0]), associativity)291else:...
aam.py
Source:aam.py
1# aam.py2#3# add all mistakes: adds a number [mis of #] to each line that doesn't have it4#5import i76import sys7import os8import re9from collections import defaultdict10from shutil import copy11from filecmp import cmp12proj = 'ai'13def usage():14 print("-a / -q = all opts (copy, no dif, fill/reorder)")15 print("-c / -nc = copy over / don't, default =", on_off[copy_back])16 print("-d / -nd = show differences / don't, default =", on_off[difs])17 print("-co / -do / -oc / -od = only copy/show differences, not both")18 print("-f / -fr / -rf = fill and reorder, trumps other options (-nr/-rn turns it off)", on_off[reorder])19 print("-m(#) = maximum number of errors to ignore before reassigning numbers to mistakes. mn = max notify. Default = {:d}".format(max_errs))20 print(" 0 = always reassign, -1 (or x) = never")21 exit()22def my_mistake(a):23 x = a.split('"')24 return x[1]25def change_mis(my_str, my_num):26 return re.sub("(\[[^\]]*\])?\"\)", "[mis of {:d}]\")".format(my_num), my_str, 0)27def insert_num(my_str, my_num): # this may be more complex in the future28 return re.sub("\"\)", "[mis of {:d}]\")".format(my_num), my_str, 0)29def num_of(a):30 temp = re.sub(".*mis of ", "", a)31 temp = re.sub("\].*", "", temp)32 try:33 return int(temp)34 except:35 return 036def mistake_check(reord):37 line_count = 038 bail_after = False39 old_school_yet = False40 local_copy_back = True41 cur_num = (0 if reord else x)42 filre = ['fill', 'reorder']43 fout = open(mis2, "w", newline='\n')44 with open(mis) as file:45 for (line_count, line) in enumerate(file, 1):46 if 'volume old school' in line:47 old_school_yet = True48 print("Ignoring all past line", line_count)49 if old_school_yet is False:50 if re.search("^understand.*as a mistake", line):51 if not re.search("\) +when", line) and "[okall]" not in line: print("NEED-WHEN WARNING line", line_count, "needs conditional when or [okall].")52 if re.search("mis of [0-9]+", line) and not re.search("mis of [0-9]+\]\"", line):53 bail_after = True54 print("ERROR: 'mis of' syntax needs quote after parenthesis in line", line_count)55 # print(reord, line_count, line)56 if reord:57 cur_num += 158 line = change_mis(line, cur_num)59 else:60 if not re.search("mis of [0-9]+", line):61 cur_num += 162 line = insert_num(line, cur_num)63 elif re.search("is a list of truth state", line):64 line = "checkoffs is a list of truth states variable. checkoffs is {{ {:s} }}.\n".format(', '.join(['false'] * cur_num))65 fout.write(line)66 fout.close()67 if bail_after: sys.exit("Fix mistakes to rerun.")68 print("RESULTS FOR", filre[reord], "operations........")69 if difs:70 if cmp(mis, mis2):71 print("No changes", mis, "vs", mis2 + ". No compare shown.")72 else:73 print("Comparing")74 os.system("wm \"{:s}\" \"{:s}\"".format(mis, mis2))75 if copy_back:76 if not local_copy_back:77 print("Not copying back. Fix bugs first.")78 if cmp(mis, mis2):79 print("No changes needed in mistakes file. Not copying over.")80 else:81 print("Copying back modified file.")82 copy(mis2, mis)83 elif not cmp(mis, mis2):84 print("Run -c to copy changes over.")85on_off = ['off', 'on']86difs = True87copy_back = False88count = 189reorder = False90max_err_default = 591max_errs = max_err_default92max_errs_not = 2093while count < len(sys.argv):94 arg = sys.argv[count]95 if arg[0] == '-': arg = arg[1:]96 if arg == 'a' or arg == 'q':97 copy_back = True98 difs = False99 reorder = True100 elif arg == 'c': copy_back = True101 elif arg == 'nc': copy_back = False102 elif arg == 'co' or arg == 'oc':103 copy_back = True104 difs = False105 elif arg == 'd': difs = True106 elif arg == 'do' or arg == 'od':107 copy_back = False108 difs = True109 elif arg == 'nd': difs = False110 elif arg == 'r' or arg == 'fr' or arg == 'f': reorder = True111 elif arg == 'nr' or arg == 'rn': reorder = False112 elif arg == 'mx': max_errs = -1113 elif arg[:2] == 'm-': sys.exit("Instead of {:s}, try mx to disable rearrangement regardless of the number of errors.".format(arg))114 elif arg[:2] == 'mn': max_errs_not = int(arg[2:])115 elif arg[0] == 'm':116 try:117 if len(arg[0]) > 1: max_errs = int(arg[0][1:])118 else: max_errs = int(sys.argv[count+1])119 except:120 sys.exit("Need positive number argument after m, or mx (alone) to disable reshuffling.")121 else:122 usage()123 count += 1124got = defaultdict(bool)125mis = i7.mifi(proj)126mis2 = i7.sdir(proj) + "\\temp.i7x"127# mis2 = mis + '2'128last_num_of = 0129last_mist = ""130this_mist = ""131errs = 0132with open(mis) as file:133 for (line_count, line) in enumerate(file, 1):134 if line.startswith("volume old school verbs"):135 break136 if line.startswith("understand"):137 nol = num_of(line)138 if nol in got.keys() and nol > 0:139 print("WARNING", nol, "pops up twice in mistake file.")140 errs += 1141 got[nol] = True142 this_mist = my_mistake(line)143 if nol - last_num_of != 1:144 if (errs <= max_errs_not or max_errs_not == 0):145 if nol:146 print("WARNING bad " + ("start at" if last_num_of == 0 else "delta from {:s} {:d} to".format(last_mist, last_num_of)), this_mist, nol)147 else:148 print("WARNING blank number for", this_mist, nol)149 errs += 1150 last_num_of = nol151 last_mist = this_mist152 elif line.startswith("u") and 'mistake' in line:153 print("******** Line {:d} has understand-typo ********".format(line_count))154 print("************ FIX BEFORE CONTINUING ************".format(line_count))155 i7.npo(mis, line_count, True)156 exit()157if len(got.keys()) > 0:158 x = max(got, key=int)159 skips = 0160 for i in range(1, x+1):161 if i not in got.keys():162 skips += 1163 if skips == 11:164 print("Skipping all remaining notifications...")165 elif skips <= 10:166 if skips == 1: print("LIST OF SKIPPED NUMBERED CUES IN FILE E.G. MIS OF ###")167 print(skips, "Skipped", i, "in mistake cues.")168 print("maximum value of", x, "in mistake cues")169else:170 print("First run...")171if max_errs > -1 and errs > max_errs and not reorder:172 print("Forcing reorder since there are more than", max_errs, "numbering errors: to be precise,", errs)173 reorder = True174if max_errs_not and errs > max_errs_not: print("Got", errs, "errors but only listed", max_errs_not)175if not reorder and errs > 0:176 if max_errs > 0:177 print("Use -f to reorder fully. Only found", errs, "out of", max_errs, "errors necessary for automatic reorder.")178 else:179 print("Use -f to reorder fully. There are", errs, "errors to reorder.")180mistake_check(reorder)...
copy_cspider_sql_json_to_spider.py
Source:copy_cspider_sql_json_to_spider.py
1import json2import copy3def copy_back(correct_sql, spider_sql):4 # copy back the values in 'having' clause of the SPIDER entry5 for hv_idx in range(len(spider_sql['having'])):6 if isinstance(spider_sql['having'][hv_idx], str):7 assert isinstance(correct_sql['having'][hv_idx], str)8 continue9 if isinstance(spider_sql['having'][hv_idx][3], dict):10 assert isinstance(correct_sql['having'][hv_idx][3], dict)11 correct_sql['having'][hv_idx][3] = copy_back(copy.deepcopy(correct_sql['having'][hv_idx][3]),12 copy.deepcopy(spider_sql['having'][hv_idx][3]))13 elif isinstance(spider_sql['having'][hv_idx][3], list):14 pass15 else:16 correct_sql['having'][hv_idx][3] = copy.deepcopy(spider_sql['having'][hv_idx][3])17 if isinstance(spider_sql['having'][hv_idx][4], dict):18 assert isinstance(correct_sql['having'][hv_idx][4], dict)19 correct_sql['having'][hv_idx][4] = copy_back(copy.deepcopy(correct_sql['having'][hv_idx][4]),20 copy.deepcopy(spider_sql['having'][hv_idx][4]))21 elif isinstance(spider_sql['having'][hv_idx][4], list):22 pass23 else:24 correct_sql['having'][hv_idx][4] = copy.deepcopy(spider_sql['having'][hv_idx][4])25 for wh_idx in range(len(spider_sql['where'])):26 if isinstance(spider_sql['where'][wh_idx], str):27 assert isinstance(correct_sql['where'][wh_idx], str)28 continue29 if isinstance(spider_sql['where'][wh_idx][3], dict):30 assert isinstance(correct_sql['where'][wh_idx][3], dict)31 correct_sql['where'][wh_idx][3] = copy_back(copy.deepcopy(correct_sql['where'][wh_idx][3]),32 copy.deepcopy(spider_sql['where'][wh_idx][3]))33 elif isinstance(spider_sql['where'][wh_idx][3], list):34 pass35 else:36 correct_sql['where'][wh_idx][3] = copy.deepcopy(spider_sql['where'][wh_idx][3])37 if isinstance(spider_sql['where'][wh_idx][4], dict):38 assert isinstance(correct_sql['where'][wh_idx][4], dict)39 correct_sql['where'][wh_idx][4] = copy_back(copy.deepcopy(correct_sql['where'][wh_idx][4]),40 copy.deepcopy(spider_sql['where'][wh_idx][4]))41 elif isinstance(spider_sql['where'][wh_idx][4], list):42 pass43 else:44 correct_sql['where'][wh_idx][4] = copy.deepcopy(spider_sql['where'][wh_idx][4])45 if spider_sql['intersect'] is not None:46 assert spider_sql['union'] is None and spider_sql['except'] is None47 assert correct_sql['intersect'] is not None and \48 correct_sql['union'] is None and correct_sql['except'] is None49 correct_sql['intersect'] = copy_back(copy.deepcopy(correct_sql['intersect']),50 copy.deepcopy(spider_sql['intersect']))51 if spider_sql['union'] is not None:52 assert spider_sql['intersect'] is None and spider_sql['except'] is None53 assert correct_sql['union'] is not None and \54 correct_sql['intersect'] is None and correct_sql['except'] is None55 correct_sql['union'] = copy_back(copy.deepcopy(correct_sql['union']),56 copy.deepcopy(spider_sql['union']))57 if spider_sql['except'] is not None:58 assert spider_sql['intersect'] is None and spider_sql['union'] is None59 assert correct_sql['except'] is not None and \60 correct_sql['intersect'] is None and correct_sql['union'] is None61 correct_sql['except'] = copy_back(copy.deepcopy(correct_sql['except']),62 copy.deepcopy(spider_sql['except']))63 return correct_sql64def main():65 with open('./spider/spider/dev.json', 'r') as fp:66 spider_jsons = json.load(fp)67 with open('cspider/dev.json', 'r') as fp:68 cspider_jsons = json.load(fp)69 new_spider_jsons = []70 for e_idx in range(len(spider_jsons)):71 spider_entry = spider_jsons[e_idx]72 cspider_entry = cspider_jsons[e_idx]73 if spider_entry['query'] != cspider_entry['query']:74 print('idx: ', e_idx)75 assert len(spider_entry['sql']['having']) == len(cspider_entry['sql']['having'])76 assert len(spider_entry['sql']['where']) == len(cspider_entry['sql']['where'])77 correct_sql = copy.deepcopy(cspider_entry['sql'])78 correct_sql = copy_back(copy.deepcopy(correct_sql), copy.deepcopy(spider_entry['sql']))79 spider_entry['sql'] = copy.deepcopy(correct_sql)80 new_spider_jsons.append(spider_entry)81 with open('./spider/spider/dev_withc.json', 'w') as fp:82 json.dump(new_spider_jsons, fp, indent=4)83if __name__ == '__main__':...
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!!