Convert useful headers to a normalized type and return in a new dict

    Only processes content-type, content-length, etag, and last-modified
    :param headers:
    :return:
349154
def normalize_headers(headers):
    
    for (k, v) in headers.items():
        headers.pop(k)
        headers[k.lower()] = v

    result = {}
    if 'content-length' in headers:
        result['content-length'] = headers['content-length']
    elif 'contentlength' in headers:
        result['content-length'] = headers['contentlength']

    if 'content-type' in headers:
        result['content-type'] = headers['content-type']
    elif 'contenttype' in headers:
        result['content-type'] = headers['contenttype']

    if 'last-modified' in headers:
        result['last-modified'] = headers['last-modified']
    elif 'lastmodified' in headers:
        result['last-modified'] = headers['lastmodified']
    else:
        result['last-modified'] = datetime.datetime.utcnow().strftime(RFC1123_TIME_FORMAT)

    # Normalize date
    if isinstance(result['last-modified'], datetime.datetime):
        result['last-modified'] = result['last-modified'].strftime(RFC1123_TIME_FORMAT)

    if 'ETag' in headers:
        result['etag'] = headers['etag'].strip('"')
    elif 'etag' in headers:
        result['etag'] = headers['etag'].strip('"')

    return result
949250
function(headers, params) {
        var newHeaders = {};
        for (var header in headers)
            newHeaders[header] = headers[header];
        for (var param in params) {
            var re = new RegExp(":"+ param);
            for (var header in newHeaders) {
                if (newHeaders[header].search(re) != -1) {
                    newHeaders[header] = newHeaders[header].replace(re, params[param]);
                }
            }
        }
        return newHeaders;
    }
242234
def http_headers
      req_headers = self.reject {|k,v| !k.start_with? "HTTP_" }
      normalized = req_headers.map do |key, value|
        new_key = key.sub("HTTP_",'').split('_').map(&:capitalize).join('-')
        [new_key, value]
      end
      Hash[normalized]
    end
667122
def build_headers(self):
        '''
        
        '''
        if not 'Content-Type' in self.headers:
            content_type = self.content_type
            if self.encoding != DEFAULT_ENCODING:
                content_type += '; charset=%s' % self.encoding
            self.headers['Content-Type'] = content_type

        headers = list(self.headers.items())
        # Append cookies
        headers += [
            ('Set-Cookie', cookie.OutputString())
            for cookie in self.cookies.values()
        ]
        return headers
821760
def _unpack_headers(self, headers):
        
        return dict((k,v[0]) for (k,v) in headers.getAllRawHeaders())
313223
function Headers (size, type, ttl, enc) {
  if (!(this instanceof Headers)) return new Headers(size, type, ttl, enc)
  if (size) this['Content-Length'] = size
  if (type) this['Content-Type'] = type
  if (!isNaN(ttl)) this['Cache-Control'] = 'max-age=' + ttl
  if (enc) this['Content-Encoding'] = enc
}
166653
function parseHeaders(headers) {
  var parsed = {}, key, val, i;

  if (!headers) return parsed;

  forEach(headers.split('\n'), function(line) {
    i = line.indexOf(':');
    key = lowercase(trim(line.substr(0, i)));
    val = trim(line.substr(i + 1));

    if (key) {
      if (parsed[key]) {
        parsed[key] += ', ' + val;
      } else {
        parsed[key] = val;
      }
    }
  });

  return parsed;
}
412694
function Headers(headers) {
	            var _this = this;
	            /** @internal header names are lower case */
	            this._headers = new Map();
	            /** @internal map lower case names to actual names */
	            this._normalizedNames = new Map();
	            if (!headers) {
	                return;
	            }
	            if (headers instanceof Headers) {
	                headers._headers.forEach(function (values, name) {
	                    values.forEach(function (value) { return _this.append(name, value); });
	                });
	                return;
	            }
	            Object.keys(headers).forEach(function (name) {
	                var values = Array.isArray(headers[name]) ? headers[name] : [headers[name]];
	                _this.delete(name);
	                values.forEach(function (value) { return _this.append(name, value); });
	            });
	        }
712227
def select_header_content_type(self, content_types):
        
        if not content_types:
            return 'application/json'

        content_types = [x.lower() for x in content_types]

        if 'application/json' in content_types or '*/*' in content_types:
            return 'application/json'
        else:
            return content_types[0]
94181
function parseHttpHeaders(headers) {
    var meta = {};
    
    for (var headerName in headers) {
        var headerValue = headers[headerName];
        
        if (headerName=="x-ratelimit-limit") {
            meta.rateLimit = headerValue;
        } else if (headerName=="x-ratelimit-remaining") {
            meta.rateLimitRemaining = headerValue;
        } else if (headerName=="x-ratelimit-reset") {
            meta.rateLimitReset = headerValue;
        } else if (headerName=="link") {
            var regexp = /<(.+)>; rel=(.+),?/g;
            var match;
            do {
                match = regexp.exec(headerValue);
                if (match) {
                    var url = match[1];
                    var rel = match[2];
                    
                    var regexp2 = /[\?|&]page=(\d+)/;
                    var match2 = regexp2.exec(url);
                    if (match2) {
                        var page = match2[1];
                        if (rel=='prev') {
                            meta.prevPage = page;
                        } else if (rel=='next') {
                            meta.nextPage = page;
                        } else if (rel=='last') {
                            meta.lastPage = page;
                        }
                    }
                }
            } while (match);
        } 
    }
    
    return meta;
}
514562
def canonical_headers(self):
        
        canonical_headers = ''

        for header in HEADERS:
            if header not in self.message:
                continue

            for value in self.message.get_all(header):
                canonical_value = self.canonical_header_value(header, value)
                if re.search(r'\S', canonical_value):
                    canonical_headers += '{}: {}\n'.format(
                        header, canonical_value)

        canonical_headers = canonical_headers.encode('utf-8')
        if len(canonical_headers) > 50:
            return canonical_headers

        # At this point we should have at absolute minimum 3 or 4 headers, e.g.
        # From/To/Date/Subject; if not, something went badly wrong.

        if len(canonical_headers) == 0:
            raise InsufficientHeadersError("No canonical headers found")

        err = textwrap.dedent("""\
            Not enough data from canonical headers to compute reliable hash!
            Headers:
            --------- 8< --------- 8< --------- 8< --------- 8< ---------
            {}
            --------- 8< --------- 8< --------- 8< --------- 8< ---------""")
        raise InsufficientHeadersError(err.format(canonical_headers))
118343
def set_headers(self) -> None:
        
        self.set_header("Accept-Ranges", "bytes")
        self.set_etag_header()

        if self.modified is not None:
            self.set_header("Last-Modified", self.modified)

        content_type = self.get_content_type()
        if content_type:
            self.set_header("Content-Type", content_type)

        cache_time = self.get_cache_time(self.path, self.modified, content_type)
        if cache_time > 0:
            self.set_header(
                "Expires",
                datetime.datetime.utcnow() + datetime.timedelta(seconds=cache_time),
            )
            self.set_header("Cache-Control", "max-age=" + str(cache_time))

        self.set_extra_headers(self.path)
871731
def headers(self):
        '''  '''
        self.__dict__['headers'] = hdict = HeaderDict()
        hdict.dict = self._headers
        return hdict
872518
def _characterize_header(self, header, hgroups):
        
        out = []
        for h in [header[g[0]] for g in hgroups]:
            this_ctype = None
            for ctype, names in self._col_types.items():
                if h.startswith(names):
                    this_ctype = ctype
                    break
            out.append(this_ctype)
        return out
440201
def header(cls, name, type_=Type.String, description=None, default=None, required=None, **options):
        
        return cls(name, In.Header, type_, None, description,
                   required=required, default=default,
                   **options)
978930
function parseHeaders(headers) {
  var parsed = createMap(), i;

  function fillInParsed(key, val) {
    if (key) {
      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
    }
  }

  if (isString(headers)) {
    forEach(headers.split('\n'), function(line) {
      i = line.indexOf(':');
      fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
    });
  } else if (isObject(headers)) {
    forEach(headers, function(headerVal, headerKey) {
      fillInParsed(lowercase(headerKey), trim(headerVal));
    });
  }

  return parsed;
}
61687
def extract_headers(headers):
    """"""
    sorted_headers = {}
    matches = re.findall(r'(.*):\s(.*)', headers)
    for match in matches:
        header = match[0]
        value = match[1]
        try:
            if value[-1] == ',':
                value = value[:-1]
            sorted_headers[header] = value
        except IndexError:
            pass
    return sorted_headers