def display(): """All included tools and details will be printed to STDOUT.""" pkgslist = getPackages() pkgslistIn = [] pkgslistEx = [] pkgslistAll = [] # All packages pkgslistAll = [] for pkg in pkgslist: pkgslistAll.append(pkg['pkg']) # Split list of packages into included and excluded packages # Not used at the moment #for pkg in pkgslist: # if 'exclude' in pkg: # pkgslistEx.append(pkg['pkg']) # else: # pkgslistIn.append(pkg['pkg']) # Displays the details to STDOUT print '\nDetails about the packages in the Fedora Security Lab\n' print 'Packages in comps : %s' % len(pkgslist) print 'Packages included in live media : %s\n' % len(pkgslistIn) print 'Package listing:' sorted_pkgslist = sorted(pkgslistAll) print columnize.columnize(sorted_pkgslist, displaywidth=72)
def selectDB(self): self.console_height, self.console_width = map(int, os.popen('stty size', 'r').read().split()) print "\n\nSelect Entrez databases to query for SRA accession numbers. Enter the corresponding integer:" screenoutput = list() screenoutput.append(('[0] All Entrez Databases')) for key in enumerate(EntrezDBs): screenoutput.append(('[%s] %s' % (key[0]+1, key[1][0]))) print columnize.columnize(screenoutput, displaywidth=self.console_width) print "(Default [32] sra):", s = raw_input() if s == '': self.currentEntrezDB = 'sra' else: try: number = map(int, s) if not (number in range(0,len(EntrezDBs)+1)): print "\nERROR: Invalid input value. Please enter an integer in the range [0-" + str(len(EntrezDBs)) + "].\n\n" number = None except ValueError: print "\nERROR: Invalid input type. Please enter an integer in the range [0-" + str(len(EntrezDBs)) + "].\n\n" number = number-1 if number == -1: self.currentEntrezDB = 'mmdAllEntrezDBs' else: self.currentEntrezDB = EntrezDBs[number][2]
def full(): """All included tools and details will be printed to STDOUT.""" pkgslist = getPackages() pkgslistIn = [] pkgslistEx = [] pkgslistAll = [] # All packages pkgslistAll = [] for pkg in pkgslist: pkgslistAll.append(pkg['pkg']) # Split list of packages into included and excluded packages # Not used at the moment #for pkg in pkgslist: # if 'exclude' in pkg: # pkgslistEx.append(pkg['pkg']) # else: # pkgslistIn.append(pkg['pkg']) # Displays the details to STDOUT print("\nDetails about the packages in the Fedora Security Lab.\n") print("Packages in comps : ", len(pkgslist)) #print("Packages included in live media : ", len(pkgslistIn)) print("\nPackage listing:") sorted_pkgslist = sorted(pkgslistAll) print(columnize.columnize(sorted_pkgslist, displaywidth=72))
def test_colfmt(self): self.assertEqual( ' 0 1 2 3\n', columnize([0, 1, 2, 3], 7, arrange_vertical=False, opts={'colfmt': '%5d'}))
def analyze_game_20190222(): ANSWERS = [ Answer(colors_to_num('OOGP'), (0,1)), Answer(colors_to_num('RYWW'), (1,2)), Answer(colors_to_num('PRPR'), (1,0)), Answer(colors_to_num('GRYW'), (1,1)), Answer(colors_to_num('WRWO'), (0,2)), Answer(colors_to_num('YWPW'), (4,0)) ] for i in range(1, len(ANSWERS) + 1): answers = ANSWERS[:i] possible = count_consistent(answers) print('After {}, {}/{} possible'.format( answers, possible, 6**4 )) if possible < 100: color_list = [ num_to_colors(val) for val in yield_consistent(answers) ] print(columnize(color_list, displaywidth=80))
def display_instrumentation(): with open("instrumentation_list.txt") as f: instrument = f.readlines() list = [] for i, each in enumerate(instrument): list.append(f"{i}. {each.strip()}") print(columnize.columnize(list))
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=""): """Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not.""" if not (isinstance(val, list) or isinstance(val, tuple)): return False numeric = True for i in range(len(val)): if not (type(val[i]) in [bool, float, int]): numeric = False if not (type(val[i]) in [bool, float, int, bytes]): return False pass pass mess = columnize( [repr(v) for v in val], opts={ "arrange_array": True, "lineprefix": lineprefix, "displaywidth": int(displaywidth) - 3, "ljust": not numeric, }, ) msg_nocr(mess) return True
def test_lineprefix(self): self.assertEqual('>>> 0 3\n>>> 1\n>>> 2\n', columnize([0, 1, 2, 3], 7, arrange_vertical=False, opts={'colfmt': '%5d', 'displaywidth': 17, 'lineprefix': '>>> '}))
async def list_abv(self, ctx, *, query: str = None): """ Get a GIANT list of abbreviations, or search for one (recommended) """ em = discord.Embed(color=self.color) # Sends a giant spammy list if query is None: abv_list = columnize.columnize( [f'{x} - `{self.abv_dict[x]}`' for x in self.abv_dict], displaywidth=100) return await ctx.message.edit( content=f"**Abbreviations:**\n{abv_list}") query = query.title() closest_match = None # Finds the closest item to a search if query not in self.abv_dict: closest_match = min(self.abv_dict, key=lambda v: len(set(query) ^ set(v))) if closest_match: msg = '**Closest Abbreviation**' msg += f'{closest_match} - `{self.abv_dict[closest_match]}`' else: msg = '**Matching Abbreviation**' msg += f'{query} - `{self.abv_dict[query]}`' await ctx.message.edit(content=msg)
def D(self, parameter_s=''): """SUMMARY D(parameter_s='') @Arguments: - `parameter_s`: @Return: @Error: """ init() # for colorama args = parse_argstring(self.D, parameter_s) obj = self.shell.ev(args.evaluation) if args.pattern: # "-g" grep option regex = re.compile(args.pattern) members = [(name, elem) for name, elem in getmembers(obj) if regex.search(name) is not None] else: members = getmembers(obj) results = [] for name, elem in members: if isclass(elem): member = ColumnizeDirMagic._fore_green_reset(name) elif self._iscallable(elem): member = ColumnizeDirMagic._fore_red_reset(name) elif ismodule(elem): member = ColumnizeDirMagic._fore_cyan_reset(name) elif not name.startswith('_', ): member = ColumnizeDirMagic._fore_yellow_reset(name) else: member = ColumnizeDirMagic._fore_white_reset(name) results.append(member) print(columnize(results, displaywidth=110))
def format_columns(iterable: Iterable[str]) -> str: '''A helper functor to output the list in columns.''' term_width = click.get_terminal_size()[0] - len(_COLUMIZED_LIST_INDENT_PFX) return textwrap.indent(columnize.columnize(iterable, displaywidth=term_width, colsep=' │ '), prefix=_COLUMIZED_LIST_INDENT_PFX)
def columnize_commands(self, commands): """List commands arranged in an aligned columns""" commands.sort() width = self.debugger.settings['width'] return columnize.columnize(commands, displaywidth=width, lineprefix=' ')
def test_columnize_not_enough_items(): sequence = 'AB' expected = [ ('A', 'B'), ] result = columnize(sequence, 3) assert expected == result
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''): '''Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not. ''' if type(val) != list: return False numeric = True for i in range(len(val)): if not (type(val[i]) in [bool, float, int]): numeric = False if not (type(val[i]) in [bool, float, int, bytes]): return False pass pass mess = columnize( [repr(v) for v in val], opts={ "arrange_array": True, "lineprefix": lineprefix, "displaywidth": int(displaywidth) - 3, 'ljust': not numeric }) msg_nocr(mess) return True
def test_columnize_8_in_4(): sequence = 'ABCDEFGH' expected = [ ('A', 'C', 'E', 'G'), ('B', 'D', 'F', 'H'), ] result = columnize(sequence, 4) assert expected == result
def test_lineprefix_just_wide_enough(self): self.assertEqual( '>>>10 12\n>>>11 13\n', columnize([10, 11, 12, 13], opts={ 'lineprefix': '>>>', 'displaywidth': 9 }))
def output_dict(data, key_label, value_label, value_vt=ValueType.STRING): sys.stdout.write( columnize([ '{0}={1}'.format( row[0], AsciiOutputFormatter.format_value(row[1], value_vt)) for row in list(data.items()) ])) sys.stdout.flush()
def run(self, args): events = list(self.debugger.settings['printset']) if events != []: events.sort() self.section('Trace events we may stop on:') self.msg(columnize.columnize(events, lineprefix=' ')) else: self.msg('No events trapped.') return return
def test_columnize_7_in_2(): sequence = 'ABCDEFG' expected = [ ('A', 'E'), ('B', 'F'), ('C', 'G'), ('D', ), ] result = columnize(sequence, 2) assert expected == result
def test_columnize_7_in_5(): # Not the right number of columns, but the right number of rows. # This actually looks better, so it's OK! sequence = 'ABCDEFG' expected = [ ('A', 'C', 'E', 'G'), ('B', 'D', 'F'), ] result = columnize(sequence, 5) assert expected == result
async def list(self, ctx): """ List all of your tags (Warning: potentially spammy) """ if len(self.tag_dict) == 0: return await ctx.error('No tags to list.') # Create two columns just in case there's a lot of stuff to send tag_list = [x for x in list(self.tag_dict)] tag_col = columnize.columnize([f"\u2022 {x}" for x in tag_list]) await ctx.message.edit(content=f"**Your Tags:**\n{tag_col}")
def test_lineprefix(self): self.assertEqual( '>>> 0\n>>> 1\n>>> 2\n>>> 3\n', columnize([0, 1, 2, 3], 7, arrange_vertical=False, opts={ 'colfmt': '%5d', 'displaywidth': 16, 'lineprefix': '>>> ' }))
def main(): cur_answers = [] answer_tree = {} metric_val, best_next = best_partitions(cur_answers, minmax_metric) print('After {}, {} with value {}:'.format(cur_answers, len(best_next), metric_val)) print(columnize( [num_to_colors(v) for v in best_next], displaywidth=80 )) cur_answer = best_next[0] answer_tree[cur_answer] = {} next_parts = next_partitions([], cur_answer) for res, values in next_parts.items(): print('|{}| = {}'.format(Answer(cur_answer, res), len(values))) print(columnize( [num_to_colors(v) for v in values], displaywidth=80 ))
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''): '''Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not. ''' if type(val) != list: return False numeric = True for i in range(len(val)): if not (type(val[i]) in [bool, float, int, types.LongType]): numeric = False if not (type(val[i]) in [bool, float, int, bytes, str, types.LongType, types.UnicodeType, types.NoneType]): return False pass pass lines = columnize([repr(v) for v in val], displaywidth = int(displaywidth)-2, arrange_vertical = False, ljust = not numeric, lineprefix=lineprefix + ' ', colsep = ', ').split('\n') if '' == lines[-1]: del lines[-1] if 0 == len(lines): msg(lineprefix + '[]') return msg_nocr(lineprefix + "[") msg_nocr(lines[0][1:]) if 1 == len(lines): msg(lineprefix + ']') else: msg('') for line in lines[1:-1]: msg(lineprefix + line) pass msg(lineprefix + lines[-1] + ']') pass return True
def run(self, args): aliases = list(self.proc.aliases.keys()) aliases.sort() if len(args) == 0: self._alias_header() for alias in aliases: self._alias_line(alias) pass return if "*" in args: self.section("Current aliases:") self.msg(columnize.columnize(aliases, lineprefix=" ")) else: self._alias_header() for alias in args: if alias in aliases: self._alias_line(alias) else: self.errmsg("%s is not an alias" % alias) pass pass return return
def run(self, args): aliases = list(self.proc.aliases.keys()) aliases.sort() if len(args) == 0: self._alias_header() for alias in aliases: self._alias_line(alias) pass return if '*' in args: self.section("Current aliases:") self.msg(columnize.columnize(aliases, lineprefix=' ')) else: self._alias_header() for alias in args: if alias in aliases: self._alias_line(alias) else: self.errmsg("%s is not an alias" % alias) pass pass return return
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''): '''Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not. ''' if type(val) != list: return False numeric = True for i in range(len(val)): if not (type(val[i]) in [bool, float, int, types.LongType]): numeric = False if not (type(val[i]) in [bool, float, int, bytes, str, types.LongType, types.UnicodeType, types.NoneType]): return False pass pass mess = columnize([repr(v) for v in val], opts={"arrange_array": True, "lineprefix": lineprefix, "displaywidth": int(displaywidth)-3, 'ljust': not numeric}) msg_nocr(mess) return True
#!/usr/bin/env python from columnize import columnize from random import randint lst = [] for i in range(200): num_digits = randint(1, 6) lst.append(randint(0, 10 ** num_digits)) output = columnize(lst, opts={'ljust': True}) print(output)
def choosefromdict(self, sm): """ Query the user about which records to retrieve """ self.console_height, self.console_width = map(int, os.popen('stty size', 'r').read().split()) restart = True while restart: restart = False choice = dict(); exclude = dict(); numbers = None while numbers is None: print("\nSelect data fields to choose from. Enter corresponding integer(s), separated by commas.\n") screenoutput = list() for key in enumerate(sorted(sm.keys())): screenoutput.append(('[%s] %s' % (key[0]+1, key[1]))) print columnize.columnize(screenoutput, displaywidth=self.console_width) print ":", s = raw_input() try: numbers = map(int, s.split(',')) for n in numbers: if not (n in range(1,len(sm)+1)): print "\nERROR: Invalid input value. Please enter a comma separated list of integers in the range [1-" + str(len(sm)) + "].\n\n" numbers = None except ValueError: print "\nERROR: Invalid input type. Please enter a comma separated list of integers in the range [1-" + str(len(sm)) + "].\n\n" numbers = [n-1 for n in numbers] for number in numbers: thiskey = sorted(sm.keys())[number] choice[thiskey] = list(); exclude[thiskey] = list(); fieldvalues = sorted(set(sm[thiskey])) allowablevalues = range(-len(fieldvalues), len(fieldvalues)+1); allowablevalues.remove(0) numbers_fv = None while numbers_fv is None: print("\nSelect values to retrieve from " + thiskey + ". Enter corresponding integer(s), separated by commas. You can specify values to EXCLUDE by entering a negative valued integer. (Numbers in parentheses are the number of records that match that value).\n") screenoutput = list() for key in enumerate(fieldvalues): screenoutput.append(('[%s] %s (%s)' % (key[0]+1, key[1], sm[thiskey].count(key[1])))) print columnize.columnize(screenoutput, displaywidth=self.console_width) print ":", s = raw_input() try: numbers_fv = map(int, s.split(',')) for n in numbers_fv: if not (n in allowablevalues): print "\n ERROR: Invalid input value. Please enter a comma separated list of integers in the range ["+str(-len(fieldvalues))+"-" + str(len(fieldvalues)) + "], excluding 0.\n\n" numbers_fv = None except ValueError: print "\n ERROR: Invalid input type. Please enter a comma separated list of integers in the range ["+str(-len(fieldvalues))+"-" + str(len(fieldvalues)) + "], excluding 0.\n\n" for nfv in numbers_fv: if nfv > 0: choice[thiskey].append(fieldvalues[nfv-1]) if nfv < 0: exclude[thiskey].append(fieldvalues[abs(nfv)-1]) # get rid of keys with empty lists for values choice = dict((k, v) for k, v in choice.iteritems() if len(v)>0) exclude = dict((k, v) for k, v in exclude.iteritems() if len(v)>0) for k in set(choice.keys()) & set(exclude.keys()): if choice[k] == exclude[k]: print "\nERROR: Same value present in both choice and exclude:" print str(k) + " : " + str(choice[k]) print "Repeat selection? [y]/n: ", if raw_input() == ('y' or 'Y' or ''): restart = True return choice, exclude
def output_list(data, label, vt=ValueType.STRING, **kwargs): sys.stdout.write(columnize(data)) sys.stdout.flush()
def test_colfmt(self): self.assertEqual(' 0 1 2 3\n', columnize([0, 1, 2, 3], 7, arrange_vertical=False, opts={'colfmt': '%5d'}))
def columns(lst): return columnize(lst, opts={'ljust': True})
def output_dict(data, key_label, value_label, value_vt=ValueType.STRING): sys.stdout.write(columnize(['{0}={1}'.format(row[0], AsciiOutputFormatter.format_value(row[1], value_vt)) for row in list(data.items())])) sys.stdout.flush()
def run(self, args): """Get file information""" if len(args) == 0: if not self.proc.curframe: self.errmsg("No frame - no default file.") return False filename = self.proc.curframe.f_code.co_filename else: filename = args[0] pass m = filename + ' is' filename_cache = self.core.filename_cache if filename in filename_cache: m += " cached in debugger" if filename_cache[filename] != filename: m += ' as:' m = Mmisc.wrapped_lines(m, filename_cache[filename] + '.', self.settings['width']) else: m += '.' pass self.msg(m) else: matches = [ file for file in self.file_list() if file.endswith(filename) ] if (len(matches) > 1): self.msg("Multiple files found ending filename string:") for match_file in matches: self.msg("\t%s" % match_file) pass elif len(matches) == 1: canonic_name = pyficache.unmap_file(matches[0]) m += " matched debugger cache file:\n " + canonic_name self.msg(m) else: self.msg(m + ' not cached in debugger.') pass canonic_name = self.core.canonic(filename) self.msg( Mmisc.wrapped_lines('Canonic name:', canonic_name, self.settings['width'])) for name in (canonic_name, filename): if name in sys.modules: for key in [ k for k, v in list(sys.modules.items()) if name == v ]: self.msg("module: %s", key) pass pass pass for arg in args[1:]: processed_arg = False if arg in ['all', 'size']: if pyficache.size(canonic_name): self.msg("File has %d lines." % pyficache.size(canonic_name)) pass processed_arg = True pass if arg in ['all', 'sha1']: self.msg("SHA1 is %s." % pyficache.sha1(canonic_name)) processed_arg = True pass if arg in ['all', 'brkpts']: lines = pyficache.trace_line_numbers(canonic_name) if lines: self.section("Possible breakpoint line numbers:") fmt_lines = columnize.columnize(lines, ljust=False, arrange_vertical=False, lineprefix=' ') self.msg(fmt_lines) pass processed_arg = True pass if not processed_arg: self.errmsg("Don't understand sub-option %s." % arg) pass pass return
import sys import re import argparse import columnize def assword(length=12): try: num = int(length) if num < 8 or num > 16: return "Number must be between 8 and 16" num = str(num) except: num = "16" payload = {'n': num} r = requests.post("http://p.assword.me/", data=payload) assword = re.search('h2>(.*)<\/h2', r.text).group(1).replace('<span>','').replace('</span>','') return assword if __name__ == '__main__': parser = argparse.ArgumentParser(description='(P)assword generator based off http://p.assword.me.') parser.add_argument('iterations', metavar='N', type=int, default=1, help='Number of passwords to generate', nargs='?') parser.add_argument('-s', dest='length', type=int, default=12, help='Length of each password') args = parser.parse_args() asswords = [] for n in xrange(0, args.iterations): asswords.append(assword(args.length)) print(columnize.columnize(asswords, displaywidth=80))
def test_basic(self): """Basic sanity and status testing.""" self.assertEqual("1, 2, 3\n", columnize(['1', '2', '3'], 10, ', ')) self.assertEqual("1 3\n2 4\n", columnize(['1', '2', '3', '4'], 4)) self.assertEqual("1 3\n2 4\n", columnize(['1', '2', '3', '4'], 7)) self.assertEqual( "0 1 2\n3\n", columnize(['0', '1', '2', '3'], 7, arrange_vertical=False)) self.assertEqual("<empty>\n", columnize([])) self.assertEqual("oneitem\n", columnize(["oneitem"])) data = [str(i) for i in range(55)] self.assertEqual( "0, 6, 12, 18, 24, 30, 36, 42, 48, 54\n" + "1, 7, 13, 19, 25, 31, 37, 43, 49\n" + "2, 8, 14, 20, 26, 32, 38, 44, 50\n" + "3, 9, 15, 21, 27, 33, 39, 45, 51\n" + "4, 10, 16, 22, 28, 34, 40, 46, 52\n" + "5, 11, 17, 23, 29, 35, 41, 47, 53\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=True, colsep=', ')) self.assertEqual( " 0, 7, 14, 21, 28, 35, 42, 49\n" + " 1, 8, 15, 22, 29, 36, 43, 50\n" + " 2, 9, 16, 23, 30, 37, 44, 51\n" + " 3, 10, 17, 24, 31, 38, 45, 52\n" + " 4, 11, 18, 25, 32, 39, 46, 53\n" + " 5, 12, 19, 26, 33, 40, 47, 54\n" + " 6, 13, 20, 27, 34, 41, 48\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=True, colsep=', ', lineprefix=' ')) self.assertEqual( " 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n" + "10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n" + "20, 21, 22, 23, 24, 25, 26, 27, 28, 29\n" + "30, 31, 32, 33, 34, 35, 36, 37, 38, 39\n" + "40, 41, 42, 43, 44, 45, 46, 47, 48, 49\n" + "50, 51, 52, 53, 54\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=False, colsep=', ')) self.maxDiff = None self.assertEqual( " 0, 1, 2, 3, 4, 5, 6, 7\n" + " 8, 9, 10, 11, 12, 13, 14, 15\n" + " 16, 17, 18, 19, 20, 21, 22, 23\n" + " 24, 25, 26, 27, 28, 29, 30, 31\n" + " 32, 33, 34, 35, 36, 37, 38, 39\n" + " 40, 41, 42, 43, 44, 45, 46, 47\n" + " 48, 49, 50, 51, 52, 53, 54\n", columnize(data, displaywidth=34, ljust=False, arrange_vertical=False, colsep=', ', lineprefix=' ')) data = ( "one", "two", "three", "for", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen", "twenty", "twentyone", "twentytwo", "twentythree", "twentyfour", "twentyfive", "twentysix", "twentyseven", ) self.assertEqual( "one two three for five six \n" + "seven eight nine ten eleven twelve \n" + "thirteen fourteen fifteen sixteen seventeen eightteen \n" + "nineteen twenty twentyone twentytwo twentythree twentyfour\n" + "twentyfive twentysix twentyseven\n", columnize(data, arrange_vertical=False)) self.assertEqual( "one five nine thirteen seventeen twentyone twentyfive \n" + "two six ten fourteen eightteen twentytwo twentysix \n" + "three seven eleven fifteen nineteen twentythree twentyseven\n" + "for eight twelve sixteen twenty twentyfour \n", columnize(data)) self.assertEqual('0 1 2 3\n', columnize(list(range(4)))) self.assertEqual( "[ 0, 1, 2, 3, 4, 5, 6, 7, 8,\n" + " 9, 10, 11, 12, 13, 14, 15, 16, 17,\n" + " 18, 19, 20, 21, 22, 23, 24, 25, 26,\n" + " 27, 28, 29, 30, 31, 32, 33, 34, 35,\n" + " 36, 37, 38, 39, 40, 41, 42, 43, 44,\n" + " 45, 46, 47, 48, 49, 50, 51, 52, 53,\n" + " 54]\n\n", columnize(list(range(55)), opts={ 'displaywidth': 38, 'arrange_array': True })) self.assertEqual( """[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] """, columnize(list(range(12)), opts={ 'displaywidth': 6, 'arrange_array': True })) self.assertEqual( """[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] """, columnize(list(range(12)), opts={ 'displaywidth': 9, 'arrange_array': True })) return
def print_nodes(h5: Union[str, HDFStore], displaywidth=160): from columnize import columnize nodes = do_h5(h5, lambda h5db: sorted(h5db.keys())) print(columnize(nodes, displaywidth=displaywidth))
def run(self, args): """Get file information""" if len(args) == 0: if not self.proc.curframe: self.errmsg("No frame - no default file.") return False filename = self.proc.curframe.f_code.co_filename else: filename = args[0] pass m = filename + " is" filename_cache = self.core.filename_cache if filename in filename_cache: m += " cached in debugger" if filename_cache[filename] != filename: m += " as:" m = Mmisc.wrapped_lines(m, filename_cache[filename] + ".", self.settings["width"]) else: m += "." pass self.msg(m) else: matches = [file for file in file_list() if file.endswith(filename)] if len(matches) > 1: self.msg("Multiple files found ending filename string:") for match_file in matches: self.msg("\t%s" % match_file) pass elif len(matches) == 1: canonic_name = pyficache.unmap_file(matches[0]) m += " matched debugger cache file:\n " + canonic_name self.msg(m) else: self.msg(m + " not cached in debugger.") pass canonic_name = self.core.canonic(filename) self.msg(Mmisc.wrapped_lines("Canonic name:", canonic_name, self.settings["width"])) for name in (canonic_name, filename): if name in sys.modules: for key in [k for k, v in list(sys.modules.items()) if name == v]: self.msg("module: %s", key) pass pass pass for arg in args[1:]: processed_arg = False if arg in ["all", "size"]: if pyficache.size(canonic_name): self.msg("File has %d lines." % pyficache.size(canonic_name)) pass processed_arg = True pass if arg in ["all", "sha1"]: self.msg("SHA1 is %s." % pyficache.sha1(canonic_name)) processed_arg = True pass if arg in ["all", "brkpts"]: lines = pyficache.trace_line_numbers(canonic_name) if lines: self.section("Possible breakpoint line numbers:") fmt_lines = columnize.columnize(lines, ljust=False, arrange_vertical=False, lineprefix=" ") self.msg(fmt_lines) pass processed_arg = True pass if not processed_arg: self.errmsg("Don't understand sub-option %s." % arg) pass pass return
def process(self, player, args=''): argList = args.split(" ", 1) t = None if len(argList) != 2: player.writeWithPrompt("Proper format is: info ctemplate/cinstance/itemplate/iinstance ID") return if argList[0].lower() == 'cinstance': for eachChar in player.getRoomRef().getCharacters().values(): try: if eachChar.getId() == int(argList[1]): t = eachChar break except: player.writeWithPrompt("IDs must be numbers only!") return if t == None: player.writeWithPrompt("That character instance was not found.") return player.writePlain("<red>[Name]: <r> "+t.getName()+'\r\n') player.writePlain("<red>[ID ]: <r>"+str(t.getId())+'\r\n') player.writePlain("<red>[TID ]: <r>"+str(t.getTemplateId())+'\r\n') player.writePlain("\r\n<green>[STATISTICS]") statList = t.getStats().keys() newList = [] for eachItem in statList: eachItem = eachItem + ": "+str(t.getStat(eachItem)) newList.append(eachItem) columnize.columnize(player, newList, 4) cmdList = t.getCommands() player.writePlain("\r\n\r\n<green>[COMMANDS]<r>") columnize.columnize(player, cmdList, 6) player.writePlain('\r\n\r\n<green>[LOGICS]<r>') logicList = t.getLogics().keys() columnize.columnize(player, logicList, 6) player.writeWithPrompt("\r\nEND INFO") elif argList[0].lower() == 'ctemplate': t = MudWorld.world.templateDb.findTemplateById('character', int(argList[1])) if t == None: player.writeWithPrompt("That template was not found.") return player.writePlain("<red>[Name]: <r> "+t.getName()+'\r\n') player.writePlain("<red>[ID ]: <r>"+str(t.getId())+'\r\n') player.writePlain("\r\n<green>[STATISTICS]") statList = t.getStats().keys() for eachItem in statList: eachItem = eachItem + ": "+str(t.getStat(eachItem)) columnize.columnize(player, statList, 4) cmdList = t.getCommands() player.writePlain("\r\n\r\n<green>[COMMANDS]<r>") columnize.columnize(player, cmdList, 6) player.writePlain('\r\n\r\n<green>[LOGICS]<r>') logicList = t.getLogics().keys() columnize.columnize(player, logicList, 6) player.writeWithPrompt("\r\nEND INFO") elif argList[0].lower() == 'itemplate': t = MudWorld.world.templateDb.findTemplateById('item', int(argList[1])) if t == None: player.writeWithPrompt("That template was not found.") return player.writePlain("<red>[Name]: <r> "+t.getName()+'\r\n') player.writePlain("<red>[ID ]: <r>"+str(t.getId())+'\r\n') player.writePlain("\r\n<green>[STATISTICS]") statList = t.getStats().keys() for eachItem in statList: eachItem = eachItem + ": "+str(t.getStat(eachItem)) columnize.columnize(player, statList, 4) cmdList = t.getCommands() player.writePlain("\r\n\r\n<green>[COMMANDS]<r>") columnize.columnize(player, cmdList, 6) player.writePlain('\r\n\r\n<green>[LOGICS]<r>') logicList = t.getLogics().keys() columnize.columnize(player, logicList, 6) player.writeWithPrompt("\r\nEND INFO") elif argList[0].lower() == 'iinstance': for eachItem in player.getRoomRef().getItems().values(): try: if eachItem.getId() == int(argList[1]): t = eachItem break except: player.writeWithPrompt("IDs must be numbers only!") return if t == None: player.writeWithPrompt("An item with that ID was not found in this room.") return player.writePlain("<red>[Name]: <r> "+t.getName()+'\r\n') player.writePlain("<red>[ID ]: <r>"+str(t.getId())+'\r\n') player.writePlain("<red>[TID ]: <r>"+str(t.getTemplateId())+'\r\n') player.writePlain("\r\n<green>[STATISTICS]") statList = t.getStats().keys() for eachItem in statList: eachItem = eachItem + ": "+str(t.getStat(eachItem)) columnize.columnize(player, statList, 4) cmdList = t.getCommands() player.writePlain("\r\n\r\n<green>[COMMANDS]<r>") columnize.columnize(player, cmdList, 6) player.writePlain('\r\n\r\n<green>[LOGICS]<r>') logicList = t.getLogics().keys() columnize.columnize(player, logicList, 6) player.writeWithPrompt("\r\nEND INFO") player.writeWithPrompt(argList[2]+' was changed to: '+str(argList[3])+' on: '+t.getName()) else: player.writeWithPrompt("Invalid type. Please use iinstance, itemplate, cinstance, or ctemplate.") return
#!/usr/bin/env python from columnize import columnize from random import randint lst = [] for i in range(200): num_digits = randint(1, 6) lst.append(randint(0, 10**num_digits)) output = columnize(lst, opts={'ljust': True}) print(output)
# vehicle_no rated_power v_max ndv_6 no_of_gears v_max_4 v_max_10 n_min_drive_set n95_high at_s # comments kerb_mass ndv_1 ndv_7 ng_vmax v_max_5 v_s_max n_min_wot n_max1 above_s # pmr_km test_mass ndv_2 ndv_8 v_max_ext v_max_6 n_vmax f_dsc_req n_max2 vmax_determined_by_n_lim # pmr_tm rated_speed ndv_3 ndv_9 v_max_1 v_max_7 f0 Pres_130 n_max3 # IDclass idling_speed ndv_4 ndv_10 v_max_2 v_max_8 f1 Pres_130_Prated n_max_wot # class v_max_declared ndv_5 v_max_transmission v_max_3 v_max_9 f2 n95_low below_s # # Index(['no_engine', 'n', 'Pwot', 'Twot', 'Pwot_norm', 'Twot_norm', 'SM', 'ASM', # 'Pavai'], # dtype='object') # ``` # %% import qgrid print(columnize(list(specs.columns), displaywidth=160)) print(pwots.columns) print(specs[c_vehnum].unique(), specs[c_case].unique()) display(vehdb.grid(specs, fitcols=False), vehdb.grid(pwots)) # %% def extract_SM_from_pwot( pwot, c_n=c_n, c_pwot=c_pwot, c_SM=c_SM, c_ASM=c_ASM ) -> "Tuple(pd.DataFrame, float)": """ Keep just (n, Pwot, ASM) columns & extract SM column as scalar value. :param pwot: the wot-curve dataframe for a single vehicle, with columns::
def test_basic(self): """Basic sanity and status testing.""" self.assertEqual("1, 2, 3\n", columnize(['1', '2', '3'], 10, ', ')) self.assertEqual("1 3\n2 4\n", columnize(['1', '2', '3', '4'], 4)) self.assertEqual("1 3\n2 4\n", columnize(['1', '2', '3', '4'], 7)) self.assertEqual("0 1 2\n3\n", columnize(['0', '1', '2', '3'], 7, arrange_vertical=False)) self.assertEqual("<empty>\n", columnize([])) self.assertEqual("oneitem\n", columnize(["oneitem"])) data = [str(i) for i in range(55)] self.assertEqual( "0, 6, 12, 18, 24, 30, 36, 42, 48, 54\n" + "1, 7, 13, 19, 25, 31, 37, 43, 49\n" + "2, 8, 14, 20, 26, 32, 38, 44, 50\n" + "3, 9, 15, 21, 27, 33, 39, 45, 51\n" + "4, 10, 16, 22, 28, 34, 40, 46, 52\n" + "5, 11, 17, 23, 29, 35, 41, 47, 53\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=True, colsep=', ')) self.assertEqual( " 0, 7, 14, 21, 28, 35, 42, 49\n" + " 1, 8, 15, 22, 29, 36, 43, 50\n" + " 2, 9, 16, 23, 30, 37, 44, 51\n" + " 3, 10, 17, 24, 31, 38, 45, 52\n" + " 4, 11, 18, 25, 32, 39, 46, 53\n" + " 5, 12, 19, 26, 33, 40, 47, 54\n" + " 6, 13, 20, 27, 34, 41, 48\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=True, colsep=', ', lineprefix=' ')) self.assertEqual( " 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n" + "10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n" + "20, 21, 22, 23, 24, 25, 26, 27, 28, 29\n" + "30, 31, 32, 33, 34, 35, 36, 37, 38, 39\n" + "40, 41, 42, 43, 44, 45, 46, 47, 48, 49\n" + "50, 51, 52, 53, 54\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=False, colsep=', ')) self.maxDiff = None self.assertEqual( " 0, 1, 2, 3, 4, 5, 6, 7\n" + " 8, 9, 10, 11, 12, 13, 14, 15\n" + " 16, 17, 18, 19, 20, 21, 22, 23\n" + " 24, 25, 26, 27, 28, 29, 30, 31\n" + " 32, 33, 34, 35, 36, 37, 38, 39\n" + " 40, 41, 42, 43, 44, 45, 46, 47\n" + " 48, 49, 50, 51, 52, 53, 54\n", columnize(data, displaywidth=39, ljust=False, arrange_vertical=False, colsep=', ', lineprefix=' ')) data = ( "one", "two", "three", "for", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen", "twenty", "twentyone", "twentytwo", "twentythree", "twentyfour", "twentyfive","twentysix", "twentyseven",) self.assertEqual( "one two three for five six \n" + "seven eight nine ten eleven twelve \n" + "thirteen fourteen fifteen sixteen seventeen eightteen \n" + "nineteen twenty twentyone twentytwo twentythree twentyfour\n" + "twentyfive twentysix twentyseven\n", columnize(data, arrange_vertical=False)) self.assertEqual( "one five nine thirteen seventeen twentyone twentyfive \n" + "two six ten fourteen eightteen twentytwo twentysix \n" + "three seven eleven fifteen nineteen twentythree twentyseven\n" + "for eight twelve sixteen twenty twentyfour \n", columnize(data)) self.assertEqual('0 1 2 3\n', columnize(list(range(4)))) self.assertEqual( "[ 0, 1, 2, 3, 4, 5, 6, 7, 8,\n"+ " 9, 10, 11, 12, 13, 14, 15, 16, 17,\n"+ " 18, 19, 20, 21, 22, 23, 24, 25, 26,\n"+ " 27, 28, 29, 30, 31, 32, 33, 34, 35,\n"+ " 36, 37, 38, 39, 40, 41, 42, 43, 44,\n"+ " 45, 46, 47, 48, 49, 50, 51, 52, 53,\n"+ " 54]\n\n", columnize(list(range(55)), opts={'displaywidth':39, 'arrange_array':True})) self.assertEqual("""[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] """, columnize(list(range(12)), opts={'displaywidth':6, 'arrange_array':True})) self.assertEqual("""[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] """, columnize(list(range(12)), opts={'displaywidth':10, 'arrange_array':True})) return