Check parameters passed to avoid errors and help debug.

        :param dict response: search request parameters
182746
def check_request_parameters(self, parameters: dict = dict):
        
        # -- SEMANTIC QUERY ---------------------------------------------------
        li_args = parameters.get("q").split()
        logging.debug(li_args)

        # Unicity
        li_filters = [i.split(":")[0] for i in li_args]
        filters_count = Counter(li_filters)
        li_filters_must_be_unique = ("coordinate-system", "format", "owner", "type")
        for i in filters_count:
            if i in li_filters_must_be_unique and filters_count.get(i) > 1:
                raise ValueError(
                    "This query filter must be unique: {}"
                    " and it occured {} times.".format(i, filters_count.get(i))
                )

        # dict
        dico_query = FILTER_KEYS.copy()
        for i in li_args:
            if i.startswith("action"):
                dico_query["action"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("catalog"):
                dico_query["catalog"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("contact") and i.split(":")[1] == "group":
                dico_query["contact:group"].append(i.split(":")[1:][1])
                continue
            elif i.startswith("contact"):
                dico_query["contact:isogeo"].append(i.split(":", 1)[1])
                continue
            elif i.startswith("coordinate-system"):
                dico_query["coordinate-system"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("data-source"):
                dico_query["data-source"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("format"):
                dico_query["format"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("has-no"):
                dico_query["has-no"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("keyword:isogeo"):
                dico_query["keyword:isogeo"].append(i.split(":")[1:][1])
                continue
            elif i.startswith("keyword:inspire-theme"):
                dico_query["keyword:inspire-theme"].append(i.split(":")[1:][1])
                continue
            elif i.startswith("license:isogeo"):
                dico_query["license:isogeo"].append(i.split(":")[1:][1:])
                continue
            elif i.startswith("license"):
                dico_query["license:group"].append(i.split(":", 1)[1:][0:])
                continue
            elif i.startswith("owner"):
                dico_query["owner"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("provider"):
                dico_query["provider"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("share"):
                dico_query["share"].append(i.split(":")[1:][0])
                continue
            elif i.startswith("type"):
                dico_query["type"].append(i.split(":")[1:][0])
                continue
            else:
                # logging.debug(i.split(":")[1], i.split(":")[1].isdigit())
                dico_query["text"].append(i)
                continue

        # Values
        dico_filters = {i.split(":")[0]: i.split(":")[1:] for i in li_args}
        if dico_filters.get("type", ("dataset",))[0].lower() not in FILTER_TYPES:
            raise ValueError(
                "type value must be one of: {}".format(" | ".join(FILTER_TYPES))
            )
        elif dico_filters.get("action", ("download",))[0].lower() not in FILTER_ACTIONS:
            raise ValueError(
                "action value must be one of: {}".format(" | ".join(FILTER_ACTIONS))
            )
        elif (
            dico_filters.get("provider", ("manual",))[0].lower() not in FILTER_PROVIDERS
        ):
            raise ValueError(
                "provider value must be one of: {}".format(" | ".join(FILTER_PROVIDERS))
            )
        else:
            logging.debug(dico_filters)

        # -- GEOGRAPHIC -------------------------------------------------------
        in_box = parameters.get("box")
        in_geo = parameters.get("geo")
        # geometric relation
        in_rel = parameters.get("rel")
        if in_rel and in_box is None and in_geo is None:
            raise ValueError("'rel' should'nt be used without box or geo.")
        elif in_rel not in GEORELATIONS and in_rel is not None:
            raise ValueError(
                "{} is not a correct value for 'georel'."
                " Must be one of: {}.".format(in_rel, " | ".join(GEORELATIONS))
            )
860521
def _handle_http_errors(response):
    
    code = response.status_code
    if 200 <= code < 400:
        return response
    elif code in (403, 404):
        raise {403: _ObjectPermissionError,
               404: _ObjectNotFoundError}[code](response.reason)
    response.raise_for_status()
568208
def _check_error(response):
        """"""
        if (not response.ok) or (response.status_code != 200):
            raise Exception(
                response.json()['error'] + ': ' +
                response.json()['error_description']
            )
1223422
def check_for_additional_actions(self, url_params: dict,
                                     html: str,
                                     login_data: dict) -> None:
        
        action_response = ''
        if 'sid' in url_params:
            action_response = self.handle_captcha(url_params, html, login_data)
        elif 'authcheck' in url_params:
            action_response = self.handle_two_factor_check(html)
        elif 'security_check' in url_params:
            action_response = self.handle_phone_number_check(html)
        if action_response:
            check_page_for_warnings(action_response.text)
967885
def result_or_error(response):
    
    data = response.json()
    result = data.get('result')
    if result is not None:
        return result
    raise exceptions.ApiError(response, data)
1262767
def read_validate_params(self, request):
        
        self.client = self.client_authenticator.by_identifier(request)

        response_type = request.get_param("response_type")

        if self.client.response_type_supported(response_type) is False:
            raise OAuthInvalidError(error="unauthorized_client")

        self.state = request.get_param("state")

        self.scope_handler.parse(request, "query")

        return True
700586
def _validate_response(response):
        
        try:
            response.raise_for_status()
        except requests.RequestException:
            raise RequestException(
                code=response.status_code,
                url=response.url,
                description=response.text)
        else:
            return response
1325410
def check(func):
    
    def iCheck(request, *args, **kwargs):
        if not request.method == "POST":
            return HttpResponseBadRequest("Must be POST request.")
        follow = func(request, *args, **kwargs)
        if request.is_ajax():
            return HttpResponse('ok')
        try:
            if 'next' in request.GET:
                return HttpResponseRedirect(request.GET.get('next'))
            if 'next' in request.POST:
                return HttpResponseRedirect(request.POST.get('next'))
            return HttpResponseRedirect(follow.target.get_absolute_url())
        except (AttributeError, TypeError):
            if 'HTTP_REFERER' in request.META:
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            if follow:
                return HttpResponseServerError('"%s" object of type ``%s`` has no method ``get_absolute_url()``.' % (
                    unicode(follow.target), follow.target.__class__))
            return HttpResponseServerError('No follow object and `next` parameter found.')
    return iCheck
1222961
def check_response(self, resp):
        

        # For successful API call, response code will be 200 (OK)
        if resp.ok:
            json = resp.json()
            self.response = ResponseHolder()
            self.response.response = json

            # Check the code
            if 'status' not in json:
                raise InvalidResponse('No status field')

            self.response.status = self.field_to_long(json['status'])
            if self.response.status != EBConsts.STATUS_OK:
                txt_status = self.get_text_status(json)
                raise InvalidStatus('Status is %s (%04X)'
                                    % (txt_status if txt_status is not None else "", self.response.status))

            if self.response_checker is not None:
                self.response_checker(self.response)

            return self.response

        else:
            # If response code is not ok (200), print the resulting http error code with description
            resp.raise_for_status()
        pass
912295
def _handle_response(self, response):
        
        if response.status_code == requests.codes.ok or response.status_code == requests.codes.created:
            try:
                return response.json()
            except ValueError:
                return response
        else:
            return self._handle_failed_response(response)
470590
def parse_response(self, response):
        
        status = response.status_code
        if response.ok:
            data = response.json()
            return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
        else:
            try:
                errors = response.json()
            except ValueError:
                errors = response.content
            return HttpResponse(ok=response.ok, status=status, errors=errors, data=None)
59166
function checkResponseForErrors(res) {
    let { statusCode, body, headers } = res;

    if (statusCode >= 400) {
        return { error: true, body };
    }

    // API key is invalid
    if ((body.error) && (body.error === 'Unauthorized')) {
        return { error: true, body };
    }

    // response is not json
    if (headers['content-type'] !== 'application/json; charset=utf-8') {
        return { error: true, body: { error: 'JSON expected' } };
    }

    return { error: false, body };
}
437402
def check_response(self, response):
        
        status = response.get('status', None)
        if status is None or status == ErrorCode.SUCCESS:
            return
        value = None
        message = response.get("message", "")
        screen = response.get("screen", "")
        stacktrace = None
        if isinstance(status, int):
            value_json = response.get('value', None)
            if value_json and isinstance(value_json, basestring):
                import json
                try:
                    value = json.loads(value_json)
                    if len(value.keys()) == 1:
                        value = value['value']
                    status = value.get('error', None)
                    if status is None:
                        status = value["status"]
                        message = value["value"]
                        if not isinstance(message, basestring):
                            value = message
                            message = message.get('message')
                    else:
                        message = value.get('message', None)
                except ValueError:
                    pass

        if status in ErrorCode.NO_SUCH_ELEMENT:
            exception_class = NoSuchElementException
        elif status in ErrorCode.NO_SUCH_FRAME:
            exception_class = NoSuchFrameException
        elif status in ErrorCode.NO_SUCH_WINDOW:
            exception_class = NoSuchWindowException
        elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
            exception_class = StaleElementReferenceException
        elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
            exception_class = ElementNotVisibleException
        elif status in ErrorCode.INVALID_ELEMENT_STATE:
            exception_class = InvalidElementStateException
        elif status in ErrorCode.INVALID_SELECTOR \
                or status in ErrorCode.INVALID_XPATH_SELECTOR \
                or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
            exception_class = InvalidSelectorException
        elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
            exception_class = ElementNotSelectableException
        elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
            exception_class = ElementNotInteractableException
        elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
            exception_class = InvalidCookieDomainException
        elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
            exception_class = UnableToSetCookieException
        elif status in ErrorCode.TIMEOUT:
            exception_class = TimeoutException
        elif status in ErrorCode.SCRIPT_TIMEOUT:
            exception_class = TimeoutException
        elif status in ErrorCode.UNKNOWN_ERROR:
            exception_class = WebDriverException
        elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
            exception_class = UnexpectedAlertPresentException
        elif status in ErrorCode.NO_ALERT_OPEN:
            exception_class = NoAlertPresentException
        elif status in ErrorCode.IME_NOT_AVAILABLE:
            exception_class = ImeNotAvailableException
        elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
            exception_class = ImeActivationFailedException
        elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
            exception_class = MoveTargetOutOfBoundsException
        elif status in ErrorCode.JAVASCRIPT_ERROR:
            exception_class = JavascriptException
        elif status in ErrorCode.SESSION_NOT_CREATED:
            exception_class = SessionNotCreatedException
        elif status in ErrorCode.INVALID_ARGUMENT:
            exception_class = InvalidArgumentException
        elif status in ErrorCode.NO_SUCH_COOKIE:
            exception_class = NoSuchCookieException
        elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
            exception_class = ScreenshotException
        elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
            exception_class = ElementClickInterceptedException
        elif status in ErrorCode.INSECURE_CERTIFICATE:
            exception_class = InsecureCertificateException
        elif status in ErrorCode.INVALID_COORDINATES:
            exception_class = InvalidCoordinatesException
        elif status in ErrorCode.INVALID_SESSION_ID:
            exception_class = InvalidSessionIdException
        elif status in ErrorCode.UNKNOWN_METHOD:
            exception_class = UnknownMethodException
        else:
            exception_class = WebDriverException
        if value == '' or value is None:
            value = response['value']
        if isinstance(value, basestring):
            raise exception_class(value)
        if message == "" and 'message' in value:
            message = value['message']

        screen = None
        if 'screen' in value:
            screen = value['screen']

        stacktrace = None
        if 'stackTrace' in value and value['stackTrace']:
            stacktrace = []
            try:
                for frame in value['stackTrace']:
                    line = self._value_or_default(frame, 'lineNumber', '')
                    file = self._value_or_default(frame, 'fileName', '<anonymous>')
                    if line:
                        file = "%s:%s" % (file, line)
                    meth = self._value_or_default(frame, 'methodName', '<anonymous>')
                    if 'className' in frame:
                        meth = "%s.%s" % (frame['className'], meth)
                    msg = "    at %s (%s)"
                    msg = msg % (meth, file)
                    stacktrace.append(msg)
            except TypeError:
                pass
        if exception_class == UnexpectedAlertPresentException:
            alert_text = None
            if 'data' in value:
                alert_text = value['data'].get('text')
            elif 'alert' in value:
                alert_text = value['alert'].get('text')
            raise exception_class(message, screen, stacktrace, alert_text)
        raise exception_class(message, screen, stacktrace)
1251718
def checkResponse(request):
        '''
        
        '''

        # Check the status code of the returned request
        if str(request.status_code)[0] not in ['2', '3']:
            w = str(request.text).split('\\r')[0][2:]
            raise InvalidRequest(w)
        return
1111031
public void assertCorrectResonse(JSONObject response) throws JSONException {
		Integer lastHTTPResponseCode = getLastHTTPResponseCode();
		if(lastHTTPResponseCode != null) {
			//if a response code is set, check it. Selenium requests do not let you query this which is why we can't check this in case of a selenium API call
			assertEquals("The https response code should be 200 (OK)", new Integer(HttpURLConnection.HTTP_OK), lastHTTPResponseCode);
		}
		assertNotNull("The request should result in a response", response);	
	}
1147892
def _extract_params(request_dict, param_list, param_fallback=False):
        '''  '''

        if not param_list or not request_dict:
            return dict()

        query = dict()
        for param in param_list:
            # Retrieve all items in the form of {param: value} and
            # convert {param__key: value} into {param: {key: value}}
            for query_key, query_value in request_dict.items():
                if param == query_key:
                    query[param] = query_value
                else:
                    query_key_parts = query_key.split('__', 1)
                    if param == query_key_parts[0]:
                        query[param] = {query_key_parts[1]: query_value}

        # Convert special string "__null__" into Python None
        nullifier = lambda d: {k:(nullifier(v) if isinstance(v, dict) else # pylint: disable=used-before-assignment
                                  (None if v == '__null__' else v)) for k, v in d.items()}

        # When fallback is enabled and no parameter matched, assume query refers to first parameter
        if param_fallback and all([param_key not in query.keys() for param_key in param_list]):
            query = {param_list[0]: dict(request_dict)}

        # Return a dictionary with only the requested parameters
        return {k:v for k, v in nullifier(query).items() if k in param_list}
982178
def query_params(*es_query_params):
    

    def _wrapper(func):
        @wraps(func)
        def _wrapped(*args, **kwargs):
            params = {}
            if "params" in kwargs:
                params = kwargs.pop("params").copy()
            for p in es_query_params + GLOBAL_PARAMS:
                if p in kwargs:
                    v = kwargs.pop(p)
                    if v is not None:
                        params[p] = _escape(v)

            # don't treat ignore and request_timeout as other params to avoid escaping
            for p in ("ignore", "request_timeout"):
                if p in kwargs:
                    params[p] = kwargs.pop(p)
            return func(*args, params=params, **kwargs)

        return _wrapped

    return _wrapper