Process a JSONP request by evaluating the mocked response text
1897
function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
		// Synthesize the mock request for adding a script tag
		var callbackContext = origSettings && origSettings.context || requestSettings,
			newMock = null;


		// If the response handler on the moock is a function, call it
		if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
			mockHandler.response(origSettings);
		} else {

			// Evaluate the responseText javascript in a global context
			if( typeof mockHandler.responseText === 'object' ) {
				$.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
			} else {
				$.globalEval( '(' + mockHandler.responseText + ')');
			}
		}

		// Successful response
		setTimeout(function() {
			jsonpSuccess( requestSettings, callbackContext, mockHandler );
			jsonpComplete( requestSettings, callbackContext, mockHandler );
		}, parseResponseTimeOpt(mockHandler.responseTime) || 0);

		// If we are running under jQuery 1.5+, return a deferred object
		if($.Deferred){
			newMock = new $.Deferred();
			if(typeof mockHandler.responseText == "object"){
				newMock.resolveWith( callbackContext, [mockHandler.responseText] );
			}
			else{
				newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
			}
		}
		return newMock;
	}
153585
function jsonp(req) {
    var sUrl = req.url,
        inData = req.data,
        callback = req.callback;
    if (!sUrl || typeof sUrl != 'string') throw new Error('invalid URL');
    if (inData && (typeof inData === 'undefined' ? 'undefined' : _typeof(inData)) != 'object') throw new Error('invalid input argument (data)');
    if (typeof callback != 'function') throw new Error('input argument (callback) should be a function');

    var id = newJsonPid_();
    if (sUrl.indexOf('?') > 0) sUrl += '&';else sUrl += '?';
    sUrl += 'callback=TRIGGER__%5B' + id + '%5D'; // encodeURIComponent('[' + id + ']')

    if (inData) {
      Object.keys(inData).forEach(function (sKey) {
        var item = inData[sKey];
        sUrl += '&' + sKey + '=' + encodeURIComponent(item + '');
      });
    }

    var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
    var script = document.createElement('script');
    script.async = 'async';
    if (req.scriptCharset) script.charset = req.scriptCharset;
    script.src = sUrl;
    script.onload = script.onreadystatechange = function () {
      if (!script.readyState || /loaded|complete/.test(script.readyState)) {
        script.onload = script.onreadystatechange = null; // handle memory leak in IE
        if (head && script.parentNode) // remove the script node
          head.removeChild(script);

        script = undefined; // dereference the script
        setTimeout(function () {
          var fn = window.TRIGGER__[id];
          if (fn) {
            delete window.TRIGGER__[id];
            if (req.notifyError) callback(null); // null means failed, fn not removed in TRIGGER__[id]() yet
          }
        }, 0);
      }
    };
    head.insertBefore(script, head.firstChild);

    window.TRIGGER__[id] = function (json) {
      var fn = window.TRIGGER__[id];
      if (fn) {
        delete window.TRIGGER__[id]; // unregist callback: TRIGGER__[xxx]
        callback(json);
      }
    };
  }
670329
def json_wrap(function, *args, **kwargs):
    ''''''
    try:
        # Some responses have data = None, but they generally signal a
        # successful API call as well.
        response = json.loads(function(*args, **kwargs).content)
        if 'data' in response:
            return response['data'] or True
        else:
            return response
    except Exception as exc:
        raise ClientException(exc)
721202
def _handle_response(self, response):
        
        if not response.ok:
            raise ScrapydResponseError(
                "Scrapyd returned a {0} error: {1}".format(
                    response.status_code,
                    response.text))

        try:
            json = response.json()
        except ValueError:
            raise ScrapydResponseError("Scrapyd returned an invalid JSON "
                                       "response: {0}".format(response.text))
        if json['status'] == 'ok':
            json.pop('status')
            return json
        elif json['status'] == 'error':
            raise ScrapydResponseError(json['message'])
817133
def _request_process_json(self, response):
        
        data = []
        try:
            if self._api_branch == 'bulk':
                response_data = self._request_bulk(response)
            else:
                response_data = response.json()

            if self._request_entity is None:
                data = response_data
                status = 'Success'
            elif self._api_branch == 'bulk':
                data, status = self._request_process_json_bulk(response_data)
            elif response_data.get('data') is None:
                data, status = self._request_process_json_status(response_data)
            elif response_data.get('status') == 'Success':
                data, status = self._request_process_json_standard(response_data)

                # setup pagination
                if self._result_count is None:
                    self._result_count = response_data.get('data', {}).get('resultCount')
            else:
                self.tcex.log.error('Failed Request: {}'.format(response.text))
                status = 'Failure'
        except KeyError as e:
            # TODO: Remove try/except block
            status = 'Failure'
            msg = u'Error: Invalid key {}. [{}] '.format(e, self.request_entity)
            self.tcex.log.error(msg)
        except ValueError as e:
            # TODO: Remove try/except block
            status = 'Failure'
            msg = u'Error: ({})'.format(e)
            self.tcex.log.error(msg)

        return data, status
710436
def _new_mock_response(self, response, file_path):
        ''''''
        mock_response = copy.copy(response)

        mock_response.body = Body(open(file_path, 'rb'))
        mock_response.fields = NameValueRecord()

        for name, value in response.fields.get_all():
            mock_response.fields.add(name, value)

        mock_response.fields['Content-Type'] = 'text/html; charset="utf-8"'

        return mock_response
1161579
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    JsonGenerator jg = null;
    String jsonpcb = null;
    PrintWriter writer = null;
    try {

      writer = response.getWriter();

      // "callback" parameter implies JSONP output
      jsonpcb = request.getParameter(CALLBACK_PARAM);
      if (jsonpcb != null) {
        response.setContentType("application/javascript; charset=utf8");
        writer.write(jsonpcb + "(");
      } else {
        response.setContentType("application/json; charset=utf8");
      }

      jg = jsonFactory.createJsonGenerator(writer);
      jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
      jg.useDefaultPrettyPrinter();

      int statusCode = renderMBeans(jg, request.getParameterValues("qry"));
      response.setStatus(statusCode);

    } catch (IOException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } finally {
      if (jg != null) {
        jg.close();
      }
      if (jsonpcb != null) {
        writer.write(");");
      }
      if (writer != null) {
        writer.close();
      }
    }

  }
1257744
def _request_process_octet(response):
        
        status = 'Failure'
        # Handle document download
        data = response.content
        if data:
            status = 'Success'

        return data, status
842599
def _process_json_response(self, response):
        '''  '''

        json_response = self._get_json_response(response)
        
        if self.response_callback is not None:
            json_response = self.response_callback(json_response)
            response._content = json.dumps(json_response)

        self.http_status_code = response.status_code
        self._check_error(response, json_response)
        self._check_warnings(json_response)

        return json_response
423600
def hook_response(self, response):
        " "
        # Decode content with json.
        response._content = json.loads(response.content)
        return response
1552
def jsonp(*args, **kw):
    
    data = json.dumps(dict(*args, **kw), indent=2)
    callback = request.args.get('callback', request.args.get('jsonp'))
    if callback and __jsoncallback_re.search(callback) is not None:
        data = callback + u'(' + data + u');'
        mimetype = 'application/javascript'
    else:
        mimetype = 'application/json'
    return Response(data, mimetype=mimetype)
944610
function handleAjax( url, origSettings ) {
		var mockRequest, requestSettings, mockHandler, overrideCallback;

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			origSettings = url;
			url = undefined;
		} else {
			// work around to support 1.5 signature
			origSettings = origSettings || {};
			origSettings.url = url;
		}

		// Extend the original settings for the request
		requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);

		// Generic function to override callback methods for use with
		// callback options (onAfterSuccess, onAfterError, onAfterComplete)
		overrideCallback = function(action, mockHandler) {
			var origHandler = origSettings[action.toLowerCase()];
			return function() {
				if ( $.isFunction(origHandler) ) {
					origHandler.apply(this, [].slice.call(arguments));
				}
				mockHandler['onAfter' + action]();
			};
		};

		// Iterate over our mock handlers (in registration order) until we find
		// one that is willing to intercept the request
		for(var k = 0; k < mockHandlers.length; k++) {
			if ( !mockHandlers[k] ) {
				continue;
			}

			mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
			if(!mockHandler) {
				// No valid mock found for this request
				continue;
			}

			mockedAjaxCalls.push(requestSettings);

			// If logging is enabled, log the mock to the console
			$.mockjaxSettings.log( mockHandler, requestSettings );


			if ( requestSettings.dataType && requestSettings.dataType.toUpperCase() === 'JSONP' ) {
				if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {
					// This mock will handle the JSONP request
					return mockRequest;
				}
			}


			// Removed to fix #54 - keep the mocking data object intact
			//mockHandler.data = requestSettings.data;

			mockHandler.cache = requestSettings.cache;
			mockHandler.timeout = requestSettings.timeout;
			mockHandler.global = requestSettings.global;

			// In the case of a timeout, we just need to ensure
			// an actual jQuery timeout (That is, our reponse won't)
			// return faster than the timeout setting.
			if ( mockHandler.isTimeout ) {
				if ( mockHandler.responseTime > 1 ) {
					origSettings.timeout = mockHandler.responseTime - 1;
				} else {
					mockHandler.responseTime = 2;
					origSettings.timeout = 1;
				}
				mockHandler.isTimeout = false;
			}

			// Set up onAfter[X] callback functions
			if ( $.isFunction( mockHandler.onAfterSuccess ) ) {
				origSettings.success = overrideCallback('Success', mockHandler);
			}
			if ( $.isFunction( mockHandler.onAfterError ) ) {
				origSettings.error = overrideCallback('Error', mockHandler);
			}
			if ( $.isFunction( mockHandler.onAfterComplete ) ) {
				origSettings.complete = overrideCallback('Complete', mockHandler);
			}

			copyUrlParameters(mockHandler, origSettings);

			(function(mockHandler, requestSettings, origSettings, origHandler) {

				mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {
					// Mock the XHR object
					xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }
				}));
			})(mockHandler, requestSettings, origSettings, mockHandlers[k]);

			return mockRequest;
		}

		// We don't have a mock request
		unmockedAjaxCalls.push(origSettings);
		if($.mockjaxSettings.throwUnmocked === true) {
			throw new Error('AJAX not mocked: ' + origSettings.url);
		}
		else { // trigger a normal request
			return _ajax.apply($, [origSettings]);
		}
	}
413237
async def _request_mock(self, orig_self: ClientSession,
                            method: str, url: 'Union[URL, str]',
                            *args: Tuple,
                            **kwargs: Dict) -> 'ClientResponse':
        """"""
        url = normalize_url(merge_params(url, kwargs.get('params')))
        url_str = str(url)
        for prefix in self._passthrough:
            if url_str.startswith(prefix):
                return (await self.patcher.temp_original(
                    orig_self, method, url, *args, **kwargs
                ))

        response = await self.match(method, url, **kwargs)
        if response is None:
            raise ClientConnectionError(
                'Connection refused: {} {}'.format(method, url)
            )
        self._responses.append(response)
        key = (method, url)
        self.requests.setdefault(key, [])
        self.requests[key].append(RequestCall(args, kwargs))
        return response
1123737
function parseResource (err, responseSpec, next) {
      var resource = responseSpec ? responseSpec.body : undefined;
      this.invokeNext(err, resource, next);
    }
1055478
def _process_req_txt(req):
    ''''''
    if req.status_code == 404:
        return ''
    if req.status_code != 200:
        raise DapiCommError('Response of the server was {code}'.format(code=req.status_code))
    return req.text
1201018
def _parse_reply(request):
        
        try:
            return jsonutils.loads(request.content)
        except ValueError:
            raise ib_ex.InfobloxConnectionError(reason=request.content)
159651
def handle_response (response):
    
    
    response = json.loads(response.read())
    
    # Was the expression valid?
    if 'error' in response:
        raise ValueError(response['error'])
    else:
        # Some of the strings returned can be parsed to integers or floats
        try:
            return json.loads(response['result'])
        except (TypeError, json.decoder.JSONDecodeError):
            # If the result is NaN, return the actual NaN float
            if response['result'] == 'NaN':
                return float('nan')
            else:
                return response['result']