Best Python code snippet using nose2
tiledworld.py
Source:tiledworld.py
...63 return room64 return None65def get_path(path, exclude_src = False):66 return path[4 if path.startswith("src") and exclude_src else 0:path.find(os.path.basename(path))]67def name_from_path(path):68 return os.path.basename(path).split('.', 1)[0].capitalize()69def __main__():70 parser = argparse.ArgumentParser()71 parser.add_argument("-o", "--output", dest = "output", type = argparse.FileType('w'), nargs = 1, required = True)72 parser.add_argument("-i", "--include", dest = "include", type = argparse.FileType('w'), nargs = 1, required = True)73 parser.add_argument("input", type = argparse.FileType('r'), nargs = 1, help = "Input .world file.")74 args = parser.parse_args()75 infile = args.input[0]76 outfile = args.output[0]77 include_file = args.include[0]78 map_name = name_from_path(infile.name)79 rooms = []80 # Create rooms structures.81 for room in json.loads(infile.read())["maps"]:82 new_room = Room()83 new_room.path = room["fileName"]84 new_room.name = name_from_path(new_room.path)85 new_room.json = json.loads(open(get_path(infile.name) + new_room.path, "r").read())86 new_room.x = room["x"] // 25687 new_room.y = room["y"] // 25688 if room["x"] % 256 != 0 or room["y"] % 256 != 0:89 error(f"Room position of {new_room.path} must be a multiple of 256.")90 if (room["width"] != 256 or room["height"] != 256):91 error(f"Width and height of {new_room.path} must be 256.")92 rooms.append(new_room)93 if get_height(rooms) > 16 and get_width(rooms) > 16:94 error("A world must be 16x16 rooms or smaller.")95 outfile.write("; Generated by tiledworld.py for use in the VuiBui engine.\n\n")96 outfile.write(f"SECTION \"{map_name} World Map\", ROMX\n")97 if include_file:98 include_file.write("; Generated by tiledworld.py for use in the VuiBui engine.\n\n")99 # INCBIN each of the rooms. This should eventually happen directly in100 # tiledworld rather than splitting the work with tiledbin.101 outfile.write("; --- Maps ---\n")102 for room in rooms:103 outpath = get_path(infile.name, True) + room.path.split('.', 1)[0]104 tiledbin.convert_map(open(f"src/{outpath}.json", "r"), open(f"{outpath}.tilemap", "wb"), open(f"{outpath}.datafile", "w"))105 outfile.write(f"{room.name}:\n")106 outfile.write(f" INCBIN \"{outpath + '.tilemap'}\"\n")107 outfile.write("\n; --- Scripts ---\n")108 for room in rooms:109 outfile.write(f"{name_from_path(room.name)}_script:\n")110 try:111 script_path = get_path(infile.name) + room.path.split('.', 1)[0] + '.roomscript'112 open(script_path)113 outfile.write(f" INCLUDE \"{script_path}\"\n")114 except:115 pass116 outfile.write(f" INCLUDE \"{get_path(infile.name, True) + room.path.split('.', 1)[0] + '.datafile'}\"\n")117 outfile.write(" end_mapdata\n")118 # Get the tileset path and assert that there is only one.119 tileset_path = ""120 for room in rooms:121 if len(room.json["tilesets"]) < 1:122 error(f"{room.path} has no tileset!")123 if len(room.json["tilesets"]) > 1:124 warn(f"{room.path} has more than 1 tileset. Only the first will be used.")125 if not tileset_path:126 tileset_path = room.json["tilesets"][0]["source"]127 if tileset_path != room.json["tilesets"][0]["source"]:128 error(f"Multiple tilesets detected in {map_name}! All cells in a world must share a tileset.")129 tileset = get_path(infile.name) + json.loads(open(get_path(infile.name) + tileset_path, 'r').read())['image']130 # Include the tileset.131 outfile.write(132f"""133; --- Tileset ---134{name_from_path(tileset_path)}_tileset:135 INCBIN \"{tileset[4 if tileset.startswith("src") else 0:].split('.', 1)[0] + '.2bpp'}\"136""")137 # Include the palettes.138 outfile.write(139f"""140; --- Palettes ---141{name_from_path(tileset_path)}_palettes:142 pal_blank143""")144 # Incude the metatile data.145 outfile.write(146f"""147; --- Metatiles ---148{name_from_path(tileset_path)}:149.definitions150 INCLUDE \"{tileset[4 if tileset.startswith("src") else 0:].split('.', 1)[0] + '.mtiledata'}\"151.end152.attributes153 DS 12 * 4, 0 ; TODO154""")155 # Collision data here156 outfile.write(".data\n")157 try:158 for line in open(tileset.split('.', 1)[0] + ".tdata").read().splitlines():159 line = line.strip()160 if line == "" or line[0] == ";":161 continue162 outfile.write(f" DB TILEDATA_{line.upper()}\n")163 except:164 error(f"Failed to open {tileset.split('.', 1)[0] + '.tdata'}. Is it missing?")165 # Prepare world structure.166 outfile.write(167f"""168x{map_name}::169 define_map \\170 {get_width(rooms)}, {get_height(rooms)}, \\ ; Width, Size171 {name_from_path(tileset_path)}_tileset, \\ ; Tileset172 {name_from_path(tileset_path)}_palettes, \\ ; Palettes - TODO173 {name_from_path(tileset_path)} ; Metatile data174.map""")175 # Output room matrix.176 (lowest_height, highest_height) = get_height_range(rooms)177 (lowest_width, highest_width) = get_width_range(rooms)178 for y in range(lowest_height, highest_height + 1):179 outfile.write("\n DW ")180 for x in range(lowest_width, highest_width + 1):181 room = get_room(x, y, rooms)182 if room is None:183 outfile.write("null, ")184 else:185 outfile.write(f"{room.name}, ")186 if include_file:187 include_file.write(f"DEF {room.name}_X EQU {x + abs(lowest_width)}\n")188 include_file.write(f"DEF {room.name}_Y EQU {y + abs(lowest_height)}\n")189 # And finally, output room script matrix.190 outfile.write("\n.data")191 for y in range(lowest_height, highest_height + 1):192 outfile.write("\n DW ")193 for x in range(lowest_width, highest_width + 1):194 room = get_room(x, y, rooms)195 if room is None:196 outfile.write("null, ")197 else:198 outfile.write(f"{name_from_path(room.name)}_script, ")199if __name__ == "__main__":...
westlaw.py
Source:westlaw.py
1import re2def get_name_of_case_in_westlaw(open_case={}, name_from_path={}, text=''):3 page = open_case.loadPage(0)4 text = page.getText()5 text_lowered = text.lower()6 name_from_path_lowered = name_from_path.lower()7 # We are changing the v to a v. for the purpose of westlaw8 name_from_path_lowered_with_v = re.sub(' v ', ' v. ', name_from_path)9 if name_from_path_lowered in text_lowered or name_from_path_lowered_with_v in text_lowered:10 return name_from_path11 else:12 split_text = text.split('\n')13 split_text = clear_blanks(split_text)14 index_with_name = find_index_with_name(name_from_path, split_text)15 if index_with_name != None:16 return split_text[index_with_name]17 else:18 try:19 if '§' in split_text[0]:20 # Find the next section sign for the title of the page.21 index_of_second_section_sign = find_index_of_second_section_sign(22 split_text)23 return split_text[index_of_second_section_sign]24 return None25 except:26 return None27def find_index_of_second_section_sign(split_text):28 for i in range(1, len(split_text)):29 if '§' in split_text[i]:30 return i31 else:32 return 033def find_index_with_name(name_from_path, split_text):34 split_name = name_from_path.split(' ')35 first_part_of_name = split_name[0]36 first_part_of_name = first_part_of_name.strip()37 for i in range(len(split_text)):38 split_text_again = split_text[i].split(' ')39 first_part_of_text = split_text_again[0]40 first_part_of_text = first_part_of_text.strip()41 first_part_of_text = first_part_of_text.lower()42 if first_part_of_name == first_part_of_text:43 return i44 else:45 try:46 index_of_slash = name_from_path.rindex('\\')47 first_white_space = name_from_path[index_of_slash:len(48 name_from_path)].index(' ')49 plaintiff_name = name_from_path[index_of_slash + 1:50 index_of_slash + first_white_space].strip()51 if plaintiff_name.lower() in first_part_of_text:52 return i53 except:54 return None55 return None56def clear_blanks(split_text):57 new_split_text = []58 for split in split_text:59 if len(split) > 0:60 new_split_text.append(split.strip())...
translator.py
Source:translator.py
...11 return urllib.parse.urlunsplit((scheme, None, uripath, None, None))12def uri_to_path(uri):13 """Convert URI to file path."""14 return path.uri_to_path(uri)15def name_from_path(path):16 """Extract name from file path."""17 name = bytes(pathlib.Path(path.stem))18 try:19 return name.decode(errors="replace")20 except UnicodeError:21 return None22def path_from_name(name, ext=None, sep="|"):23 """Convert name with optional extension to file path."""24 if ext:25 name = name.replace(os.sep, sep) + ext26 else:27 name = name.replace(os.sep, sep)28 return pathlib.Path(name)29def path_to_ref(path):30 return models.Ref.playlist(uri=path_to_uri(path), name=name_from_path(path))31def load_items(fp, basedir):32 refs = []33 name = None34 for line in filter(None, (line.strip() for line in fp)):35 if line.startswith("#"):36 if line.startswith("#EXTINF:"):37 name = line.partition(",")[2]38 continue39 elif not urllib.parse.urlsplit(line).scheme:40 path = basedir / line41 if not name:42 name = name_from_path(path)43 uri = path_to_uri(path, scheme="file")44 else:45 # TODO: ensure this is urlencoded46 uri = line # do *not* extract name from (stream?) URI path47 refs.append(models.Ref.track(uri=uri, name=name))48 name = None49 return refs50def dump_items(items, fp):51 if any(item.name for item in items):52 print("#EXTM3U", file=fp)53 for item in items:54 if item.name:55 print(f"#EXTINF:-1,{item.name}", file=fp)56 # TODO: convert file URIs to (relative) paths?57 if isinstance(item.uri, bytes):58 print(item.uri.decode(), file=fp)59 else:60 print(item.uri, file=fp)61def playlist(path, items=None, mtime=None):62 if items is None:63 items = []64 return models.Playlist(65 uri=path_to_uri(path),66 name=name_from_path(path),67 tracks=[models.Track(uri=item.uri, name=item.name) for item in items],68 last_modified=(int(mtime * 1000) if mtime else None),...
filewatch.py
Source:filewatch.py
...14class FileStoreEventHandler(FileSystemEventHandler):15 def __init__(self, env, model):16 self.env = env17 self.model = model18 def name_from_path(self, path):19 path = os.path.abspath(os.path.join(self.env.path, path))20 if not path.startswith(os.path.abspath(self.env.path)):21 print("Unexpected update of file {} not under {}".format(path, self.env.path))22 raise Exception("Bad file: {}".format(path))23 path = path[len(os.path.abspath(self.env.path)):].lstrip("/")24 return path25 def on_modified(self, event):26 if event.is_directory:27 return28 filename = event.src_path29 name = self.name_from_path(filename)30 with open(filename, "r") as fp:31 content = fp.read()32 expected = self.model.files.get(name)33 if expected and expected["content"] == content:34 return35 send(FileEdit(filename=name, content=content, external_edit=True))36 on_created = on_modified37 def on_moved(self, event):38 if event.is_directory:39 return40 name = self.name_from_path(event.src_path)41 dest_name = self.name_from_path(event.dest_path)42 if self.model.files.get(name):43 send(FileDelete(filename=name), external_edit=True)44 with open(event.dest_path, "r") as fp:45 content = fp.read()46 expected = self.model.files.get(dest_name)47 if not expected or expected["content"] != content:48 send(FileEdit(filename=dest_name, content=content, external_edit=True))49 def on_deleted(self, event):50 if event.is_directory:51 return52 name = self.name_from_path(event.src_path)53 if self.model.files.get(name):...
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!!