/*
for js sdk, some jsonp requests will stringiy the request data and send as a query param called _jsonpdata
if we see it, parse it as json and send to the request
777533
function(params, req) {
    if (req.query._jsonpdata) {
      var jsonpdata = null;
      try {
        jsonpdata = JSON.parse(decodeURIComponent(req.query._jsonpdata));
        params = _.extend(params, jsonpdata);
      } catch (e) {
        params._jsonpdata = req.query._jsonpdata;
      }
    }
    return params;
  }
1002103
function queryParamsState(queryParamsArray, controller) {
  return queryParamsArray.reduce(
    (state, qp) => {
      let value = qp.value(controller);

      state[qp.key] = {
        value,
        serializedValue: qp.serializedValue(controller),
        as: qp.as,
        defaultValue: qp.defaultValue,
        changed: JSON.stringify(value) !== JSON.stringify(qp.defaultValue)
      };
      return state;
    },
    {},
    undefined
  );
}
368204
def _post_query(self, query, params):
        
        if "apikey" not in params:
            params["apikey"] = self.api_key

        response = requests.post(query, data=params)
        return response.json()
195518
function send(data) {
                verifyState(this);

                if (!/^(get|head)$/i.test(this.method)) {
                    var contentType = getHeader(this.requestHeaders, "Content-Type");
                    if (this.requestHeaders[contentType]) {
                        var value = this.requestHeaders[contentType].split(";");
                        this.requestHeaders[contentType] = value[0] + ";charset=utf-8";
                    } else if (!(data instanceof FormData)) {
                        this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
                    }

                    this.requestBody = data;
                }

                this.errorFlag = false;
                this.sendFlag = this.async;
                this.readyStateChange(FakeXMLHttpRequest.OPENED);

                if (typeof this.onSend == "function") {
                    this.onSend(this);
                }

                this.dispatchEvent(new sinon.Event("loadstart", false, false, this));
            }
668418
function (req) {

    // Allow customizable blacklist for params NOT to include as values.
    req.options.values = req.options.values || {};
    req.options.values.blacklist = req.options.values.blacklist;

    // Validate blacklist to provide a more helpful error msg.
    var blacklist = req.options.values.blacklist;
    if (blacklist && !_.isArray(blacklist)) {
      throw new Error('Invalid `req.options.values.blacklist`. Should be an array of strings (parameter names.)');
    }

    // Merge params into req.options.values, omitting the blacklist.
    var values = mergeDefaults(req.params.all(), _.omit(req.options.values, 'blacklist'));

    // Omit values that are in the blacklist (like query modifiers)
    values = _.omit(values, blacklist || []);

    // Omit any values w/ undefined values
    values = _.omit(values, function (p){ if (_.isUndefined(p)) return true; });

    // Omit jsonp callback param (but only if jsonp is enabled)
    var jsonpOpts = req.options.jsonp && !req.isSocket;
    jsonpOpts = _.isObject(jsonpOpts) ? jsonpOpts : { callback: JSONP_CALLBACK_PARAM };
    if (jsonpOpts) {
      values = _.omit(values, [jsonpOpts.callback]);
    }

    return values;
  }
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);
      }
    };
  }
671330
def json_or_jsonp( data )
  callback = params.delete('callback')
  response = ''

  if callback
    content_type :js
    response = "#{callback}(#{data.to_json})"
  else
    content_type :json
    response = data.to_json
  end
  
  response
end
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)
242808
function ( params, callback, method, done ) {
			const self = this,
				// store requested action - will be used when parsing a response
				actionName = params.action,
				// "request" options
				options = {
					method: method || 'GET',
					proxy: this.proxy || false,
					jar: this.jar,
					headers: {
						'User-Agent': this.userAgent
					}
				};

			// HTTP request parameters
			params = params || {};

			// force JSON format
			params.format = 'json';

			// handle uploads
			if ( method === 'UPLOAD' ) {
				options.method = 'POST';

				const CRLF = '\r\n',
					postBody = [],
					boundary = `nodemw${Math.random().toString().substr( 2 )}`;

				// encode each field
				Object.keys( params ).forEach( function ( fieldName ) {
					const value = params[ fieldName ];

					postBody.push( `--${boundary}` );
					postBody.push( CRLF );

					if ( typeof value === 'string' ) {
					// properly encode UTF8 in binary-safe POST data
						postBody.push( `Content-Disposition: form-data; name="${fieldName}"` );
						postBody.push( CRLF );
						postBody.push( CRLF );
						postBody.push( new Buffer( value, 'utf8' ) );
					} else {
					// send attachment
						postBody.push( `Content-Disposition: form-data; name="${fieldName}"; filename="foo"` );
						postBody.push( CRLF );
						postBody.push( CRLF );
						postBody.push( value );
					}

					postBody.push( CRLF );
				} );

				postBody.push( `--${boundary}--` );

				// encode post data
				options.headers[ 'content-type' ] = `multipart/form-data; boundary=${boundary}`;
				options.body = postBody;

				params = {};
			}

			// form an URL to API
			options.url = this.formatUrl( {
				protocol: this.protocol,
				port: this.port,
				hostname: this.server,
				pathname: this.path + '/api.php',
				query: ( options.method === 'GET' ) ? params : {}
			} );

			// POST all parameters (avoid "request string too long" errors)
			if ( method === 'POST' ) {
				options.form = params;
			}

			this.logger.debug( 'API action: %s', actionName );
			this.logger.debug( '%s <%s>', options.method, options.url );
			if ( options.form ) {
				this.logger.debug( 'POST fields: %s', Object.keys( options.form ).join( ', ' ) );
			}

			request( options, function ( error, response, body ) {
				response = response || {};

				if ( error ) {
					self.logger.error( 'Request to API failed: %s', error );
					callback( new Error( `Request to API failed: ${error}` ) );
					done();
					return;
				}

				if ( response.statusCode !== 200 ) {
					self.logger.error( 'Request to API failed: HTTP status code was %d for <%s>', response.statusCode || 'unknown', options.url );
					self.logger.debug( 'Body: %s', body );

					self.logger.data( new Error().stack );

					callback( new Error( `Request to API failed: HTTP status code was ${response.statusCode}` ) );
					done();
					return;
				}

				// parse response
				let data,
					info,
					next;

				try {
					data = JSON.parse( body );
					info = data && data[ actionName ];

					// acfrom=Zeppelin Games
					next = data && data[ 'query-continue' ] && data[ 'query-continue' ][ params.list || params.prop ];

					// handle the new continuing queries introduced in MW 1.21
					// (and to be made default in MW 1.26)
					// issue #64
					// @see https://www.mediawiki.org/wiki/API:Query#Continuing_queries
					if ( !next ) {
					// cmcontinue=page|5820414e44205920424f534f4e53|12253446, continue=-||
						next = data && data.continue;
					}
				} catch ( e ) {
					self.logger.error( 'Error parsing JSON response: %s', body );
					self.logger.data( body );

					callback( new Error( 'Error parsing JSON response' ) );
					done();
					return;
				}

				// if (!callback) data.error = {info: 'foo'}; // debug

				if ( data && !data.error ) {
					if ( next ) {
						self.logger.debug( 'There\'s more data' );
						self.logger.debug( next );
					}

					callback( null, info, next, data );
				} else if ( data.error ) {
					self.logger.error( 'Error returned by API: %s', data.error.info );
					self.logger.data( data.error );

					callback( new Error( `Error returned by API: ${data.error.info}` ) );
				}
				done();
			} );
		}
149510
function(url, data, jsonpParam, callbacnName) {
		if (jsonpParam) {
			url = url.replace(jsonpParam + '=?', jsonpParam + '=' + callbacnName);
		} else {
			data['callback'] = callbacnName;
		}
		var buffer = [];
		for (var key in data) {
			buffer.push(key + '=' + encodeURIComponent(data[key]));
		}
		return url + (url.indexOf('?') > -1 ? '&' : '?') + buffer.join('&');
	}
575349
function requestData() {
    let visible = Math.ceil(_(this).parent.offsetHeight / _(this).itemHeight);
    let scrollIndex = Math.floor(_(this).view.scrollbar.scrollTop / _(this).itemHeight);
    let request = buildRequest.call(this, scrollIndex, visible);
    _(this).request = request;
    _(this).onDataFetch(request, setData.bind(this));
}
1158026
function processJsonpMock( requestSettings, mockHandler, origSettings ) {
		// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
		// because there isn't an easy hook for the cross domain script tag of jsonp

		processJsonpUrl( requestSettings );

		requestSettings.dataType = "json";
		if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
			createJsonpCallback(requestSettings, mockHandler, origSettings);

			// We need to make sure
			// that a JSONP style response is executed properly

			var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
				parts = rurl.exec( requestSettings.url ),
				remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);

			requestSettings.dataType = "script";
			if(requestSettings.type.toUpperCase() === "GET" && remote ) {
				var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );

				// Check if we are supposed to return a Deferred back to the mock call, or just
				// signal success
				if(newMockReturn) {
					return newMockReturn;
				} else {
					return true;
				}
			}
		}
		return null;
	}
1332435
function jsonp(options, successCallback, errorCallback) {
    /*jshint camelcase:false */

    options = options || {};

    // Define unique callback name.
    var uniqueName = 'callback_json' + (++counter);

    // Send all data (including method, api key and data) via GET
    // request params.
    var params = options.params || {};
    params.callback = uniqueName;
    params.access_token = options.authorization;
    params.method = options.method || 'get';
    params.data = JSON.stringify(options.data);
    options.params = params;

    options.apiUrl = options.apiUrl && options.apiUrl.replace('//api', '//js-api');

    // Evrythng REST API default endpoint does not provide JSON-P
    // support, which '//js-api.evrythng.com' does.
    var url = Utils.buildUrl(options);

    // Return a promise and resolve/reject it in the callback function.
    return new Promise(function(resolve, reject) {

      // Attach callback as a global method. Evrythng's REST API error
      // responses always have a status and array of errors.
      window[uniqueName] = function(response){

        if (response.errors && response.status) {

          var errorData = _buildError(url, response.status, params.method, response);
          Logger.error(errorData);

          if(errorCallback) {
            Logger.warnCallbackDeprecation();
            errorCallback(errorData);
          }
          reject(errorData);

        }else {

          if(successCallback) {
            Logger.warnCallbackDeprecation();
            successCallback(response);
          }

          try {
            response = JSON.parse(response);
          } catch(e){}

          resolve(response);
        }

        // Remove callback from window.
        try {
          delete window[uniqueName];
        } catch (e) {}
        window[uniqueName] = null;
      };

      _load(url, reject);

    });
  }
345613
function JSONPPolling (opts) {
  Polling.call(this, opts);

  // define global callbacks array if not present
  // we do this here (lazily) to avoid unneeded global pollution
  if (!callbacks) {
    // we need to consider multiple engines in the same page
    if (!global.___eio) global.___eio = [];
    callbacks = global.___eio;
  }

  // callback identifier
  this.index = callbacks.length;

  // add callback to jsonp global
  var self = this;
  callbacks.push(function (msg) {
    self.onData(msg);
  });

  // append to query string
  this.query.j = this.index;
}
825745
function(url, callback) {
      if (!url) return callback('send(): url is empty.');
      console.log('send(): ' + url);
      request.get(url, function(err, res, body) {
        console.log(body);
	if (err) return callback(err);
        body = JSON.parse(body);
        if (body && body.query) {
          return callback('', body);
        } else {
          return callback('send(): No results returned.');
        }
      });
    }
1055656
function (data) {
    var str = '', start = true;
    var jsondata = '';
    for (var key in data) {
      if (typeof (jsondata = JSON.stringify(data[key])) === 'string') {
        str += (start? '': '&');
        str += encodeURIComponent(key) + '=' + encodeURIComponent(jsondata);
        if (start) { start = false; }
      }
    }
    return str;
  }
1061519
function serveRemoteJson(request, response, next) {
	if (request.path !== '/remote') {
		return next();
	}
	var options = {
		url: request.query.url,
		headers: request.query.headers
	};
	var error;

	if (!options.url || typeof options.url !== 'string') {
		error = new Error('Invalid query parameter: url');
		error.status = 400;
		return next(error);
	}

	if (options.headers && typeof options.headers !== 'string') {
		error = new Error('Invalid query parameter: headers');
		error.status = 400;
		return next(error);
	}

	options.headers = parseHeaders(options.headers);

	loadRemoteJson(options, function (error, json) {
		if (error) {
			return next(error);
		}
		response.writeHead(200, {
			'Content-Type': 'application/x-shunter+json'
		});
		response.end(JSON.stringify(json, null, 4));
	});
}