text:
/* colibri.js -- a COLIBRI focus
 * The colibri spec has been submitted to the XMPP Standards Foundation
 * for publications as a XMPP extensions:
 * http://xmpp.org/extensions/inbox/colibri.html
 *
 * colibri.js is a participating focus, i.e. the focus participates
 * in the conference. The conference itself can be ad-hoc, through a
 * MUC, through PubSub, etc.
 *
 * colibri.js relies heavily on the strophe.jingle library available
 * from https://github.com/ESTOS/strophe.jingle
 * and interoperates with the Jitsi videobridge available from
 * https://jitsi.org/Projects/JitsiVideobridge
 */
/*
Copyright (c) 2013 ESTOS GmbH

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* jshint -W117 */
function ColibriFocus(connection, bridgejid) {
    this.connection = connection;
    this.bridgejid = bridgejid;
    this.peers = [];
    this.confid = null;

    this.peerconnection = null;

    this.sid = Math.random().toString(36).substr(2, 12);
    this.connection.jingle.sessions[this.sid] = this;
    this.mychannel = [];
    this.channels = [];
    this.remotessrc = {};

    // ssrc lines to be added on next update
    this.addssrc = [];
    // ssrc lines to be removed on next update
    this.removessrc = [];

    // silly wait flag
    this.wait = true;
}

// creates a conferences with an initial set of peers
ColibriFocus.prototype.makeConference = function (peers) {
    var self = this;
    if (this.confid !== null) {
        console.error('makeConference called twice? Ignoring...');
        // FIXME: just invite peers?
        return;
    }
    this.confid = 0; // !null
    this.peers = [];
    peers.forEach(function (peer) {
        self.peers.push(peer);
        self.channels.push([]);
    });

    this.peerconnection = new TraceablePeerConnection(this.connection.jingle.ice_config, this.connection.jingle.pc_constraints);
    this.peerconnection.addStream(this.connection.jingle.localStream);
    this.peerconnection.oniceconnectionstatechange = function (event) {
        console.warn('ice connection state changed to', self.peerconnection.iceConnectionState);
        /*
        if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
            console.log('adding new remote SSRCs from iceconnectionstatechange');
            window.setTimeout(function() { self.modifySources(); }, 1000);
        }
        */
    };
    this.peerconnection.onsignalingstatechange = function (event) {
        console.warn(self.peerconnection.signalingState);
        /*
        if (self.peerconnection.signalingState == 'stable' && self.peerconnection.iceConnectionState == 'connected') {
            console.log('adding new remote SSRCs from signalingstatechange');
            window.setTimeout(function() { self.modifySources(); }, 1000);
        }
        */
    };
    this.peerconnection.onaddstream = function (event) {
        self.remoteStream = event.stream;
        // search the jid associated with this stream
        Object.keys(self.remotessrc).forEach(function (jid) {
            if (self.remotessrc[jid].join('\r\n').indexOf('mslabel:' + event.stream.id) != -1) {
                event.peerjid = jid;
                if (self.connection.jingle.jid2session[jid]) {
                    self.connection.jingle.jid2session[jid].remotestream = event.stream;
                }
            }
        });
        $(document).trigger('remotestreamadded.jingle', [event, self.sid]);
    };
    this.peerconnection.onicecandidate = function (event) {
        self.sendIceCandidate(event.candidate);
    };
    this.peerconnection.createOffer(
        function (offer) {
            self.peerconnection.setLocalDescription(
                offer,
                function () {
                    // success
                    $(document).trigger('setLocalDescription.jingle', [self.sid]);
                    // FIXME: could call _makeConference here and trickle candidates later
                },
                function (error) {
                    console.log('setLocalDescription failed', error);
                }
            );
        },
        function (error) {
            console.warn(error);
        }
    );
    this.peerconnection.onicecandidate = function (event) {
        if (!event.candidate) {
            console.log('end of candidates');
            self._makeConference();
            return;
        }
    };
};

ColibriFocus.prototype._makeConference = function () {
    var self = this;
    var elem = $iq({to: this.bridgejid, type: 'get'});
    elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri'});

    var localSDP = new SDP(this.peerconnection.localDescription.sdp);
    localSDP.media.forEach(function (media, channel) {
        var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
        elem.c('content', {name: name});
        elem.c('channel', {initiator: 'false', expire: '15'});

        // FIXME: should reuse code from .toJingle
        var mline = SDPUtil.parse_mline(media.split('\r\n')[0]);
        for (var j = 0; j < mline.fmt.length; j++) {
            var rtpmap = SDPUtil.find_line(media, 'a=rtpmap:' + mline.fmt[j]);
            elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
            elem.up();
        }

        localSDP.TransportToJingle(channel, elem);

        elem.up(); // end of channel
        for (j = 0; j < self.peers.length; j++) {
            elem.c('channel', {initiator: 'true', expire:'15' }).up();
        }
        elem.up(); // end of content
    });

    this.connection.sendIQ(elem,
        function (result) {
            self.createdConference(result);
        },
        function (error) {
            console.warn(error);
        }
    );
};

// callback when a conference was created
ColibriFocus.prototype.createdConference = function (result) {
    console.log('created a conference on the bridge');
    var tmp;

    this.confid = $(result).find('>conference').attr('id');
    var remotecontents = $(result).find('>conference>content').get();
    var numparticipants = 0;
    for (var i = 0; i < remotecontents.length; i++) {
        tmp = $(remotecontents[i]).find('>channel').get();
        this.mychannel.push($(tmp.shift()));
        numparticipants = tmp.length;
        for (j = 0; j < tmp.length; j++) {
            if (this.channels[j] === undefined) {
                this.channels[j] = [];
            }
            this.channels[j].push(tmp[j]);
        }
    }
    console.log('remote channels', this.channels);
    var localSDP = new SDP(this.peerconnection.localDescription.sdp);
    localSDP.removeSessionLines('a=group:');
    localSDP.removeSessionLines('a=msid-semantic:');

    // establish our channel with the bridge
    // static answer taken from chrome M31, should be replaced by a
    // dynamic one that is based on our offer FIXME
    var bridgeSDP = new SDP("");
    // var bridgeSDP = new SDP('v=0\r\no=- 5151055458874951233 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1 RTP/SAVPF 111 103 104 0 8 106 105 13 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=mid:audio\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\na=fmtp:111 minptime=10\r\na=rtpmap:103 ISAC/16000\r\na=rtpmap:104 ISAC/32000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:106 CN/32000\r\na=rtpmap:105 CN/16000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:126 telephone-event/8000\r\na=maxptime:60\r\nm=video 1 RTP/SAVPF 100 116 117\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=mid:video\r\na=extmap:2 urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=rtpmap:100 VP8/90000\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 goog-remb\r\na=rtpmap:116 red/90000\r\na=rtpmap:117 ulpfec/90000\r\n');
    // only do what's in the offer
    bridgeSDP.session = localSDP.session;
    bridgeSDP.media.length = localSDP.media.length;
    var channel;
    for (channel = 0; channel < bridgeSDP.media.length; channel++) {
        bridgeSDP.media[channel] = '';
        // unchanged lines
        bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'm=') + '\r\n';
        bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'c=') + '\r\n';
        if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:')) {
            bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=rtcp:') + '\r\n';
        }
        if (SDPUtil.find_line(localSDP.media[channel], 'a=mid:')) {
            bridgeSDP.media[channel] += SDPUtil.find_line(localSDP.media[channel], 'a=mid:') + '\r\n';
        }
        if (SDPUtil.find_line(localSDP.media[channel], 'a=sendrecv')) {
            bridgeSDP.media[channel] += 'a=sendrecv\r\n';
        }
        if (SDPUtil.find_line(localSDP.media[channel], 'a=extmap:')) {
            bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=extmap:').join('\r\n') + '\r\n';
        }

        // FIXME: should look at m-line and group the ids together
        if (SDPUtil.find_line(localSDP.media[channel], 'a=rtpmap:')) {
            bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtpmap:').join('\r\n') + '\r\n';
        }
        if (SDPUtil.find_line(localSDP.media[channel], 'a=fmtp:')) {
            bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=fmtp:').join('\r\n') + '\r\n';
        }
        if (SDPUtil.find_line(localSDP.media[channel], 'a=rtcp-fb:')) {
            bridgeSDP.media[channel] += SDPUtil.find_lines(localSDP.media[channel], 'a=rtcp-fb:').join('\r\n') + '\r\n';
        }
        // FIXME: changed lines -- a=sendrecv direction, a=setup direction
    }
    // get the mixed ssrc
    for (channel = 0; channel < bridgeSDP.media.length; channel++) {
        tmp = $(this.mychannel[channel]).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
        // FIXME: check rtp-level-relay-type
        if (tmp.length) {
            bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
            bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
            bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
            bridgeSDP.media[channel] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
        } else {
            // make chrome happy... '3735928559' == 0xDEADBEEF
            // FIXME: this currently appears as two streams, should be one
            bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
            bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
            bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
            bridgeSDP.media[channel] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
        }

        // FIXME: should take code from .fromJingle
        tmp = $(this.mychannel[channel]).find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
        if (tmp.length) {
            bridgeSDP.media[channel] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
            bridgeSDP.media[channel] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
            tmp.find('>candidate').each(function () {
                bridgeSDP.media[channel] += SDPUtil.candidateFromJingle(this);
            });
            tmp = tmp.find('>fingerprint');
            if (tmp.length) {
                bridgeSDP.media[channel] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
                if (tmp.attr('setup')) {
                    bridgeSDP.media[channel] += 'a=setup:' + tmp.attr('setup') + '\r\n';
                } else {
                    bridgeSDP.media[channel] += 'a=setup:active\r\n';
                }
            }
        }
    }
    bridgeSDP.raw = bridgeSDP.session + bridgeSDP.media.join('');

    var self = this;
    this.peerconnection.setRemoteDescription(
        new RTCSessionDescription({type: 'answer', sdp: bridgeSDP.raw}),
        function () {
            console.log('setRemoteDescription success');
            for (var i = 0; i < numparticipants; i++) {
                self.initiate(self.peers[i], true);
            }
        },
        function (error) {
            console.log('setRemoteDescription failed');
        }
    );

};

// send a session-initiate to a new participant
ColibriFocus.prototype.initiate = function (peer, isInitiator) {
    var participant = this.peers.indexOf(peer);
    console.log('tell', peer, participant);
    var sdp;
    if (this.peerconnection !== null && this.peerconnection.signalingState == 'stable') {
        sdp = new SDP(this.peerconnection.remoteDescription.sdp);
        var localSDP = new SDP(this.peerconnection.localDescription.sdp);
        // throw away stuff we don't want
        // not needed with static offer
        sdp.removeSessionLines('a=group:');
        sdp.removeSessionLines('a=msid-semantic:'); // FIXME: not mapped over jingle anyway...
        for (var i = 0; i < sdp.media.length; i++) {
            sdp.removeMediaLines(i, 'a=rtcp-mux');
            sdp.removeMediaLines(i, 'a=ssrc:');
            sdp.removeMediaLines(i, 'a=crypto:');
            sdp.removeMediaLines(i, 'a=candidate:');
            sdp.removeMediaLines(i, 'a=ice-options:google-ice');
            sdp.removeMediaLines(i, 'a=ice-ufrag:');
            sdp.removeMediaLines(i, 'a=ice-pwd:');
            sdp.removeMediaLines(i, 'a=fingerprint:');
            sdp.removeMediaLines(i, 'a=setup:');

            if (1) { //i > 0) { // not for audio FIXME: does not work as intended
                // re-add all remote a=ssrcs
                for (var jid in this.remotessrc) {
                    if (jid == peer) continue;
                    sdp.media[i] += this.remotessrc[jid][i];
                }
                // and local a=ssrc lines
                sdp.media[i] += SDPUtil.find_lines(localSDP.media[i], 'a=ssrc').join('\r\n') + '\r\n';
            }
        }
        sdp.raw = sdp.session + sdp.media.join('');
    } else {
        console.error('can not initiate a new session without a stable peerconnection');
        return;
    }

    // add stuff we got from the bridge
    for (var j = 0; j < sdp.media.length; j++) {
        var chan = $(this.channels[participant][j]);
        console.log('channel id', chan.attr('id'));

        tmp = chan.find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
        if (tmp.length) {
            sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'cname:mixed' + '\r\n';
            sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'label:mixedlabela0' + '\r\n';
            sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'msid:mixedmslabel mixedlabela0' + '\r\n';
            sdp.media[j] += 'a=ssrc:' + tmp.attr('ssrc') + ' ' + 'mslabel:mixedmslabel' + '\r\n';
        } else {
            // make chrome happy... '3735928559' == 0xDEADBEEF
            sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'cname:mixed' + '\r\n';
            sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'label:mixedlabelv0' + '\r\n';
            sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'msid:mixedmslabel mixedlabelv0' + '\r\n';
            sdp.media[j] += 'a=ssrc:' + '3735928559' + ' ' + 'mslabel:mixedmslabel' + '\r\n';
        }

        tmp = chan.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
        if (tmp.length) {
            if (tmp.attr('ufrag'))
                sdp.media[j] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
            if (tmp.attr('pwd'))
                sdp.media[j] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
            // and the candidates...
            tmp.find('>candidate').each(function () {
                sdp.media[j] += SDPUtil.candidateFromJingle(this);
            });
            tmp = tmp.find('>fingerprint');
            if (tmp.length) {
                sdp.media[j] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
                /*
                if (tmp.attr('direction')) {
                    sdp.media[j] += 'a=setup:' + tmp.attr('direction') + '\r\n';
                }
                */
                sdp.media[j] += 'a=setup:actpass\r\n';
            }
        }
    }
    // make a new colibri session and configure it
    // FIXME: is it correct to use this.connection.jid when used in a MUC?
    var sess = new ColibriSession(this.connection.jid,
                                  Math.random().toString(36).substr(2, 12), // random string
                                  this.connection);
    sess.initiate(peer);
    sess.colibri = this;
    sess.localStream = this.connection.jingle.localStream;
    sess.media_constraints = this.connection.jingle.media_constraints;
    sess.pc_constraints = this.connection.jingle.pc_constraints;
    sess.ice_config = this.connection.jingle.ice_config;

    this.connection.jingle.sessions[sess.sid] = sess;
    this.connection.jingle.jid2session[sess.peerjid] = sess;

    // send a session-initiate
    var init = $iq({to: peer, type: 'set'})
        .c('jingle',
            {xmlns: 'urn:xmpp:jingle:1',
             action: 'session-initiate',
             initiator: sess.me,
             sid: sess.sid
            }
    );
    sdp.toJingle(init, 'initiator');
    this.connection.sendIQ(init,
        function (res) {
            console.log('got result');
        },
        function (err) {
            console.log('got error');
        }
    );
};

// pull in a new participant into the conference
ColibriFocus.prototype.addNewParticipant = function (peer) {
    var self = this;
    if (this.confid === 0) {
        // bad state
        console.log('confid does not exist yet, postponing', peer);
        window.setTimeout(function () {
            self.addNewParticipant(peer);
        }, 250);
        return;
    }
    var index = this.channels.length;
    this.channels.push([]);
    this.peers.push(peer);

    var elem = $iq({to: this.bridgejid, type: 'get'});
    elem.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
    var localSDP = new SDP(this.peerconnection.localDescription.sdp);
    localSDP.media.forEach(function (media, channel) {
        var name = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
        elem.c('content', {name: name});
        elem.c('channel', {initiator: 'true', expire:'15'});
        elem.up(); // end of channel
        elem.up(); // end of content
    });

    this.connection.sendIQ(elem,
        function (result) {
            var contents = $(result).find('>conference>content').get();
            for (var i = 0; i < contents.length; i++) {
                tmp = $(contents[i]).find('>channel').get();
                self.channels[index][i] = tmp[0];
            }
            self.initiate(peer, true);
        },
        function (error) {
            console.warn(error);
        }
    );
};

// update the channel description (payload-types + dtls fp) for a participant
ColibriFocus.prototype.updateChannel = function (remoteSDP, participant) {
    console.log('change allocation for', this.confid);
    var change = $iq({to: this.bridgejid, type: 'set'});
    change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
    for (channel = 0; channel < this.channels[participant].length; channel++) {
        change.c('content', {name: channel === 0 ? 'audio' : 'video'});
        change.c('channel', {id: $(this.channels[participant][channel]).attr('id')});

        var rtpmap = SDPUtil.find_lines(remoteSDP.media[channel], 'a=rtpmap:');
        rtpmap.forEach(function (val) {
            // TODO: too much copy-paste
            var rtpmap = SDPUtil.parse_rtpmap(val);
            change.c('payload-type', rtpmap);
            //
            // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
            /*
            if (SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id)) {
                tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(remoteSDP.media[channel], 'a=fmtp:' + rtpmap.id));
                for (var k = 0; k < tmp.length; k++) {
                    change.c('parameter', tmp[k]).up();
                }
            }
            */
            change.up();
        });
        // now add transport
        remoteSDP.TransportToJingle(channel, change);

        change.up(); // end of channel
        change.up(); // end of content
    }
    this.connection.sendIQ(change,
        function (res) {
            console.log('got result');
        },
        function (err) {
            console.log('got error');
        }
    );
};

// tell everyone about a new participants a=ssrc lines (isadd is true)
// or a leaving participants a=ssrc lines
// FIXME: should not take an SDP, but rather the a=ssrc lines and probably a=mid
ColibriFocus.prototype.sendSSRCUpdate = function (sdp, jid, isadd) {
    var self = this;
    this.peers.forEach(function (peerjid) {
        if (peerjid == jid) return;
        console.log('tell', peerjid, 'about ' + (isadd ? 'new' : 'removed') + ' ssrcs from', jid);
        if (!self.remotessrc[peerjid]) {
            // FIXME: this should only send to participants that are stable, i.e. who have sent a session-accept
            // possibly, this.remoteSSRC[session.peerjid] does not exist yet
            console.warn('do we really want to bother', peerjid, 'with updates yet?');
        }
        var channel;
        var peersess = self.connection.jingle.jid2session[peerjid];
        var modify = $iq({to: peerjid, type: 'set'})
            .c('jingle', {
                xmlns: 'urn:xmpp:jingle:1',
                action: isadd ? 'addsource' : 'removesource',
                initiator: peersess.initiator,
                sid: peersess.sid
            }
        );
        // FIXME: only announce video ssrcs since we mix audio and dont need
        //      the audio ssrcs therefore
        var modified = false;
        for (channel = 0; channel < sdp.media.length; channel++) {
            modified = true;
            tmp = SDPUtil.find_lines(sdp.media[channel], 'a=ssrc:');
            modify.c('content', {name: SDPUtil.parse_mid(SDPUtil.find_line(sdp.media[channel], 'a=mid:'))});
            modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
            // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
            tmp.forEach(function (line) {
                var idx = line.indexOf(' ');
                var linessrc = line.substr(0, idx).substr(7);
                modify.attrs({ssrc: linessrc});

                var kv = line.substr(idx + 1);
                modify.c('parameter');
                if (kv.indexOf(':') == -1) {
                    modify.attrs({ name: kv });
                } else {
                    modify.attrs({ name: kv.split(':', 2)[0] });
                    modify.attrs({ value: kv.split(':', 2)[1] });
                }
                modify.up();
            });
            modify.up(); // end of source
            modify.up(); // end of content
        }
        if (modified) {
            self.connection.sendIQ(modify,
                function (res) {
                    console.warn('got modify result');
                },
                function (err) {
                    console.warn('got modify error');
                }
            );
        } else {
            console.log('modification not necessary');
        }
    });
};

ColibriFocus.prototype.setRemoteDescription = function (session, elem, desctype) {
    var participant = this.peers.indexOf(session.peerjid);
    console.log('Colibri.setRemoteDescription from', session.peerjid, participant);
    var self = this;
    var remoteSDP = new SDP('');
    var tmp;
    var channel;
    remoteSDP.fromJingle(elem);

    // ACT 1: change allocation on bridge
    this.updateChannel(remoteSDP, participant);

    // ACT 2: tell anyone else about the new SSRCs
    this.sendSSRCUpdate(remoteSDP, session.peerjid, true);

    // ACT 3: note the SSRCs
    this.remotessrc[session.peerjid] = [];
    for (channel = 0; channel < this.channels[participant].length; channel++) {
        //if (channel == 0) continue; FIXME: does not work as intended
        this.remotessrc[session.peerjid][channel] = SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n';
    }

    // ACT 4: add new a=ssrc lines to local remotedescription
    for (channel = 0; channel < this.channels[participant].length; channel++) {
        //if (channel == 0) continue; FIXME: does not work as intended
        if (!this.addssrc[channel]) this.addssrc[channel] = '';
        this.addssrc[channel] += SDPUtil.find_lines(remoteSDP.media[channel], 'a=ssrc:').join('\r\n') + '\r\n';
    }
    this.modifySources();
};

// relay ice candidates to bridge using trickle
ColibriFocus.prototype.addIceCandidate = function (session, elem) {
    var self = this;
    var participant = this.peers.indexOf(session.peerjid);
    //console.log('change transport allocation for', this.confid, session.peerjid, participant);
    var change = $iq({to: this.bridgejid, type: 'set'});
    change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
    $(elem).each(function () {
        var name = $(this).attr('name');
        var channel = name == 'audio' ? 0 : 1; // FIXME: search mlineindex in localdesc

        change.c('content', {name: name});
        change.c('channel', {id: $(self.channels[participant][channel]).attr('id')});
        $(this).find('>transport').each(function () {
            change.c('transport', {
                ufrag: $(this).attr('ufrag'),
                pwd: $(this).attr('pwd'),
                xmlns: $(this).attr('xmlns')
            });

            $(this).find('>candidate').each(function () {
                /* not yet
                if (this.getAttribute('protocol') == 'tcp' && this.getAttribute('port') == 0) {
                    // chrome generates TCP candidates with port 0
                    return;
                }
                */
                var line = SDPUtil.candidateFromJingle(this);
                change.c('candidate', SDPUtil.candidateToJingle(line)).up();
            });
            change.up(); // end of transport
        });
        change.up(); // end of channel
        change.up(); // end of content
    });
    // FIXME: need to check if there is at least one candidate when filtering TCP ones
    this.connection.sendIQ(change,
        function (res) {
            console.log('got result');
        },
        function (err) {
            console.warn('got error');
        }
    );
};

// send our own candidate to the bridge
ColibriFocus.prototype.sendIceCandidate = function (candidate) {
    //console.log('candidate', candidate);
    if (!candidate) {
        console.log('end of candidates');
        return;
    }
    var mycands = $iq({to: this.bridgejid, type: 'set'});
    mycands.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
    mycands.c('content', {name: candidate.sdpMid });
    mycands.c('channel', {id: $(this.mychannel[candidate.sdpMLineIndex]).attr('id')});
    mycands.c('transport', {xmlns: 'urn:xmpp:jingle:transports:ice-udp:1'});
    tmp = SDPUtil.candidateToJingle(candidate.candidate);
    mycands.c('candidate', tmp).up();
    this.connection.sendIQ(mycands,
        function (res) {
            console.log('got result');
        },
        function (err) {
            console.warn('got error');
        }
    );
};

ColibriFocus.prototype.terminate = function (session, reason) {
    console.log('remote session terminated from', session.peerjid);
    var participant = this.peers.indexOf(session.peerjid);
    if (!this.remotessrc[session.peerjid] || participant == -1) {
        return;
    }
    var ssrcs = this.remotessrc[session.peerjid];
    for (var i = 0; i < ssrcs.length; i++) {
        if (!this.removessrc[i]) this.removessrc[i] = '';
        this.removessrc[i] += ssrcs[i];
    }
    // remove from this.peers
    this.peers.splice(participant, 1);
    // expire channel on bridge
    var change = $iq({to: this.bridgejid, type: 'set'});
    change.c('conference', {xmlns: 'http://jitsi.org/protocol/colibri', id: this.confid});
    for (var channel = 0; channel < this.channels[participant].length; channel++) {
        change.c('content', {name: channel === 0 ? 'audio' : 'video'});
        change.c('channel', {id: $(this.channels[participant][channel]).attr('id'), expire: '0'});
        change.up(); // end of channel
        change.up(); // end of content
    }
    this.connection.sendIQ(change,
        function (res) {
            console.log('got result');
        },
        function (err) {
            console.log('got error');
        }
    );
    // and remove from channels
    this.channels.splice(participant, 1);

    // tell everyone about the ssrcs to be removed
    var sdp = new SDP('');
    var localSDP = new SDP(this.peerconnection.localDescription.sdp);
    var contents = SDPUtil.find_lines(localSDP.raw, 'a=mid:').map(SDPUtil.parse_mid);
    for (var j = 0; j < ssrcs.length; j++) {
        sdp.media[j] = 'a=mid:' + contents[j] + '\r\n';
        sdp.media[j] += ssrcs[j];
        this.removessrc[j] += ssrcs[j];
    }
    this.sendSSRCUpdate(sdp, session.peerjid, false);

    delete this.remotessrc[session.peerjid];
    this.modifySources();
};

ColibriFocus.prototype.modifySources = function () {
    var self = this;
    if (!(this.addssrc.length || this.removessrc.length)) return;
    if (this.peerconnection.signalingState == 'closed') return;

    // FIXME: this is a big hack
    // https://code.google.com/p/webrtc/issues/detail?id=2688
    if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
        console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
        window.setTimeout(function () { self.modifySources(); }, 250);
        this.wait = true;
        return;
    }
    if (this.wait) {
        window.setTimeout(function () { self.modifySources(); }, 2500);
        this.wait = false;
        return;
    }
    var sdp = new SDP(this.peerconnection.remoteDescription.sdp);

    // add sources
    this.addssrc.forEach(function (lines, idx) {
        sdp.media[idx] += lines;
    });
    this.addssrc = [];

    // remove sources
    this.removessrc.forEach(function (lines, idx) {
        lines = lines.split('\r\n');
        lines.pop(); // remove empty last element;
        lines.forEach(function (line) {
            sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
        });
    });
    this.removessrc = [];

    sdp.raw = sdp.session + sdp.media.join('');
    /*
     * this seems to create a number of problems...
    this.peerconnection.setRemoteDescription(
        new RTCSessionDescription({type: 'offer', sdp: sdp.raw }),
        function () {
            console.log('setModifiedRemoteDescription ok');
            self.peerconnection.createAnswer(
                function (modifiedAnswer) {
                    console.log('modifiedAnswer created', modifiedAnswer.sdp);
                    // FIXME: pushing down an answer while ice connection state
                    // is still checking is bad...
                    console.log(self.peerconnection.iceConnectionState);

                    // trying to work around another chrome bug
                    //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
                    self.peerconnection.setLocalDescription(modifiedAnswer,
                        function () {
                            console.log('setModifiedLocalDescription ok');
                            $(document).trigger('setLocalDescription.jingle', [self.sid]);
                        },
                        function (error) {
                            console.log('setModifiedLocalDescription failed');
                        }
                    );
                },
                function (error) {
                    console.log('createModifiedAnswer failed');
                }
            );
        },
        function (error) {
            console.log('setModifiedRemoteDescription failed');
        }
    );
    */
    this.peerconnection.createOffer(
        function (modifiedOffer) {
            console.log('created (un)modified offer');
            self.peerconnection.setLocalDescription(modifiedOffer,
                function () {
                    console.log('setModifiedLocalDescription ok');
                    self.peerconnection.setRemoteDescription(
                        new RTCSessionDescription({type: 'answer', sdp: sdp.raw }),
                        function () {
                            console.log('setModifiedRemoteDescription ok');
                        },
                        function (error) {
                            console.log('setModifiedRemoteDescription failed');
                        }
                    );
                    $(document).trigger('setLocalDescription.jingle', [self.sid]);
                },
                function (error) {
                    console.log('setModifiedLocalDescription failed');
                }
            );
        },
        function (error) {
            console.log('creating (un)modified offerfailed');
        }
    );
};

// A colibri session is similar to a jingle session, it just implements some things differently
// FIXME: inherit jinglesession, see https://github.com/legastero/Jingle-RTCPeerConnection/blob/master/index.js
function ColibriSession(me, sid, connection) {
    this.me = me;
    this.sid = sid;
    this.connection = connection;
    //this.peerconnection = null;
    //this.mychannel = null;
    //this.channels = null;
    this.peerjid = null;

    this.colibri = null;
}

// implementation of JingleSession interface
ColibriSession.prototype.initiate = function (peerjid, isInitiator) {
    this.peerjid = peerjid;
};

ColibriSession.prototype.sendOffer = function (offer) {
    console.log('ColibriSession.sendOffer');
};

ColibriSession.prototype.accept = function () {
    console.log('ColibriSession.accept');
};

ColibriSession.prototype.terminate = function (reason) {
    this.colibri.terminate(this, reason);
};

ColibriSession.prototype.active = function () {
    console.log('ColibriSession.active');
};

ColibriSession.prototype.setRemoteDescription = function (elem, desctype) {
    this.colibri.setRemoteDescription(this, elem, desctype);
};

ColibriSession.prototype.addIceCandidate = function (elem) {
    this.colibri.addIceCandidate(this, elem);
};

ColibriSession.prototype.sendAnswer = function (sdp, provisional) {
    console.log('ColibriSession.sendAnswer');
};

ColibriSession.prototype.sendTerminate = function (reason, text) {
    console.log('ColibriSession.sendTerminate');
};


text:
package main

import (
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	log "github.com/sirupsen/logrus"
	"k8s.io/client-go/kubernetes"
)

var _ = Describe("calculation graph scale test", func() {

	var (
		clientset *kubernetes.Clientset
		nsPrefix  string
	)

	BeforeEach(func() {
		log.Info(">>> BeforeEach <<<")
		clientset = initialize(k8sServerEndpoint)
		nsPrefix = getNamespacePrefix()
		expectFelixReady()
	})

	It("should run label rotation test", func() {
		Expect(rotateLabels(clientset, nsPrefix)).To(BeNil())
	})

	It("should process 1000 pods", func() {
		Expect(create1000Pods(clientset, nsPrefix)).To(BeNil())
	})

	AfterEach(func() {
		log.Info(">>> AfterEach <<<")
		time.Sleep(10 * time.Second)
		cleanupAll(clientset, nsPrefix)
	})
})

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.NavigateTo;

namespace Microsoft.CodeAnalysis.Remote
{
    internal partial class CodeAnalysisService : IRemoteNavigateToSearchService
    {
        public Task<IList<SerializableNavigateToSearchResult>> SearchDocumentAsync(
            DocumentId documentId, string searchPattern, string[] kinds, CancellationToken cancellationToken)
        {
            return RunServiceAsync(async token =>
            {
                using (UserOperationBooster.Boost())
                {
                    var solution = await GetSolutionAsync(token).ConfigureAwait(false);

                    var project = solution.GetDocument(documentId);
                    var result = await AbstractNavigateToSearchService.SearchDocumentInCurrentProcessAsync(
                        project, searchPattern, kinds.ToImmutableHashSet(), token).ConfigureAwait(false);

                    return Convert(result);
                }
            }, cancellationToken);
        }

        public Task<IList<SerializableNavigateToSearchResult>> SearchProjectAsync(
            ProjectId projectId, DocumentId[] priorityDocumentIds, string searchPattern, string[] kinds, CancellationToken cancellationToken)
        {
            return RunServiceAsync(async token =>
            {
                using (UserOperationBooster.Boost())
                {
                    var solution = await GetSolutionAsync(token).ConfigureAwait(false);

                    var project = solution.GetProject(projectId);
                    var priorityDocuments = priorityDocumentIds.Select(d => solution.GetDocument(d))
                                                               .ToImmutableArray();

                    var result = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync(
                        project, priorityDocuments, searchPattern, kinds.ToImmutableHashSet(), token).ConfigureAwait(false);

                    return Convert(result);
                }
            }, cancellationToken);
        }

        private IList<SerializableNavigateToSearchResult> Convert(
            ImmutableArray<INavigateToSearchResult> result)
        {
            return result.SelectAsArray(SerializableNavigateToSearchResult.Dehydrate);
        }
    }
}


text:
import angular from 'angular';
import threeNumbersAlwaysFilter from './threeNumbersAlways.filter';

let threeNumbersAlwaysModule = angular.module('threeNumbersAlways', [])

.filter('threeNumbersAlways', threeNumbersAlwaysFilter)

.name;

export default threeNumbersAlwaysModule;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <title>Sample UL</title>

    <link  href="../../../../dist/css/ionic.css" rel="stylesheet">

    <ion-header-bar class="bar-positive">

Hi

        Bottom

    </ion-header-bar>
    <ion-content>
        <ion-refresher on-refresh="loadMore()"></ion-refresher>

      Hi, I'm some text before the list.

        Hi, I'm a card before the list.

      <ion-list>
        <ion-item
          class="item-avatar-left item-icon-right"
          ng-click="alert(item)"
          collection-repeat="item in items"
          collection-item-height="85"
          collection-item-width="'100%'"
          ng-style="{height: '85px'}"
          style="left: 0; right: 0;">

{{item.text}}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis porttitor diam urna, vitae consectetur lectus aliquet quis.

        </ion-item>
      </ion-list>
      <ion-infinite-scroll on-infinite="loadMore()"></ion-infinite-scroll>

        Hi, I'm a card after the list.

    </ion-content>


text:
from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)

serverPort = 5612

serverSocket.bind(('', serverPort))

serverSocket.listen(1)
filename = ''
while True:
    if filename == '':
        (clientsocket, address) = serverSocket.accept()
        l = clientsocket.recv(4096)
        try:
            filename = l.splitlines()[0]
        except:
            pass
        clientsocket.send('A-ACK\n')
    if filename is not '':
        print "file is set!"
        print filename
        f = open(filename, 'wb')
        l = clientsocket.recv(4096)
        while(l):
            f.write(l)
            l = clientsocket.recv(4096)
        f.close()
        filename = ''
        print "Done"

        clientsocket.close()


text:
package com.suzhou.carmanager.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.suzhou.carmanager.AppHelper;
import com.suzhou.carmanager.Constants;
import com.suzhou.carmanager.R;
import com.suzhou.carmanager.base.BaseActivity;
import com.suzhou.carmanager.entity.NetMessageVO;
import com.suzhou.carmanager.entity.SystemConfig;
import com.suzhou.carmanager.entity.UserInfo;
import com.suzhou.carmanager.helper.SharePreferenceHelper;
import com.suzhou.carmanager.network.CarApiManager;
import com.suzhou.carmanager.network.HttpData;
import com.suzhou.carmanager.network.RxJava.MySubscriber;
import com.suzhou.carmanager.utils.ExampleUtil;
import com.suzhou.carmanager.utils.FrescoUtils;
import com.suzhou.carmanager.utils.ParseJsonUtils;
import com.suzhou.carmanager.utils.UIUtils;
import com.suzhou.carmanager.view.CustomCountDownTimer;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2017/1/1.
 */
public class SplashActivity extends BaseActivity{

    private static final String TAG = SplashActivity.class.getSimpleName();
    private Context _context;
    private SimpleDraweeView _splashBg;

    private CustomCountDownTimer _customCountDownTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

        _context = SplashActivity.this;

        _splashBg = (SimpleDraweeView) findViewById(R.id.splash_bg);

        FrescoUtils.loadDrawable(_splashBg, R.drawable.splash);

        if (ActivityCompat.checkSelfPermission(_context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            UIUtils.askForPermission(_context, "请在应用设置中打开获取手机信息权限!");
            return;
        }

        //存储设备唯一ID
        if (SharePreferenceHelper.getSharePreferenceFromString(_context, Constants.APP_CONFIG, Constants.APP_CONFIG).isEmpty()) {
            SharePreferenceHelper.saveSharePreferenceFromString(_context, Constants.APP_CONFIG, Constants.APP_ONLY_ID, AppHelper.getOnlyId(_context));
        }

        //没有设置极光allas
        if (!SharePreferenceHelper.getSharePreferenceFromBoolean(_context, Constants.APP_CONFIG, Constants.SET_JG_ALIAS_SUCCESS)) {
            //设置极光推送alias
            setAlias(AppHelper.getSaveMd5OnlyId(_context), null);
        }

        uploadDeviceInfo();
        getSystemConfig();
    }

    private void getSystemConfig() {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                //保存系统配置的值 location upload time
                JsonArray jsonArray = o.data.getAsJsonArray();

                if (jsonArray.size() > 0) {
                    JsonObject object = jsonArray.get(0).getAsJsonObject();
                    SystemConfig systemConfig = ParseJsonUtils.getObjectFromJson(object, SystemConfig.class);

                    if (systemConfig.getKey().equals(Constants.LOCATION_UPLOAD_TIME)) {
                        SharePreferenceHelper.saveSharePreferenceFromInteger(_context, Constants.APP_CONFIG,
                                Constants.LOCATION_UPLOAD_TIME, Integer.parseInt(systemConfig.getValue()));
                    }
                }

                if (SharePreferenceHelper.getSharePreferenceFromString(_context, Constants.APP_USER_INFO, Constants.USER_UID).isEmpty()) {
                    initJumpButton(false, null, null, null);
                } else {
                    checkLoginAction();
                }

//                Toast.makeText(_context, "数据获取成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                UIUtils.showToastMessage(_context, "数据初始化失败,请重启应用!");
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.CONFIG_GET_SYSTEM, ss, HttpData.getEmptyData());
    }

    private void uploadDeviceInfo () {
        SharePreferenceHelper.saveSharePreferenceFromString(this, Constants.APP_CONFIG,
                Constants.REGISTRATION_ID, JPushInterface.getRegistrationID(this));
        Log.d(TAG, "REGISTRATION_ID" + SharePreferenceHelper.getSharePreferenceFromString(_context, Constants.APP_CONFIG, Constants.REGISTRATION_ID));
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                //保存系统配置的值 location upload time

//                Toast.makeText(_context, "数据获取成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                UIUtils.showToastMessage(_context, "数据初始化失败,请重启应用!");
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.DEVICE_UPLOAD_INFO, ss,
                HttpData.getUploadDeviceData(AppHelper.getIMSI(_context), "", "", Build.MODEL, "", Build.VERSION.RELEASE,
                        SharePreferenceHelper.getSharePreferenceFromString(_context, Constants.APP_CONFIG, Constants.REGISTRATION_ID)));
    }

    private void checkLoginAction() {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                UserInfo userInfo = ParseJsonUtils.getObjectFromJson(o.data, UserInfo.class);

                String uid = userInfo.getUid();
                String userName = userInfo.getUserName();
                String nickName = userInfo.getNickName();
                String accessToken = userInfo.getAccessToken();
                String bindStatus = userInfo.getBindStatus();

                String bindTransportCompanyName = userInfo.getBindTransportCompanyName();
                String driverName = userInfo.getDriverName();

                String password = SharePreferenceHelper.getSharePreferenceFromString(_context, Constants.APP_CONFIG, Constants.USER_PASSWORD);
                SharePreferenceHelper.saveUserInfoSharePreference(_context, uid, userName, nickName, accessToken,
                        password, bindStatus, bindTransportCompanyName);

                initJumpButton(true, bindStatus, bindTransportCompanyName, driverName);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                initJumpButton(false, null, null, null);
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.USER_CHECK_LOGIN, ss, HttpData.getEmptyData());
    }

    private void initJumpButton(final boolean isStartMainPage, final String bindStatus, final String bindTransportCompanyName, final String driverName) {

        _customCountDownTimer = new CustomCountDownTimer(2 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (isStartMainPage) {
                    Intent intent = new Intent();
                    switch (bindStatus) {
                        case "PASS":
                            startMainActivity();
                            break;

                        case "REFUSED":
                            intent.setClass(SplashActivity.this, BindCompanyResultActivity.class);
                            intent.putExtra("bind_status", bindStatus);
                            intent.putExtra("bind_company_note", bindTransportCompanyName + "拒绝您的申请!");
                            startActivity(intent);

                            break;
                        case "IN_AUDIT":
                            intent.setClass(SplashActivity.this, BindCompanyResultActivity.class);
                            intent.putExtra("bind_status", bindStatus);
                            intent.putExtra("bind_company_note", bindTransportCompanyName + "正在审核中...");
                            startActivity(intent);
                            break;
                        case "NO_BIND":
                            intent.setClass(SplashActivity.this, BindCompanyResultActivity.class);
                            intent.putExtra("bind_status", bindStatus);
                            intent.putExtra("bind_company_note", "");
                            intent.putExtra("driver_name", driverName);
                            startActivity(intent);
                            break;
                    }

                } else {
                    startLoginActivity();
                }
            }
        };

        _customCountDownTimer.start();
    }

    private void startLoginActivity() {
        Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    private void startMainActivity() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(getIntent().getBundleExtra(Constants.EXTRA_BUNDLE) != null){
            intent.putExtra(Constants.EXTRA_BUNDLE,
                    getIntent().getBundleExtra(Constants.EXTRA_BUNDLE));
        }
        startActivity(intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (_customCountDownTimer != null) {
            _customCountDownTimer.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (_customCountDownTimer != null) {
            _customCountDownTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (_customCountDownTimer != null) {
            _customCountDownTimer.cancel();
        }
    }

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    protected int getFragmentContentId() {
        return 0;
    }

    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口,在任何方便的地方调用都可以。
    private void setAlias(String alias, Set<String> tags) {

        if (!ExampleUtil.isValidTagAndAlias(AppHelper.getDeviceId(_context))) {
            //Log.d(TAG, "You alias is error!");
            return;
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后,以后不必再次设置了。
                    SharePreferenceHelper.saveSharePreferenceFromBoolean(_context, Constants.APP_CONFIG, Constants.SET_JG_ALIAS_SUCCESS, true);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
            //ExampleUtil.showToast(logs, getApplicationContext());
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    //防止用户返回键退出APP
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}


text:
'use strict';

export default class ConfirmPlayerController {
  constructor($scope, $mdDialog, player) {
    this.$scope = $scope;
    this.dialog = $mdDialog;
    this.player = player;
  }

  cancel() {
    this.dialog.cancel();
  }

  answer(answer) {
    this.dialog.hide(answer);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LiteNetLib;
using LiteNetLib.Utils;
using System.Threading;

namespace DiasporaServer.Modules.Input
{
    class ServerListener : INetEventListener
    {
        public NetServer Server;

        public void OnPeerConnected(NetPeer peer)
        {
            Console.WriteLine("[Server] Peer connected: " + peer.EndPoint);
            var peers = Server.GetPeers();
            foreach (var netPeer in peers)
            {
                Console.WriteLine("ConnectedPeersList: id={0}, ep={1}", netPeer.Id, netPeer.EndPoint);
            }
            InterestManagement.InterestManager.Instance.Regions["System"].Nodes[0].Subscribe(peer);
        }

        public void OnPeerDisconnected(NetPeer peer, DisconnectReason disconnectReason, int socketErrorCode)
        {
            InterestManagement.InterestManager.Instance.RemovePeer(peer);
            Console.WriteLine("[Server] Peer disconnected: " + peer.EndPoint + ", reason: " + disconnectReason);
        }

        public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode)
        {
            Console.WriteLine("[Server] error: " + socketErrorCode);
        }

        public void OnNetworkLatencyUpdate(NetPeer peer, int latency)
        {
        }

        public void OnNetworkReceive(NetPeer peer, NetDataReader reader)
        {
            //handle messages here
            Console.WriteLine("Recieved message");
            try
            {
                new Thread(() => new MessageJob(reader.Data, peer)).Start();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                throw;
            }
            //new MessageJob(reader.Data, peer);
        }

        public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
        {
            Console.WriteLine("[Server] ReceiveUnconnected: {0}", reader.GetString(100));
            Server.SendUnconnectedMessage(reader.Data, remoteEndPoint);
        }
    }
}


text:
Cals

				Posted on

				by

    	No Cals yet, why don't you create one?


text:
using DarkUI.Config;
using System.Windows.Forms;

namespace DarkUI.Controls
{
    public class DarkTextBox : TextBox
    {
        #region Constructor Region

        public DarkTextBox()
        {
            BackColor = Colors.LightBackground;
            ForeColor = Colors.LightText;
            Padding = new Padding(2, 2, 2, 2);
            BorderStyle = BorderStyle.FixedSingle;
        }

        #endregion
    }
}


text:
<?php

// See the README in tests/ for information on running and writing these tests.

require_once('PHPUnit/Framework.php');
require_once('../src/Sag.php');

class SagTest extends PHPUnit_Framework_TestCase
{
  protected $couchIP;
  protected $couchDBName;

  protected $couch;
  protected $session_couch;

  public function setUp()
  {
    $this->couchIP = '127.0.0.1';
    $this->couchDBName = 'sag_tests';

    $this->couch = new Sag($this->couchIP);
    $this->couch->login('admin', 'passwd');
    $this->couch->setDatabase($this->couchDBName);

    $this->session_couch = new Sag($this->couchIP);
    $this->session_couch->setDatabase($this->couchDBName);
  }

  public function test_createDB()
  {
    $result = $this->couch->createDatabase($this->couchDBName);
    $this->assertTrue($result->body->ok);
  }

  public function test_allDatabases()
  {
    $this->assertTrue(in_array($this->couchDBName, $this->couch->getAllDatabases()->body));
  }

  public function test_newDoc()
  {
    $doc = new StdClass();
    $doc->foo = 'bar';

    $result = $this->couch->put('1', $doc);
    $this->assertTrue($result->body->ok);
    $this->assertEquals($result->body->id, '1');
  }

  public function test_getID()
  {
    $result = $this->couch->get('/1');
    $this->assertEquals($result->body->_id, '1');
    $this->assertEquals($result->body->foo, 'bar');

    //make sure we're prepending slashes when they're not present
    $this->assertEquals($result->body->_id, $this->couch->get('1')->body->_id);
  }

  public function test_copyToNew()
  {
    $result = $this->couch->copy('1', '1copy');
    $this->assertEquals($result->headers->_HTTP->status, '201');
    $this->assertEquals($result->body->id, '1copy');
  }

  public function test_copyToOverwrite()
  {
    $result = $this->couch->copy('1', '1copy', $this->couch->get('/1copy')->body->_rev);
    $this->assertEquals($result->headers->_HTTP->status, '201');
  }

  public function test_getIDNoDecode()
  {
    $this->couch->decode(false);

    $json = $this->couch->get('/1')->body;
    $this->assertTrue(is_string($json));

    $this->couch->decode(true); //for the benefit of future tests
    $this->assertEquals(json_decode($json)->_id, '1');
  }

  public function test_updateDoc()
  {
    //get it and set it...
    $doc = $this->couch->get('/1')->body;
    $doc->foo = 'foo';

    //...send it...
    $this->assertTrue($this->couch->post($doc)->body->ok);

    //...and get it again
    $this->assertEquals($this->couch->get('/1')->body->foo, 'foo');
  }

  public function test_getAllDocs()
  {
    $resDefaults = $this->couch->getAllDocs();
    $this->assertTrue(is_array($resDefaults->body->rows));
    $this->assertTrue(isset($resDefaults->body->rows[0]));
    $this->assertFalse(isset($resDefaults->body->rows[0]->doc));

    $resAllWithDocs = $this->couch->getAllDocs(true, null, '""', '[]');
    $this->assertTrue(is_array($resAllWithDocs->body->rows));
    $this->assertTrue(isset($resAllWithDocs->body->rows[0]->doc));
    $this->assertEquals(
              sizeof($resDefaults->body->rows),
              sizeof($resAllWithDocs->body->rows)
    );

    $resLimitZero = $this->couch->getAllDocs(false, 0);
    $this->assertTrue(is_array($resLimitZero->body->rows));
    $this->assertTrue(empty($resLimitZero->body->rows));

    $this->assertEquals(
              '1',
              $this->couch->getAllDocs(true, null, null, null, array("1"))->body->rows[0]->id
    );
  }

  public function test_deleteDoc()
  {
    $doc = $this->couch->get('/1')->body;
    $this->assertTrue($this->couch->delete($doc->_id, $doc->_rev)->body->ok);

    try
    {
      $doc = $this->couch->get('/1');
      $this->assertTrue(false); //previous line should have thrown an exception
    }
    catch(SagCouchException $e)
    {
      //make sure that we're setting codes correctly and catching the right exception
      $this->assertEquals($e->getCode(), '404');
    }
  }

  public function test_genIDs()
  {
    $uuids = $this->couch->generateIDs()->body->uuids;
    $this->assertTrue(is_array($uuids));
    $this->assertEquals(sizeof($uuids), 10);
  }

  public function test_errorHandling()
  {
    try
    {
      $this->couch->generateIDs(-1); //should throw a SagException
      $this->assertTrue(false);
    }
    catch(SagException $e)
    {
      $this->assertTrue(true);
    }

    try
    {
      $this->couch->get('/_all_docs?key=badJSON'); //should throw a SagCouchException
      $this->assertTrue(false);
    }
    catch(SagCouchException $e)
    {
      $this->assertTrue(true);
    }
  }

  public function test_bulk()
  {
    $a = new StdClass();
    $a->foo = "bar";
    $a->bwah = "hi";

    $b = new StdClass();
    $b->hi = "there";
    $b->lo = "fi";

    $result = $this->couch->bulk(array($a, $b));
    $this->assertTrue(is_array($result->body));

    $doc = $this->couch->get('/'.$result->body[0]->id);
    $this->assertEquals($doc->body->foo, $a->foo);
    $this->assertEquals($doc->body->bwah, $a->bwah);
  }

  public function test_replication()
  {
    $newDB = "sag_tests_replication";

    $this->assertFalse(in_array($newDB, $this->couch->getAllDatabases()->body));
    $this->assertTrue($this->couch->createDatabase($newDB)->body->ok);
    $this->assertTrue($this->couch->replicate($this->couchDBName, $newDB)->body->ok);
    $this->assertTrue($this->couch->deleteDatabase($newDB)->body->ok);
  }

  public function test_compactView()
  {
    $designID = "bwah";

    $ddoc = new StdClass();
    $ddoc->_id = "_design/$designID";
    $ddoc->language = "javascript";
    $ddoc->views = new StdClass();
    $ddoc->views->all = new StdClass();
    $ddoc->views->all->map = "function(doc) { emit(null, doc); }";

    $this->assertTrue($this->couch->post($ddoc)->body->ok);
    $this->assertTrue($this->couch->compact($designID)->body->ok);
  }

  public function test_compactDatabase()
  {
    $this->assertTrue($this->couch->compact()->body->ok);
  }

  public function test_attachments()
  {
    $docID = 'howdy';
    $name = 'lyrics';
    $data = 'Somebody once told me';
    $ct = 'text/plain';

    $res = $this->couch->setAttachment($name, $data, $ct, $docID);

    // Make sure the new doc was created.
    $this->assertEquals('201', $res->headers->_HTTP->status);

    $res = $this->couch->get("/$docID");

    // Same type?
    $this->assertEquals($ct, $res->body->_attachments->{$name}->content_type);

    // Don't get the whole attachment by default.
    $this->assertTrue($res->body->_attachments->{$name}->stub);

    // Get the attachment inline style
    $res = $this->couch->get("/$docID?attachments=true");

    // Check contents - text/plain gets base64 encoded
    $this->assertEquals($data, base64_decode($res->body->_attachments->{$name}->data));

    // Check contents, via stand alone
    $this->assertEquals($data, $this->couch->get("/$docID/$name")->body);
  }

  public function test_createSession()
  {
    try
    {
      $this->assertTrue(is_string($this->session_couch->login('admin', 'passwd', Sag::$AUTH_COOKIE)));
    }
    catch(Exception $e)
    {
      //should not happen - FAIL
      $this->assertTrue(false);
    }
  }

  public function test_createDocWithSession()
  {
    $db = new Sag($this->couchIP);
    $db->setDatabase($this->couchDBName);
    $db->login('admin', 'passwd', Sag::$AUTH_COOKIE);

    $doc = new StdClass();
    $doc->sag = 'for couchdb';

    $res = $db->put('sag', $doc);
    $this->assertTrue($res->body->ok);

    $del_res = $db->delete('sag', $res->body->rev);
    $this->assertTrue($del_res->body->ok);
  }

  public function test_deleteDB()
  {
    $this->assertTrue($this->couch->deleteDatabase($this->couchDBName)->body->ok);
  }

  public function test_connectionFailure()
  {
    $badCouch = new Sag('example.com');
    $badCouch->setOpenTimeout(1);

    try
    {
      $badCouch->setDatabase('bwah');
      $badCouch->get('/asdf');
      $this->assertTrue(false); //shouldn't reach this line
    }
    catch(SagException $e)
    {
      $this->assertTrue(true);
    }
  }

  public function test_timeoutRWValues()
  {
    //should NOT throw on positive seconds
    try { $this->couch->setRWTimeout(1); $this->assertTrue(true); }
    catch(Exception $e) { $this->assertFalse(true); }

    //should NOT throw on positive seconds && microseconds
    try { $this->couch->setRWTimeout(1, 1); $this->assertTrue(true); }
    catch(Exception $e) { $this->assertFalse(true); }

    //should NOT throw on 0 seconds && positive microseconds
    try { $this->couch->setRWTimeout(0, 1); $this->assertTrue(true); }
    catch(Exception $e) { $this->assertFalse(true); }

    //should throw on 0 timeout
    try { $this->couch->setRWTimeout(0, 0); $this->assertFalse(true); }
    catch(Exception $e) { $this->assertTrue(true); }

    //should throw on negative timeout
    try { $this->couch->setRWTimeout(-1); $this->assertFalse(true); }
    catch(Exception $e) { $this->assertTrue(true); }

    //should throw on negative seconds and positive microseconds
    try { $this->couch->setRWTimeout(-1, 1); $this->assertFalse(true); }
    catch(Exception $e) { $this->assertTrue(true); }
  }

  public function test_loginBadType()
  {
    try
    {
      $this->couch->login('a', 'b', "aasdfsadfasf");
      $this->assertTrue(false);
    }
    catch(SagException $e)
    {
      //We want this exception
      $this->assertTrue(true);
    }
    catch(Exception $e)
    {
      //wrong type of exception
      $this->assertTrue(false);
    }
  }
}


text:
var EE = require("events").EventEmitter;

module.exports = new EE();


text:
/**
 *
 */
package gov.va.med.imaging;

import gov.va.med.GeneratedCodeValidationUtility;
import gov.va.med.exceptions.ValidationException;
import junit.framework.TestCase;

/**
 * @author vhaiswbeckec
 *
 */
public class ValidateRouterFacadeTest
extends TestCase
{
	public void testGeneratedFacade()
	{
		try
		{
			GeneratedCodeValidationUtility.validateImplementation(
				gov.va.med.imaging.BaseWebFacadeRouter.class,
				gov.va.med.imaging.BaseWebFacadeRouterImpl.class
			);
		}
		catch (ValidationException x)
		{
			fail(x.getMessage());
		}
	}
}


text:
require 'rubygems'
require 'appsignal-moped'

require 'pry'

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))

RSpec.configure do |config|
  config.mock_with :rspec
end


text:
WildFly Capabilities
====================
http://wildfly.org

This project provides the central registry of descriptive information about capabilities accessible via the management layer of a WildFly Core based process. The intent is to provide a central location where capability developers can go to learn about other capabilities available in the WildFly ecosystem and to advertise their capability. Most importantly, registering capabilities helps ensure that different capabilities won't use the same name.

Building
------------------

This project does not produce a build. It is simply a registry of information.

Structure of the Registry
-------------------------

The registry consists of two primary elements:

* a single text file in the root of the repository, 'registry.txt' which is a simple alphabetically ordered list of capability names. This file provides a single location where users can quickly learn the names of available capabilities
* a filesystem tree where the tree structure corresponds to the names of the capabilities. Each leaf in the tree is a 'capability.adoc' file which includes standard information describing a particular capability. The 'template.adoc' file in the root of the repository shows the standard format of a capability.adoc file.

Capabilities
-------------------

A capability is a piece of functionality used in a WildFly Core based process that is exposed via the WildFly Core management layer. Capabilities may depend on other capabilities, and this interaction between capabilities is mediated by the WildFly Core management layer.

Some capabilities are automatically part of a WildFly Core based process, but in most cases the configuration provided by the end user (i.e. in standalone.xml, domain.xml and host.xml) determines what capabilities are present at runtime. It is the responsibility of the handlers for management operations to register capabilities and to register any requirements those capabilities may have for the presence of other capabilities.

* Capabilities vs modules: A JBoss Modules module is the means of making resources available to the classloading system of a WildFly Core based process. To make a capability available, you must package its resources in one or more modules and make them available to the classloading system. But a module is not a capability in and of itself, and simply copying a module to a WildFly installation does not mean a capability is available. Modules can include resources completely unrelated to management capabilities.
* Capabilities vs Extensions: An extension is the means by which the WildFly Core management layer is made aware of manageable functionality that is not part of the WildFly Core kernel. The extension registers with the kernel new management resource types and handlers for operations on those resources. One of the things a handler can do is register or unregister a capability and its requirements. An extension may register a single capability, multiple capabilities, or possibly none at all. Further, not all capabilities are registered by extensions; the WildFly Core kernel itself may register a number of different capabilities.

Capability Names
-------------------

Capability names are simple strings, with the dot character serving as a separator to allow namespacing.

The 'org.wildfly' namespace is reserved for projects associated with the WildFly organization on github (https://github.com/wildfly)

The structure of this repository is based on the structure of capability names. The name is split based on the dot character and then each section becomes a directory in the repository. Each directory whose path from the repository root represents a complete capability name then includes a capability.adoc file describing that capability.

Statically vs Dynamically Named Capabilities
--------------------------------------------

The full name of a capability is either statically known, or it may include a statically known base element and then a dynamic element. The dynamic part of the name is determined at runtime based on the address of the management resource that registers the capability. For example, the management resource at the address '/socket-binding-group=standard-sockets/socket-binding=web' will register a dynamically named capability named 'org.wildlfy.network.socket-binding.web'. The 'org.wildlfy.network.socket-binding' portion is the static part of the name.

All dynamically named capabilities that have the same static portion of their name should provide a consistent feature set and set of requirements. The entry in this registry should be for the static part of the capability name. So, for the socket-binding example above, the registry.txt file would include a line for 'org.wildlfy.network.socket-binding' and the repository would include a capability.adoc file at location org/wildfly/network/socket-binding/capability.adoc.

Services provided by a capability
---------------------------------

Typically a capability functions by registering a service with the WildFly process' MSC ServiceContainer, and then dependent capabilities depend on that service. The WildFly Core management layer orchestrates registration of those services and service dependencies by providing a means to discover service names.

The capability.adoc entry for a capability should provide information about the service made available by the capability, if there is one.

Custom integration APIs provided by a capability
------------------------------------------------

Instead of or in addition to providing MSC services, a capability may expose some other API to dependent capabilities. This API must be encapsulated in a single class (although that class can use other non-JRE classes as method parameters or return types).

The capability.adoc entry for a capability should provide information about the custom integration API made available by the capability, if there is one.

Capability Requirements
------------------------

A capability may rely on other capabilities in order to provide its functionality at runtime. The management operation handlers that register capabilities are also required to register their requirements.

There are three basic types of requirements a capability may have:

* Hard requirements. The required capability must always be present for the dependent capability to function.
* Optional requirements. Some aspect of the configuration of the dependent capability controls whether the depended on capability is actually necessary. So the requirement cannot be known until the running configuration is analyzed.
* Runtime-only requirements. The dependent capability will check for the presence of the depended upon capability at runtime, and if present it will utilize it, but if it is not present it will function properly without the capability. There is nothing in the dependent capability's configuration that controls whether the depended on capability must be present. Only capabilities that declare themselves as being suitable for use as a runtime-only requirement should be depended upon in this manner.

Hard and optional requirements may be for either statically named or dynamically named capabilities. Runtime-only requirements can only be for statically named capabilities, as such a requirement cannot be specified via configuration, and without configuration the dynamic part of the required capability name is unknown.

The capability.adoc entry for a capability should provide information about capability requirements, if there are any.

Supporting runtime-only requirements
------------------------------------

Not all capabilities are usable as a runtime-only requirement, and the capability.adoc entry for a capability should express this.

Any dynamically named capability is not usable as a runtime-only requirement.

For a capability to support use as a runtime-only requirement, it must guarantee that a configuration change to a running process the removes the capability will not impact currently running capabilities that have a runtime-only requirement for it. This means:

* A capability that supports runtime-only usage must ensure that it never removes its runtime service except via a full process reload.
* A capability that exposes a custom integration API generally is not usable as a runtime-only requirement. If such a capability does support use as a runtime-only requirement, it must ensure that any functionality provided via its integration API remains available as long as a full process reload has not occurred.

Private capabilities
--------------------

A capability can be private if the project that registers it does not wish its services or custom integration API to be depended upon by others. Any service or custom integration API exposed by the capability can be changed at any time and it is not necessary to record information in this registry about such services or integration API. However, the capability itself should be recorded, including descriptive information about what it does and what requirements it may have.

Private capabilities are useful because only a capability can depend upon another capability and use its services and integration API.  "Anonymous" code cannot require capabilities because that would result in users not being able to determine what functionality would be lost if a required capability were removed. However, just because code wishes to use another capability and is willing to register itself as doing so doesn't mean it is willing to publish a contract that other, unknown capabilities can rely upon.

Private capabilities are allowed to provide services or a custom integration API for use by other capabilities controlled by the maintainer of the private capability. However the private capability implementation is free to change those at any time. This kind of usage scenario is analogous to typical use of package-protected Java methods.

Contents of capability.adoc
--------------------------

The following is information describing the contents of a capability.adoc file. See the template.adoc file in the repository root for context.

NAME: The name of the capability. See above.

DESCRIPTION: A free form description of the capability

REGISTERED BY: Information about the project that is responsible for the integration contract exposed by the capability. There may be multiple projects that provide an implementation the capability, but there should be a single project responsible for the capability's contract. The contract is defined by the capability.adoc file and by the Java API of any classes referenced in the "SERVICE PROVIDED" and "CUSTOM INTEGRATION API" sections below. The following information should be provided:

* NAME: The name of the project
* URL: A useful URL. Perhaps a general project URL, perhaps one for relevant source code (e.g. a github repo)

DYNAMIC: True if the capability is dynamically named; false otherwise.

PRIVATE: True if the capability should not be used outside of its respective codebase; false otherwise. If true, any SERVICE PROVIDED or CUSTOM INTEGRATION API information provided is purely informational and is subject to change at any time.

SUPPORTS RUNTIME ONLY: True if the capability can be depended upon by another capability as a runtime-only requirement. Must be 'false' if DYNAMIC is 'true'.

SERVICE PROVIDED: Information about an MSC service registered by the capability which can be depended upon or injected by other capabilities, if there are any.

* CLASS: The fully qualified class name of the value type of the MSC Service
* MODULE: The name of the jboss-modules module that typically provides the class

CUSTOM INTEGRATION API: Information about the custom integration API provided by the capability, if there is one.

* CLASS: The fully qualified class name of class that provides a custom API for interacting with the capability
* MODULE: The name of the jboss-modules module that typically provides the class

HARD REQUIREMENTS: Information about other capabilities that must be present if this capability is registered, if there are any. For each such capability the following should be provided:

* NAME: The static portion of the name of the required capability
* DYNAMIC: True if the required capability is dynamically named

OPTIONAL REQUIREMENTS: Information about other capabilities that must be present if some aspect of this capability's configuration is present, if there are any. For each such capability the following should be provided:

* NAME: The static portion of the name of the required capability
* DYNAMIC: True if the required capability is dynamically named
* DESCRIPTION: Free form text description of what makes this requirement optional

RUNTIME ONLY REQUIREMENTS: Information about other capabilities that cannot be required by this capability's configuration, but which will be detected and used if present.

* NAME: The static portion of the name of the required capability
* DESCRIPTION: Free form text description of what functionality is enabled if this capability is present


text:
/**
 * The following is taken from "JavaScript Patterns" by Stoyan Stefanov
 *
 * As the complexity of a program grows and some parts of code get split into different files and included
 * conditionally, it becomes unsafe to just assume that your code is the first to define a certain namespace
 * or a property inside of it. Some of the properties your're adding to the namespace may already exist, and
 * you could be overwriting them. Therefore before adding a property or creating a namespace, it's best to
 * check first that it doesn't already exist, as shown in this example:
 *
 *         // unsafe
 *         var CONTACTS = {};
 *
 *         // better
 *         if (typeof CONTACTS === "undefined") {
 *             var CONTACTS = {};
 *         }
 *
 *         // or shorter
 *         var CONTACTS = CONTACTS || {};
 *
 * The module pattern is widely used because it provides structure and helps organize your code as it grows.
 * Unlike other languages, JavaScript doesn't have special syntax for packages, but the module pattern provides
 * the tools to create self-contained decoupled pieces of code, which can be treated as black boxes of functionality
 * and added, replaced, or removed according to the (ever-changing requirements of the software you're writing.
 *
 * @author Joshua Wilson
 */

var CONTACTS = CONTACTS || {};

CONTACTS.namespace = function (ns_string) {
    var parts = ns_string.split('.'),
        parent = CONTACTS,
        i;

    // Strip redundant leading global
    if (parts[0] === "CONTACTS") {
        parts = parts.slice(1);
    }

    for (i=0; i < parts.length; i += 1) {
        // Create a property if it doesn't exist
        if  (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }

        parent = parent[parts[i]];
    }
    return parent;
};


text:
<?xml version="1.0"?>

<!DOCTYPE faces-config PUBLIC
  "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
  "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<!-- This registers the OSP 2.0 JSF widgets (Tags, Components, and Renderers) -->
<faces-config>

    <!-- =================== Components ============== -->

    <component>
        <component-type>org.theospi.help.Glossary</component-type>
        <component-class>org.theospi.portfolio.help.jsf.component.GlossaryComponent</component-class>
    </component>

    <!-- =================== Renderers ============== -->

    <render-kit>

        <renderer>
            <component-family>javax.faces.Output</component-family>
            <renderer-type>org.theospi.help.Glossary</renderer-type>
            <renderer-class>org.theospi.portfolio.help.jsf.renderer.GlossaryRenderer</renderer-class>
        </renderer>

    </render-kit>

    <!-- =================== Converters ============== -->

</faces-config>


text:
angular.module('app.authentication', []).factory('authenticationInterceptor', [
	function () {
		return {
			// for more read about angular http interceptors
			request: function (config) {
				// https://www.npmjs.com/package/store
				// use it to get token from localStorage

				var token = store.get('token');
				config.headers.Authorization = 'Bearer ' + token;
				return config;
			}
		};
	}
])


text:
function nn.gModule:reset(stdv)
   self:apply(function(module) module:reset(stdv) end)
   return self
end


text:
import { FILTER_BY_CONTRIBUTING_FACTOR } from '../constants/action_types';

export default (state = 'ALL', action) => {
  switch (action.type) {
    case FILTER_BY_CONTRIBUTING_FACTOR:
      return action.factor;
    default:
      return state;
  }
};


text:
% =========================================================================
% *** matlab2simview
% ***
% *** This function converts  MATLAB data in struct format to *.txt simvew
% data
% *** Convert PSIM txt data to simulink struct data
% =========================================================================
% ***
% *** The MIT License (MIT)
% ***
% *** Copyright (c) 2016 Adriano Ruseler
% ***
% *** Permission is hereby granted, free of charge, to any person obtaining a copy
% *** of this software and associated documentation files (the "Software"), to deal
% *** in the Software without restriction, including without limitation the rights
% *** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% *** copies of the Software, and to permit persons to whom the Software is
% *** furnished to do so, subject to the following conditions:
% ***
% *** The above copyright notice and this permission notice shall be included in all
% *** copies or substantial portions of the Software.
% ***
% *** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% *** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% *** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% *** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% *** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% *** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% *** SOFTWARE.
% ***
% =========================================================================

function [status]=matlab2simview(MATLABdata,filename)

% Loads directory structure
try
    dirstruct = evalin('base', 'dirstruct'); % Load dirstruct from base workspace
catch
    [status, dirstruct]= checkdirstruct(); % Well, check this out
end

if nargin <1  % MATLABdata not supplied
    disp(' MATLABdata not supplied!')
   status =1; % Not Ok
   return;
end

% Generates Matrix   MATLABdata=PLECSdata
data=MATLABdata.time; % Get time vector

ns=length(MATLABdata.signals); % Number of signals

VarsName{1}='Time';

for i=2:ns+1
    VarsName{i}=MATLABdata.signals(i-1).label;
    data=horzcat(data,MATLABdata.signals(i-1).values);
end

if nargin < 2  % txtfilename not supplied
    if isfield(dirstruct,'simulatedir')
        if isequal(exist(dirstruct.simulatedir,'dir'),7)
            cd(dirstruct.simulatedir) % Change to directory with simutalad data
        end
    end
   [File, Path] = uiputfile({'*.txt;*.csv;','SIMVIEW data Files (*.txt,*.csv)'; ...
        '*.mat','SIMVIEW - Text (*.txt)';'*.csv','SIMVIEW - Excel (*.csv)';...
        '*.*','All files'}, 'Save the SIMVIEW data file!');
    if isequal(File,0)
        disp('User selected Cancel!')
        status =1; % Return empty data
        return
    end
    filename=[Path File]; % Provide
end

[pathstr, name, ext] = fileparts(filename);

switch ext % Make a simple check of file extensions
    case '.csv' % Waiting for code implementation
        csvheader=VarsName{1};
        for nvars=2:length(VarsName)
            csvheader=[csvheader ', ' VarsName{nvars}];
        end
        % Write csv file
        status=savecsvfile(data, csvheader, filename);
    case '.txt'
        txtheader=VarsName{1};
        for nvars=2:length(VarsName)
            txtheader=[txtheader ' ' VarsName{nvars}];
        end
        % Write text file
        status=savetxtfile(data, txtheader, filename); % OK testado
    otherwise
        disp('File extension error!')
        status =1; % Return empty data
        return
end


text:
<!--
build example for kissy loader
@author yiminghe@gmail.com
-->
<project name="compressor.build" default="build" basedir="." xmlns:ac="antlib:net.sf.antcontrib">

    <!--入口文件模块所在目录-->
    <dirname property="current.dir" file="${ant.file.compressor.build}"/>
    <property name="assets.dir" location="${current.dir}/src/"/>
    <property name="page.dir" location="${assets.dir}/biz/page/"/>
    <property name="page.dir.tmp" location="${current.dir}/tmp/"/>
    <property name="build.dir" location="${current.dir}/build/"/>
    <property name="page.build.dir" location="${build.dir}/biz/page/"/>

    <!--项目文件编码-->
    <property name="charset" value="utf-8"/>

    <property name="ks.tools" value="../../../../tools/"/>

    <property name="module.compiler" value="${ks.tools}\module-compiler\module-compiler.jar"/>

    <!-- js 构建-->
    <target name='jsrun' depends="combo">
    </target>

    <target name='prepare'>
        <mkdir dir="${build.dir}"></mkdir>
        <mkdir dir="${page.build.dir}"></mkdir>
        <copy encoding="${charset}" todir="${build.dir}">
            <fileset dir="${assets.dir}" includes="**/*.css"/>
        </copy>
    </target>

    <!--js  combo 地址获取-->
    <target name='combo' depends="prepare">
        <ac:for param="page">
            <!--入口模块文件所在目录的所有模块循环处理-->
            <path>
                <fileset dir="${page.dir}" includes="*.js" excludes="*.combo.js,*-min.js,*.dep.js"/>
            </path>
            <sequential>
                <ac:var name="var.modname" unset="true"/>
                <basename property="var.modname" file="@{page}" suffix=".js"/>
                <echo>
                    build ${var.modname} in @{page}
                </echo>
                <java classname="com.taobao.f2e.Main">
                    <arg value="-require"/>
                    <!-- 入口模块 -->
                    <arg value="biz/page/${var.modname}"/>

                    <arg value="-baseUrls"/>
                    <arg value="${assets.dir}"/>

                    <arg value="-encodings"/>
                    <arg value="${charset}"/>

                    <arg value="-outputEncoding"/>
                    <arg value="${charset}"/>

                    <arg value="-output"/>
                    <arg value="${page.build.dir}/${var.modname}.js"/>

                    <arg value="-outputDependency"/>
                    <arg value="${page.build.dir}/${var.modname}.dep.js"/>

                    <classpath>
                        <pathelement path="${module.compiler}"/>
                        <pathelement path="${java.class.path}"/>
                    </classpath>
                </java>
            </sequential>
        </ac:for>
    </target>

    <!--项目(js,css)构建-->
    <target name="build" depends="jsrun"/>

</project>


text:
from PySide import QtCore, QtGui

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(224, 117)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
        Form.setSizePolicy(sizePolicy)
        self.verticalLayout = QtGui.QVBoxLayout(Form)
        self.verticalLayout.setSpacing(1)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.translateLabel = QtGui.QLabel(Form)
        self.translateLabel.setObjectName("translateLabel")
        self.verticalLayout.addWidget(self.translateLabel)
        self.rotateLabel = QtGui.QLabel(Form)
        self.rotateLabel.setObjectName("rotateLabel")
        self.verticalLayout.addWidget(self.rotateLabel)
        self.scaleLabel = QtGui.QLabel(Form)
        self.scaleLabel.setObjectName("scaleLabel")
        self.verticalLayout.addWidget(self.scaleLabel)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.mirrorImageBtn = QtGui.QPushButton(Form)
        self.mirrorImageBtn.setToolTip("")
        self.mirrorImageBtn.setObjectName("mirrorImageBtn")
        self.horizontalLayout.addWidget(self.mirrorImageBtn)
        self.reflectImageBtn = QtGui.QPushButton(Form)
        self.reflectImageBtn.setObjectName("reflectImageBtn")
        self.horizontalLayout.addWidget(self.reflectImageBtn)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
        self.translateLabel.setText(QtGui.QApplication.translate("Form", "Translate:", None, QtGui.QApplication.UnicodeUTF8))
        self.rotateLabel.setText(QtGui.QApplication.translate("Form", "Rotate:", None, QtGui.QApplication.UnicodeUTF8))
        self.scaleLabel.setText(QtGui.QApplication.translate("Form", "Scale:", None, QtGui.QApplication.UnicodeUTF8))
        self.mirrorImageBtn.setText(QtGui.QApplication.translate("Form", "Mirror", None, QtGui.QApplication.UnicodeUTF8))
        self.reflectImageBtn.setText(QtGui.QApplication.translate("Form", "Reflect", None, QtGui.QApplication.UnicodeUTF8))


text:
var spawn = require('child_process').spawn
var mergeImg = require('merge-img')
var fs = require('fs')
var async = require('async')
var tmp = require('tmp')
var glob = require('glob')
var http = require('http')
var https = require('https')
var url = require('url')

var staticServer = require('./static-server')

function captureOptions(options) {
  var url = options.url
  if (options.path) url = '/file.stl?path=' + encodeURIComponent(options.path)

  return {
    url: url,
    image: options.image,
    color: options.color || 'eeeeee',
    width: options.width || 1000,
    height: options.height || 1000,
    x: options.x || 0,
    y: options.y || 0,
    z: options.z || 0,
    num: options.num || 20,
    port: options.port || 0,
    server: options.server || false,
  }
}

function capture(options, debug, error, progress = null, complete = null) {
  options = captureOptions(options)
  staticServer.set('port', options.port)

  var server = staticServer.listen(options.port, function () {
    var host = '0.0.0.0'
    var port = server.address().port

    debug('HTTP server listening on ' + host + ':' + port)

    var url = 'http://' + host + ':' + port + '/'
    url += '?x=' + options.x
    url += '&y=' + options.y
    url += '&z=' + options.z
    url += '&color=' + options.color
    if (options.url) url += '&url=' + encodeURIComponent(options.url)

    var tmpDir = tmp.dirSync({ unsafeCleanup: true })
    debug('Temporary directory ' + tmpDir.name)

    function phantomLog(str) {
      var match = str.match(/^(\d+)\/\d+: /)
      if (match && progress) {
        progress((parseInt(match[1]) + 1) / options.num)
      } else {
        debug(str)
      }
    }

    var phantomArgs = [
      '--web-security=false',
      __dirname + '/capture.js',
      url,
      tmpDir.name,
      options.num,
      options.width,
      options.height,
    ]

    phantomjsCommand(phantomArgs, phantomLog, debug, error, function (status) {
      if (!options.server) server.close()
      if (status != 0) return error('Command exited with ' + status)
      if (fs.readdirSync(tmpDir.name).length === 0) {
        return error('Capture directory empty: ' + tmpDir.name)
      }

      debug('Captures done')

      mergeImages({
        dir: tmpDir.name,
        finalPath: options.image,
        debug,
        done: function () {
          tmpDir.removeCallback()
          complete && complete();
        }
      })
    })
  })
}

function headRequest(requestedUrl, callback) {
  const parsedURL = url.parse(requestedUrl)
  const options = {
    protocol: parsedURL.protocol,
    hostname: parsedURL.hostname,
    method: 'HEAD',
    path: parsedURL.path
  }
  let protocolHandler = (parsedURL.protocol === 'https:' ? https : http)

  request = protocolHandler.request(options, (response) => {
    callback(response, null)
  })
  request.on('error', (e) => {
    callback(null, e)
  })
  request.end()
}

function phantomjsCommand(args, log, debug, error, onExit) {
  var command = 'node_modules/.bin/phantomjs'

  debug(command + ' ' + args.join(' '))

  var cmd = spawn(command, args)
  cmd.stdout.on('data', function (data) {
    log(data.toString().trim())
  })
  cmd.stderr.on('data', function (data) {
    error(data.toString().trim())
  })
  cmd.on('exit', onExit)
}

function mergeImages({ dir, finalPath, debug, done }) {
  var globPath = dir + '/*.png'
  debug('Merging ' + globPath + ' images to ' + finalPath)

  glob(globPath, {}, function (err, files) {
    if (err) throw err
    if (files.length == 0) throw 'No files found at ' + globPath
    if (files.length == 1) throw 'Only one file found at ' + globPath

    files = sortFiles(files)
    mergeImg(files, { direction: true }).then(function (img) {
      img.write(finalPath, function () {
        debug('Merge done: ' + finalPath)
        done()
      })
    })
  })
}

function sortFiles(paths) {
  return paths.sort(function (a, b) {
    return pathToInt(a) - pathToInt(b)
  })
}

function pathToInt(path) {
  return parseInt(path.replace(/^.*craster-(\d+)\.png$/i, '$1'), 10)
}

module.exports.capture = capture