Result: the function to get `Result` instance. The request result object.
- xhrObj: the xhr obj which can get the xhr result.

How to use it? if `r` is the instance of `Result`.
var r_json = r.json();
var status = r.status_code;
var headers = r.headers;
976908
function(method, url, body, onsuccess, onfail) {
    _method = method;
    _url = url;
    _body = body;
    on('success', onsuccess);
    on('fail', onfail);
    return _request();
  }
277348
def get(self, uri=''):
        "'"
        (node, rule_kw) = node_from_uri(uri)

        if node == None:
            abort(404)
        rule_kw.update( node )
        values = rule_kw
        xhr_data = request.get_json()
        if xhr_data:
            values.update( xhr_data )
        values.update( request.form.to_dict(flat=True) )
        values.update( request.args.to_dict(flat=True) )
        values.update( request.cookies )
        values['method'] = request.method
        noderequest = values.copy()
        noderequest.pop('node_id')
        noderequest.pop('name')
        noderequest.pop('value')

        current_app.logger.debug("get kw: %s", values)
        rendered = render_node(node['id'], noderequest=noderequest, **values)
        current_app.logger.debug("rendered: %s", rendered)
        if rendered:
            if not isinstance(rendered, (str, unicode, int, float)):
                # return a json string
                return encoder.encode(rendered)
            return rendered

        # Nothing to show, so nothing found
        abort(404)
608642
function createResponse(xhr, request){
  
  // XHR header processing borrowed from jQuery
  var responseHeaders = {}, match;
  while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
		responseHeaders[match[1].toLowerCase()] = match[2];
	}
	
  return {
    statusCode: xhr.status,
    statusText: xhr.statusText,
    headers: responseHeaders,
    originalUrl: request.url,
    effectiveUrl: request.url,
    redirected: false,
    requestMethod: request.method,
    requestHeaders: request.headers,
    body: xhr.responseText,
    retries: 0,
    throttled: false
  };
}
441260
def result(self, property, *args):
        
        if self.obj is None:
            return self._wrap(self.obj)

        if(hasattr(self.obj, property)):
            value = getattr(self.obj, property)
        else:
            value = self.obj.get(property)
        if _.isCallable(value):
            return self._wrap(value(*args))
        return self._wrap(value)
321625
function(err, result) {
        var data=[];
    
        // default route name if not present in XML
        var now=new Date();
        data.name= 'ParseGPX' + now.toISOString(); 
    
        // search for gpx tag
        if (result['gpx'] === undefined) {
            console.log ("Fatal: Not a GPX route/track file [no <gpx></gpx> tag]");
            return (-1);
        }
        // search for track tag
        if (result['gpx']["trk"] !== undefined) {
            // console.log ("track=%s", JSON.stringify(result['gpx']["trk"]));
            data = {
                mode    : 'track',
                name    : result['gpx']["trk"][0].name,
                segment : result['gpx']["trk"][0]["trkseg"][0]['trkpt']
            };
        }
        // search for route tag
        if (result['gpx']["rte"] !== undefined) {
            //console.log ("route=%s", JSON.stringify(result['gpx']["rte"]));
            data = {
                mode    :'route',
                name    :result['gpx']["rte"][0].name,
                segment :result['gpx']["rte"][0]["rtept"]
            };
        }
        if (data.mode === undefined) {
           console.log ("Fatal Not a valid GPX route/track file <trk>|<rte> tag");
           return (-1);
        }
    
        // provide a default name if nothing found in gpxfile
        if (data.name === undefined) {
            now= new Date();
            route.name = 'GGsimulator://' + opts.gpxfile + "/" + now.toISOString();
        } else {
            route.name = 'GGsimulator://' + data.name;
        }
    
        switch (data.mode) {
            case "track":
            var spd, crs, alt,dat;
            for (var trackpts in data.segment)  {
                // console.log ("trackpts[%s]=%s", trackpts, JSON.stringify(data.segment[trackpts]));
                if (data.segment[trackpts]['name'] === undefined) nam= 'TrackPts-' + trackpts; 
                    else nam=data.segment[trackpts]['name'];
                
                lat=parseFloat (data.segment[trackpts]["$"].lat);
                lon=parseFloat (data.segment[trackpts]["$"].lon);
                spd=data.segment[trackpts]['sog'];
                crs=data.segment[trackpts]['course'];
                alt=data.segment[trackpts]['ele'];
                dat=data.segment[trackpts]['time'];
                //console.log ("name=%s  lat=%s lon=%s sog=%s course=%s alt=%s", nam, lat, lon, spd, crs, alt);
                route.waypts.push ({name: nam, lat: lat, lon: lon, date: dat});
                route.count++;
            }
            break;
        case 'route':
            var nam, lat, lon;
            for (var routepts in data.segment)  {
                // console.log ("routepts[%s]=%s", routepts, JSON.stringify(data.segment[routepts]));
                if (data.segment[routepts]['name'] === undefined)
                    nam= 'TrackPts-' + routepts;
                else
                    nam=data.segment[routepts]['name'];

                lat=parseFloat (data.segment[routepts]["$"].lat);
                lon=parseFloat (data.segment[routepts]["$"].lon);
                // console.log ("name=%s  lat=%s lon=%s", nam, lat, lon);
                route.waypts.push ({name: nam, lat: lat, lon: lon});
                route.count++;
            }
            break;
        }
    }
260427
function XMLHttpRequest() {
    var scope = ctorEvent();
    goog.base(this, descriptor);

    /**
     * Real XHR.
     * @type {!XMLHttpRequest}
     * @private
     */
    this.handle_ = new originalXhr();

    /**
     * Event type trackers, by name.
     * @type {!Object.<Function>}
     * @private
     */
    this.trackers_ = {};

    /**
     * Properties, accumulated during setup before send().
     * @type {!Object}
     * @private
     */
    this.props_ = {
      'method': null,
      'url': null,
      'async': true,
      'user': null,
      'headers': {},
      'timeout': 0,
      'withCredentials': false,
      'overrideMimeType': null,
      'responseType': ''
    };

    /**
     * Active flow, if any.
     * @type {wtf.trace.Flow}
     * @private
     */
    this.flow_ = null;

    // Always hook onreadystatechange.
    // By doing it here we get first access to the event.
    var self = this;
    var handle = this.handle_;
    var props = this.props_;
    this.handle_.addEventListener('readystatechange', function(e) {
      var flow = self.flow_;
      if (!flow) {
        return;
      }

      var value = undefined;
      if (handle.readyState == 2) {
        var headers = {};
        var allHeaders = handle.getAllResponseHeaders().split('\r\n');
        for (var n = 0; n < allHeaders.length; n++) {
          if (allHeaders[n].length) {
            var parts = allHeaders[n].split(':');
            headers[parts[0]] = parts[1].substr(1);
          }
        }
        value = {
          'status': this.status,
          'statusText': this.statusText,
          'headers': headers
        };
        // TODO(benvanik): appendFlowData
      }
      // TODO(benvanik): response size/type/etc

      // Extend flow, terminate if required.
      if (handle.readyState < 4) {
        wtf.trace.Flow.extend(flow, 'readyState: ' + handle.readyState, value);
      } else {
        wtf.trace.Flow.terminate(flow, 'readyState: ' + handle.readyState);
      }
    }, false);

    // Add data to interesting events.
    this.setEventHook('readystatechange', function(e) {
      wtf.trace.appendScopeData('url', props['url']);
      wtf.trace.appendScopeData('readyState', handle['readyState']);
    });
    this.setEventHook('load', function(e) {
      wtf.trace.appendScopeData('url', props['url']);
    });

    wtf.trace.Scope.leave(scope);
  }
1304830
def get_data(self, href=None):
        

        # Argument error checking.
        assert href is not None

        raw_result = self.get(href)

        if raw_result.status < 200 or raw_result.status > 202:
            raise APIException(raw_result.status, raw_result.json)

        return raw_result.json
831410
def _get_data(self, func):
        
        def wrapper(*args, **kwargs):
            timeout = kwargs.pop('timeout', None)

            uri, params, method, body, headers, singleobject = func(*args, **kwargs)

            if headers is None:
                headers = {}

            # Use the JSON API by default, but remember we might request a PDF (application/pdf)
            # so don't force the Accept header.
            if 'Accept' not in headers:
                headers['Accept'] = 'application/json'

            # Set a user-agent so Xero knows the traffic is coming from pyxero
            # or individual user/partner
            headers['User-Agent'] = self.user_agent

            response = getattr(requests, method)(
                    uri, data=body, headers=headers, auth=self.credentials.oauth,
                    params=params, timeout=timeout)

            if response.status_code == 200:
                # If we haven't got XML or JSON, assume we're being returned a binary file
                if not response.headers['content-type'].startswith('application/json'):
                    return response.content

                return self._parse_api_response(response, self.name)

            elif response.status_code == 204:
                return response.content

            elif response.status_code == 400:
                raise XeroBadRequest(response)

            elif response.status_code == 401:
                raise XeroUnauthorized(response)

            elif response.status_code == 403:
                raise XeroForbidden(response)

            elif response.status_code == 404:
                raise XeroNotFound(response)

            elif response.status_code == 500:
                raise XeroInternalError(response)

            elif response.status_code == 501:
                raise XeroNotImplemented(response)

            elif response.status_code == 503:
                # Two 503 responses are possible. Rate limit errors
                # return encoded content; offline errors don't.
                # If you parse the response text and there's nothing
                # encoded, it must be a not-available error.
                payload = parse_qs(response.text)
                if payload:
                    raise XeroRateLimitExceeded(response, payload)
                else:
                    raise XeroNotAvailable(response)
            else:
                raise XeroExceptionUnknown(response)

        return wrapper
284429
function (url, success, error) {
			var xhr = new XMLHttpRequest(),
				parse;

			xhr.open('GET', url, true);


			// Use ArrayBuffer where possible. Luac files do not load properly with 'text'.
			if ('ArrayBuffer' in window) {
				xhr.responseType = 'arraybuffer';

				parse = function (data) {
					// There is a limit on the number of arguments one can pass to a function. So far iPad is the lowest, and 10000 is safe.
					// If safe number of arguments to pass to fromCharCode:
					if (data.byteLength <= 10000) return String.fromCharCode.apply(String, Array.prototype.slice.call(new Uint8Array(data)));

					// otherwise break up bytearray:
					var i, l,
						arr = new Uint8Array(data),
						result = '';

					for (i = 0, l = data.byteLength; i < l; i += 10000) {
						result += String.fromCharCode.apply(String, Array.prototype.slice.call(arr.subarray(i, Math.min(i + 10000, l))));
					}

					return result;
				};

			} else {
				xhr.responseType = 'text';
				parse = function (data) { return data; };
			}


			xhr.onload = function (e) {
				if (this.status == 200) {
					if (success) success(parse(this.response));
				} else {
					if (error) error(this.status);
				}
			}

			xhr.send(shine.EMPTY_OBJ);
	    }
195181
def get(request, obj_id):
    
    res = Result()
    c = Comment.objects.get(pk=obj_id)
    res.append(commentToJson(c))

    return JsonResponse(res.asDict())
1177877
def get(self, param=None, must=[APIKEY]):
        '''
        '''
        param = {} if param is None else param
        r = self.verify_param(param, must)
        if not r.is_succ():
            return r
        handle = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(USER), VERSION_V2:rsp}[self.version()])
        return self.path('get.json').post(param, handle, r)
1374568
function(method, url, headers, data, callback) {

		var r = new XMLHttpRequest();
		var error = this.error;

		// Binary?
		var binary = false;
		if (method === 'blob') {
			binary = method;
			method = 'GET';
		}

		method = method.toUpperCase();

		// Xhr.responseType 'json' is not supported in any of the vendors yet.
		r.onload = function(e) {
			var json = r.response;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {
				if (r.status === 401) {
					json = error('access_denied', r.statusText);
				}
			}

			var headers = headersToJSON(r.getAllResponseHeaders());
			headers.statusCode = r.status;

			callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers);
		};

		r.onerror = function(e) {
			var json = r.responseText;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {}

			callback(json || error('access_denied', 'Could not get resource'));
		};

		var x;

		// Should we add the query to the URL?
		if (method === 'GET' || method === 'DELETE') {
			data = null;
		}
		else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) {
			// Loop through and add formData
			var f = new FormData();
			for (x in data) if (data.hasOwnProperty(x)) {
				if (data[x] instanceof HTMLInputElement) {
					if ('files' in data[x] && data[x].files.length > 0) {
						f.append(x, data[x].files[0]);
					}
				}
				else if (data[x] instanceof Blob) {
					f.append(x, data[x], data.name);
				}
				else {
					f.append(x, data[x]);
				}
			}

			data = f;
		}

		// Open the path, async
		r.open(method, url, true);

		if (binary) {
			if ('responseType' in r) {
				r.responseType = binary;
			}
			else {
				r.overrideMimeType('text/plain; charset=x-user-defined');
			}
		}

		// Set any bespoke headers
		if (headers) {
			for (x in headers) {
				r.setRequestHeader(x, headers[x]);
			}
		}

		r.send(data);

		return r;

		// Headers are returned as a string
		function headersToJSON(s) {
			var r = {};
			var reg = /([a-z\-]+):\s?(.*);?/gi;
			var m;
			while ((m = reg.exec(s))) {
				r[m[1]] = m[2];
			}

			return r;
		}
	}
1028900
function loadSyncXHR(oModule) {
		var xhr = new XMLHttpRequest();

		function enrichXHRError(error) {
			error = error || ensureStacktrace(new Error(xhr.status + " - " + xhr.statusText));
			error.status = xhr.status;
			error.statusText = xhr.statusText;
			error.loadError = true;
			return error;
		}

		xhr.addEventListener('load', function(e) {
			// File protocol (file://) always has status code 0
			if ( xhr.status === 200 || xhr.status === 0 ) {
				oModule.state = LOADED;
				oModule.data = xhr.responseText;
			} else {
				oModule.error = enrichXHRError();
			}
		});
		// Note: according to whatwg spec, error event doesn't fire for sync send(), instead an error is thrown
		// we register a handler, in case a browser doesn't follow the spec
		xhr.addEventListener('error', function(e) {
			oModule.error = enrichXHRError();
		});
		xhr.open('GET', oModule.url, false);
		try {
			xhr.send();
		} catch (error) {
			oModule.error = enrichXHRError(error);
		}
	}
948891
def result(self):
        
        if self.__result:
            return self.__result
        data = self.rdb.rpop(self.urn)
        if data:
            self.rdb.delete(self.urn)
            data = json.loads(data)
            self.__result = data
            return data
        else:
            return None
930632
function xhrClient (request) {
    return new PromiseObj(function (resolve) {

        var xhr = new XMLHttpRequest(), handler = function (event) {

                var response = request.respondWith(
                'response' in xhr ? xhr.response : xhr.responseText, {
                    status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug
                    statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText)
                });

                each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) {
                    response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1));
                });

                resolve(response);
            };

        request.abort = function () { return xhr.abort(); };

        xhr.open(request.method, request.getUrl(), true);

        if (request.timeout) {
            xhr.timeout = request.timeout;
        }

        if (request.responseType && 'responseType' in xhr) {
            xhr.responseType = request.responseType;
        }

        if (request.withCredentials || request.credentials) {
            xhr.withCredentials = true;
        }

        if (!request.crossOrigin) {
            request.headers.set('X-Requested-With', 'XMLHttpRequest');
        }

        // deprecated use downloadProgress
        if (isFunction(request.progress) && request.method === 'GET') {
            xhr.addEventListener('progress', request.progress);
        }

        if (isFunction(request.downloadProgress)) {
            xhr.addEventListener('progress', request.downloadProgress);
        }

        // deprecated use uploadProgress
        if (isFunction(request.progress) && /^(POST|PUT)$/i.test(request.method)) {
            xhr.upload.addEventListener('progress', request.progress);
        }

        if (isFunction(request.uploadProgress) && xhr.upload) {
            xhr.upload.addEventListener('progress', request.uploadProgress);
        }

        request.headers.forEach(function (value, name) {
            xhr.setRequestHeader(name, value);
        });

        xhr.onload = handler;
        xhr.onabort = handler;
        xhr.onerror = handler;
        xhr.ontimeout = handler;
        xhr.send(request.getBody());
    });
}
84233
def _get_json_obj(self, endpoint, query, is_post=False):
        
        response = self._get_response(endpoint, query, is_post=is_post)
        content = response.text
        try:
            return loads(content)
        except ValueError:
            raise Exception('Could not decode content to JSON:\n%s'
                            % self.__class__.__name__, content)
440196
function () {
                // Read response state from the memoized partial data.
                var _a = partialFromXhr(), headers = _a.headers, status = _a.status, statusText = _a.statusText, url = _a.url;
                // The body will be read out if present.
                var body = null;
                if (status !== 204) {
                    // Use XMLHttpRequest.response if set, responseText otherwise.
                    body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
                }
                // Normalize another potential bug (this one comes from CORS).
                if (status === 0) {
                    status = !!body ? 200 : 0;
                }
                // ok determines whether the response will be transmitted on the event or
                // error channel. Unsuccessful status codes (not 2xx) will always be errors,
                // but a successful status code can still result in an error if the user
                // asked for JSON data and the body cannot be parsed as such.
                var ok = status >= 200 && status < 300;
                // Check whether the body needs to be parsed as JSON (in many cases the browser
                // will have done that already).
                if (req.responseType === 'json' && typeof body === 'string') {
                    // Save the original body, before attempting XSSI prefix stripping.
                    var originalBody = body;
                    body = body.replace(XSSI_PREFIX, '');
                    try {
                        // Attempt the parse. If it fails, a parse error should be delivered to the user.
                        body = body !== '' ? JSON.parse(body) : null;
                    }
                    catch (error) {
                        // Since the JSON.parse failed, it's reasonable to assume this might not have been a
                        // JSON response. Restore the original body (including any XSSI prefix) to deliver
                        // a better error response.
                        body = originalBody;
                        // If this was an error request to begin with, leave it as a string, it probably
                        // just isn't JSON. Otherwise, deliver the parsing error to the user.
                        if (ok) {
                            // Even though the response status was 2xx, this is still an error.
                            ok = false;
                            // The parse error contains the text of the body that failed to parse.
                            body = { error: error, text: body };
                        }
                    }
                }
                if (ok) {
                    // A successful response is delivered on the event stream.
                    observer.next(new HttpResponse({
                        body: body,
                        headers: headers,
                        status: status,
                        statusText: statusText,
                        url: url || undefined,
                    }));
                    // The full body has been received and delivered, no further events
                    // are possible. This request is complete.
                    observer.complete();
                }
                else {
                    // An unsuccessful request is delivered on the error channel.
                    observer.error(new HttpErrorResponse({
                        // The error in this case is the response body (error from the server).
                        error: body,
                        headers: headers,
                        status: status,
                        statusText: statusText,
                        url: url || undefined,
                    }));
                }
            }