How to use replace_template method in gabbi

Best Python code snippet using gabbi_python

linear_optimizer.py

Source:linear_optimizer.py Github

copy

Full Screen

...34 template = [base_op(), types.Verify()]35 optimizations.append((template, [op()]))36 for template, replacement in optimizations:37 callback = lambda values, replacement=replacement: replacement38 instructions.replace_template(template, callback)39@peephole40def replace_repeated_ops(instructions):41 """Replace repeated opcodes with single opcodes."""42 optimizations = [43 # OP_DROP OP_DROP -> OP_2DROP44 ([types.Drop(), types.Drop()], [types.TwoDrop()]),45 ]46 for template, replacement in optimizations:47 callback = lambda values, replacement=replacement: replacement48 instructions.replace_template(template, callback)49@peephole50def optimize_stack_ops(instructions):51 """Optimize stack operations."""52 for template, replacement in [53 # OP_1 OP_PICK -> OP_OVER54 ([types.One(), types.Pick()], [types.Over()]),55 # OP_1 OP_ROLL OP_DROP -> OP_NIP56 ([types.One(), types.Roll(), types.Drop()], [types.Nip()]),57 # OP_0 OP_PICK -> OP_DUP58 ([types.Zero(), types.Pick()], [types.Dup()]),59 # OP_0 OP_ROLL -> _60 ([types.Zero(), types.Roll()], []),61 # OP_1 OP_ROLL OP_1 OP_ROLL -> _62 ([types.One(), types.Roll(), types.One(), types.Roll()], []),63 # OP_1 OP_ROLL -> OP_SWAP64 ([types.One(), types.Roll()], [types.Swap()]),65 # OP_NIP OP_DROP -> OP_2DROP66 ([types.Nip(), types.Drop()], [types.TwoDrop()]),67 # OP_OVER OP_OVER -> OP_2DUP68 ([types.Over(), types.Over()], [types.TwoDup()]),69 ]:70 callback = lambda values, replacement=replacement: replacement71 instructions.replace_template(template, callback)72@peephole73def replace_shortcut_ops(instructions):74 """Replace opcodes with a corresponding shortcut form."""75 optimizations = []76 # Replace division by 2.77 # OP_2 OP_DIV -> OP_2DIV78 optimizations.append(([types.Two(), types.Div()], lambda values: [types.Div2()]))79 # Replace subtraction by 1.80 # OP_1 OP_SUB -> OP_1SUB81 optimizations.append(([types.One(), types.Sub()], lambda values: [types.Sub1()]))82 # Replace 1 * -1 with -1.83 # OP_1 OP_NEGATE -> OP_1NEGATE84 optimizations.append(([types.One(), types.Negate()], lambda values: [types.NegativeOne()]))85 # Replace addition by 1.86 # OP_1 OP_ADD -> OP_1ADD87 for permutation in permutations([types.Push(), types.One()]) + permutations([types.SmallIntOpCode(), types.One()]):88 idx = 0 if not isinstance(permutation[0], types.One) else 189 optimizations.append((permutation + [types.Add()], lambda values, idx=idx: [values[idx], types.Add1()]))90 optimizations.append(([types.Assumption(), types.One(), types.Add()], lambda values: [values[0], types.Add1()]))91 # Replace multiplication by 2.92 # OP_2 OP_MUL -> OP_2MUL93 for permutation in permutations([types.Push(), types.Two()]) + permutations([types.SmallIntOpCode(), types.Two()]):94 idx = 0 if not isinstance(permutation[0], types.Two) else 195 optimizations.append((permutation + [types.Mul()], lambda values, idx=idx: [values[idx], types.Mul2()]))96 optimizations.append(([types.Assumption(), types.Two(), types.Mul()], lambda values: [values[0], types.Mul2()]))97 for template, callback in optimizations:98 instructions.replace_template(template, callback, strict=False)99@peephole100def replace_null_ops(instructions):101 """Replace operations that do nothing."""102 # Remove subtraction by 0.103 # OP_0 OP_SUB -> _104 optimizations = [([types.Zero(), types.Sub()], lambda values: [])]105 # Remove addition by 0.106 # OP_0 OP_ADD -> _107 for permutation in permutations([None, types.Zero()]):108 idx = 0 if permutation[0] is None else 1109 optimizations.append((permutation + [types.Add()], lambda values, idx=idx: [values[idx]]))110 for template, callback in optimizations:111 instructions.replace_template(template, callback)112@peephole113def optimize_dup_and_checksig(instructions):114 for template, callback in [115 ([types.Dup(), None, types.CheckSig()], lambda values: values[1:]),116 ]:117 instructions.replace_template(template, callback)118@peephole119def optimize_hashes(instructions):120 for template, replacement in [121 # OP_SHA256 OP_SHA256 -> OP_HASH256122 ([types.Sha256(), types.Sha256()], [types.Hash256()]),123 # OP_SHA256 OP_RIPEMD160 -> OP_HASH160124 ([types.Sha256(), types.RipeMD160()], [types.Hash160()]),125 ]:126 callback = lambda values, replacement=replacement: replacement127 instructions.replace_template(template, callback)128@peephole129def use_arithmetic_ops(instructions):130 """Replace ops with more convenient arithmetic ops."""131 optimizations = []132 _two_values = permutations([types.SmallIntOpCode(), types.Push()])133 _two_values.append([types.SmallIntOpCode()] * 2)134 _two_values.append([types.Push()] * 2)135 def all_strict_nums(numbers):136 """Evaluate whether instances represent strict numbers."""137 return all(formats.is_strict_num(i) for i in map(LInstructions.instruction_to_int, numbers))138 # Use NUMNOTEQUAL if both values are numbers.139 def numnotequal_callback(values):140 if not all_strict_nums(values[0:2]):141 return values142 return values[0:2] + [types.NumNotEqual()]143 for permutation in _two_values:144 optimizations.append((permutation + [types.Equal(), types.Not()], numnotequal_callback))145 for template, callback in optimizations:146 instructions.replace_template(template, callback, strict=False)147@peephole148def remove_trailing_verifications(instructions):149 """Remove any trailing OP_VERIFY occurrences.150 A trailing OP_VERIFY is redundant since a truthy value151 is required for a script to pass.152 """153 while len(instructions) and isinstance(instructions[-1], types.Verify):154 instructions.pop(-1)155@peephole156def promote_return(instructions):157 """Place any OP_RETURN occurrence at the beginning of the script."""158 # Get the indices of all OP_RETURN occurrences.159 occurrences = instructions.find_occurrences(types.Return())160 if not occurrences or occurrences == [0]:161 return162 map(instructions.pop, reversed(occurrences))163 instructions.insert(0, types.Return())164@peephole165def use_small_int_opcodes(instructions):166 """Convert data pushes to equivalent small integer opcodes."""167 def convert_push(push):168 push = push[0]169 try:170 i = formats.bytearray_to_int(push.data)171 return [types.small_int_opcode(i)()]172 except TypeError:173 pass174 return [push]175 instructions.replace_template([types.Push()], convert_push, strict=False)176@peephole177def shorten_commutative_operations(instructions):178 """Remove ops that change the order of commutative operations."""179 optimizations = []180 for op in [types.Add(), types.Mul(), types.BoolAnd(), types.BoolOr(),181 types.NumEqual(), types.NumEqualVerify(), types.NumNotEqual(),182 types.Min(), types.Max(),183 types.And(), types.Or(), types.Xor(), types.Equal(), types.EqualVerify(),184 ]:185 template = [types.Swap(), op]186 optimizations.append((template, lambda values: values[1:]))187 for template, callback in optimizations:188 instructions.replace_template(template, callback)189@peephole190def remove_null_conditionals(instructions):191 """Replace empty conditionals with an op that consumes the test value."""192 # OP_ELSE OP_ENDIF -> OP_ENDIF193 instructions.replace_template([types.Else(), types.EndIf()], lambda values: [types.EndIf()])194 # OP_IF OP_ENDIF -> OP_DROP195 instructions.replace_template([types.If(), types.EndIf()], lambda values: [types.Drop()])196@peephole197def replace_not_if(instructions):198 # OP_NOT OP_IF -> OP_NOTIF199 instructions.replace_template([types.Not(), types.If()], lambda values: [types.NotIf()])200class PeepholeOptimizer(object):201 """Performs peephole optimization on the linear IR."""202 MAX_PASSES = 5203 def __init__(self, enabled=True):204 self.enabled = enabled205 def optimize(self, instructions, max_passes=-1):206 if not self.enabled:207 return208 if max_passes == -1:209 max_passes = self.MAX_PASSES210 pass_number = 0211 while 1:212 if pass_number > max_passes:213 break...

Full Screen

Full Screen

pcollections.py

Source:pcollections.py Github

copy

Full Screen

1# Submitter: yihanx2(Xu, Yihan)2# Partner : zihaog(Gao, Zihao)3# We certify that we worked cooperatively on this programming4# assignment, according to the rules for pair programming5import re, traceback, keyword67def pnamedtuple(type_name, field_names, mutable=False):8 def show_listing(s):9 for i, l in enumerate(s.split('\n'),1):10 print('{num: >3} {txt}'.format(num = i, txt = l.rstrip()))11 if type(type_name) != str:12 raise SyntaxError13 legal_bool1 = re.match('^[(a-z)(A-Z)]([\w\d(_\w)]+)?$', type_name)14 if legal_bool1 == None:15 raise SyntaxError16 elif legal_bool1 != None:17 if type_name in keyword.kwlist:18 raise SyntaxError19 20 if type(field_names) == list:21 for names in field_names:22 legal_bool2 = re.match('^[(a-z)(A-Z)]([\w\d(_\w)]+)?$', names)23 if legal_bool2 == None:24 raise SyntaxError25 elif legal_bool2 != None:26 if names in keyword.kwlist:27 raise SyntaxError28 29 elif type(field_names) == str:30 if ',' in field_names:31 field_names = field_names.replace(' ', '')32 field_names = field_names.split(',')33 for names in field_names:34 legal_bool3 = re.match('^[(a-z)(A-Z)]([\w\d(_\w)]+)?$', names)35 if legal_bool3 == None:36 raise SyntaxError37 elif legal_bool3 != None:38 if names in keyword.kwlist:39 raise SyntaxError 40 else:41 field_names = field_names.split(' ')42 for i in field_names:43 if i == ' ':44 field_names.remove(i)45 for names in field_names:46 legal_bool3 = re.match('^[(a-z)(A-Z)]([\w\d(_\w)]+)?$', names)47 if legal_bool3 == None:48 raise SyntaxError49 elif legal_bool3 != None:50 if names in keyword.kwlist:51 raise SyntaxError52 else:53 raise SyntaxError 54 l1 = []55 for names in field_names:56 if names not in l1:57 l1.append(names)58 field_names = l159 60 class_name_template = '''\61class {type_name}:\n'''62 63 def gen_init(field_names):64 init_template = '''\65 def __init__(self'''66 for i in field_names:67 init_template += ',' + str(i)68 init_template += '):\n'69 for i in field_names:70 init_template += ' self.' + str(i) + '=' + str(i) + '\n'71 init_template += ' self._fields = '+ str(field_names)+ '\n'72 init_template += ' self._mutable = '+ str(mutable)+ '\n'73 return init_template74 75 def gen_repr(type_name, field_names):76 repr_template = '''\77 def __repr__(self):\n'''78 repr_template += ' return ' + "'"+type_name + "('"79 for i in field_names:80 repr_template += '+str(' +"'"+ i +"'"+ ')+"="+str('+'self.' + str(i)+ ')+","'81 repr_template = repr_template[:-4] + "+')'" + '\n'82 return repr_template83 84 def gen_get(field_names):85 get_template = ''86 for i in field_names:87 get_template += ' def get_' + str(i) + '(self): \n return self.' + str(i)+'\n'88 return get_template89 90 def gen_getitem(type_name, field_names):91 getitem_template = ' def __getitem__(self, int_str):\n'92 for i in field_names:93 getitem_template += ' if int_str ==' +"'" + str(i) + "'" +':\n' 94 getitem_template += ' return ' + type_name + '.get_' + str(i) +'(self)' +'\n'95 getitem_template += ' if int_str ==' + str(field_names.index(i)) + ':\n'96 getitem_template += ' return ' + 'self.' + str(i) + '\n'97 getitem_template += ' else:\n' 98 getitem_template += ' raise IndexError\n'99 return getitem_template 100 101 def gen_eq(type_name, field_names):102 eq_template = ' def __eq__(self, target):\n'103 eq_template += ' if type(target) is ' + type_name + ' and ' + 'len(target._fields) == len(self._fields): \n' 104 for i in range(len(field_names)):105 eq_template += ' if self[' + str(i) + ']' + '!= target[' + str(i) + ']:\n'106 eq_template += ' return False\n'107 eq_template += ' return True\n'108 eq_template += ' return False\n'109 return eq_template110 111 def gen_replace(type_name, field_names):112 replace_template = ' def _replace(self, **kargs):\n'113 replace_template += ' for keys, values in kargs.items():\n'114 replace_template += ' if keys not in self._fields:\n'115 replace_template += ' raise TypeError\n'116 replace_template += ' if self._mutable == True:\n'117 replace_template += ' for keys, values in kargs.items():\n'118 replace_template += ' self.__dict__[keys] = values\n'119 replace_template += ' if self._mutable == False:\n'120 replace_template += ' new_class = '+ type_name + '(' 121 for i in field_names:122 replace_template += 'self[' + "'" + str(i)+ "'" +'],' 123 replace_template = replace_template[:-1] + ')\n'124 replace_template += ' for keys, values in kargs.items():\n'125 replace_template += ' new_class.__dict__[keys] = values\n'126 replace_template += ' return new_class\n'127 return replace_template128 129 def gen_setatt(field_names):130 setatt_template = ' def __setattr__(self,name,value):\n'131 setatt_template += ' if "_mutable" in self.__dict__:\n'132 setatt_template += ' if self._mutable == False:\n '133 setatt_template += ' if "_mutable" not in self.__dict__ or "_fields" not in self.__dict__ or'134 for i in field_names:135 setatt_template += "'"+str(i)+"'"+ ' not in self.__dict__ or '136 setatt_template = setatt_template[:-4] + ':\n'137 setatt_template += ' self.__dict__[name] = value\n'138 setatt_template += ' else:\n'139 setatt_template += ' raise AttributeError\n'140 setatt_template += ' else:\n'141 setatt_template += ' self.__dict__[name] = value\n'142 setatt_template += ' else:\n'143 setatt_template += ' self.__dict__[name] = value'144 return setatt_template145 146 class_definition = \147 class_name_template.format(type_name = type_name) + gen_init(field_names) + gen_repr(type_name, field_names) + gen_get(field_names) + gen_getitem(type_name, field_names) + gen_eq(type_name, field_names) + gen_replace(type_name,field_names) + gen_setatt(field_names)148 149150 151 152 153 154 155 156157 # put your code here158 # bind class_definition (used below) to the string constructed for the class159160161162 # For initial debugging, always show the source code of the class163 #show_listing(class_definition)164 165 # Execute the class_definition string in a local namespace and bind the166 # name source_code in its dictionary to the class_defintion; return the167 # class object created; if there is a syntax error, list the class and168 # show the error169 name_space = dict(__name__='pnamedtuple_{type_name}'.format(type_name=type_name))170 try:171 exec(class_definition, name_space)172 name_space[type_name].source_code = class_definition173 except(SyntaxError, TypeError):174 show_listing(class_definition)175 traceback.print_exc()176 return name_space[type_name]177 178if __name__ == '__main__':179 import driver180 driver.driver()181 x = pnamedtuple('Point', 'x y', mutable=False) ...

Full Screen

Full Screen

app_cfg.py

Source:app_cfg.py Github

copy

Full Screen

...116 'resetpassword',117 reset_password_form='ksweb.lib.forms.ResetPasswordForm',118 new_password_form='ksweb.lib.forms.NewPasswordForm')119# from tgext.pluggable import replace_template120# replace_template(base_config,121# 'resetpassword.templates.index',122# 'ksweb.templates.resetpassword.index')123plug(base_config, 'userprofile')124# replace_template(base_config, 'registration.templates.register', 'ksweb.templates.registration.register')125# replace_template(base_config, 'userprofile.templates.index', 'ksweb.templates.userprofile.index')126def replace_profile_form_layout():127 from axf.bootstrap import BootstrapFormLayout128 from userprofile.lib import UserForm129 # UserForm.child = BootstrapFormLayout(children=UserForm.child.children)130 UserForm.submit.css_class = 'btn btn-success'...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run gabbi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful