How to use raiser method in Behave

Best Python code snippet using behave

script_eval.py

Source:script_eval.py Github

copy

Full Screen

...97 **kwargs)98def _CastToBigNum(s, err_raiser):99 v = bitcoin.core._bignum.vch2bn(s)100 if len(s) > MAX_NUM_SIZE:101 raise err_raiser(EvalScriptError, 'CastToBigNum() : overflow')102 return v103def _CastToBool(s):104 for i in range(len(s)):105 sv = _bord(s[i])106 if sv != 0:107 if (i == (len(s) - 1)) and (sv == 0x80):108 return False109 return True110 return False111def _CheckSig(sig, pubkey, script, txTo, inIdx, err_raiser):112 key = bitcoin.core.key.CECKey()113 key.set_pubkey(pubkey)114 if len(sig) == 0:115 return False116 hashtype = _bord(sig[-1])117 sig = sig[:-1]118 # Raw signature hash due to the SIGHASH_SINGLE bug119 #120 # Note that we never raise an exception if RawSignatureHash() returns an121 # error code. However the first error code case, where inIdx >=122 # len(txTo.vin), shouldn't ever happen during EvalScript() as that would123 # imply the scriptSig being checked doesn't correspond to a valid txout -124 # that should cause other validation machinery to fail long before we ever125 # got here.126 (h, err) = RawSignatureHash(script, txTo, inIdx, hashtype)127 return key.verify(h, sig)128def _CheckMultiSig(opcode, script, stack, txTo, inIdx, flags, err_raiser, nOpCount):129 i = 1130 if len(stack) < i:131 err_raiser(MissingOpArgumentsError, opcode, stack, i)132 keys_count = _CastToBigNum(stack[-i], err_raiser)133 if keys_count < 0 or keys_count > 20:134 err_raiser(ArgumentsInvalidError, opcode, "keys count invalid")135 i += 1136 ikey = i137 i += keys_count138 nOpCount[0] += keys_count139 if nOpCount[0] > MAX_SCRIPT_OPCODES:140 err_raiser(MaxOpCountError)141 if len(stack) < i:142 err_raiser(ArgumentsInvalidError, opcode, "not enough keys on stack")143 sigs_count = _CastToBigNum(stack[-i], err_raiser)144 if sigs_count < 0 or sigs_count > keys_count:145 err_raiser(ArgumentsInvalidError, opcode, "sigs count invalid")146 i += 1147 isig = i148 i += sigs_count149 if len(stack) < i-1:150 raise err_raiser(ArgumentsInvalidError, opcode, "not enough sigs on stack")151 elif len(stack) < i:152 raise err_raiser(ArgumentsInvalidError, opcode, "missing dummy value")153 # Drop the signature, since there's no way for a signature to sign itself154 #155 # Of course, this can only come up in very contrived cases now that156 # scriptSig and scriptPubKey are processed separately.157 for k in range(sigs_count):158 sig = stack[-isig - k]159 script = FindAndDelete(script, CScript([sig]))160 success = True161 while success and sigs_count > 0:162 sig = stack[-isig]163 pubkey = stack[-ikey]164 if _CheckSig(sig, pubkey, script, txTo, inIdx, err_raiser):165 isig += 1166 sigs_count -= 1167 ikey += 1168 keys_count -= 1169 if sigs_count > keys_count:170 success = False171 # with VERIFY bail now before we modify the stack172 if opcode == OP_CHECKMULTISIGVERIFY:173 err_raiser(VerifyOpFailedError, opcode)174 while i > 1:175 stack.pop()176 i -= 1177 # Note how Bitcoin Core duplicates the len(stack) check, rather than178 # letting pop() handle it; maybe that's wrong?179 if len(stack) and SCRIPT_VERIFY_NULLDUMMY in flags:180 if stack[-1] != b'':181 raise err_raiser(ArgumentsInvalidError, opcode, "dummy value not OP_0")182 stack.pop()183 if opcode == OP_CHECKMULTISIG:184 if success:185 stack.append(b"\x01")186 else:187 # FIXME: this is incorrect, but not caught by existing188 # test cases189 stack.append(b"\x00")190# OP_2MUL and OP_2DIV are *not* included in this list as they are disabled191_ISA_UNOP = {192 OP_1ADD,193 OP_1SUB,194 OP_NEGATE,195 OP_ABS,196 OP_NOT,197 OP_0NOTEQUAL,198}199def _UnaryOp(opcode, stack, err_raiser):200 if len(stack) < 1:201 err_raiser(MissingOpArgumentsError, opcode, stack, 1)202 bn = _CastToBigNum(stack[-1], err_raiser)203 stack.pop()204 if opcode == OP_1ADD:205 bn += 1206 elif opcode == OP_1SUB:207 bn -= 1208 elif opcode == OP_NEGATE:209 bn = -bn210 elif opcode == OP_ABS:211 if bn < 0:212 bn = -bn213 elif opcode == OP_NOT:214 bn = long(bn == 0)215 elif opcode == OP_0NOTEQUAL:216 bn = long(bn != 0)217 else:218 raise AssertionError("Unknown unary opcode encountered; this should not happen")219 stack.append(bitcoin.core._bignum.bn2vch(bn))220# OP_LSHIFT and OP_RSHIFT are *not* included in this list as they are disabled221_ISA_BINOP = {222 OP_ADD,223 OP_SUB,224 OP_BOOLAND,225 OP_BOOLOR,226 OP_NUMEQUAL,227 OP_NUMEQUALVERIFY,228 OP_NUMNOTEQUAL,229 OP_LESSTHAN,230 OP_GREATERTHAN,231 OP_LESSTHANOREQUAL,232 OP_GREATERTHANOREQUAL,233 OP_MIN,234 OP_MAX,235}236def _BinOp(opcode, stack, err_raiser):237 if len(stack) < 2:238 err_raiser(MissingOpArgumentsError, opcode, stack, 2)239 bn2 = _CastToBigNum(stack[-1], err_raiser)240 bn1 = _CastToBigNum(stack[-2], err_raiser)241 # We don't pop the stack yet so that OP_NUMEQUALVERIFY can raise242 # VerifyOpFailedError with a correct stack.243 if opcode == OP_ADD:244 bn = bn1 + bn2245 elif opcode == OP_SUB:246 bn = bn1 - bn2247 elif opcode == OP_BOOLAND:248 bn = long(bn1 != 0 and bn2 != 0)249 elif opcode == OP_BOOLOR:250 bn = long(bn1 != 0 or bn2 != 0)251 elif opcode == OP_NUMEQUAL:252 bn = long(bn1 == bn2)253 elif opcode == OP_NUMEQUALVERIFY:254 bn = long(bn1 == bn2)255 if not bn:256 err_raiser(VerifyOpFailedError, opcode)257 else:258 # No exception, so time to pop the stack259 stack.pop()260 stack.pop()261 return262 elif opcode == OP_NUMNOTEQUAL:263 bn = long(bn1 != bn2)264 elif opcode == OP_LESSTHAN:265 bn = long(bn1 < bn2)266 elif opcode == OP_GREATERTHAN:267 bn = long(bn1 > bn2)268 elif opcode == OP_LESSTHANOREQUAL:269 bn = long(bn1 <= bn2)270 elif opcode == OP_GREATERTHANOREQUAL:271 bn = long(bn1 >= bn2)272 elif opcode == OP_MIN:273 if bn1 < bn2:274 bn = bn1275 else:276 bn = bn2277 elif opcode == OP_MAX:278 if bn1 > bn2:279 bn = bn1280 else:281 bn = bn2282 else:283 raise AssertionError("Unknown binop opcode encountered; this should not happen")284 stack.pop()285 stack.pop()286 stack.append(bitcoin.core._bignum.bn2vch(bn))287def _CheckExec(vfExec):288 for b in vfExec:289 if not b:290 return False291 return True292def _EvalScript(stack, scriptIn, txTo, inIdx, flags=()):293 """Evaluate a script294 """295 if len(scriptIn) > MAX_SCRIPT_SIZE:296 raise EvalScriptError('script too large; got %d bytes; maximum %d bytes' %297 (len(scriptIn), MAX_SCRIPT_SIZE),298 stack=stack,299 scriptIn=scriptIn,300 txTo=txTo,301 inIdx=inIdx,302 flags=flags)303 altstack = []304 vfExec = []305 pbegincodehash = 0306 nOpCount = [0]307 for (sop, sop_data, sop_pc) in scriptIn.raw_iter():308 fExec = _CheckExec(vfExec)309 def err_raiser(cls, *args):310 """Helper function for raising EvalScriptError exceptions311 cls - subclass you want to raise312 *args - arguments313 Fills in the state of execution for you.314 """315 raise cls(*args,316 sop=sop,317 sop_data=sop_data,318 sop_pc=sop_pc,319 stack=stack, scriptIn=scriptIn, txTo=txTo, inIdx=inIdx, flags=flags,320 altstack=altstack, vfExec=vfExec, pbegincodehash=pbegincodehash, nOpCount=nOpCount[0])321 if sop in DISABLED_OPCODES:322 err_raiser(EvalScriptError, 'opcode %s is disabled' % OPCODE_NAMES[sop])323 if sop > OP_16:324 nOpCount[0] += 1325 if nOpCount[0] > MAX_SCRIPT_OPCODES:326 err_raiser(MaxOpCountError)327 def check_args(n):328 if len(stack) < n:329 err_raiser(MissingOpArgumentsError, sop, stack, n)330 if sop <= OP_PUSHDATA4:331 if len(sop_data) > MAX_SCRIPT_ELEMENT_SIZE:332 err_raiser(EvalScriptError,333 'PUSHDATA of length %d; maximum allowed is %d' %334 (len(sop_data), MAX_SCRIPT_ELEMENT_SIZE))335 elif fExec:336 stack.append(sop_data)337 continue338 elif fExec or (OP_IF <= sop <= OP_ENDIF):339 if sop == OP_1NEGATE or ((sop >= OP_1) and (sop <= OP_16)):340 v = sop - (OP_1 - 1)341 stack.append(bitcoin.core._bignum.bn2vch(v))342 elif sop in _ISA_BINOP:343 _BinOp(sop, stack, err_raiser)344 elif sop in _ISA_UNOP:345 _UnaryOp(sop, stack, err_raiser)346 elif sop == OP_2DROP:347 check_args(2)348 stack.pop()349 stack.pop()350 elif sop == OP_2DUP:351 check_args(2)352 v1 = stack[-2]353 v2 = stack[-1]354 stack.append(v1)355 stack.append(v2)356 elif sop == OP_2OVER:357 check_args(4)358 v1 = stack[-4]359 v2 = stack[-3]360 stack.append(v1)361 stack.append(v2)362 elif sop == OP_2ROT:363 check_args(6)364 v1 = stack[-6]365 v2 = stack[-5]366 del stack[-6]367 del stack[-5]368 stack.append(v1)369 stack.append(v2)370 elif sop == OP_2SWAP:371 check_args(4)372 tmp = stack[-4]373 stack[-4] = stack[-2]374 stack[-2] = tmp375 tmp = stack[-3]376 stack[-3] = stack[-1]377 stack[-1] = tmp378 elif sop == OP_3DUP:379 check_args(3)380 v1 = stack[-3]381 v2 = stack[-2]382 v3 = stack[-1]383 stack.append(v1)384 stack.append(v2)385 stack.append(v3)386 elif sop == OP_CHECKMULTISIG or sop == OP_CHECKMULTISIGVERIFY:387 tmpScript = CScript(scriptIn[pbegincodehash:])388 _CheckMultiSig(sop, tmpScript, stack, txTo, inIdx, flags, err_raiser, nOpCount)389 elif sop == OP_CHECKSIG or sop == OP_CHECKSIGVERIFY:390 check_args(2)391 vchPubKey = stack[-1]392 vchSig = stack[-2]393 tmpScript = CScript(scriptIn[pbegincodehash:])394 # Drop the signature, since there's no way for a signature to sign itself395 #396 # Of course, this can only come up in very contrived cases now that397 # scriptSig and scriptPubKey are processed separately.398 tmpScript = FindAndDelete(tmpScript, CScript([vchSig]))399 ok = _CheckSig(vchSig, vchPubKey, tmpScript, txTo, inIdx,400 err_raiser)401 if not ok and sop == OP_CHECKSIGVERIFY:402 err_raiser(VerifyOpFailedError, sop)403 else:404 stack.pop()405 stack.pop()406 if ok:407 if sop != OP_CHECKSIGVERIFY:408 stack.append(b"\x01")409 else:410 # FIXME: this is incorrect, but not caught by existing411 # test cases412 stack.append(b"\x00")413 elif sop == OP_CODESEPARATOR:414 pbegincodehash = sop_pc415 elif sop == OP_DEPTH:416 bn = len(stack)417 stack.append(bitcoin.core._bignum.bn2vch(bn))418 elif sop == OP_DROP:419 check_args(1)420 stack.pop()421 elif sop == OP_DUP:422 check_args(1)423 v = stack[-1]424 stack.append(v)425 elif sop == OP_ELSE:426 if len(vfExec) == 0:427 err_raiser(EvalScriptError, 'ELSE found without prior IF')428 vfExec[-1] = not vfExec[-1]429 elif sop == OP_ENDIF:430 if len(vfExec) == 0:431 err_raiser(EvalScriptError, 'ENDIF found without prior IF')432 vfExec.pop()433 elif sop == OP_EQUAL:434 check_args(2)435 v1 = stack.pop()436 v2 = stack.pop()437 if v1 == v2:438 stack.append(b"\x01")439 else:440 stack.append(b"")441 elif sop == OP_EQUALVERIFY:442 check_args(2)443 v1 = stack[-1]444 v2 = stack[-2]445 if v1 == v2:446 stack.pop()447 stack.pop()448 else:449 err_raiser(VerifyOpFailedError, sop)450 elif sop == OP_FROMALTSTACK:451 if len(altstack) < 1:452 err_raiser(MissingOpArgumentsError, sop, altstack, 1)453 v = altstack.pop()454 stack.append(v)455 elif sop == OP_HASH160:456 check_args(1)457 stack.append(bitcoin.core.serialize.Hash160(stack.pop()))458 elif sop == OP_HASH256:459 check_args(1)460 stack.append(bitcoin.core.serialize.Hash(stack.pop()))461 elif sop == OP_IF or sop == OP_NOTIF:462 val = False463 if fExec:464 check_args(1)465 vch = stack.pop()466 val = _CastToBool(vch)467 if sop == OP_NOTIF:468 val = not val469 vfExec.append(val)470 elif sop == OP_IFDUP:471 check_args(1)472 vch = stack[-1]473 if _CastToBool(vch):474 stack.append(vch)475 elif sop == OP_NIP:476 check_args(2)477 del stack[-2]478 elif sop == OP_NOP:479 pass480 elif sop >= OP_NOP1 and sop <= OP_NOP10:481 if SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS in flags:482 err_raiser(EvalScriptError, "%s reserved for soft-fork upgrades" % OPCODE_NAMES[sop])483 else:484 pass485 elif sop == OP_OVER:486 check_args(2)487 vch = stack[-2]488 stack.append(vch)489 elif sop == OP_PICK or sop == OP_ROLL:490 check_args(2)491 n = _CastToBigNum(stack.pop(), err_raiser)492 if n < 0 or n >= len(stack):493 err_raiser(EvalScriptError, "Argument for %s out of bounds" % OPCODE_NAMES[sop])494 vch = stack[-n-1]495 if sop == OP_ROLL:496 del stack[-n-1]497 stack.append(vch)498 elif sop == OP_RETURN:499 err_raiser(EvalScriptError, "OP_RETURN called")500 elif sop == OP_RIPEMD160:501 check_args(1)502 h = hashlib.new('ripemd160')503 h.update(stack.pop())504 stack.append(h.digest())505 elif sop == OP_ROT:506 check_args(3)507 tmp = stack[-3]508 stack[-3] = stack[-2]509 stack[-2] = tmp510 tmp = stack[-2]511 stack[-2] = stack[-1]512 stack[-1] = tmp513 elif sop == OP_SIZE:514 check_args(1)515 bn = len(stack[-1])516 stack.append(bitcoin.core._bignum.bn2vch(bn))517 elif sop == OP_SHA1:518 check_args(1)519 stack.append(hashlib.sha1(stack.pop()).digest())520 elif sop == OP_SHA256:521 check_args(1)522 stack.append(hashlib.sha256(stack.pop()).digest())523 elif sop == OP_SWAP:524 check_args(2)525 tmp = stack[-2]526 stack[-2] = stack[-1]527 stack[-1] = tmp528 elif sop == OP_TOALTSTACK:529 check_args(1)530 v = stack.pop()531 altstack.append(v)532 elif sop == OP_TUCK:533 check_args(2)534 vch = stack[-1]535 stack.insert(len(stack) - 2, vch)536 elif sop == OP_VERIFY:537 check_args(1)538 v = _CastToBool(stack[-1])539 if v:540 stack.pop()541 else:542 raise err_raiser(VerifyOpFailedError, sop)543 elif sop == OP_WITHIN:544 check_args(3)545 bn3 = _CastToBigNum(stack[-1], err_raiser)546 bn2 = _CastToBigNum(stack[-2], err_raiser)547 bn1 = _CastToBigNum(stack[-3], err_raiser)548 stack.pop()549 stack.pop()550 stack.pop()551 v = (bn2 <= bn1) and (bn1 < bn3)552 if v:553 stack.append(b"\x01")554 else:555 # FIXME: this is incorrect, but not caught by existing556 # test cases557 stack.append(b"\x00")558 else:559 err_raiser(EvalScriptError, 'unsupported opcode 0x%x' % sop)560 # size limits561 if len(stack) + len(altstack) > MAX_STACK_ITEMS:562 err_raiser(EvalScriptError, 'max stack items limit reached')563 # Unterminated IF/NOTIF/ELSE block564 if len(vfExec):565 raise EvalScriptError('Unterminated IF/ELSE block',566 stack=stack,567 scriptIn=scriptIn,568 txTo=txTo,569 inIdx=inIdx,570 flags=flags)571def EvalScript(stack, scriptIn, txTo, inIdx, flags=()):572 """Evaluate a script573 stack - Initial stack574 scriptIn - Script575 txTo - Transaction the script is a part of576 inIdx - txin index of the scriptSig...

Full Screen

Full Screen

ludwig.py

Source:ludwig.py Github

copy

Full Screen

1import re2from datetime import datetime3import matplotlib.pyplot as plt4import os5import glob6import numpy as np7def extract_shape_units(filename):8 with open(filename) as f:9 td = f.readlines()10 su_dates = []11 su = np.zeros((3, 121, len(td)))12 su_id = np.zeros((121, len(td)))13 for d, line in enumerate(td):14 data = line.split(';')15 pts = data[:-1]16 date = re.search('(.*)\r\n',data[-1]).groups()[0]17 su_dates.append((datetime.strptime(date, '%Y-%m-DD_%H:%M:%S:%f') - datetime(1970,1,1)).total_seconds())18 print(d)19 for i,pt in enumerate(pts):20 [id,x_coord, y_coord, z_coord] = re.search('ID: ([0-9]+), (.*) (.*) (.*) ', pt).groups()21 print(pt)22 su[0,i,:] = x_coord23 su[1,i,:] = y_coord24 su[2,i,:] = z_coord25 su_id[i, d] = id26 27 return [su, su_id, su_dates]28def plot_shape_units(su, filename):29 plt.clf()30 for i in range(121):31 plt.plot(su[0,i,:], su[2,i,:])32 # plt.plot(su[0,i,:], su[1,i,:], 'o')33 plt.savefig(filename)34# au_file = '/p/spoclab/data/Ludwig/ROBOT_DATA/Session2/2/AU_session-2_id-2_order-1_0.txt'35# [lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates] = ludwig.extract_animation_units(au_file)36def extract_animation_units(filename):37 lip_raiser_data = []38 jaw_lower_data = []39 lip_stretcher_data = []40 brow_lower_data = []41 lip_corner_depressor_data = []42 brow_raiser_data = []43 au_dates = []44 with open(filename) as f:45 au = f.readlines()46 for line in au:47 [id, lip_raiser, jaw_lower, lip_stretcher, brow_lower, lip_corner_depressor, brow_raiser, date]= re.search('ID: ([0-9]+), (.*) (.*) (.*) (.*) (.*) (.*) (.*)', line).groups()48 lip_raiser_data.append(float(lip_raiser))49 jaw_lower_data.append(float(jaw_lower))50 lip_stretcher_data.append(float(lip_stretcher))51 brow_lower_data.append(float(brow_lower))52 lip_corner_depressor_data.append(float(lip_corner_depressor))53 brow_raiser_data.append(float(brow_raiser))54 au_dates.append((datetime.strptime(date, '%Y-%m-DD_%H:%M:%S:%f') - datetime(1970,1,1)).total_seconds())55 return [lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates]56# robot_file = '/p/spoclab/data/Ludwig/ROBOT_DATA/Session2/2/RobotActions_session-2_id-2_order-1_0.txt'57# [utterances, actions, utterance_dates, action_dates] = ludwig.extract_robot_actions(robot_file)58def extract_robot_actions(filename):59 utterances = []60 actions = []61 utterance_dates = []62 action_dates = []63 with open(filename) as f:64 robot = f.readlines()65 for line in robot:66 [utterance, action, date] = re.search('Utterance: (.*), Action: (.*),(.*)\r\n', line).groups()67 if action != 'NULL':68 actions.append(action)69 action_dates.append((datetime.strptime(date, '%Y-%m-DD_%H:%M:%S:%f') - datetime(1970,1,1)).total_seconds())70 if utterance != 'NULL':71 utterances.append(utterance)72 utterance_dates.append((datetime.strptime(date, '%Y-%m-DD_%H:%M:%S:%f') - datetime(1970,1,1)).total_seconds())73 return [utterances, actions, utterance_dates, action_dates]74# ludwig.plot_au_with_actions(lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates,utterances, actions, utterance_dates, action_dates, 'test.png')75def plot_au_with_actions(lr, jl, ls, bl, lcd, br, au_dates, utt, act, utt_dates, act_dates, filename):76 f, axarr = plt.subplots(6, sharex=True)77 axarr[0].plot(au_dates, lr, 'y', zorder=1)78 axarr[0].set_title('Lip raiser')79 axarr[0].set_ylim([-1,1])80 axarr[1].plot(au_dates, jl, 'y', zorder=1)81 axarr[1].set_title('Jaw lower')82 axarr[1].set_ylim([-1,1])83 axarr[2].plot(au_dates, ls, 'y', zorder=1)84 axarr[2].set_title('Lip stretcher')85 axarr[2].set_ylim([-1,1])86 axarr[3].plot(au_dates, bl, 'y', zorder=1)87 axarr[3].set_title('Brow lower')88 axarr[3].set_ylim([-1,1])89 axarr[4].plot(au_dates, lcd, 'y', zorder=1)90 axarr[4].set_title('Lip corner depressor')91 axarr[4].set_ylim([-1,1])92 axarr[5].plot(au_dates, br, 'y', zorder=1)93 axarr[5].set_title('Brow raiser')94 axarr[5].set_ylim([-1,1])95 for utt in utt_dates:96 for i in range(6):97 axarr[i].axvline(x=utt, color='m', linewidth=2, clip_on=False, zorder=0)98 for act in act_dates:99 for i in range(6):100 axarr[i].axvline(x=act, color='m', linewidth=2, clip_on=False, zorder=0)101 plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)102 f.subplots_adjust(hspace=0.3)103 f.savefig(filename)104def plot_au(lr, jl, ls, bl, lcd, br, au_dates, filename):105 f, axarr = plt.subplots(6, sharex=True)106 axarr[0].plot(au_dates, lr, 'y')107 axarr[0].set_title('Lip raiser')108 axarr[0].set_ylim([-1,1])109 axarr[1].plot(au_dates, jl, 'y')110 axarr[1].set_title('Jaw lower')111 axarr[1].set_ylim([-1,1])112 axarr[2].plot(au_dates, ls, 'y')113 axarr[2].set_title('Lip stretcher')114 axarr[2].set_ylim([-1,1])115 axarr[3].plot(au_dates, bl, 'y')116 axarr[3].set_title('Brow lower')117 axarr[3].set_ylim([-1,1])118 axarr[4].plot(au_dates, lcd, 'y')119 axarr[4].set_title('Lip corner depressor')120 axarr[4].set_ylim([-1,1])121 axarr[5].plot(au_dates, br, 'y')122 axarr[5].set_title('Brow raiser')123 axarr[5].set_ylim([-1,1])124 plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)125 f.subplots_adjust(hspace=0.3)126 f.savefig(filename)127# session_directory = '/p/spoclab/data/Ludwig/ROBOT_DATA/Session2/'128def plot_au_and_actions_session2(session_directory):129 for id in os.listdir(session_directory):130 au_files = glob.glob(session_directory + str(id) + '/AU_session*')131 robot_files = glob.glob(session_directory + str(id) + '/RobotActions*')132 for au_file, robot_file in zip(au_files, robot_files):133 filename = re.search('(AU_.*)\.txt', au_file).groups()[0] + '.png'134 [lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates] = extract_animation_units(au_file)135 [utterances, actions, utterance_dates, action_dates] = extract_robot_actions(robot_file)136 plot_au_with_actions(lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates,utterances, actions, utterance_dates, action_dates, filename)137# session_directory = '/p/spoclab/data/Ludwig/ROBOT_DATA/Session1/'138def plot_au_session1(session_directory):139 for id in ['1', '11_1', '3', '5', '7', '9', '10_1', '2', '4', '6', '8']:140 au_files = glob.glob(session_directory + str(id) + '/AU_session*')141 for au_file in au_files:142 filename = re.search('(AU_.*)\.txt', au_file).groups()[0] + '.png'143 [lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates] = extract_animation_units(au_file)144 plot_au(lip_raiser_data, jaw_lower_data, lip_stretcher_data, brow_lower_data, lip_corner_depressor_data, brow_raiser_data, au_dates, filename)145def plot_su_session2(session_directory):146 for id in os.listdir(session_directory):147 su_files = glob.glob(session_directory + str(id) + '/TD_session*')148 for su_file in su_files:149 filename = re.search('(TD_.*)\.txt', su_file).groups()[0] + '.png'150 [su, su_dates] = extract_shape_units(su_file)151 plot_shape_units(su, filename)152def plot_su_session1(session_directory):153 for id in ['1', '11_1', '3', '5', '7', '9', '10_1', '2', '4', '6', '8']:154 su_files = glob.glob(session_directory + str(id) + '/TD_session*')155 156 for su_file in su_files:157 filename = re.search('(TD_.*)\.txt', su_file).groups()[0] + '.png'158 [su, su_dates] = extract_shape_units(su_file)159 plot_shape_units(su, filename)160def classify_robot_actions(robot_actions):161 actions = [];162 ACTION_WAVE = '/usr/robokind/etc/gui/anims/AZR25_handWave_01_5000.anim.xml'163 ACTION_HAPPY = '/mnt/alternate/milo/animations/misc-demo-factory/happy_02.rkanim'164 ACTION_LOOK_RIGHT = '/usr/robokind/etc/gui/anims/AZR25_LookRightShoulder_01.anim.xml'165 for action in robot_actions:166 if action == ACTION_WAVE:167 actions.append('WAVE')168 elif action == ACTION_HAPPY:169 actions.append('HAPPY')170 elif action == ACTION_LOOK_RIGHT:171 actions.append('LOOK_RIGHT')...

Full Screen

Full Screen

crowdfund.py

Source:crowdfund.py Github

copy

Full Screen

1from zkay.examples.scenario import ScenarioBuilder2from zkay.transaction.offchain import RequireException3raiser, backer1, backer2 = 'hospital', 'patient1', 'patient2'4sb = ScenarioBuilder('CrowdFundingSuccess', 'code/CrowdFunding.zkay').set_users(raiser, backer1, backer2)5# Set hospital as owner6sb.set_deployment_transaction(100, 3600, amount=20, owner=raiser)7sb.add_balance_assertion(20)8sb.add_state_assertion('pot_balance', user=raiser, should_decrypt=True, expected_value=20)9sb.add_state_assertion('pledged', raiser, user=raiser, should_decrypt=True, expected_value=20)10# Add some money to the contract11sb.add_transaction('fund', user=backer1, amount=300)12sb.add_transaction('fund', user=backer2, amount=2000)13sb.add_balance_assertion(2320)14sb.add_state_assertion('pot_balance', user=raiser, should_decrypt=True, expected_value=20)15sb.add_state_assertion('funds', backer1, user=backer1, should_decrypt=True, expected_value=300)16sb.add_state_assertion('funds', backer2, user=backer2, should_decrypt=True, expected_value=2000)17# Ooops, correct mistake18sb.add_transaction('retrieve_unpledged_funds', user=backer2)19sb.add_state_assertion('funds', backer2, user=backer2, should_decrypt=True, expected_value=0)20sb.add_balance_assertion(320)21sb.add_transaction('fund', user=backer2, amount=500)22sb.add_state_assertion('funds', backer2, user=backer2, should_decrypt=True, expected_value=500)23sb.add_balance_assertion(820)24# This should fail since nothing is pledged yet25sb.add_transaction('accept_pledge', user=raiser, expected_exception=RequireException)26# Pledge money 127sb.add_transaction('pledge', [50], user=backer1)28sb.add_state_assertion('funds', backer1, user=backer1, should_decrypt=True, expected_value=250)29sb.add_state_assertion('pledged', backer1, user=backer1, should_decrypt=True, expected_value=50)30# This should fail since pending31sb.add_transaction('pledge', [50], user=backer1, expected_exception=RequireException)32# Accept money 133sb.add_transaction('accept_pledge', user=raiser)34sb.add_balance_assertion(820)35sb.add_state_assertion('pot_balance', user=raiser, should_decrypt=True, expected_value=70)36sb.add_state_assertion('success', user=raiser, expected_value=False)37sb.add_state_assertion('closed', user=raiser, expected_value=False)38# Pledge money 239sb.add_transaction('pledge', [10], user=backer1)40sb.add_state_assertion('funds', backer1, user=backer1, should_decrypt=True, expected_value=240)41sb.add_state_assertion('pledged', backer1, user=backer1, should_decrypt=True, expected_value=60)42# Accept money 243sb.add_transaction('accept_pledge', user=raiser)44sb.add_balance_assertion(820)45sb.add_state_assertion('pot_balance', user=raiser, should_decrypt=True, expected_value=80)46sb.add_state_assertion('success', user=raiser, expected_value=False)47sb.add_state_assertion('closed', user=raiser, expected_value=False)48# Pledge money 349sb.add_transaction('pledge', [200], user=backer2)50sb.add_state_assertion('funds', backer2, user=backer2, should_decrypt=True, expected_value=300)51sb.add_state_assertion('pledged', backer2, user=backer2, should_decrypt=True, expected_value=200)52# Try to refund which is impossible since not closed without success53sb.add_transaction('request_refund', user=backer2, expected_exception=RequireException)54sb.add_transaction('accept_pledge', user=backer2, expected_exception=RequireException)55# Collection also not yet possible since not closed56sb.add_transaction('collect_pot', user=raiser, expected_exception=RequireException)57# Drain funds early58sb.add_transaction('retrieve_unpledged_funds', user=backer1)59sb.add_state_assertion('funds', backer1, user=backer1, should_decrypt=True, expected_value=0)60sb.add_state_assertion('pledged', backer1, user=backer1, should_decrypt=True, expected_value=60)61sb.add_balance_assertion(580)62# Accept money 363sb.add_transaction('accept_pledge', user=raiser)64sb.add_balance_assertion(580)65sb.add_state_assertion('pot_balance', user=raiser, should_decrypt=True, expected_value=280)66sb.add_state_assertion('success', user=raiser, expected_value=True)67sb.add_state_assertion('closed', user=raiser, expected_value=True)68# Drain funds69sb.add_transaction('retrieve_unpledged_funds', user=backer2)70sb.add_state_assertion('funds', backer2, user=backer2, should_decrypt=True, expected_value=0)71sb.add_state_assertion('pledged', backer2, user=backer2, should_decrypt=True, expected_value=200)72sb.add_balance_assertion(280)73# No you cannot steal and you cannot get out74sb.add_transaction('collect_pot', user=backer2, expected_exception=RequireException)75sb.add_transaction('refund_everyone', user=backer2, expected_exception=RequireException)76sb.add_transaction('request_refund', user=backer2, expected_exception=RequireException)77# Too late to close and refund78sb.add_transaction('refund_everyone', user=raiser, expected_exception=RequireException)79sb.add_state_assertion('pot_balance', user=raiser, should_decrypt=True, expected_value=280)80sb.add_balance_assertion(280)81sb.add_transaction('collect_pot', user=raiser)82sb.add_balance_assertion(0)83sb.add_transaction('request_refund', user=backer2, expected_exception=RequireException)84sb.add_transaction('collect_pot', user=raiser)85sb.add_balance_assertion(0)...

Full Screen

Full Screen

events.py

Source:events.py Github

copy

Full Screen

1"""2pox event handling3events maps communication from the OpenFlow datapaths (eg switches) to4the controller. This mapping is saved in a set of pox components able to5raise an event according to the incoming packet. The control program has6to specify a set of handlers (functions) to respond to events.7Multiple functions with different features (eg: priority) may be mapped8to the same event. An event handler is able to stop or forward the event9to the next handler (eg: packet filter)10OpenFlow list of event classes: pox/pox/openflow/__init__.py11Learn: 12 how to create an object able to raise events, create a new event class,13 how to setup handler priority (pox default priority in unspecified)14 how to stop an event using an handler15 how to set-up a One-time event,16 how to unsubscribe to an event17"""18from pox.core import core19from pox.lib.revent import Event, EventMixin, EventHalt20import time21from pprint import pformat # build debug strings22log = core.getLogger()23class EventName(Event):24 """event that can be raised by EventRaiser"""25 def __init__(self):26 """TODO: to be defined1. """27 Event.__init__(self)28class EventRaiser(EventMixin):29 """obj able to raise events"""30 _eventMixin_events = set([31 EventName,32 ])33 34def _handle_EventName(event):35 """EvenName handler function36 :event: revent.Event37 """38 log.debug("callback: _handle_EventName")39def _handle_EventName_urgent(event):40 """see addListener in the launch function for the priority41 :returns: optional block the event otherwise pass the 42 control to the next handler according to priority43 """44 log.debug("callback: _handle_EventName_urgent")45 # return EventHalt46 47def _handle_EventName_onetime(event):48 """see addListener in the launch function for once49 :event: revent.Event50 """51 log.debug("callback: _handle_EventName_onetime")52def launch():53 """54 TODO55 """56 57 raiser = EventRaiser()58 raiser_log = pformat(raiser._eventMixin_events, indent=4)59 log.debug("raiser: %s" % raiser_log)60 raiser_listeners_ids = {} # store info related to raiser listeners id61 # default priority is unknown, you can use negative priority62 # addListener returns a tuple63 event_class, handler_id = raiser.addListener(EventName, _handle_EventName, priority=0)64 raiser_listeners_ids['_handle_EventName'] = handler_id65 event_class, handler_id = raiser.addListener(EventName, _handle_EventName_urgent, priority=2)66 raiser_listeners_ids['_handle_EventName_urgent'] = handler_id67 log.debug("event_class: %r" % (event_class))68 log.debug("handler_id: %r" % (handler_id))69 event_class, handler_id = raiser.addListener(EventName, _handle_EventName_onetime,70 once=True, priority=-1)71 raiser_listeners_ids['_handle_EventName_onetime'] = handler_id72 for x in range(3):73 log.info("raiser raised EventName")74 raiser.raiseEvent(EventName)75 time.sleep(1)76 log.info("Removed _handle_EventName_urgent subscription to core.openflow's EventName")77 rc = raiser.removeListener(raiser_listeners_ids['_handle_EventName_urgent'])78 for x in range(3):79 raiser.raiseEvent(EventName)...

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 Behave 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