def createWD(self): # Create WeatherDescription, 天氣預報綜合描述 # Prepare Table Payload payload = [ ["時間(接下來三小時內預測)", "敘述"] ] for wdData in self.rawData["WeatherDescription"]["time"]: payload.append([ wdData["startTime"], wdData["elementValue"][0]["value"] ]) # Create Table table = SingleTable(payload, "天氣預報綜合描述") # Custom Table table.padding_left = 2 table.padding_right = 2 table.justify_columns = { 0: "center", 1: "left" } # Return Table String return table.table
def get_grid(self, astype='table'): from pandas import DataFrame as df geoms = self.geometries().keys() phases = [p.name for p in self.phases().values() if not hasattr(p, 'mixture')] grid = df(index=geoms, columns=phases) for r in grid.index: for c in grid.columns: phys = self.find_physics(phase=self[c], geometry=self[r]) if phys is not None: grid.loc[r][c] = phys.name else: grid.loc[r][c] = '---' if astype == 'pandas': pass elif astype == 'dict': grid = grid.to_dict() elif astype == 'table': from terminaltables import SingleTable headings = [self.network.name] + list(grid.keys()) g = [headings] for row in list(grid.index): g.append([row] + list(grid.loc[row])) grid = SingleTable(g) grid.title = 'Project: ' + self.name grid.padding_left = 3 grid.padding_right = 3 grid.justify_columns = {col: 'center' for col in range(len(headings))} elif astype == 'grid': grid = ProjectGrid() return grid
def createPopandRH(self): # Create PoP6h, RH 6小時降雨機率, 相對濕度 # Prepare Table Payload payload = [ ["時間(接下來六小時內預測)", "相對濕度(%)", "降雨機率(%)"] ] for popData, rhData in zip(self.rawData["PoP6h"]["time"], [d for idx, d in enumerate(self.rawData["RH"]["time"]) if idx % 2 == 0]): payload.append([ popData["startTime"], rhData["elementValue"][0]["value"], popData["elementValue"][0]["value"] ]) # Create Table table = SingleTable(payload, "相對濕度與降雨機率") # Custom Table table.padding_left = 2 table.padding_right = 2 table.justify_columns = { 0: "center", 1: "center", 2: "center" } # Return Table String return table.table
def createWx(self): # Create Wx, 天氣現象 # Prepare Table Payload payload = [ ["時間(接下來三小時內預測)", "形容"] ] for data in self.rawData["Wx"]["time"]: payload.append([ data['startTime'], data["elementValue"][0]["value"] ]) # Create Table table = SingleTable(payload, self.rawData['Wx']['description']) # Custom Table table.padding_left = 2 table.padding_right = 2 table.justify_columns = { 0: "center", 1: "center" } # Return Table String return table.table
def stat_bar(cur): """ one-liner stat bar """ # Block : All=X Ours=Y Oth=Z | Allow : All=X Ours=Y Oth=Z data = [] data.append("Blocks Enabled: All=" + str(get(cur, "total_adlist_enabled"))) data.append("│") data.append("Ours=" + str(get(cur, "our_adlist_enabled"))) # data.append("│") # data.append("Other=" + str(get(cur, "other_adlist_enabled"))) data.append("│") data.append("Allows Enabled: All=" + str(get(cur, "total_allow_enabled"))) data.append("│") data.append("Ours=" + str(get(cur, "our_allow_enabled"))) # data.append("│") # data.append("Other=" + str(get(cur, "other_allow_enabled"))) table = SingleTable([data]) table.inner_heading_row_border = False table.outer_border = False table.inner_row_border = False table.inner_column_border = False table.padding_left = 2 print() print(color(table.table, bg="#505050", fg="white")) print()
def createATandT(self): # Create T, AT 溫度, 體感溫度 # Prepare Table Payload payload = [ ["時間(接下來三小時內預測)", "溫度(C)", "體感溫度(C)"] ] for tData, atData in zip(self.rawData["T"]["time"], self.rawData["AT"]["time"]): payload.append([ tData["dataTime"], tData["elementValue"][0]["value"], atData["elementValue"][0]["value"] ]) # Create Table table = SingleTable(payload, "溫度與體感溫度") # Custom Table table.padding_left = 2 table.padding_right = 2 table.justify_columns = { 0: "center", 1: "center", 2: "center" } # Return Table String return table.table
def print_table(rows): table = SingleTable(rows) table.inner_column_border = False table.inner_footing_row_border = False table.inner_heading_row_border = False table.inner_row_border = False table.outer_border = False table.padding_left = 0 table.padding_right = 3 print(table.table)
def _borderless_table(data): """ Returns a terminaltables.SingleTable object with no borders and correct padding """ tab = SingleTable(data) tab.inner_heading_row_border = False tab.inner_column_border = False tab.outer_border = False tab.padding_left = 0 tab.padding_right = 2 return tab
def block_header(cur): """ block portion of header """ block_data = [ [ "Total :", get(cur, "total_adlist_enabled") + "/" + get(cur, "total_adlist"), ], [ "Our Lists :", get(cur, "our_adlist_enabled") + "/" + get(cur, "our_adlist") ], [ "Others :", get(cur, "other_adlist_enabled") + "/" + get(cur, "other_adlist"), ], ] block_table = AsciiTable(block_data) block_table.inner_heading_row_border = False block_table.outer_border = False block_table.inner_row_border = False block_table.inner_column_border = False rows = adlist_top3_by_comment(cur) t3_block_data = [] for row in rows: t3_block_data.append([row[0], row[1]]) t3_block_table = AsciiTable(t3_block_data) t3_block_table.inner_heading_row_border = False t3_block_table.outer_border = False t3_block_table.inner_row_border = False t3_block_table.inner_column_border = False table_data = [ ["Ad/Blocklist Stats", "Top 3 by Comment"], [block_table.table, t3_block_table.table], [], ] table = SingleTable(table_data) table.padding_left = 2 table.outer_border = False utils.info(table.table)
def _update_table(self): from terminaltables import SingleTable from colorclass import Color max_values = self.cols * self.rows col_out_width = int(self.MAX_COLUMNS / self.cols) col_inn_width = col_out_width - 3 col0_inn_width = 2 col1_inn_width = col_inn_width - col0_inn_width options_number = [' ' * col0_inn_width] * max_values options_label = [' ' * col1_inn_width] * max_values for pos, (name, description, steps) in enumerate(self.tasks): if pos <= max_values: label = [ Color('{autocyan}Name: {}{/autocyan}').format(name), Color('{yellow}({} steps){/yellow}').format(steps), "\n".join(wrap(description, col1_inn_width)) ] wrapped_label = "\n".join(label) options_label[pos] = wrapped_label options_number[pos] = Color( '{autowhite}{}{/autowhite}').format(str(pos)) sliced = [None for i in range(self.cols * 2)] for col in range(self.cols): sliced[col * 2] = options_number[col * self.rows:col * self.rows + self.rows] sliced[1 + col * 2] = options_label[col * self.rows:col * self.rows + self.rows] table_data = zip(*sliced) table = SingleTable(table_data) table.inner_heading_row_border = False table.inner_row_border = True table.padding_left = 0 table.padding_right = 0 table.justify_columns = dict( (i, 'left' if i % 2 else 'right') for i in range(self.cols * 2)) self._table = table
def list_deployments(): def process_versions(versions: List[dict]) -> (str, str): active_version = "None" versions_string = "" for v in sorted(versions, key=lambda version: version["created_on"]): if v["active"]: active_version = v["version"] if versions_string: versions_string += ", " versions_string += v["version"] return (active_version, versions_string) deployments = STATE.api_call("deployments/") table_headers = ["Name", "URL", "Creation Date", "Active Version", "All Versions", "Categories"] table_data = map( lambda datum: [ datum["name"], "{}://{}.{}/".format( STATE.conf["hosting_protocol"], datum["subdomain"], STATE.conf["hosting_base_url"] ), dateutil.parser.parse(datum["created_on"]).strftime("%Y-%m-%d"), *process_versions(datum["versions"]), ", ".join( filter(None, map(lambda category: category["category"], datum["categories"])) ), ], deployments, ) table = SingleTable([table_headers, *table_data]) table.inner_column_border = False table.inner_footing_row_border = False table.inner_heading_row_border = False table.inner_row_border = False table.outer_border = False table.padding_left = 0 table.padding_right = 3 print(table.table)
def build_grid(self, rover_row, rover_col, rover_dir): grid = [] for i in range(self.cols, 0, -1): row = [str(i)] for j in range(self.rows): row.append(self.arrows[rover_dir] if ( rover_row == j + 1 and rover_col == i) else "") grid.append(row) headings = [str(x + 1) for x in range(self.rows)] headings.insert(0, "") grid.append(headings) grid = SingleTable(grid) grid.padding_left = 2 grid.padding_right = 2 grid.inner_heading_row_border = True grid.inner_column_border = True grid.outer_border = False grid.inner_row_border = True return grid.table
def get_grid(self, astype='table'): from pandas import DataFrame as df geoms = self.geometries().keys() phases = [ p.name for p in self.phases().values() if not hasattr(p, 'mixture') ] grid = df(index=geoms, columns=phases) for r in grid.index: for c in grid.columns: phys = self.find_physics(phase=self[c], geometry=self[r]) if phys is not None: grid.loc[r][c] = phys.name else: grid.loc[r][c] = '---' if astype == 'pandas': pass elif astype == 'dict': grid = grid.to_dict() elif astype == 'table': from terminaltables import SingleTable headings = [self.network.name] + list(grid.keys()) g = [headings] for row in list(grid.index): g.append([row] + list(grid.loc[row])) grid = SingleTable(g) grid.title = 'Project: ' + self.name grid.padding_left = 3 grid.padding_right = 3 grid.justify_columns = { col: 'center' for col in range(len(headings)) } elif astype == 'grid': grid = ProjectGrid() return grid
def report_table(ctx, nonhuman_header, human_header, data_rows, title, **table_options): # don't align numbers for non-human reporting if ctx.args.table in ('csv', 'tsv', 'ssv'): data_rows = [[_to_string(ctx, v) for v in row] for row in data_rows] delim = {'csv': ',', 'tsv': '\t', 'ssv': ' '}[ctx.args.table] writer = csv.writer(sys.stdout, quoting=csv.QUOTE_MINIMAL, delimiter=delim) with redirect_stdout(ctx.args.outfile): writer.writerow(nonhuman_header) for row in data_rows: writer.writerow(row) return # align numbers on the decimal point def get_whole_digits(n): if isinstance(n, int): return len(str(n)) if isinstance(n, float): return get_whole_digits(int(n + 0.5)) return 0 whole_digits = [max(map(get_whole_digits, values)) for values in zip(*data_rows)] def pad(n_string, n, col): if isinstance(n, int): return ' ' * (whole_digits[col] - len(n_string)) + n_string if isinstance(n, float): digits = n_string.find('.') if digits == -1: digits = len(n_string) return ' ' * (whole_digits[col] - digits) + n_string return n_string # stringify data data_rows = [[pad(_to_string(ctx, v), v, col) for col, v in enumerate(row)] for row in data_rows] # print human-readable table if ctx.args.table == 'fancy': from terminaltables import SingleTable as Table else: assert ctx.args.table == 'ascii' from terminaltables import AsciiTable as Table table = Table([human_header] + data_rows, ' %s ' % title) table.inner_column_border = False table.padding_left = 0 for kw, val in table_options.items(): if isinstance(val, dict): attr = getattr(table, kw) if isinstance(val, dict): attr.update(val) else: assert isinstance(attr, list) for index, elem in val.items(): attr[index] = elem else: setattr(table, kw, val) with redirect_stdout(ctx.args.outfile): print(table.table)
def print_headline(self, text): text = SingleTable([[text]]) text.padding_left, text.padding_right = [35, 35] print(text.table)