Best Python code snippet using behave
qdmr_transformations.py
Source:qdmr_transformations.py
...465 return re.match("^#[0-9]*$", phrase)466 return list(filter(lambda x: is_reference(x), qdmr_arguments))467def create_qdmr_step(qdmr_example, operator, arguments):468 dummy_step = QDMRStep("", operator, arguments)469 qdmr_str = qdmr_example.step_to_text(dummy_step)470 return QDMRStep(qdmr_str, operator, arguments)471class AppendBooleanTransform(QDMRTransform):472 """473 Return list of transformed QDMR examples.474 Appends boolean steps comparing referenced step to a value.475 Implemented for QDMRs where last step is number, i.e., aggregate step:476 """477 def __init__(self, qdmr_example, limit=-1, numeric_qa_data=None):478 """numeric qa file is a json file from original datasets question ids479 to their numeric answers. file computed in pre-processing"""480 self.numeric_qa_data = numeric_qa_data481 self.limit = limit482 super(AppendBooleanTransform, self).__init__(qdmr_example)483 def _transformations(self):...
sokoban_game.py
Source:sokoban_game.py
1import multiprocessing2import pyglet3import pyglet.window.key as key4import solver5import space6KEY_TO_ACTIONS = {7 key.LEFT: 'l',8 key.RIGHT: 'r',9 key.DOWN: 'd',10 key.UP: 'u'11}12STEP_NONE = 013STEP_THINK = 114STEP_ACT = 215PLAYMODE_STEP_PLAY = 016PLAYMODE_STEP_WIN = 117class SokobanGame(object):18 def __init__(self):19 loader = space.SokobanLoader()20 self.layouts = loader.load_maps()21 self.tiles = loader.load_tiles()22 self.settings = space.SokobanSettings()23 self.solved = self.settings.solved24 print("{0}å
³æªè§£å³".format(len(self.layouts) - len(self.solved)))25 self.tile_width = self.tiles[0].width26 self.window = pyglet.window.Window()27 self.window.event(self.on_draw)28 self.window.event(self.on_key_press)29 self.play_mode = True30 self.play_mode_step = PLAYMODE_STEP_PLAY31 self.play_mode_win_remain = 032 self.cur_level = None33 self.start_state = None34 self.state = None35 self.state_history = []36 self.step_state = STEP_NONE37 self.solver = None38 self.solver_algorithm = solver.ASTAR_DEADLOCK39 self.plan_explored = 040 self.planned_actions = []41 self.planned_actions_idx = 042 self.label1 = pyglet.text.Label('', font_size=16, x=10, y=450)43 self.label2 = pyglet.text.Label('', font_size=16, x=10, y=10)44 self.labelWin = pyglet.text.Label('', bold=True, color=(255, 0, 0, 255), font_size=24, x=10, y=400)45 self.batch = None46 self.all_sprites = None47 self.start_level(self.settings.getint("last_open", fallback=0))48 pyglet.clock.schedule_interval(self.step, 0.1)49 def start_level(self, level):50 if level < 0:51 level = len(self.layouts) - 152 elif level >= len(self.layouts):53 level = 054 if self.cur_level == level:55 return56 self.settings.set('last_open', level)57 self.cur_level = level58 self.start_state = self.layouts[level]59 self.state = self.start_state60 self.window.set_caption("level {0}".format(self.cur_level))61 self.stop_plan()62 self.state_history = []63 layout_height = len(self.state.layout) * self.tile_width64 layout_width = len(self.state.layout[0]) * self.tile_width65 self.window.set_minimum_size(layout_width, layout_height)66 start_x = (self.window.width - layout_width) / 267 start_y = (self.window.height - layout_height) / 268 self.batch = pyglet.graphics.Batch()69 self.all_sprites = []70 for y, line in enumerate(self.state.layout):71 line_sprite = []72 for x, idx in enumerate(line):73 sprite = pyglet.sprite.Sprite(self.tiles[idx], x=x * self.tile_width + start_x,74 y=y * self.tile_width + start_y,75 batch=self.batch)76 line_sprite.append(sprite)77 self.all_sprites.append(line_sprite)78 self.batch.invalidate()79 def act(self, action):80 dx, dy = space.ACTIONS[action]81 nxt = self.state.try_move(dx, dy)82 if nxt is None:83 return84 self.state_history.append(self.state)85 self._set_state(nxt)86 if self.play_mode and self.state.is_finished():87 self.play_mode_step = PLAYMODE_STEP_WIN88 self.play_mode_win_remain = 589 def _set_state(self, state):90 self.state = state91 for y, line in enumerate(self.state.layout):92 line_sprite = self.all_sprites[y]93 for x, idx in enumerate(line):94 sprite = line_sprite[x]95 sprite.image = self.tiles[idx]96 self.batch.invalidate()97 def undo(self):98 if self.state_history:99 last_state = self.state_history.pop()100 self._set_state(last_state)101 def on_key_press(self, symbol, modifiers):102 if symbol in KEY_TO_ACTIONS:103 self.stop_plan()104 self.act(KEY_TO_ACTIONS[symbol])105 elif symbol == key.B:106 self.stop_plan()107 self.undo()108 elif symbol in [key.PAGEDOWN, key.PAGEUP]:109 dir = symbol == key.PAGEDOWN and 1 or -1110 ctrl = modifiers & key.MOD_CTRL != 0111 if ctrl:112 nxt = self.next_unsolved_level(dir)113 else:114 nxt = self.cur_level + dir115 self.start_level(nxt)116 elif symbol == key.HOME:117 ctrl = modifiers & key.MOD_CTRL != 0118 if not ctrl and self.cur_level in self.solved:119 actions, explored = self.solved[self.cur_level]120 self.start_act(actions, explored)121 else:122 self.start_plan()123 elif symbol == key.END:124 self.stop_plan()125 elif symbol == key.M:126 self.play_mode = not self.play_mode127 self.update_label()128 elif symbol == key._1:129 self.solver_algorithm = solver.BFS130 self.stop_plan()131 elif symbol == key._2:132 self.solver_algorithm = solver.ASTAR133 self.stop_plan()134 elif symbol == key._3:135 self.solver_algorithm = solver.ASTAR_DEADLOCK136 self.stop_plan()137 def next_unsolved_level(self, dir):138 c = self.cur_level139 while True:140 c += dir141 if c == self.cur_level:142 return c143 if c < 0:144 c = len(self.layouts) - 1145 elif c >= len(self.layouts):146 c = 0147 if c not in self.solved:148 return c149 def step(self, dt):150 if self.play_mode and self.play_mode_step == PLAYMODE_STEP_WIN:151 self.play_mode_win_remain -= dt152 if self.play_mode_win_remain < 0:153 self.play_mode_step = PLAYMODE_STEP_PLAY154 nxt = self.cur_level + 1155 self.start_level(nxt)156 self.update_label()157 if self.step_state == STEP_NONE:158 return159 if self.step_state == STEP_THINK:160 progress = None161 while self.step_state == STEP_THINK:162 info = self.solver.poll()163 if info is None:164 break165 typ, inf = info166 if typ == 0:167 progress = inf168 elif typ == 1:169 action_list, explored = inf170 action_str = "".join(action_list)171 if self.state == self.start_state:172 self.solved[self.cur_level] = (action_str, explored)173 self.settings.set_solved(self.solved)174 self.start_act(action_str, explored)175 progress = None176 print(self.cur_level, "solution:", explored, action_str)177 if progress:178 self.plan_explored, frontier = progress179 self.update_label()180 if self.step_state == STEP_ACT:181 if self.planned_actions_idx < len(self.planned_actions):182 action = self.planned_actions[self.planned_actions_idx]183 self.act(action)184 self.planned_actions_idx += 1185 else:186 self.stop_plan()187 step_to_text = {STEP_NONE: '', STEP_THINK: 'think', STEP_ACT: 'act'}188 algorithm_to_text = {solver.BFS: 'bfs', solver.ASTAR: 'astar', solver.ASTAR_DEADLOCK: 'astar_deadlock'}189 def update_label(self):190 if self.play_mode:191 self.label1.text = "第 {0} å
³".format(self.cur_level)192 if self.step_state == STEP_THINK:193 self.label2.text = '解å³ä¸... {0}'.format(self.plan_explored)194 else:195 self.label2.text = ""196 if self.play_mode_step == PLAYMODE_STEP_WIN:197 self.labelWin.text = "åç好ï¼{0} ç§åè¿å
¥ç¬¬ {1} å
³".format(int(self.play_mode_win_remain), self.cur_level + 1)198 else:199 self.labelWin.text = ""200 else:201 self.label1.text = SokobanGame.algorithm_to_text[self.solver_algorithm]202 solved_text = (self.cur_level in self.solved) and 'solved' or 'unsolved'203 explored_text = (self.cur_level not in self.solved and self.step_state == STEP_NONE) \204 and ' ' or 'explored={0}'.format(self.plan_explored)205 self.label2.text = '{0} {1} {2}'.format(solved_text, SokobanGame.step_to_text[self.step_state],206 explored_text)207 def start_plan(self):208 if self.solver:209 self.solver.end()210 self.solver = None211 self.solver = ConcurrentSolver(self.state, self.solver_algorithm)212 self.solver.start()213 self.step_state = STEP_THINK214 self.plan_explored = 0215 self.update_label()216 def start_act(self, actions, explored):217 if self.solver:218 self.solver.end()219 self.solver = None220 self.step_state = STEP_ACT221 self.plan_explored = explored222 self.planned_actions = actions223 self.planned_actions_idx = 0224 self.update_label()225 def stop_plan(self):226 if self.solver:227 self.solver.end()228 self.solver = None229 self.step_state = STEP_NONE230 if self.cur_level in self.solved:231 self.planned_actions, self.plan_explored = self.solved[self.cur_level]232 self.update_label()233 def on_draw(self):234 self.window.clear()235 self.batch.draw()236 self.label1.draw()237 self.label2.draw()238 self.labelWin.draw()239 def run(self):240 pyglet.app.run()241class ConcurrentSolver:242 def __init__(self, startState, algorithm):243 self.startState = startState244 self.queue = multiprocessing.Queue()245 self.problem = solver.SokobanSearchProblem(startState, progress=self._progress, algorithm=algorithm)246 self.process = multiprocessing.Process(target=self._solve)247 def start(self):248 self.process.start()249 def end(self):250 self.process.terminate()251 def poll(self):252 try:253 return self.queue.get_nowait()254 except:255 return None256 def _progress(self, exploredSet, frontier):257 exploredSize, frontierSize = len(exploredSet), len(frontier)258 if exploredSize % 100 == 0:259 self.queue.put([0, (exploredSize, frontierSize)])260 def _solve(self):261 actions, exploredSet = self.problem.solve()262 exploredSize = len(exploredSet)263 self.queue.put([1, (actions, exploredSize)])264def main():265 game = SokobanGame()266 game.run()267if __name__ == '__main__':...
test_model2.py
Source:test_model2.py
...17 data2 = dict(data, **kwargs)18 headings = list(data2.keys())19 cells = [text(value) for value in data2.values()]20 return Row(headings, cells, line=line)21def step_to_text(step, indentation=" "):22 step_text = u"%s %s" % (step.keyword, step.name)23 more_text = None24 if step.text:25 more_text = ModelDescriptor.describe_docstring(step.text, indentation)26 elif step.table:27 more_text = ModelDescriptor.describe_table(step.table, indentation)28 if more_text:29 step_text = u"%s\n%s" % (step_text, more_text)30 return step_text.rstrip()31# ----------------------------------------------------------------------------32# TEST SUITE:33# ----------------------------------------------------------------------------34class TestScenarioOutlineBuilder(object):35 """Unit tests for the templating mechanism that is provided by the36 :class:`behave.model:ScenarioOutlineBuilder`.37 """38 @staticmethod39 def assert_make_step_for_row(step_text, expected_text, params=None):40 if params is None:41 params = {}42 step = parse_step(step_text)43 row = make_row(**params)44 output = ScenarioOutlineBuilder.make_step_for_row(step, row)45 assert step_to_text(output) == expected_text46 @staticmethod47 def assert_make_row_tags(tag_text, expected_tags, params=None):48 if params is None:49 params = {}50 tags = parse_tags(tag_text)51 row = make_row(**params)52 actual_tags = ScenarioOutlineBuilder.make_row_tags(tags, row)53 assert actual_tags == expected_tags54 def test_make_step_for_row__without_placeholders_remains_unchanged(self):55 step_text = u'Given a step without placeholders'56 expected_text = text(step_text)57 params = dict(firstname="Alice", lastname="Beauville")58 self.assert_make_step_for_row(step_text, expected_text, params)59 def test_make_step_for_row__with_placeholders_in_step(self):...
qdmr_example.py
Source:qdmr_example.py
...27 def qdmr_encoding(self):28 prefix = "return "29 return prefix + " ;return ".join(self.qdmr_steps_text())30 def qdmr_steps_text(self):31 step_phrases = [self.step_to_text(step) for step in self.steps]32 return step_phrases33 def step_to_text(self, qdmr_step):34 op = qdmr_step.operator35 if op == "select":36 return self.select_step_phrase(qdmr_step)37 elif op == "project":38 return self.project_step_phrase(qdmr_step)39 elif op == "filter":40 return self.filter_step_phrase(qdmr_step)41 elif op == "aggregate":42 return self.aggregate_step_phrase(qdmr_step)43 elif op == "group":44 return self.group_step_phrase(qdmr_step)45 elif op == "superlative":46 return self.superlative_step_phrase(qdmr_step)47 elif op == "comparative":...
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!!