def print_unallocated(self): """print_unallocated """ unallocated_people = [] unallocated_table = PrettyTable(['Name', 'Person id', 'Missing']) for person in self.all_people: if person.wants_accommodation == "N": if not person.has_office: unallocated_people.append( {"Name": person.get_fullname(), "Missing": "Office"}) unallocated_table.add_row( [person.get_fullname(), person.person_id, "Office"]) else: if not person.has_office and not person.has_living_space: unallocated_people.append( {"Name": person.get_fullname(), "Missing": "Office and Living Space"}) unallocated_table.add_row( [person.get_fullname(), person.person_id, "Office and Living Space"]) elif not person.has_office and person.has_living_space: unallocated_people.append( {"Name": person.get_fullname(), "Missing": "Office"}) unallocated_table.add_row( [person.get_fullname(), person.person_id, "Office"]) elif person.has_office and not person.has_living_space: unallocated_people.append( {"Name": person.get_fullname(), "Missing": "Living Space"}) unallocated_table.add_row( [person.get_fullname(), person.person_id, "Living Space"]) print(colorful.blue("Table showing people along with missing rooms")) print(colorful.blue(unallocated_table))
def test_correct_output_on_print_unallocated(self): """test """ dojo = Dojo() dojo.add_person("Kylian", "Mbappe", "Fellow", "Y") # dojo.create_room("living_space", "zebra") # dojo.add_person("Gonzalo", "Higuan", "Fellow", "Y") dojo.add_person("Gianluggi", "Buffon", "Fellow", "N") dojo.create_room("office", "red") dojo.add_person("Timoue", "Bakayoko", "Fellow", "Y") program_captured_output = io.StringIO() sys.stdout = program_captured_output dojo.print_unallocated() sys.stdout = sys.__stdout__ table = PrettyTable(['Name', 'Person id', 'Missing']) table.add_row(["Kylian Mbappe", "1", "Office and Living Space"]) table.add_row(["Gianluggi Buffon", "2", "Office"]) table.add_row(["Timoue Bakayoko", "3", "Living Space"]) captured_output = io.StringIO() sys.stdout = captured_output print(colorful.blue("Table showing people along with missing rooms")) print(colorful.blue(table)) sys.stdout = sys.__stdout__ print(program_captured_output.getvalue().strip()) print(captured_output.getvalue()) self.assertTrue(captured_output.getvalue().strip() in program_captured_output.getvalue().strip())
def download(self, subject, title, url): """ 下载课件 :param title: :param url: :return: """ filename = 'data/{}/{}.zip'.format(subject, title) if os.path.exists(filename) and os.path.getsize(filename): return True print('{c.italic_yellow}开始下载 《{title}》{c.no_italic}{c.close_fg_color}'.format(c=cf, title=title)) with requests.get(url, headers=Downloader.headers, stream=True, proxies=self.__get_proxy()) as r: r.encoding = 'GBK' if 'ERROR' in r.text: print('出现未知错误') return False if '本站对特定时间段的下载数量进行了限制' in r.text: print('下载数量受限制') return False dirname = os.path.dirname(filename) os.makedirs(dirname, exist_ok=True) try: with open(filename, 'wb') as f: # 分块写入磁盘,支持大文件 for chunk in r.iter_content(chunk_size=1024): chunk and f.write(chunk) except Exception as e: Downloader.silent_remove(filename) print(cf.blue(f'下载《{title}》时出现未知错误,已下载部分已被删除')) raise # 检查文件的完整性 # requests v3 也许会支持在文件不完整时抛出异常,但是 v2 不会 # 参考:https://blog.petrzemek.net/2018/04/22/on-incomplete-http-reads-and-the-requests-library-in-python/ content_len = int(r.headers.get('Content-Length')) actual_len = r.raw.tell() if content_len != actual_len: Downloader.silent_remove(filename) print(cf.blue(f'下载《{title}》时发现服务器返回的数据不完整,已删除不完整的文件')) raise IOError(f'读取不完整,已读取 {actual_len} 个字节,预期还差 {content_len - actual_len} 个字节,但是连接被关闭了') if os.path.getsize(filename) < 5120: Downloader.silent_remove(filename) print('文件过小,已删除') return title
def print_allocations(self, file_name=None, print_table="N"): """Prints the people and respective rooms""" if print_table is "N": rooms_people = [] printed_output = "" for room in self.rooms: people = [(person.get_fullname()).upper() for person in room.residents] rooms_people.append({room.name: people}) output = "Room: {0} \n ------\n{1}\n\n".format( room.name, ",".join(people)) printed_output += output if not file_name: if printed_output: print(colorful.blue(printed_output)) else: print( colorful.orange("There are " "no people allocated to " "any rooms at the moment")) else: file = open("resources/" + file_name, "w") file.write(str(printed_output)) file.close() return rooms_people else: allocated_people = \ [person for person in self.people if person.rooms_occupied] if allocated_people: table = PrettyTable(['Name', 'Type', 'Office', 'Living Space']) for person in allocated_people: office_name, living_space_name \ = "Not Assigned", "Not Assigned" for room_occupied in range(0, len(person.rooms_occupied)): if "office" in person.rooms_occupied[room_occupied]: office_name = \ person.rooms_occupied[room_occupied]['office'] if "living_space" in\ person.rooms_occupied[room_occupied]: living_space_name \ = person.rooms_occupied[room_occupied]['living_space'] table.add_row([ person.get_fullname(), person._type, office_name, living_space_name ]) print( colorful.blue("List showing people with space " "and their respective rooms")) print(colorful.blue(table)) else: print( colorful.orange("There are no people allocated" " to any rooms at the moment"))
def color_args_str(args, title=None, type='info'): s = cf.blue(f'\n{LINE}\n') if title: with cf.with_palette(PALETTE) as c: if type == 'error': s += f'{c.bold_error(title)}\n' elif type == 'success': s += f'{c.bold_success(title)}\n' else: s += f'{c.bold_info(title)}\n' for k in args: s += f'{cf.bold_violet(k)}: ' s += f'{args[k]}\n' s += cf.blue(f'{LINE}\n') return s
def show(): """ Show the modifiers and colors """ # modifiers sys.stdout.write(colorful.bold('bold') + ' ') sys.stdout.write(colorful.dimmed('dimmed') + ' ') sys.stdout.write(colorful.italic('italic') + ' ') sys.stdout.write(colorful.underlined('underlined') + ' ') sys.stdout.write(colorful.inversed('inversed') + ' ') sys.stdout.write(colorful.concealed('concealed') + ' ') sys.stdout.write(colorful.struckthrough('struckthrough') + '\n') # foreground colors sys.stdout.write(colorful.red('red') + ' ') sys.stdout.write(colorful.green('green') + ' ') sys.stdout.write(colorful.yellow('yellow') + ' ') sys.stdout.write(colorful.blue('blue') + ' ') sys.stdout.write(colorful.magenta('magenta') + ' ') sys.stdout.write(colorful.cyan('cyan') + ' ') sys.stdout.write(colorful.white('white') + '\n') # background colors sys.stdout.write(colorful.on_red('red') + ' ') sys.stdout.write(colorful.on_green('green') + ' ') sys.stdout.write(colorful.on_yellow('yellow') + ' ') sys.stdout.write(colorful.on_blue('blue') + ' ') sys.stdout.write(colorful.on_magenta('magenta') + ' ') sys.stdout.write(colorful.on_cyan('cyan') + ' ') sys.stdout.write(colorful.on_white('white') + '\n')
def run_anvi_newick_matrix(self): ''' Checks whether the environment contains anvio and if it does, it would run important commands on the shell that will load up the dendrogram necessary for manually classifying and training the data ''' environment = os.getenv('CONDA_DEFAULT_ENV') os.chdir(self.directory) if 'anvio' not in environment: raise EnvironmentError( """ Your default environment '%s' is not related to anvio and thus makes it difficult to perform this algorithm. To install anvio, please refer to the site: https://merenlab.org/2016/06/26/installation-v2/ """ % (environment)) sys.exit() os.system("clear") print(cf.blue("Now running Anvio's matrix-to-newick command...\n")) os.system(""" anvi-matrix-to-newick %s \ -o %s """ % (self.coverage_values_file, self.tree_file)) print( """Finished! If you look at thme directory %s, your tree file will appear as '%s'""" % (self.directory, self.tree_file))
def printBoard(self): cf.use_true_colors() p1_str = cf.red("#") p2_str = cf.blue("#") print("P1 Chips: ", end='') p1_unplayed = list(filter(lambda x: x._pos == -1, self._players[0]._stones)) tmpstr = "" for i in p1_unplayed: tmpstr += str(i._id) + " " print(cf.red(tmpstr)) for i in reversed(range(0,4)): tmp = 'X' if i in self._star_pos else ' ' tmp2 = cf.red(str(self._board[i][0]._id)) if self._board[i][0] != None else None print(f"[{tmp2 if self._board[i][0] != None else tmp }]", end='') print(" ", end='') # Space for i in reversed(range(12,14)): tmp = 'X' if i in self._star_pos else ' ' tmp2 = cf.red(str(self._board[i][0]._id)) if self._board[i][0] != None else None print(f"[{tmp2 if self._board[i][0] != None else tmp }]", end='') print("") for i in range(4, 12): tmp = 'X' if i in self._star_pos else ' ' p1_s = cf.red(str(self._board[i][0]._id)) if self._board[i][0] != None else None p2_s = cf.blue(str(self._board[i][0]._id)) if self._board[i][0] != None else None print(f"[{(p1_s if self._board[i][0]._player == self._players[0] else p2_s) if self._board[i][0] != None else tmp }]", end='') print("") for i in reversed(range(0,4)): tmp = 'X' if i in self._star_pos else ' ' tmp2 = cf.blue(str(self._board[i][1]._id)) if self._board[i][1] != None else None print(f"[{tmp2 if self._board[i][1] != None else tmp }]", end='') print(" ", end='') # Space for i in reversed(range(12,14)): tmp2 = cf.blue(str(self._board[i][1]._id)) if self._board[i][1] != None else None tmp = 'X' if i in self._star_pos else ' ' print(f"[{tmp2 if self._board[i][1] != None else tmp }]", end='') print("") print("P2 Chips: ", end='') p2_unplayed = list(filter(lambda x: x._pos == -1, self._players[1]._stones)) tmpstr = "" for i in p2_unplayed: tmpstr += str(i._id) + " " print(cf.red(tmpstr))
def display_token(self): if self.token: if self.token.lower() == 'b': return colorful.blue(self.edges.format(self.token)) elif self.token.lower() == 'r': return colorful.red(self.edges.format(self.token)) else: return colorful.white(self.edges.format(' '))
def arguments_list_string(args, title=None, type='info'): s = f'\n{LONG_LINE}\n' if DISABLE_COLORS else cf.blue(f'\n{LONG_LINE}\n') if title: if DISABLE_COLORS: s += f'{title}\n' else: with cf.with_palette(PALETTE) as c: if type == 'error': s += f'{c.bold_error(title)}\n' elif type == 'success': s += f'{c.bold_success(title)}\n' else: s += f'{c.bold_info(title)}\n' for k in args: s += f'{k}: ' if DISABLE_COLORS else f'{cf.bold_violet(k)}: ' s += f'{args[k]}\n' s += f'{LONG_LINE}\n' if DISABLE_COLORS else cf.blue(f'{LONG_LINE}\n') return s
def print_allocations(self, file_name="", print_table="N"): """ print_allocations """ if print_table != "Y": rooms_people = [] printed_output = "" for room in self.all_rooms: people = [(person.get_fullname()).upper() for person in room.residents] rooms_people.append({room.room_name: people}) output = "Room: {0} \n ------------------------------------- \n{1}\n\n".format( room.room_name, ",".join(people)) printed_output += output if file_name == "": print(colorful.blue(printed_output)) else: file = open(file_name, "w") file.write(str(printed_output)) file.close() return rooms_people else: allocated_people = \ [person for person in self.all_people if person.rooms_occupied] if allocated_people: table = PrettyTable(['Name', 'Type', 'Office', 'Living Space']) for person in allocated_people: office_name, living_space_name = "Not Assigned", "Not Assigned" for i in range(0, len(person.rooms_occupied)): if "office" in person.rooms_occupied[i]: office_name = person.rooms_occupied[i]['office'] if "living_space" in person.rooms_occupied[i]: living_space_name = person.rooms_occupied[i][ 'living_space'] table.add_row([ person.get_fullname(), person.person_type, office_name, living_space_name ]) print( colorful.blue( "List showing people with space and their respective rooms" )) print(colorful.blue(table))
def print_room(self, room_name): """Prints all the people in a room """ if room_name in [room.name for room in self.rooms]: # output = "\n".join(get_residents # (find_room(self.rooms, room_name))) print( colorful.blue("People in Room: " + room_name + "\n -----------------------------------" "---------------------------------")) print( colorful.blue(", ".join( get_residents(find_room(self.rooms, room_name))))) return get_residents(find_room(self.rooms, room_name)) else: print( colorful.red(room_name + " does not exist in the system." "Please change name and try again!")) return []
def get_methods_string(self, indent=0): resource = self.document # rename methods = resource.get("methods") methods_string = "" if methods: methods_string += colorful.blue("Methods:") for k, v in methods.items(): method = ("\n" + colorful.green(k) + ": " + wrapped_text(v.get("description"), indent)) methods_string += method return methods_string
def log_message(self, message, color='blue'): # Outputs a colorful message to the terminal # and only if is_debug prop is set to True. if self.is_debug: if color == 'blue': message = cf.bold | cf.blue(message) elif color == 'orange': message = cf.bold | cf.orange(message) elif color == 'green': message = cf.bold | cf.green(message) elif color == 'red': message = cf.bold | cf.red(message) print(message)
def display_key_and_value(key: str, value: Any, separator: str, seen: Set[int], show_values: bool = True, indent: int = 0, batch_dims: Optional[Tuple[Optional[int], ...]] = None) -> str: if id(value) in seen: value = "<seen>" elif is_dataclass(value) and not isinstance(value, type): seen.add(id(value)) return (_indent_space(indent) + cf.blue(key) + cf.base00(separator) + display_generic(value, seen, show_values, indent, batch_dims))
def print_room(self, room_name): """ print_room """ if room_name in [room.room_name for room in self.all_rooms]: output = "\n".join(self.find_room(room_name).get_people_in_room()) print( colorful.blue( "People in Room: " + room_name + "\n --------------------------------------------------------------------")) print( colorful.blue( ", ".join( self.find_room(room_name).get_people_in_room()))) return self.find_room(room_name).get_people_in_room() else: print( colorful.red( room_name + " does not exist in the system. Please change name and try again!")) return []
def test_tabular_output_on_print_allocations(self): """Tests that tabular data is output on print_allocations""" #Create StringIO object and redirect output self.dojo.add_person("Dele", "Ali", "Fellow", "Y") program_captured_output = io.StringIO() sys.stdout = program_captured_output self.dojo.print_allocations("", "Y") sys.stdout = sys.__stdout__ table = PrettyTable(['Name', 'Type', 'Office', 'Living Space']) table.add_row(["Dele Ali", "fellow", "testoffice", "testlivingspace"]) captured_output = io.StringIO() sys.stdout = captured_output print( colorful.blue( "List showing people with space and their respective rooms")) print(colorful.blue(table)) sys.stdout = sys.__stdout__ print(program_captured_output.getvalue().strip()) print(captured_output.getvalue()) self.assertTrue(captured_output.getvalue().strip() in program_captured_output.getvalue().strip())
def adjusted_dataframe_and_classification(self, title, override, export): ''' Adjusts training data so that the coverage values are clustered, using anvio clustering algorithm, and the dataframe is sorted Overall, this eases the process of manually inputting the data. This is, however, only useful for inputting training data into the model. ''' self.run_anvi_newick_matrix() self.is_tree_file_OK() self.F = AdjustClassification( tree_file=self.tree_file, directory=self.directory, coverage_values_file=self.coverage_values_file, classified_values_file=self.classified_values_file) self.dataframe = self.F.dataframe.reindex(self.F.genes) self.dataframe['Classification'] = 0 self.dataframe.to_csv(self.coverage_values_file, sep='\t') print( cf.green( """Now we will open up the excel file so you can input the classified values \n\n\n""")) print( cf.green("Opening up '%s' on an Excel spreadsheet\n" % (self.coverage_values_file))) path_to_excel = '/Applications/Microsoft Excel.app' path_to_file = os.path.join(self.directory, self.coverage_values_file) string = "open -a '%s' '%s'" % (path_to_excel, path_to_file) os.system(string) print( cf.blue("""Now launching anvi-interactive. When you are done manually classifying the data, make sure to press CTRL + C to exit out. If the data is already classified, simply press CTRL + C\n""")) self.launch_anvi_interactive(title, override) print( cf.green("""Finished! By now, you must have a column in your Excel spreadsheet labeled 'Classification' and manually inputted the classifying data for each gene. """)) if export: self.export_classifier()
# combine styles with strings print(cf.bold & cf.red | 'Hello World') # use true colors cf.use_true_colors() # extend default color palette cf.update_palette({'mint': '#c5e8c8'}) print(cf.mint_on_snow('Wow, this is actually mint')) # choose a predefined style cf.use_style('solarized') # print the official solarized colors print(cf.yellow('yellow'), cf.orange('orange'), cf.red('red'), cf.magenta('magenta'), cf.violet('violet'), cf.blue('blue'), cf.cyan('cyan'), cf.green('green')) # directly print with colors cf.print('{c.bold_blue}Hello World{c.reset}') # choose specific color mode for one block with cf.with_8_ansi_colors() as c: print(c.bold_green('colorful is awesome!')) # create and choose your own color palette MY_COMPANY_PALETTE = { 'companyOrange': '#f4b942', 'companyBaige': '#e8dcc5' } with cf.with_palette(my_company_palette) as c:
def info(self, *args, **kwargs): self._print(colorful.blue("*"), *args, **kwargs)
def print_apis(): output_str = colorful.blue("Available APIs:") for api in list_api_names_versions(): output_str += colorful.green("\n" + api.get("name") + " " + api.get("version")) print(output_str)
def header(string): # style a header return colorful.blue(string) + "\n"