Return a rows.Table created from imported TXT file.
978119
def import_from_txt(
    filename_or_fobj, encoding="utf-8", frame_style=FRAME_SENTINEL, *args, **kwargs
):
    """"""

    # TODO: (maybe)
    # enable parsing of non-fixed-width-columns
    # with old algorithm - that would just split columns
    # at the vertical separator character for the frame.
    # (if doing so, include an optional parameter)
    # Also, this fixes an outstanding unreported issue:
    # trying to parse tables which fields values
    # included a Pipe char - "|" - would silently
    # yield bad results.

    source = Source.from_file(filename_or_fobj, mode="rb", plugin_name="txt", encoding=encoding)
    raw_contents = source.fobj.read().decode(encoding).rstrip("\n")

    if frame_style is FRAME_SENTINEL:
        frame_style = _guess_frame_style(raw_contents)
    else:
        frame_style = _parse_frame_style(frame_style)

    contents = raw_contents.splitlines()
    del raw_contents

    if frame_style != "None":
        contents = contents[1:-1]
        del contents[1]
    else:
        # the table is possibly generated from other source.
        # check if the line we reserve as a separator is realy empty.
        if not contents[1].strip():
            del contents[1]
    col_positions = _parse_col_positions(frame_style, contents[0])

    table_rows = [
        [
            row[start + 1 : end].strip()
            for start, end in zip(col_positions, col_positions[1:])
        ]
        for row in contents
    ]

    meta = {
        "imported_from": "txt",
        "source": source,
        "frame_style": frame_style,
    }
    return create_table(table_rows, meta=meta, *args, **kwargs)
264539
def table_output(data):
    ''''''
    if type(data) == DictType:
        data = data.items()
    headings = [ item[0] for item in data ]
    rows = [ item[1] for item in data ]
    columns = zip(*rows)
    if len(columns):
        widths = [ max([ len(str(y)) for y in row ]) for row in rows ]
    else:
        widths = [ 0 for c in headings ]
    for c, heading in enumerate(headings):
        widths[c] = max(widths[c], len(heading))
    column_count = range(len(rows))
    table = [ ' '.join([ headings[c].ljust(widths[c]) for c in column_count ]) ]
    table.append(' '.join([ '=' * widths[c] for c in column_count ]))
    for column in columns:
        table.append(' '.join([ str(column[c]).ljust(widths[c]) for c in column_count ]))
    return '\n'.join(table)
487024
def build_table(self, msg):
        """"""
        rows = msg.split('\n')
        if rows:
            header_row, *body_rows = rows
            self.create_md_row(header_row, True)
            for row in body_rows:
                self.create_md_row(row)
992847
def _GetRow(self, columns=None):
        """"""

        row = self._table[self._row_index]
        if columns:
            result = []
            for col in columns:
                if col not in self.header:
                    raise TableError("Column header %s not known in table." % col)
                result.append(row[self.header.index(col)])
            row = result
        return row
806635
def row_factory(cursor, row):
    """"""
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d
773221
def dict_to_table(header, contents):
    
    def to_text(row):
        name, value = row
        m = max_col1_size + 1 - len(name)
        spacing = ' ' * m

        return ''.join([name, spacing, value])

    thead = tuple(str(col) for col in header)
    rows = []
    for name, value in contents.items():
        # code highlighting
        if value != '':
            if isinstance(value, str):
                value = "'{}'".format(value)
            value = ':py:`{}`'.format(value)
        rows.append((name, value))

    n = np.max([len(header[0])] +
               [len(col1) for col1, _ in rows])
    hborder = tuple('='*n for col in header)
    rows = [hborder, thead, hborder] + rows + [hborder]
    max_col1_size = np.max([len(col1) for col1, _ in rows])
    table = '\n'.join([to_text(row) for row in rows])
    return table
457054
def import_table(self, source, table_name):
        """"""
        query = "SELECT * FROM `%s`" % table_name.lower()
        df = pandas.read_sql(query, source.connection)
        df.to_sql(table_name, con=self.own_connection)
513074
def from_rows(cls, rows, labels):
        """"""
        warnings.warn("Table.from_rows is deprecated. Use Table(labels).with_rows(...)", FutureWarning)
        return cls(labels).with_rows(rows)
1198767
def _read_table(self, filename):
        
        filename = pkg_resources.resource_filename(
            __name__, filename)
        segments = []
        with open(filename, 'rb') as f:
            reader = csv.reader(f, encoding='utf-8')
            header = next(reader)
            names = header[1:]
            for row in reader:
                seg = row[0]
                vals = row[1:]
                specs = set(zip(vals, names))
                segments.append((seg, specs))
        seg_dict = dict(segments)
        return segments, seg_dict, names
1101149
def _textToTable(self, text, separator='\t'):
        
        table = None
        if text.startswith('[[') or text.startswith('(('):
            try:
                # maybe it's already formated as a list e.g. "[['1','2'],[...]]"
                # check it:
                t = eval(text)
            # has to be a 2d-list:
                if isinstance(t, list) and isinstance(t[0], list):
                    table = t
            except SyntaxError:
                # not a valid list
                pass
        if not table:
            # create the list from the clipboard-text
            # therefore the text has to be formated like this:
                # "1\t2\3\n4\t5\6\n"
            table = text.split('\n')
            n = 0
            while n < len(table):
                sline = table[n].split(separator)
                if sline != ['']:
                    table[n] = sline
                else:
                    table.pop(n)
                    n -= 1
                n += 1
        return table
457920
def _get_column(in_file, out_file, column, data=None):
    
    with file_transaction(data, out_file) as tx_out_file:
        with open(in_file) as in_handle:
            with open(tx_out_file, 'w') as out_handle:
                for line in in_handle:
                    cols = line.strip().split("\t")
                    if line.find("eff_count") > 0:
                        continue
                    number = cols[column]
                    if column == 7:
                        number = int(round(float(number), 0))
                    out_handle.write("%s\t%s\n" % (cols[1], number))
    return out_file
1021728
def prepare_rows(self,
                     rows,
                     indent,
                     has_header):

        ''''''

        out = []

        def row_wrapper(row):
            new_rows = [
                self.wrapfunc(item).split('\n')
                for item in row
            ]
            rows = []
            for item in map(lambda *args: args, *new_rows):
                if isinstance(item, (tuple, list)):
                    rows.append([substr or '' for substr in item])
                else:
                    rows.append([item])
            return rows

        logical_rows = [
            row_wrapper(row)
            for row in rows
        ]

        columns = map(lambda *args: args, *reduce(operator.add, logical_rows))

        max_widths = [
            max([len(six.text_type(item)) for item in column])
            for column in columns
        ]
        row_separator = self.row_delimiter * (len(self.prefix) + len(self.suffix) + sum(max_widths) +
                                              len(self.delim) * (len(max_widths) - 1))

        justify = self._JUSTIFY_MAP[self.justify.lower()]

        if self.separate_rows:
            out.append(
                self.ustring(
                    indent,
                    self.LIGHT_GRAY,  # pylint: disable=no-member
                    row_separator
                )
            )
        for physical_rows in logical_rows:
            for row in physical_rows:
                line = self.prefix \
                        + self.delim.join([
                                justify(six.text_type(item), width)
                                for (item, width) in zip(row, max_widths)
                        ]) + self.suffix
                out.append(
                    self.ustring(
                        indent,
                        self.WHITE,  # pylint: disable=no-member
                        line
                    )
                )
            if self.separate_rows or has_header:
                out.append(
                    self.ustring(
                        indent,
                        self.LIGHT_GRAY,  # pylint: disable=no-member
                        row_separator
                    )
                )
                has_header = False
        return out
588505
def table_repr(columns, rows, data, padding=2):
    """"""
    padding = ' ' * padding
    column_lengths = [len(column) for column in columns]
    for row in rows:
        for i, column in enumerate(columns):
            item = str(data[row][column])
            column_lengths[i] = max(len(item), column_lengths[i])
    max_row_length = max(len(row) for row in rows) if len(rows) else 0
    table_row = ' ' * max_row_length
    for i, column in enumerate(columns):
        table_row += padding + column.rjust(column_lengths[i])
    table_rows = [table_row]
    for row in rows:
        table_row = row.rjust(max_row_length)
        for i, column in enumerate(columns):
            item = str(data[row][column])
            table_row += padding + item.rjust(column_lengths[i])
        table_rows.append(table_row)
    return '\n'.join(table_rows)
82195
def iter_to_table(value):
    """"""
    if isinstance(value, list):
        return _format_list(value)
    if isinstance(value, dict):
        return _format_dict(value)
    return value
1362155
def get_table(self, tablename):
        
        table, (_row, _col) = self.__tables[tablename]
        return table
562297
def _read_table_file(self, table_file):
        """"""
        self._table_file = table_file
        if os.path.exists(self._table_file):
            self._table = Table.read(self._table_file)
        else:
            self._table = FileHandle.make_table({})
        self._fill_cache()
125972
def open_data(self, text, colsep=u"\t", rowsep=u"\n",
                  transpose=False, skiprows=0, comments='#'):
        """"""
        if pd:
            self.pd_text = text
            self.pd_info = dict(sep=colsep, lineterminator=rowsep,
                skiprows=skiprows, comment=comments)
            if colsep is None:
                self.pd_info = dict(lineterminator=rowsep, skiprows=skiprows,
                    comment=comments, delim_whitespace=True)
        self._table_view.process_data(text, colsep, rowsep, transpose,
                                      skiprows, comments)