this is a support function for halfTrickIce support. it sends a message to the peer when ice collection has finished on this side. it is only invoked for peers that have sent us a supportHalfTrickIce message.
500466
function checkIceGatheringState(otherPeer) {
        console.log("entered checkIceGatheringState");
        if( peerConns[otherPeer] && peerConns[otherPeer].pc && peerConns[otherPeer].pc.iceGatheringState ) {
           if( peerConns[otherPeer].pc.iceGatheringState === "complete" ) {
               self.sendPeerMessage(otherPeer, "iceGatheringDone", {});
               console.log("sent iceGatherDone message to ", otherPeer);
           } 
           else {
               setTimeout( function() {
                  checkIceGatheringState(otherPeer); 
               }, 500);
           }
        }
        else { 
           console.log("checkIceGatherState: leaving");
           // peer left, ignore
        }
    }
1034227
function ZeroPushErrorStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // There was an error when attempting to send message
  this.state.message = response.name + ': ' + response.message;

  if (response.name === 'InvalidPayloadError') this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
256927
private void sendFirstFragResponse()
    {
        if (ELASTICLOG.isDebugEnabled()) {
            ELASTICLOG.debug("P" + m_partitionId + " sending first fragment response to coordinator " +
                    CoreUtils.hsIdToString(m_coordinatorHsId));
        }
        RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(),
                RejoinMessage.Type.FIRST_FRAGMENT_RECEIVED);
        m_mailbox.send(m_coordinatorHsId, msg);
        m_firstFragResponseSent = true;
    }
840099
@Override
  public void handleMessage(PeerMessage msg) {
//    logger.trace("Received msg {} from {}", msg.getType(), this);
    if (isStopped.get())
      return;
    if (!torrent.isInitialized()) {
      torrent.initIfNecessary(this);
    }
    switch (msg.getType()) {
      case KEEP_ALIVE:
        // Nothing to do, we're keeping the connection open anyways.
        break;
      case CHOKE:
        this.choked = true;
        this.firePeerChoked();
        this.cancelPendingRequests();
        break;
      case UNCHOKE:
        this.choked = false;
        logger.trace("Peer {} is now accepting requests.", this);
        this.firePeerReady();
        break;
      case INTERESTED:
        this.interested = true;
        if (this.choking) {
          unchoke();
        }
        break;
      case NOT_INTERESTED:
        this.interested = false;
        if (!interesting) {
          unbind(true);
        }
        break;
      case HAVE:
        // Record this peer has the given piece
        PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg;
        Piece havePiece = this.torrent.getPiece(have.getPieceIndex());

        synchronized (this.availablePiecesLock) {
          this.availablePieces.set(havePiece.getIndex());
          logger.trace("Peer {} now has {} [{}/{}].",
                  new Object[]{
                          this,
                          havePiece,
                          this.availablePieces.cardinality(),
                          this.torrent.getPieceCount()
                  });
        }

        this.firePieceAvailabity(havePiece);
        break;
      case BITFIELD:
        // Augment the hasPiece bit field from this BITFIELD message
        PeerMessage.BitfieldMessage bitfield =
                (PeerMessage.BitfieldMessage) msg;

        synchronized (this.availablePiecesLock) {
          this.availablePieces.or(bitfield.getBitfield());
          logger.trace("Recorded bitfield from {} with {} " +
                          "pieces(s) [{}/{}].",
                  new Object[]{
                          this,
                          bitfield.getBitfield().cardinality(),
                          this.availablePieces.cardinality(),
                          this.torrent.getPieceCount()
                  });
        }

        this.fireBitfieldAvailabity();
        break;
      case REQUEST:
        PeerMessage.RequestMessage request =
                (PeerMessage.RequestMessage) msg;
        logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{
                Arrays.toString(TorrentUtils.getTorrentFileNames(torrent).toArray()),
                request.getPiece(),
                request.getLength(),
                request.getOffset(),
                this
        });
        Piece rp = this.torrent.getPiece(request.getPiece());

        // If we are choking from this peer and it still sends us
        // requests, it is a violation of the BitTorrent protocol.
        // Similarly, if the peer requests a piece we don't have, it
        // is a violation of the BitTorrent protocol. In these
        // situation, terminate the connection.
        if (!rp.isValid()) {
          logger.warn("Peer {} violated protocol, terminating exchange: " + this.isChoking() + " " + rp.isValid(), this);
          this.unbind(true);
          break;
        }

        if (request.getLength() >
                PeerMessage.RequestMessage.MAX_REQUEST_SIZE) {
          logger.warn("Peer {} requested a block too big, terminating exchange.", this);
          this.unbind(true);
          break;
        }

        // At this point we agree to send the requested piece block to
        // the remote peer, so let's queue a message with that block
        try {

          ByteBuffer bufferForMessage = PeerMessage.PieceMessage.createBufferWithHeaderForMessage(
                  request.getPiece(), request.getOffset(), request.getLength());

          rp.read(request.getOffset(), request.getLength(), bufferForMessage);

          this.send(PeerMessage.PieceMessage.craft(request.getPiece(),
                  request.getOffset(), bufferForMessage));
          this.upload.add(request.getLength());

          if (request.getOffset() + request.getLength() == rp.size()) {
            this.firePieceSent(rp);
          }
        } catch (IOException ioe) {
          logger.debug("error", ioe);
          this.fireIOException(new IOException(
                  "Error while sending piece block request!", ioe));
        }

        break;
      case PIECE:
        // Record the incoming piece block.

        // Should we keep track of the requested pieces and act when we
        // get a piece we didn't ask for, or should we just stay
        // greedy?
        PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg;
        Piece p = this.torrent.getPiece(piece.getPiece());

        logger.trace("Got piece ({} {}@{}) from {}", new Object[]{
                p.getIndex(),
                p.size(),
                piece.getOffset(),
                this
        });

        this.download.add(piece.getBlock().capacity());

        try {
          boolean isPieceDownloaded = false;
          synchronized (p) {
            // Remove the corresponding request from the request queue to
            //  make room for next block requests.
            this.removeBlockRequest(p);
            if (p.isValid()) {
              this.cancelPendingRequests(p);
              this.firePeerReady();
              logger.trace("Discarding block for already completed " + p);
              break;
            }
            //TODO add proper catch for IOException
            p.record(piece.getBlock(), piece.getOffset());

            // If the block offset equals the piece size and the block
            // length is 0, it means the piece has been entirely
            // downloaded. In this case, we have nothing to save, but
            // we should validate the piece.
            if (getRemainingRequestedPieces(p) == 0) {
              this.firePieceCompleted(p);
              isPieceDownloaded = true;
            }
          }
          if (isPieceDownloaded) {
            firePeerReady();
          }
        } catch (IOException ioe) {
          logger.error(ioe.getMessage(), ioe);
          this.fireIOException(new IOException(
                  "Error while storing received piece block!", ioe));
          break;
        }
        break;
      case CANCEL:
        // No need to support
        break;
    }
  }
716072
function onPeerClose(peer)
    {
        var id = peer.id;
        scope.removePeer(peer);
        sendPeerClose(id);

        scope.dispatchEvent("peerDisconnected",id);
    }
316821
function () {
        // check if the clients still exists
        var peer = self.swr.webrtc.getPeers(uid)[0]
        var success
        if (peer) {
          // success is true, if the message is successfully sent
          success = peer.sendDirectly('simplewebrtc', 'yjs', message)
        }
        if (!success) {
          // resend the message if it didn't work
          setTimeout(send, 500)
        }
      }
1196987
private boolean checkMisroutedIv2IntiateTaskMessage(Iv2InitiateTaskMessage message) {
        if (message.isForReplica()) {
            return false;
        }

        if (m_scheduler.isLeader() && m_migratePartitionLeaderStatus != MigratePartitionLeaderStatus.TXN_RESTART) {
            //At this point, the message is sent to partition leader
            return false;
        }

        //At this point, the message is misrouted.
        //(1) If a site has been demoted via @MigratePartitionLeader, the messages which are sent to the leader will be restarted.
        //(2) If a site becomes new leader via @MigratePartitionLeader. Transactions will be restarted before it gets notification from old
        //    leader that transactions on older leader have been drained.
        InitiateResponseMessage response = new InitiateResponseMessage(message);
        response.setMisrouted(message.getStoredProcedureInvocation());
        response.m_sourceHSId = getHSId();
        deliver(response);
        if (tmLog.isDebugEnabled()) {
            tmLog.debug("Sending message back on:" + CoreUtils.hsIdToString(m_hsId) + " isLeader:" + m_scheduler.isLeader() +
                    " status:" + m_migratePartitionLeaderStatus + "\n" + message);
        }
        //notify the new partition leader that the old leader has completed the Txns if needed.
        notifyNewLeaderOfTxnDoneIfNeeded();
        return true;
    }
934280
@ObjectiveCName("onConversationClosedWithPeer:")
    public void onConversationClosed(@NotNull Peer peer) {
        modules.getEvents().post(new PeerChatClosed(peer));
    }
272239
def notify_peer_message(self, message, sender_id):
        """"""
        payload = message.SerializeToString()
        self._notify(
            "consensus_notifier_notify_peer_message",
            payload,
            len(payload),
            sender_id,
            len(sender_id))
1041138
function(callback) {
  tox.on('friendRequest', function(evt) {
    console.log('Accepting friend request from ' + evt.publicKeyHex());
    // Automatically accept the request
    tox.addFriendNoRequestAsync(evt.publicKey()).then(function() {
      console.log('Successfully accepted the friend request!');
    }).catch(function(err) {
      console.error('Couldn\'t accept the friend request:', err);
    });
  });

  tox.on('friendMessage', function(evt) {
    console.log('Message from friend ' + evt.friend() + ': ' + evt.message());
    // Echo message back to friend
    tox.sendMessageAsync(evt.friend(), evt.message()).then(function(receipt) {
      console.log('Echoed message back to friend, received receipt ' + receipt);
    }).catch(function(err) {
      console.error('Couldn\'t echo message back to friend:', err);
    });
  });

  // Setup friendMessage callback to listen for groupchat invite requests
  tox.on('friendMessage', function(evt) {
    if(evt.message() === 'invite text') {
      tox.inviteAsync(evt.friend(), groupchats['text']).then(function() {
        console.log('Invited ' + evt.friend() + ' to the text groupchat');
      });
    } else if(evt.message() === 'invite av') {
      tox.inviteAsync(evt.friend(), groupchats['av']).then(function() {
        console.log('Invited ' + evt.friend() + ' to the audio/video groupchat');
      });
    }
  });

  callback();
}
1027920
@Override
  public void handlePeerReady(SharingPeer peer) {
    initIfNecessary(peer);

    RequestsCollection requestsCollection = getRequestsCollection(peer);
    requestsCollection.sendAllRequests();
  }
539496
function PeerDrain(peer, options, callback) {
    var chan = peer.channel.topChannel || peer.channel;

    assert(options, 'options is required');
    assert(options.reason, 'a reason is required');
    assert(!chan.draining, 'cannot drain a peer while channel is draining');
    assert(!options.goal ||
           options.goal === GOAL_NOOP ||
           options.goal === GOAL_CLOSE_DRAINED ||
           options.goal === GOAL_CLOSE_PEER,
           'expected a valid goal (if any)');

    this.goal = options.goal || PeerDrain.GOAL_NOOP;
    this.channel = chan;
    this.peer = peer;
    this.timeout = options.timeout || 0;
    this.reason = options.reason;
    this.direction = options.direction || 'both';
    this.callback = callback || null;
    this.timer = null;
    this.drained = null;
    this.startedAt = 0;
    this.stoppedAt = 0;
    this.finishedAt = 0;
    this.thenFinish = thenFinish;

    var self = this;

    function thenFinish(err) {
        var now = self.channel.timers.now();
        self.finish(err, now);
    }
}
600807
void setHalfEdgeUserIndex(int half_edge, int index, int value) {
		int i = getHalfEdgeIndex_(half_edge);
		AttributeStreamOfInt32 stream = m_edgeIndices.get(index);
		if (stream.size() <= i)
			stream.resize(m_halfEdgeData.size(), -1);

		stream.write(i, value);
	}
1094068
@Override
    protected void doStart() {

        try {
            sendTransportCandidatesOffer();
            setNegotiatorState(JingleNegotiatorState.PENDING);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.log(Level.WARNING, "exception", e);
        }

    }
41574
function success(item, ctx) {
		item.count++;

		if (item.state === C.CIRCUIT_HALF_OPEN_WAIT)
			circuitClose(item, ctx);
		else
			checkThreshold(item, ctx);
	}
452550
private void handleSendDataRequest(SerialMessage incomingMessage) {
		logger.trace("Handle Message Send Data Request");
		
		int callbackId = incomingMessage.getMessagePayloadByte(0);
		TransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));
		SerialMessage originalMessage = this.lastSentMessage;
		
		if (status == null) {
			logger.warn("Transmission state not found, ignoring.");
			return;
		}

		logger.debug("CallBack ID = {}", callbackId);
		logger.debug(String.format("Status = %s (0x%02x)", status.getLabel(), status.getKey()));
		
		if (originalMessage == null || originalMessage.getCallbackId() != callbackId) {
			logger.warn("Already processed another send data request for this callback Id, ignoring.");
			return;
		}
		
		switch (status) {
			case COMPLETE_OK:
				ZWaveNode node = this.getNode(originalMessage.getMessageNode());
				node.resetResendCount();
				
				// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.
				if (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {
					node.advanceNodeStage();
				}
				if (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				return;
			case COMPLETE_NO_ACK:
			case COMPLETE_FAIL:
			case COMPLETE_NOT_IDLE:
			case COMPLETE_NOROUTE:
				try {
					handleFailedSendDataRequest(originalMessage);
				} finally {
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
			default:
		}
	}
297482
@Override
    public void afterCompletion(TransactionCommon tran, boolean committed)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "afterCompletion", new Object[] { tran, Boolean.valueOf(committed) });

        // We don't care if the transaction committed or rolled back, either way
        // this callback indicates that a message that this consumer had active
        // is no longer active and therefore we should decrement the active message
        // count (this callback is called once per active message).
        removeActiveMessages(1);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "afterCompletion");
    }