def handle(self, explain, default_logging, verbosity): processors = [] processors.append(run.load_loader()) processors.extend(run.load_steps(None)) processors.extend(run.load_alerts(None)) report = qa.qa_report( processors, default_logging=default_logging, verbosity=verbosity) if verbosity > 1: print(report.full_output()) table = Texttable(max_width=0) table.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES) table.header(("Indicator", "Value")) for k, v in report.resume().items(): pv = v if isinstance(v, str) else str(v) table.add_row([k, pv]) print("\n**** RESUME ****") print(table.draw()) print("") if explain: print("- QA Index (QAI):\n {}".format( report.qai.__doc__.strip())) print("") print( "- QA Score (QAS) is a cuantitave scale based on rounded QAI:") print(" " + ", ".join( ["QAS(~{k}%)={v}".format(v=v, k=k*10) for k, v in sorted(qa.SCORE_COMMENTS.items())])) print("")
def handle(self, status, tiles): log2critcal() table = Texttable(max_width=0) table.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES) table.header(("Pawprint", "Status", "Band", "MJD", "Size")) cnt = 0 with db.session_scope() as session: query = session.query(PawprintStack.name, PawprintStack.status, PawprintStack.band, PawprintStack.mjd, PawprintStack.size) if tiles: ids = [ r[0] for r in session.query( PawprintStackXTile.pawprint_stack_id).join( Tile).filter(Tile.name.in_(tiles)) ] query = query.filter(PawprintStack.id.in_(ids)) if status: query = query.filter(PawprintStack.status.in_(status)) map(table.add_row, query) cnt = query.count() print(table.draw()) print("Count: {}".format(cnt))
def cmd_list(): imap = connectIMAP(CONFIG.accounts[0]) # open readonly b/c otherwise messages will be marked as read '\\Seen' imap.select_folder(ARGS.mailbox, readonly=True) imap = connectIMAP(CONFIG.accounts[0]) # open readonly b/c otherwise messages will be marked as read '\\Seen' imap.select_folder(ARGS.mailbox, readonly=True) try: msgs = iterMessages(imap) msgs = sorted(msgs, key=lambda m: m.date) ids = [m.id for m in msgs] table = Texttable() table.set_deco(Texttable.HEADER | Texttable.HLINES) table.header( ['Date', 'ID', 'Score', 'From', 'Subject', 'Flags', 'age (mins)']) table.set_cols_width([20, 10, 6, 30, 30, 12, 10]) table.set_precision(1) for m in msgs: if m.score is not None and m.score < ARGS.score: if ARGS.verbose: verbose( 'skipping message id=%d date=%s score=%s below threshold of %s' % (m.id, m.date, m.scoreStr(), str(ARGS.score))) continue table.add_row([ m.date, m.id, m.scoreStr(), m.headers.get('From', None), m.headers.get('Subject', None), m.flags, m.ageMinutes() ]) info(table.draw()) finally: imap.logout()
def test_texttable_header(): table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_dtype([ 't', # text 'f', # float (decimal) 'e', # float (exponent) 'i', # integer 'a', # automatic ]) table.set_cols_align(["l", "r", "r", "r", "l"]) table.add_rows([ ["text", "float", "exp", "int", "auto"], ["abcd", "67", 654, 89, 128.001], ["efghijk", 67.5434, .654, 89.6, 12800000000000000000000.00023], ["lmn", 5e-78, 5e-78, 89.4, .000000000000128], ["opqrstu", .023, 5e+78, 92., 12800000000000000000000], ]) assert clean(table.draw()) == dedent('''\ text float exp int auto ============================================== abcd 67.000 6.540e+02 89 128.001 efghijk 67.543 6.540e-01 90 1.280e+22 lmn 0.000 5.000e-78 89 0.000 opqrstu 0.023 5.000e+78 92 1.280e+22 ''')
def test_file(name) -> None: print(f">>>>>>>>>> {name} <<<<<<<<<<") print() t = Texttable(max_width=100) t.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES) t.set_precision(3) t.header(["Encoder", "Size", "Diff", "Diff%"]) t.set_cols_align(["l", "r", "r", "r"]) rows = [] for encoder, encode in ENCODERS.items(): nintendo_len = len(TEST_FILE_DATA[name]) encoder_len = len(encode(TEST_FILE_DATA_UNCOMP[name])) diff = encoder_len - nintendo_len ratio = encoder_len / nintendo_len percentage = (ratio - 1) * 100.0 rows.append([encoder, encoder_len, diff, percentage]) # Sort by diff. rows.sort(key=lambda row: row[2]) t.add_rows(rows, header=False) print(t.draw()) print()
def summary(self, deco: int = Texttable.BORDER, cols_align: Optional[List[str]] = None, cols_valign: Optional[List[str]] = None) -> CollateFunction: """ Get summary of trainer Args: deco (int): border of texttable cols_align (List[str], optional): list of string of columns' align cols_valign (List[str], optional): list of string of columns' valign Returns: torecsys.data.dataloader.CollateFunction: self """ if cols_align is None: cols_align = ['l', 'l', 'l'] if cols_valign is None: cols_valign = ['t', 't', 't'] t = Texttable() t.set_deco(deco) t.set_cols_align(cols_align) t.set_cols_valign(cols_valign) t.add_rows( [['Field Name: ', 'Field Type: ', 'Arguments: ']] + [[k, v, ', '.join(self.kwargs.get(k, {}).keys())] for k, v in self.schema.items()] ) print(t.draw()) return self
def print_diff_as_table(self, include=None, exclude=None, deco_border=False, deco_header=False, deco_hlines=False, deco_vlines=False): diffdict = self.diff(include, exclude) if not diffdict: return from texttable import Texttable table = Texttable() deco = 0 if deco_border: deco |= Texttable.BORDER if deco_header: deco |= Texttable.HEADER if deco_hlines: deco |= Texttable.HLINES if deco_vlines: deco |= Texttable.VLINES table.set_deco(deco) sortedkey = sorted(diffdict) table.add_rows( [[''] + self._name] + [[keystr] + [self._getrepr(diffdict[keystr], name) for name in self._name] for keystr in sortedkey]) print table.draw()
def output_table_list(tables): terminal_size = get_terminal_size()[1] widths = [] for tab in tables: for i in range(0, len(tab.columns)): current_width = len(tab.columns[i].label) if len(widths) < i + 1: widths.insert(i, current_width) elif widths[i] < current_width: widths[i] = current_width for row in tab.data: current_width = len(resolve_cell(row, tab.columns[i].accessor)) if current_width > widths[i]: widths[i] = current_width if sum(widths) != terminal_size: widths[-1] = terminal_size - sum(widths[:-1]) - len(widths) * 3 for tab in tables: table = Texttable(max_width=terminal_size) table.set_cols_width(widths) table.set_deco(0) table.header([i.label for i in tab.columns]) table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False) six.print_(table.draw() + "\n")
def list_instances(): table = Texttable( max_width=0 ) table.set_deco( Texttable.HEADER ) table.set_cols_dtype( [ 't', 't', 't', 't', 't', 't', 't', 't' ] ) table.set_cols_align( [ 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't' ] ) if not options.no_header: ### using add_row, so the headers aren't being centered, for easier grepping table.add_row( [ '# id', 'Name', 'Type', 'Zone', 'Group', 'State', 'Root', 'Volumes' ] ) instances = get_instances() for i in instances: ### XXX there's a bug where you can't get the size of the volumes, it's ### always reported as None :( volumes = ", ".join( [ ebs.volume_id for ebs in i.block_device_mapping.values() if ebs.delete_on_termination == False ] ) ### you can use i.region instead of i._placement, but it pretty ### prints to RegionInfo:us-east-1. For now, use the private version ### XXX EVERY column in this output had better have a non-zero length ### or texttable blows up with 'width must be greater than 0' error table.add_row( [ i.id, i.tags.get( 'Name', ' ' ), i.instance_type, i._placement , i.groups[0].name, i.state, i.root_device_type, volumes or '-' ] ) #PP.pprint( i.__dict__ ) ### table.draw() blows up if there is nothing to print if instances or not options.no_header: print table.draw()
def output_object(obj): table = Texttable(max_width=get_terminal_size()[1]) table.set_deco(0) for item in obj: table.add_row(['{0} ({1})'.format(item.descr, item.name), AsciiOutputFormatter.format_value(item.value, item.vt)]) print(table.draw())
def output_table(tab): max_width = get_terminal_size()[1] table = Texttable(max_width=max_width) table.set_deco(0) table.header([i.label for i in tab.columns]) widths = [] number_columns = len(tab.columns) remaining_space = max_width # set maximum column width based on the amount of terminal space minus the 3 pixel borders max_col_width = (remaining_space - number_columns * 3) / number_columns for i in range(0, number_columns): current_width = len(tab.columns[i].label) tab_cols_acc = tab.columns[i].accessor max_row_width = max( [len(str(resolve_cell(row, tab_cols_acc))) for row in tab.data ] ) current_width = max_row_width if max_row_width > current_width else current_width if current_width < max_col_width: widths.insert(i, current_width) # reclaim space not used remaining_columns = number_columns - i - 1 remaining_space = remaining_space - current_width - 3 if remaining_columns != 0: max_col_width = (remaining_space - remaining_columns * 3)/ remaining_columns else: widths.insert(i, max_col_width) remaining_space = remaining_space - max_col_width - 3 table.set_cols_width(widths) table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False) print(table.draw())
def list (): api.getCredentials() log.debug ("Command: List.") url = "/gists" gists = api.get(url) public_count = 0 private_count = 0 table = Texttable(max_width=defaults.max_width) table.set_deco(Texttable.HEADER | Texttable.HLINES) table.set_cols_align(["l", "l", "l", "l", "l"]) table.set_cols_width([4, 30, 6, 20, 30]) table.header( ["","Files","Public", "Gist ID", "Description"] ) for (i, gist) in enumerate(gists): private = False file_list = '' for (file, data) in gist['files'].items(): file_list += "'" + file + "' " if gist['public']: public_count += 1 else: private_count += 1 table.add_row( [i+1, file_list, str(gist['public']), gist['id'], gist['description']] ) print table.draw() print '' print "You have %i Gists. (%i Private)" % (len(gists), private_count)
def output(self, data, style=STYLE_PLAIN, filename=None, separator=' '): """ Output a dataset with given parameters. """ if filename: xfile = open(filename, 'w') oldstdout = sys.stdout sys.stdout = xfile if style == STYLE_PLAIN: print separator.join(map(str, data['header'])) elif style == STYLE_TABLE: table = Texttable() table.set_deco(Texttable.HEADER) table.add_row(data['header']) else: raise NotImplementedError('Unsupported style') for aline in data['data']: if style == STYLE_PLAIN: print separator.join(map(str, aline)) elif style == STYLE_TABLE: table.add_row(aline) else: raise NotImplementedError('Unsupported style') if style == STYLE_TABLE: print table.draw() if filename: # restore the old value sys.stdout = oldstdout
def print_histogram(self, minimum=5, maximum=100, max_range=10): table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_align(('l', 'r', 'l')) table.set_cols_width((10, 3, maximum)) table.header(('range', '#', '')) start = 0 previous = 0 current_sum = 0 for value, count in sorted(self.histogram.items()): new_row = \ (value - start) > max_range or \ current_sum >= minimum or \ current_sum + count >= maximum if new_row: # passing **locals() is such a hax, don't do this table.add_row(self._format_histogram_row(**locals())) start = value previous = value current_sum = count else: previous = value current_sum += count # passing **locals() is such a hax, don't do this table.add_row(self._format_histogram_row(**locals())) print table.draw()
class tabela_ambiente(): def __init__(self, ambiente): self.ambiente = ambiente self.table = Texttable() def print_table(self, global_time): self.table.reset() self.table.set_deco(Texttable.HEADER) self.table.set_cols_dtype(['t', # text 't', # float ]) self.table.set_cols_align(["l", "c"]) self.table.add_rows([["Informações do ambiente", ""], ["Hora: ", str(datetime.timedelta(seconds=global_time))], ["Temperatura: ", str(round(self.ambiente.temperatura, 2))], ["Chuva: ", str(self.ambiente.chuva)], ["Estado Atmosférico: ", str(self.ambiente.estado_atmosferico)], ["Sujeira: ", str(self.ambiente.sujeira)], [" ", " "], ["Último movimento foi há: ", str(datetime.timedelta(seconds=self.ambiente.mov_count))], ["Ar-condicionado: ", str(self.ambiente.ar_condicionado)], ["Aquecedor: ", str(self.ambiente.aquecedor)], ["Lâmpada: ", str(self.ambiente.lampada)], ["Porta: ", str(self.ambiente.porta)], ["Janela: ", str(self.ambiente.janela)], ["Televisão: ", str(self.ambiente.televisão)], ["Aspirador de pó: ", str(self.ambiente.aspirador)]]) print(self.table.draw())
def __rescheduleTemplates(self, filter, fullInfo, simulate, message): jobs = Job.objects.filter(**filter).distinct() logger.info("%s jobs are prepared to reschedule." % len(jobs)) if fullInfo: table = Texttable() table.set_deco(Texttable.HEADER) table.header(["from Job", "to Job", "Whiteboard", "Tags"]) for job in jobs: jobN = "" if not simulate: jobN = self.beaker.jobReschedule(job, message) if jobN: logger.info("%s job was rescheduled as %s." % (job.uid, jobN.uid)) else: logger.info("Problem with rescheduling of job (%s)." % job.uid) if fullInfo: tags = ",".join([tag.name for tag in job.template.tags.all()]) table.add_row([job.uid, str(jobN), job.template.whiteboard, tags]) else: print str(jobN) if not simulate: # Beaker guys told us we are causing too big load, # so adding this sleep # FIXME only temporary, rewrite code for scheduling to tttt # taskomatic time.sleep(4.5) if fullInfo: print table.draw()
def print_table(prefix, items): table = Texttable(max_width=160) table.set_deco(Texttable.HEADER) table.header(['%s_id' % prefix, '%s_updated' % prefix, '%s_fk' % prefix]) for key, values in items.iteritems(): table.add_row([key, values.get('updated'), values.get('opposite_id')]) print table.draw() + "\n"
def __return2beakerTemplates(self, filter, fullInfo, simulate): recipes = Recipe.objects.filter(**filter).distinct() logger.info("%s recipes are prepared to return2beaker." % len(recipes)) if fullInfo: table = Texttable() table.set_deco(Texttable.HEADER) table.header(["Returned", "Recipe", "Job", "Whiteboard", "Tags"]) for recipe in recipes: res = False if not simulate: res = self.beaker.return2beaker(recipe) if res: logger.info("R:%s recipes was returned to beaker." % recipe.uid) else: logger.info("Problem with returning to beaker (R:%s)." % recipe.uid) if fullInfo: tags = ",".join([tag.name for tag in recipe.job.template .tags.all()]) table.add_row([res, "R:%s" % str(recipe), str(recipe.job), "%s - %s" % (recipe.job.template.whiteboard, recipe.whiteboard), tags]) else: print str(recipe) if fullInfo: print table.draw()
def showJson(data): table = Texttable() table.set_deco(Texttable.BORDER) table.set_cols_align([ "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l" ]) # require three columns table.set_cols_valign([ "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m" ]) table.set_cols_width( [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15]) print(data) for i in range(len(data)): l = {} # print(type(l)) for j in data[i]: #print((data[i][j])) #print(data[i][j]) l[j] = data[i][j] #print(j, data[i][j]) print(l.values()) table.add_rows([l, l.values()]) print(table.draw() + "\n")
def __cancelJobs(self, filter, fullInfo, simulate, message): jobs = Job.objects.filter(**filter).distinct() logger.info("You are going to cancel %s jobs " % len(jobs)) if fullInfo: table = Texttable() table.set_deco(Texttable.HEADER) table.header(["Canceled", "Job", "Whiteboard", "Tags"]) for job in jobs: res = False if not simulate: res = self.beaker.jobCancel(job, message) if res: logger.info("%s job was cancled." % job.uid) else: logger.info("Problem with canceling of job (%s)." % job.uid) if fullInfo: tags = ",".join([tag.name for tag in job.template.tags.all()]) table.add_row([str(res), job.uid, job.template.whiteboard, tags]) if not simulate: # Beaker guys told us we are causing too big load, # so adding this sleep # FIXME only temporary, rewrite code for scheduling to tttt # taskomatic time.sleep(4.5) if fullInfo: print table.draw()
def output(self, data, style=STYLE_PLAIN, filename=None, separator=' '): """ Output a dataset with given parameters. """ if filename: xfile = open(filename, 'w') oldstdout = sys.stdout sys.stdout = xfile if style == STYLE_PLAIN: print(separator.join(map(str, data['header']))) elif style == STYLE_TABLE: table = Texttable() table.set_deco(Texttable.HEADER) table.add_row(data['header']) else: raise NotImplementedError('Unsupported style') for aline in data['data']: if style == STYLE_PLAIN: print(separator.join(map(str, aline))) elif style == STYLE_TABLE: table.add_row(aline) else: raise NotImplementedError('Unsupported style') if style == STYLE_TABLE: print(table.draw()) if filename: # restore the old value sys.stdout = oldstdout
def do_list_changesets(self, arg, opts=None): """Show changesets needing review.""" changesets = requests.get( "http://%s/api/v1/changeset/" % self.site, params={"review_status": "needs"}, auth=self.api_auth ) objects = changesets.json().get("objects") table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_align(["c", "c", "c", "c", "c"]) table.set_cols_width([5, 20, 15, 15, 10]) rows = [["ID", "Type", "Classification", "Version Control URL", "Submitted By"]] for cs in objects: user = requests.get("http://%s%s" % (self.site, cs.get("submitted_by")), auth=self.api_auth) user_detail = user.json() rows.append( [ cs.get("id"), cs.get("type"), cs.get("classification"), cs.get("version_control_url"), user_detail.get("name"), ] ) table.add_rows(rows) print "Changesets That Need To Be Reviewed:" print table.draw()
def dump(relation): width, height = term_size() table = Texttable(width) sample, iterator = tee(relation) table.add_rows(take(1000, sample)) table._compute_cols_width() del sample table.reset() table.set_deco(Texttable.HEADER) table.header([f.name for f in relation.schema.fields]) rows = take(height - 3, iterator) try: while rows: table.add_rows(rows, header=False) print table.draw() rows = take(height - 3, iterator) if rows: raw_input("-- enter for more ^c to quit --") except KeyboardInterrupt: print
def find_commands(db, *filters): user_filter = '\s+'.join(filters) user_re = re.compile(user_filter) RE_CACHE[user_filter] = user_re query = ''' SELECT hostname, timestamp, duration, user_string FROM commands WHERE timestamp > ? AND user_string REGEXP ? ORDER BY timestamp ''' table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_align(('l', 'r', 'r', 'l')) table.header(('host', 'date', 'duration', 'command')) host_width = 6 max_command_width = 9 now = time.time() for row in db.execute(query, (TIMESTAMP, user_filter)): host_width = max(host_width, len(row[0])) max_command_width = max(max_command_width, len(row[3])) table.add_row(( row[0], format_time(row[1], now), format_duration(row[2]) if row[2] > 0 else '', highlight(row[3], user_re))) table.set_cols_width((host_width, 30, 10, max_command_width + 2)) print table.draw()
def list(self): """List the Drbd volumes and statuses""" # Create table and add headers table = Texttable() table.set_deco(Texttable.HEADER | Texttable.VLINES) table.header(('Volume Name', 'VM', 'Minor', 'Port', 'Role', 'Connection State', 'Disk State', 'Sync Status')) # Set column alignment and widths table.set_cols_width((30, 20, 5, 5, 20, 20, 20, 13)) table.set_cols_align(('l', 'l', 'c', 'c', 'l', 'c', 'l', 'c')) # Iterate over Drbd objects, adding to the table for drbd_object in self.get_all_drbd_hard_drive_object(True): table.add_row((drbd_object.resource_name, drbd_object.vm_object.get_name(), drbd_object.drbd_minor, drbd_object.drbd_port, 'Local: %s, Remote: %s' % (drbd_object._drbdGetRole()[0].name, drbd_object._drbdGetRole()[1].name), drbd_object._drbdGetConnectionState().name, 'Local: %s, Remote: %s' % (drbd_object._drbdGetDiskState()[0].name, drbd_object._drbdGetDiskState()[1].name), 'In Sync' if drbd_object._isInSync() else 'Out of Sync')) return table.draw()
def list(self): """List the Drbd volumes and statuses""" # Create table and add headers table = Texttable() table.set_deco(Texttable.HEADER | Texttable.VLINES) table.header(('Volume Name', 'VM', 'Minor', 'Port', 'Role', 'Connection State', 'Disk State', 'Sync Status')) # Set column alignment and widths table.set_cols_width((30, 20, 5, 5, 20, 20, 20, 13)) table.set_cols_align(('l', 'l', 'c', 'c', 'l', 'c', 'l', 'c')) # Iterate over Drbd objects, adding to the table for drbd_object in self.get_all_drbd_hard_drive_object(True): table.add_row( (drbd_object.resource_name, drbd_object.vm_object.get_name(), drbd_object.drbd_minor, drbd_object.drbd_port, 'Local: %s, Remote: %s' % (drbd_object._drbdGetRole()[0].name, drbd_object._drbdGetRole()[1].name), drbd_object._drbdGetConnectionState().name, 'Local: %s, Remote: %s' % (drbd_object._drbdGetDiskState()[0].name, drbd_object._drbdGetDiskState()[1].name), 'In Sync' if drbd_object._isInSync() else 'Out of Sync')) return table.draw()
def dump(relation): width,height = term_size() table = Texttable(width) sample, iterator = tee(relation) table.add_rows(take(1000,sample)) table._compute_cols_width() del sample table.reset() table.set_deco(Texttable.HEADER) table.header([f.name for f in relation.schema.fields]) rows = take(height-3, iterator) try: while rows: table.add_rows(rows, header=False) print table.draw() rows = take(height-3, iterator) if rows: raw_input("-- enter for more ^c to quit --") except KeyboardInterrupt: print
def get_hard_drive_list_table(self): """Return a table of hard drives""" # Manually set permissions asserted, as this function can # run high privilege calls, but doesn't not require # permission checking self._get_registered_object('auth').set_permission_asserted() # Create table and set headings table = Texttable() table.set_deco(Texttable.HEADER | Texttable.VLINES) table.header(('ID', 'Size', 'Type', 'Storage Backend', 'Virtual Machine')) table.set_cols_width((50, 15, 15, 50, 20)) # Obtain hard ives and add to table for hard_drive_obj in self.get_all(): vm_object = hard_drive_obj.get_virtual_machine() hdd_type = '' storage_backend_id = 'Storage backend does not exist' try: storage_backend_id = hard_drive_obj.storage_backend.id_ hdd_type = hard_drive_obj.get_type() hdd_size = SizeConverter(hard_drive_obj.get_size()).to_string() except (VolumeDoesNotExistError, HardDriveDoesNotExistException, StorageBackendDoesNotExist), exc: hdd_size = str(exc) table.add_row((hard_drive_obj.id_, hdd_size, hdd_type, storage_backend_id, vm_object.get_name() if vm_object else 'Not attached'))
def handle(self, *args, **options): if options.get('list'): starter_files = StartersFileManager.starter_files() table = Texttable(max_width=100) table.set_deco(Texttable.HEADER) table.add_row(('#', 'File')) for i, sf in enumerate(starter_files): table.add_row((i, sf.file_name)) print(table.draw()) return if options.get('print') is not None: starter_file = StartersFileManager.starter_files()[options.get( 'print')] print('Starters:') print(set(starter_file.starting_players())) print('Injured:') print(set(starter_file.injured_players())) return if options.get('write'): print('Scraping from rotoworld..') starters, injured = RotoScraper.pull_data_from_roto() print('done.') print('Creating file..') StartersFileManager.create_starters_file(starters, injured, options.get('write')) print('done.')
def print_matrix(m: np.ndarray, head: np.ndarray = None, title: str = "", c_type: str = 'a') -> None: """ display matrix :param m: :param head: head matrix :param title: title matrix :param c_type: :return: """ cols_align = [] cols_m = m.shape[1] rows_m = m.shape[0] for i in range(0, cols_m): if i == 0: cols_align.append("l") else: cols_align.append("r") content = [] if head is None: head = [' ' for x in range(0, cols_m)] content.append(head) for i in range(0, rows_m): content.append(m[i]) table = Texttable() table.set_deco(Texttable.HEADER) table.set_header_align(cols_align) table.set_cols_dtype([c_type] * cols_m) # automatic table.set_cols_align(cols_align) table.add_rows(content) if title != "": print("********************** " + title + " **********************") print(table.draw())
def images_to_ascii_table(images): """Just a method that formats the images to ascii table. Expects dictionary {host: [images]} and prints multiple tables """ with closing(StringIO()) as out: for host, values in images.iteritems(): out.write(str(host) + "\n") t = TextTable() t.set_deco(TextTable.HEADER) t.set_cols_dtype(['t'] * 5) t.set_cols_align(["l"] * 5) rows = [] rows.append(['Repository', 'Tag', 'Id', 'Created', 'Size']) for image in values: rows.append([ image.repository or '<none>', image.tag or '<none>', image.id[:12], time_ago(image.created), human_size(image.size) ]) t.add_rows(rows) out.write(t.draw() + "\n\n") return out.getvalue()
def print_mapping(prefix, key, items): table = Texttable(max_width=160) table.set_deco(Texttable.HEADER) table.header(['%s_%s' % (prefix, key), '%s_fk' % prefix]) for key, value in items.iteritems(): table.add_row([key, value]) print table.draw() + "\n"
def containers_to_ascii_table(containers): """Just a method that formats the images to ascii table. Expects dictionary {host: [images]} and prints multiple tables """ with closing(StringIO()) as out: for host, values in containers.iteritems(): out.write("[" + str(host) + "] \n") t = TextTable(max_width=400) t.set_deco(TextTable.HEADER) t.set_cols_dtype(['t'] * 6) t.set_cols_align(["l"] * 6) t.set_cols_width([12, 25, 25, 15, 20, 15]) rows = [] rows.append( ['Id', 'Image', 'Command', 'Created', 'Status', 'Ports']) for container in values: rows.append([ container.id[:12], container.image, container.command[:20], time_ago(container.created), container.status, container.ports ]) t.add_rows(rows) out.write(t.draw() + "\n\n") return out.getvalue()
def make_new(): table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_dtype(["t", "t"]) table.set_cols_align(["l", "l"]) table.add_row(get_txt(ctx.guild.id, "ws_list_row")) return table
def getDescOfEachNoSystemTable(self): ''' returns a String for print ''' outputString = "" logging.debug("Getting all no system tables accessible with the current user") tablesAccessible = self.__execQuery__(query=self.REQ_GET_ALL_NO_SYSTEM_TABLES, ld=['owner', 'table_name']) if isinstance(tablesAccessible,Exception): logging.warning("Impossible to execute the request '{0}': {1}".format(self.REQ_GET_ALL_NO_SYSTEM_TABLES, tablesAccessible.generateInfoAboutError(self.REQ_GET_ALL_NO_SYSTEM_TABLES))) return "" else: nbTables = len(tablesAccessible) colNb = nbTables if colNb>0 : pbar,currentColNum = self.getStandardBarStarted(colNb), 0 for aTable in tablesAccessible: if colNb>0: currentColNum += 1 pbar.update(currentColNum) request = self.REQ_GET_COLUMNS_FOR_TABLE.format(aTabl<e['table_name'], aTable['owner']) columnsAndTypes = self.__execQuery__(query=request, ld=['column_name', 'data_type']) if isinstance(columnsAndTypes,Exception): logging.warning("Impossible to execute the request '{0}': {1}".format(request, columnsAndTypes.generateInfoAboutError(request))) outputString += "\n[+] {0}.{1} ({2}/{3})\n".format(aTable['owner'], aTable['table_name'], currentColNum, colNb) resultsToTable = [('column_name', 'data_type')] for aLine in columnsAndTypes: resultsToTable.append((aLine['column_name'], aLine['data_type'])) table = Texttable(max_width=getScreenSize()[0]) table.set_deco(Texttable.HEADER) table.add_rows(resultsToTable) outputString += table.draw() outputString += '\n' if colNb>0 : pbar.finish() return outputString
def display_departures(station_name, limit=10, mode=None): station_name = get_station_name(station_name) departuresJSON = get_departures_by_name(station_name) departures = [] if mode is not None: for d in departuresJSON: if mode.upper() in d['product']: departures += [Departure(d)] else: departures = [Departure(i) for i in departuresJSON] departures = departures[:limit] print('\nStation: ' + station_name + '\n') table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_dtype(['t', 't', 'i']) table.set_cols_align(['l', 'l', 'r']) rows = [] rows.append([ '\x1b[38;5;231m\x1b[48;5;23mline\x1b[0m', 'destination', 'departure (min)' ]) for dep in departures: rows.append([ dep.get_label_colored(), dep.destination, dep.departure_time_minutes ]) table.add_rows(rows) print(color(table.draw(), fore=MVG_FG, back=MVG_BG))
def list(self): """List the Drbd volumes and statuses""" # Set permissions as having been checked, as listing VMs # does not require permissions self._get_registered_object('auth').set_permission_asserted() # Create table and add headers table = Texttable() table.set_deco(Texttable.HEADER | Texttable.VLINES) table.header(('Name', 'Type', 'Location', 'Nodes', 'Shared', 'Free Space', 'ID')) # Set column alignment and widths table.set_cols_width((15, 5, 30, 70, 6, 15, 50)) table.set_cols_align(('l', 'l', 'l', 'l', 'l', 'l', 'l')) for storage_backend in self.get_all(): table.add_row(( storage_backend.name, storage_backend.storage_type, storage_backend.get_location(), ', '.join(storage_backend.nodes), str(storage_backend.shared), SizeConverter(storage_backend.get_free_space()).to_string(), storage_backend.id_ )) return table.draw()
def long_format(self, records): """Format records in long format. Args: records: Controlled records to format. Returns: str: Record data in long format. """ title = util.hline(self.title_fmt % {'model_name': records[0].name.capitalize(), 'storage_path': records[0].storage}, 'cyan') retval = [title] for record in records: rows = [['Attribute', 'Value', 'Command Flag', 'Description']] populated = record.populate() for key, val in sorted(populated.iteritems()): if key != self.model.key_attribute: rows.append(self._format_long_item(key, val)) table = Texttable(logger.LINE_WIDTH) table.set_cols_align(['r', 'c', 'l', 'l']) table.set_deco(Texttable.HEADER | Texttable.VLINES) table.add_rows(rows) retval.append(util.hline(populated[self.model.key_attribute], 'cyan')) retval.extend([table.draw(), '']) return retval
def top(db): count_query = ''' SELECT count(*) FROM commands WHERE timestamp > ? ''' percentage = 100 / float(execute_scalar(db, count_query, TIMESTAMP)) query = ''' SELECT count(*) AS counts, command FROM commands WHERE timestamp > ? GROUP BY command ORDER BY counts DESC LIMIT 20 ''' table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_align(('r', 'r', 'l')) table.header(('count', '%', 'command')) for row in db.execute(query, (TIMESTAMP,)): table.add_row((row[0], int(row[0]) * percentage, row[1])) print table.draw()
def to_txt_file(self, rounds,file, print_header): table = Texttable() table.set_cols_width([len(self.team_one.get_name()) + 9, len(self.team_two.get_name()) + 9]) if print_header: deco = Texttable.HEADER | Texttable.VLINES table.header([self.team_one.get_name(), self.team_two.get_name()]) else: deco = Texttable.VLINES table.set_deco(deco) table.set_chars(['-', '|', '=', '=']) rows = [[str(rounds[0].get_team_one_points()),str(rounds[0].get_team_two_points())]] for i in range(1,len(rounds)): column1 = f"{sum([x.get_team_one_points() for x in rounds[:i]])} + {rounds[i].get_team_one_points()}" column2 = f"{sum([x.get_team_two_points() for x in rounds[:i]])} + {rounds[i].get_team_two_points()}" rows.append([column1,column2]) column1 = f"{sum([x.get_team_one_points() for x in rounds])}" column2 = f"{sum([x.get_team_two_points() for x in rounds])}" rows.append([column1,column2]) table.add_rows(rows, header = False) file.write(table.draw()) file.write('\n') self.write_divider_to_file(file) table.reset() table.add_row([f"({self.team_one.games_won})", f"({self.team_two.games_won})"]) table.set_cols_align(["c","c"]) file.write(table.draw()) file.write('\n') self.write_divider_to_file(file)
def sub(db, command, *filters): counts = collections.defaultdict(int) user_filter = ' '.join(itertools.chain([command], filters)) total = 0 query = ''' SELECT user_string FROM commands WHERE timestamp > ? AND command = ? ''' for row in db.execute(query, (TIMESTAMP, command)): command = normalize_user_string(row[0]) if command.startswith(user_filter): counts[command] += 1 total += 1 percentage = 100 / float(total) table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_align(('r', 'r', 'l')) table.set_cols_width((5, 6, 75)) table.header(('count', '%', 'command')) for key, value in sorted(counts.iteritems(), key=lambda (k, v): (v, k), reverse=True)[:20]: table.add_row((value, value * percentage, key)) print table.draw()
def output_console(data): data = data[out_columns] to_be_list = np.array(data) table = Texttable() table.set_deco(Texttable.BORDER) table.add_rows(to_be_list.tolist(), header=False) print(table.draw())
def display_menu(self): """ Discplay menu and forward user to the appropriate method. :return: boolean, whether the program should continue or not """ # display menu and define action action_map = { 1: self.process_orders, 2: self.check_inventory, 3: self.create_report } menu = Texttable() menu.add_rows([["Holiday store menu:"], ["1. Process web orders"], ["2. Check inventory"], ["3. Exit"]]) menu.set_deco(Texttable.BORDER | Texttable.HEADER) print(menu.draw()) # get user's input user_input = 0 while user_input not in range(1, 4): try: user_input = int(input("Enter a number between 1~3: ")) except ValueError: pass # input prompt is clear, additional message is not needed action_map[user_input]() return True if user_input in (1, 2) else False
def list_command(): """List apps that you have access to.""" from texttable import Texttable cli.user() with spinner(): res = api.Apps.list() count = 0 # Heads up! Texttable does not like colours. # So don't use click.style here. table = Texttable(max_width=800) table.set_deco(Texttable.HEADER) table.set_cols_align(['l', 'l', 'l']) all_apps = [['NAME', 'STATE', 'CREATED']] for app in res: count += 1 date = datetime.parse_psql_date_str(app['timestamp']) all_apps.append([ app['name'], maintenance(app['maintenance']), datetime.reltime(date) ]) table.add_rows(rows=all_apps) if count == 0: click.echo('No application found. Create your first app with') click.echo(click.style('$ story apps create', fg='magenta')) else: click.echo(table.draw())
def nsBanner(ns): pyfiglet.print_figlet( nsGet(ns, "/etc/name").value, nsGet(ns, "/etc/bannerFont", "isometric2").value, "GREEN:" ) tbl = Texttable(nsGet(ns, "/etc/bannerTableWidth", 120).value) tbl.set_deco(Texttable.HEADER) tbl.add_rows( [ ["Variable", "Value", "Description"], ["/etc/name", nsGet(ns, "/etc/name").value, "Name of the application"], ["/etc/hostname", nsGet(ns, "/etc/hostname").value, "Hostname"], ["/sys/env/platform/platform", nsGet(ns, "/sys/env/platform/platform").value, "Host platform"], ["/sys/env/platform/python", nsGet(ns, "/sys/env/platform/python").value, "Version of the Python"], ["/sys/env/platform/system", nsGet(ns, "/sys/env/platform/system").value, "OS Name"], ["/sys/env/user", nsGet(ns, "/sys/env/user").value, "Name of the user"], ["/sys/env/home", nsGet(ns, "/sys/env/home").value, "Home directory"], ["/sys/env/apphome", nsGet(ns, "/sys/env/apphome").value, "Application home"], ["/sys/env/pidFile", nsGet(ns, "/sys/env/pidFile").value, "PID file"], ["/config/user.library", nsGet(ns, "/config/user.library").value, "Application library"], ["/etc/daemonize", nsGet(ns, "/etc/daemonize").value, "Become daemon ?"], ["/etc/flags/internalServer",nsGet(ns, "/etc/flags/internalServer", False).value,"Enable internal server"], ["/etc/version", str(nsGet(ns, "/etc/version").value), "Application version"], ["/etc/release", nsGet(ns, "/etc/release").value, "Application release"], ["/etc/author", nsGet(ns, "/etc/author").value, "Author of application"], ["/etc/author.email", nsGet(ns, "/etc/author.email").value, "Author's email"], ["/etc/coref/version", str(nsGet(ns, "/etc/coref/version").value), "core.F version"], ["/etc/coref/release", nsGet(ns, "/etc/coref/release").value, "core.F release"], ["/config/RPCCatchCalls", nsGet(ns, "/config/RPCCatchCalls").value, "Trace RPC"], ["/etc/answer", nsGet(ns, "/etc/answer").value, "THE ANSWER"], ] ) print(tbl.draw()) return True
def _new_table(self, headers=None): """Constructs a new table to pretty-print vertex and edge attributes""" table = Texttable(max_width=0) table.set_deco(0) if headers is not None: table.header(headers) return table
def run(minutes, filter_str, top, verbose, return_zero): invocations = get_lambda_functions_and_counts(minutes, filter_str, verbose) invocations = sorted(invocations, key=lambda k: k['invocations'], reverse=True) if verbose: print 'Lambda functions counted: ' + str(len(invocations)) if top > 0: if verbose: print 'Reducing result set to ' + str(top) + ' highest results' invocations = invocations[0:top] if not return_zero: if verbose: print 'Removing results with 0 invocations' invocations = [i for i in invocations if i['invocations'] != 0] if verbose: print '\n' # clear lines t = Texttable() t.set_deco(Texttable.HEADER) for i in invocations: t.add_row([i['name'], i['invocations']]) #print i['name'] + ' = ' + str(i['invocations']) + ' invocations' print t.draw()
def print_price_data(data): # Current BTC Price # -------------------- print '\n%s' % colorize('CaVirtex Market\n---------------', colors.CYAN) status_color = colors.GREEN if data['net'] > 0 else colors.RED print '\n%s' % colorize('Price', colors.BLUE) print '\n%s' % colorize('$%.2f CAD/BTC' % data['current_price'], status_color) # Latest Trades # ---------------- print '\n%s\n' % colorize('Latest Trades', colors.BLUE) trades_table = Texttable() trades_table.set_deco(Texttable.HEADER) trades_table.set_precision(2) trades_table.set_cols_dtype(['f', 'f', 'f', 't']) trades_table.add_rows(data['latest_trades']) print trades_table.draw() # Investment Returns # --------------------- print '\n%s' % colorize('Your Investment', colors.BLUE) print '\nNet: %s' % colorize('$%.2f CAD' % data['net'], status_color) print '\nVOI: %s' % colorize('$%.2f CAD' % data['voi'], status_color) print '\nROI: %s' % colorize('%.2f%%' % data['roi'], status_color)
def build_table(matches, result_map, headers): table = Texttable() if len(matches) > 1: table.set_deco(Texttable.HEADER | Texttable.HLINES | Texttable.VLINES) table.set_cols_align(['c'] * len(headers)) table.set_cols_valign(['c'] * len(headers)) table.header(headers) for match in matches: print(f'match: {match}: {result_map[match]}') data = [match] data.extend(value for value in result_map[match][0:]) # print(f'Adding row: {data}') table.add_row(data) output = '```' + table.draw() + '```' else: table.set_cols_align(["l", "r"]) table.set_cols_valign(["m", "m"]) table.set_cols_width([10, 20]) table.header([headers[0], matches[0]]) data = list(zip(headers[1:], (result_map[matches[0]])[0:])) table.add_rows(data, header=False) output = '`' + table.draw() + '`' return output
def list(): api.getCredentials() log.debug("Command: List.") url = "/gists" gists = api.get(url) public_count = 0 private_count = 0 table = Texttable(max_width=defaults.max_width) table.set_deco(Texttable.HEADER | Texttable.HLINES) table.set_cols_align(["l", "l", "l", "l", "l"]) table.set_cols_width([4, 30, 6, 20, 30]) table.header(["", "Files", "Public", "Gist ID", "Description"]) for (i, gist) in enumerate(gists): private = False file_list = '' for (file, data) in gist['files'].items(): file_list += "'" + file + "' " if gist['public']: public_count += 1 else: private_count += 1 table.add_row([ i + 1, file_list, str(gist['public']), gist['id'], gist['description'] ]) print(table.draw()) print('') print("You have %i Gists. (%i Private)" % (len(gists), private_count))
def readjust_scores(self, driver, actual_answers, context: 'TestContext', report) -> Tuple[bool, List]: choices = self.choices if False: if len(choices) != len(self.choices): raise IntegrityException( "wrong number of choices in readjustment.") for key, score in self.choices.items(): if choices[key] != score: raise IntegrityException( "wrong choice score in readjustment.") table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_dtype(['t', 't', 't']) table.add_row(['', 'old', 'readjusted']) for key, score in list(choices.items()): new_score = _readjust_choice_item(context.random, score) choices[key] = new_score table.add_row([key, '(%f, %f)' % score, '(%f, %f)' % new_score]) report(table) _readjust_ui(context, driver, choices) return True, list()
def handle(self): table = Texttable(max_width=0) table.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES) table.header(("Name", "Path")) table.add_row(("Input Data", conf.settings.INPUT_PATH)) table.add_row(("Storage", conf.settings.DATA_PATH)) print(table.draw())
def summary( self, deco: int = Texttable.BORDER, cols_align: List[str] = ["l", "l", "l"], cols_valign: List[str] = ["t", "t", "t"]) -> TypeVar("DataloaderCollator"): r"""Get summary of trainer. Args: deco (int): Border of texttable cols_align (List[str]): List of string of columns' align cols_valign (List[str]): List of string of columns' valign Returns: torecsys.data.dataloader.DataloaderCollator: self """ # create and configure text table t = Texttable() t.set_deco(deco) t.set_cols_align(cols_align) t.set_cols_valign(cols_valign) # append data to text table t.add_rows( [["Field Name: ", "Field Type: ", "Arguments: "]] + \ [[k, v, ", ".join(self.kwargs.get(k, {}).keys())] \ for k, v in self.schema.items()] ) # Print summary with text table print(t.draw()) return self
def main(args): if args.gevent: import gevent.monkey gevent.monkey.patch_all() if not args.strict: args.name = ['*' + name + '*' for name in args.name] table = Texttable(args.width) table.set_cols_dtype(['t'] * len(args.fields)) table.set_cols_align([args.align] * len(args.fields)) if not args.quiet: table.add_row([pretify_field(field) for field in args.fields]) table.set_deco(0) instances = [] for required_name in args.name: instances.extend( get_instances_by_id_or_name(required_name, projects=args.projects, raw=args.raw, regions=args.regions, clouds=args.clouds)) if args.active: instances = [ instance for instance in instances if instance.state == 'running' ] if not instances: sys.exit(1) instances.sort(key=lambda instance: [getattr(instance, field) for field in args.sort_by]) table.add_rows([[getattr(instance, field) for field in args.fields] for instance in instances], header=False) print table.draw()
def print_diff_as_table(self, include=None, exclude=None, deco_border=False, deco_header=False, deco_hlines=False, deco_vlines=False): diffdict = self.diff(include, exclude) if not diffdict: return from texttable import Texttable table = Texttable() deco = 0 if deco_border: deco |= Texttable.BORDER if deco_header: deco |= Texttable.HEADER if deco_hlines: deco |= Texttable.HLINES if deco_vlines: deco |= Texttable.VLINES table.set_deco(deco) sortedkey = sorted(diffdict) table.add_rows( [[''] + self._name] + [[keystr] + [self._getrepr(diffdict[keystr], name) for name in self._name] for keystr in sortedkey] ) print table.draw()
def schedule(self, label="default", *argvs, **kwargs): simulate = kwargs.get("simulate") reserver = kwargs.get("reserve") fullInfo = kwargs.get("fullInfo") if kwargs.get("list"): tp = TaskPeriod.objects.all() table = Texttable() table.set_deco(Texttable.HEADER) table.header(["Id", "Title", "Label", "Schedule"]) for it in tp: table.add_row([it.id, it.title, it.label, it.cron]) print(table.draw()) if kwargs.get("template_id"): template_ids = kwargs.get("template_id") logger.debug("Schedule template id %s" % template_ids) filter = {"id__in": template_ids} self.scheduleByJobTemplates( filter, label, fullInfo, simulate, reserver) if kwargs.get("schedule_label"): period_label = kwargs.get("schedule_label") filter = {"schedule__label__in": period_label, "is_enable": True} if not label: label = period_label self.scheduleByJobTemplates( filter, "".join(label), fullInfo, simulate, reserver)
def evt_handler(sender, object, iface, signal, args): event, tags = args print("evt_handler called %s" % event) if event == 'dhcp-lease-added': print("event %s for mac %s" % (event, tags['mac'])) ret = dev.xget( "/status/rg/dhcp[pool='%s'][mac='%s']/leases" % (tags['pool-name'], tags['mac'])) try: result = xmltodict.parse(ret) except: print("XML = " + ret) raise # print(json.dumps(result, sort_keys=True, indent=4)) lease = result['status']['rg']['dhcp']['leases']['lease'] print(lease) table = Texttable() table.set_deco(Texttable.HEADER) table.set_cols_dtype(['t', 't', 't', 'i', 't', 't']) table.set_cols_width([6, 17, 18, 12, 28, 10]) table.header(['Pool','MAC','IP Address','Expiry','DHCP Option','Ifname']) table.add_row([ lease['pool'], lease['mac'], lease['ipaddr'], lease['expiry'], '\n'.join(lease['dhcp-option']), lease['ifname']]) print(table.draw())
def list(self): """ List all mapping in the map folder """ logger.info("request rev: list") try: self.load() except DirectoryNotFound as e: print e.value logger.exception(e.value) table = Texttable() table.set_deco(Texttable.HEADER) rows = [] rows.append(["name", "type"]) for node_name in self.__name_list: node_type = "" with open(os.path.join(self.__mapping_folder, "{}.yml".format(node_name)), 'r') as fp: node_info = YAMLLoader(fp).get_data() node_type = node_info['type'] rows.append([node_name, node_type]) table.add_rows(rows) print table.draw() logger.info("request res: list OK")