/*
JSONP callback function for displaying weather data
340834
function (data) {
	var tempColorFunction = new L.PiecewiseFunction([new L.HSLHueFunction(new L.Point(100,270), new L.Point(210,270), {outputLuminosity: '25%'}), new L.HSLHueFunction(new L.Point(210,270), new L.Point(320,0), {outputLuminosity: '25%'})]);
	var tempFillColorFunction = new L.PiecewiseFunction([new L.HSLHueFunction(new L.Point(100,270), new L.Point(210,270), {outputLuminosity: '50%'}), new L.HSLHueFunction(new L.Point(210,270), new L.Point(320,0), {outputLuminosity: '50%'})]);
	var radiusFunction = new L.LinearFunction(new L.Point(272,5), new L.Point(320,15));
	var K_TO_C = 273.15;
	var convert = function (value) {
		var celsius = value - K_TO_C;
		var farenheit = (9/5) * celsius + 32;
		
		return {
			c: celsius,
			f: farenheit
		};
	};
	
	var options = {
		recordsField: 'list',
		latitudeField: 'coord.lat',
		longitudeField: 'coord.lon',
		displayOptions: {
			'main.temp': {
				displayName: 'Temperature',
				color: tempColorFunction,
				fillColor: tempFillColorFunction,
				radius: radiusFunction,
				displayText: function (value) {
					var values = convert(value);
					
					return values.f.toFixed(0) + '&deg;F / ' + values.c.toFixed(0) + '&deg;C';
				}
			}
		},
		layerOptions: {
			width: 5,
			weight: 1,
			iconSize: new L.Point(60,40),
			fillOpacity: 0.8,
			opacity: 1.0,
			radius: 6
		},
		tooltipOptions: {
			iconSize: new L.Point(100,55),
			iconAnchor: new L.Point(-5,55)
		},
		onEachRecord: function (layer,record) {
			var html = '<table class="table table-condensed table-striped table-bordered"><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody></tbody></table>';
			var $html = $(html);
			var $tbody = $html.find('tbody');
			
			for (var property in record.main) {
				$tbody.append('<tr><td>' + property + '</td><td>' + record.main[property] + '</td></tr>');
			}
			layer.bindPopup($html.wrap('<div/>').parent().html(),{
				minWidth: 400,
				maxWidth: 400
			});
		}
	};
	
	var weatherLayer = new L.MapMarkerDataLayer(data, options);

	map.addLayer(weatherLayer);
	
	if (!lastWeatherLayer) {		
		var legend = weatherLayer.getLegend({
			numSegments: 20,
			width: 80,
			className: 'well'
		});
		
		$('#legend').append(legend);
	}
	
	lastWeatherLayer = weatherLayer;
	
}
619225
function httpNdjson (req, res, opts, cb) {
  if (!cb) {
    cb = opts
    opts = {}
  }
  opts = opts || {}

  const start = Date.now()
  var size = null

  function setContentLength (nwSize) {
    size = nwSize
  }

  const headers = req.headers
  const request = {
    name: 'http',
    message: 'request',
    method: req.method,
    remoteAddress: req.connection.remoteAddress,
    url: req.url
  }
  if (headers['x-forwarded-for']) {
    request.xForwardedFor = headers['x-forwarded-for']
  }
  if (headers['x-real-ip']) {
    request.xRealIp = headers['x-real-ip']
  }
  if (headers['http-client-ip']) {
    request.httpClientIp = headers['http-client-ip']
  }
  if (opts.req) extend(request, value(opts.req))
  cb(request)

  eos(res, function (err) {
    if (err) cb({ name: 'error', message: err })

    const response = {
      name: 'http',
      message: 'response',
      method: req.method,
      url: req.url,
      statusCode: res.statusCode,
      elapsed: Date.now() - start
    }
    if (size !== null) response.contentLength = size
    if (opts.res) extend(response, value(opts.res))
    cb(response)
  })

  return setContentLength
}
1301660
function getJSONP(url, options) {
  return new Promise(function (resolve, reject) {
    if (!url) {
      reject(new Error('No request url'));
    }

    var _ref = options || {};

    var _ref$params = _ref.params;
    var params = _ref$params === undefined ? {} : _ref$params;
    var _ref$timeout = _ref.timeout;
    var timeout = _ref$timeout === undefined ? 15000 : _ref$timeout;
    // the funtion name of callback function

    var name = void 0;
    var timer = void 0;
    var requestUrl = parseUrl(url, params);
    // check whether the callbacl name has been defined
    var match = /callback=(\w+)/.exec(requestUrl);

    if (match && match[1]) {
      name = match[1];
    } else {
      // generate a random function name if no callback name was defined
      // return a function name generated by timestamp and random number
      // eg: jsonp_1355750852040_8260732076596469
      name = 'jsonp_' + getNow() + '_' + getRandomNumber();
      requestUrl += '&callback=' + name;
    }

    // create a script element
    var script = document.createElement('script');
    script.type = 'text/javascript';
    // set the request url
    script.src = requestUrl;
    // set the id of dom node which can be used to find this node
    script.id = 'id_' + name;

    var cleanUp = function cleanUp() {
      // exec callback and remove the callback
      window[name] = undefined;
      // get the script node
      var elem = document.getElementById('id_' + name);
      // remove added script node
      removeElement(elem);

      if (timer) {
        clearTimeout(timer);
      }
    };

    if (timeout) {
      timer = setTimeout(function () {
        cleanUp();
        reject(new Error('Timeout'));
      }, timeout);
    }

    // the callback when request finish
    window[name] = function (json) {
      cleanUp();
      // exec callback
      resolve(json);
    };

    // add script node in head
    var head = document.getElementsByTagName('head');

    if (head && head[0]) {
      head[0].appendChild(script);
    }
  });
}
394411
function(method, data, callback) {
      xhr.open(method, url, true, user, password);
      if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
      if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
      if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
      if (responseType != null) xhr.responseType = responseType;
      if (timeout > 0) xhr.timeout = timeout;
      if (callback == null && typeof data === "function") callback = data, data = null;
      if (callback != null && callback.length === 1) callback = fixCallback(callback);
      if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
      event.call("beforesend", request, xhr);
      xhr.send(data == null ? null : data);
      return request;
    }
582220
function (json, callback) {
        //validate input
        if (!inputValidation(json)) {
            var inputError = new SearchError('invalid input');
            callback(undefined, inputError);
            return;
        }
        var number = json.number;
        //mongodb api here, then handle the response from mongodb
        database.getSentimentTimeframe(json.startDate, json.endDate, function (json, err) {
            if (err) {
                callback(undefined, err);
            } else {
                var res = calculateTopSum(json, number, ["posSum"]);
                callback(res);
            }
        });
    }
1035081
function(pages, callback) {
      var t = this,
          didError = false,
          numLeft = pages.length;

      // Callback early if no pages to read
      if (pages.length === 0) {
        return callback();
      }

      // Read and parse each file for the title/description
      pages.forEach(function(page, index) {

        // Read the file
        var fullPath = Path.join(t.dirPath, page.id + '.json');
        FS.readFile(fullPath, 'utf8', function(error, file) {

          // Process a stat error
          if (error) {
            didError = true;
            return callback(error);
          }

          // Parse the JSON
          var parsed = null;
          try {
            parsed = JSON.parse(file);
          }
          catch (e) {
            didError = true;
            console.error('JSON error parsing page: ' + fullPath, e);
            return callback(e);
          }

          // Do nothing if a prior error callback happened
          if (didError) {
            return;
          }

          // Set the page title and description
          if (parsed.title) {
            page.label = parsed.title;
          }
          if (parsed.description) {
            page.description = parsed.description;
          }

          // Add a file watcher if not already watching
          if (!t.fileWatchers[page.id]) {
            t.fileWatchers[page.id] = new FS.watch(fullPath, {persistent:false}, function(type){
              t.sync();
            });
          }

          // Callback if all page reads are complete
          if (--numLeft === 0) {
            callback(null);
          }
        });
      });
    }
294385
def jsonp(func):
    """"""
    @wraps(func)
    def decorated(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs).data)
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated
1221144
function ajax(url, callback, data) {
  if (data) {
    request.post({url: url, body: data, json: true}, function(err, res, body) {
      if (err) console.log(err);
      callback(err, body, res);
    });
  } else {
    request(url, function(err, res, body) {
      if (err) console.log(err);
      callback(err, body, res);
    });
  }
}
797226
public function jsonp($callback, $data = [], $status = 200, array $headers = [], $options = 0)
    {
        return $this->json($data, $status, $headers, $options)->setCallback($callback);
    }
288261
def add_data_from_jsonp(self, data_src, data_name = 'json_data', series_type="map", name=None, **kwargs):
        
        self.jsonp_data_flag = True
        self.jsonp_data_url = json.dumps(data_src)
        if data_name == 'data':
            data_name = 'json_'+ data_name
        self.jsonp_data = data_name
        self.add_data_set(RawJavaScriptText(data_name), series_type, name=name, **kwargs)
432789
function _jsonLoaded(callback, err, data) {
  if (err) return callback(err);
  var parsed;
  try {
    parsed = JSON.parse(data);
  } catch(jerr) {
    return callback(jerr);
  }
  callback(null, parsed);
}
21763
function ajax(url, options, callback) {
        if (typeof options === 'function') {
          callback = options;
          options = {};
        }
        callback = callback || function () {};
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
          if (xhr.status >= 400) {
            return callback(new Error(xhr.responseText || xhr.statusText));
          }
          try {
            return callback(null, JSON.parse(xhr.responseText));
          } catch (e) {
            return callback(new Error('invalid_response'));
          }
        };
        xhr.onerror = function (err) {
          return callback(err);
        };
        xhr.open('GET', url);
        xhr.send();
      }
1072503
function(options, callback, opt_data) {
  var request = http.request(options, function(response) {
    if (response.statusCode == 302 || response.statusCode == 303) {
      try {
        var location = url.parse(response.headers['location']);
      } catch (ex) {
        callback(Error(
            'Failed to parse "Location" header for server redirect: ' +
            ex.message + '\nResponse was: \n' +
            new HttpResponse(response.statusCode, response.headers, '')));
        return;
      }

      if (!location.hostname) {
        location.hostname = options.host;
        location.port = options.port;
      }

      request.abort();
      sendRequest({
        method: 'GET',
        host: location.hostname,
        path: location.pathname + (location.search || ''),
        port: location.port,
        headers: {
          'Accept': 'application/json; charset=utf-8'
        }
      }, callback);
      return;
    }

    var body = [];
    response.on('data', body.push.bind(body));
    response.on('end', function() {
      var resp = new HttpResponse(response.statusCode,
          response.headers, body.join('').replace(/\0/g, ''));
      callback(null, resp);
    });
  });

  request.on('error', function(e) {
    if (e.code === 'ECONNRESET') {
      setTimeout(function() {
        sendRequest(options, callback, opt_data);
      }, 15);
    } else {
      var message = e.message;
      if (e.code) {
        message = e.code + ' ' + message;
      }
      callback(new Error(message));
    }
  });

  if (opt_data) {
    request.write(opt_data);
  }

  request.end();
}
916451
function json (program, callback) {
    var formatterRedux = formatter(jsonRedux())
    parse(program.stdin, program.stderr, printer(formatterRedux, program.stdout, program.stderr), callback)
}
1004746
public function jsonp($arr, $callback = '', $out = true)
    {
        if (!$callback) {
            $vitex = Vitex::getInstance();
            $key = $vitex->getConfig('callback');
            $callback = $vitex->req->query[$key];
        }
        $res = json_encode($arr, JSON_UNESCAPED_UNICODE);
        $res = $callback . '(' . $res . ');';
        if ($out) {
            echo $res;
            return "";
        }
        return $res;
    }
212690
function prepareWeather(weatherData) {
      return {
        temperature: weatherData.main.temp,
        icon: (angular.isDefined(weatherIcons[weatherData.weather[0].icon])) ? weatherData.weather[0].icon : weatherData.weather[0].id,
        description: weatherData.weather[0].description
      }
    }
40228
def jsonp(data, **json_kwargs):
    
    from uliweb import request
    
    if 'jsonp' in json_kwargs:
        cb = json_kwargs.pop('jsonp')
    else:
        cb = 'callback'
        
    begin = str(request.GET.get(cb))
    if not begin:
        raise BadRequest("Can't found %s parameter in request's query_string" % cb)
    if not r_callback.match(begin):
        raise BadRequest("The callback name is not right, it can be alphabetic, number and underscore only")
    
    if callable(data):
        @wraps(data)
        def f(*arg, **kwargs):
            ret = data(*arg, **kwargs)
            return Response(begin + '(' + json_dumps(ret) + ');', **json_kwargs)
        return f
    else:
        return Response(begin + '(' + json_dumps(data) + ');', **json_kwargs)