Best Python code snippet using SeleniumLibrary
theforest.py
Source:theforest.py
1import inspect2import math3import random4import sys5import numpy as np6this_file_loc = (inspect.stack()[0][1])7main_dir_loc = this_file_loc[:this_file_loc.index('ca_descriptions')]8sys.path.append(main_dir_loc)9sys.path.append(main_dir_loc + 'capyle')10sys.path.append(main_dir_loc + 'capyle/ca')11sys.path.append(main_dir_loc + 'capyle/guicomponents')12import capyle.utils as utils13from capyle.ca import Grid2D, Neighbourhood, randomise2d14# constants15WORLD_DIRECTIONS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]16GRID_SIZE = 10017NUM_GENERATION = 50018WIND_DIRECTION = "SW"19WIND_SPEED = 1020# water drop variables21global water_counter22water_counter = 18023water_drop_up = 024water_drop_down = 2025water_drop_left = 8026water_drop_right = 10027water_drop_time = 2628# cell states29CHAPARRAL = 030FOREST = 131LAKE = 232CANYON = 333BURNING = 434BURNT_ALREADY = 535BURNING_START = 636BURNING_ENDING = 737# burning tresholds38start_burning_threshhold = [0.02, 0.005, 0, 0.05, 0, 0, 0.04]39start_burning_factor = 2040burning_threshhold = [0.04, 0.01, 0, 0.1, 0, 0, 0.04]41burning_factor = 3042# extinguishing values43global ext_val44ext_val = [0, 0, 0, 0, 0]45ext_val[CHAPARRAL] = 6246ext_val[FOREST] = 15047ext_val[LAKE] = 148ext_val[CANYON] = 249# for initial state, only burning cell is chaparral50ext_val[BURNING] = ext_val[CHAPARRAL]51# start grid and ignition_grid52global start_grid53global ignition_grid54# seting up start grid55start_grid = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int)56start_grid[60:80, 30:50] = FOREST57start_grid[20:30, 10:30] = LAKE58start_grid[10:60, 60:70] = CANYON59start_grid[0, GRID_SIZE-1] = BURNING # initial fire right upper corner60ignition_grid = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int)61def setup(args):62 config_path = args[0]63 config = utils.load(config_path)64 config.title = "The forest"65 config.dimensions = 266 config.grid_dims = (GRID_SIZE, GRID_SIZE)67 config.num_generations = NUM_GENERATION68 config.states = (CHAPARRAL, FOREST, LAKE, CANYON, BURNING,69 BURNT_ALREADY, BURNING_START, BURNING_ENDING)70 config.state_colors = \71 [72 (0.7, 0.7, 0.1), # chaparral73 (0, 0.6, 0), # forrest74 (0, 0.5, 1), # lake75 (1, 0.6, 0.1), # canyon76 (1, 0, 0), # burning77 (0.25, 0.25, 0.25), # burnt already78 (1, 0.7, 0), # burn start79 (0.8, 0, 0.2) # burning end80 ]81 config.set_initial_grid(start_grid)82 config.wrap = False83 if len(args) == 2:84 config.save()85 sys.exit()86 return config87def transition_function(grid, neighbourstates, neighbourcounts, ext_grid):88 global water_counter89 global ignition_grid90 neighbourstates = np.array(neighbourstates)91 init_grid = start_grid.astype(int)92 iggrid = np.array(ignition_grid)93 # handle fire ignition factors94 igfactors = []95 for i in range(len(grid)):96 row = []97 for j in range(len(grid[i])):98 row.append(first_phase(grid[i][j], neighbourstates[:, i, j], calculate_wind()))99 igfactors.append(row)100 igfactors = np.array(igfactors)101 # handle start burn state102 already_started_to_burn = []103 for i in range(len(grid)):104 row = []105 for j in range(len(grid[i])):106 row.append(second_phase(grid[i][j], iggrid[i, j], igfactors[i, j]))107 already_started_to_burn.append(row)108 grid[already_started_to_burn] = BURNING_START109 #handle buning statr110 iggrid = np.add(igfactors, iggrid) 111 burning = []112 for i in range(len(grid)):113 row = []114 for j in range(len(grid[i])):115 row.append(third_phase( grid[i][j], iggrid[i, j], ext_grid[i, j]))116 burning.append(row)117 grid[burning] = BURNING118 # handle end burning state119 end_burn = []120 for i in range(len(grid)):121 row = []122 for j in range(len(grid[i])):123 row.append(fourth_phase( grid[i][j], ext_grid[i, j], int(start_grid[i, j])) )124 end_burn.append(row)125 grid[end_burn] = BURNING_ENDING126 ext_grid[(grid == BURNING) | (grid == BURNING_ENDING)] -= 1127 already_burnt = (ext_grid == 0)128 grid[already_burnt] = BURNT_ALREADY129 water_counter += 1130 if(water_counter> water_drop_time and water_counter < water_drop_time+100):131 grid[water_drop_up:water_drop_down, water_drop_left:water_drop_right] = LAKE132 if(water_counter == water_drop_time+100):133 grid[water_drop_up:water_drop_down, water_drop_left:water_drop_right] = start_grid[water_drop_up:water_drop_down, water_drop_left:water_drop_right]134 ignition_grid = iggrid135 return grid136def first_phase(state, neighbourstates, wind_factor):137 current_state = int(state)138 neighbourstates = neighbourstates.astype(int)139 if(current_state == BURNING or current_state == LAKE or current_state == BURNT_ALREADY or current_state == BURNING_ENDING):140 return 0141 fire_factor = 0142 for i, nbstate in enumerate(neighbourstates):143 ran = random.uniform(0, 1)144 if(nbstate == BURNING and burning_threshhold[current_state] * wind_factor[i] >= ran):145 f = math.floor(burning_factor * wind_factor[i])146 fire_factor += int(f)147 if(nbstate == BURNT_ALREADY or nbstate == BURNING_ENDING):148 if(start_burning_threshhold[current_state] * wind_factor[i] >= ran):149 f = math.floor(start_burning_factor * wind_factor[i])150 fire_factor += int(f)151 if(current_state == BURNING_START):152 fire_factor += start_burning_factor153 return int(fire_factor)154def second_phase(state, iggrid_state, start_burning_grid_state):155 if(state == BURNING_START):156 return True157 if(state != BURNING and state != LAKE and state != BURNING_ENDING and state != BURNT_ALREADY and iggrid_state == 0 and start_burning_grid_state > 0):158 return True159 return False160def third_phase(state, iggrid_state, ext_grid_state):161 if(state == BURNING):162 return True163 if(state == BURNING_START and iggrid_state >= ext_grid_state):164 return True165 return False166def fourth_phase(state, ext_grid_state, initial_grid_state):167 if(state == BURNING_ENDING):168 return True169 if(state == BURNING and ext_val[initial_grid_state] >= ext_grid_state * 2):170 return True171 return False172def calculate_wind():173 wind_factor = np.zeros(8)174 angl = 0175 for i in range(8):176 wind_factor[(i + WORLD_DIRECTIONS.index(WIND_DIRECTION) ) % 8] = np.exp(177 WIND_SPEED * np.cos(np.deg2rad(angl)) * 0.1783)178 angl += 45179 indexation = [180 3, 4, 5, 2, 6, 1, 0, 7181 ]182 return wind_factor[indexation]183def main():184 config = setup(sys.argv[1:])185 ext_grid = [[ext_val[i] for i in j]186 for j in start_grid.astype(int)]187 ext_grid = np.array(ext_grid)188 ignition_grid = np.zeros((GRID_SIZE, GRID_SIZE))189 ignition_grid = ignition_grid.astype(int)190 grid = Grid2D(config, (transition_function, ext_grid))191 timeline = grid.run()192 config.save()193 utils.save(timeline, config.timeline_path) 194if __name__ == "__main__":...
mn_puzzle.py
Source:mn_puzzle.py
1from puzzle import Puzzle2class MNPuzzle(Puzzle):3 """4 An nxm puzzle, like the 15-puzzle, which may be solved, unsolved,5 or even unsolvable.6 """7 def __init__(self, from_grid, to_grid):8 """9 MNPuzzle in state from_grid, working towards10 state to_grid11 @param MNPuzzle self: this MNPuzzle12 @param tuple[tuple[str]] from_grid: current configuration13 @param tuple[tuple[str]] to_grid: solution configuration14 @rtype: None15 """16 # represent grid symbols with letters or numerals17 # represent the empty space with a "*"18 assert len(from_grid) > 019 assert all([len(r) == len(from_grid[0]) for r in from_grid])20 assert all([len(r) == len(to_grid[0]) for r in to_grid])21 self.n, self.m = len(from_grid), len(from_grid[0])22 self.from_grid, self.to_grid = from_grid, to_grid23 def __eq__(self, other):24 """25 Return whether MNPuzzle self is equivalent to other MNPuzzle.26 @type self: MNPuzzle27 @type other: MNPuzzle28 @rtype: bool29 >>> target_grid = (("1", "2", "3"), ("4", "5", "*"))30 >>> start_grid = (("*", "2", "3"), ("1", "4", "5"))31 >>> start_grid1 = (("3", "2", "*"), ("1", "4", "5"))32 >>> mn = MNPuzzle(start_grid, target_grid)33 >>> mn1 = MNPuzzle(start_grid, target_grid)34 >>> mn2 = MNPuzzle(start_grid1, target_grid)35 >>> mn == mn136 True37 >>> mn == mn238 False39 """40 return (self.n == other.n and self.m == other.m and41 self.from_grid == other.from_grid and42 self.to_grid == other.to_grid)43 def __str__(self):44 """45 Return a human-readable string representation of MNPuzzle self.46 @type self: MNPuzzle47 @rtype: str48 >>> target_grid = (("1", "2", "3"), ("4", "5", "*"))49 >>> start_grid = (("3", "*", "2"), ("5", "4", "1"))50 >>> p = MNPuzzle(start_grid, target_grid)51 >>> print(p)52 3*253 54154 """55 list_ = []56 for row in self.from_grid:57 for ch in row:58 list_.append(ch)59 list_.append('\n')60 list_ = list_[:-1]61 return ''.join(list_)62 def extensions(self):63 """64 Return all possible extensions of current configuration by swapping one65 symbol to the left, right, above, or below "*" with "*".66 @type self: MNPuzzle67 @rtype: list[MNPuzzle]68 >>> target_grid = (("1", "2", "3"), ("4", "5", "*"))69 >>> start_grid = (("*", "2", "3"), ("1", "4", "5"))70 >>> start_grid1 = (("2", "*", "3"), ("1", "4", "5"))71 >>> start_grid2 = (("1", "2", "3"), ("*", "4", "5"))72 >>> mn = MNPuzzle(start_grid, target_grid)73 >>> mn1 = MNPuzzle(start_grid1, target_grid)74 >>> mn2 = MNPuzzle(start_grid2, target_grid)75 >>> a = mn.extensions()76 >>> a[0] == mn1 or a[0] == mn277 True78 """79 # helper function80 def to_tuple(list_):81 """82 Convert list into tuple, including all internal lists.83 @type list_: list | list[list]84 @rtype: tuple | tuple(tuple)85 """86 i = 087 while i < len(list_):88 list_[i] = tuple(list_[i])89 i += 190 return list_91 # find position of "*" in the grid92 row = 093 column = 094 for line in self.from_grid:95 if "*" in line:96 row = self.from_grid.index(line)97 column = self.from_grid[row].index("*")98 extensions = []99 # move "*" to the right100 if column < len(self.from_grid[row]) - 1:101 grid_list = [list(x) for x in self.from_grid]102 grid_list[row][column] = grid_list[row][column + 1]103 grid_list[row][column + 1] = "*"104 to_tuple(grid_list)105 extensions.append(MNPuzzle(tuple(grid_list), self.to_grid))106 # move "*" to the left107 if 1 < column < len(self.from_grid[row]):108 grid_list = [list(x) for x in self.from_grid]109 grid_list[row][column] = grid_list[row][column - 1]110 grid_list[row][column - 1] = "*"111 to_tuple(grid_list)112 extensions.append(MNPuzzle(tuple(grid_list), self.to_grid))113 # move "*" down114 if row < len(self.from_grid) - 1:115 grid_list = [list(x) for x in self.from_grid]116 grid_list[row][column] = grid_list[row + 1][column]117 grid_list[row + 1][column] = "*"118 to_tuple(grid_list)119 extensions.append(MNPuzzle(tuple(grid_list), self.to_grid))120 # move "*" up121 if 1 < row < len(self.from_grid):122 grid_list = [list(x) for x in self.from_grid]123 grid_list[row][column] = grid_list[row - 1][column]124 grid_list[row - 1][column] = "*"125 to_tuple(grid_list)126 extensions.append(MNPuzzle(tuple(grid_list), self.to_grid))127 return extensions128 def is_solved(self):129 """130 Return whether from_grid is the same as to_grid.131 @type self: MNPuzzle132 @rtype: bool133 >>> target_grid = (("1", "2", "3"), ("4", "5", "*"))134 >>> start_grid = (("*", "2", "3"), ("1", "4", "5"))135 >>> start_grid1 = (("1", "2", "3"), ("4", "5", "*"))136 >>> mn = MNPuzzle(start_grid, target_grid)137 >>> mn1 = MNPuzzle(start_grid1, target_grid)138 >>> mn.is_solved()139 False140 >>> mn1.is_solved()141 True142 """143 return self.from_grid == self.to_grid144if __name__ == "__main__":145 import doctest146 doctest.testmod()147 target_grid = (("1", "2", "3"), ("4", "5", "*"))148 start_grid = (("*", "2", "3"), ("1", "4", "5"))149 from puzzle_tools import breadth_first_solve, depth_first_solve150 from time import time151 start = time()152 solution = breadth_first_solve(MNPuzzle(start_grid, target_grid))153 end = time()154 print("BFS solved: \n\n{} \n\nin {} seconds".format(155 solution, end - start))156 start = time()157 solution = depth_first_solve((MNPuzzle(start_grid, target_grid)))158 end = time()159 print("DFS solved: \n\n{} \n\nin {} seconds".format(...
image.py
Source:image.py
1import io2import discord3import numpy as np4from PIL import Image, ImageDraw56async def insert_profile(profile, base, pos:list):7 if type(base) is str:8 image = Image.open(base)9 else:10 image = base11 image.alpha_composite(profile, (int(image.size[0] - pos[0]), int(image.size[1] - pos[1])))12 return image1314async def griddify(size, x_cut, y_cut):15 width = size[0]16 length = size[1]17 x_step = width / float(x_cut)18 y_step = length / float(y_cut)19 y = 0.020 vertexMatrix = []21 for i in range(x_cut + 1):22 vertexMatrix.append([])23 x = 0.024 for j in range(y_cut + 1):25 vertexMatrix[-1].append([int(x), int(y)])26 x += x_step27 y += y_step28 return np.array(vertexMatrix), x_step, y_step2930async def bonk_distort(grid, strength, x_step, y_step):31 new_grid = np.copy(grid)32 x_move = x_step * strength33 y_move = y_step * strength34 new_grid[0][0] = [int(new_grid[0][0][0] - x_move), int(new_grid[0][0][1] - y_move)]35 new_grid[0][1] = [int(new_grid[0][1][0] - 1.2*x_move), int(new_grid[0][1][1] - 1.2*y_move)]36 new_grid[1][0] = [int(new_grid[1][0][0] - 1.2*x_move), int(new_grid[1][0][1] - 1.2*y_move)]37 new_grid[1][1] = [int(new_grid[1][1][0] - x_move), int(new_grid[1][1][1] - y_move)]38 new_grid[0][2] = [int(new_grid[0][2][0] - 0.6*x_move), int(new_grid[0][2][1] - 0.6*y_move)]39 new_grid[2][0] = [int(new_grid[2][0][0] - 0.6*x_move), int(new_grid[2][0][1] - 0.6*y_move)]40 new_grid[2][1] = [int(new_grid[2][1][0] - 0.8*x_move), int(new_grid[2][1][1] - 0.8*y_move)]41 new_grid[1][2] = [int(new_grid[1][2][0] - 0.8*x_move), int(new_grid[1][2][1] - 0.8*y_move)]42 return new_grid4344async def quad_as_rect(quad):45 if quad[0] != quad[2]: return False46 if quad[1] != quad[7]: return False47 if quad[4] != quad[6]: return False48 if quad[3] != quad[5]: return False49 return True5051async def quad_to_rect(quad):52 assert(len(quad) == 8)53 assert(await quad_as_rect(quad))54 return (quad[0], quad[1], quad[4], quad[3])5556async def grid_to_mesh(distorted_grid, start_grid):57 assert(distorted_grid.shape == start_grid.shape)58 mesh = []59 for i in range(distorted_grid.shape[0] - 1):60 for j in range(distorted_grid.shape[1] - 1):61 src_quad = [distorted_grid[i , j , 0], distorted_grid[i , j , 1],62 distorted_grid[i + 1, j , 0], distorted_grid[i + 1, j , 1],63 distorted_grid[i + 1, j + 1, 0], distorted_grid[i + 1, j + 1, 1],64 distorted_grid[i , j + 1, 0], distorted_grid[i , j + 1, 1]]65 dst_quad = [start_grid[i , j , 0], start_grid[i , j , 1],66 start_grid[i + 1, j , 0], start_grid[i + 1, j , 1],67 start_grid[i + 1, j + 1, 0], start_grid[i + 1, j + 1, 1],68 start_grid[i , j + 1, 0], start_grid[i , j + 1, 1]]69 dst_rect = await quad_to_rect(dst_quad)70 mesh.append([dst_rect, src_quad])71 return mesh7273async def warp_profile(profile, strength):74 start_grid, x_step, y_step = await griddify(profile.size, 4, 4)75 distorted_grid = await bonk_distort(start_grid, strength, x_step, y_step)76 mesh = await grid_to_mesh(distorted_grid, start_grid)77 profile = profile.transform(profile.size, Image.MESH, mesh)78 return profile, x_step, y_step7980async def get_round_profile(user, diam=320):81 avatarAsset = user.avatar_url_as(format='png', size=1024)82 avatarBuffer = io.BytesIO()83 await avatarAsset.save(avatarBuffer)84 avatarBuffer.seek(0)85 userAvatar = Image.open(avatarBuffer)86 userAvatar = userAvatar.resize((diam, diam))87 mask = Image.new('1', (diam, diam), color = 255)88 drawMask = ImageDraw.Draw(mask)89 drawMask.ellipse((0, 0, diam, diam), fill=0)90 userAvatar = Image.composite(Image.new("RGBA", (diam, diam), (255, 0, 0, 0)), userAvatar.convert("RGBA"), mask=mask)91 return userAvatar9293async def make_discord_image(image:Image, filename, ext="png", spoiler=False):94 with io.BytesIO() as buffer:95 image.save(buffer, format=ext)96 buffer.seek(0)
...
day20.py
Source:day20.py
1from typing import List, Tuple2def read_input(lines: List[str]) -> Tuple[str, List[List[str]]]:3 """4 parse input lines to decode string5 and grid6 """7 i = 08 decode_string = ""9 while lines[i] not in {"", "\n"}:10 decode_string += lines[i].replace("\n", "")11 i += 112 i += 113 grid = []14 while i < len(lines):15 grid.append(list(lines[i].replace("\n", "")))16 i += 117 return decode_string, grid18def pad_image(img: List[List[str]],19 n: int = 2,20 pad_char: str = ".") -> List[List[str]]:21 """22 pad image with n layers of dark23 cells24 """25 for i, row in enumerate(img):26 padding = [pad_char] * n27 img[i] = padding + row + padding28 padding_row = [pad_char] * len(img[0])29 img = [padding_row] * n + img + [padding_row] * n30 return img31def decode_image(img: List[List[str]],32 decode_string: str) -> Tuple[List[List[str]], int]:33 """34 decode the image, and return this and the number35 of light '#' cells in the result36 """37 m = [[256, 128, 64], [32, 16, 8], [4, 2, 1]]38 out = []39 total = 040 for i in range(len(img) - 2):41 row = []42 for j in range(len(img[0]) - 2):43 idx = 044 for i_0 in range(3):45 for j_0 in range(3):46 if img[i + i_0][j + j_0] == "#":47 idx += m[i_0][j_0]48 decoded_pixel = decode_string[idx]49 total += 1 if decoded_pixel == "#" else 050 row.append(decoded_pixel)51 out.append(row)52 return out, total53def print_img(img: List[List[str]]) -> None:54 """55 print image for debugging purposes56 """57 for line in img:58 print("".join(line))59if __name__ == "__main__":60 from collections import Counter61 with open("inputs/day20.txt") as input_file:62 data = input_file.readlines()63 pad_characters = [".", "#"]64 decoder_string, start_grid = read_input(data)65 # print_img(start_grid)66 # print("---------")67 for i in range(50):68 pad_character = "." if i % 2 == 0 else "#"69 start_grid = pad_image(start_grid, 2, pad_character)70 start_grid, count = decode_image(start_grid, decoder_string)71 # print_img(start_grid)72 # print("-------------")...
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!!