def _visualize(json_data, currency, report_date): data = [] data.append(['Non-Commercial (% long)', 'Commercial (% long)']) non_com_current = json_data['non-commercial']['current'] non_com_changes = json_data['non-commercial']['changes'] com_current = json_data['commercial']['current'] com_changes = json_data['commercial']['changes'] # all data.append([ float(locale.atoi(non_com_changes['long'])) / locale.atoi(non_com_current['long']) * 100, float(locale.atoi(com_changes['long'])) / locale.atoi(com_current['long']) * 100 ]) table = SingleTable(data) table.title = 'Commitment of Traders (long %): ' + currency + " | " + report_date print table.table # Non-Commercial data = [] data.append([ 'Long (current)', 'Short (current)', 'Long (changes)', 'Short (changes)' ]) data.append([ locale.atoi(non_com_current['long']), locale.atoi(non_com_current['short']), locale.atoi(non_com_changes['long']), locale.atoi(non_com_changes['short']) ]) table = SingleTable(data) table.title = 'Commitment of Traders (Non-Commercial):' + currency + "|" + report_date print table.table # Com data = [] data.append([ 'Long (current)', 'Short (current)', 'Long (changes)', 'Short (changes)' ]) data.append([ locale.atoi(com_current['long']), locale.atoi(com_current['short']), locale.atoi(com_changes['long']), locale.atoi(com_changes['short']) ]) table = SingleTable(data) table.title = 'Commitment of Traders (Commercial):' + currency + "|" + report_date print table.table
def add(login, name, email, password): user = Users().create(login, name, email, password) table = SingleTable(Transform().api_response_to_terminaltables( user, include=DEFAULT_DISPLAY_ATTRIBUTES)) table.inner_row_border = True table.title = "List of users" click.echo(table.table)
def close(args): path = args.config['book-path'] if not os.path.isfile(path): print('Order book empty, use buy command to fill it') return data = json.loads(open(path).read()) i = 0 while i < len(data): if data[i]['id'] == args.id: table_data = [[ 'id', 'Exchange', 'Market', 'Price', 'Current', 'Profit' ]] current = get_last_price_tmp(data[i]['market']) profit = get_profit(data[i]['last'], current) table_data.append([ data[i]['id'], data[i]['exchange'], data[i]['market'], data[i]['last'], current, profit ]) table = SingleTable(table_data) table.title = 'Close Order' print(table.table) data.pop(i) break i += 1 with open('./book.json', 'w') as outfile: json.dump(data, outfile, indent=4)
def print_inventory(emoji, emoji_you_have, title="Your Inventory"): newlist = [emoji[1:], emoji_you_have[1:]] table = SingleTable(newlist) table.inner_row_border = True table.inner_heading_row_border = False table.title = title print(table.table)
def main(): user_inp = str(raw_input('Enter the ip address : ')).strip() ip = IPAddress(str(user_inp)) if ip.version == 4: ipaddr = user_inp elif ip.version == 6: ipaddr = user_inp.replace(":","%3A") else: print "Please enter only a valid ipv4 or ipv6 address" sys.exit() tor_result = torproject(ipaddr) status,asn,owner,isp,continent,country,city,region = blacklist(ipaddr) table_data = [["ASN",asn], ["Owner",owner], ["ISP",isp], ["TorNode",tor_result], ["Blacklist",status], ["City",city], ["Region",region], ["Continent",continent], ["Country",country]] table = SingleTable(table_data) table.title = ipaddr table.justify_columns = {0: 'center', 1: 'center'} table.inner_row_border = True print "" print table.table
def print_table(data: List[List[str]] = None, title: str = '', colored_header: bool = True, no_borders: bool = False): if data is None: return # Make header blue if colored_header: for x in range(len(data[0])): data[0][x] = print_utils.color(data[0][x], 'blue') table = SingleTable(data) table.title = title table.inner_row_border = True if no_borders: table.inner_row_border = False table.inner_column_border = False table.outer_border = False table.inner_footing_row_border = False table.inner_heading_row_border = False print('') print(table.table) print('')
def service_list_to_table(worker_info): """ Transforms the worker status into a user-friendly table. Example: >>> service_list_to_table({TODO}) Args: worker_info: The workerInfo object Returns: services_status_stable (terminaltables.SingleTable): A services status represented as a table """ llogger = local_logger.LocalLogger() llogger.log_call(sys._getframe().f_code.co_name) table_data = [['ID', 'Name', 'Image', 'Status']] for service in worker_info.services: table_data.append([ str(service.id), str(service.name), str(service.image), str(service.status) ]) worker_status_table = SingleTable(table_data) worker_status_table.title = SERVICE_STATUS_LIST return worker_status_table.table
def estadosEnCaja(self, nombrecaja): '''Muestra la cantidad de estados diferentes en una caja''' pipeline = [{ '$match': { 'caja': nombrecaja } }, { '$group': { '_id': '$estado', 'cantidad': { '$sum': 1 } } }] estados = list(db.aggregate(pipeline)) #Crea tabla table_data = [[ Color('{autocyan}Estado{/cyan}'), Color('{autocyan}Cantidad{/cyan}') ]] total = 0 for estado in estados: table_data.append([estado['_id'], estado['cantidad']]) total += estado['cantidad'] table_data.append([ Color('{autocyan}Total:{/cyan}'), Color('{autocyan}' + str(total) + '{/cyan}') ]) table = SingleTable(table_data) table.title = nombrecaja table.justify_columns = {0: 'right'} print(table.table)
def add(name, description): workspace = Workspaces().create(name, description) table = SingleTable(Transform().api_response_to_terminaltables( workspace, include=DEFAULT_DISPLAY_ATTRIBUTES)) table.inner_row_border = True table.title = "List of workspaces" click.echo(table.table)
def print_table(table_headers, table_values, table_title='', table_view='v'): os.system("cls") if table_view == 'v': table_data = [table_headers] for i in range(len(table_values[0])): dataline = [] for j in range(len(table_headers)): dataline.append(str(table_values[j][i])) table_data.append(dataline) elif table_view == 'h': table_data = [] for i in range(len(table_values)): table_data.append([table_headers[i]] + list(map(str, table_values[i]))) table = SingleTable(table_data) table.title = table_title table.justify_columns = {0: 'left', 1: 'left', 2: 'left'} table.inner_row_border = False print(table.table)
def print_report(self, scan_results): if not scan_results: return False results = list(scan_results.values()) scan_report = [] scan_report.append([ '#', 'Vuln. Name', 'Risk', 'Severity', 'CVE/CWE ID', 'URLs', 'Desc.', 'Sol.', 'Scanner' ]) count = 0 for vuln in sorted(results, key = lambda x: x['severity'], reverse=True): count += 1 name = vuln['name'] risk = vuln['risk'] severity = vuln['severity'] cve_id = vuln.get('cweid') or vuln.get('cveid', '') urls = list(vuln.get('urls', [])) description = vuln['description'] solution = vuln['solution'] reported_by = vuln['reported_by'] urls = f'({len(urls)} URLs) {urls[0]}' if urls else '' scan_report.append([ count, name, risk, severity, cve_id, urls, 'desc', 'sol', reported_by ]) scan_report_table = SingleTable(scan_report) scan_report_table.title = 'Vuln. Alerts' print(scan_report_table.table)
def print_vending_machine(): line1 = ' 1 2 3 ' line2 = ' ' line3 = ' ^_^ | T-T | @_@ ' line4 = ' 20 | 60 | 100 ' line5 = ' 4 5 6 ' line6 = ' ' line7 = ' @.@ | *-* | :P ' line8 = ' 150 | 200 | 250 ' line9 = ' ' line10 = ' OUTPUT ' line11 = ' ' line12 = ' _______________ ' newlist = [] newlist.append([line1 + "\n" + line2 + "\n" + line3 + "\n" + line4]) newlist.append([line5 + "\n" + line6 + "\n" + line7 + "\n" + line8]) newlist.append([line9 + "\n" + line10 + "\n" + line11 + "\n" + line12]) #print(newlist) table = SingleTable(newlist) table.inner_row_border = True table.inner_heading_row_border = False table.title = "Emoji Vending Machine" sp.call("clear", shell=True) print(table.table)
def swarm_status_to_worker_list(swarm_status): """ Extracts the worker list of the swarm status and transforms it into a user-friendly list representation. Example: >>> swarm_status_to_worker_list({TODO}) Args: swarm_status: Swarm status Returns: worker_list_as_string (string): List of workers """ llogger = local_logger.LocalLogger() llogger.log_call(sys._getframe().f_code.co_name) worker_list = list(dict(swarm_status._worker_list).items()) table_data = [[ 'UUID', 'Hostname', 'AdvertiseAddress', 'Assigned Services', 'Running Services' ]] for worker_list_key, worker_list_val in worker_list: worker = jsonpickle.decode(worker_list_val.get_info_as_json()) running_container_list = [] for service in worker.services: if str(service.status) != 'exited': running_container_list.append(service) table_data.append([ str(worker_list_key), str(worker.hostname), str(worker.advertise_address), str(len(worker.services)), str(len(running_container_list)) ]) table = SingleTable(table_data) table.title = WORKER_STATUS_LIST return table.table
def worker_status_to_table(worker_info): """ Transforms the worker status into a user-friendly table. Example: >>> worker_status_to_table({TODO}) Args: worker_info: The WorkerInfo object Returns: worker_status_stable (terminaltables.SingleTable): A worker status represented as a table """ llogger = local_logger.LocalLogger() llogger.log_call(sys._getframe().f_code.co_name) table_data = [[ 'UUID', 'Swarm UUID', 'AdvertiseAddress', 'Assigned Services', 'Running Services' ]] running_container_list = [] for service in worker_info.services: if str(service.status) != 'exited': running_container_list.append(service) table_data.append([ str(worker_info.uuid), str(worker_info.swarm_uuid), str(worker_info.advertise_address), str(len(worker_info.services)), str(len(running_container_list)) ]) swarm_status_table = SingleTable(table_data) swarm_status_table.title = WORKER_STATUS_TITLE return swarm_status_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 print_agent_table(data: List[List[str]] = None, formatting: List[List[str]] = None, title: str = ''): if data is None: return # Make header blue for x in range(len(data[0])): data[0][x] = print_utils.color(data[0][x], 'blue') for x in range(len(data))[1:]: # Add asterisk for high-integrity agents if formatting[x][1]: data[x][1] = data[x][1] + '*' # color agents if formatting[x][0]: color = 'red' elif not formatting[x][0]: color = 'green' # Set colors for entire row for y in range(len(data[x])): data[x][y] = print_utils.color(data[x][y], color) table = SingleTable(data) table.title = title table.inner_row_border = True print('') print(table.table) print('')
def show_status(self): table_data=[] temp=[] temp.append('Event') for i in range (number_of_players): temp.append(self.event[i]) table_data.append(temp) temp1=[] temp1.append('Diagnosis') for i in range (number_of_players): temp1.append(self.diagnosis[i]) table_data.append(temp1) temp2=[] temp2.append('Tests') for i in range (number_of_players): temp2.append(self.tests[i]) table_data.append(temp2) table=SingleTable(table_data) table.title=Color('{autored}Node ID:'+self.nodeid+' NodeNum:' + self.nodenum+'{/autored}') table.inner_row_border="True" print "" print table.table
def add(name, description, git_url): project = Projects() project = project.create(name, description, git_url) table = SingleTable(Transform().api_response_to_terminaltables( project, include=DEFAULT_DISPLAY_ATTRIBUTES)) table.inner_row_border = True table.title = "List of projects" click.echo(table.table)
def print_table(guessed_result): newlist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], guessed_result] table = SingleTable(newlist) table.inner_row_border = True table.inner_heading_row_border = False table.title = "Number List" # sp.call("clear",shell=True) print(table.table)
def show_packet(self): table_data=[ ['SendID', 'RecvID', 'RootEvent'], ['qwe', 'qwe', 'qwe'] ] table=SingleTable(table_data) table.title=Color('{autocyan}Packet 1/2{/autocyan}') print table.table table_data2=[ ['Event', 'From', 'Topology', 'IsTested'], ['to tez tabl', 'to tez', 'to tez'] ] table2=SingleTable(table_data2) table2.title=Color('{autocyan}Packet 2/2{/autocyan}') print "" print table2.table
def list_files(folder_path): ipa_files = [f for f in os.listdir(folder_path) if str(f).endswith(".ipa")] table_data = [[' * ', Color('{autoblue}%-40s{/autoblue}' % f)] for f in ipa_files] table = SingleTable(table_data) table.title = "All ipa files:" table.inner_column_border = False table.inner_heading_row_border = False print(table.table)
def show_sorted_gold(self): table = SingleTable(self.mat) table.title = Color('{blue}Sorted gold{/blue}') table.inner_row_border = True table.inner_heading_row_border = False for i in range(5): table.justify_columns[i] = 'center' print(table.table) print()
def print_table(title: str, header: List[str], rows: List[List[str]], overhead_col: int) -> None: table = SingleTable([header] + rows) for row in table.table_data: row[overhead_col] = fill(row[overhead_col], width=table.column_max_width(overhead_col)) table.outer_border = False table.title = title print(table.table)
def display_latest_rankings(date=None, json_output=False, data_dir=None, esi_filename=None, esi_sheet_name=None): """Display ESI rankings in the console or output as JSON.""" BOLD = '\033[1m' ENDC = '\033[0m' GREEN = '\033[92m' RED = '\033[91m' indicators = [ 'esi', 'industrial_confidence', 'services_confidence', 'consumer_confidence', 'retail_confidence', 'construction_confidence' ] esi = ESIDataWrapper() if data_dir: esi.data_dir = data_dir if esi_filename: esi.esi_filename = esi_filename if esi_sheet_name: esi.esi_sheet_name = esi_sheet_name num_entries = len(esi.ESI_ENTITIES) rankings = esi.get_latest_rankings(date=date) if json_output: print(json.dumps(rankings)) else: table_data = [ # Headers. [ BOLD + 'ESI' + ENDC, 'Industrial Confidence (40%)', 'Services Confidence (30%)', 'Consumer Confidence (20%)', 'Retail Trade Confidence (5%)', 'Construction Confidence (5%)' ] ] for i in range(num_entries): if i == 0: tmpl = GREEN + '{} ({})' + ENDC elif i == 15: tmpl = RED + '{} ({})' + ENDC else: tmpl = '{} ({})' row = [ tmpl.format(rankings[indicator][i][0], rankings[indicator][i][1]) for indicator in indicators ] table_data.append(row) rankings_table = SingleTable(table_data) rankings_table.inner_heading_row_border = False rankings_table.inner_heading_row_border = True if date: rankings_table.title = 'Rankings for {}'.format(date) print(rankings_table.table)
def print_query_table(cursor, title): # Fetch the result of the last execution rows = list(cursor.fetchall()) # insert column header rows.insert(0, [row[0] for row in cursor.description]) # table config table = SingleTable(rows) table.inner_row_border = True table.title = title print(table.table)
def format_config_read_queue(self, use_color: bool = False, max_col_width: int = 50) -> str: """ Prepares a string with pretty printed config read queue. :param use_color: use terminal colors :param max_col_width: limit column width, ``50`` by default :return: """ try: from terminaltables import SingleTable except ImportError: import warnings warnings.warn( 'Cannot display config read queue. Install terminaltables first.' ) return '' col_names_order = ['path', 'value', 'type', 'parser'] pretty_bundles = [[ self._colorize(name, name.capitalize(), use_color=use_color) for name in col_names_order ]] for config_read_item in self.config_read_queue: pretty_attrs = [ config_read_item.variable_path, config_read_item.value, config_read_item.type, config_read_item.parser_name ] pretty_attrs = [ self._pformat(pa, max_col_width) for pa in pretty_attrs ] if config_read_item.is_default: pretty_attrs[0] = '*' + pretty_attrs[0] if use_color: pretty_attrs = [ self._colorize(column_name, pretty_attr, use_color=use_color) for column_name, pretty_attr in zip( col_names_order, pretty_attrs) ] pretty_bundles.append(pretty_attrs) table = SingleTable(pretty_bundles) table.title = self._colorize('title', 'CONFIG READ QUEUE', use_color=use_color) table.justify_columns[0] = 'right' # table.inner_row_border = True return str(table.table)
def print_input_table(process_list): yh = open('input_all.txt') #百合みたい(笑)。妄想すぎだろう pn = 1 input_table = [['Process', 'Burst Time', 'Arrival Time', 'Priority']] for p in process_list: input_table.append( ["P" + str(p.id), p.burst_time, p.arrival_time, p.priority_number]) in_table = SingleTable(input_table) in_table.title = "Input Data: " print(in_table.table)
def ls(id): if id: users = Users().get(id) else: users = Users().get_all() if users: table = SingleTable(Transform().api_response_to_terminaltables( users, include=DEFAULT_DISPLAY_ATTRIBUTES)) table.inner_row_border = True table.title = "List of users" click.echo(table.table)
def show_result(self, matrix, line): matrix[0][0] = Color('{green}START{/green}') matrix[-1][-1] = Color('{red}FINISH{/red}') table = SingleTable(matrix) table.title = Color('{yellow}Path{/yellow}') table.inner_row_border = True table.inner_heading_row_border = False for i in range(line + 1): table.justify_columns[i] = 'center' print(table.table) print('\nThe maximum amount of gold that the robot can mine =', sum(self.x))
def as_table(tlv, title=None, redact=False): res = [['Tag', 'Name', 'Value']] if type(tlv) is not TLV: return '' for tag, value in tlv.items(): res.append([ format_bytes(tag.id), tag.name or '', '\n'.join( textwrap.wrap(render_element(tag, value, redact=redact), 80)) ]) table = SingleTable(res) if title is not None: table.title = title return table.table
def return_tabulated(): for key, value in scores.items(): table_data.append([key, value[0], value[1]]) table_data.insert(0, ['STATE', 'DEMOCRAT', 'REPUBLICAN']) table = SingleTable(table_data) table.title = 'Model Index Scores' table.inner_row_border = True table.justify_columns[0] = 'right' table.justify_columns[1] = 'center' table.justify_columns[2] = 'center' print(table.table)
def worker_daemon_status_to_table(worker_status): """ Formats the worker status as a Table :param worker_status: Table of the worker status :return: """ llogger = local_logger.LocalLogger() llogger.log_call(sys._getframe().f_code.co_name) table_data = [['UUID', 'Swarm UUID', 'Advertise Address']] for _, val in list(dict(worker_status).items()): table_data.append([str(val.uuid), str(val.swarm_uuid), str(val.advertise_address)]) table = SingleTable(table_data) table.title = WORKER_STATUS_TITLE return table.table
def main(): # URI Link URI = "http://dashboard.pldthome.com/HomeWifiLoad/Availment/_LoadBalance" # Get the data data = request.urlopen(URI).read() # Create a BeatifulSoup object soup = BeautifulSoup(data, "html.parser") # Retrieve Main Title from the page main_title = soup.find("h2", {"class": "hwd"}).getText() # Retrieve the parent of the significant data parent_element = soup.find("div", {"class": ["balance", "prepaid"]}) # Retrieve significant data general_data = parent_element.findAll("div", {"class": ["row", "prepaid"]}) rows = list() for row in general_data: # Title of data title = row.find("p", {"class": "family-pack"}).getText().title() # Value of data value = row.find("p", {"class": ["value", "bal-info"]}).getText() # Expiration date tmp_exp = row.find("p", {"class": "expiration"}).getText() if tmp_exp.startswith("Expires on "): exp = tmp_exp[11:] rows.append([title, value, exp]) # Custom column name col_name = ["Name", "Value", "Expiration"] # insert column names to rows rows.insert(0, col_name) # Create a table table = SingleTable(rows) # Set table title table.title = chalk.yellow(main_title) # Print the table print(table.table)
def show_aur(self, matrix_a, line, column): try: if line == '0' and column == '0': print(Color('{red}File is empty!{/red}\n')) elif matrix_a != []: table = SingleTable(matrix_a) table.title = Color( '{autoyellow}GOLD-BEARING AREA{/autoyellow}') table.inner_row_border = True table.inner_heading_row_border = False print(table.table) print() except FileNotFoundError: print(Color('{red}File wasn\'t found{/red}\n'))
def as_table(tlv, title=None, redact=False): res = [["Tag", "Name", "Value"]] if type(tlv) is not TLV: return "" for tag, value in tlv.items(): res.append([ format_bytes(tag.id), tag.name or "", "\n".join( textwrap.wrap(render_element(tag, value, redact=redact), 80)), ]) table = SingleTable(res) if title is not None: table.title = title return table.table
def _print_deployment_summary(env): table_data = [ ["Project name:", env.project_name], ["Target:", env.target_name], ["User:"******"Host(s):", "; ".join(env.hosts)], ] table = SingleTable(table_data) table.title = Color('{autoyellow}Deployment configuration{/autoyellow}') table.justify_columns = {0: 'left', 1: 'left'} table.inner_row_border = False table.inner_heading_row_border = False _print_table(table)
def show_matches(): from models import Match from terminaltables import SingleTable # Initialize table data data = [['keyword', 'answer']] # List all matches matches = list(Match.select().order_by(Match.keyword, Match.id)) for match in matches: data.append([str(match.keyword), str(match.answer).replace('\n', '↵')[:30]]) # Create and print table table = SingleTable(data) table.title = '{} dialogues'.format(len(matches)) print(table.table)
def main(): user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36' headers = { 'User-Agent' : user_agent } trackingid = raw_input("Please enter the trackingid of your UPS package : ") url1 = "https://wwwapps.ups.com/WebTracking/processRequest?HTMLVersion=5.0&Requester=NES&AgreeToTermsAndConditions=yes&loc=en_US&" url2 = "tracknum={0}".format(trackingid) if len(trackingid) < 18: print "The tracking id is wrong" url = url1 + url2 city,country,statusdate,localtime,activity = ups(url,headers) table_data = [["Tracking ID",trackingid], ["City",city], ["Country",country], ["Status Date",statusdate], ["Status Time",localtime], ["Status",activity]] table = SingleTable(table_data) table.title = "UPS Package Status" table.justify_columns = {0: 'center', 1: 'center'} table.inner_row_border = True print "" print table.table
ascii_table = AsciiTable(table_data) print ascii_table.table ascii_table.inner_row_border = True print ascii_table.table print single_table = SingleTable(table_data) print single_table.table single_table.inner_row_border = True print single_table.table single_table.title = "List" print single_table.table print gfw_table = GithubFlavoredMarkdownTable(table_data) print gfw_table.table """ +-------+------+ | Name | Size | +-------+------+ | test1 | 512M | | test2 | 1G | +-------+------+
from terminaltables import SingleTable Windows.enable(auto_colors=True, reset_atexit=True) # Does nothing if not on Windows. table_data = [ [Color('{autobgred}{autogreen}<10ms{/autogreen}{/bgred}'), '192.168.0.100, 192.168.0.101'], [Color('{autoyellow}10ms <= 100ms{/autoyellow}'), '192.168.0.102, 192.168.0.103'], [Color('{autored}>100ms{/autored}'), '192.168.0.105'], ] table = SingleTable(table_data) table.inner_heading_row_border = False print() print(table.table) table.title = '192.168.0.105' table.justify_columns = {0: 'center', 1: 'center', 2: 'center'} table.inner_row_border = True table.table_data = [ [Color('Low Space'), Color('{autocyan}Nominal Space{/autocyan}'), Color('Excessive Space')], [Color('Low Load'), Color('Nominal Load'), Color('{autored}High Load{/autored}')], [Color('{autocyan}Low Free RAM{/autocyan}'), Color('Nominal Free RAM'), Color('High Free RAM')], ] print() print(table.table) table.title = None table.outer_border = False table.table_data = [['A', 'B'], ['C', 'D']] print() print(table.table)