def print_table(self): t = AsciiTable(self.table) t.inner_heading_row_border = False print(t.table) t = AsciiTable(self.backptr) t.inner_heading_row_border = False print(t.table)
def output_ascii_table_list(table_title=None, table_data=None, table_header=None, inner_heading_row_border=False, inner_row_border=False): """ @type table_title: unicode @type table_data: list @type inner_heading_row_border: bool @type inner_row_border: bool @type table_header: list """ console_rows, _ = get_console_dimensions() console_rows = int(console_rows) full_display_length = len(table_data) + 7 items_per_page = console_rows - 7 num_pages = 0 if full_display_length > console_rows: try: num_pages = int( math.ceil(float(len(table_data)) / float(items_per_page))) except ZeroDivisionError: exit('Console too small to display.') if num_pages: running_count = 0 for page in range(1, num_pages + 1): page_table_output = list() page_table_output.insert(0, table_header) upper = (console_rows + running_count) - 7 if upper > len(table_data): upper = len(table_data) for x in range(running_count, upper): page_table_output.append(table_data[x]) running_count += 1 table = AsciiTable(page_table_output) table.inner_heading_row_border = inner_heading_row_border table.inner_row_border = inner_row_border table.title = table_title if page != 1: print('') print(table.table) if page < num_pages: input("Press Enter to continue...") os.system('clear') else: table_data.insert(0, table_header) table = AsciiTable(table_data) table.inner_heading_row_border = inner_heading_row_border table.inner_row_border = inner_row_border table.title = table_title print(table.table)
def output_ascii_table_list(table_title=None, table_data=None, table_header=None, inner_heading_row_border=False, inner_row_border=False): """ @type table_title: unicode @type table_data: list @type inner_heading_row_border: bool @type inner_row_border: bool @type table_header: list """ console_rows, _ = get_console_dimensions() console_rows = int(console_rows) full_display_length = len(table_data) + 7 items_per_page = console_rows - 7 num_pages = 0 if full_display_length > console_rows: try: num_pages = int(math.ceil(float(len(table_data)) / float(items_per_page))) except ZeroDivisionError: exit('Console too small to display.') if num_pages: running_count = 0 for page in range(1, num_pages + 1): page_table_output = list() page_table_output.insert(0, table_header) upper = (console_rows + running_count) - 7 if upper > len(table_data): upper = len(table_data) for x in range(running_count, upper): page_table_output.append(table_data[x]) running_count += 1 table = AsciiTable(page_table_output) table.inner_heading_row_border = inner_heading_row_border table.inner_row_border = inner_row_border table.title = table_title if page != 1: print('') print(table.table) if page < num_pages: input("Press Enter to continue...") os.system('clear') else: table_data.insert(0, table_header) table = AsciiTable(table_data) table.inner_heading_row_border = inner_heading_row_border table.inner_row_border = inner_row_border table.title = table_title print(table.table)
def show_workflow(ctx, name): """Display details of a workflow""" data = [] try: workflow = cel_workflows.get_by_name(name) except WorkflowNotFound as e: click.echo(f"Error: {e}") return # Construct the table data.append(["Name", name]) # Wrap the tasks list tasks_str = "" for task in workflow["tasks"]: tasks_str += f"{task}\n" # Just remove the last newline if tasks_str: tasks_str = tasks_str[:-1] data.append(["Tasks", tasks_str]) # Handle periodic information periodic = workflow.get("periodic", {}).get("schedule", "--") data.append(["Periodic", periodic]) payload = workflow.get("periodic", {}).get("payload", {}) data.append(["Payload", payload]) table = AsciiTable(data) table.inner_heading_row_border = False table.inner_row_border = True click.echo(table.table)
def current_session_summary(self): mission_values = sum( [b["MissionValue"] for b in self.session_bounties]) reward_values = sum([ sum(r["Reward"] for r in b["Rewards"]) for b in self.session_bounties ]) cr_earned = mission_values + reward_values time_in_session = ((self.most_recent_update_at - self.first_pirate_killed_at).total_seconds() / 3600.0) hrs = round(time_in_session, 2) num_pirates_killed = len(self.session_bounties) kills_per_hour = 0.0 if self.first_pirate_killed_at != None and time_in_session != 0: kills_per_hour = round(num_pirates_killed / time_in_session, 1) cr_per_hour = 0.0 if self.first_pirate_killed_at != None and time_in_session != 0: cr_per_hour = cr_earned / time_in_session table_data = [ ["Kills", f'{num_pirates_killed}'], ["Kills/hr", f'{kills_per_hour}'], ["CR earned", '${:,}'.format(int(cr_earned))], ["CR/hr", '${:,}'.format(int(cr_per_hour))], ] table = AsciiTable(table_data, f" Session stats ({hrs} hrs)") table.inner_heading_row_border = False return table.table
def option(self): """ Print the options required by the module Usage: options [-h] Options: -h, --help print this help menu """ table_data = [ ["Name", "Current Settings", "Required", "Description"] ] for name, options in self.options.items(): table_data.append([name, options["Current Settings"], options["Require"], options["Description"]]) table = AsciiTable(table_data) table.inner_column_border = False table.inner_footing_row_border = False table.inner_heading_row_border = True table.inner_row_border = False table.outer_border = False print (f'\nModule Options ({self.name}):\n\n{table.table}\n')
def home_office(ctx, year=CURRENT_YEAR): """ Show home office expenses. """ ss = open_spreadsheet('Home Office %s' % year) worksheet = ss.worksheet('Monthly fees') categories = defaultdict(Decimal) for row in worksheet.get_all_records(): categories['hoa assessments'] += get_decimal(row['hoa assessments']) categories['homeowners insurance'] += get_decimal(row['homeowners insurance']) categories['mortgage'] += get_decimal(row['mortgage']) categories['utilities (gas & electric)'] += \ get_decimal(row['electric']) + get_decimal(row['gas']) data = [(k.capitalize(), v) for k, v in categories.items()] data += [ (f'Total for {year}', sum(categories.values())), (f'Office rent for {year}', sum(categories.values()) / 4), ('Repairs & maintenance', get_rm_total(ss)), ] table = AsciiTable(data, 'Home office') table.inner_heading_row_border = False print(table.table)
def print(self): """ Print cart contents """ table_data = [] tables_headers = ['Item', ' ', 'Price'] border_row = ["----", "", "-----"] table_data.append(tables_headers) table_data.append(border_row) msg = "" for item in self.contents(): row = [item.product_code, "", "{0:.2f}".format(item.price)] table_data.append(row) if item.discount: discount_row = ["", item.coupon, f"-{item.discount}"] table_data.append(discount_row) total_row = ["", "", "{0:.2f}".format(self.total())] table_data.append(total_row) table = AsciiTable(table_data=table_data) table.inner_column_border = False table.outer_border = False table.inner_heading_row_border = False table.inner_footing_row_border = True table.justify_columns[1] = 'center' # Justify coupons center table.justify_columns[2] = 'right' # Justify prices right msg += table.table return msg
def render_summary(summary, title=None, outer_border=True): # we should split long lines here at some point. table = AsciiTable(summary, title=title) table.inner_heading_row_border = False table.outer_border = outer_border return str(table.table)
def main_help(): commands = ['database', 'sniffing', 'exploit', 'modelling', 'exit'] description = [ 'Use database mode.', 'Use sniffing mode.', 'Use exploit mode.', 'Use modelling mode.', 'Quit this program' ] table_data = [['Commands', 'Description']] for i in range(len(commands) - 1): table_data.append([commands[i], description[i]]) table = AsciiTable(table_data) table.inner_column_border = False table.inner_footing_row_border = False table.inner_heading_row_border = True table.inner_row_border = False table.outer_border = False msg = f""" Core commands ============= {table.table}\n\n""" return msg
def get_puzzle_as_str(puzzle): table = AsciiTable(puzzle) table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns[0] = "center" table.justify_columns[1] = "center" return table.table
def to_readable_output(self, serialized_packet): """Converts the decoded, but serialized packet to a clean, readable output. Intended for human readability. Args: serialized_packet: The raw, decoded APRS packet string. """ try: packet = aprslib.parse(serialized_packet) table_data = [[ "From ", "To ", "Lat ", "Long ", "Alt ", "Comment ", "Text " ], [ self.__get_formatted(packet, 'from', 9), self.__get_formatted(packet, 'to', 9), self.__get_formatted(packet, 'latitude', 8), self.__get_formatted(packet, 'longitude', 8), self.__get_formatted(packet, 'altitude', 8), self.__get_formatted(packet, 'comment', 27), self.__get_formatted(packet, 'text', 27), ]] table_instance = AsciiTable(table_data, ' Packet ') table_instance.inner_heading_row_border = False table_instance.inner_row_border = True return '\n' + table_instance.table except (aprslib.ParseError, aprslib.UnknownFormat): return serialized_packet
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 show_workflows(self): details = [] workflows = self.metascan.get_workflows() for wf in workflows.json(): details.append([wf["name"]]) table = AsciiTable(details, "Workflows") table.inner_heading_row_border = False print table.table
def _simple_table(data): if isinstance(data, str): return data assert isinstance(data, dict) table = [[key, _pp(value)] for key, value in data.items()] st = AsciiTable(table) st.inner_heading_row_border = False return st.table
def show_license(self): licenses = self.metascan.get_license() details = [] for lic in licenses.json().iteritems(): details.append([str(lic[0]), str(lic[1])]) table = AsciiTable(details, "Licenses") table.inner_heading_row_border = False print table.table
def current_materials_table(self): materials_table = [] for mat_type in self.MATERIAL_DATA.keys(): table_instance = AsciiTable(self.material_table_data[mat_type], f" {mat_type} ") table_instance.inner_heading_row_border = False materials_table.append(table_instance.table) return materials_table
def show_status(self, services=None): services = self.check_service(services, msg='In SHOW STATUS:') table_data = [] table_data.append([ 'Service', 'Host', 'Service-Status', 'Image-Status', 'Depends-On', 'Ports', 'Network-Mode', 'Stats' ]) try: default_network = self.stream['networks']['default']['driver'] except: default_network = 'bridge' for service in services: container = self.get_container_instance_by_service_name(service) host = self.get_host_instance_by_container_id(service) image_status = '' host_color = "{autobgwhite}{%s}%s{/%s}{/autobgwhite}" % ( host.color, container.hostip, host.color) container_color = "{autobgwhite}{%s}%s{/%s}{/autobgwhite}" % ( container.color, container.status, container.color) if container._image_status == 'changed': image_status = container._image_status depends = '' for depend in container.s_depends_on: depend_container = self.get_container_instance_by_service_name( depend) depend_container_color = "- {autobgwhite}{%s}%s{/%s}{/autobgwhite}\n" % ( depend_container.color, depend, depend_container.color) depends += (Color(depend_container_color)) depends = depends.strip('\n') ports = '' for port in container.ports: ports += "- %s\n" % port ports = ports.strip('\n') nm = default_network if container.network_mode == '' else container.network_mode stats = '' for s in [ 'cpu:' + str(container.cpu_utilization) + '%' + '\n', 'mem:' + str(container.mem_usage) + 'm' + '\n', 'check:' + str(container.exec_time) + 'ms' ]: stats += s table_data.append([ container.id, Color(host_color), Color(container_color), image_status, depends, ports, nm, stats ]) table_instance = AsciiTable(table_data) table_instance.inner_heading_row_border = False table_instance.inner_row_border = True print table_instance.table
def _create_table(data): """Creates a table from the given data.""" table = AsciiTable(data) table.inner_column_border = False table.inner_row_border = False table.outer_border = False table.inner_heading_row_border = False table.padding_right = 4 return str(table.table)
def display_account_summary(self): html_txt = self.login() parse_data = self.parse_response(html_txt) table_data = [(key, chalk.blue(value)) for key, value in parse_data] table_instance = AsciiTable(table_data) table_instance.inner_heading_row_border = False table_instance.inner_row_border = True print(chalk.blue("\nAccount Summary".upper())) print(table_instance.table)
def overview(self): print("Layers:") overview = [] for layer in self.layers: overview.append(layer._overview()) table = AsciiTable(overview) table.inner_heading_row_border = False print(table.table)
def printOut(self): # Again we loop over to get the most common(n) values and print this in a table for key, value in self.dataList.items(): collection = collections.Counter( self.dataList[key]).most_common(10) tableData = AsciiTable(collection) tableData.inner_heading_row_border = False tableData.title = key print(tableData.table)
def view_tags(): """ View all tags currently in the database. """ db = tagdb.db(notes_dir) all_tags = [ x['name'] for x in db.get_all_tags() ] alphabet_sorted_tags = sorted(all_tags) # Breaking this down: itertools.groupby() tags_in_lists = [alphabet_sorted_tags[i:i+3] for i in range(0, len(alphabet_sorted_tags), 3)] table = AsciiTable(tags_in_lists) table.inner_heading_row_border = False print(table.table)
def get_puzzle_as_str(puzzle): # print(puzzle) # raise ValueError(str(puzzle)) table = AsciiTable(puzzle) table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns[0] = "center" table.justify_columns[1] = "center" return table.table
def print_matches(matches): matches_arr = [] for match in matches: #match_arr = [str(match[2]), str(match[3]), str(match[4]), str(match[5]), str(match[1])] match_arr = [str(match[2]), str(match[3]), str(match[4]), str(match[5])] matches_arr.append(match_arr) #print (matches_array) table = AsciiTable(matches_arr) table.inner_heading_row_border = False table.inner_row_border = True print (table.table)
def output_tables(self): global sectorsPassingCond global errorStocks stocksRankingTable = AsciiTable(sectorsPassingCond) stocksRankingTable.inner_heading_row_border = True logger.info('\n') logger.info('Potential candidates:') logger.info(stocksRankingTable.table) self.out_file.write('\n') self.out_file.write('Potential candidates:\n') self.out_file.write(stocksRankingTable.table) errorStocksTable = AsciiTable(errorStocks) errorStocksTable.inner_heading_row_border = True logger.info('\n') logger.info('Stocks with ERRORs:') logger.info(errorStocksTable.table) self.out_file.write('\n') self.out_file.write('Stocks with ERRORs:\n') self.out_file.write(errorStocksTable.table)
def remainingWords(self): """ Returns the current board as a formatted string """ data = [] for i in range(0, len(self.wordgrid), 5): data.append(self.wordgrid[i:i + 5]) table = AsciiTable(data) table.inner_heading_row_border = False return table.table
def output_tables(self): global sectorsPassingCond global errorStocks stocksRankingTable = AsciiTable(sectorsPassingCond) stocksRankingTable.inner_heading_row_border = True logger.info('\n') logger.info('Potential candidates:') logger.info(stocksRankingTable.table) self.out_file.write('\n') self.out_file.write('Potential candidates:\n') self.out_file.write(stocksRankingTable.table) errorStocksTable = AsciiTable(errorStocks) errorStocksTable.inner_heading_row_border = True logger.info('\n') logger.info('Stocks with ERRORs:') logger.info(errorStocksTable.table) self.out_file.write('\n') self.out_file.write('Stocks with ERRORs:\n') self.out_file.write(errorStocksTable.table)
def do_stats(self, arg): """Lists some statistics about the merged database""" user_count = self.hist.get_user_count() url_count = self.hist.get_url_count() visit_count = self.hist.get_visit_count() table = AsciiTable([ ["Users", user_count], ["Urls", url_count], ["Visits", visit_count] ], "Stats") table.inner_heading_row_border = False print(table.table)
def print(self, data, **kwargs): table = AsciiTable(data) table.inner_footing_row_border = False table.inner_row_border = False table.inner_column_border = False table.outer_border = False if "inner_heading_row_border" in kwargs: table.inner_heading_row_border = kwargs["inner_heading_row_border"] if "style" in kwargs: table.justify_columns = kwargs["style"] click.echo(table.table)
def list_users(self): users_table = [['Room', 'User']] for room, members in rooms.iteritems(): for conn in members: for nickname, sock_conn in conn.iteritems(): users_table.append([room, nickname]) users_table_instance = AsciiTable(users_table) users_table_instance.inner_heading_row_border = True users_table_instance.inner_row_border = False users_table_instance.justify_columns = {0: 'left', 1: 'left'} print users_table_instance.table
def print_model_params(): params = [['epochs', args.epochs]] params.append(['batch size', args.batch_size]) params.append(['lstm units', args.lstm_units]) params.append(['input point len', args.input_point_len]) params.append(['gradient clip', args.gradient_clip]) params.append(['train pred len', args.train_pred_len]) params.append(['test pred len', args.test_pred_len]) params.append(['dropout input', args.dropout_input]) params.append(['learning rate', args.learning_rate]) table = AsciiTable(params) table.inner_heading_row_border = False print(table.table)
def display_ip(ctx, compartment_id, instance): """Display public/private IP for the instance.""" if not instance: ctx.exit(1) vnic = ctx.obj['oci'].get_vnic(compartment_id, instance) if not vnic: ctx.exit(1) table = AsciiTable( (('Private IP', vnic.private_ip), ('Public IP', vnic.public_ip))) table.inner_heading_row_border = False table.title = 'Instance provisioned' click.echo(table.table)
def checking_account(ctx, year=CURRENT_YEAR): """ Print business checking account metrics. """ ss = open_spreadsheet('Business Checking Account Activity') worksheet = ss.worksheet(year) debit = credit = revenue = Decimal(0.0) categories = defaultdict(Decimal) rows = worksheet.get_all_records() for row in rows: category = row['Category'] if category == 'Revenue': revenue += get_decimal(row['Credit']) else: categories[category] += get_decimal(row['Debit']) debit += get_decimal(row['Debit']) credit += get_decimal(row['Credit']) data = [ ('Total debit', debit), ('Total credit', credit), ('Total revenue', revenue) ] table = AsciiTable(data, 'Summary') table.inner_heading_row_border = False print(table.table) data = sorted(categories.items(), key=lambda x: x[1], reverse=True) table = AsciiTable(data, 'Debits by category') table.inner_heading_row_border = False print(table.table)
def tableprint(noModifydata, cutColoumn, tableName='', itemize=-1, initCol=0, lastCol=10): MAX_TABLE_WIDTH = 80 minCol = int(MAX_TABLE_WIDTH / 5) data = [] # Copy all input data to local list # Convert to mutable type - list # And cut coloumns if needed for i, row in enumerate(noModifydata): data.append(list(row[initCol:(lastCol + 1)])) # If selection table if itemize >= 0: tableName = 'Select ' + tableName[:MAX_TABLE_WIDTH - 10] # Add item number if needed cutColoumn += 1 for row in data: row.insert(0, itemize) itemize += 1 else: tableName = tableName[:MAX_TABLE_WIDTH - 3] table = AsciiTable(data, title=tableName) width = table.table_width if width > MAX_TABLE_WIDTH: maxCol = table.column_widths[cutColoumn] - (width - MAX_TABLE_WIDTH) maxCol = minCol if maxCol < minCol else maxCol for i, row in enumerate(data): row = list(row) # Cutting row if needed if row[cutColoumn] == None: row[cutColoumn] = '------' elif len(row[cutColoumn]) > maxCol: row[cutColoumn] = row[cutColoumn][:maxCol - 4] + '... ' else: pass data[i] = row table = AsciiTable(data, title=tableName) table.inner_heading_row_border = False print(table.table)
def _get_print_info(self): """ Returns console-formatted table showing essential values to end user. """ table_data = [ [clrz('source', 'cyan'), clrz(self.original, 'white')], # [clrz('source', 'cyan'), click.style(self.original, fg='green', blink=True, bold=True)], [clrz('output', 'cyan'), clrz(self.output, 'white')], [clrz('preset', 'cyan'), clrz(self.preset_name, 'magenta')], [clrz('duration', 'cyan'), clrz(str(self.duration), 'red')], [clrz('framerate', 'cyan'), clrz(str(self.frame_rate), 'red')], [clrz('frames', 'cyan'), clrz(str(int(self.duration * self.frame_rate)), 'red')], ] table = AsciiTable(table_data, clrz(' FFSE - the FFS Encoder ', 'yellow')) table.inner_heading_row_border = False return table.table
def output_ascii_table(table_title=None, table_data=None, inner_heading_row_border=False, inner_footing_row_border=False, inner_row_border=False): """ @type table_title: unicode @type table_data: list @type inner_heading_row_border: bool @type inner_footing_row_border: bool @type inner_row_border: bool """ table = AsciiTable(table_data) table.inner_heading_row_border = inner_heading_row_border table.inner_row_border = inner_row_border table.inner_footing_row_border = inner_footing_row_border table.title = table_title print(table.table)
def info(self, options): """ Display service status information. Usage: info """ from terminaltables import AsciiTable rows = [] for key, value in self.project.info().iteritems(): rows.append([key + ':', value]) table = AsciiTable(rows) table.outer_border = False table.inner_column_border = False table.inner_heading_row_border = False table.title = 'Dork status information' print table.table
def create_table(res_map): table_data = [['function', 'path_params', 'methods', 'query_params / body']] max_width = 30 _data = [] for key, value in res_map.items(): _function = key pp = re.findall(r"\{(\w+)\}", value['resource']) _path_params = '' if pp: _path_params = ",\n".join(pp) _methods = ",\n".join(value['methods']) _remarks = '\n'.join(wrap(value['remarks'], 30)) _data.append([_function, _path_params, _methods, _remarks]) table_data.extend(_data) table_instance = AsciiTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = True return table_instance
def rateSectors(self, args): idx = 0 for sector in self.sectors_list: logger.info("Rating sector %s..." % (sector, )) rating = 0 # self.stock.plotlyData(i_destDictKey=sector) if self.stock.m_data['SPY']['analysis']['d']['trendType'] == self.stock.m_data[sector]['analysis']['d']['trendType'] and \ self.stock.m_data['SPY']['analysis']['d']['trendType'] > 0 and \ self.stock.m_data[sector]['analysis']['d']['trendType'] > 0: rating = rating + RATE_1_SCORE if not DAILY_ONLY_BASED: if self.stock.m_data[sector]['analysis']['d']['trendType'] == 2: # up if self.stock.m_data[sector]['analysis']['w']['moveType'] == 2: # up rating = rating + RATE_2_SCORE * 0.5 if self.stock.m_data['SPY']['analysis']['w']['moveType'] == 2: # up rating = rating + RATE_2_SCORE * 0.125 if self.stock.m_data[sector]['analysis']['m']['moveType'] == 2: # up rating = rating + RATE_2_SCORE * 0.25 if self.stock.m_data['SPY']['analysis']['m']['moveType'] == 2: # up rating = rating + RATE_2_SCORE * 0.125 elif self.stock.m_data[sector]['analysis']['d']['trendType'] == 1: # down if self.stock.m_data[sector]['analysis']['w']['moveType'] == 1: # down rating = rating + RATE_2_SCORE * 0.5 if self.stock.m_data['SPY']['analysis']['w']['moveType'] == 1: # down rating = rating + RATE_2_SCORE * 0.125 if self.stock.m_data[sector]['analysis']['m']['moveType'] == 1: # down rating = rating + RATE_2_SCORE * 0.25 if self.stock.m_data['SPY']['analysis']['m']['moveType'] == 1: # down rating = rating + RATE_2_SCORE * 0.125 if self.stock.m_data[sector]['analysis']['d']['rs'] >= RS_THS: rating = rating + RATE_3_SCORE if DAILY_ONLY_BASED: if (self.stock.m_data[sector]['analysis']['d']['trendType'] == 2) and \ (self.stock.m_data[sector]['analysis']['d']['moveType'] == 2): # up rating = rating + RATE_4_SCORE * 0.7 elif (self.stock.m_data[sector]['analysis']['d']['trendType'] == 1) and \ (self.stock.m_data[sector]['analysis']['d']['moveType'] == 1): # up rating = rating + RATE_4_SCORE * 0.7 else: if (self.stock.m_data[sector]['analysis']['d']['trendType'] == 2) and \ (self.stock.m_data[sector]['analysis']['d']['moveType'] == 2) and \ (self.stock.m_data[sector]['analysis']['w']['moveType'] == 2): # up rating = rating + RATE_4_SCORE * 0.7 elif (self.stock.m_data[sector]['analysis']['d']['trendType'] == 1) and \ (self.stock.m_data[sector]['analysis']['d']['moveType'] == 1) and \ (self.stock.m_data[sector]['analysis']['w']['moveType'] == 1): # up rating = rating + RATE_4_SCORE * 0.7 if (self.stock.m_data[sector]['analysis']['d']['moveType'] == 2) and \ (self.stock.m_data[sector]['analysis']['w']['moveType'] == 2): # up rating = rating + RATE_4_SCORE * 0.3 elif (self.stock.m_data[sector]['analysis']['d']['moveType'] == 1) and \ (self.stock.m_data[sector]['analysis']['w']['moveType'] == 1): # up rating = rating + RATE_4_SCORE * 0.3 self.sectors_rating.append(rating) idx += 1 # adjust the rating threshold and pick sectors for analysis idx = 0 np_array = np.asarray(self.sectors_rating) ANALYSIS_THS = sum(self.sectors_rating) / len(np_array[np_array > 0]) logger.info("Adjusted ANALYSIS_THS: %d", ANALYSIS_THS) for sector in self.sectors_list: logger.info("rating[%s]: %d", sector, self.sectors_rating[idx]) rating = self.sectors_rating[idx] if rating >= ANALYSIS_THS or args['_all']: self.sectors_to_analyze.append(idx) table_data.append([sector, str(rating) + '/' + str(RATE_1_SCORE+RATE_2_SCORE+RATE_3_SCORE+RATE_4_SCORE)]) idx += 1 rankingTable = AsciiTable(table_data) rankingTable.inner_heading_row_border = True logger.info("%s", rankingTable.table) self.out_file.write(rankingTable.table) self.out_file.write('\n') logger.info('\n') logger.debug("Sectors to be analyzed: %s", self.sectors_to_analyze) logger.debug("Sectors ranking: %s", self.sectors_rating) self.out_file.write("Sectors to be analyzed and it rank:\n") for sector in self.sectors_to_analyze: self.out_file.write("%s:%f\n" % (self.sectors_list[sector], self.sectors_rating[sector]))
#!/usr/bin/env python import re import config import click import subprocess from pathlib import Path from terminaltables import AsciiTable table_data = [ ['row1 column1', 'row1 column2'], ['row2 column1', 'row2 column2'] ] table = AsciiTable(table_data, 'title') table.inner_heading_row_border = False print(table.table)
def test_attributes(): """Test table attributes.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ['Watermelon', 'green'] ] table = AsciiTable(table_data) table.justify_columns[0] = 'right' expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | +------------+-------+-----------+ | Avocado | green | nut | | Tomato | red | fruit | | Lettuce | green | vegetable | | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.justify_columns[2] = 'center' expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | +------------+-------+-----------+ | Avocado | green | nut | | Tomato | red | fruit | | Lettuce | green | vegetable | | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.inner_heading_row_border = False expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | | Avocado | green | nut | | Tomato | red | fruit | | Lettuce | green | vegetable | | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.title = 'Foods' table.inner_column_border = False expected = dedent("""\ +Foods-------------------------+ | Name Color Type | | Avocado green nut | | Tomato red fruit | | Lettuce green vegetable | | Watermelon green | +------------------------------+""") assert expected == table.table table.outer_border = False expected = ( ' Name Color Type \n' ' Avocado green nut \n' ' Tomato red fruit \n' ' Lettuce green vegetable \n' ' Watermelon green ' ) assert expected == table.table table.outer_border = True table.inner_row_border = True expected = dedent("""\ +Foods-------------------------+ | Name Color Type | +------------------------------+ | Avocado green nut | +------------------------------+ | Tomato red fruit | +------------------------------+ | Lettuce green vegetable | +------------------------------+ | Watermelon green | +------------------------------+""") assert expected == table.table table.title = False table.inner_column_border = True table.inner_heading_row_border = False # Ignored due to inner_row_border. table.inner_row_border = True expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | +------------+-------+-----------+ | Avocado | green | nut | +------------+-------+-----------+ | Tomato | red | fruit | +------------+-------+-----------+ | Lettuce | green | vegetable | +------------+-------+-----------+ | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.outer_border = False expected = ( ' Name | Color | Type \n' '------------+-------+-----------\n' ' Avocado | green | nut \n' '------------+-------+-----------\n' ' Tomato | red | fruit \n' '------------+-------+-----------\n' ' Lettuce | green | vegetable \n' '------------+-------+-----------\n' ' Watermelon | green | ' ) assert expected == table.table