Return stubbed response from external system.
420011
protected Response getStubbedResponse(Object requestObject) {
        // compatibility
        String resp = getStubResponse(externalRequestToString(requestObject));
        if (resp != null) {
            Response oldStubbed = new Response();
            oldStubbed.setObject(resp);
            oldStubbed.setContent(externalResponseToString(resp));
            return oldStubbed;
        }

        List<SimulationResponse> responses = new ArrayList<>();
        for (Attribute attr : this.getAttributes()) {
            if (attr.getAttributeName().startsWith(WorkAttributeConstant.SIMULATION_RESPONSE)) {
                SimulationResponse r = new SimulationResponse(attr.getAttributeValue());
                responses.add(r);
            }
        }
        String unfilteredResponse = null;
        String returnCode = null;
        if (responses.size() == 0) {
            unfilteredResponse = null;
        }
        else if (responses.size() == 1) {
            unfilteredResponse = responses.get(0).getResponse();
            returnCode = responses.get(0).getReturnCode();
        }
        else {    // randomly pick a response based on chances
            int total_chances = 0;
            for (SimulationResponse r : responses) {
                total_chances += r.getChance().intValue();
            }
            if (random == null)
                random = new Random();
            int ran = random.nextInt(total_chances);
            int k = 0;
            for (SimulationResponse r : responses) {
                if (ran >= k && ran < k + r.getChance().intValue()) {
                    unfilteredResponse = r.getResponse();
                    break;
                }
                k += r.getChance().intValue();
            }
        }
        Response response = new Response();
        String filtered = filter(unfilteredResponse, requestObject);
        response.setObject(filtered);
        response.setContent(filtered);
        if (returnCode != null) {
            try {
                response.setStatusCode(Integer.parseInt(returnCode));
            }
            catch (NumberFormatException ex) {
            }
        }
        return response;
    }
888409
def process_response(self, response: requests.models.Response) -> dict:
        
        try:
            output = response.json()
        except json.JSONDecodeError: # Server is having a bad day and crashed.
            raise self.BadResponseError(
                'Json not returned with status code [' + str(response.status_code) + ']')

        if response.status_code == 400:
            return output

        if response.status_code not in [200, 201]: # Safety catch.
            raise self.BadResponseError(
                str(output) + ': with status code [' + str(response.status_code) +
                '] and params:' + str(output))

        return output['data']
490862
def check_response(self, resp):
        """"""
        if resp.status_code == 400:
            raise ApiException(json.loads(resp.content).get('message'))
        return resp
1246945
def response(cls, dic, status=200):
        
        response = JsonResponse(dic, status=status)
        response['Cache-Control'] = 'no-store'
        response['Pragma'] = 'no-cache'

        return response
1165745
def answers(self, other):
        """"""
        if other.__class__ == self.__class__:
            return (other.service + 0x40) == self.service or \
                   (self.service == 0x7f and
                    (self.requestServiceId == other.service))
        return 0
1272831
def dump_to_response(request, app_label=None, exclude=None,
                     filename_prefix=None):
    
    app_label = app_label or []
    exclude = exclude
    try:
        filename = '%s.%s' % (datetime.now().isoformat(),
                              settings.SMUGGLER_FORMAT)
        if filename_prefix:
            filename = '%s_%s' % (filename_prefix, filename)
        if not isinstance(app_label, list):
            app_label = [app_label]
        response = serialize_to_response(app_label, exclude)
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response
    except CommandError as e:
        messages.error(
            request,
            _('An exception occurred while dumping data: %s') % force_text(e))
    return HttpResponseRedirect(request.build_absolute_uri().split('dump')[0])
1168149
def process_response(self, req, resp, resource):
        
        if 'result' not in req.context:
            return
        req.context['result']['is_login'] = 'user_id' in req.env['session']
        if settings.DEBUG:
            req.context['result']['_debug_queries'] = sys._debug_db_queries
            sys._debug_db_queries = []
        if resp.body is None and req.context['result']:
            resp.body = json.dumps(req.context['result'])

        try:
            log.debug("RESPONSE: %s" % resp.body)
        except:
            log.exception("ERR: RESPONSE CANT BE LOGGED ")
863095
def get_response(self):
        """"""
        request = getattr(requests, self.request_method, None)
        if request is None and self._request_method is None:
            raise ValueError("A effective http request method must be set")
        if self.request_url is None:
            raise ValueError(
                "Fatal error occurred, the class property \"request_url\" is"
                "set to None, reset it with an effective url of dingtalk api."
            )
        response = request(self.request_url, **self.kwargs)
        self.response = response
        return response
1088545
def get_response_object(self, service_id, version_number, name):
		""""""
		content = self._fetch("/service/%s/version/%d/response_object/%s" % (service_id, version_number, name))
		return FastlyResponseObject(self, content)
430068
@Override
    public Response toResponse(IllegalArgumentException ex) {
        return Response.status(Status.BAD_REQUEST).entity(new ErrorMessage(Status.BAD_REQUEST.getStatusCode(), ex.getMessage())).type(
            MediaType.APPLICATION_JSON_TYPE).build();
    }
1003175
def _BuildResponse(self,
                     status,
                     rendered_data,
                     method_name=None,
                     headers=None,
                     content_length=None,
                     token=None,
                     no_audit_log=False):
    """"""

    # To avoid IE content sniffing problems, escape the tags. Otherwise somebody
    # may send a link with malicious payload that will be opened in IE (which
    # does content sniffing and doesn't respect Content-Disposition header) and
    # IE will treat the document as html and executre arbitrary JS that was
    # passed with the payload.
    str_data = json.Dump(
        rendered_data, encoder=JSONEncoderWithRDFPrimitivesSupport)
    # XSSI protection and tags escaping
    rendered_data = ")]}'\n" + str_data.replace("<", r"\u003c").replace(
        ">", r"\u003e")

    response = werkzeug_wrappers.Response(
        rendered_data,
        status=status,
        content_type="application/json; charset=utf-8")
    response.headers[
        "Content-Disposition"] = "attachment; filename=response.json"
    response.headers["X-Content-Type-Options"] = "nosniff"

    if token and token.reason:
      response.headers["X-GRR-Reason"] = utils.SmartStr(token.reason)
    if method_name:
      response.headers["X-API-Method"] = method_name
    if no_audit_log:
      response.headers["X-No-Log"] = "True"

    for key, value in iteritems(headers or {}):
      response.headers[key] = value

    if content_length is not None:
      response.content_length = content_length

    return response
76206
def req(self, method, params=()):
        """"""

        response = self.session.post(
            self.url,
            data=json.dumps({"method": method, "params": params, "jsonrpc": "1.1"}),
        ).json()

        if response["error"] is not None:
            return response["error"]
        else:
            return response["result"]
10839
def _handle_response(res, delimiter):
    """"""
    if res.status_code == 200:
        # Python 2 -- csv.reader will need bytes
        if sys.version_info[0] < 3:
            csv_io = BytesIO(res.content)
        # Python 3 -- csv.reader needs str
        else:
            csv_io = StringIO(res.text)
        data_iter = read_unicode_csv_fileobj(csv_io, delimiter=delimiter,
                                             skiprows=1)
    else:
        raise Exception('Could not download Signor data.')
    return data_iter
1148905
def get_external_ip():
    
    response = requests.get('http://icanhazip.com/')
    if not response.ok:
        raise RuntimeError('Failed to get external ip: %s' % response.content)
    return response.content.strip()
996467
def _get_error_response(self, exc):
        
        if exc.has_code(codes.UNAUTHORIZED):
            return self._get_auth_challenge(exc)
        else:
            if exc.has_code(codes.INTERNAL_SERVER_ERROR):
                logging.getLogger('devil').error('devil caught http error: ' + str(exc), exc_info=True)
            else:
                logging.getLogger('devil').error('devil caught http error: ' + str(exc))
            content = exc.content or ''
            return HttpResponse(content=content, status=exc.get_code_num())
938236
def return_response(self, value=None):
        # type: (Any) -> Tuple[Callback, Return]
        """"""
        response = Return(id=self.id, value=value)
        return self.callback, response
40592
def external(func):
    '''
    
    '''

    def f(*args, **kwargs):
        '''
        Stub.

        :param args:
        :param kwargs:
        :return:
        '''
        return func(*args, **kwargs)

    f.external = True
    f.__doc__ = func.__doc__

    return f