How to use evaluate_handle method in Playwright Python

Best Python code snippet using playwright-python

test_element_handle.py

Source:test_element_handle.py Github

copy

Full Screen

...117def test_content_frame_for_non_iframes(page, server, utils):118 page.goto(server.EMPTY_PAGE)119 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)120 frame = page.frames[1]121 element_handle = frame.evaluate_handle("document.body")122 assert element_handle.content_frame() is None123def test_content_frame_for_document_element(page, server, utils):124 page.goto(server.EMPTY_PAGE)125 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)126 frame = page.frames[1]127 element_handle = frame.evaluate_handle("document.documentElement")128 assert element_handle.content_frame() is None129def test_owner_frame(page, server, utils):130 page.goto(server.EMPTY_PAGE)131 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)132 frame = page.frames[1]133 element_handle = frame.evaluate_handle("document.body")134 assert element_handle.owner_frame() == frame135def test_owner_frame_for_cross_process_iframes(page, server, utils):136 page.goto(server.EMPTY_PAGE)137 utils.attach_frame(page, "frame1", server.CROSS_PROCESS_PREFIX + "/empty.html")138 frame = page.frames[1]139 element_handle = frame.evaluate_handle("document.body")140 assert element_handle.owner_frame() == frame141def test_owner_frame_for_document(page, server, utils):142 page.goto(server.EMPTY_PAGE)143 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)144 frame = page.frames[1]145 element_handle = frame.evaluate_handle("document")146 assert element_handle.owner_frame() == frame147def test_owner_frame_for_iframe_elements(page, server, utils):148 page.goto(server.EMPTY_PAGE)149 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)150 frame = page.main_frame151 element_handle = frame.evaluate_handle('document.querySelector("#frame1")')152 print(element_handle)153 assert element_handle.owner_frame() == frame154def test_owner_frame_for_cross_frame_evaluations(page, server, utils):155 page.goto(server.EMPTY_PAGE)156 utils.attach_frame(page, "frame1", server.EMPTY_PAGE)157 frame = page.main_frame158 element_handle = frame.evaluate_handle(159 'document.querySelector("#frame1").contentWindow.document.body'160 )161 assert element_handle.owner_frame() == frame.child_frames[0]162def test_owner_frame_for_detached_elements(page, server):163 page.goto(server.EMPTY_PAGE)164 div_handle = page.evaluate_handle(165 """() => {166 div = document.createElement('div');167 document.body.appendChild(div);168 return div;169 }"""170 )171 assert div_handle.owner_frame() == page.main_frame172 page.evaluate(173 """() => {174 div = document.querySelector('div')175 document.body.removeChild(div)176 }"""177 )178 assert div_handle.owner_frame() == page.main_frame179def test_click(page, server):180 page.goto(server.PREFIX + "/input/button.html")181 button = page.query_selector("button")182 button.click()183 assert page.evaluate("result") == "Clicked"184def test_click_with_node_removed(page, server):185 page.goto(server.PREFIX + "/input/button.html")186 page.evaluate('delete window["Node"]')187 button = page.query_selector("button")188 button.click()189 assert page.evaluate("result") == "Clicked"190def test_click_for_shadow_dom_v1(page, server):191 page.goto(server.PREFIX + "/shadow.html")192 button_handle = page.evaluate_handle("button")193 button_handle.click()194 assert page.evaluate("clicked")195def test_click_for_TextNodes(page, server):196 page.goto(server.PREFIX + "/input/button.html")197 buttonTextNode = page.evaluate_handle('document.querySelector("button").firstChild')198 buttonTextNode.click()199 assert page.evaluate("result") == "Clicked"200def test_click_throw_for_detached_nodes(page, server):201 page.goto(server.PREFIX + "/input/button.html")202 button = page.query_selector("button")203 page.evaluate("button => button.remove()", button)204 with pytest.raises(Error) as exc_info:205 button.click()206 assert "Element is not attached to the DOM" in exc_info.value.message207def test_click_throw_for_hidden_nodes_with_force(page, server):208 page.goto(server.PREFIX + "/input/button.html")209 button = page.query_selector("button")210 page.evaluate('button => button.style.display = "none"', button)211 with pytest.raises(Error) as exc_info:212 button.click(force=True)213 assert "Element is not visible" in exc_info.value.message214def test_click_throw_for_recursively_hidden_nodes_with_force(page, server):215 page.goto(server.PREFIX + "/input/button.html")216 button = page.query_selector("button")217 page.evaluate('button => button.parentElement.style.display = "none"', button)218 with pytest.raises(Error) as exc_info:219 button.click(force=True)220 assert "Element is not visible" in exc_info.value.message221def test_click_throw_for__br__elements_with_force(page, server):222 page.set_content("hello<br>goodbye")223 br = page.query_selector("br")224 with pytest.raises(Error) as exc_info:225 br.click(force=True)226 assert "Element is outside of the viewport" in exc_info.value.message227def test_double_click_the_button(page, server):228 page.goto(server.PREFIX + "/input/button.html")229 page.evaluate(230 """() => {231 window.double = false;232 button = document.querySelector('button');233 button.addEventListener('dblclick', event => {234 window.double = true;235 });236 }"""237 )238 button = page.query_selector("button")239 button.dblclick()240 assert page.evaluate("double")241 assert page.evaluate("result") == "Clicked"242def test_hover(page, server):243 page.goto(server.PREFIX + "/input/scrollable.html")244 button = page.query_selector("#button-6")245 button.hover()246 assert page.evaluate('document.querySelector("button:hover").id') == "button-6"247def test_hover_when_node_is_removed(page, server):248 page.goto(server.PREFIX + "/input/scrollable.html")249 page.evaluate('delete window["Node"]')250 button = page.query_selector("#button-6")251 button.hover()252 assert page.evaluate('document.querySelector("button:hover").id') == "button-6"253def test_scroll(page, server):254 page.goto(server.PREFIX + "/offscreenbuttons.html")255 for i in range(11):256 button = page.query_selector(f"#btn{i}")257 before = button.evaluate(258 """button => {259 return button.getBoundingClientRect().right - window.innerWidth260 }"""261 )262 assert before == 10 * i263 button.scroll_into_view_if_needed()264 after = button.evaluate(265 """button => {266 return button.getBoundingClientRect().right - window.innerWidth267 }"""268 )269 assert after <= 0270 page.evaluate("() => window.scrollTo(0, 0)")271def test_scroll_should_throw_for_detached_element(page, server):272 page.set_content("<div>Hello</div>")273 div = page.query_selector("div")274 div.evaluate("div => div.remove()")275 with pytest.raises(Error) as exc_info:276 div.scroll_into_view_if_needed()277 assert "Element is not attached to the DOM" in exc_info.value.message278def test_should_timeout_waiting_for_visible(page):279 page.set_content('<div style="display:none">Hello</div>')280 div = page.query_selector("div")281 with pytest.raises(Error) as exc_info:282 div.scroll_into_view_if_needed(timeout=3000)283 assert "element is not visible" in exc_info.value.message284def test_fill_input(page, server):285 page.goto(server.PREFIX + "/input/textarea.html")286 handle = page.query_selector("input")287 handle.fill("some value")288 assert page.evaluate("result") == "some value"289def test_fill_input_when_Node_is_removed(page, server):290 page.goto(server.PREFIX + "/input/textarea.html")291 page.evaluate('delete window["Node"]')292 handle = page.query_selector("input")293 handle.fill("some value")294 assert page.evaluate("result") == "some value"295def test_select_textarea(page, server, is_firefox):296 page.goto(server.PREFIX + "/input/textarea.html")297 textarea = page.query_selector("textarea")298 textarea.evaluate('textarea => textarea.value = "some value"')299 textarea.select_text()300 if is_firefox:301 assert textarea.evaluate("el => el.selectionStart") == 0302 assert textarea.evaluate("el => el.selectionEnd") == 10303 else:304 assert page.evaluate("() => window.getSelection().toString()") == "some value"305def test_select_input(page, server, is_firefox):306 page.goto(server.PREFIX + "/input/textarea.html")307 input = page.query_selector("input")308 input.evaluate('input => input.value = "some value"')309 input.select_text()310 if is_firefox:311 assert input.evaluate("el => el.selectionStart") == 0312 assert input.evaluate("el => el.selectionEnd") == 10313 else:314 assert page.evaluate("() => window.getSelection().toString()") == "some value"315def test_select_text_select_plain_div(page, server):316 page.goto(server.PREFIX + "/input/textarea.html")317 div = page.query_selector("div.plain")318 div.select_text()319 assert page.evaluate("() => window.getSelection().toString()") == "Plain div"320def test_select_text_timeout_waiting_for_invisible_element(page, server):321 page.goto(server.PREFIX + "/input/textarea.html")322 textarea = page.query_selector("textarea")323 textarea.evaluate('e => e.style.display = "none"')324 with pytest.raises(Error) as exc_info:325 textarea.select_text(timeout=3000)326 assert "element is not visible" in exc_info.value.message327def test_a_nice_preview(page, server):328 page.goto(f"{server.PREFIX}/dom.html")329 outer = page.query_selector("#outer")330 inner = page.query_selector("#inner")331 check = page.query_selector("#check")332 text = inner.evaluate_handle("e => e.firstChild")333 page.evaluate("1") # Give them a chance to calculate the preview.334 assert str(outer) == 'JSHandle@<div id="outer" name="value">…</div>'335 assert str(inner) == 'JSHandle@<div id="inner">Text,↵more text</div>'336 assert str(text) == "JSHandle@#text=Text,↵more text"337 assert (338 str(check) == 'JSHandle@<input checked id="check" foo="bar"" type="checkbox"/>'339 )340def test_get_attribute(page, server):341 page.goto(f"{server.PREFIX}/dom.html")342 handle = page.query_selector("#outer")343 assert handle.get_attribute("name") == "value"344 assert page.get_attribute("#outer", "name") == "value"345def test_inner_html(page, server):346 page.goto(f"{server.PREFIX}/dom.html")...

Full Screen

Full Screen

train.py

Source:train.py Github

copy

Full Screen

1import torch2from torch.optim import Optimizer3from torch.nn import Module4from torch.utils.data import DataLoader5from typing import Callable, List, Union6import os7import os.path as osp8from tqdm import tqdm9from collections import OrderedDict10from models.callbacks import (11 ProgressBarLogger,12 CallbackList,13 Callback,14 EvaluateFewShot,15 CSVLogger16)17from models.few_shot.protonet import fit_handle as ProtoNet_fit_handle18from models.few_shot.matchingnet import fit_handle as MatchingNet_fit_handle19from models.few_shot.relationnet import fit_handle as RelationNet_fit_handle20from models.few_shot.metaoptnet import fit_handle as MetaOptNet_fit_handle21from models.few_shot.maml import fit_handle as Maml_fit_handle22Linear_fit_handle = ProtoNet_fit_handle23FEAT_fit_handle = ProtoNet_fit_handle24Rouge_fit_handle = ProtoNet_fit_handle25from models.few_shot.protonet import laplacian_protonet_fit_handle as LaplacianProtoNet_fit_handle26from models.few_shot.protonet_mm import fit_handle as MultiModalProtoNet_fit_handle27from models.few_shot.tima import fit_handle as MultiModalTIMA_fit_handle28from models.few_shot.tima_plus import fit_handle as MultiModalTIMAPlus_fit_handle29from models.few_shot.protonet import protonet_pretrain_fit_handle as ProtoNetPretrainClassifier_fit_handle30from models.few_shot.protonet import crg_pretrain_fit_handle as CRGPretrainClassifier_fit_handle31RTPretrainClassifier_fit_handle = CRGPretrainClassifier_fit_handle32from models.classical.linearclassifier import fit_handle as LinearClassifier_fit_handle33from models.few_shot.helper import PrepareFunc34from models.utils import get_lr, set_logger, pretrain_prepare_batch, multimodal_pretrain_prepare_batch, set_gpu, set_seeds, load_pickle, save_pickle35from models.metrics import metrics_handle, ROOT_PATH36# from models.ycy import RouGee37class Trainer(object):38 def __init__(self, args):39 self.gpu = args.gpu40 set_gpu(self.gpu)41 set_seeds(torch_seed=args.torch_seed, cuda_seed=args.cuda_seed, np_seed=args.np_seed, random_seed=args.random_seed)42 torch.autograd.set_detect_anomaly(True)43 self.logger_filename = ROOT_PATH + f'{args.logger_filename}/process/{args.params_str}.log'44 self.result_filename = ROOT_PATH + f'{args.logger_filename}/result/{args.params_str}.csv'45 self.logger = set_logger(self.logger_filename, 'train_logger')46 for k in sorted(vars(args).keys()):47 self.logger.info(k + ': %s' % str(vars(args)[k]))48 prepare_handle = PrepareFunc(args)49 # 前向传播所需:50 # ( model 有且仅有这一个, callbacks 基类派生类都是共享这一个model. 下面其他东西也是这样存储 )51 """52 准备 Dataloader53 """54 (self.train_loader, train_num_classes), (self.val_loader, _), (self.test_loader, _) = \55 prepare_handle.prepare_dataloader(option=args.paradigm)56 """57 准备 Model, Optimizer, loss_fn, callbacks58 """59 self.model = prepare_handle.prepare_model(train_num_classes)60 self.optimizer, self.lr_scheduler, self.scaler = prepare_handle.prepare_optimizer(self.model)61 self.loss_fn = prepare_handle.prepare_loss_fn()62 self.fit_handle = eval(args.model_class + '_fit_handle')(63 model=self.model,64 optimizer=self.optimizer,65 scaler=self.scaler,66 loss_fn=self.loss_fn67 ) 68 # 接下来要准备fit函数之前的所有东西, 包括callbacks.69 # 记录数据所需:70 # 这里的params统一传到基类成员, 所有派生类共享. 注意这里一定要精简.71 # # 目前pretrain的prepare_batch_func不支持多模态.72 # self.train_prepare_batch, val_prepare_batch, test_prepare_batch = prepare_handle.prepare_prepare_batch_func(73 # model_prepare_batch=self.model.multimodal_prepare_kshot_task if ',' in args.multimodal_option else self.model.prepare_kshot_task,74 # option=0b111 if not args.pretrain_mode else 0b01175 # )76 self.train_prepare_batch, val_prepare_batch, test_prepare_batch = prepare_handle.prepare_prepare_batch_func(77 model_prepare_batch=self.model.prepare_kshot_task,78 option=args.paradigm,79 query_is_label=True if args.model_class != 'Linear' else False80 )81 DEBUG_CLASSICAL_ML = False82 if DEBUG_CLASSICAL_ML:83 (self.train_loader, train_num_classes), (self.val_loader, _), (self.test_loader, _) = \84 prepare_handle.prepare_dataloader(option=0b000)85 self.fit_handle = ProtoNet_fit_handle(86 model=self.model,87 optimizer=self.optimizer,88 scaler=self.scaler,89 loss_fn=self.loss_fn90 )91 test_prepare_batch = pretrain_prepare_batch92 self.verbose, self.epoch_verbose = args.verbose, args.epoch_verbose93 # self.params = {94 # 'max_epoch': args.max_epoch,95 # 'verbose': args.verbose,96 # 'metrics': (self.metrics or []),97 # 'prepare_batch': prepare_kshot_task(args.test_way, args.test_query),98 # 'loss_fn': self.loss_fn,99 # 'optimizer': self.optimizer,100 # 'lr_scheduler': self.lr_scheduler101 # }102 # args 是一个参数集合, 期望在这里分模块, 对每个类 对应特定的功能, 类的参数也要**具体化**, 这样才可以一层层分解, 较好.103 self.model_filepath = args.model_filepath104 self.train_monitor = args.train_monitor105 self.batch_metrics = metrics_handle(self.model, self.train_monitor)106 self.do_train = args.do_train107 self.do_test = args.do_test108 self.max_epoch = args.max_epoch109 self.evaluate_handle = EvaluateFewShot(110 val_loader=self.val_loader,111 test_loader=self.test_loader,112 val_prepare_batch=val_prepare_batch,113 test_prepare_batch=test_prepare_batch,114 batch_metrics=self.batch_metrics,115 eval_fn=self.fit_handle,116 test_interval=args.test_interval,117 max_epoch=self.max_epoch,118 model_filepath=args.model_filepath,119 model_filepath_test_best=args.model_filepath_test_best,120 monitor=self.train_monitor,121 save_best_only=True,122 mode='max',123 simulation_test=False,124 verbose=args.verbose,125 epoch_verbose=args.epoch_verbose126 )127 callbacks = [128 self.evaluate_handle,129 CSVLogger(130 self.result_filename,131 separator=',',132 append=False133 )134 ]135 if self.do_train:136 callbacks.append(137 ProgressBarLogger(138 length=len(self.train_loader),139 epoch_verbose=self.epoch_verbose140 )141 )142 # LearningRateScheduler 最好直接在fit函数里面传一个lr_scheduler, 直接step吧. 看FEAT.143 self.callbacks = CallbackList((callbacks or []))144 self.callbacks.set_model_and_logger(self.model, self.logger)145 """146 meta147 """148 self.meta = args.meta149 # if args.init_weights is not None:150 # self.evaluate_handle.predict_log(1, 'test_')151 self.mm_train_list = args.mm_train_list152 PREPROCESS_FEATURE_MEAN_STD = False153 if PREPROCESS_FEATURE_MEAN_STD:154 (feat_train_loader, feat_num_classes), (_, _), (_, _) = prepare_handle.prepare_dataloader(option=0b100, is_only_one=True)155 from models.dataloader.lrw import LRW_VIDEO_DATA_PATH_NAME, LRW_AUDIO_DATA_PATH_NAME156 FEATURE_MEAN_CACHE_FILE_NAME_SUFFIX = '_base_features_mean.pkl'157 FEATURE_STD_CACHE_FILE_NAME_SUFFIX = '_base_features_std.pkl'158 data_root_path_video = osp.join(args.data_path, LRW_VIDEO_DATA_PATH_NAME)159 data_root_path_audio = osp.join(args.data_path, LRW_AUDIO_DATA_PATH_NAME)160 cache_filepath = {161 'mean': {162 'video': osp.join(data_root_path_video, '_'.join(args.backbone_class) + FEATURE_MEAN_CACHE_FILE_NAME_SUFFIX),163 'audio': osp.join(data_root_path_audio, '_'.join(args.backbone_class) + FEATURE_MEAN_CACHE_FILE_NAME_SUFFIX)164 },165 'std': {166 'video': osp.join(data_root_path_video, '_'.join(args.backbone_class) + FEATURE_STD_CACHE_FILE_NAME_SUFFIX),167 'audio': osp.join(data_root_path_audio, '_'.join(args.backbone_class) + FEATURE_STD_CACHE_FILE_NAME_SUFFIX)168 }169 }170 self.model.eval()171 with torch.no_grad():172 def compute(cur_modal, cache_mean_filepath, cache_std_filepath):173 if self.epoch_verbose:174 cur_iter = enumerate(tqdm(feat_train_loader))175 else:176 cur_iter = enumerate(feat_train_loader)177 data = {}178 for batch_idx, batch in cur_iter:179 x, y = multimodal_pretrain_prepare_batch(batch)180 x = self.model.forward_get_feature(x, modal=cur_modal)181 # 构造 类别 -> embedding(特征) 的字典, 为后续计算类中心打下基础.182 tmp_dict = {} # <class ID (int), feature>183 for i, v in enumerate(y):184 v = v.item()185 if v in tmp_dict.keys():186 tmp_dict[v].append(x[cur_modal][i])187 else:188 tmp_dict[v] = [x[cur_modal][i]]189 for i, v in tmp_dict.items():190 tmp_dict[i] = torch.stack(v, dim=0)191 # 该batch数据 加入data:192 for i, v, in tmp_dict.items():193 if i in data.keys():194 data[i] = torch.cat([data[i], v.cpu().detach()], dim=0)195 else:196 data[i] = v.cpu().detach()197 feat_train_feature = torch.cat([i for i in data.values()], dim=0)198 save_pickle(cache_mean_filepath, torch.mean(feat_train_feature, dim=0, keepdim=True))199 save_pickle(cache_std_filepath, torch.std(feat_train_feature, dim=0, unbiased=False, keepdim=True))200 compute('video', cache_filepath['mean']['video'], cache_filepath['std']['video'])201 compute('audio', cache_filepath['mean']['audio'], cache_filepath['std']['audio'])202 assert 0, 'PREPROCESS_FEATURE_MEAN_STD OK!'203 self.test_load_from_file = True204 self.init_weights = args.init_weights205 self.unimodal = args.unimodal206 def delete_logs(self):207 os.remove(self.logger_filename)208 os.remove(self.result_filename)209 def lr_handle(self, epoch, epoch_logs):210 if self.unimodal:211 self.logger.info(f'lr: {get_lr(self.optimizer)}.')212 self.lr_scheduler.step()213 else:214 for mdl in self.mm_train_list:215 self.logger.info(f'lr: {get_lr(self.optimizer[mdl])} ({mdl}).')216 self.lr_scheduler[mdl].step()217 def test(self):218 # check_model_changed_handle.check_model(self.model)219 if self.do_test:220 self.logger.info(f'Testing model: {self.model_filepath}')221 if self.verbose:222 print(f'Testing model: {self.model_filepath}')223 if self.test_load_from_file:224 state_dict = torch.load(self.model_filepath)225 if ',' not in self.gpu and 'module' in list(state_dict.keys())[0]:226 # for models using nn.DataParallel:227 print("WARNING: Loading test model in train.py test().")228 tmp_state_dict = OrderedDict()229 for k, v in state_dict.items():230 tmp_state_dict[k.replace('.module', '')] = v # remove `.module`231 state_dict = tmp_state_dict232 elif ',' in self.gpu and 'module' not in list(state_dict.keys())[0]:233 raise Exception('Loading test model in train.py test(). The model may be training on a single GPU, but testing on multiple GPUs.')234 model_dict = self.model.state_dict()235 if len(state_dict.keys()) != len(model_dict.keys()):236 self.logger.info(f'Oops! Error loading model, not fully loaded: {[i for i in model_dict.keys() if i not in state_dict.keys()]}.')237 raise Exception(f'Oops! Error loading model, not fully loaded: {[i for i in model_dict.keys() if i not in state_dict.keys()]}.')238 else:239 self.model.load_state_dict(state_dict)240 # check_model_changed_handle.check_model(self.model)241 return self.evaluate_handle.predict_log(self.max_epoch, 'test_')242 return None243 def fit(self):244 print(f'Please check [do_train: {self.do_train}, do_test: {self.do_test}] again.')245 if not self.do_train:246 if not osp.isfile(self.init_weights):247 torch.save(self.model.state_dict(), self.model_filepath)248 else:249 self.test_load_from_file = False250 return251 self.logger.info('Begin training...')252 if self.verbose:253 print('Begin training...')254 self.callbacks.on_train_begin()255 # from torch.utils.tensorboard import SummaryWriter256 # writer = SummaryWriter('runs/model')257 for epoch in range(1, self.max_epoch + 1):258 self.callbacks.on_epoch_begin(epoch)259 epoch_logs, batch_logs = {}, {}260 for batch_index, batch in enumerate(self.train_loader):261 self.callbacks.on_batch_begin(batch_index, batch_logs)262 x, y = self.train_prepare_batch(batch)263 logits, reg_logits, loss = self.fit_handle(x=x, y=y, prefix='train_')264 batch_logs['loss'] = loss.item()265 batch_logs[self.train_monitor] = self.batch_metrics(logits, y)266 self.callbacks.on_batch_end(batch_index, batch_logs)267 # Run on epoch end268 # 注意这个 epoch_logs 是共享变量, 在callbacks里面的类传递的!269 self.lr_handle(epoch, epoch_logs)270 self.callbacks.on_epoch_end(epoch, epoch_logs)271 self.callbacks.on_train_end()272 # Run on train end273 self.logger.info('Finished')274 if self.verbose:...

Full Screen

Full Screen

modified_operator_precedence.py

Source:modified_operator_precedence.py Github

copy

Full Screen

...51 self.advance()52 self.stack = [self.presymbols['$soi$']]53 def id_symbol(self, id):54 return SymbolDesc(id, 999, 1000, identity_evaluator)55 def evaluate_handle(self, args):56 for i in args:57 if type(i) == SymbolDesc:58 return i.evaluator(args)59 raise RuntimeError('Internal error: no evaluator found in {}'.format(args))60 def evaluate(self):61 idx = len(self.stack)-162 if type(self.stack[idx]) != SymbolDesc:63 idx -= 164 curprio = self.stack[idx].lprio65 while type(self.stack[idx-1]) != SymbolDesc or self.stack[idx-1].rprio == curprio:66 idx -= 167 if type(self.stack[idx]) == SymbolDesc:68 curprio = self.stack[idx].lprio69 args = self.stack[idx:]70 self.stack[idx:] = []71 self.stack.append(self.evaluate_handle(args))72 def tos_symbol(self):73 idx = len(self.stack)-174 while type(self.stack[idx]) != SymbolDesc:75 idx -= 176 return self.stack[idx]77 def cur_sym(self, allow_presymbol):78 if self.cur_token is None:79 return None80 elif self.cur_token.kind == 'ID':81 return self.id_symbol(self.cur_token)82 elif self.cur_token.kind == 'NUMBER':83 return self.id_symbol(self.cur_token)84 elif allow_presymbol and self.cur_token.lexem in self.presymbols:85 return self.presymbols[self.cur_token.lexem]...

Full Screen

Full Screen

recursive_operator_precedence.py

Source:recursive_operator_precedence.py Github

copy

Full Screen

...48 self.lexer = lexer.tokenize(s)49 self.advance()50 def id_symbol(self, id):51 return SymbolDesc(id, 999, 1000, identity_evaluator)52 def evaluate_handle(self, args):53 for i in args:54 if type(i) == SymbolDesc:55 return i.evaluator(args)56 raise RuntimeError('Internal error: no evaluator found in {}'.format(args))57 def cur_sym(self, allow_presymbol):58 if self.cur_token is None:59 return None60 elif self.cur_token.kind == 'ID':61 return self.id_symbol(self.cur_token)62 elif self.cur_token.kind == 'NUMBER':63 return self.id_symbol(self.cur_token)64 elif allow_presymbol and self.cur_token.lexem in self.presymbols:65 return self.presymbols[self.cur_token.lexem]66 elif self.cur_token.lexem in self.postsymbols:67 return self.postsymbols[self.cur_token.lexem]68 else:69 return None70 def parse_to(self, prio):71 args = []72 while True:73 assert len(args) == 0 or (len(args) == 1 and type(args[0]) != SymbolDesc)74 sym = self.cur_sym(len(args) == 0)75 if sym is None or prio >= sym.lprio:76 break77 while True:78 args.append(sym)79 self.advance()80 curprio = sym.rprio81 next = self.parse_to(curprio)82 if next is not None:83 args.append(next)84 sym = self.cur_sym(next is None)85 if sym is None or curprio != sym.lprio:86 break87 args = [self.evaluate_handle(args)]88 if len(args) == 1:89 return args[0]90 else:91 return None92 def parse(self, s):93 self.reset(s)94 res = self.parse_to(0)95 if self.cur_token is not None:96 res = CompositeNode('REMAINING INPUT', [res, self.cur_token])97 return res98def open_parenthesis_evaluator(args):99 if (len(args) == 3100 and type(args[0]) == SymbolDesc and args[0].symbol == '('101 and type(args[1]) != SymbolDesc...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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