|
NMEAParser
NMEA Parser Library - Monte Variakojis @VisualGPS
|
This class will parse NMEA data, store its data and report that it has received data. More...
#include <NMEAParser.h>
Public Member Functions | |
| CNMEAParser () | |
| virtual | ~CNMEAParser () |
| void | ResetData (void) |
| Resets or clears all NMEA data to a known default value. More... | |
| CNMEAParserData::ERROR_E | GetGPGGA (CNMEAParserData::GGA_DATA_T &sentenseData) |
| Places a copy of the GPGGA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGPGSV (CNMEAParserData::GSV_DATA_T &sentenseData) |
| Places a copy of the GPGSV data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGPGSA (CNMEAParserData::GSA_DATA_T &sentenseData) |
| Places a copy of the GPGSA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGPRMC (CNMEAParserData::RMC_DATA_T &sentenseData) |
| Places a copy of the GPRMC data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGNGSA (CNMEAParserData::GSA_DATA_T &sentenseData) |
| Places a copy of the GNGSA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGLGSV (CNMEAParserData::GSV_DATA_T &sentenseData) |
| Places a copy of the GLGSV data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGLGSA (CNMEAParserData::GSA_DATA_T &sentenseData) |
| Places a copy of the GLGSA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetQZGSV (CNMEAParserData::GSV_DATA_T &sentenseData) |
| Places a copy of the QZGSV data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetQZGSA (CNMEAParserData::GSA_DATA_T &sentenseData) |
| Places a copy of the QZGSA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetBDGSV (CNMEAParserData::GSV_DATA_T &sentenseData) |
| Places a copy of the BDGSV data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetBDGSA (CNMEAParserData::GSA_DATA_T &sentenseData) |
| Places a copy of the QZGSA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGAGGA (CNMEAParserData::GGA_DATA_T &sentenseData) |
| Places a copy of the GAGGA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGAGSA (CNMEAParserData::GSA_DATA_T &sentenseData) |
| Places a copy of the GAGSA data into sentenseData. More... | |
| CNMEAParserData::ERROR_E | GetGARMC (CNMEAParserData::RMC_DATA_T &sentenseData) |
| Places a copy of the GARMC data into sentenseData. More... | |
| Public Member Functions inherited from CNMEAParserPacket | |
| CNMEAParserPacket () | |
| ~CNMEAParserPacket () | |
| CNMEAParserData::ERROR_E | ProcessNMEABuffer (char *pData, size_t nBufferSize) |
| Parses pData for NMEA data. More... | |
| void | Reset (void) |
| Reset the parser. More... | |
| virtual void | OnError (CNMEAParserData::ERROR_E nError, char *pCmd) |
| This method is called whenever there is a parsing error. More... | |
Protected Member Functions | |
| virtual CNMEAParserData::ERROR_E | ProcessRxCommand (char *pCmd, char *pData) |
| This method is redefined from CNMEAParserPacket::ProcessRxCommand(char *pCmd, char *pData) More... | |
| virtual void | DataAccessSemaphoreLock (void) |
| This method will invoke a semaphore lock (mutex) for data access. More... | |
| virtual void | DataAccessSemaphoreUnlock (void) |
| This method will invoke a semaphore unlock (mutex) for data access. More... | |
| Protected Member Functions inherited from CNMEAParserPacket | |
| virtual void | TimeTag (void) |
| This method is called when receiving the start of message of the NMEA packet. More... | |
Private Attributes | |
| CNMEASentenceGGA | m_GPGGA |
| GPGGA Specific sentence data. More... | |
| CNMEASentenceGSV | m_GPGSV |
| GPGSV Satellite message (GPS) More... | |
| CNMEASentenceGSA | m_GPGSA |
| GPGSA GNSS DOP and active satellites. More... | |
| CNMEASentenceRMC | m_GPRMC |
| GPRMC Recommended minimum data for GPS. More... | |
| CNMEASentenceGGA | m_GAGGA |
| GAGGA Specific sentence data. More... | |
| CNMEASentenceGSA | m_GAGSA |
| GAGSA GNSS DOP and active satellites. More... | |
| CNMEASentenceRMC | m_GARMC |
| GARMC Recommended minimum data for GPS. More... | |
| CNMEASentenceGSA | m_GNGSA |
| GNGSA GNSS DOP and active satellites (usually GPS and GLONASS but can be GLONASS only) More... | |
| CNMEASentenceGSV | m_GLGSV |
| GLGSV Satellite message (GLONASS) More... | |
| CNMEASentenceGSA | m_GLGSA |
| GLGSA GNSS DOP and active satellites. More... | |
| CNMEASentenceGSV | m_QZGSV |
| QZGSV Satellite message (BeiDou) More... | |
| CNMEASentenceGSA | m_QZGSA |
| QZGSA GNSS DOP and active satellites. More... | |
| CNMEASentenceGSV | m_BDGSV |
| BDGSV Satellite message (QZSS) More... | |
| CNMEASentenceGSA | m_BDGSA |
| BDGSA GNSS DOP and active satellites. More... | |
This class will parse NMEA data, store its data and report that it has received data.
Definition at line 42 of file NMEAParser.h.
| CNMEAParser::CNMEAParser | ( | ) |
Definition at line 29 of file NMEAParser.cpp.
|
virtual |
Definition at line 34 of file NMEAParser.cpp.
|
inlineprotectedvirtual |
This method will invoke a semaphore lock (mutex) for data access.
Redefine this method if you will be access this class from different threads.
Definition at line 188 of file NMEAParser.h.
|
inlineprotectedvirtual |
This method will invoke a semaphore unlock (mutex) for data access.
Redefine this method if you will be access this class from different threads.
Definition at line 195 of file NMEAParser.h.
| CNMEAParserData::ERROR_E CNMEAParser::GetBDGSA | ( | CNMEAParserData::GSA_DATA_T & | sentenseData | ) |
Places a copy of the QZGSA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 146 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetBDGSV | ( | CNMEAParserData::GSV_DATA_T & | sentenseData | ) |
Places a copy of the BDGSV data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSV object to place the data into. |
Definition at line 138 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGAGGA | ( | CNMEAParserData::GGA_DATA_T & | sentenseData | ) |
Places a copy of the GAGGA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGGA object to place the data into. |
Definition at line 154 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGAGSA | ( | CNMEAParserData::GSA_DATA_T & | sentenseData | ) |
Places a copy of the GAGSA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 162 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGARMC | ( | CNMEAParserData::RMC_DATA_T & | sentenseData | ) |
Places a copy of the GARMC data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 170 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGLGSA | ( | CNMEAParserData::GSA_DATA_T & | sentenseData | ) |
Places a copy of the GLGSA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 114 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGLGSV | ( | CNMEAParserData::GSV_DATA_T & | sentenseData | ) |
Places a copy of the GLGSV data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSV object to place the data into. |
Definition at line 106 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGNGSA | ( | CNMEAParserData::GSA_DATA_T & | sentenseData | ) |
Places a copy of the GNGSA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 98 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGPGGA | ( | CNMEAParserData::GGA_DATA_T & | sentenseData | ) |
Places a copy of the GPGGA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGGA object to place the data into. |
Definition at line 66 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGPGSA | ( | CNMEAParserData::GSA_DATA_T & | sentenseData | ) |
Places a copy of the GPGSA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 82 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGPGSV | ( | CNMEAParserData::GSV_DATA_T & | sentenseData | ) |
Places a copy of the GPGSV data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSV object to place the data into. |
Definition at line 74 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetGPRMC | ( | CNMEAParserData::RMC_DATA_T & | sentenseData | ) |
Places a copy of the GPRMC data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 90 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetQZGSA | ( | CNMEAParserData::GSA_DATA_T & | sentenseData | ) |
Places a copy of the QZGSA data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSA object to place the data into. |
Definition at line 130 of file NMEAParser.cpp.
| CNMEAParserData::ERROR_E CNMEAParser::GetQZGSV | ( | CNMEAParserData::GSV_DATA_T & | sentenseData | ) |
Places a copy of the QZGSV data into sentenseData.
| sentenseData | reference to a CNMEASentenceGSV object to place the data into. |
Definition at line 122 of file NMEAParser.cpp.
|
protectedvirtual |
This method is redefined from CNMEAParserPacket::ProcessRxCommand(char *pCmd, char *pData)
| pCmd | Pointer to the NMEA command string |
| pData | Comma separated data that belongs to the command |
Implements CNMEAParserPacket.
Definition at line 178 of file NMEAParser.cpp.
| void CNMEAParser::ResetData | ( | void | ) |
Resets or clears all NMEA data to a known default value.
Definition at line 38 of file NMEAParser.cpp.
|
private |
BDGSA GNSS DOP and active satellites.
Definition at line 64 of file NMEAParser.h.
|
private |
BDGSV Satellite message (QZSS)
Definition at line 63 of file NMEAParser.h.
|
private |
GAGGA Specific sentence data.
Definition at line 51 of file NMEAParser.h.
|
private |
GAGSA GNSS DOP and active satellites.
Definition at line 52 of file NMEAParser.h.
|
private |
GARMC Recommended minimum data for GPS.
Definition at line 53 of file NMEAParser.h.
|
private |
GLGSA GNSS DOP and active satellites.
Definition at line 58 of file NMEAParser.h.
|
private |
GLGSV Satellite message (GLONASS)
Definition at line 57 of file NMEAParser.h.
|
private |
GNGSA GNSS DOP and active satellites (usually GPS and GLONASS but can be GLONASS only)
Definition at line 55 of file NMEAParser.h.
|
private |
GPGGA Specific sentence data.
Definition at line 46 of file NMEAParser.h.
|
private |
GPGSA GNSS DOP and active satellites.
Definition at line 48 of file NMEAParser.h.
|
private |
GPGSV Satellite message (GPS)
Definition at line 47 of file NMEAParser.h.
|
private |
GPRMC Recommended minimum data for GPS.
Definition at line 49 of file NMEAParser.h.
|
private |
QZGSA GNSS DOP and active satellites.
Definition at line 61 of file NMEAParser.h.
|
private |
QZGSV Satellite message (BeiDou)
Definition at line 60 of file NMEAParser.h.


public static final class ExposureValues.ExposureSettings
extends java.lang.Object
| Modifier and Type | Field and Description |
|---|---|
static int |
DEC_ES_CONFORM_IMAGE
The image must conform to the auto-exposure requirements, if not, it's rejected
|
static int |
DEC_ES_CONFORM_TRIES
The number of time it will attempt to conform
|
static int |
DEC_ES_EXPOSURE_METHOD
Deprecated.
Exposure method to use
|
static int |
DEC_ES_FIXED_EXP
If exposure mode is FIXED, what is the exposure
|
static int |
DEC_ES_FIXED_FRAME_RATE
If exposure mode is FIXED, what is the frame rate (fixed, has no effect)
|
static int |
DEC_ES_FIXED_GAIN
If exposure mode is FIXED, what is the gain
|
static int |
DEC_ES_FRAME_RATE
Deprecated.
Frame rate to use - fixed cannot be changed
|
static int |
DEC_ES_MAX_EXP
This is the maximum exposure allowed to use
|
static int |
DEC_ES_MAX_GAIN
This is the maximum gain allowed to use
|
static int |
DEC_ES_SPECULAR_EXCLUSION
Deprecated.
Specular exclusion value to use
|
static int |
DEC_ES_SPECULAR_LIMIT
Deprecated.
If specular exclusion is set, what is the limit
|
static int |
DEC_ES_SPECULAR_SAT
Deprecated.
If specular exclusion is set, what is the saturation value
|
static int |
DEC_ES_TARGET_ACCEPT_GAP
How close to the target while value must image be
|
static int |
DEC_ES_TARGET_PERCENTILE
The percentile the white target value should be at
|
static int |
DEC_ES_TARGET_VALUE
Target white value in image to try and achieve
|
| Constructor and Description |
|---|
ExposureSettings() |
public static final int DEC_ES_EXPOSURE_METHOD
public static final int DEC_ES_TARGET_VALUE
public static final int DEC_ES_TARGET_PERCENTILE
public static final int DEC_ES_TARGET_ACCEPT_GAP
public static final int DEC_ES_MAX_EXP
public static final int DEC_ES_MAX_GAIN
public static final int DEC_ES_FRAME_RATE
public static final int DEC_ES_CONFORM_IMAGE
public static final int DEC_ES_CONFORM_TRIES
public static final int DEC_ES_SPECULAR_EXCLUSION
public static final int DEC_ES_SPECULAR_SAT
public static final int DEC_ES_SPECULAR_LIMIT
public static final int DEC_ES_FIXED_EXP
public static final int DEC_ES_FIXED_GAIN
public static final int DEC_ES_FIXED_FRAME_RATE


BrainBot is easy to download, configure, and run
BrainBot can liven up any conversation with conversation starters and helpful tools
BrainBot's source code is entirely visible on GitHub
All commands and configuration options are documented on the BrainBot wiki


{% extends 'base.html' %} {% load custom_tags %} {% load static %} {% load socialaccount %} {% load tz %} {% comment %} Copyright 2021, Institute for Systems Biology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. {% endcomment %} {% block header %} {% endblock %} {% block link_page_name %}user-details{% endblock %} {% block page_name %}user-details{% endblock %} {% block content %}
| Name | {{ user_details.first_name }} {{ user_details.last_name }} | {% else %}User Name | {{ user_details.username }} | {% endif %}
| {{ user_details.email }} | |||
| Last Login | {{ user_details.last_login }} |
Apply for "cloud credits" and your own Google Cloud project by submitting a request here.
Go to the Google Cloud Console.


Copyright © 2014 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.
The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This document is published as a snapshot of the XMLHttpRequest Living Standard.
If you wish to make comments regarding this document in a manner that is tracked by the W3C, please submit them via using our public bug database, or please send comments to<EMAIL_ADDRESS>(archived) with [XHR] at the start of the subject line.
The W3C Web Applications Working Group is the W3C working group responsible for this specification's progress along the W3C Recommendation track. This specification is the 26 May 2014 Editor's Draft.
Publication as an Editor's Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
Work on this specification is also done at the WHATWG. The W3C Web Applications working group actively pursues convergence of XMLHttpRequest specification with the WHATWG.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
XMLHttpRequest
status
attributestatusText
attributegetResponseHeader()
methodgetAllResponseHeaders()
methodoverrideMimeType()
methodresponseType
attributeresponse
attributeresponseText
attributeresponseXML
attributeFormData
This section is non-normative.
The XMLHttpRequest
object is an API for
fetching resources.
The name of the object is XMLHttpRequest
for compatibility
with the Web, though each component of this name is potentially
misleading. First, the object supports any text based format, including
XML. Second, it can be used to make requests over both HTTP and HTTPS
(some implementations support protocols in addition to HTTP and HTTPS, but
that functionality is not covered by this specification). Finally, it
supports "requests" in a broad sense of the term as it pertains to HTTP;
namely all activity involved with HTTP requests or responses for the
defined HTTP methods.
Some simple code to do something with data from an XML document fetched over the network:
function processData(data) {
// taking care of data
}
function handler() {
if(this.readyState == this.DONE) {
if(this.status == 200 &&
this.responseXML != null &&
this.responseXML.getElementById('test').textContent) {
// success!
processData(this.responseXML.getElementById('test').textContent);
return;
}
// something went wrong
processData(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
Or if you want to check the status of a document on the server:
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == this.DONE)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}
The XMLHttpRequest
object was initially defined as part of
the WHATWG's HTML effort long after Microsoft shipped an implementation.
It moved to the W3C in 2006. Extensions (e.g. progress events and
cross-origin requests) to XMLHttpRequest
were developed in a
separate draft (XMLHttpRequest Level 2) until end of 2011, at which point
the two drafts were merged and XMLHttpRequest
became a single
entity again from a standards perspective. Since 2012, the development work
required for getting the spec finalized has taken place both in the WHATWG and
in the W3C Web Applications working group.
XMLHttpRequest Level 1, the first stable Recommendation track
specification for the XMLHttpRequest
feature, standardizes all
parts of XMLHttpRequest
that are compatibly supported across
major implementations. Implementors should be able to rely on this
specification and the
related test suite
in order to create interoperable implementations.
Some features included in the WHATWG specification are left out because they are not yet widely implemented or used. These features are:
data:
URLs.URLSearchParams
type in send()
method.append()
defined in the interface FormData
.Historical discussion can be found in the following mailing list archives:
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this specification are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
This specification relies on several underlying specifications.
A conforming user agent must support the algorithms of the Cross-Origin Resource Sharing specification. [CORS]
A conforming user agent must
support at least the subset of the functionality defined in DOM4 that
this specification relies upon, such as various exceptions and
EventTarget
. [DOM]
A conforming user agent must support at least the serialize concept from DOM Parsing and Serialization. [DOMPS]
A conforming user agent must
support at least the subset of the functionality defined in Encoding Standard that
this specification relies upon, such as the utf-8
encoding
.
[ENCODING]
A conforming user agent must
support at least the subset of the functionality defined in File API that
this specification relies upon, such as the Blob
and
File
interfaces. [FILEAPI]
A conforming user agent must
support at least the subset of the functionality defined in HTML that
this specification relies upon, such as the basics of the
Window
object and serializing a Document
object. [HTML]
A conforming user agent must support some version of the HTTP protocol. Requirements regarding HTTP are made throughout the specification. [HTTP]
A conforming user agent must support the Progress Events specification. [PROGRESSEVENTS]
A conforming user agent must support the
ArrayBuffer
and
ArrayBufferView
objects.
[TYPEDARRAY]
A conforming user agent must support the URL parsing algorithm of the URL specification. [URL]
A conforming user agent must also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WEBIDL]
A conforming user agent must be a conforming XML processor that reports violations of namespace well-formedness. [XML] [XMLNS]
It uses the typographic conventions from HTML. [HTML]
User agents, Working Groups, and other interested parties are
strongly encouraged to discuss new features on a relevant public
forum, preferably
<EMAIL_ADDRESS>If this
is for some reason not possible prefix the extension in some way. E.g. if
company Foo wants to add a proprietary method bar()
it could
be named fooBar()
to prevent clashes with a potential
non-proprietary method bar()
.
The term user credentials for the purposes of this
specification means cookies, HTTP authentication, and client-side SSL
certificates. Specifically it does not refer to proxy authentication or
the Origin
header.
[COOKIES]
XMLHttpRequest
[NoInterfaceObject] interface XMLHttpRequestEventTarget : EventTarget { // event handlers attribute EventHandler onloadstart; attribute EventHandler onprogress; attribute EventHandler onabort; attribute EventHandler onerror; attribute EventHandler onload; attribute EventHandler ontimeout; attribute EventHandler onloadend; }; interface XMLHttpRequestUpload : XMLHttpRequestEventTarget { }; enum XMLHttpRequestResponseType { "", "arraybuffer", "blob", "document", "json", "text" }; [Constructor] interface XMLHttpRequest : XMLHttpRequestEventTarget { // event handler attribute EventHandler onreadystatechange; // states const unsigned short UNSENT = 0; const unsigned short OPENED = 1; const unsigned short HEADERS_RECEIVED = 2; const unsigned short LOADING = 3; const unsigned short DONE = 4; readonly attribute unsigned short readyState; // request void open(ByteString method, ScalarValueString url); void open(ByteString method, ScalarValueString url, boolean async, optional ScalarValueString? username = null, optional ScalarValueString? password = null); void setRequestHeader(ByteString header, ByteString value); attribute unsigned long timeout; attribute boolean withCredentials; readonly attribute XMLHttpRequestUpload upload; void send(optional (ArrayBufferView or Blob or Document or ScalarValueString or FormData)? data = null); void abort(); // response readonly attribute unsigned short status; readonly attribute ByteString statusText; ByteString? getResponseHeader(ByteString header); ByteString getAllResponseHeaders(); void overrideMimeType(DOMString mime); attribute XMLHttpRequestResponseType responseType; readonly attribute any response; readonly attribute DOMString responseText; readonly attribute Document? responseXML; };
Each XMLHttpRequest
object has a unique, associated
XMLHttpRequestUpload
object.
If the JavaScript global environment is a
worker environment, implementations must act as if
Document
and Document?
in the above IDL were not
exposed. I.e. send()
is not overloaded with it
and responseXML
always returns null (as
required by its definition, too).
Each XMLHttpRequest
object has its own
task source. Namely, the
XMLHttpRequest
task source.
The XMLHttpRequest
object has an associated
settings object.
client = new XMLHttpRequest()
XMLHttpRequest
object.
The
XMLHttpRequest()
constructor must run these steps:
Let xhr be a new XMLHttpRequest
object.
Set xhr's settings object to the relevant settings object for the global object of xhr's interface object.
Return xhr.
An XMLHttpRequest
object must not be garbage collected if
its state is OPENED and the
send()
flag is set, its state is
HEADERS_RECEIVED, or
its state is LOADING, and
one of the following is true:
It has one or more
event listeners
registered whose type is
readystatechange
,
progress
,
abort
,
error
,
load
,
timeout
, or
loadend
.
The upload complete flag is unset and the associated
XMLHttpRequestUpload
object has one or more
event listeners
registered whose type is
progress
,
abort
,
error
,
load
,
timeout
, or
loadend
.
If an XMLHttpRequest
object is garbage collected while its
connection is still open, the user agent must terminate the request.
The following are the
event handlers (and their corresponding
event handler event types)
that must be supported on objects implementing an interface that inherits
from XMLHttpRequestEventTarget
as attributes:
| event handler | event handler event type |
|---|---|
onloadstart
| loadstart
|
onprogress
| progress
|
onabort
| abort
|
onerror
| error
|
onload
| load
|
ontimeout
| timeout
|
onloadend
| loadend
|
The following is the
event handler
(and its corresponding
event handler event type) that must be
supported as attribute solely by the
XMLHttpRequest
object:
| event handler | event handler event type |
|---|---|
onreadystatechange
| readystatechange |
client . readyState
Returns the current state.
The XMLHttpRequest
object can be in several states. The
readyState
attribute must return the current state, which must be one of the
following values:
UNSENT
(numeric value 0)The object has been constructed.
OPENED
(numeric value 1)The open()
method has been successfully invoked.
During this state request headers can be set using
setRequestHeader()
and the request can be made using the
send()
method.
HEADERS_RECEIVED
(numeric value 2)All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
LOADING
(numeric value 3)The response entity body is being received.
DONE
(numeric value 4)The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
The send()
flag indicates
that the send()
method has
been invoked. It is initially unset and is used during the
OPENED state.
The error flag indicates some type of network error or fetch termination. It is initially unset.
Each XMLHttpRequest
object has the following
request-associated concepts:
request method,
request URL,
author request headers,
request entity body,
source origin,
referrer source,
synchronous flag,
upload complete flag, and
upload events flag.
The author request headers is a list of HTTP header names and corresponding header values. Comparisons against the HTTP header names must be done in a case-insensitive manner. Initially it must be empty.
The request entity body must initially be null.
The synchronous flag, upload complete flag, and upload events flag must be initially unset.
To terminate the request run these steps:
Set the error flag.
Cancel any instance of the fetch algorithm opened by this object.
If there are any tasks from
the object's XMLHttpRequest
task source in one of the
task queues, then remove them.
open()
methodclient . open(method, url [, async = true [, username = null [, password = null]]])
Sets the request method, request URL, and synchronous flag.
Throws a "SyntaxError
" exception if
either method is not a valid HTTP method or
url cannot be parsed.
Throws a "SecurityError
" exception
if method is a case-insensitive match for
CONNECT
, TRACE
or TRACK
.
Throws an "InvalidAccessError
"
exception if async is false, the
JavaScript global environment is a
document environment, and either the
timeout
attribute is not
zero, the
withCredentials
attribute is true, or the
responseType
attribute is not the empty string.
Developers must not pass false for the
async argument when the
JavaScript global environment is a
document environment as it has detrimental effects to
the end user's experience. User agents are strongly encouraged to warn about such usage in
developer tools and may experiment with
throwing a
"InvalidAccessError
" exception when it occurs so the
feature can eventually be removed from the platform.
The
open(method, url, async, username, password)
method must run these steps:
If settings object's
responsible document is not
fully active,
throw an
"InvalidStateError
" exception.
Set base to settings object's API base URL.
Set source origin to settings object's origin.
Set referrer source to the settings object's API referrer source's URL if settings object's API referrer source is a document, and settings object's API referrer source otherwise.
If method does not match the Method
token production, throw a
"SyntaxError
" exception.
If method is a case-insensitive match for CONNECT
,
DELETE
, GET
, HEAD
, OPTIONS
,
POST
, PUT
, TRACE
, or TRACK
, subtract
0x20 from each byte in the range 0x61 (ASCII a) to 0x7A (ASCII z).
If it does not match any of the above, it is passed through literally, including in the final request.
If method is a case-sensitive match for CONNECT
,
TRACE
, or TRACK
,
throw a
"SecurityError
" exception.
Allowing these methods would pose a security risk. [HTTPVERBSEC]
Let parsed URL be the result of parsing url with base.
If parsed URL is failure,
throw a
"SyntaxError
" exception.
If the async argument is omitted, set async to true, and set username and password to null.
Due to unfortunate legacy constraints, passing
undefined
for the async argument is treated differently
from async being omitted.
If parsed URL's relative flag is set, run these substeps:
If async is false, the
JavaScript global environment is a
document environment, and either the
timeout
attribute value is not zero, the
withCredentials
attribute value is
true, or the responseType
attribute
value is not the empty string,
throw an
"InvalidAccessError
" exception.
After all, a request can be ongoing at this point.
Set variables associated with the object as follows:
Set request method to method.
Set request URL to parsed URL.
If async is false, set the synchronous flag.
Set author request headers to the empty list.
Unset the send()
flag.
Set response entity body to null.
Set arraybuffer response entity body to null.
Set blob response entity body to null.
Set document response entity body to null.
Set JSON response entity body to null.
Set text response entity body to null.
If the state is not OPENED, run these substeps:
Change the state to OPENED.
Fire an event named readystatechange
.
setRequestHeader()
methodclient . setRequestHeader(header, value)
Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value.
Throws an "InvalidStateError
"
exception if the state is not
OPENED or if the
send()
flag is set.
Throws a "SyntaxError
" exception if
header is not a valid HTTP header field name or if
value is not a valid HTTP header field value.
As indicated in the algorithm below certain headers cannot
be set and are left up to the user agent. In addition there are certain
other headers the user agent will take control of if they are not set by
the author as indicated at the end of the
send()
method section.
For non same origin requests using the HTTP
GET
method a preflight request is made when headers other
than Accept
and Accept-Language
are set.
The
setRequestHeader(header, value)
method must run these steps:
If the state is not
OPENED,
throw an
"InvalidStateError
" exception.
If the send()
flag is set,
throw an
"InvalidStateError
" exception.
If header does not match the
field-name production,
throw a
"SyntaxError
" exception.
If value does not match the
field-value production,
throw a
"SyntaxError
" exception.
An empty string represents an empty header field value.
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
… or if the start of header is a case-insensitive
match for Proxy-
or Sec-
(including when
header is just Proxy-
or Sec-
).
The above headers are controlled by the user agent to
let it control those aspects of transport. This guarantees data
integrity to some extent. Header names starting with Sec-
are not allowed to be set to allow new headers to be minted that are
guaranteed not to come from XMLHttpRequest
.
If header is not in the author request headers list, append header with its associated value to the list and terminate these steps.
If header is in the author request headers list, append
",
", followed by U+0020, followed by value, to the
value of the header matching header.
The XMLHttpRequest standard intentionally constraints the use of HTTP here in line with contemporary implementations.
Some simple code demonstrating what happens when setting the same header twice:
// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'demo.cgi');
client.setRequestHeader('X-Test', 'one');
client.setRequestHeader('X-Test', 'two');
client.send();
// …results in the following header being sent:
X-Test: one, two
timeout
attributeclient . timeout
Can be set to a time in milliseconds. When set to a non-zero value
will cause fetching to
terminate after the given time has passed. When the time has passed, the request has
not yet completed, and the synchronous flag is unset, a
timeout
event will then be
dispatched,
or a "TimeoutError
" exception will be
thrown otherwise
(for the send()
method).
When set: throws an
"InvalidAccessError
" exception if
the synchronous flag is set and the
JavaScript global environment is a
document environment.
The
timeout
attribute must return its value. Initially its value must be zero.
Setting the timeout
attribute must run these steps:
If the
JavaScript global environment is a
document environment and the
synchronous flag is set,
throw an
"InvalidAccessError
" exception.
Set its value to the new value.
This implies that the
timeout
attribute can be
set while fetching is in
progress. If that occurs it will still be measured relative to the start
of fetching.
withCredentials
attributeclient . withCredentials
True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.
When set: throws an
"InvalidStateError
" exception if the
state is not UNSENT or
OPENED, or if
the send()
flag is set.
When set: throws an
"InvalidAccessError
" exception if
the synchronous flag is set and the
JavaScript global environment is a
document environment.
The
withCredentials
attribute must return its value. Initially its value must be false.
Setting the
withCredentials
attribute must run these steps:
If the state is not
UNSENT or
OPENED,
throw an
"InvalidStateError
" exception.
If the send()
flag is set,
throw an
"InvalidStateError
" exception.
If the
JavaScript global environment is a
document environment and the
synchronous flag is set,
throw an
"InvalidAccessError
" exception.
Set the
withCredentials
attribute's value to the given value.
The
withCredentials
attribute has no effect when
fetching
same-origin
resources.
upload
attributeclient . upload
Returns the associated XMLHttpRequestUpload
object. It can be used to gather transmission information when data is
transferred to a server.
The
upload
attribute must return the associated
XMLHttpRequestUpload
object.
As indicated earlier, each XMLHttpRequest
object has an associated XMLHttpRequestUpload
object.
send()
methodclient . send([data = null])
Initiates the request. The optional argument provides the
request entity body. The argument is ignored if
request method is GET
or
HEAD
.
Throws an "InvalidStateError
"
exception if the state is not
OPENED or if the
send()
flag is set.
The send(data)
method must run these steps:
If the state is not
OPENED,
throw an
"InvalidStateError
" exception.
If the send()
flag is set,
throw an
"InvalidStateError
" exception.
If the request method is GET
or
HEAD
, set data to null.
If data is null, do not include a request entity body and go to the next step.
Otherwise, let encoding be null, mime type be null, and then follow these rules, depending on data:
ArrayBufferView
Let the request entity body be the raw data represented by data.
Blob
If the object's
type
attribute is not the empty string let mime type be its
value.
Let the request entity body be the raw data represented by data.
Let encoding be "UTF-8
".
If data is an HTML document, let
mime type be "text/html
", or let mime type be
"application/xml
" otherwise. Then append ";charset=UTF-8
" to
mime type.
Let the request entity body be data, serialized, converted to Unicode, and utf-8 encoded. Re-throw any exception serializing throws.
If data cannot be
serialized, an
"InvalidStateError
" exception is thrown.
Let encoding be "UTF-8
".
Let mime type be "text/plain;charset=UTF-8
".
Let the request entity body be data, utf-8 encoded.
FormData
Let the request entity body be the result of running
the
multipart/form-data
encoding algorithm
with data as form data set and with
utf-8 as the
explicit character encoding.
Let mime type be the concatenation of
"multipart/form-data;
",
a U+0020 SPACE character,
"boundary=
", and the
multipart/form-data
boundary string
generated by the
multipart/form-data
encoding algorithm.
If a Content-Type
header is in
author request headers and its value is a
valid MIME type that has a
charset
parameter whose value is not a case-insensitive
match for encoding, and encoding
is not null, set all the charset
parameters of that
Content-Type
header to encoding.
If no Content-Type
header is in
author request headers and mime type is
not null, append a Content-Type
header with value
mime type to author request headers.
If the synchronous flag is set, release the storage mutex.
Unset the error flag, upload complete flag and upload events flag.
If there is no request entity body or if it is empty, set the upload complete flag.
If the synchronous flag is unset and one or more
event listeners are registered on the XMLHttpRequestUpload
object, set the upload events flag.
If the synchronous flag is unset, run these substeps:
Set the send()
flag.
Fire a progress event named loadstart
.
If the upload complete flag is unset,
fire a progress event named loadstart
on the XMLHttpRequestUpload
object.
Return the send()
method call, but continue running the steps in this algorithm.
These are the same-origin request steps.
Fetch the request URL from origin source origin, using referrer source as override referrer source, with the synchronous flag set if the synchronous flag is set, using HTTP method request method, taking into account the request entity body, list of author request headers, and the rules listed at the end of this section.
While making the request also follow the same-origin request event rules.
The
send()
method call will
now be returned by virtue of this algorithm ending.
Make upload progress notifications.
While processing the request, as data becomes available and when the user interferes with the request, queue tasks to update the response entity body and follow the same-origin request event rules.
These are the cross-origin request steps.
Make a cross-origin request, passing these as parameters:
withCredentials
attribute's value is false.
While making the request also follow the cross-origin request event rules.
The
send()
method call will
now be returned by virtue of this algorithm ending.
While processing the request, as data becomes available and when the end user interferes with the request, queue tasks to update the response entity body and follow the cross-origin request event rules.
If the user agent allows the end user to configure a proxy it
should modify the request appropriately; i.e., connect
to the proxy host instead of the origin server, modify the
Request-Line
and send Proxy-Authorization
headers as specified.
If the user agent supports HTTP Authentication and
Authorization
is not in the list
of author request headers, it should
consider requests originating from the XMLHttpRequest
object
to be part of the protection space that includes the accessed URIs and
send Authorization
headers and
handle 401 Unauthorized
requests appropriately.
If authentication fails,
source origin and the
request URL are same origin,
Authorization
is not in the list
of author request headers,
request URL's
username is
the empty string and request URL's
password is
null, user agents should prompt the end user for their username and
password.
Otherwise, if authentication fails, user agents must not prompt the end user for their username and password. [HTTPAUTH]
Unfortunately end users are prompted because of legacy content constraints. However, when possible this behavior is prohibited, as it is bad UI. E.g. that is why the same origin restriction is made above.
If the user agent supports HTTP State Management it
should persist, discard and send cookies (as received
in the Set-Cookie
response header, and sent in the
Cookie
header) as applicable.
[COOKIES]
If the user agent implements a HTTP cache it should
respect Cache-Control
headers in
author request headers
(e.g. Cache-Control: no-cache
bypasses the cache). It
must not send Cache-Control
or
Pragma
request headers automatically unless the end user
explicitly requests such behavior (e.g. by reloading the page).
For 304 Not Modified
responses that are a result of a
user agent generated conditional request the user agent
must act as if the server gave a 200 OK
response with the appropriate content. The user agent
must allow author request headers to override automatic cache
validation (e.g. If-None-Match
or
If-Modified-Since
), in which case
304 Not Modified
responses must be passed through.
[HTTP]
If the user agent implements server-driven content-negotiation
it must follow these constraints for the
Accept
and Accept-Language
request headers:
Both headers must not be modified if they are in author request headers.
If not in author request headers,
Accept-Language
with an appropriate value should be appended
to it.
If not in author request headers, Accept
with value */*
must be appended to it.
Responses must have the content-encodings automatically decoded. [HTTP]
Besides the author request headers, user agents
should not include additional request headers other than those mentioned
above or other than those authors are not allowed to set using
setRequestHeader()
.
This ensures that authors have a predictable API.
send()
methodThe same-origin request event rules are as follows:
Terminate these steps.
If the redirect violates infinite loop precautions this is a network error.
Otherwise, run these steps:
Set the request URL to the
URL conveyed by the
Location
header.
If the source origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.
Otherwise, follow the cross-origin request steps and terminate the steps for this algorithm.
HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end users to be notified of certain kinds of automatic redirections.
This is an abort error.
In case of DNS errors, TLS negotiation failure, or other type of network errors, this is a network error. Do not request any kind of end user interaction.
This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.
timeout
is not 0
and since the request started the amount of milliseconds specified by
timeout
has passedThis is a timeout error.
The cross-origin request event rules are as follows:
Terminate these steps.
This is a network error.
This is an abort error.
timeout
is not 0
and since the request started the amount of milliseconds specified by
timeout
has passedThis is a timeout error.
When something is said to be a network error run the
request error steps for exception
"NetworkError
" and
event error
.
When something is said to be an abort error run the
request error steps for exception
"AbortError
" and event
abort
.
When something is said to be a timeout error run the
request error steps for exception
"TimeoutError
" and event
timeout
.
When something is said to be a request error for exception exception and event event run these steps:
Change the state to DONE.
If the synchronous flag is set, throw an exception exception.
Fire an event named readystatechange
.
At this point it is clear that the synchronous flag is unset.
If the upload complete flag is unset, follow these substeps:
Set the upload complete flag.
Fire a progress event named
progress
on the XMLHttpRequestUpload
object.
Fire a progress event named
event on the XMLHttpRequestUpload
object.
Fire a progress event named
loadend
on the XMLHttpRequestUpload
object.
Fire a progress event named progress
.
Fire a progress event named event.
Fire a progress event named loadend
.
When it is said to switch to the HEADERS_RECEIVED state run these steps:
Change the state to HEADERS_RECEIVED.
Fire an event named readystatechange
.
When it is said to switch to the LOADING state run these steps:
Change the state to LOADING.
Fire an event named readystatechange
.
When it is said to switch to the DONE state run these steps:
If the synchronous flag is set, update the response entity body.
Unset the synchronous flag.
Change the state to DONE.
Fire an event named readystatechange
.
Fire a progress event named progress
.
Fire a progress event named load
.
Fire a progress event named loadend
.
When it is said to make progress notifications, while the
download is progressing, queue a task to
fire a progress event named progress
about every 50ms or for every byte received, whichever is least
frequent.
When it is said to make upload progress notifications run these steps:
While the request entity body is being transmitted and the
upload complete flag is unset,
queue a task to
fire a progress event named progress
on
the XMLHttpRequestUpload
object about every 50ms or for
every byte transmitted, whichever is least frequent.
If the request entity body has been fully transmitted (irrespective of whether the server has started transmitting a response or the status code of such a response) and the upload complete flag is still unset, queue a task to run these substeps:
Set the upload complete flag.
Fire a progress event named progress
on the XMLHttpRequestUpload
object.
Fire a progress event named load
on the XMLHttpRequestUpload
object.
Fire a progress event named loadend
on the XMLHttpRequestUpload
object.
abort()
methodclient . abort()
The abort()
method must run
these steps:
If the state is UNSENT,
OPENED with the
send()
flag being unset, or
DONE go to the next step.
Otherwise, run these substeps:
Change the state to DONE.
Unset the send()
flag.
Fire an event named readystatechange
.
If the upload complete flag is false run these substeps:
Set the upload complete flag to true.
Fire a progress event named progress
on the XMLHttpRequestUpload
object.
Fire a progress event named abort
on the XMLHttpRequestUpload
object.
Fire a progress event named loadend
on the XMLHttpRequestUpload
object.
Fire a progress event named progress
.
Fire a progress event named abort
.
Fire a progress event named loadend
.
Change the state to UNSENT.
No readystatechange
event is dispatched.
A response header is a HTTP response header transmitted before the response entity body. [HTTP]
This excludes trailer fields ("trailers").
status
attributeclient . status
Returns the HTTP status code.
The
status
attribute must return the result of running these
steps:
If the error flag is set, return 0.
Return the HTTP status code.
statusText
attributeclient . statusText
Returns the HTTP status text.
The
statusText
attribute must return the result of running these steps:
If the error flag is set, return the empty string.
Return the HTTP status text.
getResponseHeader()
methodclient . getResponseHeader(header)
Returns the header field value from the response of which the
field name matches header, unless the field name is
Set-Cookie
or Set-Cookie2
.
The
getResponseHeader(header)
method must run these steps:
If the error flag is set, return null.
If header is a case-insensitive match for
Set-Cookie
or Set-Cookie2
, return null.
If header is a case-insensitive match for multiple response headers, return the values of these headers as a single concatenated string separated from each other by a U+002C COMMA U+0020 SPACE character pair.
If header is a case-insensitive match for a single response header, return the value of that header.
Return null.
The Cross-Origin Resource Sharing specification filters
response headers exposed by
getResponseHeader()
for cross-origin requests.
[CORS]
For the following script:
var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(client.getResponseHeader("Content-Type"));
}
}
The print()
function will get to process something
like:
text/plain; charset=UTF-8
getAllResponseHeaders()
methodclient . getAllResponseHeaders()
Returns all headers from the response, with the exception of those
whose field name is Set-Cookie
or
Set-Cookie2
.
The
getAllResponseHeaders()
method must run these steps:
If the error flag is set, return the empty string.
Return all response headers, excluding headers that are a
case-insensitive match for Set-Cookie
or
Set-Cookie2
, as a single string, with each header line
separated by a U+000D CR U+000A LF pair, excluding the status line, and
with each header name and header value separated by a
U+003A COLON U+0020 SPACE pair.
The Cross-Origin Resource Sharing specification filters
response headers exposed by
getAllResponseHeaders()
for cross-origin requests.
[CORS]
For the following script:
var client = new XMLHttpRequest();
client.open("GET", "narwhals-too.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(this.getAllResponseHeaders());
}
}
The print()
function will get to process something
like:
Date: Sun, 24 Oct 2004 04:58:38 GMT
Server: Apache/1.3.31 (Unix)
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8
The response MIME type is the
MIME type the Content-Type
header contains excluding any
parameters and
converted to ASCII lowercase, or null if
the response header can not be parsed or was omitted. The
override MIME type is initially null
and can get a value if
overrideMimeType()
is invoked. Final MIME type is the
override MIME type unless that is null in which case it is
the response MIME type.
The response charset is the value of
the charset
parameter of the Content-Type
header
or null if there was no charset
parameter or the header could
not be parsed or was omitted. The
override charset is initially null and
can get a value if overrideMimeType()
is invoked.
Final charset is the
override charset unless
that is null in which case it is the response charset.
The response entity body is the fragment of the entity body of the response received so far (LOADING) or the complete entity body of the response (DONE). If the response does not have an entity body, the response entity body is null.
The response entity body is updated as part
of the send()
method and reset by the
open()
method.
The
arraybuffer response entity body
is either an ArrayBuffer
representing
the response entity body or null. If the
arraybuffer response entity body is null, let it be the return value of the
following algorithm:
If the response entity body is null, return an empty
ArrayBuffer
object.
Return an ArrayBuffer
object representing the response entity body.
The
blob response entity body is either a
Blob
representing the
response entity body or null. If the blob response entity body
is null, set it to the return value of the following algorithm:
If the response entity body is null, return an empty
Blob
object.
Return a Blob
object
representing the response entity body.
The document response entity body is either a document representing the response entity body or null. If the document response entity body is null, set it to the return value of the following algorithm:
If the response entity body is null, return null.
If the JavaScript global environment is a worker environment, return null.
If final MIME type is not null,
text/html
, text/xml
,
application/xml
, or does not end in
+xml
, return null.
If responseType
is
the empty string and final MIME type is
text/html
, return null.
This is restricted to
responseType
being
"document
" in order to prevent breaking legacy
content.
If final MIME type is text/html
, run these
substeps:
Let charset be the final charset.
If charset is null, prescan the first 1024 bytes of the response entity body and if that does not terminate unsuccessfully then let charset be the return value.
If charset is null, set charset to utf-8.
Let document be a document that represents the result parsing response entity body following the rules set forth in the HTML Standard for an HTML parser with scripting disabled and a known definite encoding charset. [HTML]
Flag document as an HTML document.
Otherwise, let document be a document that represents the result of parsing the response entity body following the rules set forth in the XML specifications. If that fails (unsupported character encoding, namespace well-formedness error, etc.), return null. [XML] [XMLNS]
Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.
If charset is null, set charset to utf-8.
Set document's encoding to charset.
Set document's content type to final MIME type.
Set document's URL to request URL.
Set document's origin to source origin.
Return document.
The JSON response entity body is either a JavaScript value representing the response entity body. If the JSON response entity body is null, set it to the return value of the following algorithm:
Let JSON text be the result of running utf-8 decode on byte stream response entity body.
Return the result of invoking the initial value of the parse
property of the JSON
object defined in JavaScript, with
JSON text as its only argument, or null if that function
throws an exception. [ECMASCRIPT]
The text response entity body is either a string representing the response entity body or null. If the text response entity body is null, set it to the return value of the following algorithm:
If the response entity body is null, return the empty string.
Let charset be the final charset.
If responseType
is
the empty string, charset is null, and
final MIME type is either null, text/xml
,
application/xml
or ends in +xml
, use the
rules set forth in the XML specifications to determine the encoding. Let
charset be the determined encoding.
[XML] [XMLNS]
This is restricted to
responseType
being
the empty string to keep the non-legacy
responseType
value
"text
" simple.
If charset is null, set charset to utf-8.
Return the result of running decode on byte stream response entity body using fallback encoding charset.
Authors are strongly encouraged to always encode their resources using utf-8.
overrideMimeType()
methodclient . overrideMimeType(mime)
Sets the Content-Type
header for the response to
mime.
Throws an "InvalidStateError
"
exception if the state is
LOADING or
DONE.
Throws a "SyntaxError
" exception if
mime is not a valid media type.
The
overrideMimeType(mime)
method must run these steps:
If the state is
LOADING or
DONE,
throw an
"InvalidStateError
" exception.
If parsing mime analogously to the value of
the Content-Type
header fails,
throw a
"SyntaxError
" exception.
If mime is successfully parsed, set override MIME type to its MIME type, excluding any parameters, and converted to ASCII lowercase.
If a charset
parameter is successfully parsed, set
override charset to its value.
responseType
attributeclient . responseType
[ = value ]
Returns the response type.
Can be set to change the response type. Values are:
the empty string (default),
"arraybuffer
",
"blob
",
"document
",
"json
", and
"text
".
When set: setting to "document
" is ignored if the
JavaScript global environment is a
worker environment
When set: throws an
"InvalidStateError
" exception if the
state is LOADING or
DONE.
When set: throws an
"InvalidAccessError
" exception if the
synchronous flag is set and the
JavaScript global environment is a
document environment.
The
responseType
attribute must return its value. Initially its value must be the empty
string.
Setting the
responseType
attribute must run these steps:
If the state is
LOADING or
DONE,
throw an
"InvalidStateError
" exception.
If the
JavaScript global environment is a
document environment and the
synchronous flag is set,
throw an
"InvalidAccessError
" exception.
If the
JavaScript global environment is a
worker environment and the given
value is "document
", terminate these steps.
Set the
responseType
attribute's value to the given value.
response
attributeclient . response
Returns the response entity body.
The
response
attribute must return the result of running these
steps:
responseType
is the empty string or "text
"If the state is not LOADING or DONE, return the empty string.
If the error flag is set, return the empty string.
Return the text response entity body.
If the state is not DONE, return null.
If the error flag is set, return null.
responseType
is
"arraybuffer
"Return the arraybuffer response entity body.
responseType
is
"blob
"Return the blob response entity body.
responseType
is
"document
"Return the document response entity body.
responseType
is
"json
"Return the JSON response entity body.
responseText
attributeclient . responseText
Returns the text response entity body.
Throws an "InvalidStateError
"
exception if
responseType
is not
the empty string or "text
".
The
responseText
attribute must return the result of running these
steps:
If
responseType
is not
the empty string or "text
",
throw an
"InvalidStateError
" exception.
If the state is not LOADING or DONE, return the empty string.
If the error flag is set, return the empty string.
Return the text response entity body.
responseXML
attributeclient . responseXML
Returns the document response entity body.
Throws an "InvalidStateError
"
exception if
responseType
is not
the empty string or "document
".
The
responseXML
attribute must return the result of running these steps:
If
responseType
is not
the empty string or "document
",
throw an
"InvalidStateError
" exception.
If the state is not DONE, return null.
If the error flag is set, return null.
Return the document response entity body.
The
responseXML
attribute
has XML in its name for historical reasons. It also returns HTML resources
as documents.
This section is non-normative.
The following events are dispatched on XMLHttpRequest
and/or XMLHttpRequestUpload
objects:
| Event name | Interface | Dispatched when… |
|---|---|---|
readystatechange |
Event |
The readyState attribute changes
value, except when it changes to UNSENT.
|
loadstart |
ProgressEvent |
The request starts. |
progress |
ProgressEvent |
Transmitting data. |
abort |
ProgressEvent |
The request has been aborted. For instance, by invoking the
abort() method. |
error |
ProgressEvent |
The request has failed. |
load |
ProgressEvent |
The request has successfully completed. |
timeout |
ProgressEvent |
The author specified timeout has passed before the request completed. |
loadend |
ProgressEvent |
The request has completed (either in success or failure). |
FormData
[Constructor(optional HTMLFormElement form)] interface FormData { void append(ScalarValueString name, Blob value, optional ScalarValueString filename); void append(ScalarValueString name, ScalarValueString value); };
If the JavaScript global environment is a
worker environment, FormData
must be
exposed to JavaScript as if the constructor part of the
IDL reads [Constructor]
(i.e. has no arguments).
The FormData
object represents an ordered list of
entries. Each
entry consists of a
name and a
value.
For the purposes of interaction with other algorithms, an
entry's type is "string" if
value is a string and "file" otherwise. If
an entry's type is "file", its filename is the
value of entry's
value's
name
attribute.
fd = new FormData([form])
Returns a new FormData
object, optionally initialized with the
entries from form (if given).
fd . append(name, value [, filename])
The
FormData(form)
constructor must run these steps:
Let fd be a new FormData
object.
If form is given, set fd's entries to the result of constructing the form data set for form.
Return fd.
The
append(name, value, filename)
method must run these steps:
Let entry be a new entry.
Set entry's name to name.
If value is a Blob
, set
value to a new File
object whose
name
attribute value is
"blob
".
If value is a File
and
filename is given, set value's
name
attribute value to
filename.
Set entry's value to value.
The editor would like to thank Addison Phillips, Adrian Bateman, Ahmed Kamel, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Andrea Marchesini, Asbjørn Ulsberg, Boris Zbarsky, Björn Höhrmann, Cameron McCormack, Chris Marrin, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Andersson, David Flanagan, David Håsäther, David Levin, Dean Jackson, Denis Sureau, Dominik Röttsches, Doug Schepers, Douglas Livingstone, Elliott Sprehn, Elliotte Harold, Eric Lawrence, Eric Uhrhane, Erik Arvidsson Erik Dahlström, Feras Moussa, Geoffrey Sneddon, Gideon Cohn, Glenn Adams, Gorm Haug Eriksen, Håkon Wium Lie, Hallvord R. M. Steen, Henri Sivonen, Huub Schaeks, Ian Davis, Ian Hickson, Ivan Herman, Jarred Nicholls, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, 송정기 (Jungkee Song), 呂康豪 (Kang-Hao Lu), Karl Dubost, Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mark S. Miller, Martin Hassman, Mohamed Zergaoui, Ms2ger, Odin Hørthe Omdal, Olli Pettay, Pawel Glowacki, Peter Michaux, Philip Taylor, Robin Berjon, Rune F. Halvorsen, Ruud Steltenpool, Sergiu Dumitriu, Sigbjørn Finne, Simon Pieters, Stewart Brodie, Sunava Dutta, Takeshi Yoshino, Thomas Roessler, Tom Magliery, Travis Leithead Yehuda Katz, and Zhenbin Xu for their contributions to this specification.
Special thanks to the Microsoft employees who first implemented the
XMLHttpRequest
interface, which was first widely
deployed by the Windows Internet Explorer browser.
Special thanks also to the WHATWG for drafting an initial version of this specification in their Web Applications 1.0 document (now renamed to HTML). [HTML]
Special thanks to Anne van Kesteren who has provided nearly all the contents until he stepped down as a W3C editor and is now in succession providing discussions and contents as the editor of the XMLHttpRequest Living Standard in WHATWG which this version of the specification pursues convergence.
Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)


Basic Render test /w parallax
Texture chooser:
Javascript port of CubicVR 3D Engine by Charles J. Cliffe -
http://www.cubicvr.org/


{{ partial "header" . }} {{ $currentURL := .URL }}
What you were looking for was not here
We could not find the page you were looking for. This website was recently restructured so maybe a link went dead.


MR G. Ha! Steward, how are you, my old boy? How do things go on at home?
STEWARD. Bad enough, your honour; the magpie's dead!
MR G. Poor mag! so he's gone. How came he to die?
STEWARD. Overate himself, sir.
MR G. Did he indeed? A greedy dog. Why, what did he get that he liked so well?
STEWARD. Horseflesh; he died of eating horseflesh.
MR G. How came he to get so much horseflesh?
STEWARD. All your father's horses, sir.
MR G. What! are they dead, too?
STEWARD. Aye, sir; they died of overwork.
MR G. And why were they overworked?
STEWARD. To carry water, sir.
MR G. To carry water, and what were they carrying water for?
STEWARD. Sure, sir, to put out the fire.
MR G. Fire! what fire?
STEWARD. Your father's house is burned down to the ground.
MR G. My father's house burnt down! and how came it to be on fire?
STEWARD. I think sir, it must have been the torches.
MR G. Torches! what torches?
STEWARD. At your mother's funeral.
MR G. My mother dead?
STEWARD. Aye, poor lady, she never looked up after it.
MR G. After what?
STEWARD. The loss of your father.
MR G. My father gone, too?
STEWARD. Yes, poor gentleman, he took to his bed as soon as he heard of it.
MR G. Heard of what?
STEWARD. The bad news, an' it please your honour.
MR G. What? more miseries, more bad news!
STEWARD. Yes, sir, your bank has failed, your credit is lost and you're not worth a shilling in the world. I make bold, sir, to come and wait on you about it; for I thought you would like to hear the news.


{{{added}}}
HOME
Events
Games
Companies
{{#registered}}
{{name}}
{{{profile_img}}}
Profile
My Lists
{{#admin}}
Admin features
{{/admin}}
{{/registered}} {{#unregistered}}
Register
{{/unregistered}}
{{#games}} {{{.}}} {{/games}}
Options:
Add new list
Set the list's name
Delete a list
Set the list's name


Conditions
connection-closed
Signalled by the disconnect
function.
Disconnecting is the default action whenever an error occurs, so this signal can for example be handled to reconnect.
client
Client whose connection was closed
connection-failed
connect
.client
Client whose connection failederror
Reason for failure
connection-lost
Signalled when connection is lost.
Currently signalled when an error occurs during trying to receive a message from the server.
client
Client whose connection was lost
Macros
define-handler
((command class-spec prefix-var arguments-var) &body body)
Define handling for command
.
This is currently a convenience for specializing on the generic
function handle
. An example is the handler for PING
messages (which by default is the only handler specialization).
(define-handler (:ping client prefix arguments)
(send-pong client (first arguments)))
If you wanted to use a different variable-name for the client variable, you could also have written it as
(define-handler (:ping (client client) prefix arguments)
(send-pong client (first arguments)))
Generics
change-nick
(client new-nickname)
nickname
of client
connect
(client)
Connect and register client
with an IRC server.
This also sets up some of the slots, and opens the log-stream.
connected-p
(client)
t
if client
is connected, nil
otherwise.disconnect
(client &key message)
Send QUIT message to server, close the socket and close the log-stream.
Always signals connection-closed
.
handle
(command client prefix arguments)
Called by receive-message
after parsing the raw message.
Specialize on this function with the macro define-handler
for customizing
behaviour.
There is a default method that spits out the unhandled message
to *standard-output*
.
nickname
(client)
client
.receive-message
(client)
Read a message from connection, parse it,
handle
, and return a list with the following 3 elements:
- the raw prefix string, or
nil
if prefix wasn't present - command is a keyword with a name corresponding to the command from the RFC and
- parsed-parameters is a list of strings representing the arguments in the message.
If an error occurs during the reading, the client will be
disconnected, and connection-closed
will be signalled.
send-join
(client channel &key password)
send-privmsg
(client victim message)
message
to victim
, where victim
is either a
channel- or nick-name.socket
(client)
client
's socket.Functions
parse-prefix
(prefix)
Return a list of the components in prefix.
The elements of the list are as follows:
- servername or nickname as string
- username string, or
nil
- a hostname string, or
nil
send-raw-message
(client raw-message)
Send raw-message
and CRLF to the socket associated with client
.
Outside of the few send-* functions, this is what you have to use to send messages to the server.
Class
client
A client connection to an IRC server.
Valid initargs are:
:nickname
-- the nickname use when connecting (required):server
-- the hostname of the server to connect to as a string (required):port
-- the port to connect to as an integer (optional):username
-- the username to register with (optional):realname
-- the realname to register with (optional):password
-- the password to regiseter with (optional):log-pathname
-- pathname for packet-log pathname (optional)
Please note that you call connect
on a client
instance, rather than
having connect
return a client
instance.
nickname
Nickname of client (mandatory). Sent at beginning of connection, and bychange-nick
password
Password used during registration (optional)username
Username sent at beginning of connection. Defaults to nickname.realname
Realname sent at beginning of connection. Defaults to username.server
Address of the IRC serverport
Port of client connectionsocket
Socket of an active connectionlog-pathname
Pathname of log-filelog-stream
Stream of log-file


This inspection suggests to use Integer.compare()
, etc. static methods where more verbose or less efficient constructs are
used. For example, x > y ? 1 : x < y ? -1 : 0
or Integer.valueOf(x).compareTo(y)
could be
replaced with Integer.compare(x, y)
.
Double.compare
and Float.compare
methods appeared in Java 1.4, methods for other primitive types
are available since Java 1.7
New in 2017.2


| Link | Expectation |
|---|---|
| Normal | Should open and install 'Cycle Text and Detail' plugin |
| Missing title |
Should open and install 'Cycle Text and Detail' plugin but use cycle_text_and_detail.sh as title
|
| Empty title |
Should open and install 'Cycle Text and Detail' plugin but use cycle_text_and_detail.sh as title
|
| Unofficial repo | Should open and install test plugin but have additional warnings - and use full URL (not title) |


If you would like to cancel this session(s), open the dropdown menu for "Reason" and choose the most appropriate item. Click "Request that this Session be Cancelled
Requesting a session to be cancelled will result in this session being removed from your calendar. You can confirm this by doing the following.
[How to confirm]


NumReader
By Sergey Chernetsov
@sergerey
Lets go
{{ history.length }}
Options
Restrict vertical
Restrict horizontal
Simplify paths
Go nutz
{{ size }}
Brush size
Brush color
Save your design
Min 3 characters
Save as
{{ save.name }}
Load a save
{{ item.name }}
load


Introduction to K-Nearest-Neighbour Algorithm
The k-nearest neighbors (KNN) algorithm is a simple supervised machine learning algorithm that can be used to solve both classification and regression problems.
Machine learning algorithms can be classified broadly into two types, supervised algorithms and unsupervised algorithms.[For more details]
Classification algorithms are used to classify data instances and regression algorithms are used to estimate or predict real values for new data instances[For more details]
K Nearest Neighbor
The KNN algorithm assumes that similar things are near to eachother. Essentially, KNN algorithm finds the k nearest neighbours of a given data instance and chooses the class label with majority vote and assigns that class label to the data instance.
The K nearest neighbors and found by calculating the distance between the testing data point and the rest of the points in the dataset. The distance can be calculated by many different methods, but the most common method is Euclidean distance.
Other methods of calculating distance include: Euclidean Distance, Hamming distance, Minkowski distance, Kullback-Leiber (KL) divergence, BM25 etc


import { UniversalWeakMap } from "./universal-weak-map.js";
import { UniversalWeakMap } from "./universal-weak-map.js";
import {
brand,
globalKey,
forEachArrayMethod,
} from "./util.js";
When called with any number of arguments, this function returns an
object that inherits from tuple.prototype
and is guaranteed to be
===
any other tuple
object that has exactly the same items. In
computer science jargon, tuple
instances are “internalized” or just
“interned,” which allows for constant-time equality checking, and makes
it possible for tuple objects to be used as Map
or WeakMap
keys, or
stored in a Set
.
export default function tuple(...items) {
return intern(items);
}
Named imports work as well as default
imports.
export { tuple };
If this package is installed multiple times, there could be mutiple
implementations of the tuple
function with distinct tuple.prototype
objects, but the shared pool of tuple
objects must be the same across
all implementations. While it would be ideal to use the global
object, there’s no reliable way to get the global object across all JS
environments without using the Function
constructor, so instead we
use the global Array
constructor as a shared namespace.
const root = globalKey in Array
? Array[globalKey]
: def(Array, globalKey, new UniversalWeakMap, false);
function intern(array) {
let node = root;
Because we are building a tree of weak maps, the tree will not
prevent objects in tuples from being garbage collected, since the
tree itself will be pruned over time when the corresponding tuple
objects become unreachable. In addition to internalization, this
property is a key advantage of the immutable-tuple
package.
array.forEach(item => {
node = node.get(item) || node.set(item, new UniversalWeakMap);
});
If a tuple
object has already been created for exactly these items,
return that object again.
if (node.tuple) {
return node.tuple;
}
const t = Object.create(tuple.prototype);
Define immutable items with numeric indexes, and permanently fix the
.length
property.
array.forEach((item, i) => def(t, i, item, true));
def(t, "length", array.length, false);
Remember this new tuple
object so that we can return the same object
earlier next time.
return node.tuple = t;
}
Convenient helper for defining hidden immutable properties.
function def(obj, name, value, enumerable) {
Object.defineProperty(obj, name, {
value: value,
enumerable: !! enumerable,
writable: false,
configurable: false
});
return value;
}
Since the immutable-tuple
package could be installed multiple times
in an application, there is no guarantee that the tuple
constructor
or tuple.prototype
will be unique, so value instanceof tuple
is
unreliable. Instead, to test if a value is a tuple, you should use
tuple.isTuple(value)
.
function isTuple(that) {
return !! (that && that[brand] === true);
}
def(tuple.prototype, brand, true, false);
tuple.isTuple = isTuple;
function toArray(tuple) {
const array = [];
let i = tuple.length;
while (i--) array[i] = tuple[i];
return array;
}
Copy all generic non-destructive Array methods to tuple.prototype
.
This works because (for example) Array.prototype.slice
can be invoked
against any Array
-like object.
forEachArrayMethod((name, desc, mustConvertThisToArray) => {
const method = desc && desc.value;
if (typeof method === "function") {
desc.value = function (...args) {
const result = method.apply(
mustConvertThisToArray ? toArray(this) : this,
args
);
Of course, tuple.prototype.slice
should return a tuple
object,
not a new Array
.
return Array.isArray(result) ? intern(result) : result;
};
Object.defineProperty(tuple.prototype, name, desc);
}
});
Like Array.prototype.concat
, except for the extra effort required to
convert any tuple arguments to arrays, so that
tuple(1).concat(tuple(2), 3) === tuple(1, 2, 3)
const { concat } = Array.prototype;
tuple.prototype.concat = function (...args) {
return intern(concat.apply(toArray(this), args.map(
item => isTuple(item) ? toArray(item) : item
)));
};


--- --- Then you'll be... Slowly sanding down those rough edges Doing your job better and faster Have greater job satisfaction The shoulders I'm standing on


Thiruvananthapuram (or Trivandrum) is the capital of the southern Indian state of Kerala. It's distinguished by its British colonial architecture and many art galleries. It’s also home to Kuthira Malika (or Puthen Malika) Palace, adorned with carved horses and displaying collections related to the Travancore royal family, whose regional capital was here from the 18th–20th centuries.
Sree Padmanabhaswamy Temple
Napier Museum
Shangumugham Beach
Kuthira Malika


Ethan Zuckerman (born 1973) is an American media scholar, blogger, and Internet activist. He is the director of the MIT Center for Civic Media, Associate Professor of the Practice in Media Arts and Sciences at MIT and the author of the book "Rewire: Digital Cosmopolitans in the Age of Connection", which won the Zócalo Book Prize
Zuckerman is an Open Society Global Board member, and also sits on the board of directors of Ushahidi, Global Voices and the Ghanaian journalism training nonprofit, PenPlusBytes.
On July 1, 2016, Zuckerman was appointed Associate Professor of the Practice in Media Arts and Sciences at MIT.
He will talk about the digital connection between worldwide comic art and all forms of relevant industries.


Breakdown: Open Data 📊
This is the to the first of our series of breakdown talks. These sessions are meant to summarize various civic technology concepts. Our subject today is Open Data.
Resources and Shoutouts:
- Project open data: project-open-data.cio.gov/
- Data.gov: www.data.gov/open-gov/
- Sunlight Foundation: sunlightfoundation.com/
- My building doesn’t recycle: mybuildingdoesntrecycle.com/
- Govlab: Nepal Earthquake case study: odimpact.org/case-nepal-earthquake-recovery.html
- Cincinnati Open Data Portal: data.cincinnati-oh.gov/
- Chicago Open Data Portal: data.cityofchicago.org/
- Chi Hack Night: chihacknight.org/
Music Credit: Tumbleweeds by Monkey Warhol
Previous Feb 20, 2018
« We the Technologists 🏛
« We the Technologists 🏛
Mar 13, 2018 Next
Open Data in Chicago 🗂 »
Open Data in Chicago 🗂 »


The Container interface server two primary purposes:
- Looking up services that has been registered in the container.
- Starting and stopping the container and the services registered within the container.
Normally the Container interface is extended with an interface providing additional domain specific functionality.
For example, the Cache interface which specifies methods for insertion and retrieval of data. Inheriting
methods for starting, stopping and looking up services from the Container interface.
Containers can be arranged in a hierachy so services register in one container is available from child containers.
This is useful, for example, for sharing a single ThreadPool among multiple containers in order to reduce the number
of threads that need to be created.
Single Container
A single container is a container that has no parent or child containers.
Container Lifecycle
The container parses through five different phases:
- Initialized. This is the initial state of the container.
- Starting. The container is in the process of starting up, but has not fully completed startup of all services.
- Running. The container has been started with success (normal state).
- Shutdown. The shutdown method has been called on the container, and the container is in the process of shutting down all its services.
- Terminated. All services has been been shutdown. The container is fully shutdown and cannot be restarted
Initialized
Starting
Running
Shutdown
Terminated
Besides explicitly starting a container by calling .
All containers will be started automatically whenever methods are invoked.
For example, calls to #getService.
Looking up a service
Service registration
Containers
Build-in services
Build-in services a services that a available from a container without any user intervention.
There are 3 types of services that available from almost any container
ExecutorService, ScheduledExecutorService, ForkjoinExecutor.
If you want to provide your own services you can just override the existing services.
For example, lets
Hirachy Containers
Hic containers are.
If you arrange containers. Starting the parent container will first start the parent
container, after it has been fully started all of its child containers will be started.
When shutting down a parent container. The parent container container will first shutdown all
child containers (why wait on services in the child container being shutdown).
The only being that a parent is never terminated before all child containers are terminated
Lifecycle.... see for Lifecycle.hmtl for complete details
The lifecycle methods
For example, if you shutdown a container that has any children, all its
children will also be shutdown.
When a user tries to look up a service
If a specific service is not found in a container
it will automatically look in the parent container (if it has one). The parent
might look in its parent and so on.
Instead you create a parent container that is shared among all cache instances


 This pooch is a lover, not a hunter.
Bred solely to be companions, Shih Tzus are affectionate, happy, outgoing house dogs who love nothing more than to follow their people from room to room. Since ancient times, they’ve made themselves comfortable on the laps of people from all walks of life, even emperors!
In recent years, however, pet parents have started taking Shih Tzus off their laps and into dog sports, training them for obedience, rally, and agility competitions. They make great family pets who get along with other animals and even children, so long as kids know how to gently handle and play with a small pup.
If you’re looking for a small best buddy who can adapt to apartment living, join you on the couch for cuddles, and shower you with unconditional love, this may be the dog for you.
Source of information


Source code for torch._vmap_internals
import torch
import functools
from torch import Tensor
from typing import Any, Callable, Optional, Tuple, Union, List
from torch.utils._pytree import tree_flatten, tree_unflatten, _broadcast_to_and_flatten
import warnings
in_dims_t = Union[int, Tuple]
out_dims_t = Union[int, Tuple[int, ...]]
# Checks that all args-to-be-batched have the same batch dim size
def _validate_and_get_batch_size(
flat_in_dims: List[Optional[int]],
flat_args: List) -> int:
batch_sizes = [arg.size(in_dim) for in_dim, arg in zip(flat_in_dims, flat_args)
if in_dim is not None]
if batch_sizes and any([size != batch_sizes[0] for size in batch_sizes]):
raise ValueError(
f'vmap: Expected all tensors to have the same size in the mapped '
f'dimension, got sizes {batch_sizes} for the mapped dimension')
return batch_sizes[0]
def _num_outputs(batched_outputs: Union[Tensor, Tuple[Tensor, ...]]) -> int:
if isinstance(batched_outputs, tuple):
return len(batched_outputs)
return 1
# If value is a tuple, check it has length `num_elements`.
# If value is not a tuple, make a tuple with `value` repeated `num_elements` times
def _as_tuple(value: Any, num_elements: int, error_message_lambda: Callable[[], str]) -> Tuple:
if not isinstance(value, tuple):
return (value,) * num_elements
if len(value) != num_elements:
raise ValueError(error_message_lambda())
return value
# Creates BatchedTensors for every Tensor in arg that should be batched.
# Returns the (potentially) batched arguments and the batch_size.
def _create_batched_inputs(
in_dims: in_dims_t, args: Tuple, vmap_level: int, func: Callable) -> Tuple[Tuple, int]:
if not isinstance(in_dims, int) and not isinstance(in_dims, tuple):
raise ValueError(
f'vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): '
f'expected `in_dims` to be int or a (potentially nested) tuple '
f'matching the structure of inputs, got: {type(in_dims)}.')
if len(args) == 0:
raise ValueError(
f'vmap({_get_name(func)})(<inputs>): got no inputs. Maybe you forgot to add '
f'inputs, or you are trying to vmap over a function with no inputs. '
f'The latter is unsupported.')
flat_args, args_spec = tree_flatten(args)
flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec)
if flat_in_dims is None:
raise ValueError(
f'vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): '
f'in_dims is not compatible with the structure of `inputs`. '
f'in_dims has structure {tree_flatten(in_dims)[1]} but inputs '
f'has structure {args_spec}.')
for arg, in_dim in zip(flat_args, flat_in_dims):
if not isinstance(in_dim, int) and in_dim is not None:
raise ValueError(
f'vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): '
f'Got in_dim={in_dim} for an input but in_dim must be either '
f'an integer dimension or None.')
if isinstance(in_dim, int) and not isinstance(arg, Tensor):
raise ValueError(
f'vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): '
f'Got in_dim={in_dim} for an input but the input is of type '
f'{type(arg)}. We cannot vmap over non-Tensor arguments, '
f'please use None as the respective in_dim')
if in_dim is not None and (in_dim < 0 or in_dim >= arg.dim()):
raise ValueError(
f'vmap({_get_name(func)}, in_dims={in_dims}, ...)(<inputs>): '
f'Got in_dim={in_dim} for some input, but that input is a Tensor '
f'of dimensionality {arg.dim()} so expected in_dim to satisfy '
f'0 <= in_dim < {arg.dim()}.')
batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args)
# See NOTE [Ignored _remove_batch_dim, _add_batch_dim]
batched_inputs = [arg if in_dim is None else
torch._add_batch_dim(arg, in_dim, vmap_level) # type: ignore
for in_dim, arg in zip(flat_in_dims, flat_args)]
return tree_unflatten(batched_inputs, args_spec), batch_size
# Undos the batching (and any batch dimensions) associated with the `vmap_level`.
def _unwrap_batched(
batched_outputs: Union[Tensor, Tuple[Tensor, ...]],
out_dims: out_dims_t,
vmap_level: int, batch_size: int, func: Callable) -> Tuple:
num_outputs = _num_outputs(batched_outputs)
out_dims_as_tuple = _as_tuple(
out_dims, num_outputs,
lambda: f'vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must '
f'have one dim per output (got {num_outputs} outputs) of {_get_name(func)}.')
# NOTE [Ignored _remove_batch_dim, _add_batch_dim]
# There is something wrong with our type bindings for functions that begin
# with '_', see #40397.
if isinstance(batched_outputs, Tensor):
out_dim = out_dims_as_tuple[0]
return torch._remove_batch_dim(batched_outputs, vmap_level, batch_size, out_dim) # type: ignore
return tuple(torch._remove_batch_dim(out, vmap_level, batch_size, out_dim) # type: ignore
for out, out_dim in zip(batched_outputs, out_dims_as_tuple))
# Checks that `fn` returned one or more Tensors and nothing else.
# NB: A python function that return multiple arguments returns a single tuple,
# so we are effectively checking that `outputs` is a single Tensor or a tuple of
# Tensors.
def _validate_outputs(outputs: Any, func: Callable) -> None:
if isinstance(outputs, Tensor):
return
if not isinstance(outputs, tuple):
raise ValueError(f'vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return '
f'Tensors, got type {type(outputs)} as the return.')
for idx, output in enumerate(outputs):
if isinstance(output, Tensor):
continue
raise ValueError(f'vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return '
f'Tensors, got type {type(output)} for return {idx}.')
def _check_out_dims_is_int_or_int_tuple(out_dims: out_dims_t, func: Callable) -> None:
if isinstance(out_dims, int):
return
if not isinstance(out_dims, tuple) or \
not all([isinstance(out_dim, int) for out_dim in out_dims]):
raise ValueError(
f'vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be '
f'an int or a tuple of int representing where in the outputs the '
f'vmapped dimension should appear.')
def _get_name(func: Callable):
if hasattr(func, '__name__'):
return func.__name__
# Not all callables have __name__, in fact, only static functions/methods do.
# A callable created via functools.partial or an nn.Module, to name some
# examples, don't have a __name__.
return repr(func)
# vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors,
# sends those into func, and then unwraps the output BatchedTensors. Operations
# on BatchedTensors perform the batched operations that the user is asking for.
[docs]def vmap(func: Callable, in_dims: in_dims_t = 0, out_dims: out_dims_t = 0) -> Callable:
"""
vmap is the vectorizing map. Returns a new function that maps `func` over some
dimension of the inputs. Semantically, vmap pushes the map into PyTorch
operations called by `func`, effectively vectorizing those operations.
vmap is useful for handling batch dimensions: one can write a function `func`
that runs on examples and then lift it to a function that can take batches of
examples with `vmap(func)`. vmap can also be used to compute batched
gradients when composed with autograd.
.. warning::
torch.vmap is an experimental prototype that is subject to
change and/or deletion. Please use at your own risk.
.. note::
If you're interested in using vmap for your use case, please
`contact us! <https://github.com/pytorch/pytorch/issues/42368>`_
We're interested in gathering feedback from early adopters to inform
the design.
Args:
func (function): A Python function that takes one or more arguments.
Must return one or more Tensors.
in_dims (int or nested structure): Specifies which dimension of the
inputs should be mapped over. `in_dims` should have a structure
like the inputs. If the `in_dim` for a particular input is None,
then that indicates there is no map dimension. Default: 0.
out_dims (int or Tuple[int]): Specifies where the mapped dimension
should appear in the outputs. If `out_dims` is a Tuple, then it should
have one element per output. Default: 0.
Returns:
Returns a new "batched" function. It takes the same inputs as `func`,
except each input has an extra dimension at the index specified by `in_dims`.
It takes returns the same outputs as `func`, except each output has
an extra dimension at the index specified by `out_dims`.
.. warning:
vmap works best with functional-style code. Please do not perform any
side-effects in `func`, with the exception of in-place PyTorch operations.
Examples of side-effects include mutating Python data structures and
assigning values to variables not captured in `func`.
One example of using `vmap` is to compute batched dot products. PyTorch
doesn't provide a batched `torch.dot` API; instead of unsuccessfully
rummaging through docs, use `vmap` to construct a new function.
>>> torch.dot # [D], [D] -> []
>>> batched_dot = torch.vmap(torch.dot) # [N, D], [N, D] -> [N]
>>> x, y = torch.randn(2, 5), torch.randn(2, 5)
>>> batched_dot(x, y)
`vmap` can be helpful in hiding batch dimensions, leading to a simpler
model authoring experience.
>>> batch_size, feature_size = 3, 5
>>> weights = torch.randn(feature_size, requires_grad=True)
>>>
>>> def model(feature_vec):
>>> # Very simple linear model with activation
>>> return feature_vec.dot(weights).relu()
>>>
>>> examples = torch.randn(batch_size, feature_size)
>>> result = torch.vmap(model)(examples)
`vmap` can also help vectorize computations that were previously difficult
or impossible to batch. One example is higher-order gradient computation.
The PyTorch autograd engine computes vjps (vector-Jacobian products).
Computing a full Jacobian matrix for some function f: R^N -> R^N usually
requires N calls to `autograd.grad`, one per Jacobian row. Using `vmap`,
we can vectorize the whole computation, computing the Jacobian in a single
call to `autograd.grad`.
>>> # Setup
>>> N = 5
>>> f = lambda x: x ** 2
>>> x = torch.randn(N, requires_grad=True)
>>> y = f(x)
>>> I_N = torch.eye(N)
>>>
>>> # Sequential approach
>>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
>>> for v in I_N.unbind()]
>>> jacobian = torch.stack(jacobian_rows)
>>>
>>> # vectorized gradient computation
>>> def get_vjp(v):
>>> return torch.autograd.grad(y, x, v)
>>> jacobian = torch.vmap(get_vjp)(I_N)
.. note::
vmap does not provide general autobatching or handle variable-length
sequences out of the box.
"""
warnings.warn(
'torch.vmap is an experimental prototype that is subject to '
'change and/or deletion. Please use at your own risk. There may be '
'unexpected performance cliffs due to certain operators not being '
'implemented. To see detailed performance warnings please use '
'`torch._C._debug_only_display_vmap_fallback_warnings(True) '
'before the call to `vmap`.',
stacklevel=2)
return _vmap(func, in_dims, out_dims)
# A version of vmap but without the initial "experimental prototype" warning
def _vmap(func: Callable, in_dims: in_dims_t = 0, out_dims: out_dims_t = 0) -> Callable:
@functools.wraps(func)
def wrapped(*args):
_check_out_dims_is_int_or_int_tuple(out_dims, func)
vmap_level = torch._C._vmapmode_increment_nesting()
try:
batched_inputs, batch_size = _create_batched_inputs(in_dims, args, vmap_level, func)
batched_outputs = func(*batched_inputs)
_validate_outputs(batched_outputs, func)
return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func)
finally:
torch._C._vmapmode_decrement_nesting()
return wrapped