routeChat handler. Receives a stream of message/location pairs, and responds
with a stream of all previous messages at each of those locations.
@param {Duplex} call The stream for incoming and outgoing messages
337347
function routeChat(call) {
  call.on('data', function(note) {
    var key = pointKey(note.location);
    /* For each note sent, respond with all previous notes that correspond to
     * the same point */
    if (route_notes.hasOwnProperty(key)) {
      _.each(route_notes[key], function(note) {
        call.write(note);
      });
    } else {
      route_notes[key] = [];
    }
    // Then add the new note to the list
    route_notes[key].push(JSON.parse(JSON.stringify(note)));
  });
  call.on('end', function() {
    call.end();
  });
}
569771
def _handle_func_call(self, node, scope, ctxt, stream):
        
        self._dlog("handling function call to '{}'".format(node.name.name))
        if node.args is None:
            func_args = []
        else:
            func_args = self._handle_node(node.args, scope, ctxt, stream)
        func = self._handle_node(node.name, scope, ctxt, stream)
        return func.call(func_args, ctxt, scope, stream, self, node.coord)
327986
function StreamHandler(host, port, delimiter) {
	events.EventEmitter.call(this);

	var self = this;
	self.delimiter = delimiter || "\r\n";
	self.host      = host;
	self.port      = port;

	self.buffer    = '';

	self.conn = net.createConnection(self.port, self.host);
	self.conn.setEncoding("utf8");

	self.conn.on('error', function(err) {
		try {
			self.emit('error', 'Stream error: ' + err, err);
		} catch (e) {
			console.log('' + err);
		}
	});
	self.conn.on('data', function(data) {
		self.conn.pause();
		self.buffer += data;
		if (self.buffer.match(/\n/)) {
			var arr = self.buffer.split(self.delimiter);
			//Everything except the last one
			for(var i = 0; i < arr.length - 1; i++) {
				self.emit('line', arr[i]);
			}
			self.buffer = arr[arr.length - 1];
		}
		if (self.conn.readyState == 'open') {
			self.conn.resume();
		}
	});
	self.conn.on('close', function(had_error) {
		if (!had_error && self.buffer.length > 0) {
			self.emit('line', self.buffer);
		}
	});
}
1295782
function(params, callback) {
                chatSendQueue.push(params);
                putInChatWaitQueue(params.message, function() {
                    callback && callback();
                });
            }
442598
public void stream(String streamId, StreamCallback callback) {
    StdChannelListener listener = new StdChannelListener(streamId) {
      @Override
      void handleFailure(String errorMsg, Throwable cause) throws Exception {
        callback.onFailure(streamId, new IOException(errorMsg, cause));
      }
    };
    if (logger.isDebugEnabled()) {
      logger.debug("Sending stream request for {} to {}", streamId, getRemoteAddress(channel));
    }

    // Need to synchronize here so that the callback is added to the queue and the RPC is
    // written to the socket atomically, so that callbacks are called in the right order
    // when responses arrive.
    synchronized (this) {
      handler.addStreamCallback(streamId, callback);
      channel.writeAndFlush(new StreamRequest(streamId)).addListener(listener);
    }
  }
639445
function listen(listener) {
    // TODO: Only use a single history listener. Otherwise we'll
    // end up with multiple concurrent calls to match.
    return history.listen(function (location) {
      if (state.location === location) {
        listener(null, state)
      } else {
        match(location, function (error, redirectLocation, nextState) {
          if (error) {
            listener(error)
          } else if (redirectLocation) {
            history.transitionTo(redirectLocation)
          } else if (nextState) {
            listener(null, nextState)
          } else {
            warning(
              false,
              'Location "%s" did not match any routes',
              location.pathname + location.search + location.hash
            )
          }
        })
      }
    })
  }
926182
function callRequestMiddleware(arg2, arg3) {
        i += 1;
        if (i < self.middlewares.length) {
            var next = self.middlewares[i].request;
            if (typeof next === 'function') {
                next(req, arg2, arg3, callRequestMiddleware);
            } else {
                // skip this middleware if it doesn't implement request
                callRequestMiddleware(arg2, arg3);
            }
        } else {
            handler(req, arg2, arg3, callResponseMiddleware);
        }
    }
546761
function handle(js,line){
    // handle message from board.
    //stream.log("handle",stream.token,line);

    var hasToken = stream.token;
    if(js.type == "token") {

      // send in event stream.
      stream.queue(js); 
      stream.token = js.token;

      if(!hasToken) {
        readycb(false,stream);
        clearTimeout(readyTimeout); 
      }
      return;
    }

    if(!stream.token) return stream.log('data from socket before auth/id token.',js);

    if(js.type == 'reply'){

      o = stream.callbacks[js.id]||{};

      if(o.id === undefined) return stream.log('got reply with no id mapping! ',js);


      var output = js.output||js.reply||"";
      var ret = js.return;// not set yet.

      if(!o.output) o.output = "";
      // handle chunked responses. they come in order.
      o.output += output;

      // soon the firmware will support returning the return int value of the scout script function/expression. it willbe the property return.
      if(ret) {
        o.return = ret;
      }

      js._cid = js.id;
      js.id = o.id;

      if(js.err || js.end) {

        delete stream.callbacks[js._cid];
        js.reply = js.output = o.output;
        js.return = o.return;
        o.cb(js.err,js)
      }

    } else if(js.type == "report" && line == stream._lastreport){
      // duplicate reports are not really useful to propagate as events because nothing changed.
      return;// stream.log('duplicate report ',line);
    } else if (js.type == "report") {
      stream._lastreport = line;
      stream.queue(js);// send report in stream.
    } else {
      stream.log('unknown message type',js);
    }
  }
757556
function CallRequest(flags, ttl, tracing, service, headers, csum, args) {
    this.type = CallRequest.TypeCode;
    this.flags = flags || 0;
    this.ttl = ttl || 0;
    this.tracing = tracing || Tracing.emptyTracing;
    this.service = service || '';
    this.headers = headers || {};
    this.csum = Checksum.objOrType(csum);
    this.args = args || [];
    this.cont = null;
}
1148919
function runRouteChat(callback) {
  var call = client.routeChat();
  call.on('data', function(note) {
    console.log('Got message "' + note.message + '" at ' +
        note.location.latitude + ', ' + note.location.longitude);
  });

  call.on('end', callback);

  var notes = [{
    location: {
      latitude: 0,
      longitude: 0
    },
    message: 'First message'
  }, {
    location: {
      latitude: 0,
      longitude: 1
    },
    message: 'Second message'
  }, {
    location: {
      latitude: 1,
      longitude: 0
    },
    message: 'Third message'
  }, {
    location: {
      latitude: 0,
      longitude: 0
    },
    message: 'Fourth message'
  }];
  for (var i = 0; i < notes.length; i++) {
    var note = notes[i];
    console.log('Sending message "' + note.message + '" at ' +
        note.location.latitude + ', ' + note.location.longitude);
    call.write(note);
  }
  call.end();
}
731561
function processRoute(opts) {
    if (routeHandler) {
        routeHandler(opts.request, opts.reply, opts.urlOverride, opts.returnCode);
    }
    else {
        opts.reply.continue();
    }
}
1065366
function(callback) {
  async.parallelAsync([
    tox.addGroupchat.bind(tox),
    tox.getAV().addGroupchat.bind(tox.getAV())
  ]).then(function(results) {
    groupchats['text'] = results[0];
    groupchats['av'] = results[1];
  }).finally(callback);
}
865495
function(params, callbacks, recursiveCallback) {
                /**
                 * + ChatMessage        {object}
                 *    - token           {string}
                 *    - tokenIssuer     {string}
                 *    - type            {int}
                 *    - typeCode        {string}
                 *    - messageType     {int}
                 *    - subjectId       {long}
                 *    - uniqueId        {string}
                 *    - content         {string}
                 *    - time            {long}
                 *    - medadata        {string}
                 *    - systemMedadata  {string}
                 *    - repliedTo       {long}
                 */

                var asyncPriority = (params.asyncPriority > 0)
                    ? params.asyncPriority
                    : msgPriority;

                var messageVO = {
                    type: params.chatMessageVOType,
                    token: token,
                    tokenIssuer: 1
                };

                var threadId = params.subjectId;

                if (params.typeCode) {
                    messageVO.typeCode = params.typeCode;
                }
                else if (generalTypeCode) {
                    messageVO.typeCode = generalTypeCode;
                }

                if (params.messageType) {
                    messageVO.messageType = params.messageType;
                }

                if (params.subjectId) {
                    messageVO.subjectId = params.subjectId;
                }

                if (params.content) {
                    if (typeof params.content == 'object') {
                        messageVO.content = JSON.stringify(params.content);
                    }
                    else {
                        messageVO.content = params.content;
                    }
                }

                if (params.metadata) {
                    messageVO.metadata = params.metadata;
                }

                if (params.systemMetadata) {
                    messageVO.systemMetadata = params.systemMetadata;
                }

                if (params.repliedTo) {
                    messageVO.repliedTo = params.repliedTo;
                }

                var uniqueId;

                if (typeof params.uniqueId != 'undefined') {
                    uniqueId = params.uniqueId;
                }
                else if (params.chatMessageVOType !== chatMessageVOTypes.PING) {
                    uniqueId = Utility.generateUUID();
                }

                if (Array.isArray(uniqueId)) {
                    messageVO.uniqueId = JSON.stringify(uniqueId);
                }
                else {
                    messageVO.uniqueId = uniqueId;
                }

                if (typeof callbacks == 'object') {
                    if (callbacks.onSeen || callbacks.onDeliver || callbacks.onSent) {
                        if (!threadCallbacks[threadId]) {
                            threadCallbacks[threadId] = {};
                        }

                        threadCallbacks[threadId][uniqueId] = {};

                        sendMessageCallbacks[uniqueId] = {};

                        if (callbacks.onSent) {
                            sendMessageCallbacks[uniqueId].onSent = callbacks.onSent;
                            threadCallbacks[threadId][uniqueId].onSent = false;
                            threadCallbacks[threadId][uniqueId].uniqueId = uniqueId;
                        }

                        if (callbacks.onSeen) {
                            sendMessageCallbacks[uniqueId].onSeen = callbacks.onSeen;
                            threadCallbacks[threadId][uniqueId].onSeen = false;
                        }

                        if (callbacks.onDeliver) {
                            sendMessageCallbacks[uniqueId].onDeliver = callbacks.onDeliver;
                            threadCallbacks[threadId][uniqueId].onDeliver = false;
                        }

                    }
                    else if (callbacks.onResult) {
                        messagesCallbacks[uniqueId] = callbacks.onResult;
                    }
                }
                else if (typeof callbacks == 'function') {
                    messagesCallbacks[uniqueId] = callbacks;
                }

                /**
                 * Message to send through async SDK
                 *
                 * + MessageWrapperVO  {object}
                 *    - type           {int}       Type of ASYNC message based on content
                 *    + content        {string}
                 *       -peerName     {string}    Name of receiver Peer
                 *       -receivers[]  {long}      Array of receiver peer ids (if you use this, peerName will be ignored)
                 *       -priority     {int}       Priority of message 1-10, lower has more priority
                 *       -messageId    {long}      Id of message on your side, not required
                 *       -ttl          {long}      Time to live for message in milliseconds
                 *       -content      {string}    Chat Message goes here after stringifying
                 *    - trackId        {long}      Tracker id of message that you receive from DIRANA previously (if you are replying a sync message)
                 */

                var data = {
                    type: (parseInt(params.pushMsgType) > 0)
                        ? params.pushMsgType
                        : 3,
                    content: {
                        peerName: serverName,
                        priority: asyncPriority,
                        content: JSON.stringify(messageVO),
                        ttl: (params.messageTtl > 0)
                            ? params.messageTtl
                            : messageTtl
                    }
                };

                asyncClient.send(data, function(res) {
                    if (res.hasError && callbacks) {
                        if (typeof callbacks == 'function') {
                            callbacks(res);
                        }
                        else if (typeof callbacks == 'object' && typeof callbacks.onResult == 'function') {
                            callbacks.onResult(res);
                        }

                        if (messagesCallbacks[uniqueId]) {
                            delete messagesCallbacks[uniqueId];
                        }
                    }
                });

                sendPingTimeout && clearTimeout(sendPingTimeout);
                sendPingTimeout = setTimeout(function() {
                    ping();
                }, chatPingMessageInterval);

                recursiveCallback && recursiveCallback();

                return {
                    uniqueId: uniqueId,
                    threadId: threadId,
                    participant: userInfo,
                    content: params.content
                };
            }
1260979
function(base_url, callback, cors) {
    var recv = new XhrReceiver(base_url + '/chunking_test', {cors: cors});
    var result = 0;
    recv.onmessage = function(e) {
        // Now a cool hack: we can stop receiving after we got at least
        // one chunk, contains some data, but not everyting.
        var l = e.responsetext.split('h\n').length;
        if(e.readystate === 3 && l > 0 && l < 6 ) {
            result = l;
            recv.abort();
        }
    };
    recv.onclose = function(e) {
        recv = recv.onmessage = recv.onclose = null;
        utils.log('Chunking test: ' + (result ? 'passed' : 'failed')
                  + ' (' + result + ' chunk received)');
        callback(!!result);
    };
}
441025
function Router() {
    var resources = {};

    // Public methods
    this.addRoute = function(resource) {
        var mPoint = resource.getMountPoint();

        if (typeof(resources[mPoint]) === 'undefined') {
            resources[mPoint] = resource;
        } else {
            resources[mPoint].update(resource);
        }
    };

    this.dispatch = function(locals) {
        var accept = locals.getAcceptedTypes();
        var request = locals.getRequest();
        var dispatched = false;
        var header;
        var mountPoint;
        var resource;

        locals.updateResponse(404);
        // Iterate over the resources
        for (mountPoint in resources) {
            // Did anybody flush already?
            resource = resources[mountPoint];
            // Does your URL definition matches this path?
            if (resource.matchesURL(request.path)) {
                locals.updateResponse(405);
                // Do you handle this method?
                if (resource.allowsMethod(request.method)) {
                    locals.updateResponse(406);
                    // Do you understand this format?
                    if (resource.acceptsType(accept, request.method)) {
                        locals.updateResponse(200);
                        // It's all yours
                        resource.takeOver(locals);
                        // And we set a flag announcing it was dispatched
                        dispatched = true;
                    }
                } else {
                    header = resource.getMethods().join(', ');
                    locals.getResponse().setHeader('Allow', header);
                }
            }
        }

        // Each resource emits a 'Resource:postRequest' event that flushes
        // the response. If no resource was found, that event was not emitted
        // and we need to do it manually.
        if (!dispatched) {
            locals.emit('Resource:completed');
            locals.emit('Resource:preRequest');
            locals.emit('Resource:postRequest');
        }
    };
}
229093
function serviceCall(req, res, next) {
        connector.runCall(req.params.connection, req.params.call, req.body).then(res.json.bind(res), next).done();
    }
431390
function Transport(location, callback) {
  if (false === (this instanceof Transport)) throw new Error('new operator required');
  if (typeof location != 'string') throw new Error('argument must a url string');
  if (typeof callback != 'function') throw new Error('argument must a callback');
  var self = this;
  self.connected = false;
  self.initialConnect = true;
  self.location = location;
  if (self.location === '') self.location = 'http host';
  self.socket = io.connect(location, {reconnection: false});
  self.socket.on('connect', function () {
    self.connected = true;
    self.initialConnect = false;
    console.log('socket.io (' + self.location + ') connected');
    callback.call(self, new Message('Connected', ''));
  });
  self.socket.on('connecting', function () {
    console.log('socket.io (' + self.location + ') connecting');
  });
  self.socket.on('error', function (reason) {
    var theError = 'general error with ' + self.location + (reason ? ', reason ' + reason : '');
    console.error(theError);
    // If have not ever connected then signal error
    if (self.initialConnect) {
      callback.call(self, new Message('Error', theError));
    }
  });
  self.socket.on('connect_error', function (reason) {
    var theError = 'connect error with ' + self.location + (reason ? ', reason ' + reason : '');
    console.error(theError);
    // If have not ever connected then signal error
    if (self.initialConnect) {
      callback.call(self, new Message('Error', theError));
    }
  });
  self.socket.on('connect_failed', function (reason) {
    var theError = 'connect failed with ' + self.location + (reason ? ', reason ' + reason : '');
    console.error(theError);
    // If have not ever connected then signal error
    if (self.initialConnect) {
      callback.call(self, new Message('Error', theError));
    }
  });
  self.socket.on('message', function (obj) {
    if (self.rawCallBack) {
      self.rawCallBack(obj);
    } else {
      console.log('socket.io (' + self.location + ') message: ' + obj);
    }
  });
  self.socket.on('disconnect', function (reason) {
    self.connected = false;
    console.log('socket.io (' + self.location + ') disconnect: ' + reason);
  });
}