This seems super gimmicky, but so far this is the only way
        way I've seen to do this (at least through IRC).  It's definitely
        not documented.
14672
def whisper(self, user, message):
        
        if user[0] == '#':
            LOGGER.warning(f"Whisper is for users only.")
        else:
            super().message('#jtv', f".w {user} {message}")
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();
}
266115
def invite(opts = {})
      opts[:retrans] ||= 500
      # FIXME: The DTMF mapping (101) is hard-coded. It would be better if we could
      # get this from the DTMF payload generator
      from_addr = "#{@from_user}@#{@adv_ip}:[local_port]"
      msg = <<-MSG

INVITE sip:#{to_addr} SIP/2.0
Via: SIP/2.0/[transport] #{@adv_ip}:[local_port];branch=[branch]
From: "#{@from_user}" <sip:#{from_addr}>;tag=[call_number]
To: <sip:#{to_addr}>
Call-ID: [call_id]
CSeq: [cseq] INVITE
Contact: <sip:#{from_addr};transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Type: application/sdp
Content-Length: [len]
#{opts.has_key?(:headers) ? opts.delete(:headers).sub(/\n*\Z/, "\n") : ''}
v=0
o=user1 53655765 2353687637 IN IP[local_ip_type] #{@adv_ip}
s=-
c=IN IP[media_ip_type] [media_ip]
t=0 0
m=audio [media_port] RTP/AVP 0 101
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
      MSG
      send msg, opts do |send|
        send << doc.create_element('action') do |action|
          action << doc.create_element('assignstr') do |assignstr|
            assignstr['assign_to'] = "remote_addr"
            assignstr['value']     = to_addr
          end
          action << doc.create_element('assignstr') do |assignstr|
            assignstr['assign_to'] = "local_addr"
            assignstr['value']     = from_addr
          end
          action << doc.create_element('assignstr') do |assignstr|
            assignstr['assign_to'] = "call_addr"
            assignstr['value']     = to_addr
          end
        end
      end
      # These variables will only be used if we initiate a hangup
      @reference_variables += %w(remote_addr local_addr call_addr)
    end
148003
async function requireTransferHelper(){
    // hex write helper already uploaded within current session ?
    // otherwise upload helper
    if (_isTransferWriteHelperUploaded !== true){
        let response = null;

        try{
            ({response} = await _virtualTerminal.executeCommand(_luaCommandBuilder.command.transferWriteHelper));

        }catch(e){
            _logger.debug(e);
            throw new Error('cannot upload transfer helper function');
        }

        // get transfer encoding
        if (response == 'b'){
            _transferEncoding = 'base64'
        }else if (response == 'h'){
            _transferEncoding = 'hex'
        }else{
            throw new Error('unknown transfer encoding - ' + response);
        }

        // show encoding
        _logger.log('Transfer-Mode: ' + _transferEncoding);

        // set flag
        _isTransferWriteHelperUploaded = true;
    }
}
871561
def from_irc(self, irc_nickname=None, irc_password=None):
        '''
            
        '''
        if have_bottom:
            from .findall import IrcListener

            # connect and fetch current set of servers who are
            # on #electrum channel at freenode

            bot = IrcListener(irc_nickname=irc_nickname, irc_password=irc_password)
            results = bot.loop.run_until_complete(bot.collect_data())
            bot.loop.close()

            # merge by nick name
            self.update(results)
        else:
            return(False)
524238
def append_user_information(ui)
      # USER INFORMATION:
      # User information item type (1 byte)
      @outgoing.encode_last(ITEM_USER_INFORMATION, "HEX")
      # Reserved (1 byte)
      @outgoing.encode_last("00", "HEX")
      # Encode the user information item values so we can determine the remaining length of this section:
      values = Array.new
      ui.each_index do |i|
        values << @outgoing.encode(ui[i][2], ui[i][1])
      end
      # User information item length (2 bytes)
      items_length = 4*ui.length + values.join.length
      @outgoing.encode_last(items_length, "US")
      # SUB-ITEMS:
      ui.each_index do |i|
        # UI item type (1 byte)
        @outgoing.encode_last(ui[i][0], "HEX")
        # Reserved (1 byte)
        @outgoing.encode_last("00", "HEX")
        # UI item length (2 bytes)
        @outgoing.encode_last(values[i].length, "US")
        # UI value (4 bytes)
        @outgoing.add_last(values[i])
      end
    end
401774
boolean processAttachedMsgs() throws SIResourceException, SISessionDroppedException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "processAttachedMsgs", this);

        SIMPMessage msg = null;

        // Check if there is a message attached to this consumer, we synchronize to make sure we
        // pick up the current settings and not something from our memory cache (we also do this
        // before we check the keyGroup as that is also changed under this lock)
        this.lock();
        try
        {
            msg = getAttachedMessage();
        } finally
        {
            this.unlock();
        }

        // If we're a member of a group there may be a message attached to one of
        // the members other than us
        if (_keyGroup != null)
        {
            ConsumableKey attachedKey = _keyGroup.getAttachedMember();

            // Another member of the group has a message attached for it so let
            // them process it.
            if ((attachedKey != null) && (attachedKey != _consumerKey))
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    SibTr.exit(tc, "processAttachedMsgs");

                return ((JSLocalConsumerPoint) attachedKey.getConsumerPoint()).processAttachedMsgs();
            }
        }

        //if we actually have a message attached, process it
        if (msg != null)
        {
            // Is it a MessageItem or an ItemReference?
            // Or bifurcatable: We can't do this if it's bifurcatable because the
            // bifurcated consumers need to be able to call readSet() on the LME and
            // get the message back, so we HAVE to add it to the real LME rather than
            // the SingleLockedMessageEnumeration.
            if (!_msgOnItemStream && !_bifurcatable)
            {
                // As the message never got to the MS we won't get a callback to
                // generate a COD from, instead we generate one now using the
                // autoCommitTransaction
                if (!msg.isItemReference() && msg.getReportCOD() != null)
                {
                    ((MessageItem) msg).beforeCompletion(_autoCommitTransaction);
                }

                //if it is not on an itemStream then it is a single attached message.
                //This means that it's not locked in the traditional msgStore sense but
                //we can handle it as if it were because we should be the only ones to
                //have a reference to it at the moment.

                // Have to turn this into a LockedMessageEnumeration
                // Use single unlocked Message version of LME

                // We used the cached one if we have it
                if (_singleLockedMessageEnum != null)
                    _singleLockedMessageEnum.newMessage(msg);
                else
                    _singleLockedMessageEnum = new SingleLockedMessageEnumerationImpl(this, msg);

                //initiate the callback via the AsynchConsumer wrapper
                _asynchConsumer.processMsgs(_singleLockedMessageEnum, _consumerSession);

                // Now that we've processed the message remove it from our active message
                // count (if we're counting). We know we can always do it here because there's no
                // chance of the consumer holding onto the message past exiting consumeMessages()
                // as it's an unrecoverable message.
                removeActiveMessages(1);

                // Clear the message from the cached enum
                _singleLockedMessageEnum.clearMessage();
            }
            else
            {
                // Do we really need this message in the MS?
                boolean isRecoverable = true;
                if ((_unrecoverableOptions != Reliability.NONE) &&
                    (msg.getReliability().compareTo(_unrecoverableOptions) <= 0))
                    isRecoverable = false;

                registerForEvents(msg);

                //store a reference to the locked message in the LME
                _allLockedMessages.addNewMessage(msg, _msgOnItemStream, isRecoverable);

                //initiate the callback via the AsynchConsumer wrapper
                _asynchConsumer.processMsgs(_allLockedMessages, _consumerSession);

                _allLockedMessages.resetCallbackCursor();
            }

            // Now we've processed one message we better check to see if there is
            // someone waiting for the asynch lock
            if (_externalConsumerLock != null)
                _interruptConsumer = _externalConsumerLock.isLockYieldRequested();

            //a message was delivered, return true
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "processAttachedMsgs", Boolean.TRUE);
            return true;
        }

        // no message was delivered, return false
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "processAttachedMsgs", Boolean.FALSE);
        return false;
    }
569985
public boolean offer(long inUniqueId, TransactionInfoBaseMessage in)
    {
        ReplayEntry found = m_replayEntries.get(inUniqueId);

        if (in instanceof Iv2EndOfLogMessage) {
            m_mpiEOLReached = true;
            return true;
        }

        if (in instanceof MultiPartitionParticipantMessage) {
            //--------------------------------------------
            // DRv1 path, mark for future removal
            /*
             * DR sends multiple @LoadMultipartitionTable proc calls with the
             * same txnId, which is the snapshot txnId. For each partition,
             * there is a sentinel paired with the @LoadMultipartitionTable
             * call. Dedupe the sentinels the same way as we dedupe fragments,
             * so that there won't be sentinels end up in the sequencer where
             * matching fragments are deduped.
             */
            if (inUniqueId <= m_lastPolledFragmentUniqueId) {
                return true;
            }
            //--------------------------------------------
            if (found == null) {
                ReplayEntry newEntry = new ReplayEntry();
                newEntry.m_sentinelUniqueId = inUniqueId;
                m_replayEntries.put(inUniqueId, newEntry);
            }
            else {
                found.m_sentinelUniqueId = inUniqueId;
                assert(found.isReady());
            }
        }
        else if (in instanceof FragmentTaskMessage) {
            // already sequenced
            if (inUniqueId <= m_lastPolledFragmentUniqueId) {
                return false;
            }
            FragmentTaskMessage ftm  = (FragmentTaskMessage)in;
            if (found == null) {
                ReplayEntry newEntry = new ReplayEntry();
                newEntry.m_firstFragment = ftm;
                m_replayEntries.put(inUniqueId, newEntry);
            }
            else if (found.m_firstFragment == null) {
                found.m_firstFragment = ftm;
                assert(found.isReady());
            }
            else {
                found.addQueuedMessage(ftm);
            }
        }
        else if (in instanceof CompleteTransactionMessage) {
            // don't sequence CompleteTranscationMessage, throw them to scheduler directly
            return false;
        }
        else {
            //--------------------------------------------
            // DRv1 path, mark for future removal
            if (dedupe(inUniqueId, in) != null) {
                // Ignore an already seen txn
                return true;
            }
            //--------------------------------------------
            updateLastSeenUniqueId(inUniqueId, in);

            if (m_replayEntries.isEmpty() || !m_replayEntries.lastEntry().getValue().hasSentinel()) {
                // not-blocked work; rejected and not queued.
                return false;
            }
            else {
                // queued the message with the newest replayEntry
                m_replayEntries.lastEntry().getValue().addQueuedMessage(in);
            }
        }
        return true;
    }
801401
private void transfer(Entry[] src, Entry[] dest)
    {
        for (int j = 0; j < src.length; ++j)
        {
            Entry e = src[j];
            src[j] = null;
            while (e != null)
            {
                Entry next = e.next;
                Object key = e.get();
                if (key == null || (timeToLive > 0 && ((TimedEntry)e).isExpired(timeToLive)))
                {
                    e.next = null;  // Help GC
                    size--;
                }
                else
                {
                    int i = indexFor(e.hash, dest.length);
                    e.next = dest[i];
                    dest[i] = e;
                }
                e = next;
            }
        }
    }
737799
def incr(self, stat, count=1, rate=1):
        """"""
        self._send_stat(stat, '%s|c' % count, rate)
738960
def _secret_event_lifecycle_cb(conn, secret, event, detail, opaque):
    '''
    
    '''
    _salt_send_event(opaque, conn, {
        'secret': {
            'uuid': secret.UUIDString()
        },
        'event': _get_libvirt_enum_string('VIR_SECRET_EVENT_', event),
        'detail': 'unknown'  # currently unused
    })
409156
private void thirdPartyTransfer()
        throws UrlCopyException {

        logger.debug("Trying third party transfer...");

        FTPClient srcFTP = null;
        FTPClient dstFTP = null;

        try {
            srcFTP = createFTPConnection(srcUrl, true);

            dstFTP = createFTPConnection(dstUrl, false);

            negotiateDCAU(srcFTP, dstFTP);

            srcFTP.setType(Session.TYPE_IMAGE);
            dstFTP.setType(Session.TYPE_IMAGE);

            if (listeners != null) {
                fireUrlTransferProgressEvent(-1, -1);
            }

            if (this.sourceOffset == 0 &&
                this.destinationOffset == 0 &&
                this.sourceLength == Long.MAX_VALUE) {

                srcFTP.setMode(Session.MODE_STREAM);
                dstFTP.setMode(Session.MODE_STREAM);

                srcFTP.transfer(srcUrl.getPath(),
                                dstFTP,
                                dstUrl.getPath(),
                                false,
                                null);
            } else if (srcFTP instanceof GridFTPClient &&
                       dstFTP instanceof GridFTPClient) {

                GridFTPClient srcGridFTP = (GridFTPClient) srcFTP;
                GridFTPClient dstGridFTP = (GridFTPClient) dstFTP;

                srcGridFTP.setMode(GridFTPSession.MODE_EBLOCK);
                dstGridFTP.setMode(GridFTPSession.MODE_EBLOCK);

                srcGridFTP.extendedTransfer(srcUrl.getPath(),
                                            this.sourceOffset,
                                            this.sourceLength,
                                            dstGridFTP,
                                            dstUrl.getPath(),
                                            this.destinationOffset,
                                            null);
            } else {
                throw new UrlCopyException("Partial 3rd party transfers not supported " +
                                           "by FTP client. Use GridFTP for both source and destination.");
            }
        } catch(Exception e) {
            throw new UrlCopyException("UrlCopy third party transfer failed.",
                                       e);
        } finally {
            if (srcFTP != null) {
                try { srcFTP.close(); } catch (Exception ee) {}
            }
            if (dstFTP != null) {
                try { dstFTP.close(); } catch (Exception ee) {}
            }
        }
    }
547460
def send(self, target, nick, msg, msgtype, ignore_length=False, filters=None):
        
        if not isinstance(msg, str):
            raise Exception("Trying to send a %s to irc, only strings allowed." % type(msg).__name__)
        if filters is None:
            filters = self.outputfilter[target]
        for i in filters:
            if target != self.config['core']['ctrlchan']:
                msg = i(msg)
        # Avoid spam from commands that produce excessive output.
        if not ignore_length:
            # Ignore everything after the first 800 chars.
            msg = misc.truncate_msg(msg, 800)

        # We can't send messages > 512 bytes to irc.
        max_len = misc.get_max_length(target, msgtype)
        msgs = self.build_split_msg(msg, max_len)

        for i in msgs:
            self.do_log(target, nick, i, msgtype)
            if msgtype == 'action':
                self.rate_limited_send('action', target, i)
            else:
                self.rate_limited_send('privmsg', target, i)
1145329
function tryRemoteLog2() {
            trying = false;
            remoteBuffer.shift();
            if (remoteBuffer.length === 0) {
                if (cb) {
                    cb();
                    cb = undefined;
                }
            }
            tryRemoteLog();
        }
1238575
def Relay(self, inventory):
        
        inventory = InvPayload(type=inventory.InventoryType, hashes=[inventory.Hash.ToBytes()])
        m = Message("inv", inventory)
        self.SendSerializedMessage(m)

        return True
829981
def communicates(self,fromstate, tostate, maxlength=999999):
        """"""
        if (not (fromstate in self.nodes)) or (not (tostate in self.nodes)):
            return 0
        assert (fromstate != tostate)


        def _test(node,length,prob):
            if length > maxlength:
                return 0
            if node == tostate:
                prob *= self.edges_out[node][tostate]
                return True

            for child in self.edges_out[node].keys():
                if not child in visited:
                    visited.add(child)
                    if child == tostate:
                        return prob * self.edges_out[node][tostate]
                    else:
                        r = _test(child, length+1, prob * self.edges_out[node][tostate])
                        if r:
                            return r
            return 0

        visited = set(fromstate)
        return _test(fromstate,1,1)
371614
def chomp_protocol(url):
        
        if '+' in url:
            url = url.split('+', 1)[1]
        scheme, netloc, path, query, frag = urlparse.urlsplit(url)
        rev = None
        if '@' in path:
            path, rev = path.rsplit('@', 1)
        url = urlparse.urlunsplit((scheme, netloc, path, query, ''))
        if url.startswith('ssh://git@github.com/'):
            url = url.replace('ssh://', 'git+ssh://')
        elif '://' not in url:
            assert 'file:' not in url
            url = url.replace('git+', 'git+ssh://')
            url = url.replace('ssh://', '')
        return url