From headerfield object, this generates a full header as a list, ready
    to write to a TSV file
    E.g:
    headerfield = {precusroquant: {HEADER_AREA: OD([(set1, set1_HEAD), (set2,
    set2_HEAD), etc])}}
324744
def generate_general_header(headerfields, fieldtypes, firstfield, oldheader,
                            group_by_field):
    """"""
    if not oldheader:
        header = [firstfield]
    else:
        header = [firstfield] + oldheader[1:]
    poolfields = OrderedDict()
    poolfields[None] = []  # Have non-pool/set columns come before pool-columns
    if group_by_field:
        header.extend(poolfields[None])
    for fieldtype in fieldtypes:
        try:
            fields = headerfields[fieldtype]
        except KeyError:
            continue
        if type(fields) == list:
            header.extend(fields)
        elif group_by_field:
            pfmatrix = [list(x.values()) for k, x in fields.items()
                        if not HEADER_NO_PSMS_SUFFIX in k]
            header.extend([x for y in transpose(pfmatrix) for x in y])
            if fieldtype == 'isoquant':
                pfmatrix = [list(x.values()) for k, x in fields.items()
                            if HEADER_NO_PSMS_SUFFIX in k]
                header.extend([x for y in transpose(pfmatrix) for x in y])
        else:
            for pool_field in fields.values():
                for pool, field in pool_field.items():
                    try:
                        poolfields[pool].append(field)
                    except KeyError:
                        poolfields[pool] = [field]
    if poolfields and not group_by_field:
        for fields in poolfields.values():
            header.extend(fields)
    return header
1239255
protected void writeObjectHeader(List<Object> list) {
        // action
        list.add("{\"" + getOperation() + "\":{");

        // flag indicating whether a comma needs to be added between fields
        boolean commaMightBeNeeded = false;

        commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.INDEX, indexExtractor), "", commaMightBeNeeded);
        commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TYPE, typeExtractor), "\"_type\":", commaMightBeNeeded);
        commaMightBeNeeded = id(list, commaMightBeNeeded);
        commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.PARENT, parentExtractor), requestParameterNames.parent, commaMightBeNeeded);
        commaMightBeNeeded = addExtractorOrDynamicValueAsFieldWriter(list, getMetadataExtractorOrFallback(Metadata.ROUTING, routingExtractor), requestParameterNames.routing, commaMightBeNeeded);
        commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TTL, ttlExtractor), "\"_ttl\":", commaMightBeNeeded);
        commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TIMESTAMP, timestampExtractor), "\"_timestamp\":", commaMightBeNeeded);

        // version & version_type fields
        Object versionField = getMetadataExtractorOrFallback(Metadata.VERSION, versionExtractor);
        if (versionField != null) {
            if (commaMightBeNeeded) {
                list.add(",");
                commaMightBeNeeded = false;
            }
            commaMightBeNeeded = true;
            list.add(requestParameterNames.version);
            list.add(versionField);

            // version_type - only needed when a version is specified
            Object versionTypeField = getMetadataExtractorOrFallback(Metadata.VERSION_TYPE, versionTypeExtractor);
            if (versionTypeField != null) {
                if (commaMightBeNeeded) {
                    list.add(",");
                    commaMightBeNeeded = false;
                }
                commaMightBeNeeded = true;
                list.add(requestParameterNames.versionType);
                list.add(versionTypeField);
            }
        }

        // useful for update command
        otherHeader(list, commaMightBeNeeded);
        list.add("}}\n");
    }
871731
def headers(self):
        '''  '''
        self.__dict__['headers'] = hdict = HeaderDict()
        hdict.dict = self._headers
        return hdict
518840
def _chk_fields(field_data, field_formatter):
        """"""
        if len(field_data) == len(field_formatter):
            return
        len_dat = len(field_data)
        len_fmt = len(field_formatter)
        msg = [
            "FIELD DATA({d}) != FORMATTER({f})".format(d=len_dat, f=len_fmt),
            "DAT({N}): {D}".format(N=len_dat, D=field_data),
            "FMT({N}): {F}".format(N=len_fmt, F=field_formatter)]
        raise Exception("\n".join(msg))
431596
def generate_headerfields(headertypes, allfield_defs, poolnames, db=False, genecentric=False):
    """"""
    hfields = {}
    for fieldtype in headertypes:
        if fieldtype == 'isoquant':
            continue
        elif fieldtype == 'proteindata':
            hfield_definitions = allfield_defs[fieldtype](poolnames, genecentric)
        else:
            hfield_definitions = allfield_defs[fieldtype](poolnames)
        hfields[fieldtype] = OrderedDict()
        for fieldname, poolnames in hfield_definitions.items():
            hfields[fieldtype][fieldname] = get_header_field(fieldname,
                                                             poolnames)
    if 'isoquant' in headertypes:
        hfield_definitions = allfield_defs['isoquant'](db, poolnames)
        hfields['isoquant'] = OrderedDict()
        for poolname in poolnames:
            for fieldname in hfield_definitions:
                hfields['isoquant'][fieldname] = get_header_field(
                    fieldname, poolnames)
    return hfields
729420
def render_headers(self):
        
        lines = []

        sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
        for sort_key in sort_keys:
            if self.headers.get(sort_key, False):
                lines.append('%s: %s' % (sort_key, self.headers[sort_key]))

        for header_name, header_value in self.headers.items():
            if header_name not in sort_keys:
                if header_value:
                    lines.append('%s: %s' % (header_name, header_value))

        lines.append('\r\n')
        return '\r\n'.join(lines)
502123
def get_header(results):
    ''''''
    ret = ['name', ]
    values = next(iter(results.values()))
    for k, v in values.items():
        if isinstance(v, dict):
            for metric in v.keys():
                ret.append('%s:%s' % (k, metric))
        else:
            ret.append(k)
    return ret
1139901
def save_tsv_header(p, vs):
    ''
    trdict = tsv_trdict(vs)
    delim = options.delimiter

    with p.open_text(mode='w') as fp:
        colhdr = delim.join(col.name.translate(trdict) for col in vs.visibleCols) + '\n'
        if colhdr.strip():  # is anything but whitespace
            fp.write(colhdr)
159948
def prepare(cls, value, length=0, position=0, is_last_data=True):
        
        hstruct = WriteLobHeader.header_struct
        lob_option_dataincluded = WriteLobHeader.LOB_OPTION_DATAINCLUDED if length > 0 else 0
        lob_option_lastdata = WriteLobHeader.LOB_OPTION_LASTDATA if is_last_data else 0
        options = lob_option_dataincluded | lob_option_lastdata
        pfield = hstruct.pack(cls.type_code, options, length, position)
        return pfield
114680
def prepend_field(self, field_name, list_value):
    """"""
    return self._single_list_field_operation(field_name, list_value, prepend=True)
1259769
def header(args):
    
    from jcvi.formats.base import DictFile

    p = OptionParser(header.__doc__)
    p.add_option("--prefix", default="",
                 help="Prepend text to line number [default: %default]")
    p.add_option("--ids", help="Write ids to file [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    mstmap, conversion_table = args
    data = MSTMap(mstmap)
    hd = data.header
    conversion = DictFile(conversion_table)
    newhd = [opts.prefix + conversion.get(x, x) for x in hd]

    print("\t".join(hd))
    print("--->")
    print("\t".join(newhd))

    ids = opts.ids
    if ids:
        fw = open(ids, "w")
        print("\n".join(newhd), file=fw)
        fw.close()
1264768
def get_prottable_headerfields(headertypes, lookup=False, poolnames=False, genecentric=False):
    """"""
    field_defs = {'isoquant': get_isoquant_fields,
                  'precursorquant': get_precursorquant_fields,
                  'probability': get_probability_fields,
                  'proteindata': get_proteininfo_fields,
                  'proteinfdr': get_proteinfdr_fields,
                  'proteinpep': get_proteinpep_fields,
                  'bestpepscore': get_bestpeptide_fields,
                  }
    return generate_headerfields(headertypes, field_defs, poolnames, lookup, genecentric)
339844
def generate(self):
    """"""
    header = ' '.join('=' * self.width[i] for i in range(self.w))
    lines = [
        ' '.join(row[i].ljust(self.width[i]) for i in range(self.w))
        for row in self.rows]
    return [header] + lines + [header]
577334
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
    
    if not dictlist:
        return ""
    fieldnames = dictlist[0].keys()
    tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n"
    for d in dictlist:
        tsv += "\t".join([tsv_escape(v) for v in d.values()]) + "\n"
    return tsv
1198645
def _generate_list_heading(self):
        

        local = self.parser.find('body').first_result()
        id_container_heading_before = (
            AccessibleNavigationImplementation.ID_CONTAINER_HEADING_BEFORE
        )
        id_container_heading_after = (
            AccessibleNavigationImplementation.ID_CONTAINER_HEADING_AFTER
        )
        if local is not None:
            container_before = self.parser.find(
                '#'
                + id_container_heading_before
            ).first_result()
            if (container_before is None) and (self.elements_heading_before):
                container_before = self.parser.create_element('div')
                container_before.set_attribute(
                    'id',
                    id_container_heading_before
                )

                text_container_before = self.parser.create_element('span')
                text_container_before.set_attribute(
                    'class',
                    AccessibleNavigationImplementation.CLASS_TEXT_HEADING
                )
                text_container_before.append_text(self.elements_heading_before)

                container_before.append_element(text_container_before)
                local.prepend_element(container_before)
            if container_before is not None:
                self.list_heading_before = self.parser.find(
                    container_before
                ).find_children('ol').first_result()
                if self.list_heading_before is None:
                    self.list_heading_before = self.parser.create_element('ol')
                    container_before.append_element(self.list_heading_before)

            container_after = self.parser.find(
                '#'
                + id_container_heading_after
            ).first_result()
            if (container_after is None) and (self.elements_heading_after):
                container_after = self.parser.create_element('div')
                container_after.set_attribute('id', id_container_heading_after)

                text_container_after = self.parser.create_element('span')
                text_container_after.set_attribute(
                    'class',
                    AccessibleNavigationImplementation.CLASS_TEXT_HEADING
                )
                text_container_after.append_text(self.elements_heading_after)

                container_after.append_element(text_container_after)
                local.append_element(container_after)
            if container_after is not None:
                self.list_heading_after = self.parser.find(
                    container_after
                ).find_children('ol').first_result()
                if self.list_heading_after is None:
                    self.list_heading_after = self.parser.create_element('ol')
                    container_after.append_element(self.list_heading_after)
        self.list_heading_added = True
952635
def printtable(h, header):
    """"""
    hk = header_fields(h)
    if (header):
        printheader()
    writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore')
    writer.writerow(h)
420776
def _tabulate(rows, headers, spacing=5):
    """"""
    if len(rows) == 0:
        return "None\n"
    assert len(rows[0]) == len(headers)
    count = len(rows[0])
    widths = [0 for _ in range(count)]
    rows = [headers] + rows

    for row in rows:
        for index, field in enumerate(row):
            if len(str(field)) > widths[index]:
                widths[index] = len(str(field))

    output = ""
    for row in rows:
        for index, field in enumerate(row):
            field = str(field)
            output += field + (widths[index] - len(field) + spacing) * " "
        output += "\n"
    return output