<commit_before>/*global describe it before after  =*/

"use client";

require(["lib/architect/architect", "lib/chai/chai", "/vfs-root"],
  function (architect, chai, baseProc) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath : "plugins/c9.core/c9",
            workspaceId : "johndoe/dev",
            startdate   : new Date(),
            debug       : true,
            hosted      : true,
            local       : false,
            davPrefix   : "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        {
            packagePath: "plugins/c9.core/settings",
            testing: true
        },
        "plugins/c9.core/api.js",
        {
            packagePath  : "plugins/c9.ide.ui/ui",
            staticPrefix : "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        "plugins/c9.ide.editors/editors",
        "plugins/c9.ide.editors/editor",
        "plugins/c9.ide.editors/tabmanager",
        "plugins/c9.ide.ui/focus",
        {
            packagePath: "plugins/c9.ide.console/console",
            testing : 2
        },
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.terminal/terminal",
        "plugins/c9.ide.run/output",
        {
            packagePath  : "plugins/c9.ide.run/run",
            testing      : true,
            base         : baseProc,
            staticPrefix : "plugins/c9.ide.run",
            runners      : {
                "node" : {
                    "caption" : "Node.js (current)",
                    "cmd": ["node", "${debug?--debug-brk=15454}", "$file"],
                    "debugger": "v8",
                    "debugport": 15454,
                    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
                    "selector": "source.js",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                },
                "pythoni" : {
                    "caption" : "Python in interactive mode",
                    "cmd": ["python", "-i"],
                    "selector": "source.python",
                    "info": "Hit \\033[01;34mCtrl-D\\033[00m to exit.\n"
                }
            }
        },
        "plugins/c9.ide.preferences/preferences",
        "plugins/c9.ide.ui/forms",
        "plugins/c9.fs/fs",
        "plugins/c9.fs/proc",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",

        // Mock plugins
        {
            consumes : ["apf", "ui", "Plugin"],
            provides : [
                "commands", "menus", "commands", "layout", "watcher",
                "save", "anims", "clipboard", "dialog.alert", "auth.bootstrap",
                "info", "debugger", "dialog.question", "run.gui", "dialog.error"
            ],
            setup    : expect.html.mocked
        },
        {
            consumes : ["tabManager", "proc", "output", "fs", "ext"],
            provides : [],
            setup    : main
        }
    ], architect);

    function main(options, imports, register) {
        var tabs     = imports.tabManager;
        var output   = imports.output;
        var fs       = imports.fs;
        var ext      = imports.ext;

        expect.html.setConstructor(function(tab){
            if (typeof tab == "object")
                return tab.pane.aml.getPage("editor::" + tab.editorType).$ext;
        });

        describe('terminal', function() {
            before(function(done){
                apf.config.setProperty("allow-select", false);
                apf.config.setProperty("allow-blur", false);

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "33%";

                document.body.style.marginBottom = "33%";
                tabs.on("ready", function(){
                    tabs.getPanes()[0].focus();
                    done();
                })
            });

            this.timeout(10000);

            it('should open an output window and run with a runner', function(done) {

                var c = "console.log('Hello World', new Date());";
                fs.writeFile("/helloworld.js", c, "utf8", function(err){
                    if (err) throw err.message;

                    tabs.open({
                        editorType : "output",
                        document   : {
                            title : "Output",
                            output : {
                                id: "testoutput",
                                config : {
                                    command : "/helloworld.js",
                                    debug: false
                                },
                                runner : "auto",
                                run    : true
                            }
                        }

                    }, function(err, tab){
                        var ace = tabs.focussedTab.editor.ace;
                        tab.editor.on("connect", function(){
                            ace.session.term.once('afterWrite', function(){
                                ace.renderer.on('afterRender', function(){
                                    if (tab.className.names.indexOf("running") == -1
                                      && ace.getValue().match(/Hello\s*World/)) {
                                        expect.html(ace.container).text(/Hello\s*World/);
                                        done();
                                    }
                                });
                            });
                        });
                    });
                });
            });

            if (!onload.remain){
                after(function(done){
                    ext.unloadAllPlugins();

                    document.body.style.marginBottom = "";
                    done();
                });
            }
        });

        onload && onload();
    }
});<commit_msg>Fix output_test<commit_after>/*global describe it before after  =*/

"use client";

require(["lib/architect/architect", "lib/chai/chai", "/vfs-root"],
  function (architect, chai, baseProc) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath : "plugins/c9.core/c9",
            workspaceId : "johndoe/dev",
            startdate   : new Date(),
            debug       : true,
            hosted      : true,
            local       : false,
            davPrefix   : "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        {
            packagePath: "plugins/c9.core/settings",
            testing: true
        },
        "plugins/c9.core/api.js",
        {
            packagePath  : "plugins/c9.ide.ui/ui",
            staticPrefix : "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        "plugins/c9.ide.editors/editors",
        "plugins/c9.ide.editors/editor",
        "plugins/c9.ide.editors/tabmanager",
        "plugins/c9.ide.ui/focus",
        {
            packagePath: "plugins/c9.ide.console/console",
            testing : 2
        },
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.terminal/terminal",
        "plugins/c9.ide.run/output",
        {
            packagePath  : "plugins/c9.ide.run/run",
            testing      : true,
            base         : baseProc,
            staticPrefix : "plugins/c9.ide.run",
            runners      : {
                "node" : {
                    "caption" : "Node.js (current)",
                    "cmd": ["node", "${debug?--debug-brk=15454}", "$file"],
                    "debugger": "v8",
                    "debugport": 15454,
                    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
                    "selector": "source.js",
                    "info": "Your code is running at \\033[01;34m$hostname\\033[00m.\n"
                        + "\\033[01;31mImportant:\\033[00m use \\033[01;32mprocess.env.PORT\\033[00m as the port and \\033[01;32mprocess.env.IP\\033[00m as the host in your scripts!\n"
                },
                "pythoni" : {
                    "caption" : "Python in interactive mode",
                    "cmd": ["python", "-i"],
                    "selector": "source.python",
                    "info": "Hit \\033[01;34mCtrl-D\\033[00m to exit.\n"
                }
            }
        },
        "plugins/c9.ide.preferences/preferences",
        "plugins/c9.ide.ui/forms",
        "plugins/c9.fs/fs",
        "plugins/c9.fs/proc",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",

        // Mock plugins
        {
            consumes : ["apf", "ui", "Plugin"],
            provides : [
                "commands", "menus", "commands", "layout", "watcher",
                "save", "anims", "clipboard", "dialog.alert", "auth.bootstrap",
                "info", "debugger", "dialog.question", "run.gui", "dialog.error",
                "dialog.filesave"
            ],
            setup    : expect.html.mocked
        },
        {
            consumes : ["tabManager", "proc", "output", "fs", "ext"],
            provides : [],
            setup    : main
        }
    ], architect);

    function main(options, imports, register) {
        var tabs     = imports.tabManager;
        var output   = imports.output;
        var fs       = imports.fs;
        var ext      = imports.ext;

        expect.html.setConstructor(function(tab){
            if (typeof tab == "object")
                return tab.pane.aml.getPage("editor::" + tab.editorType).$ext;
        });

        describe('terminal', function() {
            before(function(done){
                apf.config.setProperty("allow-select", false);
                apf.config.setProperty("allow-blur", false);

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "33%";

                document.body.style.marginBottom = "33%";
                tabs.on("ready", function(){
                    tabs.getPanes()[0].focus();
                    done();
                })
            });

            this.timeout(10000);

            it('should open an output window and run with a runner', function(done) {

                var c = "console.log('Hello World', new Date());";
                fs.writeFile("/helloworld.js", c, "utf8", function(err){
                    if (err) throw err.message;

                    tabs.open({
                        editorType : "output",
                        document   : {
                            title : "Output",
                            output : {
                                id: "testoutput",
                                config : {
                                    command : "/helloworld.js",
                                    debug: false
                                },
                                runner : "auto",
                                run    : true
                            }
                        }

                    }, function(err, tab){
                        var ace = tabs.focussedTab.editor.ace;
                        tab.editor.on("connect", function(){
                            ace.session.term.once('afterWrite', function(){
                                ace.renderer.on('afterRender', function(){
                                    if (tab.className.names.indexOf("running") == -1
                                      && ace.getValue().match(/Hello\s*World/)) {
                                        expect.html(ace.container).text(/Hello\s*World/);
                                        done();
                                    }
                                });
                            });
                        });
                    });
                });
            });

            if (!onload.remain){
                after(function(done){
                    ext.unloadAllPlugins();

                    document.body.style.marginBottom = "";
                    done();
                });
            }
        });

        onload && onload();
    }
});<|endoftext|>


<commit_before>var Prism = require('prismjs');
var loadLanguages = require('prismjs/components/');
loadLanguages(['php']);

module.exports = {
    title: 'Sharp',
    base: '/docs/',
    themeConfig: {
        nav: [
            { text: 'Home', link: '/' },
            { text: 'Documentation', link: '/guide/' },
            { text: 'Github', link:'https://github.com/code16/sharp' },
            { text: 'Medium', link:'https://medium.com/code16/tagged/sharp' },
        ],
        sidebar: {
            '/guide/': [
                {
                    title: 'Introduction',
                    collapsable: false,
                    children: [
                        '',
                        'authentication',
                    ]
                },
                {
                    title: 'Entity Lists',
                    collapsable: false,
                    children: [
                        'building-entity-list',
                        'filters',
                        'commands',
                        'entity-states',
                        'reordering-instances',
                    ]
                },
                {
                    title: 'Entity Forms',
                    collapsable: false,
                    children: [
                        'building-entity-form',
                        'entity-authorizations',
                        'multiforms',
                        'custom-form-fields'
                    ]
                },
                {
                    title: 'Form fields',
                    collapsable: false,
                    children: [
                        'text',
                        'textarea',
                        'markdown',
                        'wysiwyg',
                        'number',
                        'html',
                        'check',
                        'date',
                        'upload',
                        'select',
                        'autocomplete',
                        'tags',
                        'list',
                        'autocomplete-list',
                        'geolocation',
                    ].map(page => `form-fields/${page}`),
                },
                {
                    title: 'Dashboard',
                    collapsable: false,
                    children: [
                        'dashboard',
                        ...[
                            'graph',
                            'panel',
                        ].map(page => `dashboard-widgets/${page}`),
                    ],
                },
                {
                    title: 'Generalities',
                    collapsable: false,
                    children: [
                        'building-menu',
                        'how-to-transform-data',
                        'context',
                        'sharp-built-in-solution-for-uploads',
                        'form-data-localization',
                        'testing-with-sharp',
                        'artisan-generators',
                        'style-visual-theme'
                    ]
                },
                {
                    title: 'Migrations guide',
                    collapsable: false,
                    children: [
                        'upgrading/4.1',
                        'upgrading/4.1.3',
                    ],
                },
            ]
        },
    },
    markdown: {
        extendMarkdown: md => {
            md.renderer.rules['code_inline'] = (tokens, idx, options, env, slf) => {
                let token = tokens[idx];
                return '' +
                    Prism.highlight(token.content, Prism.languages.php) +
                '';
            };
        }
    },
    scss: {
        implementation: require('sass'),
    }
};<commit_msg>add demo link to top menu<commit_after>var Prism = require('prismjs');
var loadLanguages = require('prismjs/components/');
loadLanguages(['php']);

module.exports = {
    title: 'Sharp',
    base: '/docs/',
    themeConfig: {
        nav: [
            { text: 'Home', link: '/' },
            { text: 'Documentation', link: '/guide/' },
            { text: 'Demo', link: 'http://sharp.code16.fr/sharp/' },
            { text: 'Github', link:'https://github.com/code16/sharp' },
            { text: 'Medium', link:'https://medium.com/code16/tagged/sharp' },
        ],
        sidebar: {
            '/guide/': [
                {
                    title: 'Introduction',
                    collapsable: false,
                    children: [
                        '',
                        'authentication',
                    ]
                },
                {
                    title: 'Entity Lists',
                    collapsable: false,
                    children: [
                        'building-entity-list',
                        'filters',
                        'commands',
                        'entity-states',
                        'reordering-instances',
                    ]
                },
                {
                    title: 'Entity Forms',
                    collapsable: false,
                    children: [
                        'building-entity-form',
                        'entity-authorizations',
                        'multiforms',
                        'custom-form-fields'
                    ]
                },
                {
                    title: 'Form fields',
                    collapsable: false,
                    children: [
                        'text',
                        'textarea',
                        'markdown',
                        'wysiwyg',
                        'number',
                        'html',
                        'check',
                        'date',
                        'upload',
                        'select',
                        'autocomplete',
                        'tags',
                        'list',
                        'autocomplete-list',
                        'geolocation',
                    ].map(page => `form-fields/${page}`),
                },
                {
                    title: 'Dashboard',
                    collapsable: false,
                    children: [
                        'dashboard',
                        ...[
                            'graph',
                            'panel',
                        ].map(page => `dashboard-widgets/${page}`),
                    ],
                },
                {
                    title: 'Generalities',
                    collapsable: false,
                    children: [
                        'building-menu',
                        'how-to-transform-data',
                        'context',
                        'sharp-built-in-solution-for-uploads',
                        'form-data-localization',
                        'testing-with-sharp',
                        'artisan-generators',
                        'style-visual-theme'
                    ]
                },
                {
                    title: 'Migrations guide',
                    collapsable: false,
                    children: [
                        'upgrading/4.1',
                        'upgrading/4.1.3',
                    ],
                },
            ]
        },
    },
    markdown: {
        extendMarkdown: md => {
            md.renderer.rules['code_inline'] = (tokens, idx, options, env, slf) => {
                let token = tokens[idx];
                return '' +
                    Prism.highlight(token.content, Prism.languages.php) +
                '';
            };
        }
    },
    scss: {
        implementation: require('sass'),
    }
};<|endoftext|>


<commit_before>var async = require("async");
var cp = require("child_process");
var ralinkcmd ="/usr/bin/lsusb | /bin/egrep Ralink";
var huaweicmd = "/usr/bin/lsusb | /bin/egrep Huawei";
var cellcmd = "/usr/bin/wvdial IMEI; exit 0";

exports.deviceIds = function(callbackMain){
  async.parallel({
    ralink: function(callback){
      cp.exec(ralinkcmd,function(error,stdout,stderr){
        if (error) throw error;
        if (stdout){
          var str = stdout.toString().trim();
          //console.log(str);
          callback(null,str);
        }
        if (stderr) throw stderr;
      });
    },
    huawei: function(callback){
      cp.exec(huaweicmd,function(error,stdout,stderr){
        if (error) throw error;
        if (stdout){
          var str = stdout.toString().trim();
          //console.log(str);
          callback(null,str);
        }
        if (stderr) throw stderr;
      });
    },
    cell: function(callback){
      cp.exec(cellcmd,function(error,stdout,stderr){
        if (error) throw error;
        if (stdout){
          //console.log("stdout "+stdout);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: (\d+)\n/;
          var imei = stdout.match(imeiRX);
          var iccid = stdout.match(iccidRX);
          if(imei == null || iccid == null){
            callback("no modem");
          }else{
            var obj = {};
            obj["imei"] = imei[1];
            obj["iccid"] = iccid[1];
            callback(null,obj);
            console.log("imei: " + imei[1] + " iccid: " + iccid[1]);
          }

        }
        if (stderr){
          //console.log("Error "+ stderr);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: (\d+)\n/;
          var imei = stderr.match(imeiRX);
          var iccid = stderr.match(iccidRX);
          if(imei == null || iccid == null){
            callback("no modem");
          }else{
            var obj = {};
            obj["imei"] = imei[1];
            obj["iccid"] = iccid[1];
            callback(null,obj);
            //console.log("imei: " + imei[1] + " iccid: " + iccid[1]);
          }
        }// throw stderr;
      });
    }
},
function(err, results) {
    // results is now equals to: {one: 1, two: 2}
    callbackMain(err,results);
});

}
<commit_msg>handle usb setup error<commit_after>var async = require("async");
var cp = require("child_process");
var ralinkcmd ="/usr/bin/lsusb | /bin/egrep Ralink";
var huaweicmd = "/usr/bin/lsusb | /bin/egrep Huawei";
var cellcmd = "/usr/bin/wvdial IMEI; exit 0";

exports.deviceIds = function(callbackMain){
  async.parallel({
    ralink: function(callback){
      cp.exec(ralinkcmd,function(error,stdout,stderr){
        if (error) throw error;
        if (stdout){
          var str = stdout.toString().trim();
          //console.log(str);
          callback(null,str);
        }
        if (stderr) throw stderr;
      });
    },
    huawei: function(callback){
      cp.exec(huaweicmd,function(error,stdout,stderr){
        if (error) throw error;
        if (stdout){
          var str = stdout.toString().trim();
          //console.log(str);
          callback(null,str);
        }
        if (stderr) throw stderr;
      });
    },
    cell: function(callback){
      cp.exec(cellcmd,function(error,stdout,stderr){
        if (error) throw error;
        if (stdout){
          //console.log("stdout "+stdout);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: (\d+)\n/;
          var imei = stdout.match(imeiRX);
          var iccid = stdout.match(iccidRX);
          if(imei == null || iccid == null){
            callback("no modem");
          }else{
            var obj = {};
            obj["imei"] = imei[1];
            obj["iccid"] = iccid[1];
            callback(null,obj);
            console.log("imei: " + imei[1] + " iccid: " + iccid[1]);
          }

        }
        if (stderr){
          //console.log("Error "+ stderr);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: (\d+)\n/;
          var imei = stderr.match(imeiRX);
          var iccid = stderr.match(iccidRX);
          if(imei == null || iccid == null){
            var obj = {};
            obj["imei"] = null;
            obj["iccid"] = null;
            callback(null,obj);
          }else{
            var obj = {};
            obj["imei"] = imei[1];
            obj["iccid"] = iccid[1];
            callback(null,obj);
            //console.log("imei: " + imei[1] + " iccid: " + iccid[1]);
          }
        }// throw stderr;
      });
    }
},
function(err, results) {
    // results is now equals to: {one: 1, two: 2}
    callbackMain(err,results);
});

}
<|endoftext|>


<commit_before>/* StoPlay Content JS */

var Provider = function() {
	var _this = this;

	this.allowed = ['vk.com', 'grooveshark.com', 'youtube.com', 'vimeo.com', 'muzebra.com'];
	this.status = 'paused';
	this.interval = null;
	this.events = {};

	if(this.detectProvider()) {
		this.attachEvents();
		this.interval = setInterval(function(){
			_this.checkStatus();
		}, 1500);
	} else {
		return false;
	}
};

Provider.prototype.on = function(name, callback){
	if(typeof this.events[name] === 'undefined') this.events[name] = [];

	this.events[name].push(callback);
};

Provider.prototype.trigger = function(name){
	if(typeof this.events[name] === 'undefined') return;

	var l = this.events[name].length,
			i = 0;
	while(i < l) {
		this.events[name][i].call();
		i++;
	}
};

Provider.prototype.detectProvider = function() {
	this.host = window.location.host.replace('www.', '');

	return (this.allowed.indexOf(this.host) >= 0);
};

Provider.prototype.attachEvents = function() {
	var _this = this;

	this.on('start', function(){
		_this.status = 'playing';
		chrome.runtime.sendMessage({action: 'started'});
	});

	this.on('pause', function(){
		_this.status = 'paused';
		chrome.runtime.sendMessage({action: 'paused'});
	})
};

Provider.prototype.__changeState = function(status) {
	if(status != this.status) {
		switch(status) {
			case "playing":
				this.trigger( 'start' );
				break;

			case "paused":
				this.trigger( 'pause' );
				break;
		}
	}
};

Provider.prototype.checkStatus = function() {
	switch(this.host) {
		case "vk.com":
			var status = document.getElementById('head_play_btn').classList.contains('playing') ? 'playing' : 'paused';
			this.__changeState(status);
			break;

		case "vimeo.com":
			var status = document.querySelector('.play.state-playing') ? 'playing' : 'paused';
			this.__changeState(status);
			break;

		case "muzebra.com":
			var status = document.querySelector('#player button.play').classList.contains('icon-play') ? 'playing' : 'paused';
			this.__changeState(status);
			break;

		case "youtube.com":
			var p = document.getElementById("movie_player") || document.querySelector(".html5-video-player");
			if(p.getPlayerState) {
				var status = p.getPlayerState() == 1 ? 'playing' : 'paused';
			} else {
				var status = document.title.indexOf('▶') >= 0 ? 'playing' : 'paused';
			}
			this.__changeState(status);
			break;

		case "grooveshark.com":
			var status = document.getElementById('play-pause').classList.contains('playing') ? 'playing' : 'paused';
			this.__changeState(status);
			break;
	}
};

Provider.prototype.pause = function() {
	if(this.status == 'playing') {
		switch(this.host) {
			case "vk.com":
				document.querySelector('#gp_play.playing') && document.querySelector('#gp_play.playing').click();
				break;

			case "vimeo.com":
				document.querySelector('.play.state-playing') && document.querySelector('.play.state-playing').click();
				break;

			case "muzebra.com":
				document.querySelector('#player button.play.icon-pause') && document.querySelector('#player button.play.icon-pause').click();
				break;

			case "youtube.com":
				if(!document.querySelector(".html5-video-player")) {
					var p = document.getElementById("movie_player") || document.querySelector(".html5-video-player");
					p.pauseVideo();
				} else {
					document.querySelector(".ytp-button-pause") && document.querySelector(".ytp-button-pause").click();
				}
				break;

			case "grooveshark.com":
				document.querySelector('#play-pause.playing') && document.querySelector('#play-pause.playing').click();
				break;
		}
		this.__changeState('paused');
	}
};

Provider.prototype.play = function() {
	if(this.status != 'playing') {
		switch(this.host) {
			case "vk.com":
				document.querySelector('#gp_play:not(.playing)') && document.querySelector('#gp_play:not(.playing)').click();
				break;

			case "vimeo.com":
				document.querySelector('.play.state-paused') && document.querySelector('.play.state-paused').click();
				break;

			case "muzebra.com":
				document.querySelector('#player button.play.icon-play') && document.querySelector('#player button.play.icon-play').click();
				break;

			case "youtube.com":
				if(!document.querySelector(".html5-video-player")) {
					var p = document.getElementById("movie_player") || document.querySelector(".html5-video-player");
					p.playVideo();
				} else {
					document.querySelector(".ytp-button-play") && document.querySelector(".ytp-button-play").click();
				}
				break;

			case "grooveshark.com":
				document.querySelector('#play-pause.paused') && document.querySelector('#play-pause.paused').click();
				break;

		}
		this.__changeState('playing');
	}
};

var ProviderInstance = new Provider();

if(ProviderInstance) {
	chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
		if(request.action == 'pause') {
			ProviderInstance.pause();
		}

		if(request.action == 'play') {
			ProviderInstance.play();
		}
	});
}<commit_msg>muzebra status fix<commit_after>/* StoPlay Content JS */

var Provider = function() {
	var _this = this;

	this.allowed = ['vk.com', 'grooveshark.com', 'youtube.com', 'vimeo.com', 'muzebra.com'];
	this.status = 'paused';
	this.interval = null;
	this.events = {};

	if(this.detectProvider()) {
		this.attachEvents();
		this.interval = setInterval(function(){
			_this.checkStatus();
		}, 1500);
	} else {
		return false;
	}
};

Provider.prototype.on = function(name, callback){
	if(typeof this.events[name] === 'undefined') this.events[name] = [];

	this.events[name].push(callback);
};

Provider.prototype.trigger = function(name){
	if(typeof this.events[name] === 'undefined') return;

	var l = this.events[name].length,
			i = 0;
	while(i < l) {
		this.events[name][i].call();
		i++;
	}
};

Provider.prototype.detectProvider = function() {
	this.host = window.location.host.replace('www.', '');

	return (this.allowed.indexOf(this.host) >= 0);
};

Provider.prototype.attachEvents = function() {
	var _this = this;

	this.on('start', function(){
		_this.status = 'playing';
		chrome.runtime.sendMessage({action: 'started'});
	});

	this.on('pause', function(){
		_this.status = 'paused';
		chrome.runtime.sendMessage({action: 'paused'});
	})
};

Provider.prototype.__changeState = function(status) {
	if(status != this.status) {
		switch(status) {
			case "playing":
				this.trigger( 'start' );
				break;

			case "paused":
				this.trigger( 'pause' );
				break;
		}
	}
};

Provider.prototype.checkStatus = function() {
	switch(this.host) {
		case "vk.com":
			var status = document.getElementById('head_play_btn').classList.contains('playing') ? 'playing' : 'paused';
			this.__changeState(status);
			break;

		case "vimeo.com":
			var status = document.querySelector('.play.state-playing') ? 'playing' : 'paused';
			this.__changeState(status);
			break;

		case "muzebra.com":
			var status = document.querySelector('#player button.play').classList.contains('icon-pause') ? 'playing' : 'paused';
			this.__changeState(status);
			break;

		case "youtube.com":
			var p = document.getElementById("movie_player") || document.querySelector(".html5-video-player");
			if(p.getPlayerState) {
				var status = p.getPlayerState() == 1 ? 'playing' : 'paused';
			} else {
				var status = document.title.indexOf('▶') >= 0 ? 'playing' : 'paused';
			}
			this.__changeState(status);
			break;

		case "grooveshark.com":
			var status = document.getElementById('play-pause').classList.contains('playing') ? 'playing' : 'paused';
			this.__changeState(status);
			break;
	}
};

Provider.prototype.pause = function() {
	if(this.status == 'playing') {
		switch(this.host) {
			case "vk.com":
				document.querySelector('#gp_play.playing') && document.querySelector('#gp_play.playing').click();
				break;

			case "vimeo.com":
				document.querySelector('.play.state-playing') && document.querySelector('.play.state-playing').click();
				break;

			case "muzebra.com":
				document.querySelector('#player button.play.icon-pause') && document.querySelector('#player button.play.icon-pause').click();
				break;

			case "youtube.com":
				if(!document.querySelector(".html5-video-player")) {
					var p = document.getElementById("movie_player") || document.querySelector(".html5-video-player");
					p.pauseVideo();
				} else {
					document.querySelector(".ytp-button-pause") && document.querySelector(".ytp-button-pause").click();
				}
				break;

			case "grooveshark.com":
				document.querySelector('#play-pause.playing') && document.querySelector('#play-pause.playing').click();
				break;
		}
		this.__changeState('paused');
	}
};

Provider.prototype.play = function() {
	if(this.status != 'playing') {
		switch(this.host) {
			case "vk.com":
				document.querySelector('#gp_play:not(.playing)') && document.querySelector('#gp_play:not(.playing)').click();
				break;

			case "vimeo.com":
				document.querySelector('.play.state-paused') && document.querySelector('.play.state-paused').click();
				break;

			case "muzebra.com":
				document.querySelector('#player button.play.icon-play') && document.querySelector('#player button.play.icon-play').click();
				break;

			case "youtube.com":
				if(!document.querySelector(".html5-video-player")) {
					var p = document.getElementById("movie_player") || document.querySelector(".html5-video-player");
					p.playVideo();
				} else {
					document.querySelector(".ytp-button-play") && document.querySelector(".ytp-button-play").click();
				}
				break;

			case "grooveshark.com":
				document.querySelector('#play-pause.paused') && document.querySelector('#play-pause.paused').click();
				break;

		}
		this.__changeState('playing');
	}
};

var ProviderInstance = new Provider();

if(ProviderInstance) {
	chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
		if(request.action == 'pause') {
			ProviderInstance.pause();
		}

		if(request.action == 'play') {
			ProviderInstance.play();
		}
	});
}<|endoftext|>


<commit_before>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('../core');
var inherit = AWS.util.inherit;

require('../rest_xml_service');
require('../sigvs3');

/**
 * @class AWS.S3
 * @constructor
 */
AWS.S3 = inherit(AWS.RESTXMLService, {

  constructor: function S3(config) {
    this.serviceName = 's3';
    AWS.RESTXMLService.call(this, config);

    if (!this.endpoint.region) this.endpoint.region = 'us-east-1';

    if (this.endpoint.region === 'us-east-1')
      this.endpoint.host = 's3.amazonaws.com';

  },

  signatureVersion: AWS.SigVS3,

  populateURI: function populateURI(req, operation, params) {

    AWS.RESTService.prototype.populateURI.call(this, req, operation, params);

    // Try to move the bucket name from the request uri (path-style) to
    // the request endpoint host (virtual-hosted style) when possible.
    // Only possible when the bucket name is dns compatible, and still not
    // possible when using https and bucket name contains a '.'
    var b = params.Bucket;
    if (b) {
      if (!this.pathStyleBucketName(b)) {

        req.virtualHostedBucket = b; // needed for signing the request

        req.uri = req.uri.replace(new RegExp('^/' + b), '');
        if (req.uri[0] !== '/') req.uri = '/' + req.uri;
        req.endpoint.host = b + '.' + req.endpoint.host;

      }
    }

  },

  pathStyleBucketName: function pathStyleBucketName(bucketName) {

    // user can force path style requests via the configuration
    if (this.config.s3ForcePathStyle) return true;

    if (this.dnsCompatibleBucketName(bucketName)) {
      return (this.config.useSSL && bucketName.match(/\./)) ? true : false;
    } else {
      return true; // not dns compatible names must always use path style
    }

  },

  dnsCompatibleBucketName: function dnsCompatibleBucketName(bucketName) {
    var b = bucketName;
    var domain = new RegExp(/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/);
    var ipAddress = new RegExp(/(\d+\.){3}\d+/);
    var dots = new RegExp(/\.\./);
    return (b.match(domain) && !b.match(ipAddress) && !b.match(dots)) ? true : false;
  },

  escapePathParam: function escapePathParam(value) {
    return AWS.util.uriEscapePath(String(value));
  }

});

require('./s3.api');

AWS.Service.defineMethods(AWS.S3);
<commit_msg>Added additional documentation to the functions in AWS.S3.<commit_after>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('../core');
var inherit = AWS.util.inherit;

require('../rest_xml_service');
require('../sigvs3');

/**
 * @class AWS.S3
 * @constructor
 */
AWS.S3 = inherit(AWS.RESTXMLService, {

  constructor: function S3(config) {
    this.serviceName = 's3';
    AWS.RESTXMLService.call(this, config);

    if (!this.endpoint.region) this.endpoint.region = 'us-east-1';

    if (this.endpoint.region === 'us-east-1')
      this.endpoint.host = 's3.amazonaws.com';

  },

  signatureVersion: AWS.SigVS3,

  // S3 prefers dns-compatible bucket names to be moved from the uri path
  // to the host as a sub-domain.  This is not possible, even for dns-compat
  // buckets when using SSL and the bucket name contains a dot ('.').  The
  // ssl wildcart certificate is only 1-level deep.
  populateURI: function populateURI(req, operation, params) {

    AWS.RESTService.prototype.populateURI.call(this, req, operation, params);

    var b = params.Bucket;
    if (b) {
      if (!this.pathStyleBucketName(b)) {

        req.virtualHostedBucket = b; // needed for signing the request

        req.uri = req.uri.replace(new RegExp('^/' + b), '');
        if (req.uri[0] !== '/') req.uri = '/' + req.uri;
        req.endpoint.host = b + '.' + req.endpoint.host;

      }
    }

  },

  // Returns true if the bucket name should be left in the URI path for
  // a request to S3.  This function takes into account the current
  // endpoint scheme (e.g. http or https).
  pathStyleBucketName: function pathStyleBucketName(bucketName) {

    // user can force path style requests via the configuration
    if (this.config.s3ForcePathStyle) return true;

    if (this.dnsCompatibleBucketName(bucketName)) {
      return (this.config.useSSL && bucketName.match(/\./)) ? true : false;
    } else {
      return true; // not dns compatible names must always use path style
    }

  },

  // Returns true if the bucket name is DNS compatible.  Buckets created
  // outside of the classic region MUST be DNS compatible.
  dnsCompatibleBucketName: function dnsCompatibleBucketName(bucketName) {
    var b = bucketName;
    var domain = new RegExp(/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/);
    var ipAddress = new RegExp(/(\d+\.){3}\d+/);
    var dots = new RegExp(/\.\./);
    return (b.match(domain) && !b.match(ipAddress) && !b.match(dots)) ? true : false;
  },

  // S3 requires that path params not escape forward slashes.
  escapePathParam: function escapePathParam(value) {
    return AWS.util.uriEscapePath(String(value));
  }

});

require('./s3.api');

AWS.Service.defineMethods(AWS.S3);
<|endoftext|>


<commit_before>;(function () {
  'use strict'

  var configuration = {}

  var urlObserver = new window.MutationObserver(function(mutations, observer) {
    setTimeout(main)
  })

  urlObserver.observe(document.getElementById('js-pjax-loader-bar'), {
    attributes: true,
    attributeFilter: ['class']
  })

  function main() {
    if (configuration.SHOW_OUTDATED_COMMENTS) {
      shoutOutdatedDiffs()
    }

    if (configuration.SHOW_CURRENT_FILE_NAME) {
      showCurrentFileName()
    }

    if (configuration.COLLAPSABLE_DIFFS) {
      collapsableDiffs()
    }

    if (configuration.SHOW_ALL_HIDE_ALL_BUTTONS) {
      showHideAllButtons()
    }

    if (configuration.COLLAPSABLE_COMMITS) {
      collapseCommits()
    }
  }

  chrome.storage.sync.get({
    SHOW_OUTDATED_COMMENTS   : true,
    SHOW_CURRENT_FILE_NAME   : true,
    COLLAPSABLE_DIFFS        : true,
    SHOW_ALL_HIDE_ALL_BUTTONS: true,
    COLLAPSABLE_COMMITS      : true
  }, function (items) {
    configuration = items
    main()
  })

  chrome.storage.onChanged.addListener(function(changes, namespace) {
    // This could be nicer and re-bind all events after each update
    for(var prop in changes) {
      configuration[prop] = changes[prop].newValue
    }
  })

  // -----------------------------------------------------------------------------
  // Features

  function shoutOutdatedDiffs() {
    var outdatedDiffs = document.getElementsByClassName('outdated-diff-comment-container')

    for(var i = 0; i < outdatedDiffs.length; i++) {
      outdatedDiffs[i].classList.add('open')
    }
  }

  function showCurrentFileName() {
    var prtoolbar = document.querySelector('.pr-toolbar.js-sticky')
    if (! prtoolbar) return

    var diffbar = prtoolbar.querySelector('.diffbar')
    var headers = document.getElementsByClassName('file-header')
    var blobs   = document.getElementsByClassName('blob-wrapper')

    var diffbarItem = document.getElementById('__github-suite-current-file')
    if (! diffbarItem) {
      diffbarItem = document.createElement('div')
      diffbarItem.id = '__github-suite-current-file'
      diffbarItem.className = 'diffbar-item'
      diffbar.insertBefore(diffbarItem, diffbar.querySelector('.float-right'))
    }

    document.addEventListener('scroll', onScroll, false)

    onScroll()

    function onScroll() {
      var index = firstIndexInViewport(blobs)
      var currentHeader = headers[index]

      diffbarItem.style.display = prtoolbar.style.position === 'fixed' ? 'block' : 'none'

      if (currentHeader) {
        diffbarItem.innerHTML = currentHeader.dataset.path
      }
    }
  }

  function collapsableDiffs() {
    makeCollapsable({
      trigger: 'file-header',
      toggleableSibling: 'blob-wrapper'
    })
  }

  function showHideAllButtons() {
    var actions = document.querySelector('.pr-toolbar.js-sticky .float-right')

    if (actions) {
      var headers = Array.prototype.slice.call(document.getElementsByClassName('file-header'))

      var showAll = document.createElement('button')
      showAll.innerHTML = 'Show all'
      showAll.className = 'diffbar-item btn-link muted-link'
      showAll.onclick = function () { changeHadersVisibillity('remove') }

      var hideAll = document.createElement('button')
      hideAll.innerHTML = 'Hide all'
      hideAll.className = 'diffbar-item btn-link muted-link'
      hideAll.onclick = function () { changeHadersVisibillity('add') } // This will potentially break the filename

      actions.appendChild(showAll)
      actions.appendChild(hideAll)
    }

    function changeHadersVisibillity(method) {
      headers.forEach(function (header) {
        var code = nextByClass(header, 'blob-wrapper')
        if (code) code.classList[method]('hidden')
      })
    }
  }

  function collapseCommits() {
    if(! document.getElementById('commits_bucket')) return

    makeCollapsable({
      trigger: 'commit-group-title',
      toggleableSibling: 'commit-group'
    })
  }

  // -----------------------------------------------------------------------------
  // Utils

  function makeCollapsable(classes) {
    var triggers = document.getElementsByClassName(classes.trigger)

    for(var i = 0; i < triggers.length; i++) {
      triggers[i].addEventListener('click', togglePanel)
      triggers[i].style.cursor = 'pointer'
    }

    function togglePanel() {
      var code = nextByClass(this, classes.toggleableSibling)
      if (code) {
        code.classList.toggle('hidden')
      }
    }
  }

  function prevByClass(node, className) {
    return findSibling(node, 'previous', className)
  }

  function nextByClass(node, className) {
    return findSibling(node, 'next', className)
  }

  function findSibling(node, direction, className) {
    while (node = node[direction + 'Sibling']) {
      if (node.classList && node.classList.contains(className)) {
        return node
      }
    }
  }

  function firstIndexInViewport(els) {
    for(let i = 0; i < els.length; i++) {
      if (inViewport(els[i])) {
        return i
      }
    }
  }

  function inViewport(el) {
    let rect = el.getBoundingClientRect()
    let windowHeight = window.innerHeight || document.documentElement.clientHeight
    return rect.height && rect.top <= windowHeight && (rect.top + rect.height) >= 0
  }
})()
<commit_msg>Unnecessary guard<commit_after>;(function () {
  'use strict'

  var configuration = {}

  var urlObserver = new window.MutationObserver(function(mutations, observer) {
    setTimeout(main)
  })

  urlObserver.observe(document.getElementById('js-pjax-loader-bar'), {
    attributes: true,
    attributeFilter: ['class']
  })

  function main() {
    if (configuration.SHOW_OUTDATED_COMMENTS) {
      shoutOutdatedDiffs()
    }

    if (configuration.SHOW_CURRENT_FILE_NAME) {
      showCurrentFileName()
    }

    if (configuration.COLLAPSABLE_DIFFS) {
      collapsableDiffs()
    }

    if (configuration.SHOW_ALL_HIDE_ALL_BUTTONS) {
      showHideAllButtons()
    }

    if (configuration.COLLAPSABLE_COMMITS) {
      collapseCommits()
    }
  }

  chrome.storage.sync.get({
    SHOW_OUTDATED_COMMENTS   : true,
    SHOW_CURRENT_FILE_NAME   : true,
    COLLAPSABLE_DIFFS        : true,
    SHOW_ALL_HIDE_ALL_BUTTONS: true,
    COLLAPSABLE_COMMITS      : true
  }, function (items) {
    configuration = items
    main()
  })

  chrome.storage.onChanged.addListener(function(changes, namespace) {
    // This could be nicer and re-bind all events after each update
    for(var prop in changes) {
      configuration[prop] = changes[prop].newValue
    }
  })

  // -----------------------------------------------------------------------------
  // Features

  function shoutOutdatedDiffs() {
    var outdatedDiffs = document.getElementsByClassName('outdated-diff-comment-container')

    for(var i = 0; i < outdatedDiffs.length; i++) {
      outdatedDiffs[i].classList.add('open')
    }
  }

  function showCurrentFileName() {
    var prtoolbar = document.querySelector('.pr-toolbar.js-sticky')
    if (! prtoolbar) return

    var diffbar = prtoolbar.querySelector('.diffbar')
    var headers = document.getElementsByClassName('file-header')
    var blobs   = document.getElementsByClassName('blob-wrapper')

    var diffbarItem = document.getElementById('__github-suite-current-file')
    if (! diffbarItem) {
      diffbarItem = document.createElement('div')
      diffbarItem.id = '__github-suite-current-file'
      diffbarItem.className = 'diffbar-item'
      diffbar.insertBefore(diffbarItem, diffbar.querySelector('.float-right'))
    }

    document.addEventListener('scroll', onScroll, false)

    onScroll()

    function onScroll() {
      var index = firstIndexInViewport(blobs)
      var currentHeader = headers[index]

      diffbarItem.style.display = prtoolbar.style.position === 'fixed' ? 'block' : 'none'

      if (currentHeader) {
        diffbarItem.innerHTML = currentHeader.dataset.path
      }
    }
  }

  function collapsableDiffs() {
    makeCollapsable({
      trigger: 'file-header',
      toggleableSibling: 'blob-wrapper'
    })
  }

  function showHideAllButtons() {
    var actions = document.querySelector('.pr-toolbar.js-sticky .float-right')

    if (actions) {
      var headers = Array.prototype.slice.call(document.getElementsByClassName('file-header'))

      var showAll = document.createElement('button')
      showAll.innerHTML = 'Show all'
      showAll.className = 'diffbar-item btn-link muted-link'
      showAll.onclick = function () { changeHadersVisibillity('remove') }

      var hideAll = document.createElement('button')
      hideAll.innerHTML = 'Hide all'
      hideAll.className = 'diffbar-item btn-link muted-link'
      hideAll.onclick = function () { changeHadersVisibillity('add') } // This will potentially break the filename

      actions.appendChild(showAll)
      actions.appendChild(hideAll)
    }

    function changeHadersVisibillity(method) {
      headers.forEach(function (header) {
        var code = nextByClass(header, 'blob-wrapper')
        if (code) code.classList[method]('hidden')
      })
    }
  }

  function collapseCommits() {
    makeCollapsable({
      trigger: 'commit-group-title',
      toggleableSibling: 'commit-group'
    })
  }

  // -----------------------------------------------------------------------------
  // Utils

  function makeCollapsable(classes) {
    var triggers = document.getElementsByClassName(classes.trigger)

    for(var i = 0; i < triggers.length; i++) {
      triggers[i].addEventListener('click', togglePanel)
      triggers[i].style.cursor = 'pointer'
    }

    function togglePanel() {
      var code = nextByClass(this, classes.toggleableSibling)
      if (code) {
        code.classList.toggle('hidden')
      }
    }
  }

  function prevByClass(node, className) {
    return findSibling(node, 'previous', className)
  }

  function nextByClass(node, className) {
    return findSibling(node, 'next', className)
  }

  function findSibling(node, direction, className) {
    while (node = node[direction + 'Sibling']) {
      if (node.classList && node.classList.contains(className)) {
        return node
      }
    }
  }

  function firstIndexInViewport(els) {
    for(let i = 0; i < els.length; i++) {
      if (inViewport(els[i])) {
        return i
      }
    }
  }

  function inViewport(el) {
    let rect = el.getBoundingClientRect()
    let windowHeight = window.innerHeight || document.documentElement.clientHeight
    return rect.height && rect.top <= windowHeight && (rect.top + rect.height) >= 0
  }
})()
<|endoftext|>


<commit_before>import { Base } from 'yeoman-generator'

export default class LintingGenerator extends Base {

  //----------------------------------------
  // Writing
  //----------------------------------------

  writing() {
    this.log('LintingGenerator.writing...')
  }

  //----------------------------------------
  // Install
  //----------------------------------------

  install() {
    this.log('LintingGenerator.install')
  }
}
<commit_msg>Updated linting generator<commit_after>import { Base } from 'yeoman-generator'

export default class LintingGenerator extends Base {

  //----------------------------------------
  // Prompt User
  //----------------------------------------

  prompting() {
    this.log('LintingGenerator.prompting')
    return this.prompt([{
      type: 'confirm',
      name: 'flow',
      message: 'Use flow type checker:',
      default: true
    }]).then((answers) => {
      this.config.set(answers)
    })
  }

  //----------------------------------------
  // Writing
  //----------------------------------------

  writing() {
    this.log('LintingGenerator.writing')
  }

  //----------------------------------------
  // Install
  //----------------------------------------

  install() {
    this.log('LintingGenerator.install')
  }
}
<|endoftext|>


<commit_before>/* !
 * hotbot
 * Copyright (c) 2016 Guillaume RUCH <shirase.dev@gmail.com>
 * MIT Licensed
 */

const path = require('path');
const fs = require('fs');
const Module = require('../Module.js');

const RtmClient = require('@slack/client').RtmClient;
const MemoryDataStore = require('@slack/client').MemoryDataStore;
const clientEvts = require('@slack/client').CLIENT_EVENTS;
const rtmEvts = require('@slack/client').RTM_EVENTS;

class Slack extends Module {

	constructor(config) {
		super(config);
		const slackToken = config.connection.token;
		const autoReconnect = config.connection.autoReconnect || true;
		const autoMark = config.connection.autoMark || true;

		this.slack = new RtmClient(slackToken, {
			logLevel: 'error',
			dataStore: new MemoryDataStore(),
			autoReconnect,
			autoMark
		});

		this.slack.on(clientEvts.RTM.RTM_CONNECTION_OPENED, () => {
			const user = this.slack.dataStore.getUserById(this.slack.activeUserId);
			const team = this.slack.dataStore.getTeamById(this.slack.activeTeamId);

			this.name = user.name;

			this.log(`Connected to ${team.name} as ${user.name}`);
		});

		const p = this.config.commandsPath;

		this.commands = fs.readdirSync(p).filter(f => fs.statSync(p + '/' + f).isDirectory());
		this.modules = {};
		this.expects = [];
	}

	init(cb) {
		this.commands.forEach(m => {
			const Command = require(path.resolve(this.config.commandsPath, m));

			this.log(`Slack - Loaded Command ${m}`);
			this.modules[m] = new Command(this.slack.dataStore)
				.on('init', this.log)
				.on('log', this.log)
				.on('expect', msg => this.expects.push({module: m, chan: msg.chan, method: msg.method || 'reply'}))
				.on('rmExpect', msg => {
					this.expects = this.expects.filter(o => o.chan !== msg);
				})
				.on('requestModuleComponent', d => {
					this.emit('requestComponent', {
						from: 'slack',
						to: d.to,
						method: 'forwardComponent',
						component: d.component,
						fw: {name: m, method: d.method}
					});
				})
				.on('msg', this.sendFromObject.bind(this));
			this.modules[m].init();
		});

		this.slack.on(rtmEvts.MESSAGE, msg => {
			if (! msg.text) {
				return;
			}
			this.processMsg(msg);
		});

		this.slack.start();
		cb();
	}

	forwardComponent(comp, dest) {
		this.modules[dest.name][dest.method](comp);
	}

	processMsg(msg) {
		const cmd = msg.text.split(' ')[0];
		const isExpected = this.expects.filter(o => o.chan === msg.channel)[0];

		if (isExpected) {
			this.modules[isExpected.module][isExpected.method](msg);
		}else if (this.commands.includes(cmd)) {
			let res;

			if (! this.modules[cmd].config.noValidate) {
				res = this.verifyArgs(cmd, msg.text);
			}
			let reply;

			if (res === 1) {
				reply = `Wrong number of arguments for command *${cmd}*, expected *${this.modules[cmd].config.help}*`;
				this.send(reply, msg.channel);
			}else if (res === 2) {
				reply = `Wrong arguments type for command *${cmd}*, expected *${this.modules[cmd].config.help}*`;
				this.send(reply, msg.channel);
			}else {
				msg.text = res;
				this.modules[cmd].execute(msg);
			}
		}else {
			this.watch(msg);
		}
	}

	watch(msg) {

	}

	parseArgs(str) {
		const parser = new RegExp(/"[^"]*"|[^\s"]+/g);
		const args = str.match(parser);

		return args.splice(0, 1);
	}

	verifyArgs(cmd, msg) {
		let result = 0;
		const args = this.parseArgs(msg);
		const valid = this.modules[cmd].config.args;

		result = args;
		if (valid.length !== args.length) {
			return 1;
		}

		valid.forEach((e, i) => {
			try {
				if (! (e.type === 'string' || e.type === JSON.parse(args[i]))) {
					// TODO add options param
					result = 2;
				}
			}catch (wtv) {
				result = 2;
			}
		});
		return result;
	}

	send(msg, chanId, cb) {
		if (msg) {
			this.slack.sendMessage(msg, chanId, () => {
				if (cb) {
					cb();
				}
			});
		}
	}

	sendFromObject(o) {
		console.log(o);
		this.send(o.msg, o.chan);
	}

	sendFromModule(o) {
		console.log(o);
		this.send(o.msg, o.chan);
	}

	message(m) {
		if (m.DM) {
			const DM = m.DM.split(',');

			DM.forEach(e => this.send(m.msg, this.slack.dataStore.getDMByName(e).id));
		}
		if (m.chan) {
			const chan = m.chan.split(',');

			chan.forEach(e => this.send(m.msg, this.slack.dataStore.getChannelByName(e).id));
		}
	}

}

module.exports = Slack;
<commit_msg>dumb thing I forgot<commit_after>/* !
 * hotbot
 * Copyright (c) 2016 Guillaume RUCH <shirase.dev@gmail.com>
 * MIT Licensed
 */

const path = require('path');
const fs = require('fs');
const Module = require('../Module.js');

const RtmClient = require('@slack/client').RtmClient;
const MemoryDataStore = require('@slack/client').MemoryDataStore;
const clientEvts = require('@slack/client').CLIENT_EVENTS;
const rtmEvts = require('@slack/client').RTM_EVENTS;

class Slack extends Module {

	constructor(config) {
		super(config);
		const slackToken = config.connection.token;
		const autoReconnect = config.connection.autoReconnect || true;
		const autoMark = config.connection.autoMark || true;

		this.slack = new RtmClient(slackToken, {
			logLevel: 'error',
			dataStore: new MemoryDataStore(),
			autoReconnect,
			autoMark
		});

		this.slack.on(clientEvts.RTM.RTM_CONNECTION_OPENED, () => {
			const user = this.slack.dataStore.getUserById(this.slack.activeUserId);
			const team = this.slack.dataStore.getTeamById(this.slack.activeTeamId);

			this.name = user.name;

			this.log(`Connected to ${team.name} as ${user.name}`);
		});

		const p = this.config.commandsPath;

		this.commands = fs.readdirSync(p).filter(f => fs.statSync(p + '/' + f).isDirectory());
		this.modules = {};
		this.expects = [];
	}

	init(cb) {
		this.commands.forEach(m => {
			const Command = require(path.resolve(this.config.commandsPath, m));

			this.log(`Slack - Loaded Command ${m}`);
			this.modules[m] = new Command(this.slack.dataStore)
				.on('init', this.log)
				.on('log', this.log)
				.on('expect', msg => this.expects.push({module: m, chan: msg.chan, method: msg.method || 'reply'}))
				.on('rmExpect', msg => {
					this.expects = this.expects.filter(o => o.chan !== msg);
				})
				.on('requestModuleComponent', d => {
					this.emit('requestComponent', {
						from: 'slack',
						to: d.to,
						method: 'forwardComponent',
						component: d.component,
						fw: {name: m, method: d.method}
					});
				})
				.on('msg', this.sendFromObject.bind(this));
			this.modules[m].init();
		});

		this.slack.on(rtmEvts.MESSAGE, msg => {
			if (! msg.text) {
				return;
			}
			this.processMsg(msg);
		});

		this.slack.start();
		cb();
	}

	forwardComponent(comp, dest) {
		this.modules[dest.name][dest.method](comp);
	}

	processMsg(msg) {
		const cmd = msg.text.split(' ')[0];
		const isExpected = this.expects.filter(o => o.chan === msg.channel)[0];

		if (isExpected) {
			this.modules[isExpected.module][isExpected.method](msg);
		}else if (this.commands.includes(cmd)) {
			let res = this.parseArgs(msg.text);

			msg.text = res;
			if (! this.modules[cmd].config.noValidate) {
				res = this.verifyArgs(cmd, msg.text);
			}
			let reply;

			if (res === 1) {
				reply = `Wrong number of arguments for command *${cmd}*, expected *${this.modules[cmd].config.help}*`;
				this.send(reply, msg.channel);
			}else if (res === 2) {
				reply = `Wrong arguments type for command *${cmd}*, expected *${this.modules[cmd].config.help}*`;
				this.send(reply, msg.channel);
			}else {
				this.modules[cmd].execute(msg);
			}
		}else {
			this.watch(msg);
		}
	}

	watch(msg) {

	}

	parseArgs(str) {
		const parser = new RegExp(/"[^"]*"|[^\s"]+/g);
		const args = str.match(parser);

		return args.splice(0, 1);
	}

	verifyArgs(cmd, msg) {
		let result = 0;
		const args = this.parseArgs(msg);
		const valid = this.modules[cmd].config.args;

		result = args;
		if (valid.length !== args.length) {
			return 1;
		}

		valid.forEach((e, i) => {
			try {
				if (! (e.type === 'string' || e.type === JSON.parse(args[i]))) {
					// TODO add options param
					result = 2;
				}
			}catch (wtv) {
				result = 2;
			}
		});
		return result;
	}

	send(msg, chanId, cb) {
		if (msg) {
			this.slack.sendMessage(msg, chanId, () => {
				if (cb) {
					cb();
				}
			});
		}
	}

	sendFromObject(o) {
		console.log(o);
		this.send(o.msg, o.chan);
	}

	sendFromModule(o) {
		console.log(o);
		this.send(o.msg, o.chan);
	}

	message(m) {
		if (m.DM) {
			const DM = m.DM.split(',');

			DM.forEach(e => this.send(m.msg, this.slack.dataStore.getDMByName(e).id));
		}
		if (m.chan) {
			const chan = m.chan.split(',');

			chan.forEach(e => this.send(m.msg, this.slack.dataStore.getChannelByName(e).id));
		}
	}

}

module.exports = Slack;
<|endoftext|>


<commit_before>/**
 * Trainer Cards
 *
 * This is where the trainer cards commands
 * are located.
 *
 */

var trainerCards = {

	beforemath: 'judgmental'
	judge: 'judgmental',
	elitefourjudge: 'judgmental',
	judgmental: function (target, room, user) {
	    if (!this.canBroadcast()) return;
	    this.sendReplyBox('
<blink>Ace: Lapras</blink>
Stay Tuned!');
	},
};

Object.merge(CommandParser.commands, trainerCards);
exports.trainerCards = trainerCards;
<commit_msg>Update trainer-cards.js<commit_after>/**
 * Trainer Cards
 *
 * This is where the trainer cards commands
 * are located.
 *
 */

var trainerCards = {

	beforemath: 'judgmental',
	judge: 'judgmental',
	elitefourjudge: 'judgmental',
	judgmental: function (target, room, user) {
	    if (!this.canBroadcast()) return;
	    this.sendReplyBox('
<blink>Ace: Lapras</blink>
Stay Tuned!');
	},
};

Object.merge(CommandParser.commands, trainerCards);
exports.trainerCards = trainerCards;
<|endoftext|>


<commit_before>// https://jsfiddle.net/b4ycbo4p/12/

function t (x, y) {
  return `translate(${x},${y})`;
}

function genSmithChart ($) {

  function Re (props) {
    const r = props.r;
    return $('g', {transform: t(2 * r, r)},
    	props.lines
      .map(x => r / (1 + x))
      .map((e, i) => $('circle', {
        key: i,
        cx: -e,
        cy: 0,
        r: e,
        className: 'l1'
      }))
    );
  }

  function Im (props) {
    const r = props.r;
    return $('g', {transform: t(2 * r, r)},
      props.lines
      .map(x => [
      	$('circle', {
        	key: 0,
          cx: 0,
          cy: -(r / x),
          r: (r / x),
          className: 'l1'
        }),
        $('circle', {
        	key: 1,
          cx: 0,
          cy: r / x,
          r: r / x,
          className: 'l1'
        })
/* 			$('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 1 ${r},0`
        }),
        $('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 0 ${r},${2 * r}`
        }) */
      ]
      ),
      $('line', {
        x1: 0, y1: 0,
        x2: -2 * r, y2: 0,
        className: 'l1'
      })
    );
  }

  return function SmithChart(props) {
    const r = props.r;
    return $('div', {},
      $('div', {}, 'Smith Chart'),
      $('div', {},
        $('svg', { viewBox: [0, 0, 2 * r + 2, 2 * r + 2] },
          $('defs', {},
            $('style', {},
            `.l1 {
            	stroke: black;
              fill: none;
              stroke-linecap: square; /* butt */
              stroke-opacity: 0.1;
            }`)
          ),
          $('g', {transform: t(.5, .5)},
            $(Re, {r: r, lines: [0, .2, .5, 1, 2, 5]}),
            $(Im, {r: r, lines: [.2, .5, 1, 1.4, 2, 3, 5]})
          )
        )
      )
    );
  };
}

module.exports = genSmithChart;

// ReactDOM.render(
//   genSmithChart(React.createElement)({ r: 256 }),
//   document.getElementById('container')
// );
<commit_msg>Update smith-chart.js<commit_after>// https://jsfiddle.net/b4ycbo4p/18/

function t (x, y) {
	return `translate(${x},${y})`;
}

function genSmithChart ($) {

	function ReLine (props) {
  	return $('circle', {
      cx: -props.r,
      r: props.r
    });
  }

	function Re (props) {
    const r = props.r;
    return $('g', {
    	transform: t(2 * r, r),
      className: 'l1'
    },
    	props.lines
      .map(x => r / (1 + x))
      .map((x, i) => $(ReLine, {r: x}))
    );
  }

	function ImLine (props) {
  	const y = props.y;
    const r = props.r;
    console.log(y, r);

		const r0 = Math.abs(y);
    const r1 = props.r;
    const r2 = 0.5 * r;
    const sign = -Math.sign(y);
    //const sweep = (y > 0) ? 1.5 : 1;
    const sweep = (y > 0) ? 1 : 0;
    const alfa = Math.atan(r0 / r2);
    const beta = Math.atan(r0 / r1);
    const x0 = r2 * (Math.cos(2 * alfa) - 1);
    const y0 = sign * r2 * Math.sin(2 * alfa);
    const x1 = r1 * (Math.cos(2 * beta) - 1);
    const y1 = sign * r1 * Math.sin(2 * beta);
/*
return $('circle', {
    	cy: -y,
      r: Math.abs(y)
    });
*/
    return $('path', {
       d: `M ${x0},${y0} A ${r0} ${r0} 0 0 ${sweep} ${x1},${y1}`
    });
  }

  function Im (props) {
    const r = props.r;
    return $('g', {
    	transform: t(2 * r, r),
      className: 'l1'
    },
      props.lines
      .map(y => r / y)
      .map(y => [
      	$(ImLine, {y:  y, r: r}),
        $(ImLine, {y: -y, r: r})
/* 			$('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 1 ${r},0`
        }),
        $('path', {
          className: 'l1',
          d: `M ${2 * r},${r} A ${r} ${r} 0 0 0 ${r},${2 * r}`
        }) */
      ]
      ),
      $('line', {
        x1: 0, y1: 0,
        x2: -2 * r, y2: 0,
        className: 'l1'
      })
    );
  }

  return function SmithChart(props) {
    const r = props.r;
    return $('div', {},
      $('div', {}, 'Smith Chart'),
      $('div', {},
        $('svg', { viewBox: [0, 0, 2 * r + 1, 2 * r + 1] },
          $('defs', {},
            $('style', {},
            `.l1 {
            	stroke: black;
              fill: none;
              stroke-linecap: square; /* butt */
              stroke-opacity: 0.1;
            }`)
          ),
          $('g', {transform: t(.5, .5)},
            $(Re, {r: r, lines: [0, .2, .5, 1, 2, 5]}),
            $(Im, {r: r, lines: [.2, .5, 1, 1.4, 2, 3, 5]})
          )
        )
      )
    );
  };
}

module.exports = genSmithChart;

// ReactDOM.render(
//   genSmithChart(React.createElement)({ r: 256 }),
//   document.getElementById('container')
// );
<|endoftext|>


<commit_before>/*
Copyright 2010 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*******************************************************************************
ControlJS - a JavaScript module for loading scripts faster.
  - home page: http://stevesouders.com/controljs/
  - code project: http://code.google.com/p/controljs/
  - discussion list: http://groups.google.com/group/controljs
*******************************************************************************/

var CJS = CJS || {};

CJS.start = function() {
	CJS.init();

	// Find all the script DOM elements that have been modified for ControlJS.
	CJS.findScripts();

	// Start scripts downloading in the background ASAP.
	CJS.downloadScripts();

	// Process scripts now or later depending on the defer setting.
	if ( CJS.defer ) {
		CJS.addHandler(window, 'load', CJS.processScripts);
	}
	else {
		alert("Immediate processing is not currently supported.");
		CJS.processScripts();
	}
};

// Find all scripts with a "text/cjs" type.
CJS.findScripts = function() {
	var aScripts = document.getElementsByTagName('script');
	var len = aScripts.length;
	for ( var i = 0; i < len; i++ ) {
		var script = aScripts[i];
		if ( "text/cjs" === CJS.getAttribute(script, "type") && "undefined" === typeof(script.cjsfound) ) {
			CJS.aScripts[CJS.aScripts.length] = script;
			script.cjsfound = true;  // mark the script as found so we can do a second pass later
		}
	}
	//CJS.dprint("found " + CJS.aScripts.length + " CJS scripts");
};

//
// DOWNLOAD PHASE
//

// Find all scripts with a "cjssrc" attribute.
CJS.downloadScripts = function() {
	var len = CJS.aScripts.length;
	for ( var i = 0; i < len; i++ ) {
		var script = CJS.aScripts[i];
		var src = CJS.getAttribute(script, "cjssrc");
		if ( src ) {
			CJS.downloadScript(src);
		}
	}
};

// Download a script in such a way that it's not executed immediately.
CJS.downloadScript = function(url) {
	CJS.dprint("downloading " + url);

	if ( CJS.bIE || CJS.bOpera ) {
		CJS.downloadScriptImage(url);
	}
	else {
		CJS.downloadScriptObject(url);
	}
};

// Download a script as an image.
// This puts it in the browser's cache, but doesn't execute it.
CJS.downloadScriptImage = function(url) {
	var img = new Image();
	img.onload = function() { CJS.onloadCallback(url); };
	img.onerror = function() { CJS.onloadCallback(url); }; // Chrome does onerror (not onload).
	img.src = url;
};

// Download a script as an object.
// This puts it in the browser's cache, but doesn't execute it.
// Based on http://www.phpied.com/preload-cssjavascript-without-execution/
CJS.downloadScriptObject = function(url) {
	if ( "undefined" === typeof(document.body) || ! document.body ) {
		// we need body for appending objects
		setTimeout("CJS.downloadScriptObject('" + url + "')", 50);
		return;
	}

	var obj = document.createElement('object');
	obj.data = url;
	obj.width  = 0;
	obj.height = 0;
	obj.onload = function() { CJS.onloadCallback(url); };
	obj.onerror = function() { CJS.onloadCallback(url); };
	//CJS.dprint("downloadScriptObject: appending " + url);
	document.body.appendChild(obj);
};

CJS.onloadCallback = function(url) {
	//CJS.dprint("onloadCallback: " + url);
	CJS.hLoaded[url] = true;
};

//
// EXECUTION PHASE
//

CJS.processScripts = function() {
	CJS.processNextScript();
};

CJS.processNextScript = function() {
	//CJS.dprint("processNextScript: enter");
	if ( CJS.aScripts.length ) {
		var script = CJS.aScripts[0];
		CJS.curScript = script;  // for docwrite

		var src = CJS.getAttribute(script, "cjssrc");
		var cjsexec = CJS.getAttribute(script, "cjsexec");
		if ( src ) {
			// External Script
			if ( "false" === cjsexec ) {
				CJS.aScripts.splice(0, 1);   // remove leading script
				setTimeout(CJS.processNextScript, 0);
			}
			else if ( CJS.hLoaded[src] ) {
				// Done downloading.
				CJS.processExternalScript(script, CJS.processNextScript);
				CJS.aScripts.splice(0, 1);   // remove leading script
				// Race condition! Need to call processNextScript from the onload handler
				// of the script added down inside processExternalScript. (Notice the
				// callback added above when calling processExternalScript.)
				//setTimeout(CJS.processNextScript, 0);
			}
			else {
				// Still downloading.
				CJS.dprint("processNextScript: waiting for script " + src);
				if ( "undefined" === typeof(script.startwait) ) {
					script.startwait = Number(new Date());  // start time
				}
				var delta = Number(new Date()) - script.startwait;
				if ( delta < CJS.maxWait ) {
					// try again
					setTimeout(CJS.processNextScript, CJS.waitival);
				}
				else {
					// bail
					alert("There was an error loading script: " + src);
				}
			}
		}
		else {
			// Inline Script
			CJS.processInlineScript(script);
			CJS.aScripts.splice(0, 1);   // remove leading script
			setTimeout(CJS.processNextScript, 0);
		}

		return;
	}

	// Do a 2nd pass looking for CJS scripts.
	// Because control.js loads async, it's possible for findScripts to be
	// be called before all SCRIPT tags have been created.
	CJS.findScripts();
	if ( CJS.aScripts.length ) {
		CJS.downloadScripts();
		setTimeout(CJS.processNextScript, 0);
		return;
	}

	// restore the original document.write function definition
	document.write = CJS.docwriteOrig;

	CJS.dprint("DONE processing scripts");

	/*
	TODO - We can try something like this to re-fire the window load event.
	var eventObj = document.createEvent("HTMLEvents");
	eventObj.initEvent("load", true, true);
	window.dispatchEvent(eventObj);
    */
};

// Eval the code in an inlined script.
CJS.processInlineScript = function(script) {
	//CJS.dprint("processInlineScript: enter");
	CJS.curScript = script;  // for docwrite

	var code = script.text;
	CJS.dprint("processInlineScript: processing script code: " + code.substring(0, 64));
	CJS.eval(code);
};

// If downloaded then add the external script as a real script DOM element.
CJS.processExternalScript = function(script, callback) {
	//CJS.dprint("processExternalScript: enter");

	var src = CJS.getAttribute(script, "cjssrc");
	CJS.dprint("processExternalScript: processing script " + src);
	CJS.execScript(src, callback);
};

// Insert a script DOM element.
// Presumably the src has already been downloaded and is in the cache.
CJS.execScript = function(src, onload) {
	CJS.dprint("execScript: " + src);
	var se = document.createElement('script');
	se.src = src;

	// handle onload code
	// TODO - support this from processExternalScript
	if ( "function" === typeof(onload) ) {
		se.onload = onload;
		se.onreadystatechange = onload;
	}
	else if ( "string" === typeof(onload) ) {
		se.onload = function() { CJS.eval(onload); };
		se.onreadystatechange = function() { CJS.eval(onload); };
	}

	var s1 = document.getElementsByTagName('script')[0];
	s1.parentNode.insertBefore(se, s1);
};

// Eval a string of JavaScript in the proper context.
CJS.eval = function(code) {
	//CJS.dprint("evaling: " + code.substring(0, 64));

	if (window.execScript) {
		window.execScript(code);
	}
	else {
		var fn = function() {
			window.eval.call(window, code);
		};
		fn();
	}

	//CJS.dprint("eval exit");
};

//
// UTILITY FUNCTIONS
//

CJS.init = function() {
	CJS.bInited = true;  // don't init twice

	// If defer is true then scripts aren't loaded until the onload event.
	CJS.defer = ( "undefined" === typeof(CJS.defer) ? true : CJS.defer );

	CJS.aScripts = [];  // array of CJS script DOM elements
	CJS.hLoaded = {};   // hash of script URLs that have loaded

	CJS.bIE = ( -1 != navigator.userAgent.indexOf('MSIE') );
	CJS.bChrome = ( -1 != navigator.userAgent.indexOf('Chrome/') );
	CJS.bOpera = ( -1 != navigator.userAgent.indexOf('Opera') );

	CJS.curScript = null; // for document.write

	CJS.maxWait = 5000;  // maximum number of milliseconds to wait for a script to download
	CJS.waitival = 200;  // number of milliseconds to wait between retries of looking for external script download

	CJS.docwriteOrig = document.write;  // keep a reference to the original function
	document.write = CJS.docwrite;      // override document.write
};

// Return the URL of the script that has been converted to CJS.
CJS.getAttribute = function(elem, name) {
	var attrs = elem.attributes;
	var len = attrs.length;
	for ( var i = 0; i < len; i++ ) {
		var attr = attrs[i];
		if ( name === attr.nodeName ) {
			return attr.nodeValue;
		}
	}

	return undefined;
};

// Wrapper for addEventListener and attachEvent.
CJS.addHandler = function(elem, sType, fn, capture) {
	capture = (capture) ? true : false;
	if (elem.addEventListener) {
		elem.addEventListener(sType, fn, capture);
	}
	else if (elem.attachEvent) {
		elem.attachEvent("on" + sType, fn);
	}
	else {
		// Netscape 4
		if ( elem["on" + sType] ) {
			// Do nothing - we don't want to overwrite an existing handler.
		}
		else {
			elem["on" + sType] = fn;
		}
	}
};

// Dynamically define dprint debug logging function.
if ( "undefined" != typeof(console) && "undefined" != typeof(console.log) ) {
	CJS.dprint = function(msg) {
		console.log("CJS " + Number(new Date()) + ": " + msg);
	};
}
else {
	CJS.dprint = function(msg) { };
};

//
// Override document.write
//

// Attempt to handle document.write. Doesn't work well if the
// document.write occurs in the HEAD or if it outputs a SCRIPT tag.
CJS.docwrite = function(text) {
	if ( CJS.curScript ) {
		if ( ! CJS.curScript.docwriteTarget ) {
			CJS.curScript.docwriteTarget = document.createElement('span');
			CJS.curScript.parentNode.insertBefore(CJS.curScript.docwriteTarget, CJS.curScript);
		}

		var i1 = text.indexOf("<script");
		if ( -1 === i1 ) {
			// no scripts
			CJS.dprint("docwrite: " + text.substring(0, 64));
			CJS.curScript.docwriteTarget.innerHTML += text;
		}
		else {
			// script tag
			var i2 = text.indexOf("<\/script>", i1) + 9;
			if ( -1 != i2 ) {
				var textBefore = text.substring(0, i1);
				var textScript = text.substring(i1, i2);
				var textAfter = text.substring(i2+1);

				if ( textBefore ) {
					CJS.dprint("docwrite: " + textBefore.substring(0, 64));
					CJS.curScript.docwriteTarget.innerHTML += textBefore + textAfter;
				}

				CJS.docwriteScript(textScript);
			}
		}
	}
	else {
		CJS.dprint("ERROR: There's a problem with the async override of document.write.");
	}
};

// Insert a SCRIPT element found during document.write.
CJS.docwriteScript = function(textScript) {
	// extract SRC from script docwrite and insert dynamically
	var aMatches = textScript.match(/src='([^']*)/i) ||
                   textScript.match(/src="([^"]*)/i) ||
                   textScript.match(/src=([^ >]*)/i);

	if ( aMatches ) {
		var url = aMatches[1];
		CJS.dprint("docwriteScript url = " + url);
		var se = document.createElement('script');
		se.src = url;
		document.body.appendChild(se);
	}
    else {
	    // TODO - handle inline SCRIPT code
	}
};

CJS.start();
<commit_msg>Add an execution queue. Turns out we can have race conditions where two calls to CJS.execScript might not be executed in the order they were called.<commit_after>/*
Copyright 2010 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*******************************************************************************
ControlJS - a JavaScript module for loading scripts faster.
  - home page: http://stevesouders.com/controljs/
  - code project: http://code.google.com/p/controljs/
  - discussion list: http://groups.google.com/group/controljs
*******************************************************************************/

var CJS = CJS || {};

CJS.start = function() {
	CJS.init();

	// Find all the script DOM elements that have been modified for ControlJS.
	CJS.findScripts();

	// Start scripts downloading in the background ASAP.
	CJS.downloadScripts();

	// Process scripts now or later depending on the defer setting.
	if ( CJS.defer ) {
		CJS.addHandler(window, 'load', CJS.processScripts);
	}
	else {
		alert("Immediate processing is not currently supported.");
		CJS.processScripts();
	}
};

// Find all scripts with a "text/cjs" type.
CJS.findScripts = function() {
	var aScripts = document.getElementsByTagName('script');
	var len = aScripts.length;
	for ( var i = 0; i < len; i++ ) {
		var script = aScripts[i];
		if ( "text/cjs" === CJS.getAttribute(script, "type") && "undefined" === typeof(script.cjsfound) ) {
			CJS.aScripts[CJS.aScripts.length] = script;
			script.cjsfound = true;  // mark the script as found so we can do a second pass later
		}
	}
	//CJS.dprint("found " + CJS.aScripts.length + " CJS scripts");
};

//
// DOWNLOAD PHASE
//

// Find all scripts with a "cjssrc" attribute.
CJS.downloadScripts = function() {
	var len = CJS.aScripts.length;
	for ( var i = 0; i < len; i++ ) {
		var script = CJS.aScripts[i];
		var src = CJS.getAttribute(script, "cjssrc");
		if ( src ) {
			CJS.downloadScript(src);
		}
	}
};

// Download a script in such a way that it's not executed immediately.
CJS.downloadScript = function(url) {
	CJS.dprint("downloading " + url);

	if ( CJS.bIE || CJS.bOpera ) {
		CJS.downloadScriptImage(url);
	}
	else {
		CJS.downloadScriptObject(url);
	}
};

// Download a script as an image.
// This puts it in the browser's cache, but doesn't execute it.
CJS.downloadScriptImage = function(url) {
	var img = new Image();
	img.onload = function() { CJS.onloadCallback(url); };
	img.onerror = function() { CJS.onloadCallback(url); }; // Chrome does onerror (not onload).
	img.src = url;
};

// Download a script as an object.
// This puts it in the browser's cache, but doesn't execute it.
// Based on http://www.phpied.com/preload-cssjavascript-without-execution/
CJS.downloadScriptObject = function(url) {
	if ( "undefined" === typeof(document.body) || ! document.body ) {
		// we need body for appending objects
		setTimeout("CJS.downloadScriptObject('" + url + "')", 50);
		return;
	}

	var obj = document.createElement('object');
	obj.data = url;
	obj.width  = 0;
	obj.height = 0;
	obj.onload = function() { CJS.onloadCallback(url); };
	obj.onerror = function() { CJS.onloadCallback(url); };
	//CJS.dprint("downloadScriptObject: appending " + url);
	document.body.appendChild(obj);
};

CJS.onloadCallback = function(url) {
	//CJS.dprint("onloadCallback: " + url);
	CJS.hLoaded[url] = true;
};

CJS.execCallback = function(url) {
	CJS.dprint("execCallback: " + url);

	if ( url == CJS.aExecs[0][0] ) {
		CJS.aExecs.splice(0, 1);  // remove leading URL
	}
	else {
		CJS.dprint("ERROR: We finished executing a script that wasn't on the queue: " + url);
	}

	if ( CJS.aExecs.length ) {
		CJS.execScript(CJS.aExecs[0][0], CJS.aExecs[0][1]);
	}
};

//
// EXECUTION PHASE
//

CJS.processScripts = function() {
	CJS.processNextScript();
};

CJS.processNextScript = function() {
	//CJS.dprint("processNextScript: enter");
	if ( CJS.aScripts.length ) {
		var script = CJS.aScripts[0];
		CJS.curScript = script;  // for docwrite

		var src = CJS.getAttribute(script, "cjssrc");
		var cjsexec = CJS.getAttribute(script, "cjsexec");
		if ( src ) {
			// External Script
			if ( "false" === cjsexec ) {
				CJS.aScripts.splice(0, 1);   // remove leading script
				setTimeout(CJS.processNextScript, 0);
			}
			else if ( CJS.hLoaded[src] ) {
				// Done downloading.
				CJS.processExternalScript(script, CJS.processNextScript);
				CJS.aScripts.splice(0, 1);   // remove leading script
				// Race condition! Need to call processNextScript from the onload handler
				// of the script added down inside processExternalScript. (Notice the
				// callback added above when calling processExternalScript.)
				//setTimeout(CJS.processNextScript, 0);
			}
			else {
				// Still downloading.
				CJS.dprint("processNextScript: waiting for script " + src);
				if ( "undefined" === typeof(script.startwait) ) {
					script.startwait = Number(new Date());  // start time
				}
				var delta = Number(new Date()) - script.startwait;
				if ( delta < CJS.maxWait ) {
					// try again
					setTimeout(CJS.processNextScript, CJS.waitival);
				}
				else {
					// bail
					alert("There was an error loading script: " + src);
				}
			}
		}
		else {
			// Inline Script
			CJS.processInlineScript(script);
			CJS.aScripts.splice(0, 1);   // remove leading script
			setTimeout(CJS.processNextScript, 0);
		}

		return;
	}

	// Do a 2nd pass looking for CJS scripts.
	// Because control.js loads async, it's possible for findScripts to be
	// be called before all SCRIPT tags have been created.
	CJS.findScripts();
	if ( CJS.aScripts.length ) {
		CJS.downloadScripts();
		setTimeout(CJS.processNextScript, 0);
		return;
	}

	// restore the original document.write function definition
	document.write = CJS.docwriteOrig;

	CJS.dprint("DONE processing scripts");

	/*
	TODO - We can try something like this to re-fire the window load event.
	var eventObj = document.createEvent("HTMLEvents");
	eventObj.initEvent("load", true, true);
	window.dispatchEvent(eventObj);
    */
};

// Eval the code in an inlined script.
CJS.processInlineScript = function(script) {
	//CJS.dprint("processInlineScript: enter");
	CJS.curScript = script;  // for docwrite

	var code = script.text;
	CJS.dprint("processInlineScript: processing script code: " + code.substring(0, 64));
	CJS.eval(code);
};

// If downloaded then add the external script as a real script DOM element.
CJS.processExternalScript = function(script, callback) {
	//CJS.dprint("processExternalScript: enter");

	var src = CJS.getAttribute(script, "cjssrc");
	CJS.dprint("processExternalScript: processing script " + src);
	CJS.execScript(src, callback);
};

// Insert a script DOM element.
// Presumably the src has already been downloaded and is in the cache.
CJS.execScript = function(src, onload) {
	CJS.dprint("execScript: " + src);

	if ( 0 === CJS.aExecs.length ) {
		// Add this to the queue and continue on to execute it.
		CJS.aExecs[CJS.aExecs.length] = [src, onload];
	}
	else if ( src != CJS.aExecs[0][0] ) {
		// If there's an execution queue and this SRC isn't first, try later.
		CJS.dprint("execScript: queueing for later: " + src);
		CJS.aExecs[CJS.aExecs.length] = [src, onload];
		return;
	}

	var se = document.createElement('script');
	se.src = src;

	// handle onload code
	// TODO - support this from processExternalScript
	var func = function() { CJS.execCallback(src); };
	if ( "function" === typeof(onload) ) {
		func = function() { CJS.execCallback(src); onload(); };
	}
	else if ( "string" === typeof(onload) ) {
		func = function() { CJS.execCallback(src); CJS.eval(onload); };
	}
	se.onload = func;
	se.onreadystatechange = func;

	var s1 = document.getElementsByTagName('script')[0];
	s1.parentNode.insertBefore(se, s1);
};

// Eval a string of JavaScript in the proper context.
CJS.eval = function(code) {
	//CJS.dprint("evaling: " + code.substring(0, 64));

	if (window.execScript) {
		window.execScript(code);
	}
	else {
		var fn = function() {
			window.eval.call(window, code);
		};
		fn();
	}

	//CJS.dprint("eval exit");
};

//
// UTILITY FUNCTIONS
//

CJS.init = function() {
	CJS.bInited = true;  // don't init twice

	// If defer is true then scripts aren't loaded until the onload event.
	CJS.defer = ( "undefined" === typeof(CJS.defer) ? true : CJS.defer );

	CJS.aScripts = [];  // array of CJS script DOM elements
	CJS.hLoaded = {};   // hash of script URLs that have loaded
	CJS.aExecs = [];    // array of script URLs to execute

	CJS.bIE = ( -1 != navigator.userAgent.indexOf('MSIE') );
	CJS.bChrome = ( -1 != navigator.userAgent.indexOf('Chrome/') );
	CJS.bOpera = ( -1 != navigator.userAgent.indexOf('Opera') );

	CJS.curScript = null; // for document.write

	CJS.maxWait = 5000;  // maximum number of milliseconds to wait for a script to download
	CJS.waitival = 200;  // number of milliseconds to wait between retries of looking for external script download

	CJS.docwriteOrig = document.write;  // keep a reference to the original function
	document.write = CJS.docwrite;      // override document.write
};

// Return the URL of the script that has been converted to CJS.
CJS.getAttribute = function(elem, name) {
	var attrs = elem.attributes;
	var len = attrs.length;
	for ( var i = 0; i < len; i++ ) {
		var attr = attrs[i];
		if ( name === attr.nodeName ) {
			return attr.nodeValue;
		}
	}

	return undefined;
};

// Wrapper for addEventListener and attachEvent.
CJS.addHandler = function(elem, sType, fn, capture) {
	capture = (capture) ? true : false;
	if (elem.addEventListener) {
		elem.addEventListener(sType, fn, capture);
	}
	else if (elem.attachEvent) {
		elem.attachEvent("on" + sType, fn);
	}
	else {
		// Netscape 4
		if ( elem["on" + sType] ) {
			// Do nothing - we don't want to overwrite an existing handler.
		}
		else {
			elem["on" + sType] = fn;
		}
	}
};

// Dynamically define dprint debug logging function.
if ( "undefined" != typeof(console) && "undefined" != typeof(console.log) ) {
	CJS.dprint = function(msg) {
		console.log("CJS " + Number(new Date()) + ": " + msg);
	};
}
else {
	CJS.dprint = function(msg) { };
};

//
// Override document.write
//

// Attempt to handle document.write. Doesn't work well if the
// document.write occurs in the HEAD or if it outputs a SCRIPT tag.
CJS.docwrite = function(text) {
	if ( CJS.curScript ) {
		if ( ! CJS.curScript.docwriteTarget ) {
			CJS.curScript.docwriteTarget = document.createElement('span');
			CJS.curScript.parentNode.insertBefore(CJS.curScript.docwriteTarget, CJS.curScript);
		}

		var i1 = text.indexOf("<script");
		if ( -1 === i1 ) {
			// no scripts
			CJS.dprint("docwrite: " + text.substring(0, 64));
			CJS.curScript.docwriteTarget.innerHTML += text;
		}
		else {
			// script tag
			var i2 = text.indexOf("<\/script>", i1) + 9;
			if ( -1 != i2 ) {
				var textBefore = text.substring(0, i1);
				var textScript = text.substring(i1, i2);
				var textAfter = text.substring(i2+1);

				if ( textBefore ) {
					CJS.dprint("docwrite: " + textBefore.substring(0, 64));
					CJS.curScript.docwriteTarget.innerHTML += textBefore + textAfter;
				}

				CJS.docwriteScript(textScript);
			}
		}
	}
	else {
		CJS.dprint("ERROR: There's a problem with the async override of document.write.");
	}
};

// Insert a SCRIPT element found during document.write.
CJS.docwriteScript = function(textScript) {
	// extract SRC from script docwrite and insert dynamically
	var aMatches = textScript.match(/src='([^']*)/i) ||
                   textScript.match(/src="([^"]*)/i) ||
                   textScript.match(/src=([^ >]*)/i);

	if ( aMatches ) {
		var url = aMatches[1];
		CJS.dprint("docwriteScript url = " + url);
		var se = document.createElement('script');
		se.src = url;
		document.body.appendChild(se);
	}
    else {
	    // TODO - handle inline SCRIPT code
	}
};

CJS.start();
<|endoftext|>


<commit_before>var listing = require('./lib/listing.js'),
    mapping = require('./lib/mapping.js');

/*----------------------------------------------------------------------------*/

/**
 * Converts `func` of `name` to an auto-curried iteratee-first version. If `name`
 * is an object the methods on it will be converted and the object returned.
 *
 * @param {string} name The name of the function to wrap.
 * @param {Function} func The function to wrap.
 * @returns {Function|Object} Returns the new converted function or object of
 *  converted functions.
 */
function convert(name, func) {
  if (!func) {
    func = name;
    name = null;
  }
  if (func == null) {
    throw new TypeError;
  }
  var isLib = typeof func.VERSION == 'string';

  var _ = isLib ? func : {
    'ary': require('lodash-compat/function/ary'),
    'callback': require('lodash-compat/utility/callback'),
    'curry': require('lodash-compat/function/curry'),
    'each': require('lodash-compat/internal/arrayEach'),
    'rearg': require('lodash-compat/function/rearg')
  };

  var ary = _.ary,
      curry = _.curry,
      each = _.each,
      rearg = _.rearg;

  var wrappers = {
    'callback': function(callback) {
      return function(func, thisArg, argCount) {
        argCount = argCount > 2 ? (argCount - 2) : 1;
        return ary(callback(func, thisArg), argCount);
      };
    },
    'runInContext': function(runInContext) {
      return function(context) {
        return convert(runInContext(context));
      };
    }
  };

  var wrap = function(name, func) {
    var wrapper = wrappers[name];
    if (wrapper) {
      return wrapper(func);
    }
    var result;
    each(listing.caps, function(cap) {
      each(mapping.aryMethodMap[cap], function(otherName) {
        if (name == otherName) {
          result = ary(func, cap);
          if (cap > 1 && !mapping.skipReargMap[name]) {
            result = rearg(result, mapping.aryReargMap[cap]);
          }
          return !(result = curry(result, cap));
        }
      });
      return !result;
    });
    return result || func;
  };

  if (!isLib) {
    return wrap(name, func);
  }
  // Disable custom `_.indexOf` use by these methods.
  _.mixin({
    'difference': require('lodash-compat/array/difference'),
    'includes': require('lodash-compat/collection/includes'),
    'intersection': require('lodash-compat/array/intersection'),
    'omit': require('lodash-compat/object/omit'),
    'pull': require('lodash-compat/array/pull'),
    'union': require('lodash-compat/array/union'),
    'uniq': require('lodash-compat/array/uniq'),
    'without': require('lodash-compat/array/without'),
    'xor': require('lodash-compat/array/xor')
  });

  var pairs = [];
  each(listing.caps, function(cap) {
    // Iterate over methods for the current ary cap.
    each(mapping.aryMethodMap[cap], function(name) {
      var func = _[mapping.keyMap[name] || name];
      if (func) {
        // Wrap the lodash method and its aliases.
        var wrapped = wrap(name, func);
        pairs.push([name, wrapped]);
        each(mapping.aliasMap[name], function(alias) { pairs.push([alias, wrapped]); });
      }
    });
  });

  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  _.callback = wrappers.callback(_.callback);
  _.iteratee = _.callback;
  _.runInContext = wrappers.runInContext(_.runInContext);

  each(pairs, function(pair) { _[pair[0]] = pair[1]; });
  return _;
}

module.exports = convert;
<commit_msg>Add `baseAry` to reduce the overhead of the `callback` wrapper.<commit_after>var listing = require('./lib/listing.js'),
    mapping = require('./lib/mapping.js');

/*----------------------------------------------------------------------------*/

/**
 * Converts `func` of `name` to an auto-curried iteratee-first version. If `name`
 * is an object the methods on it will be converted and the object returned.
 *
 * @param {string} name The name of the function to wrap.
 * @param {Function} func The function to wrap.
 * @returns {Function|Object} Returns the new converted function or object of
 *  converted functions.
 */
function convert(name, func) {
  if (!func) {
    func = name;
    name = null;
  }
  if (func == null) {
    throw new TypeError;
  }
  var isLib = typeof func.VERSION == 'string';

  var _ = isLib ? func : {
    'ary': require('lodash-compat/function/ary'),
    'callback': require('lodash-compat/utility/callback'),
    'curry': require('lodash-compat/function/curry'),
    'each': require('lodash-compat/internal/arrayEach'),
    'rearg': require('lodash-compat/function/rearg')
  };

  var ary = _.ary,
      curry = _.curry,
      each = _.each,
      rearg = _.rearg;

  var baseAry = function(func, n) {
    return function() {
      var args = arguments,
          length = Math.min(args.length, n);

      switch (length) {
        case 0: return func();
        case 1: return func(args[0]);
        case 2: return func(args[0], args[1]);
      }
      args = Array(length);
      while (length--) {
        args[length] = arguments[length];
      }
      return func.apply(undefined, args);
    };
  };

  var wrappers = {
    'callback': function(callback) {
      return function(func, thisArg, argCount) {
        argCount = argCount > 2 ? (argCount - 2) : 1;
        return baseAry(callback(func, thisArg), argCount);
      };
    },
    'runInContext': function(runInContext) {
      return function(context) {
        return convert(runInContext(context));
      };
    }
  };

  var wrap = function(name, func) {
    var wrapper = wrappers[name];
    if (wrapper) {
      return wrapper(func);
    }
    var result;
    each(listing.caps, function(cap) {
      each(mapping.aryMethodMap[cap], function(otherName) {
        if (name == otherName) {
          result = ary(func, cap);
          if (cap > 1 && !mapping.skipReargMap[name]) {
            result = rearg(result, mapping.aryReargMap[cap]);
          }
          return !(result = curry(result, cap));
        }
      });
      return !result;
    });
    return result || func;
  };

  if (!isLib) {
    return wrap(name, func);
  }
  // Disable custom `_.indexOf` use by these methods.
  _.mixin({
    'difference': require('lodash-compat/array/difference'),
    'includes': require('lodash-compat/collection/includes'),
    'intersection': require('lodash-compat/array/intersection'),
    'omit': require('lodash-compat/object/omit'),
    'pull': require('lodash-compat/array/pull'),
    'union': require('lodash-compat/array/union'),
    'uniq': require('lodash-compat/array/uniq'),
    'without': require('lodash-compat/array/without'),
    'xor': require('lodash-compat/array/xor')
  });

  var pairs = [];
  each(listing.caps, function(cap) {
    // Iterate over methods for the current ary cap.
    each(mapping.aryMethodMap[cap], function(name) {
      var func = _[mapping.keyMap[name] || name];
      if (func) {
        // Wrap the lodash method and its aliases.
        var wrapped = wrap(name, func);
        pairs.push([name, wrapped]);
        each(mapping.aliasMap[name], function(alias) { pairs.push([alias, wrapped]); });
      }
    });
  });

  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  _.callback = wrappers.callback(_.callback);
  _.iteratee = _.callback;
  _.runInContext = wrappers.runInContext(_.runInContext);

  each(pairs, function(pair) { _[pair[0]] = pair[1]; });
  return _;
}

module.exports = convert;
<|endoftext|>