Produce dictionary of sequences from sequence of sequences, optionally with a header "row".

    >>> dos_from_table([['hello', 'world'], [1, 2], [3,4]]) == {'hello': [1, 3], 'world': [2, 4]}
    True
12322
def dos_from_table(table, header=None):
    
    start_row = 0
    if not table:
        return table
    if not header:
        header = table[0]
        start_row = 1
    header_list = header
    if header and isinstance(header, basestring):
        header_list = header.split('\t')
        if len(header_list) != len(table[0]):
            header_list = header.split(',')
        if len(header_list) != len(table[0]):
            header_list = header.split(' ')
    ans = {}
    for i, k in enumerate(header):
        ans[k] = [row[i] for row in table[start_row:]]
    return ans
970359
def to_sparse_tuple(sequence):
    
    """
    indices = np.asarray(list(zip([0]*len(sequence), range(len(sequence)))), dtype=np.int64)
    shape = np.asarray([1, len(sequence)], dtype=np.int64)
    return indices, sequence, shape
734181
def multidict(D):
    ''''''
    keys = list(D.keys())
    if len(keys) == 0:
        return [[]]
    try:
        N = len(D[keys[0]])
        islist = True
    except:
        N = 1
        islist = False
    dlist = [dict() for d in range(N)]
    for k in keys:
        if islist:
            for i in range(N):
                dlist[i][k] = D[k][i]
        else:
            dlist[0][k] = D[k]
    return [keys]+dlist
74806
def _read_as_table(self):
        
        rows = list()

        for row in self._rows:
            rows.append([row[i].get() for i in range(self.num_of_columns)])

        return rows
947718
def generate_list_table_result(lexicon_logger, output=None, without_header=None):
    """"""
    if not isinstance(output, list):
        lexicon_logger.debug('Command output is not a list, and then cannot '
                             'be printed with --quiet parameter not enabled.')
        return None

    array = [[
        row.get('id', ''),
        row.get('type', ''),
        row.get('name', ''),
        row.get('content', ''),
        row.get('ttl', '')] for row in output]

    # Insert header (insert before calculating the max width of each column
    # to take headers size into account)
    if not without_header:
        headers = ['ID', 'TYPE', 'NAME', 'CONTENT', 'TTL']
        array.insert(0, headers)

    column_widths = [0, 0, 0, 0, 0]
    # Find max width for each column
    for row in array:
        for idx, col in enumerate(row):
            width = len(str(col))
            if width > column_widths[idx]:
                column_widths[idx] = width

    # Add a 'nice' separator
    if not without_header:
        array.insert(1, ['-' * column_widths[idx]
                         for idx in range(len(column_widths))])

    # Construct table to be printed
    table = []
    for row in array:
        row_list = []
        for idx, col in enumerate(row):
            row_list.append(str(col).ljust(column_widths[idx]))
        table.append(' '.join(row_list))

    # Return table
    return os.linesep.join(table)
580332
def sequences(self):
        
        seqs = [x.sequence for x in self._molecules if hasattr(x, 'sequence')]
        return seqs
1312584
def toDict(self):
        
        d = {}
        nindices = self.getNumIndices()
        for i in range(self.getNumRows()):
            row = list(self.getRowByIndex(i))
            if nindices > 1:
                key = tuple(row[:nindices])
            elif nindices == 1:
                key = row[0]
            else:
                key = None
            if len(row) - nindices == 0:
                d[key] = None
            elif len(row) - nindices == 1:
                d[key] = row[nindices]
            else:
                d[key] = tuple(row[nindices:])
        return d
362917
def _transpose_dict_list(dict_list):
  """"""
  # 1. Unstack numpy arrays into list
  dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True)

  # 2. Extract the sequence length (and ensure the length is constant for all
  # elements)
  length = {'value': None}  # dict because `nonlocal` is Python3 only
  def update_length(elem):
    if length['value'] is None:
      length['value'] = len(elem)
    elif length['value'] != len(elem):
      raise ValueError(
          'The length of all elements of one sequence should be the same. '
          'Got {} != {}'.format(length['value'], len(elem)))
    return elem
  utils.map_nested(update_length, dict_list, dict_only=True)

  # 3. Extract each individual elements
  return [
      utils.map_nested(lambda elem: elem[i], dict_list, dict_only=True)   # pylint: disable=cell-var-from-loop
      for i in range(length['value'])
  ]
1262021
def to_dict(self, columns=None):
        
        if columns:
            assert len(columns) == len(self.feature_names)
        d = [
            dict([
                (columns[i] if columns else col_name, row[i])
                for i, col_name in enumerate(self.feature_names)
            ])
            for row in self.data
        ]
        return d
877706
def format_table(columns, rows):
    
    rows = [tuple(str(i) for i in r) for r in rows]
    columns = tuple(str(i).upper() for i in columns)
    if rows:
        widths = tuple(max(max(map(len, x)), len(c))
                       for x, c in zip(zip(*rows), columns))
    else:
        widths = tuple(map(len, columns))
    row_template = ('    '.join('%%-%ds' for _ in columns)) % widths
    header = (row_template % tuple(columns)).strip()
    if rows:
        data = '\n'.join((row_template % r).strip() for r in rows)
        return '\n'.join([header, data])
    else:
        return header
738401
def _parse_text_DB(self, s):
        """"""
        dic = self.decode_json_str(s)
        new_dic = {}
        for table_name, (header, rows) in dic.items():
            newl = [{c: ligne[i]
                     for i, c in enumerate(header)} for ligne in rows]
            new_dic[table_name] = newl
        return new_dic
1021242
def get_table_from_csv(filename='ssg_report_aarons_returns.csv', delimiter=',', dos=False):
    """"""
    table = []
    with open(filename, 'rb') as f:
        reader = csv.reader(f, dialect='excel', delimiter=delimiter)
        for row in reader:
            table += [row]
    if not dos:
        return table
    return dos_from_table(table)
999038
def inh(table):
    
    t = []
    for i in table:
        t.append(np.ndarray.tolist(np.arcsinh(i)))
    return t
603543
def as_multi_dict(d):
    ''
    if isinstance(d, bottle.MultiDict):
        return d
    md = bottle.MultiDict()
    for k, v in d.iteritems():
        if isinstance(v, list):
            for x in v:
                md[k] = x
        else:
            md[k] = v
    return md
1203383
def split_sequence(seq, n):
    """"""
    tokens = []
    while seq:
        tokens.append(seq[:n])
        seq = seq[n:]
    return tokens
20996
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'section_titles' in _dict:
            args['section_titles'] = [
                SectionTitles._from_dict(x)
                for x in (_dict.get('section_titles'))
            ]
        if 'leading_sentences' in _dict:
            args['leading_sentences'] = [
                LeadingSentence._from_dict(x)
                for x in (_dict.get('leading_sentences'))
            ]
        return cls(**args)
664423
def split(self, sequence):
    

    major_idx = sequence.idx
    idx2 = 0
    for start, end in zip(major_idx[:-1], major_idx[1:]):
      idx1 = self.idx.index(start, idx2)
      idx2 = self.idx.index(end, idx2)
      seq = Sequence(self.text[start:end])
      seq.idx = [x-start for x in self.idx[idx1:idx2]]
      yield seq