<commit_before>(function() //-----
	{
		"use strict";

		$(document)
			.ready(function()
			{ //--------------------------
				$('#streamDIV')
					.html('
MarkdownStream

Not Connected
');

				//==============
				console.log('client.js started');

				var httpPort = (window.location.host)
					.split(':')[1] * 1;

				var wsPort = httpPort + 1;

				console.log(httpPort);
				console.log(wsPort);

				var stream = function()
				{
					var url = 'ws://localhost:' + wsPort;
					var ws;

					if (typeof(window) === 'undefined')
					{
						console.log('running on node');
						var WebSocketNode = require('ws');
						ws = new WebSocketNode(url);
					}
					else
					{
						console.log('running on browser');
						ws = new WebSocket(url); // native WebSocket on browser
					}

					var WebSocketStream = require('stream-websocket');

					var c = new WebSocketStream(ws);

					var rpc = require('rpc-streamx');
					var d = rpc();

					c
						.pipe(d)
						.pipe(c)
						.on('close', function()
						{
							console.log('c close');
							console.log('Connection lost and Reconnecting...');
							$('#streamDIV')
								.html('
MarkdownStream

Connection lost and Reconnecting...
');

							setTimeout(function()
							{
								console.log('reconnecting');
								stream();
							}, 1000);
						})
						.on('error', function()
						{
							console.log('c error');
						})
						.on('finish', function()
						{
							console.log('c finish');
						});

					//---
					var marked = require('marked');
					var newlinesAsIsMode;

					//---
					d
						.rpc('connect',
							true,
							function(data)
							{
								if (data === 'connected')
								{
									console.log('Connected!');
									$('#streamDIV')
										.html('
MarkdownStream

Markdown Live Streaming View for ATOM

Connected!

Open

.md
.markdown
.mdown
.mkdn
.mkd
.mdwn
.mdtxt
.mdtext
.text
.txt
');

								}
							});
					d
						.rpc('settings',
							true,
							function(data)
							{
								console.log('Settings changed');

								marked.setOptions(data.marked);
								marked.setOptions(
								{
									highlight: function(code)
									{
										return require('highlight.js')
											.highlightAuto(code)
											.value;
									}
								});
								newlinesAsIsMode = data.newlinesAsIsMode;

							});

					d
						.rpc('bind',
							true,
							function(data)
							{
								//---
								var html;
								if (newlinesAsIsMode)
								{
									html = '' +
										marked(hack(data));
								}
								else
								{
									html = marked(data);
								}

								//---
								$('#streamDIV')
									.html(html);
							});

				};
				stream();
				//===============
				//-------------------------
			});
		String.prototype.replaceAll = function(org, dest)
		{
			return this.split(org)
				.join(dest);
		};
		var hack = function(data0)
		{
			var data6 = data0.replace(/`\b(.*?)\b`(?!`)/g, '**$1**');
			var data7 = data6.replace(/(- [\s\S]+?)(?:\n\n)/g, '$1\n \n');
			var data8 = data7.replace(/(- [\s\S]+?)(?:\n \n\n)/g, '$1\n\n\n\n\n');
			var data9 = data8.replace(/\n \n(?=[^-])/g, '\n\n\n'); //ok
			var data = data9; //.replace(/\n\n(?=- )/g, '\n\n');

			var rxCodeG = /[\s\S]+?<\/code>|
[\s\S]+?<\/pre>|\n```+[\s\S]+?```+|\n- [\s\S]+?\n\n/g;
			var rxCode = /[\s\S]+?<\/code>|
[\s\S]+?<\/pre>|\n```+[\s\S]+?```+|\n- [\s\S]+?\n\n/;

			var codes = data.match(rxCodeG);
			var codeKey = 'thisistheCodeKey';
			var data1 = [];
			var data1L;
			if (codes)
			{
				codes.map(
					function() //ideally use return
					{
						var len = data1.length;
						var src;
						if (len === 0)
						{
							src = data;
						}
						else
						{
							src = data1[len - 1];
						}
						data1[len] = src.replace(rxCode, codeKey + len);
					});
				data1L = data1[data1.length - 1];
			}
			else
			{
				data1L = data;
			}

			var escape1 = 'thisisdummy3141592escape1';
			var escape2 = 'thisisdummy3141592escape2';
			var toReplace = ' ' + '\n\n';

			var data2 = data1L
				.replace(/(^|[^\n])\n(?!\n)/g, '$1' + escape1)
				.replace(/(^|[^\n])\n{2}/g, '$1' + escape2)
				.replace(/\n/g, toReplace)
				.replaceAll(escape1, '\n')
				.replaceAll(escape2, '\n\n' + toReplace);

			var data3 = [];
			var data3L;
			if (codes)
			{
				codes.map(
					function()
					{
						var len = data3.length;
						var src;
						if (len === 0)
						{
							src = data2;
						}
						else
						{
							src = data3[len - 1];
						}
						data3[len] = src.replace(codeKey + len, codes[len]);
					});
				data3L = data3[data3.length - 1];
			}
			else
			{
				data3L = data2;
			}

			return data3L;
		};

	}());<commit_msg>commit<commit_after>(function() //-----
	{
		"use strict";

		$(document)
			.ready(function()
			{ //--------------------------
				$('#streamDIV')
					.html('
MarkdownStream

Not Connected
');

				//==============
				console.log('client.js started');

				var httpPort = (window.location.host)
					.split(':')[1] * 1;

				var wsPort = httpPort + 1;

				console.log(httpPort);
				console.log(wsPort);

				var stream = function()
				{
					var url = 'ws://localhost:' + wsPort;
					var ws;

					if (typeof(window) === 'undefined')
					{
						console.log('running on node');
						var WebSocketNode = require('ws');
						ws = new WebSocketNode(url);
					}
					else
					{
						console.log('running on browser');
						ws = new WebSocket(url); // native WebSocket on browser
					}

					var WebSocketStream = require('stream-websocket');

					var c = new WebSocketStream(ws);

					var rpc = require('rpc-streamx');
					var d = rpc();

					c
						.pipe(d)
						.pipe(c)
						.on('close', function()
						{
							console.log('c close');
							console.log('Connection lost and Reconnecting...');
							$('#streamDIV')
								.html('
MarkdownStream

Connection lost and Reconnecting...
');

							setTimeout(function()
							{
								console.log('reconnecting');
								stream();
							}, 1000);
						})
						.on('error', function()
						{
							console.log('c error');
						})
						.on('finish', function()
						{
							console.log('c finish');
						});

					//---
					var marked = require('marked');
					var newlinesAsIsMode;

					//---
					d
						.rpc('connect',
							true,
							function(data)
							{
								if (data === 'connected')
								{
									console.log('Connected!');
									$('#streamDIV')
										.html('
MarkdownStream

Markdown Live Streaming View for ATOM

Connected!

Open

.md
.markdown
.mdown
.mkdn
.mkd
.mdwn
.mdtxt
.mdtext
.text
.txt
');

								}
							});
					d
						.rpc('settings',
							true,
							function(data)
							{
								console.log('Settings changed');

								marked.setOptions(data.marked);
								marked.setOptions(
								{
									highlight: function(code)
									{
										return require('highlight.js')
											.highlightAuto(code)
											.value;
									}
								});
								newlinesAsIsMode = data.newlinesAsIsMode;

							});

					d
						.rpc('bind',
							true,
							function(data)
							{
								var html;
								try
								{
									if (newlinesAsIsMode)
									{
										console.log(data);
										html = '' +
											marked(hack(data));
									}
									else
									{
										html = marked(data);
									}
								}
								catch (e)
								{
									html = "";
								}

								//---
								$('#streamDIV')
									.html(html);
							});

				};
				stream();
				//===============
				//-------------------------
			});
		String.prototype.replaceAll = function(org, dest)
		{
			return this.split(org)
				.join(dest);
		};
		var hack = function(data0)
		{
			var data6 = data0.replace(/`\b(.*?)\b`(?!`)/g, '**$1**');
			var data7 = data6.replace(/(- [\s\S]+?)(?:\n\n)/g, '$1\n \n');
			var data8 = data7.replace(/(- [\s\S]+?)(?:\n \n\n)/g, '$1\n\n\n\n\n');
			var data9 = data8.replace(/\n \n(?=[^-])/g, '\n\n\n'); //ok
			var data = data9; //.replace(/\n\n(?=- )/g, '\n\n');

			var rxCodeG = /[\s\S]+?<\/code>|
[\s\S]+?<\/pre>|\n```+[\s\S]+?```+|\n- [\s\S]+?\n\n/g;
			var rxCode = /[\s\S]+?<\/code>|
[\s\S]+?<\/pre>|\n```+[\s\S]+?```+|\n- [\s\S]+?\n\n/;

			var codes = data.match(rxCodeG);
			var codeKey = 'thisistheCodeKey';
			var data1 = [];
			var data1L;
			if (codes)
			{
				codes.map(
					function() //ideally use return
					{
						var len = data1.length;
						var src;
						if (len === 0)
						{
							src = data;
						}
						else
						{
							src = data1[len - 1];
						}
						data1[len] = src.replace(rxCode, codeKey + len);
					});
				data1L = data1[data1.length - 1];
			}
			else
			{
				data1L = data;
			}

			var escape1 = 'thisisdummy3141592escape1';
			var escape2 = 'thisisdummy3141592escape2';
			var toReplace = ' ' + '\n\n';

			var data2 = data1L
				.replace(/(^|[^\n])\n(?!\n)/g, '$1' + escape1)
				.replace(/(^|[^\n])\n{2}/g, '$1' + escape2)
				.replace(/\n/g, toReplace)
				.replaceAll(escape1, '\n')
				.replaceAll(escape2, '\n\n' + toReplace);

			var data3 = [];
			var data3L;
			if (codes)
			{
				codes.map(
					function()
					{
						var len = data3.length;
						var src;
						if (len === 0)
						{
							src = data2;
						}
						else
						{
							src = data3[len - 1];
						}
						data3[len] = src.replace(codeKey + len, codes[len]);
					});
				data3L = data3[data3.length - 1];
			}
			else
			{
				data3L = data2;
			}

			return data3L;
		};

	}());<|endoftext|>


<commit_before>require.paths.unshift(__dirname + '/lib/node');

var express = require('express'),
    fs = require('fs'),
    path = require('path'),
    rmrf = require('./rm-rf'),
    _ = require('underscore')._;

var settings = require('./settings');
var app = module.exports = express.createServer();

app.use(express.bodyDecoder());
app.use(express.staticProvider('client'));
app.set('jsonp callback', true);

app.get('/api', function(req, res, params) {
  res.send({
    api: 'basic',
    version: 1.0
  });
});

app.get('/api/list', function(req, res) {
  path.exists(settings.files,
    function(exists) {
      if (exists) {
        path.exists(path.join(settings.files, req.param('filename')),
          function(exists) {
            if (!exists) fs.mkdirSync(path.join(settings.files, req.param('filename')), 0777);
            res.send({
              status: true,
              data: _.select(fs.readdirSync(
                path.join(
                  settings.files,
                  req.param('filename'))),
                function(dir) {
                  // directories that contain at least one MML file
                  return _.any(
                    fs.readdirSync(path.join(
                      settings.files,
                      req.param('filename'),
                      dir)),
                    function(filename) {
                      return filename.match('.mml');
                    }
                  );
                }
              )
            });
          });
      } else {
        res.send({
          status: false,
          data: 'The directory where TileMill keeps files is not present. ' +
            'Please create the directory ' + settings.files
        });
      }
  });
});

app.get('/api/file', function(req, res) {
  fs.readFile(path.join(settings.files, req.param('filename')), function(err, data) {
    if (!err) {
      if (req.param('callback')) {
        res.send(Object('' + data));
      } else {
        // send non-json version if callback not given.
        res.send('' + data);
      }
    }
    else {
      res.send({
        status: false,
        data: 'The file (' + req.param('filename') +
          ') could not be found. Exception: ' + err
      });
    }
  });
});

app.post('/api/file', function(req, res) {
  if ((req.param('method') || 'put') == 'put') {
      console.log('here');
    if ((req.body.filename.split('/').length < 4) &&
        /^[a-z0-9\.\/\-_]+$/i.test(req.body.filename)) {
        console.log('true');
      if (path.dirname(req.body.filename)) {
        fs.mkdir(
          path.join(
            settings.files,
            path.dirname(path.join(req.body.filename))),
          0777,
        function() {
          fs.writeFile(
              path.join(settings.files, req.body.filename),
              req.body.data,
              function() {
            res.send({
              status: true
            });
          });
        });
      } else {
          console.log('false');
      }
    } else {
      res.send({status: false});
    }
  } else {
    // TODO: nodejs doesn't provide rm-rf functionality
    rmrf(path.join(settings.files, req.body.filename), function() {
        res.send({
            status: true
        });
    });
  }
});

// TODO: use watchfile
app.get('/api/mtime', function(req, res) {
  var filename = req.param('filename');
  path.exists(path.join(settings.files, req.param('filename')),
    function (exists) {
      if (!exists) {
        res.send({
          status: false,
          data: 'The file (' +
            path.join(settings.files, req.param('filename')) +
            ') could not be found.'
        });
      } else {
        fs.stat(path.join(
            settings.files,
            req.param('filename')), function(err, stats) {
          res.send({
            mtime: '' + stats.mtime,
            filename: req.param('filename')
          });
        });
      }
    });
});

require('./providers/providers')(app, settings);
require('./tilehandler')(app, settings);
require('./inspect')(app, settings);
require('./bootstrap')(app, settings);

app.listen(settings.port);
<commit_msg>Proper order of route rules and add comments.<commit_after>require.paths.unshift(__dirname + '/lib/node');

var express = require('express'),
    fs = require('fs'),
    path = require('path'),
    rmrf = require('./rm-rf'),
    _ = require('underscore')._;

var settings = require('./settings');
var app = module.exports = express.createServer();

app.use(express.bodyDecoder());
app.use(express.staticProvider('client'));
app.set('jsonp callback', true);

app.get('/api', function(req, res, params) {
  res.send({
    api: 'basic',
    version: 1.0
  });
});

app.get('/api/list', function(req, res) {
  path.exists(settings.files,
    function(exists) {
      if (exists) {
        path.exists(path.join(settings.files, req.param('filename')),
          function(exists) {
            if (!exists) fs.mkdirSync(path.join(settings.files, req.param('filename')), 0777);
            res.send({
              status: true,
              data: _.select(fs.readdirSync(
                path.join(
                  settings.files,
                  req.param('filename'))),
                function(dir) {
                  // directories that contain at least one MML file
                  return _.any(
                    fs.readdirSync(path.join(
                      settings.files,
                      req.param('filename'),
                      dir)),
                    function(filename) {
                      return filename.match('.mml');
                    }
                  );
                }
              )
            });
          });
      } else {
        res.send({
          status: false,
          data: 'The directory where TileMill keeps files is not present. ' +
            'Please create the directory ' + settings.files
        });
      }
  });
});

app.get('/api/file', function(req, res) {
  fs.readFile(path.join(settings.files, req.param('filename')), function(err, data) {
    if (!err) {
      if (req.param('callback')) {
        res.send(Object('' + data));
      } else {
        // send non-json version if callback not given.
        res.send('' + data);
      }
    }
    else {
      res.send({
        status: false,
        data: 'The file (' + req.param('filename') +
          ') could not be found. Exception: ' + err
      });
    }
  });
});

app.post('/api/file', function(req, res) {
  if ((req.param('method') || 'put') == 'put') {
      console.log('here');
    if ((req.body.filename.split('/').length < 4) &&
        /^[a-z0-9\.\/\-_]+$/i.test(req.body.filename)) {
        console.log('true');
      if (path.dirname(req.body.filename)) {
        fs.mkdir(
          path.join(
            settings.files,
            path.dirname(path.join(req.body.filename))),
          0777,
        function() {
          fs.writeFile(
              path.join(settings.files, req.body.filename),
              req.body.data,
              function() {
            res.send({
              status: true
            });
          });
        });
      } else {
          console.log('false');
      }
    } else {
      res.send({status: false});
    }
  } else {
    // TODO: nodejs doesn't provide rm-rf functionality
    rmrf(path.join(settings.files, req.body.filename), function() {
        res.send({
            status: true
        });
    });
  }
});

// TODO: use watchfile
app.get('/api/mtime', function(req, res) {
  var filename = req.param('filename');
  path.exists(path.join(settings.files, req.param('filename')),
    function (exists) {
      if (!exists) {
        res.send({
          status: false,
          data: 'The file (' +
            path.join(settings.files, req.param('filename')) +
            ') could not be found.'
        });
      } else {
        fs.stat(path.join(
            settings.files,
            req.param('filename')), function(err, stats) {
          res.send({
            mtime: '' + stats.mtime,
            filename: req.param('filename')
          });
        });
      }
    });
});

require('./providers/providers')(app, settings);
require('./inspect')(app, settings);

// Note that tilehandler must come last as its route rule acts as a "catchall"
// @TODO: Either prefix the tile endpoint or come up with some other method of
// allowing better route handling.
require('./tilehandler')(app, settings);

// "Bootstrap" (aka install) the application.
require('./bootstrap')(app, settings);

app.listen(settings.port);
<|endoftext|>


<commit_before>var http       = require('http'),
    colors   = require('colors'),
    zookeeper  = require('node-zookeeper-client'),
    constants  = require('./node-manager/constants');

exports.sessionServer = function (addr, done) {

  process.stdout.write('\n ### Session Servers \n');

  var address = addr || 'localhost:2181';

  var zkClient = zookeeper.createClient(address);

  zkClient.connect();

  zkClient.getChildren(
    constants.BASE_ZNODE_PATH + constants.META_PATH + constants.GW_SERVER_PATH,
    function (error, nodes, stats) {

      if (error) {
        console.log(error.stack);
        return;
      }

      var servers = [];

      for (var i = 0; i < nodes.length; i++ ){

        var _host = nodes[i].substr(0, nodes[i].indexOf(':'));
        var _port = Number(nodes[i].substr(nodes[i].indexOf(':')+1));

        servers.push({
          host: _host,
          port: _port
        });

      }

      var totalCnt = servers.length;
      var checkUrls = function () {
        var server = servers.shift();

        process.stdout.write('   ['+(totalCnt-servers.length)+'/'+totalCnt+'] '+server.host+':'+server.port+' - ');

        http.get({ host: server.host, port: server.port, path: '/status/ping' }, function(res) {
          var body = '';
          res.on('data', function (d) { body += d; });
          res.on('end', function () {

            bodyObj = JSON.parse(body);

            process.stdout.write(' '+bodyObj.status.bold.green+' \n');
            if( servers.length ) {
              checkUrls();
            }else {
              if(done) done();
            }
          });
        }).on('error', function(e) {
          process.stdout.write(' '+e.message.bold.red+' \n');
          if( servers.length ) {
            checkUrls();
          }else {
            if(done) done();
          }
        });
      };

      if(totalCnt > 0) {
        checkUrls();
      }else{
        process.stdout.write(' is not existed.'.red+' \n');
        if(done) done();
      }

      zkClient.close();
    }
  );

};

exports.channelServer = function (addr, done) {

  process.stdout.write('\n ### Channel Servers \n');

  var address = addr || 'localhost:2181';

  var zkClient = zookeeper.createClient(address);

  zkClient.connect();

  zkClient.getChildren(
    constants.BASE_ZNODE_PATH + constants.SERVERS_PATH,
    function (error, nodes, stats) {

      if (error) {
        console.log(error.stack);
        return;
      }

      var servers = [];

      for (var i = 0; i < nodes.length; i++ ){

        var addrAndPort = nodes[i].substr(nodes[i].indexOf('^')+1);
        var _host = addrAndPort.substr(0, addrAndPort.indexOf(':'));
        var _port = Number(addrAndPort.substr(addrAndPort.indexOf(':')+1));
        var _snum = Number(nodes[i].substr(0, nodes[i].indexOf('^')));

        servers.push({
          snum: _snum,
          host: _host,
          port: _port
        });

      }

      var totalCnt = servers.length;
      var checkUrls = function () {
        var server = servers.shift();

        process.stdout.write('   ['+(totalCnt-servers.length)+'/'+totalCnt+'] ('+server.snum+') '+server.host+':'+server.port+' - ');

        http.get({ host: server.host, port: server.port, path: '/status/ping' }, function(res) {
          var body = '';
          res.on('data', function (d) { body += d; });
          res.on('end', function () {

            bodyObj = JSON.parse(body);

            process.stdout.write(' '+bodyObj.status.bold.green+' \n');
            if( servers.length ) {
              checkUrls();
            }else {
              if(done) done();
            }
          });
        }).on('error', function(e) {
          process.stdout.write(' '+e.message.bold.red+' \n');
          if( servers.length ) {
            checkUrls();
          }else {
            if(done) done();
          }
        });
      };

      if(totalCnt > 0) {
        checkUrls();
      }else{
        process.stdout.write(' is not existed.'.red+' \n');
        if(done) done();
      }

      zkClient.close();
    }
  );

};
<commit_msg>check status for servers not existed<commit_after>var http       = require('http'),
    colors   = require('colors'),
    zookeeper  = require('node-zookeeper-client'),
    constants  = require('./node-manager/constants');

exports.sessionServer = function (addr, done) {

  process.stdout.write('\n ### Session Servers \n');

  var address = addr || 'localhost:2181';

  var zkClient = zookeeper.createClient(address);

  zkClient.connect();

  zkClient.getChildren(
    constants.BASE_ZNODE_PATH + constants.META_PATH + constants.GW_SERVER_PATH,
    function (error, nodes, stats) {

      if (error) {
        console.log(error.stack);
        return;
      }

      var servers = [];

      for (var i = 0; i < nodes.length; i++ ){

        var _host = nodes[i].substr(0, nodes[i].indexOf(':'));
        var _port = Number(nodes[i].substr(nodes[i].indexOf(':')+1));

        servers.push({
          host: _host,
          port: _port
        });

      }

      var totalCnt = servers.length;
      var checkUrls = function () {
        var server = servers.shift();

        process.stdout.write('   ['+(totalCnt-servers.length)+'/'+totalCnt+'] '+server.host+':'+server.port+' - ');

        http.get({ host: server.host, port: server.port, path: '/status/ping' }, function(res) {
          var body = '';
          res.on('data', function (d) { body += d; });
          res.on('end', function () {

            bodyObj = JSON.parse(body);

            process.stdout.write(' '+bodyObj.status.bold.green+' \n');
            if( servers.length ) {
              checkUrls();
            }else {
              if(done) done();
            }
          });
        }).on('error', function(e) {
          process.stdout.write(' '+e.message.bold.red+' \n');
          if( servers.length ) {
            checkUrls();
          }else {
            if(done) done();
          }
        });
      };

      if(totalCnt > 0) {
        checkUrls();
      }else{
        process.stdout.write(' is not existed.'.red+' \n');
        if(done) done();
      }

      zkClient.close();
    }
  );

};

exports.channelServer = function (addr, done) {

  process.stdout.write('\n ### Channel Servers \n');

  var address = addr || 'localhost:2181';

  var zkClient = zookeeper.createClient(address);

  zkClient.connect();

  zkClient.getChildren(
    constants.BASE_ZNODE_PATH + constants.SERVERS_PATH,
    function (error, nodes, stats) {

      if (error) {
        console.log(error.stack);
        return;
      }

      var servers = [];

      for (var i = 0; i < nodes.length; i++ ){

        var addrAndPort = nodes[i].substr(nodes[i].indexOf('^')+1);
        var _host = addrAndPort.substr(0, addrAndPort.indexOf(':'));
        var _port = Number(addrAndPort.substr(addrAndPort.indexOf(':')+1));
        var _snum = Number(nodes[i].substr(0, nodes[i].indexOf('^')));

        servers.push({
          snum: _snum,
          host: _host,
          port: _port
        });

      }

      var totalCnt = servers.length;
      var checkUrls = function () {
        var server = servers.shift();

        process.stdout.write('   ['+(totalCnt-servers.length)+'/'+totalCnt+'] ('+server.snum+') '+server.host+':'+server.port+' - ');

        http.get({ host: server.host, port: server.port, path: '/status/ping' }, function(res) {
          var body = '';
          res.on('data', function (d) { body += d; });
          res.on('end', function () {

            bodyObj = JSON.parse(body);

            if(bodyObj && bodyObj.status){
              process.stdout.write(' '+bodyObj.status.bold.green+' \n');
            }else{
              var _msg = 'Not Existed';
              process.stdout.write(' '+_msg.bold.red+' \n');
            }
            if( servers.length ) {
              checkUrls();
            }else {
              if(done) done();
            }
          });
        }).on('error', function(e) {
          process.stdout.write(' '+e.message.bold.red+' \n');
          if( servers.length ) {
            checkUrls();
          }else {
            if(done) done();
          }
        });
      };

      if(totalCnt > 0) {
        checkUrls();
      }else{
        process.stdout.write(' is not existed.'.red+' \n');
        if(done) done();
      }

      zkClient.close();
    }
  );

};
<|endoftext|>


<commit_before>requirejs.config({
	urlArgs: 'v=40',
	paths: {
		'theme': 'livedesk-embed/themes/satakansa'
	}
});
require(['satakansa.min'], function() {
	require(['../scripts/js/config'], function(){
		var name;
		for(name in livedesk.theme) {
			define('tmpl!theme/'+name, ['dust/compiler'], function(dust){
				dust.loadSource(dust.compile(livedesk.theme[name],'theme/'+name));
			});
		}
		function loadCss(url) {
			var link = document.createElement("link");
			link.type = "text/css";
			link.rel = "stylesheet";
			link.href = url;
			document.getElementsByTagName("head")[0].appendChild(link);
		}
		loadCss(require.toUrl('theme/livedesk.css'));//'css!theme/livedesk',
		require(['livedesk-embed/main']);
	});
});
<commit_msg>Update satakansa.js<commit_after>requirejs.config({
	urlArgs: 'v=50',
	paths: {
		'theme': 'livedesk-embed/themes/satakansa'
	}
});
require(['satakansa.min'], function() {
	require(['../scripts/js/config'], function(){
		var name;
		for(name in livedesk.theme) {
			define('tmpl!theme/'+name, ['dust/compiler'], function(dust){
				dust.loadSource(dust.compile(livedesk.theme[name],'theme/'+name));
			});
		}
		function loadCss(url) {
			var link = document.createElement("link");
			link.type = "text/css";
			link.rel = "stylesheet";
			link.href = url;
			document.getElementsByTagName("head")[0].appendChild(link);
		}
		loadCss(require.toUrl('theme/livedesk.css'));//'css!theme/livedesk',
		require(['livedesk-embed/main']);
	});
});
<|endoftext|>


<commit_before>function timetrim(params) {

  // Default style params
  var margin = {top: 20, right: 20, bottom: 20, left: 100},
      width = 150,
      height = 800,
      markerRadius = 20,
      rangeWidth = 16

  // Configurable methods
  var onUpdate = function() { console.log('onUpdate not defined') },
      parseTime = function(_) {
        if (moment.isMoment(_)) return _
        else return moment(_, 'HH:mm')
      }

  // Default functional params
  var scale = d3.scale.linear(),
      lineFun = d3.svg.line().x(function(d) { return d.x }).y(function(d) { return d.y }),
      outerBounds = [ '0:00', '24:00' ].map(parseTime),
      trim = [ '5:00', '24:00' ].map(parseTime)

  function toUnix(_) {
    return _.unix()
  }

  function fromUnix(_) {
    return moment(_, 'X')
  }

  function chart(selection) {

    // This is because we could have more than one selection?
    selection.each(function(data) {

      // Update the scale
      scale
        .domain(outerBounds.map(toUnix))
        .range([0, height - margin.top - margin.bottom])

      // Select the svg element, if it exists.
      var svg = d3.select(this).selectAll('svg').data([data])

      // Otherwise, create the skeletal chart.
      var gEnter = svg.enter().append('svg').append('g')
      // 1. Clip path
      gEnter.append('defs').append('clipPath').attr('id', 'clip')
        .append('rect')
          .attr('id', 'clip-rect')
      // 2. Axis
      gEnter.append('g')
          .attr('class', 'axis')
        .append('path')
          .attr('d', lineFun([ { x:0, y:0 }, { x:0, y:scale.range()[1] } ]))
      // 3. Events
      gEnter.append('g').attr('class', 'events')
          .attr('clip-path', 'url(#clip)')
        .append('rect')
          .attr('x', -rangeWidth/2).attr('y', 0).attr('width', rangeWidth).attr('height', scale.range()[1])
      // 4. Trim markers
      gEnter.append('g').attr('class', 'trim from')
        .datum(trim[0])
        .call(createMark)
      gEnter.append('g').attr('class', 'trim to')
        .datum(trim[1])
        .call(createMark)

      // Update outer dimensions
      svg.attr('width', width)
         .attr('height', height)

      // Update inner dimensions.
      var g = svg.select('g')
        .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

      // Update events
      g.select('.events')
          .attr('transform', 'translate(' + 0 + ', 0)')
          .call(updateEvents)

      // Update trim limits
      g.select('#clip-rect')
          .call(updateClipPath)
      g.select('.from').datum(trim[0])
        .call(updateMark)
      g.select('.to').datum(trim[1])
        .call(updateMark)
    })
  }

  function dragmove(d) {
    var yPixel = d3.transform(d3.select(this).attr('transform')).translate[1] + d3.event.dy,
        newValue = 0

    function computeValue(bounds) {
      bounds = bounds.map(toUnix).map(scale)
      yPixel = Math.max(bounds[0], Math.min(yPixel, bounds[1]))
      newValue = fromUnix(scale.invert(yPixel))
      return newValue
    }

    if (d3.select(this).classed('from')) // from
      trim = [ computeValue([ outerBounds[0], trim[1] ]), trim[1] ]
    else // to
      trim = [ trim[0], computeValue([ trim[0], outerBounds[1] ]) ]

    d3.select(this)
      .datum(newValue)
      .attr('transform', 'translate(0, ' + yPixel + ')')
    d3.select(this).select('text').text(newValue.format('H:mm'))
    d3.select(this.parentNode.parentNode).select('#clip-rect')
      .attr('y', scale(toUnix(trim[0])))
      .attr('height', scale(toUnix(trim[1])) - scale(toUnix(trim[0])))
    onUpdate()
  }

  var drag = d3.behavior.drag()
    .on('drag', dragmove)
    .on('dragend', onUpdate)

  function updateMark(selection) {
    selection.each(function(data) {
      console.log('updateMark ' + data.format('H:mm'))
      var mark = d3.select(this)
        .transition().duration(750)
          .attr('transform', 'translate(0, ' + scale(toUnix(data)) + ')')
      mark.select('text')
        .text(data.format('H:mm'))
    })
  }

  function createMark(selection) {
    selection.each(function(data) {
      var mark = d3.select(this)
        .attr('transform', 'translate(0, ' + scale(toUnix(data)) + ')')
        .call(drag)
      mark.append('circle')
        .attr('cx', 0)
        .attr('r', markerRadius)
      mark.append('text')
        .attr('x', -markerRadius -10)
        .attr('y', 8) // Depends on the font size -- should be externally configurable
        .attr('text-anchor', 'end')
    })
  }

  function updateClipPath(selection) {
    selection.each(function(data) {
      d3.select(this)
        .transition().duration(750)
        .attr('x', '-20')
        .attr('y', scale(toUnix(trim[0])))
        .attr('width', 40)
        .attr('height', scale(toUnix(trim[1])) - scale(toUnix(trim[0])))
    })
  }

  function updateEvents(selection) {
    selection.each(function(data) {
      function updateTick(selection) {
        selection
          .attr('d', function(d) {
            var y = scale(toUnix(parseTime(d)))
            return lineFun([
              { x: -rangeWidth/2, y: y },
              { x: rangeWidth/2, y: y }
            ])
          })
      }
      var tick = d3.select(this).selectAll('path')
          .data(data)

      tick
        .transition().duration(750)
        .call(updateTick)

      tick.enter()
        .append('path')
        .call(updateTick)

      tick.exit()
        .remove()
    })
  }

  chart.margin = function(_) {
    if (!arguments.length) return margin
    margin = _
    return chart
  }

  chart.width = function(_) {
    if (!arguments.length) return width
    width = _
    return chart
  }

  chart.height = function(_) {
    if (!arguments.length) return height
    height = _
    return chart
  };

  chart.outerBounds = function(_) {
    if (!arguments.length) return outerBounds
    outerBounds = _.map(parseTime)
    return chart
  }

  chart.trim = function(_) {
    if (!arguments.length) return trim
    trim = _.map(parseTime)
    return chart
  }

  chart.onUpdate = function(_) {
    if (!arguments.length) return trim
    onUpdate = _
    return chart
  }

  return chart
}<commit_msg>onUpdate has to be called from annonymous function to be able to change it<commit_after>function timetrim(params) {

  // Default style params
  var margin = {top: 20, right: 20, bottom: 20, left: 100},
      width = 150,
      height = 800,
      markerRadius = 20,
      rangeWidth = 16

  // Configurable methods
  var onUpdate = function() { console.log('onUpdate not defined') },
      parseTime = function(_) {
        if (moment.isMoment(_)) return _
        else return moment(_, 'HH:mm')
      }

  // Default functional params
  var scale = d3.scale.linear(),
      lineFun = d3.svg.line().x(function(d) { return d.x }).y(function(d) { return d.y }),
      outerBounds = [ '0:00', '24:00' ].map(parseTime),
      trim = [ '5:00', '24:00' ].map(parseTime)

  function toUnix(_) {
    return _.unix()
  }

  function fromUnix(_) {
    return moment(_, 'X')
  }

  function chart(selection) {

    // This is because we could have more than one selection?
    selection.each(function(data) {

      // Update the scale
      scale
        .domain(outerBounds.map(toUnix))
        .range([0, height - margin.top - margin.bottom])

      // Select the svg element, if it exists.
      var svg = d3.select(this).selectAll('svg').data([data])

      // Otherwise, create the skeletal chart.
      var gEnter = svg.enter().append('svg').append('g')
      // 1. Clip path
      gEnter.append('defs').append('clipPath').attr('id', 'clip')
        .append('rect')
          .attr('id', 'clip-rect')
      // 2. Axis
      gEnter.append('g')
          .attr('class', 'axis')
        .append('path')
          .attr('d', lineFun([ { x:0, y:0 }, { x:0, y:scale.range()[1] } ]))
      // 3. Events
      gEnter.append('g').attr('class', 'events')
          .attr('clip-path', 'url(#clip)')
        .append('rect')
          .attr('x', -rangeWidth/2).attr('y', 0).attr('width', rangeWidth).attr('height', scale.range()[1])
      // 4. Trim markers
      gEnter.append('g').attr('class', 'trim from')
        .datum(trim[0])
        .call(createMark)
      gEnter.append('g').attr('class', 'trim to')
        .datum(trim[1])
        .call(createMark)

      // Update outer dimensions
      svg.attr('width', width)
         .attr('height', height)

      // Update inner dimensions.
      var g = svg.select('g')
        .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

      // Update events
      g.select('.events')
          .attr('transform', 'translate(' + 0 + ', 0)')
          .call(updateEvents)

      // Update trim limits
      g.select('#clip-rect')
          .call(updateClipPath)
      g.select('.from').datum(trim[0])
        .call(updateMark)
      g.select('.to').datum(trim[1])
        .call(updateMark)
    })
  }

  function dragmove(d) {
    var yPixel = d3.transform(d3.select(this).attr('transform')).translate[1] + d3.event.dy,
        newValue = 0

    function computeValue(bounds) {
      bounds = bounds.map(toUnix).map(scale)
      yPixel = Math.max(bounds[0], Math.min(yPixel, bounds[1]))
      newValue = fromUnix(scale.invert(yPixel))
      return newValue
    }

    if (d3.select(this).classed('from')) // from
      trim = [ computeValue([ outerBounds[0], trim[1] ]), trim[1] ]
    else // to
      trim = [ trim[0], computeValue([ trim[0], outerBounds[1] ]) ]

    d3.select(this)
      .datum(newValue)
      .attr('transform', 'translate(0, ' + yPixel + ')')
    d3.select(this).select('text').text(newValue.format('H:mm'))
    d3.select(this.parentNode.parentNode).select('#clip-rect')
      .attr('y', scale(toUnix(trim[0])))
      .attr('height', scale(toUnix(trim[1])) - scale(toUnix(trim[0])))
    onUpdate()
  }

  var drag = d3.behavior.drag()
    .on('drag', dragmove)
    .on('dragend', function() { onUpdate() })

  function updateMark(selection) {
    selection.each(function(data) {
      console.log('updateMark ' + data.format('H:mm'))
      var mark = d3.select(this)
        .transition().duration(750)
          .attr('transform', 'translate(0, ' + scale(toUnix(data)) + ')')
      mark.select('text')
        .text(data.format('H:mm'))
    })
  }

  function createMark(selection) {
    selection.each(function(data) {
      var mark = d3.select(this)
        .attr('transform', 'translate(0, ' + scale(toUnix(data)) + ')')
        .call(drag)
      mark.append('circle')
        .attr('cx', 0)
        .attr('r', markerRadius)
      mark.append('text')
        .attr('x', -markerRadius -10)
        .attr('y', 8) // Depends on the font size -- should be externally configurable
        .attr('text-anchor', 'end')
    })
  }

  function updateClipPath(selection) {
    selection.each(function(data) {
      d3.select(this)
        .transition().duration(750)
        .attr('x', '-20')
        .attr('y', scale(toUnix(trim[0])))
        .attr('width', 40)
        .attr('height', scale(toUnix(trim[1])) - scale(toUnix(trim[0])))
    })
  }

  function updateEvents(selection) {
    selection.each(function(data) {
      function updateTick(selection) {
        selection
          .attr('d', function(d) {
            var y = scale(toUnix(parseTime(d)))
            return lineFun([
              { x: -rangeWidth/2, y: y },
              { x: rangeWidth/2, y: y }
            ])
          })
      }
      var tick = d3.select(this).selectAll('path')
          .data(data)

      tick
        .transition().duration(750)
        .call(updateTick)

      tick.enter()
        .append('path')
        .call(updateTick)

      tick.exit()
        .remove()
    })
  }

  chart.margin = function(_) {
    if (!arguments.length) return margin
    margin = _
    return chart
  }

  chart.width = function(_) {
    if (!arguments.length) return width
    width = _
    return chart
  }

  chart.height = function(_) {
    if (!arguments.length) return height
    height = _
    return chart
  };

  chart.outerBounds = function(_) {
    if (!arguments.length) return outerBounds
    outerBounds = _.map(parseTime)
    return chart
  }

  chart.trim = function(_) {
    if (!arguments.length) return trim
    trim = _.map(parseTime)
    return chart
  }

  chart.onUpdate = function(_) {
    if (!arguments.length) return trim
    onUpdate = _
    return chart
  }

  return chart
}<|endoftext|>


<commit_before>import {log, describe, isPaletteName, createPalette, DEFAULT_PALETTE, VIDEO_WIDTH, VIDEO_HEIGHT} from '../../../core';
import {isStyleName, applyStyle, removeStyle, MAXIMIZED} from './styles';
import {isRendererName, createRenderer, WEBGL} from './renderers';
import {isFilter, NEAREST} from './filters';
import Fullscreen from './Fullscreen';

export default class Video {

  constructor(nes) {
    log.info('Initializing video');

    this.nes = nes;
    this.canvas = null; // Rendering target
    this.renderer = null; // Current renderer
    this.rendererName = WEBGL; // Name of current renderer
    this.paletteName = DEFAULT_PALETTE; // Name of current palette
    this.frame = null; // Frame to render standard output
    this.debugFrame = null; // Frame to render debug output
    this.scale = 1; // Canvas scale factor
    this.filter = NEAREST; // Type of video filter
    this.debug = false; // Whether debug output is enabled
    this.fullscreenType = MAXIMIZED; // Type of fullscreen mode
    this.fullscreen = new Fullscreen;
    this.fullscreen.on('change', () => this.onFullscreenChange());

    this.applyPalette();

    window.addEventListener('deviceorientation', () => this.onResolutionChange());
    window.addEventListener('resize', () => this.onResolutionChange());
  }

  //=========================================================
  // Events
  //=========================================================

  onResolutionChange() {
    if (this.isFullscreen()) {
      log.info('Updating fullscreen canvas after resolution change');
      this.updateRenderer();
      this.updateSize();
      this.updateStyle();
      this.drawFrame();
    }
  }

  onFullscreenChange() {
    if (this.canvas) {
      log.info('Updating canvas after fullscreen change');
      this.updateRenderer();
      this.updateSize();
      this.updateStyle();
      this.drawFrame();
    }
  }

  //=========================================================
  // Output
  //=========================================================

  setOutput(canvas) {
    if (canvas !== null && !(canvas instanceof HTMLCanvasElement)) {
      throw new Error('Invalid video output: ' + describe(canvas));
    }

    log.info(`Setting video output to ${canvas}`);
    this.canvas = canvas;

    if (canvas) {
      this.createRenderer();
      this.updateRenderer();
      this.updateSize();
      this.updateStyle();
      this.drawFrame();
    }
  }

  getOutput() {
    return this.canvas;
  }

  getOutputRect() {
    return this.canvas ? this.canvas.getBoundingClientRect() : null;
  }

  getOutputCoordinates(cursorX, cursorY) {
    if (this.canvas) {
      const {width, height, top, left} = this.getOutputRect();
      const horizontalScale = width / this.getBaseWidth();
      const verticalScale = height / this.getBaseHeight();
      const screenX = ~~((cursorX - left) / horizontalScale);
      const screenY = ~~((cursorY - top) / verticalScale);
      return [screenX, screenY];
    }
    return null;
  }

  //=========================================================
  // Canvas
  //=========================================================

  updateSize() {
    this.canvas.width = this.getTargetScale() * this.getBaseWidth();
    this.canvas.height = this.getTargetScale() * this.getBaseHeight();
    log.info(`Canvas resized to ${this.canvas.width}x${this.canvas.height} px`);
  }

  updateStyle() {
    if (this.isFullscreen()) {
      applyStyle(this.canvas, this.fullscreenType);
    } else {
      removeStyle(this.canvas);
    }
  }

  getBaseWidth() {
    return VIDEO_WIDTH * (this.debug ? 2 : 1);
  }

  getBaseHeight() {
    return VIDEO_HEIGHT;
  }

  //=========================================================
  // Renderer
  //=========================================================

  setRenderer(name) {
    if (!isRendererName(name)) {
      throw new Error('Invalid video renderer: ' + describe(name));
    }
    if (this.rendererName !== name) {
      if (this.canvas) {
        throw new Error('Cannot change video renderer once output is set');
      }
      log.info(`Using "${name}" video renderer`);
      this.rendererName = name;
    }
  }

  getRenderer() {
    return this.rendererName;
  }

  createRenderer() {
    this.renderer = createRenderer(this.rendererName, this.canvas);
    this.frame = this.renderer.createFrame(0, 0, VIDEO_WIDTH, VIDEO_HEIGHT);
    this.debugFrame = this.renderer.createFrame(VIDEO_WIDTH, 0, VIDEO_WIDTH, VIDEO_HEIGHT);
  }

  updateRenderer() {
    this.renderer.setFilter(this.filter);
    this.renderer.setScale(this.getTargetScale());
  }

  renderFrame() {
    this.nes.renderFrame(this.frame.data);
    if (this.debug) {
      this.nes.renderDebugFrame(this.debugFrame.data);
    }
  }

  drawFrame() {
    this.renderer.begin();
    this.renderer.drawFrame(this.frame);
    if (this.debug) {
      this.renderer.drawFrame(this.debugFrame);
    }
    this.renderer.end();
  }

  clearFrame() {
    if (this.canvas == null) {
      throw new Error('No video output');
    }
    this.nes.renderEmptyFrame(this.frame.data);
    if (this.debug) {
      this.nes.renderEmptyFrame(this.debugFrame.data);
    }
    this.drawFrame();
  }

  //=========================================================
  // Palette
  //=========================================================

  setPalette(name) {
    if (!isPaletteName(name)) {
      throw new Error('Invalid video palette: ' + describe(name));
    }

    if (this.paletteName !== name) {
      log.info(`Setting video palette to "${name}"`);

      this.paletteName = name;
      this.applyPalette();

      if (this.canvas) {
        this.renderFrame();
        this.drawFrame();
      }
    }
  }

  applyPalette() {
    this.nes.setPalette(createPalette(this.paletteName));
  }

  getPalette() {
    return this.paletteName;
  }

  //=========================================================
  // Scale
  //=========================================================

  setScale(scale) {
    if (typeof scale !== 'number' || scale <= 0) {
      throw new Error('Invalid video scale: ' + describe(scale));
    }

    if (this.scale !== scale) {
      log.info(`Setting video scale to ${scale}`);
      this.scale = scale;

      if (this.canvas) {
        this.updateRenderer();
        this.updateSize();
        this.updateStyle();
        this.drawFrame();
      }
    }
  }

  getScale() {
    return this.scale;
  }

  getTargetScale() {
    return this.isFullscreen() ? this.getFullscreenScale() : this.scale;
  }

  getFullscreenScale() {
    const horizontalScale = window.innerWidth / this.getBaseWidth();
    const verticalScale = window.innerHeight / this.getBaseHeight();
    const scale = Math.min(horizontalScale, verticalScale);
    return scale > 1 ? ~~scale : scale;
  }

  //=========================================================
  // Filter
  //=========================================================

  setFilter(filter) {
    if (!isFilter(filter)) {
      throw new Error('Invalid video filter: ' + describe(filter));
    }

    if (this.filter !== filter) {
      log.info(`Setting video filter to "${filter}"`);
      this.filter = filter;

      if (this.canvas) {
        this.updateRenderer();
        this.drawFrame();
      }
    }
  }

  getFilter() {
    return this.filter;
  }

  //=========================================================
  // Debug
  //=========================================================

  setDebug(debug) {
    if (typeof debug !== 'boolean') {
      throw new Error('Invalid video debug: ' + describe(debug));
    }

    if (this.debug !== debug) {
      log.info(`Setting video debug to ${debug ? 'on' : 'off'}`);
      this.debug = debug;

      if (this.canvas) {
        this.updateRenderer();
        this.updateSize();
        this.updateStyle();
        this.renderFrame();
        this.drawFrame();
      }
    }
  }

  isDebug() {
    return this.debug;
  }

  //=========================================================
  // Fullscreen
  //=========================================================

  enterFullscreen() {
    if (this.canvas == null) {
      throw new Error('No video output');
    }
    return this.fullscreen.enter(this.canvas.parentElement);
  }

  exitFullscreen() {
    return this.fullscreen.exit();
  }

  isFullscreen() {
    return this.fullscreen.is();
  }

  setFullscreenType(type) {
    if (!isStyleName(type)) {
      throw new Error('Invalid fullscreen type: ' + describe(type));
    }

    if (this.fullscreenType !== type) {
      log.info(`Setting fullscreen type to "${type}"`);
      this.fullscreenType = type;

      if (this.isFullscreen()) {
        this.updateStyle();
      }
    }
  }

  getFullscreenType() {
    return this.fullscreenType;
  }

}
<commit_msg>Fix chrome warning for deviceorientation event<commit_after>import {log, describe, isPaletteName, createPalette, DEFAULT_PALETTE, VIDEO_WIDTH, VIDEO_HEIGHT} from '../../../core';
import {isStyleName, applyStyle, removeStyle, MAXIMIZED} from './styles';
import {isRendererName, createRenderer, WEBGL} from './renderers';
import {isFilter, NEAREST} from './filters';
import Fullscreen from './Fullscreen';

export default class Video {

  constructor(nes) {
    log.info('Initializing video');

    this.nes = nes;
    this.canvas = null; // Rendering target
    this.renderer = null; // Current renderer
    this.rendererName = WEBGL; // Name of current renderer
    this.paletteName = DEFAULT_PALETTE; // Name of current palette
    this.frame = null; // Frame to render standard output
    this.debugFrame = null; // Frame to render debug output
    this.scale = 1; // Canvas scale factor
    this.filter = NEAREST; // Type of video filter
    this.debug = false; // Whether debug output is enabled
    this.fullscreenType = MAXIMIZED; // Type of fullscreen mode
    this.fullscreen = new Fullscreen;
    this.fullscreen.on('change', () => this.onFullscreenChange());

    this.applyPalette();

    if (location.protocol === 'https:') { // Deprecated for insecure origins
      window.addEventListener('deviceorientation', () => this.onResolutionChange());
    }
    window.addEventListener('resize', () => this.onResolutionChange());
  }

  //=========================================================
  // Events
  //=========================================================

  onResolutionChange() {
    if (this.isFullscreen()) {
      log.info('Updating fullscreen canvas after resolution change');
      this.updateRenderer();
      this.updateSize();
      this.updateStyle();
      this.drawFrame();
    }
  }

  onFullscreenChange() {
    if (this.canvas) {
      log.info('Updating canvas after fullscreen change');
      this.updateRenderer();
      this.updateSize();
      this.updateStyle();
      this.drawFrame();
    }
  }

  //=========================================================
  // Output
  //=========================================================

  setOutput(canvas) {
    if (canvas !== null && !(canvas instanceof HTMLCanvasElement)) {
      throw new Error('Invalid video output: ' + describe(canvas));
    }

    log.info(`Setting video output to ${canvas}`);
    this.canvas = canvas;

    if (canvas) {
      this.createRenderer();
      this.updateRenderer();
      this.updateSize();
      this.updateStyle();
      this.drawFrame();
    }
  }

  getOutput() {
    return this.canvas;
  }

  getOutputRect() {
    return this.canvas ? this.canvas.getBoundingClientRect() : null;
  }

  getOutputCoordinates(cursorX, cursorY) {
    if (this.canvas) {
      const {width, height, top, left} = this.getOutputRect();
      const horizontalScale = width / this.getBaseWidth();
      const verticalScale = height / this.getBaseHeight();
      const screenX = ~~((cursorX - left) / horizontalScale);
      const screenY = ~~((cursorY - top) / verticalScale);
      return [screenX, screenY];
    }
    return null;
  }

  //=========================================================
  // Canvas
  //=========================================================

  updateSize() {
    this.canvas.width = this.getTargetScale() * this.getBaseWidth();
    this.canvas.height = this.getTargetScale() * this.getBaseHeight();
    log.info(`Canvas resized to ${this.canvas.width}x${this.canvas.height} px`);
  }

  updateStyle() {
    if (this.isFullscreen()) {
      applyStyle(this.canvas, this.fullscreenType);
    } else {
      removeStyle(this.canvas);
    }
  }

  getBaseWidth() {
    return VIDEO_WIDTH * (this.debug ? 2 : 1);
  }

  getBaseHeight() {
    return VIDEO_HEIGHT;
  }

  //=========================================================
  // Renderer
  //=========================================================

  setRenderer(name) {
    if (!isRendererName(name)) {
      throw new Error('Invalid video renderer: ' + describe(name));
    }
    if (this.rendererName !== name) {
      if (this.canvas) {
        throw new Error('Cannot change video renderer once output is set');
      }
      log.info(`Using "${name}" video renderer`);
      this.rendererName = name;
    }
  }

  getRenderer() {
    return this.rendererName;
  }

  createRenderer() {
    this.renderer = createRenderer(this.rendererName, this.canvas);
    this.frame = this.renderer.createFrame(0, 0, VIDEO_WIDTH, VIDEO_HEIGHT);
    this.debugFrame = this.renderer.createFrame(VIDEO_WIDTH, 0, VIDEO_WIDTH, VIDEO_HEIGHT);
  }

  updateRenderer() {
    this.renderer.setFilter(this.filter);
    this.renderer.setScale(this.getTargetScale());
  }

  renderFrame() {
    this.nes.renderFrame(this.frame.data);
    if (this.debug) {
      this.nes.renderDebugFrame(this.debugFrame.data);
    }
  }

  drawFrame() {
    this.renderer.begin();
    this.renderer.drawFrame(this.frame);
    if (this.debug) {
      this.renderer.drawFrame(this.debugFrame);
    }
    this.renderer.end();
  }

  clearFrame() {
    if (this.canvas == null) {
      throw new Error('No video output');
    }
    this.nes.renderEmptyFrame(this.frame.data);
    if (this.debug) {
      this.nes.renderEmptyFrame(this.debugFrame.data);
    }
    this.drawFrame();
  }

  //=========================================================
  // Palette
  //=========================================================

  setPalette(name) {
    if (!isPaletteName(name)) {
      throw new Error('Invalid video palette: ' + describe(name));
    }

    if (this.paletteName !== name) {
      log.info(`Setting video palette to "${name}"`);

      this.paletteName = name;
      this.applyPalette();

      if (this.canvas) {
        this.renderFrame();
        this.drawFrame();
      }
    }
  }

  applyPalette() {
    this.nes.setPalette(createPalette(this.paletteName));
  }

  getPalette() {
    return this.paletteName;
  }

  //=========================================================
  // Scale
  //=========================================================

  setScale(scale) {
    if (typeof scale !== 'number' || scale <= 0) {
      throw new Error('Invalid video scale: ' + describe(scale));
    }

    if (this.scale !== scale) {
      log.info(`Setting video scale to ${scale}`);
      this.scale = scale;

      if (this.canvas) {
        this.updateRenderer();
        this.updateSize();
        this.updateStyle();
        this.drawFrame();
      }
    }
  }

  getScale() {
    return this.scale;
  }

  getTargetScale() {
    return this.isFullscreen() ? this.getFullscreenScale() : this.scale;
  }

  getFullscreenScale() {
    const horizontalScale = window.innerWidth / this.getBaseWidth();
    const verticalScale = window.innerHeight / this.getBaseHeight();
    const scale = Math.min(horizontalScale, verticalScale);
    return scale > 1 ? ~~scale : scale;
  }

  //=========================================================
  // Filter
  //=========================================================

  setFilter(filter) {
    if (!isFilter(filter)) {
      throw new Error('Invalid video filter: ' + describe(filter));
    }

    if (this.filter !== filter) {
      log.info(`Setting video filter to "${filter}"`);
      this.filter = filter;

      if (this.canvas) {
        this.updateRenderer();
        this.drawFrame();
      }
    }
  }

  getFilter() {
    return this.filter;
  }

  //=========================================================
  // Debug
  //=========================================================

  setDebug(debug) {
    if (typeof debug !== 'boolean') {
      throw new Error('Invalid video debug: ' + describe(debug));
    }

    if (this.debug !== debug) {
      log.info(`Setting video debug to ${debug ? 'on' : 'off'}`);
      this.debug = debug;

      if (this.canvas) {
        this.updateRenderer();
        this.updateSize();
        this.updateStyle();
        this.renderFrame();
        this.drawFrame();
      }
    }
  }

  isDebug() {
    return this.debug;
  }

  //=========================================================
  // Fullscreen
  //=========================================================

  enterFullscreen() {
    if (this.canvas == null) {
      throw new Error('No video output');
    }
    return this.fullscreen.enter(this.canvas.parentElement);
  }

  exitFullscreen() {
    return this.fullscreen.exit();
  }

  isFullscreen() {
    return this.fullscreen.is();
  }

  setFullscreenType(type) {
    if (!isStyleName(type)) {
      throw new Error('Invalid fullscreen type: ' + describe(type));
    }

    if (this.fullscreenType !== type) {
      log.info(`Setting fullscreen type to "${type}"`);
      this.fullscreenType = type;

      if (this.isFullscreen()) {
        this.updateStyle();
      }
    }
  }

  getFullscreenType() {
    return this.fullscreenType;
  }

}
<|endoftext|>


<commit_before>'use strict';

var path      = require('path');
var helpers   = require(path.resolve(__dirname, '..', 'helpers'));
var args      = require('yargs').argv;
var fs        = require('fs');
var clc       = require('cli-color');

module.exports = {
  'migration:create': {
    descriptions: {
      'short': 'Generates a new migration file.',
      options: {
        '--name': 'Defines the name of the migration. ' +
          clc.blueBright('Default: unnamed-migration'),
        '--underscored': 'Set timestamps to snake_case'
      }
    },

    aliases: [ 'migration:generate' ],

    task: function () {
      var config   = null;

      helpers.init.createMigrationsFolder();

      try {
        config = helpers.config.readConfig();
      } catch (e) {
        console.log(e.message);
        process.exit(1);
      }

      fs.writeFileSync(
        helpers.path.getMigrationPath(args.name),
        helpers.template.render('migrations/skeleton.js', {}, {
          beautify: false
        })
      );

      helpers.view.log(
        'New migration was created at',
        clc.blueBright(helpers.path.getMigrationPath(args.name)),
        '.'
      );
    }
  }
};
<commit_msg>changed description<commit_after>'use strict';

var path      = require('path');
var helpers   = require(path.resolve(__dirname, '..', 'helpers'));
var args      = require('yargs').argv;
var fs        = require('fs');
var clc       = require('cli-color');

module.exports = {
  'migration:create': {
    descriptions: {
      'short': 'Generates a new migration file.',
      options: {
        '--name': 'Defines the name of the migration. ' +
          clc.blueBright('Default: unnamed-migration'),
        '--underscored': 'Use snake case for the timestamp\'s attribute names'
      }
    },

    aliases: [ 'migration:generate' ],

    task: function () {
      var config   = null;

      helpers.init.createMigrationsFolder();

      try {
        config = helpers.config.readConfig();
      } catch (e) {
        console.log(e.message);
        process.exit(1);
      }

      fs.writeFileSync(
        helpers.path.getMigrationPath(args.name),
        helpers.template.render('migrations/skeleton.js', {}, {
          beautify: false
        })
      );

      helpers.view.log(
        'New migration was created at',
        clc.blueBright(helpers.path.getMigrationPath(args.name)),
        '.'
      );
    }
  }
};
<|endoftext|>


<commit_before>var path = require('path');
var nodeModulesDirname = path.join(__dirname, '..', '..', 'node_modules');
var htmlDifferDirname = path.join(nodeModulesDirname, 'html-differ');
var shouldDirname = path.join(nodeModulesDirname, 'should');

module.exports = require('enb/lib/build-flow').create()
    .name('tmpl-spec')
    .target('target', '?.tmpl-spec.js')
    .useSourceText('pure', '?.pure.tmpl-spec.js')
    .useSourceFilename('references', '?.references.js')
    .useSourceFilename('bemhtmlFile', '?.bemhtml.js')
    .useSourceFilename('bhFile', '?.bh.js')
    .builder(function (pure, referencesFilename, bemhtmlFilename, bhFilename) {
        var nodename = path.basename(this.node.getDir());

        if (!pure) {
            return [
                'function dropRequireCache(requireFunc, filename) {',
                '    var module = requireFunc.cache[filename];',
                '    if (module) {',
                '        if (module.parent) {',
                '            if (module.parent.children) {',
                '                var moduleIndex = module.parent.children.indexOf(module);',
                '                if (moduleIndex !== -1) {',
                '                    module.parent.children.splice(moduleIndex, 1);',
                '                }',
                '            }',
                '            delete module.parent;',
                '        }',
                '        delete module.children;',
                '        delete requireFunc.cache[filename];',
                '    }',
                '};',
                '',
                'var assert = require(\'assert\');',
                'var should = require(\'' + shouldDirname + '\');',
                'var htmlDiffer = require(\'' + htmlDifferDirname + '\');',
                'var references = require(\'' + referencesFilename + '\');',
                'var BEMHTML = require(\'' + bemhtmlFilename + '\').BEMHTML;',
                'var BH = require(\'' + bhFilename + '\');',
                'var itKeys = Object.keys(references).filter(function (name) {',
                '    return references[name].bemjson && references[name].html;',
                '});',
                'var diffOptions = {',
                '    ignoreHtmlAttrs: [\'id\', \'for\'],',
                '    compareHtmlAttrsAsJSON: [\'data-bem\']',
                '};',
                '',
                'describe(\'' + nodename + '\', function() {',
                '    beforeEach(function () {',
                '        dropRequireCache(require, \'' + shouldDirname + '\');',
                '        dropRequireCache(require, \'' + htmlDifferDirname + '\');',
                '        dropRequireCache(require, \'' + referencesFilename + '\');',
                '        dropRequireCache(require, \'' + bemhtmlFilename + '\');',
                '        dropRequireCache(require, \'' + bhFilename + '\');',
                '',
                '        should = require(\'' + shouldDirname + '\');',
                '        htmlDiffer = require(\'' + htmlDifferDirname + '\');',
                '        references = require(\'' + referencesFilename + '\');',
                '        BEMHTML = require(\'' + bemhtmlFilename + '\').BEMHTML;',
                '        BH = require(\'' + bhFilename + '\');',
                '    });',
                '',
                '    itKeys.forEach(function (name) {',
                '        it(\'should be equal `\' + name + \'` by BEMHTML\', function () {',
                '            var bemjson = references[name].bemjson;',
                '            var expectedHtml = references[name].html;',
                '            var actualHtml = BEMHTML.apply(bemjson);',
                '',
                '            htmlDiffer.isEqual(expectedHtml, actualHtml, diffOptions) ?',
                '                assert.ok(expectedHtml) :',
                '                assert.fail(actualHtml, expectedHtml);',
                '        });',
                '        it(\'should be equal `\' + name + \'` by BH\', function () {',
                '            var bemjson = references[name].bemjson;',
                '            var expectedHtml = references[name].html;',
                '            var actualHtml = BH.apply(bemjson);',
                '',
                '            htmlDiffer.isEqual(expectedHtml, actualHtml, diffOptions) ?',
                '                assert.ok(expectedHtml) :',
                '                assert.fail(actualHtml, expectedHtml);',
                '        });',
                '    });',
                '});'
            ].join('\n');
        }

        return pure;
    })
    .createTech();
<commit_msg>Added destname to describe<commit_after>var path = require('path');
var nodeModulesDirname = path.join(__dirname, '..', '..', 'node_modules');
var htmlDifferDirname = path.join(nodeModulesDirname, 'html-differ');
var shouldDirname = path.join(nodeModulesDirname, 'should');

module.exports = require('enb/lib/build-flow').create()
    .name('tmpl-spec')
    .target('target', '?.tmpl-spec.js')
    .useSourceText('pure', '?.pure.tmpl-spec.js')
    .useSourceFilename('references', '?.references.js')
    .useSourceFilename('bemhtmlFile', '?.bemhtml.js')
    .useSourceFilename('bhFile', '?.bh.js')
    .builder(function (pure, referencesFilename, bemhtmlFilename, bhFilename) {
        var dstpath = path.dirname(this.node.getPath());
        var nodename = path.basename(this.node.getDir());
        var describe = nodename + '\u001b[' + 94 + 'm' + ' (' + dstpath + ')' + '\u001b[0m';

        if (!pure) {
            return [
                'function dropRequireCache(requireFunc, filename) {',
                '    var module = requireFunc.cache[filename];',
                '    if (module) {',
                '        if (module.parent) {',
                '            if (module.parent.children) {',
                '                var moduleIndex = module.parent.children.indexOf(module);',
                '                if (moduleIndex !== -1) {',
                '                    module.parent.children.splice(moduleIndex, 1);',
                '                }',
                '            }',
                '            delete module.parent;',
                '        }',
                '        delete module.children;',
                '        delete requireFunc.cache[filename];',
                '    }',
                '};',
                '',
                'var assert = require(\'assert\');',
                'var should = require(\'' + shouldDirname + '\');',
                'var htmlDiffer = require(\'' + htmlDifferDirname + '\');',
                'var references = require(\'' + referencesFilename + '\');',
                'var BEMHTML = require(\'' + bemhtmlFilename + '\').BEMHTML;',
                'var BH = require(\'' + bhFilename + '\');',
                'var itKeys = Object.keys(references).filter(function (name) {',
                '    return references[name].bemjson && references[name].html;',
                '});',
                'var diffOptions = {',
                '    ignoreHtmlAttrs: [\'id\', \'for\'],',
                '    compareHtmlAttrsAsJSON: [\'data-bem\']',
                '};',
                '',
                'describe(\'' + describe + '\', function() {',
                '    beforeEach(function () {',
                '        dropRequireCache(require, \'' + shouldDirname + '\');',
                '        dropRequireCache(require, \'' + htmlDifferDirname + '\');',
                '        dropRequireCache(require, \'' + referencesFilename + '\');',
                '        dropRequireCache(require, \'' + bemhtmlFilename + '\');',
                '        dropRequireCache(require, \'' + bhFilename + '\');',
                '',
                '        should = require(\'' + shouldDirname + '\');',
                '        htmlDiffer = require(\'' + htmlDifferDirname + '\');',
                '        references = require(\'' + referencesFilename + '\');',
                '        BEMHTML = require(\'' + bemhtmlFilename + '\').BEMHTML;',
                '        BH = require(\'' + bhFilename + '\');',
                '    });',
                '',
                '    itKeys.forEach(function (name) {',
                '        it(\'should be equal `\' + name + \'` by BEMHTML\', function () {',
                '            var bemjson = references[name].bemjson;',
                '            var expectedHtml = references[name].html;',
                '            var actualHtml = BEMHTML.apply(bemjson);',
                '',
                '            htmlDiffer.isEqual(expectedHtml, actualHtml, diffOptions) ?',
                '                assert.ok(expectedHtml) :',
                '                assert.fail(actualHtml, expectedHtml);',
                '        });',
                '        it(\'should be equal `\' + name + \'` by BH\', function () {',
                '            var bemjson = references[name].bemjson;',
                '            var expectedHtml = references[name].html;',
                '            var actualHtml = BH.apply(bemjson);',
                '',
                '            htmlDiffer.isEqual(expectedHtml, actualHtml, diffOptions) ?',
                '                assert.ok(expectedHtml) :',
                '                assert.fail(actualHtml, expectedHtml);',
                '        });',
                '    });',
                '});'
            ].join('\n');
        }

        return pure;
    })
    .createTech();
<|endoftext|>


<commit_before>exports.additional_staff_logins = [   'aarondruck',
                                      'chloeatplay',
                                      'christensenep',
                                      'cmcavoy',
                                      'dajbelshaw',
                                      'flukeout',
                                      'iamjessklein',
                                      'jdotpz',
                                      'Pomax',
                                      'ScottDowne',
                                      'sinker',
                                      'stenington',
                                      'threeqube',
                                      'zeejab' ];

exports.repos = {
  "github_organizations": [
    {
      "name" : "mozilla", // as appears in github url
        "teams" : [
          {
            "name" : "webmaker", // internal reference for reporting
            "repos" : [ // alphabetical keeps this easier to read
                "appmaker-components",
                "bucheron",
                "butter",
                "csp-logger",
                "eoy-fundraising",
                "events.webmaker.org",
                "friendlycode",
                "Gallery-Maker",
                "goggles.webmaker.org",
                "hookshot",
                "htmlsanitizer.org",
                "login.webmaker.org",
                "lumberyard",
                "make-valet",
                "make.mozilla.org",
                "makeapi-client",
                "makeapi-docs",
                "MakeAPI-Gallery",
                "MakeAPI",
                "makedrive",
                "makerstrap",
                "nav-global",
                "node-hubble",
                "node-rtltr",
                "node-webmaker-butler",
                "node-webmaker-i18n",
                "node-webmaker-loginapi",
                "node-webmaker-postalservice",
                "park-warden",
                "popcorn_maker",
                "popcorn-docs",
                "popcorn-js",
                "popcorn.webmaker.org",
                "popcornjs.org",
                "sawmill",
                "teach-appmaker",
                "thimble.webmaker.org",
                "togetherjs",
                "web-literacy-client",
                "webliteracystandard",
                "webmaker-analytics",
                "webmaker-auth-client",
                "webmaker-auth",
                "webmaker-code-of-conduct",
                "webmaker-download-locales",
                "webmaker-events-2",
                "webmaker-events-service",
                "webmaker-events",
                "webmaker-firehose",
                "webmaker-kits",
                "webmaker-kits-builder",
                "webmaker-language-picker",
                "webmaker-login-example",
                "webmaker-mediasync",
                "webmaker-profile-service",
                "webmaker-profile",
                "webmaker-profile-2",
                "Webmaker-Prototypes",
                "webmaker-suite",
                "webmaker-tests",
                "webmaker-translation-stats",
                "webmaker-ui",
                "webmaker.org"
            ]
          },
          {
            "name" : "openbadges",
            "repos" : [
              "badge-the-world",
              "badgekit-api",
              "badgekit-api-client",
              "badgeopolis",
              "badges.mozilla.org",
              "community.openbadges.org",
              "CSOL-site",
              "openbadger",
              "openbadger-client",
              "openbadges",
              "openbadges-backpack",
              "openbadges-badgekit",
              "openbadges-badges",
              "openbadges-badgestudio",
              "openbadges-bakery",
              "openbadges-bakery-service",
              "openbadges-cem",
              "openbadges-directory",
              "openbadges-discovery",
              "openbadges-discussion",
              "openbadges-specification",
              "openbadges-validator",
              "openbadges-validator-service",
              "openbadges.org"
            ]
          },
          {
            "name" : "opennews",
            "repos" : [
              "mozilla-opennews",
              "source"
            ]
          }
        ]
    },
    {
      "name" : "openNews",
        "teams" : [
          {
            "name" : "opennews",
            "repos" : [
              "amo",
              "NewsYourOwnAdventure",
              "nomo",
              "opennews.github.com",
              "spiders",
              "zeit-online-republica-tracker"
            ]
          }
      ]
    },
    {
      "name" : "mozilla-appmaker",
        "teams" : [
          {
            "name" : "appmaker",
            "repos" : [
              "appmaker",
              "ceci",
              "ceci-button",
              "ceci-fork-me",
              "ceci-support",
              "chefbot",
              "component-addform",
              "component-alternating-gate",
              "component-button",
              "component-button-with-confirmation",
              "component-camera-button",
              "component-chat-window",
              "component-counter",
              "component-dataview",
              "component-editform",
              "component-fireworks",
              "component-header",
              "component-image",
              "component-metronome",
              "component-paypal",
              "component-spacer",
              "component-splitter",
              "component-template",
              "component-text-input",
              "component-textbox",
              "dashboard",
              "haas",
              "mozilla-appmaker.github.io",
              "phonegap-appmaker-harness",
              "start-here",
              "tools",
              "views"
            ]
          }
      ]
    },
    {
      "name" : "swcarpentry",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "site"
            ]
          }
      ]
    },
    {
      "name" : "mozillascience",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "code-research-object"
            ]
          }
      ]
    }
  ]
};
<commit_msg>add mozillafordevelopment repos<commit_after>exports.additional_staff_logins = [   'aarondruck',
                                      'chloeatplay',
                                      'christensenep',
                                      'cmcavoy',
                                      'dajbelshaw',
                                      'flukeout',
                                      'iamjessklein',
                                      'jdotpz',
                                      'Pomax',
                                      'ScottDowne',
                                      'sinker',
                                      'stenington',
                                      'threeqube',
                                      'zeejab' ];

exports.repos = {
  "github_organizations": [
    {
      "name" : "mozilla", // as appears in github url
        "teams" : [
          {
            "name" : "webmaker", // internal reference for reporting
            "repos" : [ // alphabetical keeps this easier to read
                "appmaker-components",
                "bucheron",
                "butter",
                "csp-logger",
                "eoy-fundraising",
                "events.webmaker.org",
                "friendlycode",
                "Gallery-Maker",
                "goggles.webmaker.org",
                "hookshot",
                "htmlsanitizer.org",
                "login.webmaker.org",
                "lumberyard",
                "make-valet",
                "make.mozilla.org",
                "makeapi-client",
                "makeapi-docs",
                "MakeAPI-Gallery",
                "MakeAPI",
                "makedrive",
                "makerstrap",
                "nav-global",
                "node-hubble",
                "node-rtltr",
                "node-webmaker-butler",
                "node-webmaker-i18n",
                "node-webmaker-loginapi",
                "node-webmaker-postalservice",
                "park-warden",
                "popcorn_maker",
                "popcorn-docs",
                "popcorn-js",
                "popcorn.webmaker.org",
                "popcornjs.org",
                "sawmill",
                "teach-appmaker",
                "thimble.webmaker.org",
                "togetherjs",
                "web-literacy-client",
                "webliteracystandard",
                "webmaker-analytics",
                "webmaker-auth-client",
                "webmaker-auth",
                "webmaker-code-of-conduct",
                "webmaker-download-locales",
                "webmaker-events-2",
                "webmaker-events-service",
                "webmaker-events",
                "webmaker-firehose",
                "webmaker-kits",
                "webmaker-kits-builder",
                "webmaker-language-picker",
                "webmaker-login-example",
                "webmaker-mediasync",
                "webmaker-profile-service",
                "webmaker-profile",
                "webmaker-profile-2",
                "Webmaker-Prototypes",
                "webmaker-suite",
                "webmaker-tests",
                "webmaker-translation-stats",
                "webmaker-ui",
                "webmaker.org"
            ]
          },
          {
            "name" : "openbadges",
            "repos" : [
              "badge-the-world",
              "badgekit-api",
              "badgekit-api-client",
              "badgeopolis",
              "badges.mozilla.org",
              "community.openbadges.org",
              "CSOL-site",
              "openbadger",
              "openbadger-client",
              "openbadges",
              "openbadges-backpack",
              "openbadges-badgekit",
              "openbadges-badges",
              "openbadges-badgestudio",
              "openbadges-bakery",
              "openbadges-bakery-service",
              "openbadges-cem",
              "openbadges-directory",
              "openbadges-discovery",
              "openbadges-discussion",
              "openbadges-specification",
              "openbadges-validator",
              "openbadges-validator-service",
              "openbadges.org"
            ]
          },
          {
            "name" : "opennews",
            "repos" : [
              "mozilla-opennews",
              "source"
            ]
          }
        ]
    },
    {
      "name" : "openNews",
        "teams" : [
          {
            "name" : "opennews",
            "repos" : [
              "amo",
              "NewsYourOwnAdventure",
              "nomo",
              "opennews.github.com",
              "spiders",
              "zeit-online-republica-tracker"
            ]
          }
      ]
    },
    {
      "name" : "mozilla-appmaker",
        "teams" : [
          {
            "name" : "appmaker",
            "repos" : [
              "appmaker",
              "ceci",
              "ceci-button",
              "ceci-fork-me",
              "ceci-support",
              "chefbot",
              "component-addform",
              "component-alternating-gate",
              "component-button",
              "component-button-with-confirmation",
              "component-camera-button",
              "component-chat-window",
              "component-counter",
              "component-dataview",
              "component-editform",
              "component-fireworks",
              "component-header",
              "component-image",
              "component-metronome",
              "component-paypal",
              "component-spacer",
              "component-splitter",
              "component-template",
              "component-text-input",
              "component-textbox",
              "dashboard",
              "haas",
              "mozilla-appmaker.github.io",
              "phonegap-appmaker-harness",
              "start-here",
              "tools",
              "views"
            ]
          }
      ]
    },
    {
      "name" : "swcarpentry",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "site"
            ]
          }
      ]
    },
    {
      "name" : "mozillascience",
        "teams" : [
          {
            "name" : "sciencelab",
            "repos" : [
              "code-research-object"
            ]
          }
      ]
    },
    {
      "name" : "mozillafordevelopment",
        "teams" : [
          {
            "name" : "webmaker",
            "repos" : [
              "webmaker-app-publisher",
              "webmaker-app",
              "beaker",
              "webmaker-app-csvexport",
              "webmaker-app-guide",
              "Exploring-challenge",
              "player",
              "fieldresearch",
              "mozillafordevelopment.github.io"
            ]
          }
      ]
    }
  ]
};
<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";

var textLint = require("./textlint");
var fileTraverse = require("./util/traverse");
var Config = require("./config/config");
var createFormatter = require("textlint-formatter");
var tryResolve = require("try-resolve");
var path = require("path");
var ruleManager = require("./rule/rule-manager");
var debug = require("debug")("text:cli-engine");
/**
 * Process files are wanted to lint.
 * TextLintEngine is a wrapper of textlint.js.
 * Aim to be called from cli with cli options.
 * @param {TextLintConfig|} options the options is command line options or Config object.
 * @constructor
 */
function TextLintEngine(options) {
    if (options instanceof Config) {
        // Almost internal use-case
        this.config = options;
    } else {
        this.config = new Config(options);
    }
}
/**
 * filter files by config
 * @param files
 * @param {Config} config
 */
function findFiles(files, config) {
    var processed = [];
    // sync
    fileTraverse({
        files: files,
        extensions: config.extensions,
        exclude: false
    }, function (filename) {
        debug("Processing " + filename);
        processed.push(filename);
    });
    return processed;
}

/**
 * set up lint rules using {@lint Config} object.
 * The {@lint Config} object was created with initialized {@link TextLintEngine} (as-known Constructor).
 * @param {Config} config the config is parsed object
 */
TextLintEngine.prototype.setupRules = function (config) {
    config = config || this.config;
    debug("config %O", config);
    var that = this;
    // --ruledir
    if (config.rulePaths) {
        // load in additional rules
        config.rulePaths.forEach(function (rulesdir) {
            debug("Loading rules from %o", rulesdir);
            ruleManager.loadRules(rulesdir);
        });
    }
    // --rule
    if (config.rules) {
        // load in additional rules
        config.rules.forEach(function (ruleName) {
            that.loadRule(ruleName);
        });
    }
    textLint.setupRules(ruleManager.getAllRules(), config.rulesConfig);
};
/**
 * load rule file with `ruleName` and define rule.
 * if rule is not found, then throw ReferenceError.
 * if already rule is loaded, do not anything.
 * @param {string} ruleName
 * @param {string} [directory] directory is optional. this value used as root directory to load rule.
 */
TextLintEngine.prototype.loadRule = function (ruleName, directory) {
    // ignore already defined rule
    // ignore rules from rulePaths because avoid ReferenceError is that try to require.
    if (ruleManager.isDefinedRule(ruleName)) {
        return;
    }
    if (!directory) {
        directory = "";
    }
    var pkgPath = tryResolve(path.join(directory, "textlint-rule-" + ruleName)) || tryResolve(path.join(directory, ruleName));
    if (!pkgPath) {
        throw new ReferenceError(ruleName + " is not found");
    }
    debug("Loading rules from %s", pkgPath);
    var plugin = require(pkgPath);
    var definedRuleName = ruleName.replace(/^textlint\-rule\-/, "");
    ruleManager.defineRule(definedRuleName, plugin);
};
/**
 * Remove all registered rule and clear messages.
 */
TextLintEngine.prototype.resetRules = function () {
    textLint.resetRules();
};
/**
 * Executes the current configuration on an array of file and directory names.
 * @param {String[]}  files An array of file and directory names.
 * @returns {TextLintResult[]} The results for all files that were linted.
 */
TextLintEngine.prototype.executeOnFiles = function (files) {
    this.setupRules(this.config);
    var targetFiles = findFiles(files, this.config);
    var results = targetFiles.map(function (file) {
        return textLint.lintFile(file);
    });
    textLint.resetRules();
    return results;
};
/**
 * If want to lint a text, use it.
 * But, if you have a target file, use {@link executeOnFiles} instead of it.
 * @param text plain text for lint
 * @returns {TextLintResult[]}
 * @todo specify the files format for lint by config.filetype?
 */
TextLintEngine.prototype.executeOnText = function (text) {
    this.setupRules(this.config);
    var results = [textLint.lintText(text)];
    textLint.resetRules();
    return results;
};

/**
 * format {@link results} and return output text.
 * @param {TextLintResult[]} results the collection of result
 * @returns {string} formatted output text
 * @example
 *  console.log(formatResults(results));
 */
TextLintEngine.prototype.formatResults = function (results) {
    var formatter = createFormatter({
        formatterName: this.config.formatterName
    });
    return formatter(results);
};

/**
 * Checks if the given message is an error message.
 * @param {TextLintMessage} message The message to check.
 * @returns {boolean} Whether or not the message is an error message.
 */
TextLintEngine.prototype.isErrorMessage = function (message) {
    return message.severity === 2;
};

/**
 * Checks if the given results contain error message.
 * If there is even one error then return true.
 * @param {TextLintResult[]} results Linting result collection
 * @returns {Boolean} Whether or not the results contain error message.
 */
TextLintEngine.prototype.isErrorResults = function (results) {
    var that = this;
    return results.some(function (result) {
        return result.messages.some(that.isErrorMessage);
    });
};

module.exports = TextLintEngine;
<commit_msg>set up rules only by passing config<commit_after>// LICENSE : MIT
"use strict";

var textLint = require("./textlint");
var fileTraverse = require("./util/traverse");
var Config = require("./config/config");
var createFormatter = require("textlint-formatter");
var tryResolve = require("try-resolve");
var path = require("path");
var ruleManager = require("./rule/rule-manager");
var debug = require("debug")("text:cli-engine");
/**
 * Process files are wanted to lint.
 * TextLintEngine is a wrapper of textlint.js.
 * Aim to be called from cli with cli options.
 * @param {TextLintConfig|} options the options is command line options or Config object.
 * @constructor
 */
function TextLintEngine(options) {
    if (options instanceof Config) {
        // Almost internal use-case
        this.config = options;
    } else {
        this.config = new Config(options);
    }
    this.setupRules(this.config);
}
/**
 * filter files by config
 * @param files
 * @param {Config} config
 */
function findFiles(files, config) {
    var processed = [];
    // sync
    fileTraverse({
        files: files,
        extensions: config.extensions,
        exclude: false
    }, function (filename) {
        debug("Processing " + filename);
        processed.push(filename);
    });
    return processed;
}

/**
 * set up lint rules using {@lint Config} object.
 * The {@lint Config} object was created with initialized {@link TextLintEngine} (as-known Constructor).
 * @param {Config} config the config is parsed object
 */
TextLintEngine.prototype.setupRules = function (config) {
    config = config || this.config;
    debug("config %O", config);
    var that = this;
    // --ruledir
    if (config.rulePaths) {
        // load in additional rules
        config.rulePaths.forEach(function (rulesdir) {
            debug("Loading rules from %o", rulesdir);
            ruleManager.loadRules(rulesdir);
        });
    }
    // --rule
    if (config.rules) {
        // load in additional rules
        config.rules.forEach(function (ruleName) {
            that.loadRule(ruleName);
        });
    }
    textLint.setupRules(ruleManager.getAllRules(), config.rulesConfig);
};
/**
 * load rule file with `ruleName` and define rule.
 * if rule is not found, then throw ReferenceError.
 * if already rule is loaded, do not anything.
 * @param {string} ruleName
 * @param {string} [directory] directory is optional. this value used as root directory to load rule.
 */
TextLintEngine.prototype.loadRule = function (ruleName, directory) {
    // ignore already defined rule
    // ignore rules from rulePaths because avoid ReferenceError is that try to require.
    if (ruleManager.isDefinedRule(ruleName)) {
        return;
    }
    if (!directory) {
        directory = "";
    }
    var pkgPath = tryResolve(path.join(directory, "textlint-rule-" + ruleName)) || tryResolve(path.join(directory, ruleName));
    if (!pkgPath) {
        throw new ReferenceError(ruleName + " is not found");
    }
    debug("Loading rules from %s", pkgPath);
    var plugin = require(pkgPath);
    var definedRuleName = ruleName.replace(/^textlint\-rule\-/, "");
    ruleManager.defineRule(definedRuleName, plugin);
};
/**
 * Remove all registered rule and clear messages.
 */
TextLintEngine.prototype.resetRules = function () {
    textLint.resetRules();
};
/**
 * Executes the current configuration on an array of file and directory names.
 * @param {String[]}  files An array of file and directory names.
 * @returns {TextLintResult[]} The results for all files that were linted.
 */
TextLintEngine.prototype.executeOnFiles = function (files) {
    var targetFiles = findFiles(files, this.config);
    var results = targetFiles.map(function (file) {
        return textLint.lintFile(file);
    });
    textLint.resetRules();
    return results;
};
/**
 * If want to lint a text, use it.
 * But, if you have a target file, use {@link executeOnFiles} instead of it.
 * @param text plain text for lint
 * @returns {TextLintResult[]}
 * @todo specify the files format for lint by config.filetype?
 */
TextLintEngine.prototype.executeOnText = function (text) {
    var results = [textLint.lintText(text)];
    textLint.resetRules();
    return results;
};

/**
 * format {@link results} and return output text.
 * @param {TextLintResult[]} results the collection of result
 * @returns {string} formatted output text
 * @example
 *  console.log(formatResults(results));
 */
TextLintEngine.prototype.formatResults = function (results) {
    var formatter = createFormatter({
        formatterName: this.config.formatterName
    });
    return formatter(results);
};

/**
 * Checks if the given message is an error message.
 * @param {TextLintMessage} message The message to check.
 * @returns {boolean} Whether or not the message is an error message.
 */
TextLintEngine.prototype.isErrorMessage = function (message) {
    return message.severity === 2;
};

/**
 * Checks if the given results contain error message.
 * If there is even one error then return true.
 * @param {TextLintResult[]} results Linting result collection
 * @returns {Boolean} Whether or not the results contain error message.
 */
TextLintEngine.prototype.isErrorResults = function (results) {
    var that = this;
    return results.some(function (result) {
        return result.messages.some(that.isErrorMessage);
    });
};

module.exports = TextLintEngine;
<|endoftext|>