Provides an easy way to connect to an ATEM. If a valid IP address is provided, {@link Device#connect} will be called automatically.
@param [atemIpAddress] {String} The ip address of the ATEM to connect to.
@constructor Device
168357
function Device(atemIpAddress){
	var self = this, atem = this;
	if (!(self instanceof Device))
		throw new Error('use "new" to construct an ATEM Device');

	/** Create a UDP v4 socket */
	var socket;

	/** Call the constructor of EventEmitter */
	events.EventEmitter.call(this);

	/**
	 * The ip address of the ATEM
	 * @name Device#ip
	 * @type String
	 */
	Object.defineProperty(this, 'ip', {
		set: function (ipString) {
			if (net.isIPv4(ipString)) {
				if (atem.state !== ConnectionState.closed) {
					atem.disconnect(function() {
						ip = ipString;
						atem.connect();
						atem.emit('addressChange', ip);
					});
				} else {
					ip = ipString;
					atem.emit('addressChange', ip);
				}
			}
			else {
				const err = new Error('Invalid IP address: ' + ipString);
				this.emit('error', err);
			}
		},
		get: function () { return ip }
	});

	/**
	 * The current state of the connection.
	 * For more information about the possible values see {@link ConnectionState}
	 *
	 * @name Device#state
	 * @type {ConnectionState}
	 */
	Object.defineProperty(this, 'state', {
		get: function() {return state},
		set: function(newValue) {
			state = newValue;
			/**
			 * @event Device#connectionStateChange
			 * @property {ConnectionState} state The new state
			 */
			atem.emit('connectionStateChange', state);
			if (state == 2) { atem.emit('connected'); }
		}
	});

	var
		/**
		 * Unique identifier
		 * A temporary uid is generated to make a connection.
		 * When connected, the ATEM will provide another uid for us
		 * @type {number}
		 */
		uid,
		/**
		 * The current local sequence number.
		 * Local sequence numbers are used to identify sync packets we send to the ATEM.
		 * @type {Number}
		 */
		ls = 0,
		/**
		 * Packets we sent to the ATEM but for which we received no acknowledgement yet.
		 * @type {UserPacket[]}
		 */
		pendingPackets = [],
		/**
		 * Packets the ATEM sent and have yet to be acknowledged
		 * @type {AtemPacket[]}
		 */
		incomingPackets = [],
		/**
		 * Commands we need to send to the atem
		 * @type {Command[]}
		 */
		commandQueue = [],
		/**
		 * A timer to ensure commands are sent within 16 milliseconds
		 * @type {Timeout}
		 */
		commandTimer,
		/**
		 * A timer to assure there is a sync message sent every 600 milliseconds.
		 * @type {Timer}
		 */
		syncInterval,
		/**
		 * The timeout of the last received ATEM packet. Used to detect connection loss.
		 */
		communicationTimeout,
		ip,
		state = ConnectionState.closed;

	/**
	 * When an error is encountered during communication, this event will be fired.
	 * @event Device#error
	 * @type {Error}
	 * @property {String} Message
	 */

	/**
	 * Find a pending packet by local sequence number
	 * @param {Number} ls Local sequence number
	 * @return {UserPacket} The packet
	 */
	function getPendingPacket(ls){
		var i;
		for (i = pendingPackets.length - 1; i >= 0; i--)
			if (pendingPackets[i].header.ls == ls)
				return pendingPackets[i];
	}

	/**
	 * Create and transmit a sync packet to the ATEM.
	 */
	function sync() {
		const packet = new UserPacket();
		packet.transmit();
	}



	/**
	 * Create a custom UserPacket.
	 *
	 * @constructor UserPacket
	 * @augments Packet
	 * @classdesc A Packet commissiond by the user. This is used to send messages to the ATEM.
	 *
	 * @param {Command[]|null} [commands] An array of commands. If null, a connect packet will be created
	 */
	function UserPacket(commands){
		Packet.call(this);
		this.interval = undefined;

		// If the packet contains commands
		if (typeof commands !== 'undefined'){
			// If it is a connect packet
			if (commands === null) {
				this.header.flags = flags.connect;
				this.body.commands = [{
					get length() { return 8; },
					serialize: function() {
						const connectCmd = '0100000000000000';
						return (new Buffer(connectCmd, 'hex'));
					}
				}];
			}
			else {
				this.body.commands = commands;
				this.header.flags = flags.sync;
			}
		}

		// If the packet contains no commands
		else {
			this.header.flags = flags.sync;
		}
	}
	util.inherits(UserPacket, Packet);
	/**
	 * Transmits the packet to the atem
	 * @memberof UserPacket
	 * @method
	 * @fires Device#error
	 * @fires Device#messageTimeout
	 */
	UserPacket.prototype.transmit = function() {
		var self = this;

		if (!this.isAck()) {
			if (incomingPackets.length > 0) {
				this.header.flags |= flags.ack; //enable ack flag
				this.header.fs = incomingPackets.shift().header.ls;
			}
			else {
				this.header.flags &= ~flags.ack; //disable ack flag
				this.header.fs = 0;
			}
		}

		// If it's the first time this packet is sent
		if (pendingPackets.indexOf(this) == -1 && !this.serializedCache) {
			this.header.uid = uid;

			if ( this.isSync() || this.isConnect() ) {
				this.header.ls = ls;
			}

			if ( atem.state == ConnectionState.open && this.isSync() && this.header.ls>0 && commandQueue.length>0){
				// first sync packet cannot contain data.
				this.body.commands = this.body.commands.concat(commandQueue.slice(0));
				commandQueue = [];
			}

			this.serializedCache = this.body.serialize();
			var packet = Buffer.concat([this.header.serialize(), this.serializedCache]);
			socket.send(packet, 0, packet.length, 9910, atem.ip, function(err, bytes) {
				if (err) atem.emit('error', err);
			});

			// Set the repeat flag for future transmissions
			self.header.flags |= flags.repeat;

			// Take measures for packet loss
			if (self.isSync() || self.isConnect()) {
				self.interval = setInterval(function() {self.transmit();} , 600);

				pendingPackets.push(self);
				self.messageTimeout = setTimeout(function() {
					/**
							 * When a sync message is sent to the atem and the ATEM does not
							 * respond in x milliseconds, this event will be fired.
							 *
							 * @event Device#messageTimeout
							 * @type {Error}
							 * @property message {String} The error message
							 */
					//Todo parametrize timeout
					atem.emit('messageTimeout', new Error('Sync timeout (1sec)'));
				}, 1000);
			}

			if (state != ConnectionState.attempting && this.isSync()){
				ls = (ls+1) %0x10000;
			}

		}

		// If it is a retransmission
		else {
			packet = Buffer.concat([this.header.serialize(), this.serializedCache]);
			socket.send(packet, 0, packet.length, 9910, atem.ip);
		}

		if (this.isSync() && state == ConnectionState.open){
			clearInterval(syncInterval);
			syncInterval = setInterval(sync, 600);
		}
	};
	/**
	 * Mark this packet as read. It deletes this packet
	 * from {@link Device~pendingPackets the pendingPackets list} and stops retransmitting this packet.
	 * @memberof UserPacket
	 * @method
	 */
	UserPacket.prototype.markAsRead = function() {
		clearInterval(this.interval);
		clearTimeout(this.messageTimeout);
		pendingPackets.splice(pendingPackets.indexOf(this), 1);
	};


	/**
	 * Parse an ATEM UDP message
	 *
	 * @constructor AtemPacket
	 * @augments Packet
	 * @classdesc Used to parse an UDP message from the Atem
	 *
	 * @param {Buffer} msg The message to parse
	 */
	function AtemPacket(msg){
		Packet.call(this);

		this.header.flags = msg[0]>>>3;
		this.header.uid = msg.readUInt16BE(2);
		this.header.fs  = msg.readUInt16BE(4);
		this.header.ls  = msg.readUInt16BE(10);

		if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!');

		if (state === ConnectionState.attempting) {
			if (this.isSync()){
				atem.state = ConnectionState.establishing;
				uid = this.header.uid;
			}
		} else
		if (state === ConnectionState.establishing){
			if (msg.length==12 && !this.isConnect()){
				atem.state = ConnectionState.open;
				clearInterval(syncInterval);
				syncInterval = setInterval(sync, 600);
			}
		}

		if (this.isConnect()) {
			//Do something
		}
		else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){
			const body = msg.slice(12);

			var name, data, cmd, cmdLength, cursor=0;
			while (cursor < body.length-1) {
				cmdLength = body.readUInt16BE(cursor);
				name = body.toString('utf8', cursor+4, cursor+8);
				data = body.slice(cursor+8, cursor+cmdLength);
				cmd = new Command(name, data);
				this.body.commands.push(cmd);
				cursor += cmdLength;

				/**
				 * @event Device#rawCommand
				 * @type {Command}
				 */

				// todo: check foreign sequence number, to prevent the event emitter
				// from emitting the same message twice.
				atem.emit('rawCommand', cmd);
				atem.emit(cmd.name, cmd.data);
			}
		}
		else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) {
			const err = new Error('Message length mismatch');
			self.emit('error', err);
		} else {
			const err2 = new Error('UID mismatch');
			self.emit('error', err2);
		}
	}
	util.inherits(AtemPacket, Packet);
	/**
	 * Send an acknowledgement for this packet to the ATEM
	 * @memberof AtemPacket
	 * @method
	 */
	AtemPacket.prototype.acknowledge = function(){
		const self = this;

		incomingPackets.push(self);
		if (state == ConnectionState.attempting)
			respond();
		else
			process.nextTick(respond);

		function respond() {
			const index = incomingPackets.indexOf(self);
			if (index != -1) {
				const ackPacket = new UserPacket();
				ackPacket.header.flags = flags.ack;
				ackPacket.header.fs = self.header.ls;
				ackPacket.transmit();
				incomingPackets.splice(index, 1);
			}
		}
	};
	/**
	 * Marks the corresponding (sync) UserPacket from the {@link Device~pendingPackets the pendingPackets list} as read. <br>
	 * Note that packets, transmitted before the corresponding packet
	 * (thus having a local sequence number wich is less than the corresponding packet's one),
	 * will be removed too.
	 * @memberof AtemPacket
	 * @method
	 */
	AtemPacket.prototype.removePendingPackets = function() {
		for ( var i = 0; i < pendingPackets.length; i++ ) {
			if (pendingPackets[i].header.ls <= this.header.fs) {
				pendingPackets[i].markAsRead();
			}
		}
	};


	/**
	 * Sends a packet with all the remaining command of the commandQueue
	 */

	function handleQueue() {
		const count = commandQueue.length

		if (count>0) {
			const packet = new UserPacket(commandQueue.slice(0));
			commandQueue = [];

			packet.transmit();
		}

		return count
	}




	this.sendCommand = function(cmd) {
		commandQueue = commandQueue.concat(cmd);
		if (ls>0 && state==ConnectionState.open && !commandTimer){
			commandTimer = setTimeout(function() {
				if (commandQueue.length > 0) sync();
				commandTimer = undefined;
			}, 16);
		}
	};

	/**
	 * Performs a cut transition between preview and program
	 * @function Device#cut
	 */
	this.cut = function() {
		const data = new Buffer(4);
		data.fill(0);
		self.sendCommand(new Command('DCut', data));
	};

	/**
	 * Performs an auto transition between preview and program
	 * @function Device#auto
	 */
	this.auto = function() {
		const data = new Buffer(4);
		data.fill(0);
		self.sendCommand(new Command('DAut', data));
	};

	/**
	 * Changes the specified options of the Source Configuration. Note that you don't need to specify all
	 * the properties of {@link SourceConfiguration}.
	 * @function Device#changeSourceConfiguration
	 * @param {SourceID} sourceID
	 * @param {SourceConfiguration} options
	 */
	this.changeSourceConfiguration = function(sourceID, options) {
		/**
		 * @typedef {Object} SourceConfiguration
		 * @property {String} name The display name of the source. This name is shown for each source on the multiview
		 * @property {String} abbreviation An abbreviation of the display name.
		 * this abbreviation is displayed on the ATEM switcher panels.
		 * @property {VideoInterface} videoInterface The video interface used for this source
		 */

		//todo check if source exists
		//todo laten werken voor multiview
		const data = new Buffer(32);

		const longNameFlag = options.hasOwnProperty('name');
		const shortNameFlag  = options.hasOwnProperty('abbreviation');
		const videoInterfaceFlag = options.hasOwnProperty('videoInterface');

		data[0] = longNameFlag<<0 |
			shortNameFlag<<1 |
			videoInterfaceFlag<<2;

		data.writeUInt16BE(sourceID, 2);

		if (longNameFlag){
			data.write(options.name.slice(0,20), 4);
			if (options.name.length<20)
				data[4+options.name.length] = 0;
		}

		if (shortNameFlag) {
			data.write(options.abbreviation.slice(0,4), 24);
			if (options.abbreviation.length<4)
				data[24+options.abbreviation.length] = 0;
		}

		if (videoInterfaceFlag) {
			data.writeUInt16BE(videoInterfaceNumbers[options.videoInterface], 28)
		}

		self.sendCommand(new Command('CInL', data));
	};

	/**
	 * Sets the desired source in program. (cut transition)
	 * @function Device#setProgram
	 * @param {SourceID} sourceID the ID of the source
	 */
	this.setProgram = function(sourceID) {
		var data = new Buffer(4);
		data.writeUInt32BE(sourceID, 0);

		const cmd = new Command('CPgI', data);
		atem.sendCommand(cmd);
	};

	/**
	 * Sets the desired source in preview
	 * @function Device#setPreview
	 * @param {SourceID} sourceID the ID of the source
	 */
	this.setPreview = function(source) {
		var data = new Buffer(4);
		data.writeUInt32BE(source, 0);

		const cmd = new Command('CPvI', data);
		atem.sendCommand(cmd);
	};

	/**
	 * Change the auxiliary output
	 * @param {SourceID} aux
	 * @param {SourceID} source
	 */
	this.setAux = function(aux, source){
		var data = new Buffer(4);
		data[0] = 1;
		data[1] = aux - 8001;
		data.writeUInt16BE(source, 2);

		const cmd = new Command('CAuS', data);
		atem.sendCommand(cmd);
	}




	this.on('connected', function() {
		sync();
	});

	this.on('messageTimeout', function() {

	});

	this.on('connectionLost', function() {
		console.log('Connection Lost');
		atem.disconnect(atem.connect);
	});

	this.on('InPr', function(d) {
		const sourceID = d.readUInt16BE(0);

		const longName = parseString(d.slice(2,22));
		const shortName = parseString(d.slice(22, 26));
		const videoInterface = videoInterfaceNames[d[29]];
		if (typeof videoInterface === 'undefined')
			console.log('unknown video interface ' + d[29]);

		/**
		 * When the Source Configuration changes, for example: if the display name of input 2 changes, this event will be fired
		 *
		 * @event Device#sourceConfiguration
		 * @property {SourceID} sourceID the identifier of the source
		 * @property {SourceConfiguration} sourceConfiguration the new configuration of the source
		 */
		atem.emit('sourceConfiguration', sourceID, {
			name: longName,
			abbreviation: shortName,
			'videoInterface': videoInterface
		});
	});

	this.on('TlIn', function(d) {
		const length = d.readUInt16BE(0);
		for (var i=2; i<length+2; i++){
			/**
			 * When the input tally changes, this event will be fired. <br>
			 * By input tally we mean the state (which is: live, preview or neither of them) of one of the camera inputs
			 *
			 * @event Device#inputTally
			 * @property {Number} inputNumber the index of the input
			 * @property {SourceState} state
			 */
			atem.emit('inputTally', i-1, {
				program: (d[i] & 1) === 1,
				preview: (d[i] & 2) === 2
			});
		}
	});

	this.on('TlSr', function(data) {
		const length = data.readUInt16BE(0)*3 + 2;
		var source, tallyBit;
		for (var i=2; i<length; i = i+3){
			/**
			 * When the source tally changes, this event will be fired. <br>
			 *
			 * @event Device#sourceTally
			 * @property {Number} sourceID the id of the source
			 * @property {SourceState} state
			 */

			source = data.readUInt16BE(i);
			tallyBit = data[i+2];

			atem.emit('sourceTally', source, {
				program: (tallyBit & 1) === 1,
				preview: (tallyBit & 2) === 2
			});
		}
	});

	this.on('PrvI', function(d) {
		const source = d.readUInt16BE(2),
			inTransition = (d[4] & 1) === 1;

		/**
		 * When the selected preview bus changes this event will be fired.
		 * @event Device#previewBus
		 * @property {SourceID} source The new preview source
		 */
		atem.emit('previewBus', source, inTransition);

		// todo inspect the other bytes in PrvI
	});

	this.on('PrgI', function(d) {
		const source = d.readUInt16BE(2);

		/**
		 * When the selected program bus changes this event will be fired.
		 * @event Device#programBus
		 * @property {SourceID} source The new program source
		 */
		atem.emit('programBus', source);
		// todo inspect the other bytes in PrgI
	});

	this.on('AuxS', function(d) {
		const aux = d[0] + 8001;
		const source = d.readUInt16BE(2);

		/**
		 * When an auxiliary output changes, this event will be fired.
		 * @event Device#auxiliaryOutput
		 * @property {SourceID} aux The id of the auxiliary output
		 * @property {SourceID} source The id of the source that is assigned to the auxiliary output
		 */
		atem.emit('auxiliaryOutput', aux, source);
	});

	this.on('_pin', function(data) {
		const productName = parseString(data);
		atem.emit('productNameChange', productName);
	});




	/**
	 * Initiate a new connection. If already connected it will first disconnect.
	 * @name Device#connect
	 * @method
	 */
	this.connect = function() {

		if (atem.state === ConnectionState.closed) {
			uid = Math.round(Math.random() * 0x7FF);
			ls = 0;

			if (atem.ip) {
				atem.state = ConnectionState.attempting;

				socket = dgram.createSocket('udp4');
				socket.on('message', messageHandler);

				const connectPacket = new UserPacket(null);
				connectPacket.transmit();
			} else {
				const err = new Error('IP not set');
				atem.emit('error', err);
			}

		} else {
			atem.disconnect(atem.connect);
		}
	}

	this.disconnect = function(callback) {
		console.log('Disconnecting');

		clearInterval(syncInterval);
		clearTimeout(communicationTimeout);
		pendingPackets.forEach(function(packet) {
			packet.markAsRead();
		});
		atem.state = ConnectionState.closed;

		if (socket) socket.close();

		if (callback) callback();
	}

	function messageHandler(msg, rInfo) {
		const packet = new AtemPacket(msg);

		if (uid == packet.header.uid || packet.isConnect()) {
			if (packet.isAck() || packet.isConnect())
				packet.removePendingPackets();

			if (state!=ConnectionState.establishing && packet.isSync() || packet.isConnect())
				packet.acknowledge();

			clearTimeout(communicationTimeout);
			if (!packet.isConnect()) {
				communicationTimeout = setTimeout(function() {
					/**
					 * When the connection with the atem is lost, this event will be fired.
					 * @event Device#connectionLost
					 */
					atem.emit('connectionLost');
				}, 800);
			}
		}
	}

	// set ip if provided
	if (typeof atemIpAddress != 'undefined') {
		this.ip = atemIpAddress;
		this.connect();
	}
}
753865
def connect(self, address, **kwargs):
        
        if self._transport:
            raise RuntimeError('already connected')
        kwargs.setdefault('timeout', self._timeout)
        conn = create_connection(self._protocol_factory, address, **kwargs)
        self._transport = conn[0]
        self._transport._log = self._log
        self._protocol = conn[1]
        self._protocol._log = self._log
260726
public void setInetAddress(InetSocketAddress address) {
		this.value = address.getAddress();
		this.type = AttributeType.INET_ADDRESS;
		this.assigned = this.value != null;
	}
13567
function Connector(settings) {
    this.mailgun = Mailgun({apiKey: settings.apikey, domain: settings.domain});
}
1184784
private static boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) {
        return checkMethod(networkInterface, isUp) &&
               checkMethod(networkInterface, supportsMulticast) &&
               // TODO: IpV6 support
               !(interfaceAddress instanceof Inet6Address) &&
               !interfaceAddress.isLoopbackAddress();
    }
99937
function (contractAddress) {
  this.contractAddress = contractAddress;

  if (this.contractAddress) {
    stPrimeContractObj.options.address = this.contractAddress;
  }

  //stPrimeContractObj.setProvider(web3Provider.currentProvider);

  this.currContract = stPrimeContractObj;
}
1036645
@Override
    public InetAddress toInetAddress () throws UnknownHostException {
        if ( this.addr instanceof Address ) {
            return ( (Address) this.addr ).toInetAddress();
        }
        else if ( this.addr instanceof InetAddress ) {
            return (InetAddress) this.addr;
        }
        return null;
    }
1222358
function Address(domMap, formObj, addressID, match) {
		// PRIVATE MEMBERS //

		var self = this; // Pointer to self so that internal functions can reference its parent
		var fields; // Data values and references to DOM elements
		var id; // An ID by which to classify this address on the DOM

		var state = "accepted"; // Can be: "accepted" or "changed"
		// Example of a field:  street: { value: "123 main", dom: DOMElement, undo: "123 mai"}
		// Some of the above fields will only be mapped manually, not automatically.

		// Private method that actually changes the address. The keepState parameter is
		// used by the results of verification after an address is chosen; (or an "undo"
		// on a freeform address), otherwise an infinite loop of requests is executed
		// because the address keeps changing! (Set "suppressAutoVerify" to true when coming from the "Undo" link)
		var doSet = function (key, value, updateDomElement, keepState, sourceEvent, suppressAutoVerify) {
			if (!arrayContains(acceptableFields, key) || !domMap[key]) { // Skip "id" and other unacceptable fields, also skip fields that weren't included in mapping
				return false;
			}

			if (!fields[key])
				fields[key] = {};

			if (typeof fields[key].dom !== "undefined" && fields[key].dom.tagName === "SELECT" && key !== "administrative_area" && fields[key].dom.selectedIndex >= 0) {
				value = fields[key].dom[fields[key].dom.selectedIndex].text.replace(/<|>/g, "");
			} else {
				value = value.replace(/<|>/g, ""); // prevents script injection attacks (< and > aren't in addresses, anyway)
			}

			var differentVal = fields[key].value != value;

			fields[key].undo = fields[key].value || "";
			fields[key].value = value;

			if (fields[key].dom && updateDomElement) {
				if (fields[key].dom.tagName === "INPUT") {
					$(fields[key].dom).val(value);
				} else if (fields[key].dom.tagName === "SELECT" && key === "administrative_area" && self.isDomestic()) {
					var selectedVal = "";
					$(fields[key].dom).find("option").each(function () {
						if ($(this).text().toUpperCase() === value) {
							selectedVal = $(this).val();
							return false;
						} else {
							for (var stateName in allStatesByName) {
								if (allStatesByName[stateName] === value && stateName === $(this).text().toUpperCase()) {
									selectedVal = $(this).val();
									return false;
								}
							}
						}
					});
					$(fields[key].dom).val(selectedVal);
				}
			}

			var eventMeta = {
				sourceEvent: sourceEvent, // may be undefined
				field: key,
				address: self,
				value: value,
				suppressAutoVerification: suppressAutoVerify || false
			};

			if (differentVal && !keepState) {
				ui.unmarkAsValid(self);
				var uiTag = config.ui && config.smartyTag ? $(".smarty-ui .smarty-tag.smarty-addr-" + id) : undefined;
				if (config.target.indexOf("US") >= 0 && config.target.indexOf("INTERNATIONAL") < 0) {
					if (self.isDomestic()) {
						if (uiTag && !uiTag.is(":visible"))
							uiTag.show(); // Show checkmark tag if address is in US
						self.unaccept();
						trigger("AddressChanged", eventMeta);
					} else {
						if (uiTag && uiTag.is(":visible"))
							uiTag.hide(); // Hide checkmark tag if address is non-US
						self.accept({
							address: self
						}, false);
					}
				} else if (config.target.indexOf("INTERNATIONAL") >= 0 && config.target.indexOf("US") < 0) {
					if (uiTag && !uiTag.is(":visible"))
						uiTag.show(); // Show checkmark tag if address is in US
					self.unaccept();
					trigger("AddressChanged", eventMeta);
				} else if (config.target.indexOf("US") >= 0 && config.target.indexOf("INTERNATIONAL") >= 0) {
					if (uiTag && !uiTag.is(":visible"))
						uiTag.show(); // Show checkmark tag if address is in US
					self.unaccept();
					trigger("AddressChanged", eventMeta);
				}
			}

			return true;
		};

		// PUBLIC MEMBERS //

		this.form = formObj; // Reference to the parent form object (NOT THE DOM ELEMENT)
		this.match = match; // Determines how matches are made and what kind of results are returned.
		this.verifyCount = 0; // Number of times this address was submitted for verification
		this.lastField; // The last field found (last to appear in the DOM) during mapping, or the order given
		this.active = true; // If true, verify the address. If false, pass-thru entirely.
		this.lastStreetInput = ""; // Used by autocomplete to detect changes

		// Constructor-esque functionality (save the fields in this address object)
		this.load = function (domMap, addressID) {
			fields = {};
			id = addressID ? addressID.replace(/[^a-z0-9_\-]/ig, "") : randomInt(1, 99999); // Strips non-selector-friendly characters

			if (typeof domMap === "object") { // can be an actual map to DOM elements or just field/value data
				// Find the last field likely to appear on the DOM (used for UI attachments)
				this.lastField = domMap[Object.keys(domMap)[Object.keys(domMap).length - 1]];

				var isEmpty = true; // Whether the address has data in it (pre-populated) -- first assume it is empty.

				for (var prop in domMap) {
					if (domMap.hasOwnProperty(prop)) {
						if (!arrayContains(acceptableFields, prop)) // Skip "id" and any other unacceptable field
							continue;

						if (typeof domMap[prop] == "object" && domMap[prop].getBoundingClientRect().top > this.lastField.getBoundingClientRect().top) {
							this.lastField = domMap[prop];
						}

						var elem, val, elemArray, isData;
						try {
							elem = $(domMap[prop]);
							elemArray = elem.toArray();
							isData = elemArray ? elemArray.length == 0 : false;
						} catch (e) {
							isData = true;
						}

						if (isData) // Didn't match an HTML element, so treat it as an address string ("street1" data) instead
							val = domMap[prop] || "";
						else
							val = elem.val() || "";

						fields[prop] = {};
						fields[prop].value = val;
						fields[prop].undo = val;

						if (!isData) {
							if (config.debug) {
								$(elem).addClass("smarty-debug-input");
								elem.attr("placeholder", prop + ":" + id);
							}
							fields[prop].dom = domMap[prop];
						}

						// This has to be passed in at bind-time; they cannot be obtained at run-time
						var data = {
							address: this,
							field: prop,
							value: val
						};

						// Capture the element that is clicked on so we know whether or not to close the autocomplete UI
						// (http://stackoverflow.com/a/11544766/4462191)
						$(document).mousedown(function (e) {
							// The latest element clicked
							clicky = $(e.target);
						});

						// when "clicky == null" on blur, we know it was not caused by a click
						// but maybe by pressing the tab key
						$(document).mouseup(function (e) {
							clicky = null;
						});

						$(document).keydown(function (e) {
							typey = $(e.target);
						});

						$(document).keyup(function (e) {
							typey = null;
						});

						// Bind the DOM element to needed events, passing in the data above
						// NOTE: When the user types a street, city, and state, then hits Enter without leaving
						// the state field, this change() event fires before the form is submitted, and if autoVerify is
						// on, the verification will not invoke form submit, because it didn't come from a form submit.
						// This is known behavior and is actually proper functioning in this uncommon edge case.
						!isData && $(domMap[prop]).change(data, actionsOnChange);
					}
				}

				var address = this;
				$(domMap.address1, domMap.freeform).blur(function () {
					ui.hideAutocomplete(address.id());
				});

				state = "changed";
			}
		};

		// Run the "constructor" to load up the address
		this.load(domMap, addressID);

		this.set = function (key, value, updateDomElement, keepState, sourceEvent, suppressAutoVerify) {
			if (typeof value !== "undefined") {
				if (typeof key === "string" && arguments.length >= 2)
					return doSet(key, value, updateDomElement, keepState, sourceEvent, suppressAutoVerify);
				else if (typeof key === "object") {
					var successful = true;
					for (var prop in key) {
						if (key.hasOwnProperty(prop)) {
							successful = doSet(prop, key[prop], updateDomElement, keepState, sourceEvent, suppressAutoVerify) ? successful : false;
						}
					}
					return successful;
				}
			}
		};

		this.replaceWith = function (resp, updateDomElement, e) {
			// Given the response from an API request associated with this address,
			// replace the values in the address... and if updateDomElement is true,
			// then change the values in the fields on the page accordingly.

			if (typeof resp === "array" && resp.length > 0)
				resp = resp[0];

			// Sent via US api
			if (typeof resp.candidate_index != "undefined") {
				if (self.isFreeform()) {
					var singleLineAddr = (resp.addressee ? resp.addressee + ", " : "") +
						(resp.delivery_line_1 ? resp.delivery_line_1 + ", " : "") +
						(resp.delivery_line_2 ? resp.delivery_line_2 + ", " : "") +
						(resp.components.urbanization ? resp.components.urbanization + ", " : "") +
						(resp.last_line ? resp.last_line : "");
					var fieldKey = "freeform";
					if (fields.address1) {
						fieldKey = "address1";
					}
					self.set(fieldKey, singleLineAddr, updateDomElement, true, e, false);
				} else {
					self.set("organization", resp.addressee, updateDomElement, true, e, false);
					self.set("address1", resp.delivery_line_1, updateDomElement, true, e, false);
					if (resp.delivery_line_2)
						self.set("address2", resp.delivery_line_2, updateDomElement, true, e, false); // Rarely used; must otherwise be blank.
					else
						self.set("address2", "", updateDomElement, true, e, false);
					self.set("locality", resp.components.city_name, updateDomElement, true, e, false);
					self.set("administrative_area", resp.components.state_abbreviation, updateDomElement, true, e, false);
					self.set("postal_code", resp.components.zipcode + "-" + resp.components.plus4_code, updateDomElement, true, e, false);
				}
				self.set("address3", "", updateDomElement, true, e, false);
				self.set("address4", "", updateDomElement, true, e, false);
				self.set("country", "USA", updateDomElement, true, e, false);
			} else { // Sent via international API
				if (self.isFreeform()) {
					var singleLineAddr = (resp.organization ? resp.organization + ", " : "") +
						(resp.address1 ? resp.address1 : "") +
						(resp.address2 ? ", " + resp.address2 : "") +
						(resp.address3 ? ", " + resp.address3 : "") +
						(resp.address4 ? ", " + resp.address4 : "") +
						(resp.address5 ? ", " + resp.address5 : "") +
						(resp.address6 ? ", " + resp.address6 : "") +
						(resp.address7 ? ", " + resp.address7 : "") +
						(resp.address8 ? ", " + resp.address8 : "") +
						(resp.address9 ? ", " + resp.address9 : "") +
						(resp.address10 ? ", " + resp.address10 : "") +
						(resp.address11 ? ", " + resp.address11 : "") +
						(resp.address12 ? ", " + resp.address12 : "");
					var countryLine = resp.components.country_iso_3 ? resp.components.country_iso_3 : "";
					self.set("freeform", singleLineAddr, updateDomElement, true, e, false);
					self.set("country", countryLine, updateDomElement, true, e, false);
				} else {
					self.set("organization", resp.organization, updateDomElement, true, e, false);
					self.set("locality", resp.components.locality, updateDomElement, true, e, false);
					self.set("administrative_area", resp.components.administrative_area, updateDomElement, true, e, false);
					if (resp.components.postal_code_short) {
						var fullPostalCode = resp.components.postal_code_short;
						if (resp.components.postal_code_extra)
							fullPostalCode = fullPostalCode + "-" + resp.components.postal_code_extra;
						self.set("postal_code", fullPostalCode, updateDomElement, true, e, false);
					}
					removeComponentsFromAddressLines(resp);
					if (this.getDomFields().address4) {
						self.set("address1", resp.address1, updateDomElement, true, e, false);
						self.set("address2", resp.address2, updateDomElement, true, e, false);
						self.set("address3", resp.address3, updateDomElement, true, e, false);

						var addressLine4 = resp.address4;
						addressLine4 = addAddressLine(addressLine4, resp.address5, resp.address6);
						addressLine4 = addAddressLine(addressLine4, resp.address6, resp.address7);
						addressLine4 = addAddressLine(addressLine4, resp.address7, resp.address8);
						addressLine4 = addAddressLine(addressLine4, resp.address8, resp.address9);
						addressLine4 = addAddressLine(addressLine4, resp.address9, resp.address10);
						addressLine4 = addAddressLine(addressLine4, resp.address10, resp.address11);
						addressLine4 = addAddressLine(addressLine4, resp.address11, resp.address12);
						self.set("address4", addressLine4, updateDomElement, true, e, false);
					} else if (this.getDomFields().address3) {
						self.set("address1", resp.address1, updateDomElement, true, e, false);
						self.set("address2", resp.address2, updateDomElement, true, e, false);

						var addressLine3 = resp.address3;
						addressLine3 = addAddressLine(addressLine3, resp.address4, resp.address5);
						addressLine3 = addAddressLine(addressLine3, resp.address5, resp.address6);
						addressLine3 = addAddressLine(addressLine3, resp.address6, resp.address7);
						addressLine3 = addAddressLine(addressLine3, resp.address7, resp.address8);
						addressLine3 = addAddressLine(addressLine3, resp.address8, resp.address9);
						addressLine3 = addAddressLine(addressLine3, resp.address9, resp.address10);
						addressLine3 = addAddressLine(addressLine3, resp.address10, resp.address11);
						addressLine3 = addAddressLine(addressLine3, resp.address11, resp.address12);
						self.set("address3", addressLine3, updateDomElement, true, e, false);
					} else if (this.getDomFields().address2) {
						self.set("address1", resp.address1, updateDomElement, true, e, false);

						var addressLine2 = resp.address2;
						addressLine2 = addAddressLine(addressLine2, resp.address3, resp.address4);
						addressLine2 = addAddressLine(addressLine2, resp.address4, resp.address5);
						addressLine2 = addAddressLine(addressLine2, resp.address5, resp.address6);
						addressLine2 = addAddressLine(addressLine2, resp.address6, resp.address7);
						addressLine2 = addAddressLine(addressLine2, resp.address7, resp.address8);
						addressLine2 = addAddressLine(addressLine2, resp.address8, resp.address9);
						addressLine2 = addAddressLine(addressLine2, resp.address9, resp.address10);
						addressLine2 = addAddressLine(addressLine2, resp.address10, resp.address11);
						addressLine2 = addAddressLine(addressLine2, resp.address11, resp.address12);
						self.set("address2", addressLine2, updateDomElement, true, e, false);
					} else if (this.getDomFields().address1) {
						var addressLine1 = resp.address1;
						addressLine1 = addAddressLine(addressLine1, resp.address2, resp.address3);
						addressLine1 = addAddressLine(addressLine1, resp.address3, resp.address4);
						addressLine1 = addAddressLine(addressLine1, resp.address4, resp.address5);
						addressLine1 = addAddressLine(addressLine1, resp.address5, resp.address6);
						addressLine1 = addAddressLine(addressLine1, resp.address6, resp.address7);
						addressLine1 = addAddressLine(addressLine1, resp.address7, resp.address8);
						addressLine1 = addAddressLine(addressLine1, resp.address8, resp.address9);
						addressLine1 = addAddressLine(addressLine1, resp.address9, resp.address10);
						addressLine1 = addAddressLine(addressLine1, resp.address10, resp.address11);
						addressLine1 = addAddressLine(addressLine1, resp.address11, resp.address12);
						self.set("address1", addressLine1, updateDomElement, true, e, false);
					}
					self.set("country", resp.components.country_iso_3, updateDomElement, true, e, false);
				}
			}
		};

		var removeComponentFromAddressLine = function (addressComponent, componentName, addressLineComponent, resp) {
			if (addressComponent.indexOf(componentName) !== -1) {
				var regex = new RegExp(resp.components[componentName], "g");
				var newAddressLine = resp[addressLineComponent].replace(regex, "");
				resp[addressLineComponent] = newAddressLine;
			}
		};

		var removeExtraWhitespace = function (addressLineComponent, resp) {
			var addressLine = resp[addressLineComponent];

			removeLeadingWhitespace();
			removeTrailingWhitespace();
			replaceMultipleWhitespaceWithSingle();
			resp[addressLineComponent] = addressLine;

			function removeLeadingWhitespace() {
				addressLine = addressLine.replace(/^\s+/g, "");
			}

			function removeTrailingWhitespace() {
				addressLine = addressLine.replace(/\s+$/g, "");
			}

			function replaceMultipleWhitespaceWithSingle() {
				addressLine = addressLine.replace(/\s+/g, " ");
			}
		};

		var emptyLastNonEmptyAddressLine = function (resp) {
			for (var lineNumber = 12; lineNumber >= 1; lineNumber--) {
				var addressLineComponent = "address" + lineNumber;

				if (resp.hasOwnProperty(addressLineComponent) && resp[addressLineComponent] !== "") {
					resp[addressLineComponent] = "";
					return;
				}
			}
		};

		var removeComponentsFromAddressLines = function (resp) {
			if (resp.metadata.hasOwnProperty("address_format")) {
				var addressFormatLines = resp.metadata.address_format.split("|");

				for (var addressLineNumber in addressFormatLines) {
					var componentsToRemove = [
						"locality",
						"administrative_area",
						"postal_code",
						"country"
					];
					var addressComponent = addressFormatLines[addressLineNumber];
					var lineNumberAsInt = parseInt(addressLineNumber) + 1;
					var addressLineComponent = "address" + lineNumberAsInt;

					componentsToRemove.map(function (componentName) {
						removeComponentFromAddressLine(addressComponent, componentName, addressLineComponent, resp);
					});
					removeExtraWhitespace(addressLineComponent, resp);
				}
			} else {
				emptyLastNonEmptyAddressLine(resp);
			}
		};

		var addAddressLine = function (fullLine, addressLine, nextAddressLine) {
			if (typeof addressLine !== "undefined" && typeof nextAddressLine !== "undefined") {
				if (fullLine !== "") {
					fullLine += ", ";
				}
				fullLine += addressLine;
			}
			return fullLine;
		};

		this.corners = function (lastField) {
			var corners = {};

			if (!lastField) {
				for (var prop in fields) {
					if (fields.hasOwnProperty(prop)) {
						if (!fields[prop].dom || !$(fields[prop].dom).is(":visible"))
							continue;

						var dom = fields[prop].dom;
						var offset = $(dom).offset();
						offset.right = offset.left + $(dom).outerWidth(false);
						offset.bottom = offset.top + $(dom).outerHeight(false);

						corners.top = !corners.top ? offset.top : Math.min(corners.top, offset.top);
						corners.left = !corners.left ? offset.left : Math.min(corners.left, offset.left);
						corners.right = !corners.right ? offset.right : Math.max(corners.right, offset.right);
						corners.bottom = !corners.bottom ? offset.bottom : Math.max(corners.bottom, offset.bottom);
					}
				}
			} else {
				var jqDom = $(self.lastField);
				corners = jqDom.offset();
				corners.right = corners.left + jqDom.outerWidth(false);
				corners.bottom = corners.top + jqDom.outerHeight(false);
			}

			corners.width = corners.right - corners.left;
			corners.height = corners.bottom - corners.top;

			return corners;
		};

		this.verify = function (invoke, invokeFn) {
			// Invoke contains the element to "click" on once we're all done, or is a user-defined callback function (may also be undefined)
			if (!self.enoughInput()) {
				return trigger("AddressWasMissingInput", {
					address: self,
					invoke: invoke,
					invokeFn: invokeFn,
					response: new Response([])
				});
			}

			ui.disableFields(self);
			self.verifyCount++;
			var addrData = self.toRequestIntl();
			var credentials = config.token ? "auth-id=" + encodeURIComponent(config.key) + "&auth-token=" +
				encodeURIComponent(config.token) : "auth-id=" + encodeURIComponent(config.key);
			var requestUrl = config.requestUrlInternational;
			var headers = {};
			if (self.isDomestic() && config.target.indexOf("US") >= 0) {
				requestUrl = config.requestUrlUS;
				addrData = self.toRequestUS();
			}

			var agent = "&agent=" + encodeURIComponent("smartystreets (plugin:website@" + instance.version + ")");
			if (config.agent)
				agent += "&agent=" + encodeURIComponent(config.agent);

			var ajaxSettings = {
				url: requestUrl + "?" + credentials + agent,
				contentType: "jsonp",
				data: addrData,
				timeout: config.timeout
			};

			$.ajax($.extend({}, config.ajaxSettings, ajaxSettings))
				.done(function (response, statusText, xhr) {
					trigger("ResponseReceived", {
						address: self,
						response: new Response(response),
						invoke: invoke,
						invokeFn: invokeFn
					});
				})
				.fail(function (xhr, statusText) {
					var indexOfCountry = -1;
					if (xhr.responseText) {
						indexOfCountry = xhr.responseText.split("\n")[0].indexOf("country");
					}
					if (xhr.status === 422 && indexOfCountry > -1) {
						return trigger("CountryWasInvalid", {
							address: self,
							response: new Response([]),
							invoke: invoke,
							invokeFn: invokeFn
						});
					} else {
						trigger("RequestTimedOut", {
							address: self,
							status: statusText,
							invoke: invoke,
							invokeFn: invokeFn
						});
					}
					self.verifyCount--; // Address verification didn't actually work, so don't count it
				});

			// Remember, the above callbacks happen later and this function is
			// executed immediately afterward, probably before a response is received.
			trigger("RequestSubmitted", {
				address: self
			});
		};

		this.enoughInput = function () {
			// Checks for state dropdown
			var stateText;
			if (fields.administrative_area) {
				stateText = fields.administrative_area.value;
				if (fields.administrative_area.dom !== undefined && fields.administrative_area.dom.length !== undefined) {
					if (fields.administrative_area.dom.selectedIndex < 1)
						stateText = "";
					else
						stateText = fields.administrative_area.dom.options[fields.administrative_area.dom.selectedIndex].text;
				}
			}

			if (fields.country && !fields.country.value) {
				return false;
			}
			if (fields.freeform) {
				return fields.freeform.value;
			}
			if (fields.address1 && !fields.address1.value) {
				return false;
			}

			var postalCodeIsPresentAndHasValue = !!(fields.postal_code && fields.postal_code.value);
			var administrativeAreaIsPresentAndHasValue = !!(fields.administrative_area && stateText.length > 0);
			var localityIsPresentAndHasValue = !!(fields.locality && fields.locality.value);

			return postalCodeIsPresentAndHasValue || (localityIsPresentAndHasValue && administrativeAreaIsPresentAndHasValue);
		};

		this.toRequestIntl = function () {
			var obj = {};
			if (fields.hasOwnProperty("freeform") &&
				fields.hasOwnProperty("address1") &&
				fields.hasOwnProperty("locality") &&
				fields.hasOwnProperty("administrative_area") &&
				fields.hasOwnProperty("postal_code")) {
				delete fields.address1;
				delete fields.locality;
				delete fields.administrative_area;
				delete fields.postal_code;
			}
			for (var key in fields) {
				if (fields.hasOwnProperty(key)) {
					var keyval = {};
					if (fields[key].dom && fields[key].dom.tagName === "SELECT" && fields[key].dom.selectedIndex >= 0) {
						keyval[key] = fields[key].dom[fields[key].dom.selectedIndex].text;
					} else {
						keyval[key] = fields[key].value.replace(/\r|\n/g, " "); // Line breaks to spaces
					}
					$.extend(obj, keyval);
				}
			}
			obj.geocode = config.geocode;
			return obj;
		};

		this.toRequestUS = function () {
			var obj = {};
			if (fields.address1 && fields.address1.dom && fields.address1.dom.value) {
				obj.street = fields.address1.dom.value;
			} else if (fields.address1 && fields.address1.value) { // Covers a special case where the user calls .verify on the instance
				obj.street = fields.address1.value;
			}
			if (fields.address2 && fields.address2.dom && fields.address2.dom.value) {
				obj.street2 = fields.address2.dom.value;
			}
			if (fields.address3 && fields.address3.dom && fields.address3.dom.value) {
				if (typeof obj.street2 === "undefined") {
					obj.street2 = fields.address3.dom.value;
				} else {
					obj.street2 = obj.street2 += ", " + fields.address3.dom.value;
				}
			}
			if (fields.address4 && fields.address4.dom && fields.address4.dom.value) {
				if (typeof obj.street2 === "undefined") {
					obj.street2 = fields.address4.dom.value;
				} else {
					obj.street2 = obj.street2 += ", " + fields.address4.dom.value;
				}
			}
			if (fields.locality && fields.locality.dom) {
				if (fields.locality.dom.tagName === "SELECT" && fields.locality.dom.selectedIndex >= 0) {
					obj.city = fields.locality.dom[fields.locality.dom.selectedIndex].text;
				} else {
					obj.city = fields.locality.dom.value;
				}
			}
			if (fields.administrative_area && fields.administrative_area.dom.value) {
				if (fields.administrative_area.dom.tagName === "SELECT" && fields.administrative_area.dom.selectedIndex >= 0) {
					obj.state = fields.administrative_area.dom[fields.administrative_area.dom.selectedIndex].text;
				} else {
					obj.state = fields.administrative_area.dom.value;
				}
			}
			if (fields.postal_code && fields.postal_code.dom.value) {
				obj.zipcode = fields.postal_code.dom.value;
			}
			if (fields.freeform && fields.freeform.dom.value) {
				obj.street = fields.freeform.dom.value;
			}
			if (typeof this.secondary !== "undefined") {
				obj.secondary = this.secondary;
				delete this.secondary;
			}
			if (typeof this.address1 !== "undefined") {
				obj.street = this.address1;
				delete this.address1;
				if (typeof this.zipcode !== "undefined") {
					obj.zipcode = this.zipcode;
					delete this.zipcode;
				}
				delete obj.freeform;
			}

			obj.match = this.match;
			obj.candidates = config.candidates;
			return obj;
		};

		function getStringOfPossibleDropdown(field) {
			if (field.dom) {
				if (field.dom.tagName !== "SELECT") {
					return field.dom.value + " ";
				} else if (field.dom.selectedIndex > 0) {
					return field.dom[field.dom.selectedIndex].text + " ";
				}
			}
			return "";
		}

		this.toString = function () {
			if (fields.freeform) {
				return (fields.freeform ? fields.freeform.value + " " : "") + (fields.country ? fields.country.value : "");
			} else {
				var addrString = (fields.address1 ? fields.address1.value + " " : "") + (fields.address2 ? fields.address2.value + " " : "") +
					(fields.address3 ? fields.address3.value + " " : "") + (fields.address4 ? fields.address4.value + " " : "") +
					(fields.locality ? fields.locality.value + " " : "");
				if (fields.administrative_area) {
					addrString += getStringOfPossibleDropdown(fields.administrative_area);
				}
				addrString += (fields.postal_code ? fields.postal_code.value + " " : "");
				if (fields.country) {
					addrString += getStringOfPossibleDropdown(fields.country);
				}
				return addrString;
			}
		};

		this.abort = function (event, keepAccept) {
			keepAccept = typeof keepAccept === "undefined" ? false : keepAccept;
			if (!keepAccept)
				self.unaccept();
			delete self.form.processing;
			return suppress(event);
		};

		// Based on the properties in "fields," determines if this is a single-line address
		this.isFreeform = function () {
			return fields.freeform;
		};

		this.get = function (key) {
			return fields[key] ? fields[key].value : null
		};

		this.undo = function (updateDomElement) {
			updateDomElement = typeof updateDomElement === "undefined" ? true : updateDomElement;
			for (var key in fields) {
				if (fields.hasOwnProperty(key)) {
					this.set(key, fields[key].undo, updateDomElement, false, undefined, true);
				}
			}
		};

		this.accept = function (data, showValid) {
			showValid = typeof showValid === "undefined" ? true : showValid;
			state = "accepted";
			ui.enableFields(self);
			if (showValid) // If user chooses original input or the request timed out, the address wasn't "verified"
				ui.markAsValid(self);
			trigger("AddressAccepted", data);
		};

		this.unaccept = function () {
			state = "changed";
			ui.unmarkAsValid(self);
			return self;
		};

		this.getUndoValue = function (key) {
			return fields[key].undo;
		};

		this.status = function () {
			return state;
		};

		this.getDomFields = function () {
			// Gets just the DOM elements for each field
			var obj = {};
			for (var prop in fields) {
				if (fields.hasOwnProperty(prop)) {
					var ext = {};
					ext[prop] = fields[prop].dom;
					$.extend(obj, ext);
				}
			}
			return obj;
		};

		this.hasDomFields = function () {
			for (var prop in fields) {
				if (fields.hasOwnProperty(prop) && fields[prop].dom) {
					return true;
				}
			}
		};

		this.isDomestic = function () {
			var countryValue = "";
			if (fields.country && fields.country.dom) {
				countryValue = $(fields.country.dom).val();
				var selectedOption = $(fields.country.dom).children(":selected");
				if (selectedOption.length > 0 && selectedOption.index() > 0)
					countryValue = selectedOption.text();
			}
			countryValue = countryValue.toUpperCase().replace(/\.|\s|\(|\)|\\|\/|-/g, "");
			var usa = ["", "0", "1", "US", "USA", "USOFA", "USOFAMERICA", "AMERICAN", // 1 is AmeriCommerce
				"UNITEDSTATES", "UNITEDSTATESAMERICA", "UNITEDSTATESOFAMERICA", "AMERICA",
				"840", "223", "AMERICAUNITEDSTATES", "AMERICAUS", "AMERICAUSA", "UNITEDSTATESUS",
				"AMERICANSAMOA", "AMERIKASĀMOA", "AMERIKASAMOA", "ASM",
				"MICRONESIA", "FEDERALSTATESOFMICRONESIA", "FEDERATEDSTATESOFMICRONESIA", "FSM",
				"GUAM", "GM",
				"MARSHALLISLANDS", "MHL",
				"NORTHERNMARIANAISLANDS", "NMP",
				"PALAU", "REPUBLICOFPALAU", "BELAU", "PLW",
				"PUERTORICO", "COMMONWEALTHOFPUERTORICO", "PRI",
				"UNITEDSTATESVIRGINISLANDS", "VIR"
			]; // 840 is ISO: 3166; and 223 is some shopping carts
			return arrayContains(usa, countryValue) || fields.country.value == "-1";
		};

		this.autocompleteVisible = function () {
			return config.ui && config.autocomplete && $(".smarty-autocomplete.smarty-addr-" + self.id()).is(":visible");
		};

		this.id = function () {
			return id;
		};
	}
136190
def connect(self, address):
        """"""
        if self.uses_nanoconfig:
            raise ValueError("Nanoconfig address must be sole endpoint")
        endpoint_id = _nn_check_positive_rtn(
            wrapper.nn_connect(self.fd, address)
        )
        ep = Socket.ConnectEndpoint(self, endpoint_id, address)
        self._endpoints.append(ep)
        return ep
979422
function getAddress (hostname) {
  if (net.isIP(hostname)) {
    return Promise.resolve(hostname);
  }
  return pify(dns.lookup)(hostname);
}
1108546
function(id, socket) {
  EventEmitter.call(this);
  this.id = id;
  this.socket = socket;
  this.remoteAddress = {
    ip: socket.handshake.address.address,
    port: socket.handshake.address.port
  };

  var self = this;

  socket.on('disconnect', this.emit.bind(this, 'disconnect'));

  socket.on('error', this.emit.bind(this, 'error'));

  socket.on('message', function(msg) {
    self.emit('message', msg);
  });

  this.state = ST_INITED;

  // TODO: any other events?
}
448751
protected void connect(String host, int port)
        throws UnknownHostException, IOException
    {
        boolean connected = false;
        try {
            InetAddress address = InetAddress.getByName(host);
            this.port = port;
            this.address = address;

            connectToAddress(address, port, timeout);
            connected = true;
        } finally {
            if (!connected) {
                try {
                    close();
                } catch (IOException ioe) {
                    /* Do nothing. If connect threw an exception then
                       it will be passed up the call stack */
                }
            }
        }
    }
920477
def _connect(self, address):
        

        latency = 0
        conn_interval_min = 6
        conn_interval_max = 100
        timeout = 1.0

        try:
            #Allow passing either a binary address or a hex string
            if isinstance(address, str) and len(address) > 6:
                address = address.replace(':', '')
                address = bytes(bytearray.fromhex(address)[::-1])
        except ValueError:
            return False, None

        #Allow simple determination of whether a device has a public or private address
        #This is not foolproof
        private_bits = bytearray(address)[-1] >> 6
        if private_bits == 0b11:
            address_type = 1
        else:
            address_type = 0

        payload = struct.pack("<6sBHHHH", address, address_type, conn_interval_min,
                              conn_interval_max, int(timeout*100.0), latency)
        response = self._send_command(6, 3, payload)

        result, handle = unpack("<HB", response.payload)
        if result != 0:
            return False, None

        #Now wait for the connection event that says we connected or kill the attempt after timeout
        def conn_succeeded(event):
            if event.command_class == 3 and event.command == 0:
                event_handle, = unpack("B", event.payload[0:1])
                return event_handle == handle

        #FIXME Hardcoded timeout
        events = self._wait_process_events(4.0, lambda x: False, conn_succeeded)
        if len(events) != 1:
            self._stop_scan()
            return False, None

        handle, _, addr, _, interval, timeout, latency, _ = unpack("<BB6sBHHHB", events[0].payload)
        formatted_addr = ":".join(["%02X" % x for x in bytearray(addr)])
        self._logger.info('Connected to device %s with interval=%d, timeout=%d, latency=%d',
                          formatted_addr, interval, timeout, latency)

        connection = {"handle": handle}
        return True, connection
65727
@SuppressWarnings("unchecked") // Channel Framework implements state map...
   public void connect(Object address) throws Exception
   {
      if (tc.isEntryEnabled()) SibTr.entry(this, tc, "connect", address);

      final JFapAddress jfapAddress = (JFapAddress) address;
      if ((jfapAddress != null) && (jfapAddress.getAttachType() == Conversation.CLIENT))
      {
         vc.getStateMap().put(OutboundProtocol.PROTOCOL, "BUS_CLIENT");
      }
      else
         vc.getStateMap().put(OutboundProtocol.PROTOCOL, "BUS_TO_BUS");
      
      super.connect(address);

      if (tc.isEntryEnabled()) SibTr.exit(this, tc, "connect");
   }
416099
public void bind(InetSocketAddress inetSocketAddress) throws IOException {
    if (inetSocketAddress == null) {
      throw new IllegalArgumentException("Null inetSocketAddress");
    }
    setLocalSocketAddress(inetSocketAddress);
    start();
  }
1146332
private static Collection<? extends KNXAddress> ensureDeviceAck(final KNXMediumSettings settings,
		final Collection<? extends KNXAddress> acknowledge)
	{
		if (settings.getMedium() != KNXMediumSettings.MEDIUM_TP1)
			throw new KNXIllegalArgumentException("TP-UART link supports only TP1 medium");
		// see if we have a valid device address assigned
		final IndividualAddress device = settings.getDeviceAddress();
		if (device.getDevice() == 0 || device.getDevice() == 0xff)
			return acknowledge;

		final ArrayList<KNXAddress> l = new ArrayList<>(acknowledge);
		l.add(device);
		return l;
	}
1011126
public function registerAddress()
    {
        $address                   = $this->lanIp . ':' . $this->lanPort;
        $this->_registerConnection = new AsyncTcpConnection("text://{$this->registerAddress}");
        $this->_registerConnection->send('{"event":"gateway_connect", "address":"' . $address . '", "secret_key":"' . $this->secretKey . '"}');
        $this->_registerConnection->onClose = array($this, 'onRegisterConnectionClose');
        $this->_registerConnection->connect();
    }