<commit_before>'use strict';
var https = require( 'https' ),
    GitHub = {
        users : {
            kokarn : {
                nick : 'Kokarn',
                id : false
            },
            gyran : {
                nick: 'Gyran',
                id : false
            },
            theseal: {
                nick : 'TheSeal',
                id : false
            },
            jwilsson : {
                nick : 'McGurk',
                id : false
            }
        },
        loadInterval : false,
        githubConfig : false,
        characters : {
            'lastMessage' : '┗',
            'message' : '┣'
        },
        start : function(){
            GitHub.getAllUsers();

            this.loadInterval = setInterval( function(){
                GitHub.getAllUsers();
            }, 60000 );
        },
        setup : function( bot ){
            this.githubConfig = require( './config.json' )[ 0 ];
            this.bot = bot;

            if( this.githubConfig === false ){
                console.log( 'Failed to load github config, skipping github setup' );
            } else {
                this.start();
            }
        },
        rightPad : function( myString, size, character ){
            myString = myString.toString();

            while( myString.length < size ) {
                myString = myString + character;
            }

            return myString;
        },
        apiUrlToRealUrl : function( apiUrl ){
            var realUrl = apiUrl.replace( 'api.github', 'github' );

            realUrl = realUrl.replace( '/repos/', '/' );

            return realUrl;
        },
        handleResponse : function( responseData, user ){
            // We can't use camelCase here because of the vars coming from GitHub
            /*jshint camelcase: false */
            var message = false,
                commitText = 'commit',
                messageStart,
                commitMessage;

            if( this.users[ user ].id !== false ){
                responseData[ 0 ].repo.html_url = this.apiUrlToRealUrl( responseData[ 0 ].repo.url );

                switch( responseData[ 0 ].type ){
                    case 'PushEvent':
                        if( responseData[ 0 ].payload.commits.length > 1 ){
                            commitText = commitText + 's';
                        }

                        message = this.users[ user ].nick + ' pushed ' + responseData[ 0 ].payload.commits.length + ' ' + commitText + ' to ' + responseData[ 0 ].repo.html_url;
                        for( var i = 0; i < responseData[ 0 ].payload.commits.length; i = i + 1 ){
                            messageStart = '    ';
                            if( i === responseData[ 0 ].payload.commits.length - 1 ){
                                messageStart = messageStart + this.characters.lastMessage + '   ';
                            } else {
                                messageStart = messageStart + this.characters.message + '   ';
                            }

                            commitMessage = responseData[ 0 ].payload.commits[ i ].message.replace( /(\r\n|\n\r|\n\n|\r\r|\r|\n)/gm, this.rightPad( '\n', messageStart.length + 1, ' ' ) );

                            message = message + '\n' + messageStart + commitMessage;
                        }
                        break;
                    case 'CreateEvent':
                        switch( responseData[ 0 ].payload.ref_type ){
                            case 'repository':
                                message = this.users[ user ].nick + ' created repository ' + responseData[ 0 ].repo.html_url;
                                break;
                            case 'branch':
                                message = this.users[ user ].nick + ' created a branch for ' + responseData[ 0 ].repo.html_url + ' called ' + responseData[ 0 ].payload.ref;
                                break;
                            default:
                                break;
                        }
                        break;
                    case 'PullRequestEvent' :
                        message = this.users[ user ].nick + ' created a pull request for ' + responseData[ 0 ].repo.html_url + ' titled "' + responseData[ 0 ].payload.pull_request.title + '"';
                        break;
                    case 'IssuesEvent':
                        switch( responseData[ 0 ].payload.action ){
                            case 'opened':
                                message = this.users[ user ].nick + ' created an issue for ' + responseData[ 0 ].repo.html_url + ' titled "' + responseData[ 0 ].payload.issue.title + '"';
                                break;
                            default:
                                break;
                        }
                        break;
                    case 'IssueCommentEvent':
                        //message = this.users[ user ].nick + ' commented on an issue for ' + responseData[ 0 ].repo.name;
                        //break;
                        /* falls through */
                    default:
                        break;
                }
            }

            this.users[ user ].id = responseData[ 0 ].id;

            if( message !== false ){
                this.say( message );
            }
        },
        say : function( message ){
            message = '\u0002GitHub:\u000F ' + message;

            // Say this in every channel it's connected to
            for( var channel in this.bot.opt.channels ){
                if( this.bot.opt.channels.hasOwnProperty( channel ) ){
                    this.bot.say( this.bot.opt.channels[ channel ], message );
                }
            }
        },
        getAllUsers : function(){
            var index = 0;

            for( var user in GitHub.users ){
                if( GitHub.users.hasOwnProperty( user ) ){
                    setTimeout( GitHub.getUserEvents( user ), index * 1000 );
                    index = index + 1;
                }
            }
        },
        getUserEvents : function( user ){
            var latestResponse = '',
                latestParsedResponse = '',
                request;

            request = https.get({
                hostname: 'api.github.com',
                port: 443,
                path: '/users/' + user + '/events?client_id=' + this.githubConfig.clientId + '&client_secret=' + this.githubConfig.clientSecret,
                method: 'GET',
                headers: {
                    'User-Agent': 'KokBot'
                }
            });

            request.on( 'error', function( data ){
                console.log( data );
            });

            request.on( 'response', function( response ) {
                console.log( 'Got response ' + response.statusCode + ' for user "' + user + '". Request remaining until reset: ' + response.headers[ 'x-ratelimit-remaining' ] );

                if( response.statusCode !== 200 ){
                    console.log( 'INVALID RESPONSE, service might be unavailable' );
                    return false;
                }

                response.on( 'data' , function( chunk ) {
                    latestResponse = latestResponse + chunk.toString();
                });

                response.on( 'end', function(){

                    try {
                        latestParsedResponse = JSON.parse( latestResponse );
                    } catch ( error ) {
                        console.log( error );
                        return false;
                    }

                    if( typeof latestParsedResponse[ 0 ].id !== 'undefined' && latestParsedResponse[ 0 ].id !== GitHub.users[ user ].id ){
                        GitHub.handleResponse( latestParsedResponse, user );
                    }
                });
            });
        }
    };

module.exports = GitHub;
<commit_msg>Fix minor formatting error<commit_after>'use strict';
var https = require( 'https' ),
    GitHub = {
        users : {
            kokarn : {
                nick : 'Kokarn',
                id : false
            },
            gyran : {
                nick: 'Gyran',
                id : false
            },
            theseal : {
                nick : 'TheSeal',
                id : false
            },
            jwilsson : {
                nick : 'McGurk',
                id : false
            }
        },
        loadInterval : false,
        githubConfig : false,
        characters : {
            'lastMessage' : '┗',
            'message' : '┣'
        },
        start : function(){
            GitHub.getAllUsers();

            this.loadInterval = setInterval( function(){
                GitHub.getAllUsers();
            }, 60000 );
        },
        setup : function( bot ){
            this.githubConfig = require( './config.json' )[ 0 ];
            this.bot = bot;

            if( this.githubConfig === false ){
                console.log( 'Failed to load github config, skipping github setup' );
            } else {
                this.start();
            }
        },
        rightPad : function( myString, size, character ){
            myString = myString.toString();

            while( myString.length < size ) {
                myString = myString + character;
            }

            return myString;
        },
        apiUrlToRealUrl : function( apiUrl ){
            var realUrl = apiUrl.replace( 'api.github', 'github' );

            realUrl = realUrl.replace( '/repos/', '/' );

            return realUrl;
        },
        handleResponse : function( responseData, user ){
            // We can't use camelCase here because of the vars coming from GitHub
            /*jshint camelcase: false */
            var message = false,
                commitText = 'commit',
                messageStart,
                commitMessage;

            if( this.users[ user ].id !== false ){
                responseData[ 0 ].repo.html_url = this.apiUrlToRealUrl( responseData[ 0 ].repo.url );

                switch( responseData[ 0 ].type ){
                    case 'PushEvent':
                        if( responseData[ 0 ].payload.commits.length > 1 ){
                            commitText = commitText + 's';
                        }

                        message = this.users[ user ].nick + ' pushed ' + responseData[ 0 ].payload.commits.length + ' ' + commitText + ' to ' + responseData[ 0 ].repo.html_url;
                        for( var i = 0; i < responseData[ 0 ].payload.commits.length; i = i + 1 ){
                            messageStart = '    ';
                            if( i === responseData[ 0 ].payload.commits.length - 1 ){
                                messageStart = messageStart + this.characters.lastMessage + '   ';
                            } else {
                                messageStart = messageStart + this.characters.message + '   ';
                            }

                            commitMessage = responseData[ 0 ].payload.commits[ i ].message.replace( /(\r\n|\n\r|\n\n|\r\r|\r|\n)/gm, this.rightPad( '\n', messageStart.length + 1, ' ' ) );

                            message = message + '\n' + messageStart + commitMessage;
                        }
                        break;
                    case 'CreateEvent':
                        switch( responseData[ 0 ].payload.ref_type ){
                            case 'repository':
                                message = this.users[ user ].nick + ' created repository ' + responseData[ 0 ].repo.html_url;
                                break;
                            case 'branch':
                                message = this.users[ user ].nick + ' created a branch for ' + responseData[ 0 ].repo.html_url + ' called ' + responseData[ 0 ].payload.ref;
                                break;
                            default:
                                break;
                        }
                        break;
                    case 'PullRequestEvent' :
                        message = this.users[ user ].nick + ' created a pull request for ' + responseData[ 0 ].repo.html_url + ' titled "' + responseData[ 0 ].payload.pull_request.title + '"';
                        break;
                    case 'IssuesEvent':
                        switch( responseData[ 0 ].payload.action ){
                            case 'opened':
                                message = this.users[ user ].nick + ' created an issue for ' + responseData[ 0 ].repo.html_url + ' titled "' + responseData[ 0 ].payload.issue.title + '"';
                                break;
                            default:
                                break;
                        }
                        break;
                    case 'IssueCommentEvent':
                        //message = this.users[ user ].nick + ' commented on an issue for ' + responseData[ 0 ].repo.name;
                        //break;
                        /* falls through */
                    default:
                        break;
                }
            }

            this.users[ user ].id = responseData[ 0 ].id;

            if( message !== false ){
                this.say( message );
            }
        },
        say : function( message ){
            message = '\u0002GitHub:\u000F ' + message;

            // Say this in every channel it's connected to
            for( var channel in this.bot.opt.channels ){
                if( this.bot.opt.channels.hasOwnProperty( channel ) ){
                    this.bot.say( this.bot.opt.channels[ channel ], message );
                }
            }
        },
        getAllUsers : function(){
            var index = 0;

            for( var user in GitHub.users ){
                if( GitHub.users.hasOwnProperty( user ) ){
                    setTimeout( GitHub.getUserEvents( user ), index * 1000 );
                    index = index + 1;
                }
            }
        },
        getUserEvents : function( user ){
            var latestResponse = '',
                latestParsedResponse = '',
                request;

            request = https.get({
                hostname: 'api.github.com',
                port: 443,
                path: '/users/' + user + '/events?client_id=' + this.githubConfig.clientId + '&client_secret=' + this.githubConfig.clientSecret,
                method: 'GET',
                headers: {
                    'User-Agent': 'KokBot'
                }
            });

            request.on( 'error', function( data ){
                console.log( data );
            });

            request.on( 'response', function( response ) {
                console.log( 'Got response ' + response.statusCode + ' for user "' + user + '". Request remaining until reset: ' + response.headers[ 'x-ratelimit-remaining' ] );

                if( response.statusCode !== 200 ){
                    console.log( 'INVALID RESPONSE, service might be unavailable' );
                    return false;
                }

                response.on( 'data' , function( chunk ) {
                    latestResponse = latestResponse + chunk.toString();
                });

                response.on( 'end', function(){

                    try {
                        latestParsedResponse = JSON.parse( latestResponse );
                    } catch ( error ) {
                        console.log( error );
                        return false;
                    }

                    if( typeof latestParsedResponse[ 0 ].id !== 'undefined' && latestParsedResponse[ 0 ].id !== GitHub.users[ user ].id ){
                        GitHub.handleResponse( latestParsedResponse, user );
                    }
                });
            });
        }
    };

module.exports = GitHub;
<|endoftext|>


<commit_before>/* globals chai THREE Vue VueGL */

describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace, VglPerspectiveCamera, VglScene} = VueGL;
    const assert = chai.assert;
    before(function() {
        this.WebGLRenderer = THREE.WebGLRenderer;
        THREE.WebGLRenderer = function(options) {
            this.options = options;
            this.shadowMap = {};
            this.calledRenderWith = [];
        };
        THREE.WebGLRenderer.prototype.setSize = () => {};
        THREE.WebGLRenderer.prototype.render = function(scene, camera) {
            this.calledRenderWith.push([scene, camera]);
        };
    });
    after(function() {
        THREE.WebGLRenderer = this.WebGLRenderer;
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-renderer camera="('&%" ref="rdr"><vgl-perspective-camera name="('&%" ref="cmr" /></vgl-renderer>`,
                    components: {VglRenderer, VglPerspectiveCamera}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.cmr, vm.$refs.cmr.inst);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-perspective-camera name="<!--" ref="cmr" /><vgl-renderer camera="<!--" ref="rdr" /></vgl-namespace>`,
                    components: {VglNamespace, VglRenderer, VglPerspectiveCamera}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.cmr, vm.$refs.cmr.inst);
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-renderer scene="('&%" ref="rdr"><vgl-scene name="('&%" ref="scn" /></vgl-renderer>`,
                    components: {VglRenderer, VglScene}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.scn, vm.$refs.scn.inst);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-scene name="<!--" ref="scn" /><vgl-renderer scene="<!--" ref="rdr" /></vgl-namespace>`,
                    components: {VglNamespace, VglRenderer, VglScene}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.scn, vm.$refs.scn.inst);
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                const vm = new Vue(VglRenderer);
                assert.strictEqual(vm.$refs.rdr, vm.inst.options.canvas);
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer);
                    assert.isFalse(vm.inst.options.alpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.options.alpha);
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.options.depth);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.options.depth);
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.options.stencil);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.options.stencil);
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.options.antialias);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.options.antialias);
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.options.premultipliedAlpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.options.premultipliedAlpha);
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.options.preserveDrawingBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.options.preserveDrawingBuffer);
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.options.logarithmicDepthBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.options.logarithmicDepthBuffer);
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isUndefined(vm.inst.options.precision);
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.options.precision, "lowp");
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.options.precision, "mediump");
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.options.precision, "highp");
                });
            });
        });
        describe("Properties", function() {
            describe("The shadowMapEnabled property should affect the shadowMap.enabled.", function() {
                beforeEach(function() {
                    this.outerDiv = document.createElement("div");
                    this.outerDiv.innerHTML = "

";
                    document.body.appendChild(this.outerDiv);
                });
                afterEach(function() {
                    document.body.removeChild(this.outerDiv);
                });
                it("When the property is false.", function(done) {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {shadowMapEnabled: false}, el: "#app"});
                    function waitonload(callback) {
                        if (!vm.$refs.frm.contentWindow) {
                            setTimeout(() => {
                                waitonload(callback);
                            }, 10);
                        } else {
                            callback();
                        }
                    }
                    waitonload(() => {
                        vm.$nextTick(() => {
                            setTimeout(() => {
                                try {
                                    assert.isFalse(vm.inst.shadowMap.enabled);
                                    done();
                                } catch(e) {
                                    done(e);
                                }
                            }, 0);
                        });
                    });
                });
                it("When the property is true.", function(done) {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {shadowMapEnabled: true}, el: "#app"});
                    function waitonload(callback) {
                        if (!vm.$refs.frm.contentWindow) {
                            setTimeout(() => {
                                waitonload(callback);
                            }, 10);
                        } else {
                            callback();
                        }
                    }
                    waitonload(() => {
                        vm.$nextTick(() => {
                            setTimeout(() => {
                                try {
                                    assert.isTrue(vm.inst.shadowMap.enabled);
                                    done();
                                } catch(e) {
                                    done(e);
                                }
                            }, 0);
                        });
                    });
                });
            });
        });
    });
    describe("When an initial property changes", function() {
        it("The canvas element should be replaced.", function(done) {
            const vm = new Vue(VglRenderer).$mount();
            const oldCanvas = vm.$refs.rdr;
            vm.alpha = true;
            vm.$nextTick(() => {
                try {
                    assert.notEqual(oldCanvas, vm.$refs.rdr);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
        it("The WebGLRenderer instance should be newly created.", function(done) {
            const vm = new Vue(VglRenderer).$mount();
            const oldInst = vm.inst;
            vm.alpha = true;
            vm.$nextTick(() => {
                try {
                    assert.notEqual(oldInst, vm.inst);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
        it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
            const vm = new Vue(VglRenderer).$mount();
            vm.alpha = true;
            vm.$nextTick(() => {
                try {
                    assert.strictEqual(vm.inst.options.canvas, vm.$refs.rdr);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
    });
    describe("When another property changes", function() {
        beforeEach(function() {
            this.outerDiv = document.createElement("div");
            this.outerDiv.innerHTML = "

";
            document.body.appendChild(this.outerDiv);
        });
        afterEach(function() {
            document.body.removeChild(this.outerDiv);
        });
        describe("The shadowMapEnabled should affect the shadowMap.enabled.", function() {
            it("From false to true.", function(done) {
                const vm = new Vue(VglRenderer).$mount("#app");
                vm.$nextTick(() => {
                    vm.shadowMapEnabled = true;
                    vm.$nextTick(() => {
                        try {
                            assert.isTrue(vm.inst.shadowMap.enabled);
                            done();
                        } catch(e) {
                            done(e);
                        }
                    });
                });
            });
        });
    });
    describe("Testing the rendering function", function() {
        beforeEach(function() {
            this.outerDiv = document.createElement("div");
            this.outerDiv.innerHTML = "

";
            document.body.appendChild(this.outerDiv);
        });
        afterEach(function() {
            document.body.removeChild(this.outerDiv);
        });
        it("The render function of the instance should be called once with the scene and camera after the initialization.", function(done) {
            const vm = new Vue({
                template: `<vgl-renderer scene="s" camera="c" ref="r"><vgl-scene name="s" ref="s"></vgl-scene><vgl-perspective-camera name="c" ref="c" /></vgl-renderer>`,
                components: {
                    VglRenderer,
                    VglScene,
                    VglPerspectiveCamera
                }
            }).$mount("#app");
            function waitonload(callback) {
                if (!vm.$refs.r.$refs.frm.contentWindow) {
                    setTimeout(() => {
                        waitonload(callback);
                    }, 10);
                } else {
                    callback();
                }
            }
            waitonload(() => {
                vm.$nextTick(() => {
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            try {
                                assert.lengthOf(vm.$refs.r.inst.calledRenderWith, 1);
                                assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][0], vm.$refs.s.inst);
                                assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][1], vm.$refs.c.inst);
                                done();
                            } catch(e) {
                                done(e);
                            }
                        }, 0);
                    });
                });
            });
        });
        it("The render function of the instance should be called once with the scene and camera after vglUpdate() called.", function(done) {
            const vm = new Vue({
                template: `<vgl-renderer scene="s" camera="c" ref="r"><vgl-scene name="s" ref="s"><trigger-component ref="t" /></vgl-scene><vgl-perspective-camera name="c" ref="c" /></vgl-renderer>`,
                components: {
                    VglRenderer,
                    VglScene,
                    VglPerspectiveCamera,
                    TriggerComponent: {
                        inject: ["vglUpdate"],
                        render: () => {}
                    }
                }
            }).$mount("#app");
            function waitonload(callback) {
                if (!vm.$refs.r.$refs.frm.contentWindow) {
                    setTimeout(() => {
                        waitonload(callback);
                    }, 10);
                } else {
                    callback();
                }
            }
            waitonload(() => {
                vm.$nextTick(() => {
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            vm.$refs.r.inst.calledRenderWith = [];
                            vm.$refs.t.vglUpdate();
                            vm.$nextTick(() => {
                                requestAnimationFrame(() => {
                                    setTimeout(() => {
                                        try {
                                            assert.lengthOf(vm.$refs.r.inst.calledRenderWith, 1);
                                            assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][0], vm.$refs.s.inst);
                                            assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][1], vm.$refs.c.inst);
                                            done();
                                        } catch(e) {
                                            done(e);
                                        }
                                    });
                                });
                            });
                        }, 0);
                    });
                });
            });
        });
        it("The render function should be called only once when vglUpdate() called multiple times.", function(done) {
            const vm = new Vue({
                template: `<vgl-renderer scene="s" camera="c" ref="r"><vgl-scene name="s" ref="s"><trigger-component ref="t" /></vgl-scene><vgl-perspective-camera name="c" ref="c" /></vgl-renderer>`,
                components: {
                    VglRenderer,
                    VglScene,
                    VglPerspectiveCamera,
                    TriggerComponent: {
                        inject: ["vglUpdate"],
                        render: () => {}
                    }
                }
            }).$mount("#app");
            function waitonload(callback) {
                if (!vm.$refs.r.$refs.frm.contentWindow) {
                    setTimeout(() => {
                        waitonload(callback);
                    }, 10);
                } else {
                    callback();
                }
            }
            waitonload(() => {
                vm.$nextTick(() => {
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            vm.$refs.r.inst.calledRenderWith = [];
                            vm.$refs.t.vglUpdate();
                            vm.$refs.t.vglUpdate();
                            vm.$refs.t.vglUpdate();
                            requestAnimationFrame(() => {
                                setTimeout(() => {
                                    try {
                                        assert.lengthOf(vm.$refs.r.inst.calledRenderWith, 1);
                                        assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][0], vm.$refs.s.inst);
                                        assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][1], vm.$refs.c.inst);
                                        done();
                                    } catch(e) {
                                        done(e);
                                    }
                                });
                            });
                        }, 0);
                    });
                });
            });
        });
    });
});
<commit_msg>Use contentDocument property instead contentWindow.<commit_after>/* globals chai THREE Vue VueGL */

describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace, VglPerspectiveCamera, VglScene} = VueGL;
    const assert = chai.assert;
    before(function() {
        this.WebGLRenderer = THREE.WebGLRenderer;
        THREE.WebGLRenderer = function(options) {
            this.options = options;
            this.shadowMap = {};
            this.calledRenderWith = [];
        };
        THREE.WebGLRenderer.prototype.setSize = () => {};
        THREE.WebGLRenderer.prototype.render = function(scene, camera) {
            this.calledRenderWith.push([scene, camera]);
        };
    });
    after(function() {
        THREE.WebGLRenderer = this.WebGLRenderer;
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-renderer camera="('&%" ref="rdr"><vgl-perspective-camera name="('&%" ref="cmr" /></vgl-renderer>`,
                    components: {VglRenderer, VglPerspectiveCamera}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.cmr, vm.$refs.cmr.inst);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-perspective-camera name="<!--" ref="cmr" /><vgl-renderer camera="<!--" ref="rdr" /></vgl-namespace>`,
                    components: {VglNamespace, VglRenderer, VglPerspectiveCamera}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.cmr, vm.$refs.cmr.inst);
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-renderer scene="('&%" ref="rdr"><vgl-scene name="('&%" ref="scn" /></vgl-renderer>`,
                    components: {VglRenderer, VglScene}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.scn, vm.$refs.scn.inst);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-scene name="<!--" ref="scn" /><vgl-renderer scene="<!--" ref="rdr" /></vgl-namespace>`,
                    components: {VglNamespace, VglRenderer, VglScene}
                }).$mount();
                assert.strictEqual(vm.$refs.rdr.scn, vm.$refs.scn.inst);
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                const vm = new Vue(VglRenderer);
                assert.strictEqual(vm.$refs.rdr, vm.inst.options.canvas);
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer);
                    assert.isFalse(vm.inst.options.alpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.options.alpha);
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.options.depth);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.options.depth);
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.options.stencil);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.options.stencil);
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.options.antialias);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.options.antialias);
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.options.premultipliedAlpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.options.premultipliedAlpha);
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.options.preserveDrawingBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.options.preserveDrawingBuffer);
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.options.logarithmicDepthBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.options.logarithmicDepthBuffer);
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isUndefined(vm.inst.options.precision);
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.options.precision, "lowp");
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.options.precision, "mediump");
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.options.precision, "highp");
                });
            });
        });
        describe("Properties", function() {
            describe("The shadowMapEnabled property should affect the shadowMap.enabled.", function() {
                beforeEach(function() {
                    this.outerDiv = document.createElement("div");
                    this.outerDiv.innerHTML = "

";
                    document.body.appendChild(this.outerDiv);
                });
                afterEach(function() {
                    document.body.removeChild(this.outerDiv);
                });
                it("When the property is false.", function(done) {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {shadowMapEnabled: false}, el: "#app"});
                    function waitonload(callback) {
                        if (!vm.$refs.frm.contentDocument) {
                            setTimeout(() => {
                                waitonload(callback);
                            }, 10);
                        } else {
                            callback();
                        }
                    }
                    waitonload(() => {
                        vm.$nextTick(() => {
                            setTimeout(() => {
                                try {
                                    assert.isFalse(vm.inst.shadowMap.enabled);
                                    done();
                                } catch(e) {
                                    done(e);
                                }
                            }, 0);
                        });
                    });
                });
                it("When the property is true.", function(done) {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {shadowMapEnabled: true}, el: "#app"});
                    function waitonload(callback) {
                        if (!vm.$refs.frm.contentDocument) {
                            setTimeout(() => {
                                waitonload(callback);
                            }, 10);
                        } else {
                            callback();
                        }
                    }
                    waitonload(() => {
                        vm.$nextTick(() => {
                            setTimeout(() => {
                                try {
                                    assert.isTrue(vm.inst.shadowMap.enabled);
                                    done();
                                } catch(e) {
                                    done(e);
                                }
                            }, 0);
                        });
                    });
                });
            });
        });
    });
    describe("When an initial property changes", function() {
        it("The canvas element should be replaced.", function(done) {
            const vm = new Vue(VglRenderer).$mount();
            const oldCanvas = vm.$refs.rdr;
            vm.alpha = true;
            vm.$nextTick(() => {
                try {
                    assert.notEqual(oldCanvas, vm.$refs.rdr);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
        it("The WebGLRenderer instance should be newly created.", function(done) {
            const vm = new Vue(VglRenderer).$mount();
            const oldInst = vm.inst;
            vm.alpha = true;
            vm.$nextTick(() => {
                try {
                    assert.notEqual(oldInst, vm.inst);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
        it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
            const vm = new Vue(VglRenderer).$mount();
            vm.alpha = true;
            vm.$nextTick(() => {
                try {
                    assert.strictEqual(vm.inst.options.canvas, vm.$refs.rdr);
                    done();
                } catch(e) {
                    done(e);
                }
            });
        });
    });
    describe("When another property changes", function() {
        beforeEach(function() {
            this.outerDiv = document.createElement("div");
            this.outerDiv.innerHTML = "

";
            document.body.appendChild(this.outerDiv);
        });
        afterEach(function() {
            document.body.removeChild(this.outerDiv);
        });
        describe("The shadowMapEnabled should affect the shadowMap.enabled.", function() {
            it("From false to true.", function(done) {
                const vm = new Vue(VglRenderer).$mount("#app");
                vm.$nextTick(() => {
                    vm.shadowMapEnabled = true;
                    vm.$nextTick(() => {
                        try {
                            assert.isTrue(vm.inst.shadowMap.enabled);
                            done();
                        } catch(e) {
                            done(e);
                        }
                    });
                });
            });
        });
    });
    describe("Testing the rendering function", function() {
        beforeEach(function() {
            this.outerDiv = document.createElement("div");
            this.outerDiv.innerHTML = "

";
            document.body.appendChild(this.outerDiv);
        });
        afterEach(function() {
            document.body.removeChild(this.outerDiv);
        });
        it("The render function of the instance should be called once with the scene and camera after the initialization.", function(done) {
            const vm = new Vue({
                template: `<vgl-renderer scene="s" camera="c" ref="r"><vgl-scene name="s" ref="s"></vgl-scene><vgl-perspective-camera name="c" ref="c" /></vgl-renderer>`,
                components: {
                    VglRenderer,
                    VglScene,
                    VglPerspectiveCamera
                }
            }).$mount("#app");
            function waitonload(callback) {
                if (!vm.$refs.r.$refs.frm.contentDocument) {
                    setTimeout(() => {
                        waitonload(callback);
                    }, 10);
                } else {
                    callback();
                }
            }
            waitonload(() => {
                vm.$nextTick(() => {
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            try {
                                assert.lengthOf(vm.$refs.r.inst.calledRenderWith, 1);
                                assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][0], vm.$refs.s.inst);
                                assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][1], vm.$refs.c.inst);
                                done();
                            } catch(e) {
                                done(e);
                            }
                        }, 0);
                    });
                });
            });
        });
        it("The render function of the instance should be called once with the scene and camera after vglUpdate() called.", function(done) {
            const vm = new Vue({
                template: `<vgl-renderer scene="s" camera="c" ref="r"><vgl-scene name="s" ref="s"><trigger-component ref="t" /></vgl-scene><vgl-perspective-camera name="c" ref="c" /></vgl-renderer>`,
                components: {
                    VglRenderer,
                    VglScene,
                    VglPerspectiveCamera,
                    TriggerComponent: {
                        inject: ["vglUpdate"],
                        render: () => {}
                    }
                }
            }).$mount("#app");
            function waitonload(callback) {
                if (!vm.$refs.r.$refs.frm.contentDocument) {
                    setTimeout(() => {
                        waitonload(callback);
                    }, 10);
                } else {
                    callback();
                }
            }
            waitonload(() => {
                vm.$nextTick(() => {
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            vm.$refs.r.inst.calledRenderWith = [];
                            vm.$refs.t.vglUpdate();
                            vm.$nextTick(() => {
                                requestAnimationFrame(() => {
                                    setTimeout(() => {
                                        try {
                                            assert.lengthOf(vm.$refs.r.inst.calledRenderWith, 1);
                                            assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][0], vm.$refs.s.inst);
                                            assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][1], vm.$refs.c.inst);
                                            done();
                                        } catch(e) {
                                            done(e);
                                        }
                                    });
                                });
                            });
                        }, 0);
                    });
                });
            });
        });
        it("The render function should be called only once when vglUpdate() called multiple times.", function(done) {
            const vm = new Vue({
                template: `<vgl-renderer scene="s" camera="c" ref="r"><vgl-scene name="s" ref="s"><trigger-component ref="t" /></vgl-scene><vgl-perspective-camera name="c" ref="c" /></vgl-renderer>`,
                components: {
                    VglRenderer,
                    VglScene,
                    VglPerspectiveCamera,
                    TriggerComponent: {
                        inject: ["vglUpdate"],
                        render: () => {}
                    }
                }
            }).$mount("#app");
            function waitonload(callback) {
                if (!vm.$refs.r.$refs.frm.contentDocument) {
                    setTimeout(() => {
                        waitonload(callback);
                    }, 10);
                } else {
                    callback();
                }
            }
            waitonload(() => {
                vm.$nextTick(() => {
                    requestAnimationFrame(() => {
                        setTimeout(() => {
                            vm.$refs.r.inst.calledRenderWith = [];
                            vm.$refs.t.vglUpdate();
                            vm.$refs.t.vglUpdate();
                            vm.$refs.t.vglUpdate();
                            requestAnimationFrame(() => {
                                setTimeout(() => {
                                    try {
                                        assert.lengthOf(vm.$refs.r.inst.calledRenderWith, 1);
                                        assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][0], vm.$refs.s.inst);
                                        assert.strictEqual(vm.$refs.r.inst.calledRenderWith[0][1], vm.$refs.c.inst);
                                        done();
                                    } catch(e) {
                                        done(e);
                                    }
                                });
                            });
                        }, 0);
                    });
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var utils = require('agentia-utilities');
var errors = require('../errors');
var helpers = require('../helpers');

function attach(target) {
  helpers.checkMinArgs(arguments, 1);

  if (!utils.isObject(target)) {
    throw new errors.MustBeObject('target');
  }

  this.mixin(target.prototype);
}

module.exports = attach;
<commit_msg>feat(static): update .attach() to return resulting object<commit_after>'use strict';

var utils = require('agentia-utilities');
var errors = require('../errors');
var helpers = require('../helpers');

function attach(target) {
  helpers.checkMinArgs(arguments, 1);

  if (!utils.isObject(target)) {
    throw new errors.MustBeObject('target');
  }

  this.mixin(target.prototype);

  return target;
}

module.exports = attach;
<|endoftext|>


<commit_before>/*!
 * wef.cssParser tests
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */
module("cssParser");
test("namespace", function() {
    notEqual(wef.cssParser , undefined, "is wef.cssParser namespace defined?");
    equal(typeof wef.cssParser, "function", "is wef.cssParser a function?");
});

test("constructor", function() {
    equal(typeof wef.cssParser(), "object", "empty constructor returns an object");
});

test("public properties", function() {
    equal(typeof wef.cssParser().version, "string", "wef.cssParser().version");
});

test("pubic methods", function() {
    var text = 'body { height: 100%; display: "a.b.c"  /2em "....."  /1em "d.e.f" "....."  /1em "g.h.i"  /2em 5em 1em  *  1em 10em}';
    notEqual(wef.cssParser().parse(text), null, "parse(string) ok");
});

test("parse", function() {
    raises(function() {
        wef.cssParser().parse("asd");
    }, "invalid css data throws an exception");
    raises(function() {
        wef.cssParser().parse(444);
    }, "parse(number) throws an exception");
    raises(function() {
        wef.cssParser().parse()
    }, "parse(undefined) throws an exception");
    raises(function() {
        wef.cssParser().parse(null)
    }, "parse(null) throws an exception");
    raises(function() {
        wef.cssParser().parse("")
    }, "empty data throws an exception");
    notEqual(wef.cssParser().parse("body{}"), null, "empty cssRule throws an exception");
    notEqual(wef.cssParser().parse("body{234}"), null, "invalid cssRule declaration throws an exception");
    notEqual(wef.cssParser().parse("body{} h1{display:none}"), null, "empty cssRule throws an exception");
});<commit_msg>Fix test messages<commit_after>/*!
 * wef.cssParser tests
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */
module("cssParser");
test("namespace", function() {
    notEqual(wef.cssParser , undefined, "is wef.cssParser namespace defined?");
    equal(typeof wef.cssParser, "function", "is wef.cssParser a function?");
});

test("constructor", function() {
    equal(typeof wef.cssParser(), "object", "empty constructor returns an object");
});

test("public properties", function() {
    equal(typeof wef.cssParser().version, "string", "wef.cssParser().version");
});

test("pubic methods", function() {
    var text = 'body { height: 100%; display: "a.b.c"  /2em "....."  /1em "d.e.f" "....."  /1em "g.h.i"  /2em 5em 1em  *  1em 10em}';
    notEqual(wef.cssParser().parse(text), null, "parse(string) ok");
});

test("parse exceptions", function() {
    raises(function() {
        wef.cssParser().parse("asd");
    }, "invalid css data throws an exception");
    raises(function() {
        wef.cssParser().parse(444);
    }, "parse(number) throws an exception");
    raises(function() {
        wef.cssParser().parse()
    }, "parse(undefined) throws an exception");
    raises(function() {
        wef.cssParser().parse(null)
    }, "parse(null) throws an exception");
    raises(function() {
        wef.cssParser().parse("")
    }, "empty data throws an exception");
    notEqual(wef.cssParser().parse("body{}"), null, "empty cssRule ok");
    notEqual(wef.cssParser().parse("body{234}"), null, "invalid cssRule declaration ok");
    notEqual(wef.cssParser().parse("body{} h1{display:none}"), null, "empty cssRule ok");
});<|endoftext|>


<commit_before>// Designed by rjf

var os = require( 'os' ),
    http = require("http"),
    url = require("url"),
    qs = require("querystring"),
    path = require("path"),
    fs = require("fs"),
    ct = 0,
    port = process.argv[2] || 8888, // 启动端口 port
    tp = process.argv[3] || 'ftp', // 输出类型 type
    wp = process.argv[4] || process.cwd(); // 指定目录 dir

var contentType = {
  ftp: 'application/octet-stream',
  http: {
    html: 'text/html',
    js: 'text/javascript',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    def: 'application/octet-stream'
  }
};
var contType = contentType[tp] ? contentType[tp] : false;

http.createServer(function(request, response) {

  request.setEncoding('utf8');//请求编码

  var uri = qs.unescape( url.parse(request.url).pathname ),
      filename = path.join(wp, uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    fs.stat(filename, function(err,stats) {
        if (err) {
          response.writeHead(500, {"Content-Type": "text/plain"});
          response.write(err + "\n");
          response.end();
          return;

        } else {
          if (stats.isDirectory()) {
            var files = fs.readdirSync(filename);
            if (files) {
              if ( uri.lastIndexOf('/') == uri.length -1 ) {
                uri = uri.substring(0, uri.length-1);
              }
              var dir = '/';
              if ( uri.lastIndexOf('/') > 0  ) {
                dir = uri.substring(0, uri.lastIndexOf('/'));
              }
              var all = '';
              if ( uri.length > 0) {
                all = '../' + '
';
              }
              uri += '/';
              for (var i in files) {
                all += '' + files[i] + '
';
              }
              all += '

power by nodejs downloads(' + ct + '). project: hftp author: ruanjiefeng';
              response.writeHead(202, {"Content-Type": "text/html; charset=UTF-8"});
              response.write( all );
              response.end();
            }
          } else {
            ct++;
            var t = contType ? contType[filename.replace(/.*\.(\w+)/,'$1')] : false;
            var hd = {
              'Content-Type' : t ? t : contentType['ftp'],
              'Content-Length': stats.size
            };
            response.writeHead(200, hd);

            fs.createReadStream(filename).pipe(response);
          }

        }
    });

  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + " type=" + tp + ", workspace=" + wp + "/\nCTRL + C to shutdown");
<commit_msg>Update static_server.js<commit_after>// Designed by rjf

var os = require( 'os' ),
    http = require("http"),
    url = require("url"),
    qs = require("querystring"),
    path = require("path"),
    fs = require("fs"),
    ct = 0,
    port = parseInt(process.argv[2], 10) || 8888, // 启动端口 port
    tp = process.argv[3] || 'ftp', // 输出类型 type
    wp = process.argv[4] || process.cwd(); // 指定目录 dir

if ("-v" == process.argv[2]) {
    console.log("v0.0.3");
    return;
}

var contentType = {
  ftp: 'application/octet-stream',
  http: {
    html: 'text/html',
    js: 'text/javascript',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    def: 'application/octet-stream'
  }
};
var contType = contentType[tp] ? contentType[tp] : false;

http.createServer(function(request, response) {

  request.setEncoding('utf8');//请求编码

  var uri = qs.unescape( url.parse(request.url).pathname ),
      filename = path.join(wp, uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    fs.stat(filename, function(err,stats) {
        if (err) {
          response.writeHead(500, {"Content-Type": "text/plain"});
          response.write(err + "\n");
          response.end();
          return;

        } else {
          if (stats.isDirectory()) {
            var files = fs.readdirSync(filename);
            if (files) {
              if ( uri.lastIndexOf('/') == uri.length -1 ) {
                uri = uri.substring(0, uri.length-1);
              }
              var dir = '/';
              if ( uri.lastIndexOf('/') > 0  ) {
                dir = uri.substring(0, uri.lastIndexOf('/'));
              }
              var all = '';
              if ( uri.length > 0) {
                all = '../' + '
';
              }
              uri += '/';
              for (var i in files) {
                all += '' + files[i] + '
';
              }
              all += '

power by nodejs downloads(' + ct + '). project: hftp author: ruanjiefeng';
              response.writeHead(202, {"Content-Type": "text/html; charset=UTF-8"});
              response.write( all );
              response.end();
            }
          } else {
            ct++;
            var t = contType ? contType[filename.replace(/.*\.(\w+)/,'$1')] : false;
            var hd = {
              'Content-Type' : t ? t : contentType['ftp'],
              'Content-Length': stats.size
            };
            response.writeHead(200, hd);

            fs.createReadStream(filename).pipe(response);
          }

        }
    });

  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + " type=" + tp + ", workspace=" + wp + "/\nCTRL + C to shutdown");
<|endoftext|>


<commit_before>/*!
 * wef.cssParser tests
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */
module("cssParser");

test("namespace", function () {
    notEqual(wef.cssParser, undefined, "is wef.cssParser namespace defined?");
    equal(typeof wef.cssParser, "function", "is wef.cssParser a function?");
});

test("constructor", function () {
    equal(typeof wef.cssParser(), "object", "empty constructor returns an object");
});

test("public properties", function () {
    equal(typeof wef.cssParser().version, "string", "wef.cssParser().version");
});

test("pubic methods", function () {
    var text = 'body { height: 100%; display: "a.b.c"  /2em "....."  /1em "d.e.f" "....."  /1em "g.h.i"  /2em 5em 1em  *  1em 10em}';
    notEqual(wef.cssParser().parse(text), null, "parse(string) ok");
});

test("parse exceptions", function () {
    raises(function () {
        wef.cssParser().parse("asd");
    }, "invalid css data throws an exception");
    raises(function () {
        wef.cssParser().parse(444);
    }, "parse(number) throws an exception");
    raises(function () {
        wef.cssParser().parse();
    }, "parse(undefined) throws an exception");
    raises(function () {
        wef.cssParser().parse(null);
    }, "parse(null) throws an exception");
    raises(function () {
        wef.cssParser().parse("");
    }, "empty data throws an exception");

    notEqual(wef.cssParser().parse("body{}"), null, "empty cssRule ok");
    notEqual(wef.cssParser().parse("body{234}"), null, "invalid cssRule declaration ok");
    notEqual(wef.cssParser().parse("body{} h1{display:none}"), null, "empty cssRule ok");

    notEqual(wef.cssParser().whenError(
        function () {
        }).parse("asd"), null, "error callback catches exception");
    notEqual(wef.cssParser().whenError(
        function () {
        }).parse("asd").parse("body{}"), null, "error callback allows chaining");
});

asyncTest("events", function() {
    var a = 0;
    wef.cssParser().whenStart(function() {
        a = 1;
    }).parse("body{}");
    equal(a, 1);
    setTimeout(function() {
        equal(a, 1);
        start();
        equal(a, 1);
    }, 1000);
});

//test("events", function () {
//    var text = "body {display: \"a\"}", events = [];
//
//    stop();
//    wef.cssParser().whenStart(function (e) {
//        console.log("start");
//        events.push(e.type);
//    });
//    wef.cssParser().whenProperty(function (e) {
//        console.log("prop");
//
//        events.push(e.type);
//    });
//    wef.cssParser().whenCssRule(function (e) {
//        console.log("css");
//
//        events.push(e.type);
//    });
//    wef.cssParser().whenStop(function (e) {
//        console.log("stop");
//
//        events.push(e.type);
//    });
//    wef.cssParser().parse(text);
//
//    setTimeout(function () {
//        //expect(5);
//
//
//        //equal(4, events.length);
//        //equal("parserStart", events.shift());
//        //equal("cssRuleFound", events.shift());
//        //equal("propertyFound", events.shift());
//        //equal("parserDone", events.shift());
//        start();
//    }, 1000);
//});<commit_msg>Add callbacks test<commit_after>/*!
 * wef.cssParser tests
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */
module("cssParser");

test("namespace", function () {
    notEqual(wef.cssParser, undefined, "is wef.cssParser namespace defined?");
    equal(typeof wef.cssParser, "function", "is wef.cssParser a function?");
});

test("constructor", function () {
    equal(typeof wef.cssParser(), "object", "empty constructor returns an object");
});

test("public properties", function () {
    equal(typeof wef.cssParser().version, "string", "wef.cssParser().version");
});

test("pubic methods", function () {
    var text = 'body { height: 100%; display: "a.b.c"  /2em "....."  /1em "d.e.f" "....."  /1em "g.h.i"  /2em 5em 1em  *  1em 10em}';
    notEqual(wef.cssParser().parse(text), null, "parse(string) ok");
});

test("parse exceptions", function () {
    raises(function () {
        wef.cssParser().parse("asd");
    }, "invalid css data throws an exception");
    raises(function () {
        wef.cssParser().parse(444);
    }, "parse(number) throws an exception");
    raises(function () {
        wef.cssParser().parse();
    }, "parse(undefined) throws an exception");
    raises(function () {
        wef.cssParser().parse(null);
    }, "parse(null) throws an exception");
    raises(function () {
        wef.cssParser().parse("");
    }, "empty data throws an exception");

    notEqual(wef.cssParser().parse("body{}"), null, "empty cssRule ok");
    notEqual(wef.cssParser().parse("body{234}"), null, "invalid cssRule declaration ok");
    notEqual(wef.cssParser().parse("body{} h1{display:none}"), null, "empty cssRule ok");

    notEqual(wef.cssParser().whenError(
        function () {
        }).parse("asd"), null, "error callback catches exception");
    notEqual(wef.cssParser().whenError(
        function () {
        }).parse("asd").parse("body{}"), null, "error callback allows chaining");
});

asyncTest("events", function () {
    var text = "body {display: \"a\"}", events = [];

    wef.cssParser().whenStart(function () {
        events.push("start");
    });
    wef.cssParser().whenProperty(function () {
        events.push("prop");
    });
    wef.cssParser().whenCssRule(function () {
        events.push("css");
    });
    wef.cssParser().whenStop(function () {
        events.push("stop");
    });
    wef.cssParser().parse(text);

    setTimeout(function () {
        expect(4);
        equal("start", events.shift());
        equal("css", events.shift());
        equal("prop", events.shift());
        equal("stop", events.shift());
        start();
    }, 100);
});

asyncTest("error event", function () {
    var text = "", events = [];

    wef.cssParser().whenStart(function () {
        events.push("start");
    });
    wef.cssParser().whenProperty(function () {
        events.push("prop");
    });
    wef.cssParser().whenCssRule(function () {
        events.push("css");
    });
    wef.cssParser().whenStop(function () {
        events.push("stop");
    });
    wef.cssParser().whenError(function () {
            events.push("error");
        });
    wef.cssParser().parse(text);

    setTimeout(function () {
        expect(1);
        equal("error", events.shift());
        start();
    }, 100);
});<|endoftext|>


<commit_before>module('line');

test('Confidence band is added', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12, 'l': 10, 'u': 14},
               {'date': new Date('2014-03-01'), 'value': 18, 'l': 16, 'u': 20}],
        show_confidence_band: ['l', 'u']
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-confidence-band'), 'Confidence band is added');
});

test('Only one confidence is added on multiple calls to the same target element', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12, 'l': 10, 'u': 14},
               {'date': new Date('2014-03-01'), 'value': 18, 'l': 16, 'u': 20}],
        show_confidence_band: ['l', 'u']
    };

    MG.data_graphic(params);
    MG.data_graphic(MG.clone(params));

    equal(document.querySelectorAll(target + ' .mg-confidence-band').length, 1, 'We only have one confidence band');
});

test('args.area set to true', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-main-area'), 'Path set for area');
});

test('args.area set to false', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
        area: false
    };

    MG.data_graphic(params);
    equal(document.querySelector('.mg-main-area'), null, 'No path for area');
});

test('A solitary active datapoint exists', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-active-datapoint').length, 1, 'One active datapoint exists');
});

test('A solitary rollover circle exists', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-line-rollover-circle').length, 1, 'One rollover circle exists');
});

test('Rollovers work for single lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-rollover-rect'), 'Rollovers exist');
});

test('Rollovers work for multiple lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-voronoi'), 'Rollovers exist');
});

test('We have only one set of rollovers for single lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-rollover-rect').length, 1, 'One set of rollovers exists');
});

test('We have only one set of rollovers for multiple lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-voronoi').length, 1, 'One set of rollovers exists');
});

test('We use the rect-style rollovers when `aggregate_rolloveres == true`', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]],
        aggregate_rollover: true
    };

    MG.data_graphic(params);

    // ensure rollover returns aggregated result data
    equal(document.querySelectorAll('.mg-voronoi').length, 0, 'Voronoi rollover is not generated');
    equal(document.querySelectorAll('.mg-rollover-rect').length, 1, 'Rect rollover is generated');
});

test('There are as many lines as data series (one)', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-main-line').length, 1, 'One line exists');
});

test('There are as many lines as data series (two)', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-main-line').length, 2, 'Two lines exist');
});

test('There are as many lines as data series (two) on multiple calls to an existing chart', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    MG.data_graphic(MG.clone(params));

    equal(document.querySelectorAll('.mg-main-line').length, 2, 'Two lines exist');
});

test('No zombie lines when we update a chart with fewer lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    var params2 = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    MG.data_graphic(params2);

    equal(document.querySelectorAll('.mg-main-line').length, 1, 'One line exists');
});
<commit_msg>Fixed aggregate_rollover test<commit_after>module('line');

test('Confidence band is added', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12, 'l': 10, 'u': 14},
               {'date': new Date('2014-03-01'), 'value': 18, 'l': 16, 'u': 20}],
        show_confidence_band: ['l', 'u']
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-confidence-band'), 'Confidence band is added');
});

test('Only one confidence is added on multiple calls to the same target element', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12, 'l': 10, 'u': 14},
               {'date': new Date('2014-03-01'), 'value': 18, 'l': 16, 'u': 20}],
        show_confidence_band: ['l', 'u']
    };

    MG.data_graphic(params);
    MG.data_graphic(MG.clone(params));

    equal(document.querySelectorAll(target + ' .mg-confidence-band').length, 1, 'We only have one confidence band');
});

test('args.area set to true', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-main-area'), 'Path set for area');
});

test('args.area set to false', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
        area: false
    };

    MG.data_graphic(params);
    equal(document.querySelector('.mg-main-area'), null, 'No path for area');
});

test('A solitary active datapoint exists', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-active-datapoint').length, 1, 'One active datapoint exists');
});

test('A solitary rollover circle exists', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-line-rollover-circle').length, 1, 'One rollover circle exists');
});

test('Rollovers work for single lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-rollover-rect'), 'Rollovers exist');
});

test('Rollovers work for multiple lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    ok(document.querySelector('.mg-voronoi'), 'Rollovers exist');
});

test('We have only one set of rollovers for single lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-rollover-rect').length, 1, 'One set of rollovers exists');
});

test('We have only one set of rollovers for multiple lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-voronoi').length, 1, 'One set of rollovers exists');
});

test('We use the rect-style rollovers when `aggregate_rolloveres == true`', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]],
        aggregate_rollover: true
    };

    MG.data_graphic(params);

    // ensure rollover returns aggregated result data
    equal(document.querySelectorAll('.mg-voronoi').length, 0, 'Voronoi rollover is not generated');
    equal(document.querySelectorAll('.mg-rollover-rect').length, 1, 'Rect rollover is generated');
});

test('There are as many lines as data series (one)', function() {
    var params = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-main-line').length, 1, 'One line exists');
});

test('There are as many lines as data series (two)', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    equal(document.querySelectorAll('.mg-main-line').length, 2, 'Two lines exist');
});

test('There are as many lines as data series (two) on multiple calls to an existing chart', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    MG.data_graphic(params);
    MG.data_graphic(MG.clone(params));

    equal(document.querySelectorAll('.mg-main-line').length, 2, 'Two lines exist');
});

test('No zombie lines when we update a chart with fewer lines', function() {
    var params = {
        target: '#qunit-fixture',
        data: [[{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}],
               [{'date': new Date('2014-01-01'), 'value': 120},
               {'date': new Date('2014-03-01'), 'value': 180}]]
    };

    var params2 = {
        target: '#qunit-fixture',
        data: [{'date': new Date('2014-01-01'), 'value': 12},
               {'date': new Date('2014-03-01'), 'value': 18}]
    };

    MG.data_graphic(params);
    MG.data_graphic(params2);

    equal(document.querySelectorAll('.mg-main-line').length, 1, 'One line exists');
});
<|endoftext|>