Print list of namedtuples into a table using prtfmt.
552942
def get_lines(data_nts, prtfmt=None, nt_fields=None, **kws):
    """"""
    lines = []
    # optional keyword args: prt_if sort_by
    if prtfmt is None:
        prtfmt = mk_fmtfld(data_nts[0], kws.get('joinchr', ' '), kws.get('eol', '\n'))
    # if nt_fields arg is None, use fields from prtfmt string.
    if nt_fields is not None:
        _chk_flds_fmt(nt_fields, prtfmt)
    if 'sort_by' in kws:
        data_nts = sorted(data_nts, key=kws['sort_by'])
    prt_if = kws.get('prt_if', None)
    for data_nt in data_nts:
        if prt_if is None or prt_if(data_nt):
            lines.append(prtfmt.format(**data_nt._asdict()))
    return lines
1041041
def list(cls,
             l,
             order=None,
             header=None,
             output="table",
             sort_keys=True,
             show_none=""
             ):
        
        d = {}
        count = 0
        for entry in l:
            name = str(count)
            d[name] = entry
            count += 1
        return cls.dict(d,
                        order=order,
                        header=header,
                        sort_keys=sort_keys,
                        output=output,
                        show_none=show_none)
379175
def wr_tsv(self, fout_tsv):
        """"""
        with open(fout_tsv, 'w') as prt:
            kws_tsv = {
                'fld2fmt': {f:'{:8.2e}' for f in self.flds_cur if f[:2] == 'p_'},
                'prt_flds':self.flds_cur}
            prt_tsv_sections(prt, self.desc2nts['sections'], **kws_tsv)
            print("  WROTE: {TSV}".format(TSV=fout_tsv))
376489
def print_contents(self):
        
        print "\t\t\t".join(self.columns)
        temp_list = []
        for i in self.columns:
            temp_list.append(self.get_column(i))
        for i in zip(*(temp_list)):
            print "\t\t\t".join(map(str, i))
1035661
def print_list(cls, l, output='table'):
        

        def dict_from_list(l):
            """
            returns a dict from a list for printing
            :param l: the list
            :return: 
            """
            d = dict([(idx, item) for idx, item in enumerate(l)])
            return d

        if output == 'table':
            x = PrettyTable(["Index", "Host"])
            for (idx, item) in enumerate(l):
                x.add_row([idx, item])
            x.align = "l"
            x.align["Index"] = "r"
            return x
        elif output == 'csv':
            return ",".join(l)
        elif output == 'dict':
            d = dict_from_list(l)
            return d
        elif output == 'json':
            d = dict_from_list(l)
            result = json.dumps(d, indent=4)
            return result
        elif output == 'yaml':
            d = dict_from_list(l)
            result = yaml.dump(d, default_flow_style=False)
            return result
        elif output == 'txt':
            return "\n".join(l)
10018
def print_virt_table(self, data):
        """"""

        table = prettytable.PrettyTable()
        keys = sorted(data.keys())
        table.add_column('Keys', keys)
        table.add_column('Values', [data.get(i) for i in keys])
        for tbl in table.align.keys():
            table.align[tbl] = 'l'

        self.printer(table)
1339857
def _output(cls,
            tensors: Sequence[tf.Tensor],
            dtypes: Sequence[tf.DType]) -> Sequence[tf.Tensor]:
        ''''''
        outputs = []
        for tensor, dtype in zip(tensors, dtypes):
            tensor = tensor[0]
            if tensor.dtype != dtype:
                tensor = tf.cast(tensor, dtype)
            outputs.append(tensor)
        return tuple(outputs)
466858
def print_all(self, out=sys.stdout):
        
        THREAD_FUNC_NAME_LEN = 25
        THREAD_NAME_LEN = 13
        THREAD_ID_LEN = 15
        THREAD_SCHED_CNT_LEN = 10

        out.write(CRLF)
        out.write("name           tid              ttot      scnt")
        out.write(CRLF)
        for stat in self:
            out.write(StatString(stat.name).ltrim(THREAD_NAME_LEN))
            out.write(" " * COLUMN_GAP)
            out.write(StatString(stat.id).rtrim(THREAD_ID_LEN))            
            out.write(" " * COLUMN_GAP)
            out.write(StatString(_fft(stat.ttot)).rtrim(TIME_COLUMN_LEN))
            out.write(" " * COLUMN_GAP)
            out.write(StatString(stat.sched_count).rtrim(THREAD_SCHED_CNT_LEN))
            out.write(CRLF)
82195
def iter_to_table(value):
    """"""
    if isinstance(value, list):
        return _format_list(value)
    if isinstance(value, dict):
        return _format_dict(value)
    return value
1279375
def concat_namedtuples(*tup, **kwargs):
    '''
    
    '''
    name = kwargs['name'] if 'name' in kwargs else None

    # filter out empty elements
    filtered = [i for i in filter(None, tup)]
    if filtered:
        if len(filtered) == 1:
            return filtered[0]
        else:
            fields = chain(*(t._fields for t in filtered))
            values = chain(*(t for t in filtered))
            if not name:
                name = 'SDMXNamedTuple'
            ConcatType = namedtuple_factory(name, fields)
            return ConcatType(*values)
    else:
        return ()
531213
def list_to_cells(lst):
    '''
    '''
    cells = '"cells": ['
    for cell in lst:
        to_add = '{"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["' + '\\n","'.join(cell) + '"]},'
        cells += to_add

    cells = cells[:-1] + '],'

    nb = '{' + cells + '"metadata": {"header": "HEADLESS", "kernelspec": {"display_name" : "python", "language": "", "name": "python"}, "language":"python"'

    return nbformat.writes(nbformat.reads(nb, as_version=4)).encode('utf-8')
183486
def pp_tuple(self, tup):
        """"""
        last_line = self.f.getvalue().split("\n")[-1]
        l = len(last_line)+1
        indent = ' ' * l
        self.write('(')
        sep = ''
        for item in tup:
            self.write(sep)
            l += len(sep)
            s = repr(item)
            l += len(s)
            self.write(s)
            sep = ','
            if l > LINE_LENGTH:
                l = 0
                sep += '\n' + indent
            else:
                sep += ' '
                pass
            pass
        if len(tup) == 1:
            self.write(", ")
        self.write(')')
1374102
def zip_namedtuple(nt_list):
    
    if not nt_list:
        return dict()
    if not isinstance(nt_list, list):
        nt_list = [nt_list]
    for nt in nt_list:
        assert type(nt) == type(nt_list[0])
    ret = {k : [v] for k, v in nt_list[0]._asdict().items()}
    for nt in nt_list[1:]:
        for k, v in nt._asdict().items():
            ret[k].append(v)
    return ret
508947
def process_contents(self, contents, fname=None):
        
        self.stack = []
        self.dispatch_table = self.default_table.copy()
        self.current_file = fname
        self.tuples = self.tupleize(contents)

        self.initialize_result(fname)
        while self.tuples:
            t = self.tuples.pop(0)
            # Uncomment to see the list of tuples being processed (e.g.,
            # to validate the CPP lines are being translated correctly).
            #print(t)
            self.dispatch_table[t[0]](t)
        return self.finalize_result(fname)
383980
def print_table(data, title=None):
    
    if isinstance(data, dict):
        data = list(data.items())
    tpl_row = '    {:<15}' * len(data[0])
    table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data])
    if title:
        print('\n    \033[93m{}\033[0m'.format(title))
    print('\n{}\n'.format(table))
1036664
def _get_prtfmt(self, objgowr, verbose):
        """"""
        prtfmt = objgowr.get_prtfmt('fmt')
        prtfmt = prtfmt.replace('# ', '')
        # print('PPPPPPPPPPP', prtfmt)
        if not verbose:
            prtfmt = prtfmt.replace('{hdr1usr01:2}', '')
            prtfmt = prtfmt.replace('{childcnt:3} L{level:02} ', '')
            prtfmt = prtfmt.replace('{num_usrgos:>4} uGOs ', '')
            prtfmt = prtfmt.replace('{D1:5} {REL} {rel}', '')
            prtfmt = prtfmt.replace('R{reldepth:02} ', '')
        # print('PPPPPPPPPPP', prtfmt)
        marks = ''.join(['{{{}}}'.format(nt.hdr) for nt in self.go_ntsets])
        return '{MARKS} {PRTFMT}'.format(MARKS=marks, PRTFMT=prtfmt)
730306
def print_table(lines, separate_head=True):
	""""""
	#Count the column width
	widths = []
	for line in lines:
			for i,size in enumerate([len(x) for x in line]):
					while i >= len(widths):
							widths.append(0)
					if size > widths[i]:
							widths[i] = size
	   
	#Generate the format string to pad the columns
	print_string = ""
	for i,width in enumerate(widths):
			print_string += "{" + str(i) + ":" + str(width) + "} | "
	if (len(print_string) == 0):
			return
	print_string = print_string[:-3]
	   
	#Print the actual data
	for i,line in enumerate(lines):
			print(print_string.format(*line))
			if (i == 0 and separate_head):
					print("-"*(sum(widths)+3*(len(widths)-1)))