Best Python code snippet using robotframework
compiler.py
Source:compiler.py
...565 return (lexpos - line_start) + 1566parser = yacc.yacc()567source_text += "\n"568parser.parse(source_text)569def is_var(thing):570 if not isinstance(thing, str):571 return thing572 if thing == "TRUE":573 return "1"574 if thing == "FALSE":575 return "0"576 if "tmp_" in thing:577 return "r"+(thing.replace("tmp_", ""))578 if thing[-1] == "]":579 m = re.search(r"\[(.*)\]", thing)580 t = m.group(1)581 m = re.search(r"(.*)\[.*\]", thing)582 thing = m.group(1)+"+"+t583 return "["+thing+"]"584def var_type(size):585 if size == 1:586 return "DB"587 else:588 return ".space {}".format(size)589def jump_type(comp):590 op = ["!=", "==", ">=", "<=", ">", "<"]591 ret = ["jnz", "jz", "jge", "jle", "jg", "jl"]592 return ret[op.index(comp)]593def quad_to_asm_jump(j):594 if j == "BZ":595 return "jz"596 elif j == "BGE":597 return "jge"598def quad_to_asm_op(o):599 op = ["+", "-", "*", "/"]600 ret = ["add", "sub", "mul", "div"]601 return ret[op.index(o)]602def asm(quads):603 output2 = []604 output2.append("section .data")605 for name, value in table_symbols._symbols.items():606 output2.append(name+" "+var_type(value.size))607 output2.append("section .start")608 output = []609 labels = []610 i = 0611 label_counter = 1612 for quad in quads:613 if quad[0] == "=":614 if not is_var(quad[1]) and type(quad[1]) is str:615 output.append([i, "mov {}, '{}'".format(is_var(quad[3]), quad[1])])616 else:617 output.append([i, "mov {}, {}".format(is_var(quad[3]), is_var(quad[1]))])618 elif quad[0] in ["+", "-", "/", "*"]:619 if quad[1] == quad[3]:620 output.append([i, "mov rax, {}".format(is_var(quad[3]))])621 if quad[2] == 1:622 if quad[0] == "-":623 output.append([i, "dec rax"])624 elif quad[0] == "+":625 output.append([i, "inc rax"])626 else:627 output.append([i, "{} rax, {}".format(quad_to_asm_op(quad[0]), is_var(quad[2]))])628 output.append([i, "mov {}, rax".format(is_var(quad[3]))])629 else:630 output.append([i, "mov {}, {}".format(is_var(quad[3]), is_var(quad[1]))])631 output.append([i, "{} {}, {}".format(quad_to_asm_op(quad[0]), is_var(quad[3]), is_var(quad[2]))])632 elif quad[0] in ["!=", "==", ">=", "<=", "<", ">"]:633 output.append([i, "mov {}, {}".format(is_var(quad[3]), is_var(quad[1]))])634 output.append([i, "sub {}, {}".format(is_var(quad[3]), is_var(quad[2]))])635 output.append([i, "cmp {}, 0".format(is_var(quad[3]))])636 output.append([i, "{} .label_{}".format(jump_type(quad[0]), label_counter)])637 output.append([i, "mov {}, 0".format(is_var(quad[3]))])638 output.append([i, "jmp .label_{}".format(label_counter+1)])639 output.append([i, ".label_{}".format(label_counter)])640 output.append([i, "mov {}, 1".format(is_var(quad[3]))])641 output.append([i, ".label_{}".format(label_counter+1)])642 label_counter += 2643 elif quad[0] in ["AND", "OR"]:644 output.append([i, "mov {}, {}".format(is_var(quad[3]), is_var(quad[1]))])645 output.append([i, "{} {}, {}".format(quad[0].lower(), is_var(quad[3]), is_var(quad[2]))])646 elif quad[0] == "BZ":647 output.append([i, "cmp {}, 0".format(is_var(quad[2]))])648 output.append([i, "{} .label_{}".format(quad_to_asm_jump(quad[0]), label_counter)])649 labels.append([quad[1], label_counter])650 label_counter += 1651 elif quad[0] == "BGE":652 output.append([i, "cmp {}, {}".format(is_var(quad[2]), is_var(quad[3]))])653 output.append([i, "{} .label_{}".format(quad_to_asm_jump(quad[0]), label_counter)])654 labels.append([quad[1], label_counter])655 label_counter += 1656 elif quad[0] == "BR":657 output.append([i, "jmp .label_{}".format(label_counter)])658 labels.append([quad[1], label_counter])659 label_counter += 1660 i += 1661 output.append([output[-1][0]+1, "END"])662 for inst in output:663 to_delete = []664 for k, label in enumerate(labels):665 if label[0] == inst[0]:666 output2.append(".label_{}".format(label[1]))...
stereo_project.py
Source:stereo_project.py
...171 penalty = 0.172 for row in range(disparity.shape[0]):173 for col in range(disparity.shape[1]):174 n = (disparity.shape[1] * row) + col175 if is_var(varsA[n]):176 col = varsA[n]["cord"]177 a = varsA[n]["alpha"]178 D = squared_dissimilarity(left_img, right_img, col, (col[0], int(col[1] + a))) - K179 g.add_tedge(varsAnodes[n], D, 0)180 if varsA[n] == VAR_ALPHA:181 col = (row, col)182 a = alpha183 D = squared_dissimilarity(left_img, right_img, col, (col[0], int(col[1] + a))) - K184 penalty += D185 if is_var(varsO[n]):186 col = varsO[n]["cord"]187 a = varsO[n]["alpha"]188 D = squared_dissimilarity(left_img, right_img, col, (col[0], int(col[1] + a))) - K189 g.add_tedge(varsOnodes[n], 0, D)190 for row in range(disparity.shape[0]):191 for col in range(disparity.shape[1]):192 i1 = (disparity.shape[1] * row) + col193 if is_var(varsO[i1]) and is_var(varsA[i1]):194 forbid01(g, varsOnodes[i1], varsAnodes[i1])195 ia = int(varsO[i1]["alpha"])196 c2 = col + ia - alpha197 i2 = (disparity.shape[1] * row) + c2198 forbid01(g, varsOnodes[i1], varsAnodes[i2])199 indices = (col, row)200 if indices[0] != disparity.shape[1] - 1:201 r2 = row202 c2 = col + (1)203 if c2 + alpha < disparity.shape[1]:204 i2 = (disparity.shape[1] * r2) + c2205 pen = K / 5206 d1 = int(left_img[row, col] - left_img[r2, c2])207 d2 = int(right_img[row, col + alpha] - right_img[r2, c2 + alpha])208 if max(d1, d2) < 8:209 pen *= 3.210 if is_var(varsA[i1]):211 if is_var(varsA[i2]):212 pairwise_term(g, varsAnodes[i1], varsAnodes[i2], 0, pen, pen, 0) # add term213 if is_var(varsO[i1]):214 if is_var(varsO[i2]):215 pairwise_term(g, varsAnodes[i1], varsAnodes[i2], 0, pen, pen, 0) # add term216 if is_var(varsA[i1]) and varsA[i2] == VAR_ALPHA:217 g.add_tedge(varsAnodes[i1], 0, pen)218 if is_var(varsA[i2]) and varsA[i1] == VAR_ALPHA:219 g.add_tedge(varsAnodes[i2], 0, pen)220 if is_var(varsO[i1]) and not is_var(varsO[i2]):221 g.add_tedge(varsOnodes[i1], 0, pen)222 if is_var(varsO[i2]) and not is_var(varsO[i1]):223 g.add_tedge(varsOnodes[i2], 0, pen)224 if indices[1] != disparity.shape[0] - 1:225 r2 = row + 1226 c2 = col227 if c2 + alpha < disparity.shape[1]:228 i2 = (disparity.shape[1] * r2) + c2229 pen = K / 5230 d1 = int(left_img[row, col] - left_img[r2, c2])231 d2 = int(right_img[row, col + alpha] - right_img[r2, c2 + alpha])232 if max(d1, d2) < 8:233 pen *= 3.234 if is_var(varsA[i1]):235 if is_var(varsA[i2]):236 pairwise_term(g, varsAnodes[i1], varsAnodes[i2], 0, pen, pen,237 0)238 if is_var(varsO[i1]):239 if is_var(varsO[i2]):240 pairwise_term(g, varsAnodes[i1], varsAnodes[i2], 0, pen, pen,241 0)242 if is_var(varsA[i1]) and varsA[i2] == VAR_ALPHA:243 g.add_tedge(varsAnodes[i1], 0, pen)244 if is_var(varsA[i2]) and varsA[i1] == VAR_ALPHA:245 g.add_tedge(varsAnodes[i2], 0, pen)246 if is_var(varsO[i1]) and not is_var(varsO[i2]):247 g.add_tedge(varsOnodes[i1], 0, pen)248 if is_var(varsO[i2]) and not is_var(varsO[i1]):249 g.add_tedge(varsOnodes[i2], 0, pen)250 flow = g.maxflow()251 energy = flow + penalty252 if energy < prev_e:253 prev_e = energy254 for row in range(disparity.shape[0]):255 for col in range(disparity.shape[1]):256 i = (disparity.shape[1] * row) + col257 if varsOnodes[i] != -1 and g.get_segment(varsOnodes[i]) == 1:258 disparity[row, col] = np.inf259 if varsAnodes[i] != -1 and g.get_segment(varsAnodes[i]) == 1:260 disparity[row, col] = alpha261 return handle_occlusion_scale(disparity)262def pairwise_term(g, n1, n2, A, B, C, D):263 g.add_tedge(n1, D, B)264 g.add_tedge(n2, 0, A - B)265 g.add_edge(n1, n2, 0, B + C - A - D)266def forbid01(g, n1, n2):267 g.add_edge(n1, n2, sys.maxsize, 0)268def is_var(v):269 return v != VAR_ALPHA and v != VAR_ABSENT270def calculate_k(alphaRange, image1, image2):271 K = int(alphaRange / 4)272 s = 0273 i = 0274 for r in range(alphaRange, image1.shape[0] - alphaRange):275 for c in range(alphaRange, image2.shape[1] - alphaRange):276 i += 1277 da_s = [squared_dissimilarity(image1, image2, (r, c), (r, c + alpha)) for alpha in range(alphaRange)]278 da_s.sort()279 s += da_s[K]280 return int(s / i)281def squared_dissimilarity(image1, image2, p1, p2):282 return (image1[p1] - image2[p2]) ** 2
interpret_grammar.py
Source:interpret_grammar.py
...11 # ignore the interpretation symbols 12 s = int_strip(s)13 pattern = fullmatch('u[0-9]*',s)14 return bool(pattern)15def is_var(s):16 # detect if string is a variable name, such as 'x12' (x followed by optional number)17 # ignore the interpretation symbols 18 s = int_strip(s)19 pattern = fullmatch('x[0-9]*',s)20 return bool(pattern)21def int_strip(s):22 # strip the interpretation symbols from a string23 s = s.replace('[','')24 s = s.replace(']','')25 return s26def to_interpet(s):27 # does s still need interpretation?28 return s[0] == '[' and s[-1] == ']'29class Grammar():30 max_recursion = 50 # maximum number of recursive calls31 count_recursion = 0 # recursive counters32 rules = []33 def __init__(self,rules,list_prims):34 # rules is a list of Rule objects35 # list_prims : list of primitive symbols36 self.rules = deepcopy(rules)37 for r in self.rules:38 r.set_primitives(list_prims)39 self.var_regexp = self.rules[-1].var_regexp #MAJOR HACK40 def apply(self,s, max_recursion_count=50):41 self.max_recursion = max_recursion_count42 self.count_recursion = 043 x = self.__apply_helper(s)44 # if self.count_recursion >= self.max_recursion:45 # print(x)46 return x47 def __apply_helper(self,s, return_list=False):48 self.count_recursion += 149 valid = []50 myrule = None51 for r in self.rules:52 valid.append(r.applies(s))53 # if np.count_nonzero(valid) != 1: # check that only one rule applies54 # assert False55 if not any(valid):56 return s57 myrule = self.rules[valid.index(True)]58 # run 'apply' recursively59 out = myrule.apply(s)60 for idx,o in enumerate(out):61 if to_interpet(o) and self.count_recursion < self.max_recursion:62 # print("WARNING: recursion depth exceeded")63 # break64 out[idx] = self.__apply_helper(int_strip(o))65 if return_list: 66 return out67 else:68 return ' '.join(out)69 def __str__(self):70 s = ''71 for r in self.rules:72 s += str(r)+'\n'73 return s74 def apply_once(self, s):75 self.max_recursion = 176 self.count_recursion = 077 return self.__apply_helper(s, return_list=True)78 def apply_repl(self, s, max_recursion_count=50):79 self.max_recursion = max_recursion_count80 self.count_recursion = 081 return self.__apply_helper_repl(s)82 def __apply_helper_repl(self, s, return_list=False):83 self.count_recursion += 184 valid = []85 myrule = None86 for r in self.rules:87 valid.append(r.applies(' '.join(s)))88 # if np.count_nonzero(valid) != 1: # check that only one rule applies89 # assert False90 if not any(valid):91 #print("no valid rules for", s)92 if fullmatch(self.var_regexp, ' '.join(s)):93 #if self.count_recursion == 1:94 # pass95 #else:96 return ['['] + s + [']'] #['[' + ' '.join(s) + ']']97 return s98 myrule = self.rules[valid.index(True)]99 # run 'apply' recursively100 out = myrule.apply(' '.join(s))101 for idx,o in enumerate(out):102 if to_interpet(o) and self.count_recursion < self.max_recursion:103 #if not self.count_recursion < self.max_recursion:104 # print(f'max recursion of {self.max_recursion} exceeded for miniscan repl')105 # import pdb; pdb.set_trace()106 out[idx] = self.__apply_helper_repl(int_strip(o).split(' '))107 else:108 out[idx] = o.split(' ')109 #if return_list: 110 return [token for oo in out for token in oo]111 #else:112 #return ' '.join(out)113 114class Rule():115 # left-hand-side116 LHS_str = ''117 LHS_list = []118 LHS_regexp = ''119 # right-hand-side120 RHS_str = ''121 RHS_list = []122 # 123 valid_rule = False124 var_regexp = '([ a-zA-Z0-9]+)'125 # var_regexp = '([ a-z]+)' # define acceptable string for a variable to hold126 127 def __init__(self,LHS,RHS):128 # LHS : string with variables (no interpretation symbols [ or ] )129 # RHS : string with variables (can have interpretation symbols for recursive computation)130 self.LHS_str = LHS131 self.LHS_list = LHS.split()132 self.RHS_str = RHS133 self.RHS_list = RHS.split()134 # self.RHS_list = split_special(RHS) 135 def set_primitives(self,list_prims):136 # list_prims : list of the primitive symbols137 self.list_prims = list_prims138 self.prim_regexp = '(' + '|'.join(self.list_prims) + ')' # define acceptable string for a primitive139 self.var_regexp = '([(' + '|'.join(self.list_prims + [' ']) + ')]+)'140 #print("hit this guy")141 #print(self.prim_regexp)142 #print(self.var_regexp)143 # get list of all variables in LHS144 self.vars = [v for v in self.LHS_list if is_prim(v) or is_var(v)]145 146 # sanity check 147 rhs_vars = [int_strip(v) for v in self.RHS_list if is_prim(v) or is_var(v)]148 self.valid_rule = all([v in self.vars for v in rhs_vars])149 # Compute the regexp for checking whether the rule is active150 mylist = deepcopy(self.LHS_list)151 for i,x in enumerate(mylist):152 if is_prim(x):153 mylist[i] = self.prim_regexp154 elif is_var(x):155 mylist[i] = self.var_regexp156 self.LHS_regexp = ' '.join(mylist)157 def applies(self,s, var_consistancy=False):158 # return True if the re-write rule applies to this string159 if not var_consistancy:160 return self.valid_rule and bool(fullmatch(self.LHS_regexp,s))161 else:162 if not self.valid_rule: return False163 m = fullmatch(self.LHS_regexp,s)164 if not bool(m): return False165 mygroups = m.groups()166 if not len(mygroups) == len(self.vars): return False167 vdict = dict(zip(self.vars,mygroups))168 for var, group in zip(self.vars, mygroups):169 if vdict[var] != group: return False170 return True171 def apply(self,s, var_consistancy=False):172 # apply rule to string s173 assert self.applies(s)174 assert self.valid_rule175 # if not self.valid_rule:176 # print(self)177 # assert False178 # extract variables from LHS179 m = fullmatch(self.LHS_regexp,s)180 #import pdb; pdb.set_trace()181 # if the expression has two variables "x1 x2", it returns the first split #TODO for var consistency182 mygroups = m.groups()183 assert(len(mygroups) == len(self.vars)), f"{mygroups}, {self.vars}, s={s}, rule={str(self)}"184 vdict = dict(zip(self.vars,mygroups))185 if var_consistancy:186 for var, group in zip(self.vars, mygroups):187 if vdict[var] != group: assert False188 # replace RHS with variable values189 mylist = deepcopy(self.RHS_list)190 for i,x in enumerate(mylist):191 if is_var(x) or is_prim(x):192 #import pdb; pdb.set_trace()193 mylist[i] = x.replace(int_strip(x), vdict[int_strip(x)])194 return mylist195 def __str__(self):196 if self.valid_rule:197 val_tag = ''198 else:199 val_tag = ' (invalid)'200 return str(self.LHS_str) + ' -> ' + str(self.RHS_str) + val_tag201if __name__ == "__main__":202 203 myrules = [Rule('walk','WALK'), Rule('u left','LTURN [u]'), Rule('x twice','[x] [x]')]204 G = Grammar(myrules,['walk','left'])205 print(G.apply('walk left twice'))206 print('Testing variable detector..')207 assert is_var('x')208 assert is_var('x0')209 assert is_var('x10')210 assert not is_var('X10')211 assert not is_var('10x')212 assert not is_var('y10')213 assert not is_var(' x10')214 assert not is_var('x10 ')...
alu.py
Source:alu.py
1VAR_W = 02VAR_X = 13VAR_Y = 24VAR_Z = 35class ALUSyntaxError(Exception):6 pass7class ALURuntimError(Exception):8 pass9class ALUEmulator:10 def __init__(self):11 self._vars = [0, 0, 0, 0]12 self.debug = False13 def set_debug(self, on_off):14 self.debug = on_off15 def exec(self, src_line, func, *args):16 if (self.debug):17 a = self.vars18 func(*args)19 b = self.vars20 print(f"DEBUG: {src_line:10s} {a} -> {b}")21 else:22 func(*args)23 @property24 def vars(self):25 return tuple(self._vars)26 @property27 def w(self):28 return self._vars[VAR_W]29 @property30 def x(self):31 return self._vars[VAR_X]32 @property33 def y(self):34 return self._vars[VAR_Y]35 @property36 def z(self):37 return self._vars[VAR_Z]38 def inp(self, var, value):39 self._vars[var] = value40 def add(self, arg1, arg2, is_var):41 self._vars[arg1] += self._vars[arg2] if is_var else arg242 def mul(self, arg1, arg2, is_var):43 self._vars[arg1] *= self._vars[arg2] if is_var else arg244 def div(self, arg1, arg2, is_var):45 right = self._vars[arg2] if is_var else arg246 self._vars[arg1] //= self._vars[arg2] if is_var else arg247 def mod(self, arg1, arg2, is_var):48 left = self._vars[arg1]49 right = self._vars[arg2] if is_var else arg250 self._vars[arg1] %= right51 def eql(self, arg1, arg2, is_var):52 compare_to = self._vars[arg2] if is_var else arg253 self._vars[arg1] = int(self._vars[arg1] == compare_to)54class ALUProgram():55 def __init__(self):56 self.instructions = []57 def add_instruction(self, instruction):58 self.instructions.append(instruction)59 def run(self, *args):60 alu = ALUEmulator()61 try:62 for instruction in self.instructions:63 args = instruction(alu, args)64 except IndexError:65 raise ALURuntimError("Not enough inputs provided for program")66 return alu.vars67class ALUCompiler:68 """The ALUCompiler can be used to translate ALU source code into69 a working ALU program."""70 def compile(self, src):71 """Compiles lines of source code into an ALU program."""72 program = ALUProgram()73 for line in src:74 src_line = line.strip()75 line = src_line76 if ";" in line:77 line = line[:line.index(";")]78 parts = line.lower().split()79 if not parts:80 continue81 instruction = None82 cmd = parts.pop(0)83 if cmd == "dbg":84 on_off = bool(parts.pop())85 instruction = self.make_dbg_instruction(src_line, on_off)86 elif cmd == "inp":87 var = self.get_var(line, parts)88 instruction = self.make_inp_instruction(src_line, var)89 elif cmd == "add":90 arg1 = self.get_var(line, parts)91 arg2, is_var = self.get_var_or_int(line, parts)92 instruction = self.make_add_instruction(src_line, arg1, arg2, is_var)93 elif cmd == "mul":94 arg1 = self.get_var(line, parts)95 arg2, is_var = self.get_var_or_int(line, parts)96 instruction = self.make_mul_instruction(src_line, arg1, arg2, is_var)97 elif cmd == "div":98 arg1 = self.get_var(line, parts)99 arg2, is_var = self.get_var_or_int(line, parts)100 instruction = self.make_div_instruction(src_line, arg1, arg2, is_var)101 elif cmd == "mod":102 arg1 = self.get_var(line, parts)103 arg2, is_var = self.get_var_or_int(line, parts)104 instruction = self.make_mod_instruction(src_line, arg1, arg2, is_var)105 elif cmd == "eql":106 arg1 = self.get_var(line, parts)107 arg2, is_var = self.get_var_or_int(line, parts)108 instruction = self.make_eql_instruction(src_line, arg1, arg2, is_var)109 else:110 raise ALUSyntaxError("Unknown operation:", line)111 if parts:112 raise ALUSyntaxError("Too many arguments:", line)113 program.add_instruction(instruction)114 return program115 def get_var_or_int(self, line, parts):116 try:117 value = int(parts[0])118 parts.pop(0)119 return value, False120 except (ValueError, IndexError):121 var = self.get_var(line, parts)122 return var, True123 def get_var(self, line, parts):124 if not parts:125 raise ALUSyntaxError("Missing argument(s):", line)126 name = parts.pop(0)127 if name == "w": return VAR_W128 if name == "x": return VAR_X129 if name == "y": return VAR_Y130 if name == "z": return VAR_Z131 raise ALUSyntaxError(f"Unknown variable name '{name}' used: {line}")132 def make_dbg_instruction(self, src_line, on_off):133 def instruction_(alu, args):134 alu.set_debug(on_off)135 return args136 return instruction_137 def make_inp_instruction(self, src_line, var):138 def instruction_(alu, args):139 value, args = args[0], args[1:]140 alu.exec(src_line, alu.inp, var, value)141 return args142 return instruction_143 def make_add_instruction(self, src_line, arg1, arg2, is_var):144 def instruction_(alu, args):145 alu.exec(src_line, alu.add, arg1, arg2, is_var)146 return args147 return instruction_148 def make_mul_instruction(self, src_line, arg1, arg2, is_var):149 def instruction_(alu, args):150 alu.exec(src_line, alu.mul, arg1, arg2, is_var)151 return args152 return instruction_153 def make_div_instruction(self, src_line, arg1, arg2, is_var):154 def instruction_(alu, args):155 alu.exec(src_line, alu.div, arg1, arg2, is_var)156 return args157 return instruction_158 def make_mod_instruction(self, src_line, arg1, arg2, is_var):159 def instruction_(alu, args):160 alu.exec(src_line, alu.mod, arg1, arg2, is_var)161 return args162 return instruction_163 def make_eql_instruction(self, src_line, arg1, arg2, is_var):164 def instruction_(alu, args):165 alu.exec(src_line, alu.eql, arg1, arg2, is_var)166 return args...
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!!