Filter handlers that provide an acceptable mime-type.

    Finds the best match among handlers given an Accept header, and returns
    those handlers that provide the matching mime-type.
188360
def negotiate_accept(accept, handlers):
    
    provided = [h.provides for h in handlers]
    if None in provided:
        # Not all handlers are annotated - disable content-negotiation
        # for Accept.
        # TODO: We could implement an "optimistic mode": If a fully qualified
        # mime-type was requested and we have a specific handler that provides
        # it, choose that handler instead of the default handler (depending on
        # 'q' value).
        return [h for h in handlers if h.provides is None]
    else:
        # All handlers are annotated with the mime-type they
        # provide: find the best match.
        #
        # mimeparse.best_match expects the supported mime-types to be sorted
        # in order of increasing desirability. By default, we use the order in
        # which handlers were added (earlier means better).
        # TODO: add "priority" parameter for user-defined priorities.
        best_match = mimeparse.best_match(reversed(provided), accept)
        return [h for h in handlers if h.provides == best_match]
694267
@Override
    public boolean accepts(String mimeType) {
        String contentType = request.headers().get(HeaderNames.ACCEPT);
        if (contentType == null) {
            contentType = MimeTypes.HTML;
        }
        // For performance reason, we first try a full match:
        if (contentType.contains(mimeType)) {
            return true;
        }
        // Else check the media types:
        MediaType input = MediaType.parse(mimeType);
        for (MediaType type : mediaTypes()) {
            if (input.is(type)) {
                return true;
            }
        }
        return false;
    }
1153300
def select_header_accept(accepts)
      return nil if accepts.nil? || accepts.empty?
      # use JSON when present, otherwise use all of the provided
      json_accept = accepts.find { |s| json_mime?(s) }
      json_accept || accepts.join(',')
    end
730293
def recv_match(self, condition=None, type=None, blocking=False, timeout=None):
        ''''''
        if type is not None and not isinstance(type, list):
            type = [type]
        start_time = time.time()
        while True:
            if timeout is not None:
                now = time.time()
                if now < start_time:
                    start_time = now # If an external process rolls back system time, we should not spin forever.
                if start_time + timeout < time.time():
                    return None
            m = self.recv_msg()
            if m is None:
                if blocking:
                    for hook in self.idle_hooks:
                        hook(self)
                    if timeout is None:
                        self.select(0.05)
                    else:
                        self.select(timeout/2)
                    continue
                return None
            if type is not None and not m.get_type() in type:
                continue
            if not evaluate_condition(condition, self.messages):
                continue
            return m
700374
def recv_match(self, condition=None, type=None, blocking=False):
        ''''''
        if type is not None and not isinstance(type, list):
            type = [type]
        while True:
            m = self.recv_msg()
            if m is None:
                return None
            if type is not None and not m.get_type() in type:
                continue
            if not mavutil.evaluate_condition(condition, self.messages):
                continue
            return m
1062283
private function getNotAcceptableHttpException(string $accept, array $mimeTypes = null): NotAcceptableHttpException
    {
        if (null === $mimeTypes) {
            $mimeTypes = array_keys($this->mimeTypes);
        }

        return new NotAcceptableHttpException(sprintf(
            'Requested format "%s" is not supported. Supported MIME types are "%s".',
            $accept,
            implode('", "', $mimeTypes)
        ));
    }
239320
def handler_for(rjr_method)
    # look for exact match first
    handler = @handlers.find { |k,v| k == rjr_method }

    # if not found try to match regex's
    handler ||= @handlers.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) }

    handler.nil? ? nil : handler.last
  end
1333943
async def accept(
            self,
            headers: Optional[Union[dict, CIMultiDict, Headers]] = None,
            subprotocol: Optional[str] = None,
    ) -> None:
        
        if headers is None:
            headers_ = Headers()
        else:
            headers_ = Headers(headers)
        await self._accept(headers_, subprotocol)
384995
def select_renderer(self, request, renderers):
        
        if not len(request.accept_mimetypes):
            return renderers[0], renderers[0].mimetype

        for mimetype, quality in request.accept_mimetypes:
            accept_mimetype = MimeType.parse(mimetype)
            for renderer in renderers:
                if accept_mimetype.match(renderer.mimetype):
                    return renderer, renderer.mimetype.replace(params=accept_mimetype.params)

        return None, None
556109
public function findMatch(AcceptHeader $acceptedMimeTypes)
    {
        if (count($this->mimeTypes) === 0) {
            return 'text/html';
        }

        if (count($acceptedMimeTypes) === 0) {
            reset($this->mimeTypes);
            return current($this->mimeTypes);
        }

        return $acceptedMimeTypes->findMatchWithGreatestPriority($this->mimeTypes);
    }
231661
def requested_version
      accept_headers = request.headers["HTTP_ACCEPT"]
      return nil if accept_headers.nil?
      parts = accept_headers.split(",").map(&:strip)
      requested = parts.map{|part| part.match(/version=(\d+)/)[1] if part.match(/version=\d+/)}.detect{|i| !i.nil?}
      requested.to_i unless requested.nil?
    end
511522
def best_match(requested, allowed):
    

    requested = [parse_ctype(ctype) for ctype in quoted_split(requested, ',')]

    best_q = -1
    best_ctype = ''
    best_params = {}
    best_match = '*/*'

    # Walk the list of content types
    for ctype in allowed:
        # Compare to the accept list
        for ctype_mask, params in requested:
            try:
                q = float(params.get('q', 1.0))
            except ValueError:
                # Bad quality value
                continue

            if q < best_q:
                # Not any better
                continue
            elif best_q == q:
                # Base on the best match
                if best_match.count('*') <= ctype_mask.count('*'):
                    continue

            # OK, see if we have a match
            if _match_mask(ctype_mask, ctype):
                best_q = q
                best_ctype = ctype
                best_params = params
                best_match = ctype_mask

    # Return the best match
    return best_ctype, best_params
133709
def accept(handlers, default=None, error='The requested content type does not match any of those allowed'):
    
    def output_type(data, request, response):
        accept = request.accept
        if accept in ('', '*', '/'):
            handler = default or handlers and next(iter(handlers.values()))
        else:
            handler = default
            accepted = [accept_quality(accept_type) for accept_type in accept.split(',')]
            accepted.sort(key=itemgetter(0))
            for quality, accepted_content_type in reversed(accepted):
                if accepted_content_type in handlers:
                    handler = handlers[accepted_content_type]
                    break

        if not handler:
            raise falcon.HTTPNotAcceptable(error)

        response.content_type = handler.content_type
        return handler(data, request=request, response=response)
    output_type.__doc__ = 'Supports any of the following formats: {0}'.format(', '.join(function.__doc__ for function in
                                                                                        handlers.values()))
    output_type.content_type = ', '.join(handlers.keys())
    return output_type
1300527
def parse_accept_header(header):
    """"""
    result = []
    for match in accept_re.finditer(header):
        quality = match.group(2)
        if not quality:
            quality = 1
        else:
            quality = max(min(float(quality), 1), 0)
        result.append((match.group(1), quality))
    return result
856302
def resolve(self, event_handler, *custom_filters, **full_config
                ) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
        
        filters_set = []
        filters_set.extend(self._resolve_registered(event_handler,
                                                    {k: v for k, v in full_config.items() if v is not None}))
        if custom_filters:
            filters_set.extend(custom_filters)

        return filters_set
471442
function getTypesFromHandlers(handlers) {
  var types = keys(handlers);
  types = types.map(k => k.replace(/_.*/, ''));
  if (types.indexOf('end') !== -1) {
    types.push('add', 'update', 'delete');
  }
  return types;
}
978366
def select_header_accept(accepts)
      if accepts.empty?
        return
      elsif accepts.any?{ |s| s.casecmp('application/json') == 0 }
        'application/json' # look for json data by default
      else
        accepts.join(',')
      end
    end