This function is called only on Chrome, which does not yet support connection/disconnection events but requires you to monitor an array for changes.
486917
function () {
    // Get the array of gamepads, the first method (getGamepads)
    // is the most modern one and is supported by Firefox 28+ and
    // Chrome 35+. The second one (webkitGetGamepads) is a deprecated method
    // used by older Chrome builds.
    var rawGamepads =
        (navigator.getGamepads && navigator.getGamepads()) ||
        (navigator.webkitGetGamepads && navigator.webkitGetGamepads());

    if (rawGamepads) {
      // We don't want to use rawGamepads coming straight from the browser,
      // since it can have "holes" (e.g. if you plug two gamepads, and then
      // unplug the first one, the remaining one will be at index [1]).
      gamepadSupport.gamepads = [];

      // We only refresh the display when we detect some gamepads are new
      // or removed; we do it by comparing raw gamepad table entries to
      // `undefined`.
      var gamepadsChanged = false;

      for (var i = 0; i < rawGamepads.length; i++) {
        if (typeof rawGamepads[i] !== gamepadSupport.prevRawGamepadTypes[i]) {
          gamepadsChanged = true;
          gamepadSupport.prevRawGamepadTypes[i] = typeof rawGamepads[i];
        }

        if (rawGamepads[i]) {
          gamepadSupport.gamepads.push(rawGamepads[i]);
        }
      }

      // Ask the tester to refresh the visual representations of gamepads
      // on the screen.
      if (gamepadsChanged) {
        window.tester.updateGamepads(gamepadSupport.gamepads);
      }
    }
  }
351961
function attachBrowserEvents(self) {
  if (isChromeApp()) {
    chrome.storage.onChanged.addListener(function (e) {
      // make sure it's event addressed to us
      if (e.db_name != null) {
        //object only has oldValue, newValue members
        self.emit(e.dbName.newValue);
      }
    });
  } else if (hasLocalStorage()) {
    if (typeof addEventListener !== 'undefined') {
      addEventListener("storage", function (e) {
        self.emit(e.key);
      });
    } else { // old IE
      window.attachEvent("storage", function (e) {
        self.emit(e.key);
      });
    }
  }
}
404436
function _disconnect (context) {
  /* eslint-disable no-invalid-this */
  // Remove all connections to the context
  forEach(this.__events__, (bindings, event) => {
    for (let i = bindings.length - 1; i >= 0; i--) {
      // bindings[i] may have been removed by the previous steps
      // so check it still exists
      if (bindings[i] && bindings[i].context === context) {
        _off.call(this, event, bindings[i].method, context)
      }
    }
  })
  return this
  /* eslint-enable no-invalid-this */
}
270265
function() {
      io = io.listen(app);
      io.set("log level", 1);
      io.sockets.on("connection", function(socket) {
        connections += 1;
        console.log("   info  -".cyan, ("new connection. Connections: " + connections).yellow);

        socket.on("disconnect", function() {
          connections -= 1;
          console.log("   info  -".cyan, ("connection closed. Connections: " + connections).yellow);
        });

        socket.on("iframe-loaded", function(data) {
          urlData[data.id].counter--;
          console.log("   info  -".cyan, ("client sends event iframe-loaded").yellow, JSON.stringify(data));
        });
      });
    }
303869
function(params, callback) {
      var t = this,
          disconnectError = false;

      if (!t.get('started')) {
        var err = {code:'NOT_RUNNING', msg:'The recipe is already stopped.'};
        logger.warn('precondition', err);
        return callback(err);
      }

      // Called when a monitor has disconnected
      var onDisconnect = function(error) {
        if (disconnectError) {return;}
        if (error) {
          var err = {code:'DISONNECT_ERROR', err: error};
          disconnectError = true;
          logger.error('onDisconnect', err);
          return callback(err);
        }
        for (var name1 in t.monitors) {
          if (t.monitors[name1].isConnected()) {
            return;
          }
        }
        t.set({started:false});
        t.compiledScript = null;
        callback();
      };

      // Disconnect all monitors
      t.connectListeners(false);
      t.context = null;
      for (var name2 in t.monitors) {
        t.monitors[name2].disconnect(onDisconnect);
      }
    }
1086282
function onDisconnect() {
    for (var i = 0; i < self.runners.length; i++) {
      if (self.runners[i].id === socket.id) {
        self.runners.splice(i, 1);
        break;
      }
    }
    // Check any remaining fleets, remove it from em'
    for (var deployId in self.FLEETS) {
      var deleted = false;
      if (typeof self.FLEETS[deployId] !== 'object' || !(self.FLEETS[deployId].runners instanceof Array)) continue;
      for (var j = 0; j < self.FLEETS[deployId].runners.length; j++) {
        if (deleted) continue;
        var item = self.FLEETS[deployId].runners[j];
        if (item.id === socket.id) {
          self.FLEETS[deployId].runners.splice(j, 1);
          deleted = true;
        }
      }
    }
    socket.removeAllListeners('repositories.set');
    socket.removeAllListeners('disconnect');
    socket.removeAllListeners('deploy.complete');
    socket.removeAllListeners('deploy.error');
  }
1209773
function connectionCheck(error, diagnose) {
    var servers = diagnose.knownServers;

    // Nothing to check so we fail immediately.
    if (!servers || servers.length === 0) {
      throw new ServerDownError(error);
    }

    // We check all the servers that the user asked to check. If none respond,
    // we blame the network. Otherwise, we blame the server.
    return Promise.all(servers.map(function urlToAjax(url) {
      // eslint-disable-next-line no-use-before-define
      return ajax({ url: dedupURL(normalizeURL(url)), timeout: 1000 })
        .reflect();
    })).filter(function filterSuccessfulServers(result) {
      return result.isFulfilled();
    }).then(function checkAnyFullfilled(fulfilled) {
      if (fulfilled.length === 0) {
        throw new NetworkDownError(error);
      }

      throw new ServerDownError(error);
    });
  }
243394
function(keys_to_watch_for_changes, callback) {
    if (!Array.isArray(keys_to_watch_for_changes)) {
      throw keys_to_watch_for_changes + ' must be an array'
    }

    // add keys that map to the store's keys
    for (let k of keys_to_watch_for_changes) {
      if (!store._store.hasOwnProperty(k)) {
        throw 'Store does not have key ' + k
      }
      store._recordKeySubscriber(k, callback.name)
    }

    // call this function whenever the store changes
    function _callback(changed_keys) {
      if (intersection(keys_to_watch_for_changes, changed_keys).length) {
        callback(changed_keys)
      }
    }
    return store.subscribe(_callback)
  }
565210
function() {
        try {
          var server = {
            "host": params.host,
            "port": params.port,
            "timeout": params.timeout || 20000,
            "connectHeaders": {
              "host": "/",
              "login": params.username,
              "passcode": params.password,
              "heart-beat": "5000, 5000"
            }
          };

          var servers = [server];

          var reconnectOptions = {
            'maxReconnects': 20
          };

          var manager = new Stompit.ConnectFailover(servers, reconnectOptions);

          manager.connect(function(error, stompClient, reconnect) {
            if (error) {
              fireEvent("error", {
                errorCode: error.code,
                errorMessage: error.message,
                errorEvent: error
              });

              return;
            }

            client = stompClient;

            client.on('error', function(error) {
              fireEvent("error", {
                errorCode: 999,
                errorMessage: "ActiveMQ client has had an error",
                errorEvent: error
              });
              reconnect();
            });

            fireEvent("init");
          });

        } catch (error) {
          console.error(error);
        }
      }
701724
function(connection) {
      var t = this;
      log.info('removeConnection', 'Conn_' + connection.id);
      connection.disconnect('connection_removed');
      t.connections.remove(connection);
      t.trigger('connection:remove', connection);
    }
1113521
function onchange(array, index, removed, added) {
		edb.Array.$onchange(array, index, removed, added);
	}
1072251
function(connect) {
		var obs = this._observer;
		if (obs) {
			if (connect) {
				obs.observe(document, {
					childList: true,
					subtree: true
				});
			} else {
				obs.disconnect();
			}
		}
	}
1052404
function processNewChange(args) {
  const changeStream = args.changeStream;
  const error = args.error;
  const change = args.change;
  const callback = args.callback;
  const eventEmitter = args.eventEmitter || false;

  // If the changeStream is closed, then it should not process a change.
  if (changeStream.isClosed()) {
    // We do not error in the eventEmitter case.
    if (eventEmitter) {
      return;
    }

    const error = new MongoError('ChangeStream is closed');
    return typeof callback === 'function'
      ? callback(error, null)
      : changeStream.promiseLibrary.reject(error);
  }

  const topology = changeStream.topology;
  const options = changeStream.cursor.options;

  if (error) {
    if (isResumableError(error) && !changeStream.attemptingResume) {
      changeStream.attemptingResume = true;

      if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) {
        const startAtOperationTime = changeStream.cursor.cursorState.operationTime;
        changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options);
      }

      // stop listening to all events from old cursor
      ['data', 'close', 'end', 'error'].forEach(event =>
        changeStream.cursor.removeAllListeners(event)
      );

      // close internal cursor, ignore errors
      changeStream.cursor.close();

      // attempt recreating the cursor
      if (eventEmitter) {
        waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
          if (err) return changeStream.emit('error', err);
          changeStream.cursor = createChangeStreamCursor(changeStream);
        });

        return;
      }

      if (callback) {
        waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
          if (err) return callback(err, null);

          changeStream.cursor = createChangeStreamCursor(changeStream);
          changeStream.next(callback);
        });

        return;
      }

      return new Promise((resolve, reject) => {
        waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
          if (err) return reject(err);
          resolve();
        });
      })
        .then(() => (changeStream.cursor = createChangeStreamCursor(changeStream)))
        .then(() => changeStream.next());
    }

    if (eventEmitter) return changeStream.emit('error', error);
    if (typeof callback === 'function') return callback(error, null);
    return changeStream.promiseLibrary.reject(error);
  }

  changeStream.attemptingResume = false;

  // Cache the resume token if it is present. If it is not present return an error.
  if (!change || !change._id) {
    var noResumeTokenError = new Error(
      'A change stream document has been received that lacks a resume token (_id).'
    );

    if (eventEmitter) return changeStream.emit('error', noResumeTokenError);
    if (typeof callback === 'function') return callback(noResumeTokenError, null);
    return changeStream.promiseLibrary.reject(noResumeTokenError);
  }

  changeStream.resumeToken = change._id;

  // Return the change
  if (eventEmitter) return changeStream.emit('change', change);
  if (typeof callback === 'function') return callback(error, change);
  return changeStream.promiseLibrary.resolve(change);
}
1086642
function (server_type, socket_url, connHandler, onDone) {

		// handles when connection with server is established
		var onConnect = function () {
			
			if (typeof connHandler === 'function')
				connHandler('connect');
			
			SR.Log('websocket server connected: ' + socket_url);
			if (typeof onDone === 'function')
				onDone();
		}
		
		// disconnect event
		var onDisconnect = function (obj) {
			if (typeof connHandler === 'function')
				connHandler('disconnect');
			
			SR.Warn('disconnected... obj: ');
			SR.Warn(obj);
			
			// attempt to re-connect
			if (typeof conn_options === 'object') {
				removeEntry(currentEntry);
				currentEntry = undefined;
				SR.Warn('re-connecting websocket with options');
				SR.Warn(conn_options);
				SR.setSocketServer(conn_options);
			}
		}
		
		// configure priority of protocol used
		//io.configure(function () { 
			//io.set("transports", ["xhr-polling", "flashsocket", "json-polling"]); 
		//});
				
		// connect to server
		SR.Log('connecting to server: ' + socket_url);
            
		if (server_type === 'socketio') {
            
			socket = io.connect(
				socket_url
				/*
				{	
					'reconnection delay': 10000,
					'reconnection limit': 4,
     	 			'max reconnection attempts': 4
				}
				*/
			);
			
			var generateHandler = function (name) {
				return function () {
					if (typeof connHandler === 'function')
						connHandler(name);
				}
			}
			
			// Return socket connection status and response
			for (var i=0; i < socketEvents.length; i++) {
				var event_name = socketEvents[i];
				socket.on(event_name, generateHandler(event_name));
			}
			
            // connection success
            socket.on('connect', onConnect);
			socket.on('disconnect', onDisconnect);
			
			// move this outside of 'connect' event handling (to avoid duplicates)
			socket.on('SRR', function (data) {
				SR.Log('SRR received, type: ' + data[HEADER_UPDATE]);
				onResponse(data[HEADER_UPDATE], data[HEADER_PARA]);
			});
            
            // attach customized send function
            socket.sendJSON = function (obj) {
                socket.emit('SR', obj);
            }
		}
		else if (server_type === 'sockjs') {
			socket = {};
			var url = socket_url + '/sockjs';
			SR.Log('sockjs URL to connect: ' + url);

            // Create a connection to server
            var sock = new SockJS(url);
    
            // Open the connection
			sock.onopen = function () {
				socket.opened = true;
				// send cookie explicitly
				SR.Warn('sockjs sending cookie:');
				SR.Warn(document.cookie);
				sock.send(document.cookie);
				onConnect();
			}
			
            // On connection close
            sock.onclose = onDisconnect;

            // On receive message from server
            sock.onmessage = function (e) {
                // Get the content
                var obj = JSON.parse(e.data);
				onResponse(obj[HEADER_UPDATE], obj[HEADER_PARA]);
            }
            
            // attach customized send function
			
			socket.sendJSON = function (obj) {
								sock.send(JSON.stringify(obj));
            				};
		}
		else  {
			SR.Error('unrecongizable server_type: ' + server_type + ' please check if socket.io or sockjs is used');	
		}
	}
251786
function disconnect() {
        var deferred = new $.Deferred(),
            promise = deferred.promise();

        if (_socket && (_socket.readyState === WebSocket.OPEN)) {
            _socket.onclose = function () {
                // trigger disconnect event
                _onDisconnect();

                deferred.resolve();
            };

            promise = Async.withTimeout(promise, 5000);

            _socket.close();
        } else {
            if (_socket) {
                delete _socket.onmessage;
                delete _socket.onopen;
                delete _socket.onclose;
                delete _socket.onerror;

                _socket = undefined;
            }

            deferred.resolve();
        }

        return promise;
    }
23909
function(params, callback) {
      callback = callback || function(){};
      var t = this,
          errorText = '',
          router = Monitor.getRouter(),
          probeId = params.probeId,
          monitorProxy = t.incomingMonitorsById[probeId],
          firewall = t.get('firewall'),
          logCtxt = null,
          probe = null;

      // Already disconnected
      if (!monitorProxy || !monitorProxy.probe) {
        return callback(null);
      }

      // Get a good logging context
      probe = monitorProxy.probe;
      logCtxt = {
        probeClass: monitorProxy.get('probeClass'),
        initParams: monitorProxy.get('initParams'),
        probeId: probeId
      };

      // Called upon disconnect (internal or external)
      var onDisconnect = function(error) {
        if (error) {
          log.error(t.logId + 'probeDisconnect', error);
          return callback(error);
        }
        var duration = logCtxt.duration = Date.now() - probe.connectTime;
        probe.off('change', monitorProxy.probeChange);
        monitorProxy.probe = monitorProxy.probeChange = null;
        delete t.incomingMonitorsById[probeId];
        log.info(t.logId + 'probeDisconnected', logCtxt);
        stat.time(t.logId + 'probeDisconnected', duration);
        return callback(null);
      };

      // Disconnect from an internal or external probe
      if (probe && probe.connection) {
        router.disconnectExternal(probe.connection, probeId, onDisconnect);
      } else {
        router.disconnectInternal(probeId, onDisconnect);
      }
    }
808779
def _on_trace(_loop, adapter, conn_id, trace):
    """"""

    conn_string = adapter._get_property(conn_id, 'connection_string')
    if conn_string is None:
        adapter._logger.debug("Dropping trace data with unknown conn_id=%s", conn_id)
        return

    adapter.notify_event_nowait(conn_string, 'trace', trace)