<commit_before>(function (exports) {

	/*!
	 * MsgBar
	 *
	 */

	exports.MsgBar	= MsgBar;

	function MsgBar(id){

		this.game = node.game;
		this.id = id || 'msgbar';
		this.name = 'Msg Bar';
		this.version = '0.2.1';

		this.recipient = null;
	}

	MsgBar.prototype.append = function (root, ids) {

		var PREF = this.id + '_';

		var idFieldset = PREF + 'fieldset';
		var idButton = PREF + 'sendButton';
		var idMsgText = PREF + 'msgText';
		var idRecipient = PREF + 'recipient';

		if (ids !== null && ids !== undefined) {
			if (ids.hasOwnProperty('fieldset')) idFieldset = ids.fieldset;
			if (ids.hasOwnProperty('button')) idButton = ids.button;
			if (ids.hasOwnProperty('msgText')) idMsgText = ids.msgText;
			if (ids.hasOwnProperty('recipient')) idRecipient = ids.recipient;
		}

		var fieldset = node.window.addFieldset(root, idFieldset, 'Send Msg To Players');
		var sendButton = node.window.addButton(fieldset, idButton);
		var msgText = node.window.addTextInput(fieldset, idMsgText);
		this.recipient = node.window.addRecipientSelector(fieldset, idRecipient);

		var that = this;

		sendButton.onclick = function() {

			// Should be within the range of valid values
			// but we should add a check
			var to = that.recipient.value;
			var msg = node.TXT(msgText.value,to);
			//console.log(msg.stringify());
		};

		return fieldset;

	};

	MsgBar.prototype.listeners = function(){
		var that = this;

		node.onPLIST( function(msg) {
			node.window.populateRecipientSelector(that.recipient,msg.data);
			// was
			//that.game.window.populateRecipientSelector(that.recipient,msg.data);
		});
	};
})(node.window.widgets);<commit_msg>Fixed PlayerList but in GameWindow<commit_after>(function (exports) {

	/*!
	 * MsgBar
	 *
	 */

	exports.MsgBar	= MsgBar;

	function MsgBar(id){

		this.game = node.game;
		this.id = id || 'msgbar';
		this.name = 'Msg Bar';
		this.version = '0.2.1';

		this.recipient = null;
	}

	MsgBar.prototype.append = function (root, ids) {

		var PREF = this.id + '_';

		var idFieldset = PREF + 'fieldset';
		var idButton = PREF + 'sendButton';
		var idMsgText = PREF + 'msgText';
		var idRecipient = PREF + 'recipient';

		if (ids !== null && ids !== undefined) {
			if (ids.hasOwnProperty('fieldset')) idFieldset = ids.fieldset;
			if (ids.hasOwnProperty('button')) idButton = ids.button;
			if (ids.hasOwnProperty('msgText')) idMsgText = ids.msgText;
			if (ids.hasOwnProperty('recipient')) idRecipient = ids.recipient;
		}

		var fieldset = node.window.addFieldset(root, idFieldset, 'Send Msg To Players');
		var sendButton = node.window.addButton(fieldset, idButton);
		var msgText = node.window.addTextInput(fieldset, idMsgText);
		this.recipient = node.window.addRecipientSelector(fieldset, idRecipient);

		var that = this;

		sendButton.onclick = function() {

			// Should be within the range of valid values
			// but we should add a check
			var to = that.recipient.value;
			var msg = node.TXT(msgText.value,to);
			//console.log(msg.stringify());
		};

		return fieldset;

	};

	MsgBar.prototype.listeners = function(){
		var that = this;
		node.onPLIST( function(msg) {
			node.window.populateRecipientSelector(that.recipient,msg.data);

		});
	};
})(node.window.widgets);<|endoftext|>


<commit_before>/*
 * grunt-link-checker
 * https://github.com/ChrisWren/grunt-link-checker
 *
 * Copyright (c) 2014 Chris Wren and contributors
 * Licensed under the MIT license.
 */

var Crawler = require('simplecrawler');
var cheerio = require('cheerio');
require('colors');

module.exports = function (grunt) {
  'use strict';
  grunt.registerMultiTask('link-checker', 'Checks your site for broken links after a build.', function () {

    var done = this.async();
    var options = this.options();
    var errors = false;
    var site = this.data.site;

    var crawler = new Crawler(site);

    Object.keys(options).forEach(function(key) {
      crawler[key] = options[key];
    });
    crawler
      .on('fetch404',function(queueItem) {
        errors = true;
        grunt.log.error('Resource not found linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
      })
      .on('fetcherror', function(queueItem) {
        errors = true;
        grunt.log.error('Trouble fetching the following resource linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
      })
      .on('fetchtimeout', function(queueItem) {
        errors = true;
        grunt.log.error('Timeout fetching the following resource linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
      })
      .on('fetchclienterror', function(queueItem) {
        grunt.log.error('Client error fetching the following resource linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
        errors = true;
      })
      .on('complete', function() {
        if (!errors) {
          grunt.log.ok('No broken links found at: ' + site);
        }
        done(!errors);
      })
      .on('fetchcomplete', function(queueItem, responseBuffer) {
        grunt.log.debug('Fetched: ' + queueItem.url);
        if (options.noFragment) {
          return;
        }
        var html = responseBuffer.toString();
        var $ = cheerio.load(html);

        $('a[href*="#"]').each(function(i, anchor) {
          crawler.queueURL($(anchor).attr('href'), queueItem);
        });

        if (queueItem.url.indexOf('#') !== -1) {
          try {
            if ($(queueItem.url.slice(queueItem.url.indexOf('#'))).length === 0) {
              grunt.log.error('Error finding content with the following fragment identifier linked from ' + queueItem.referrer.cyan  + ' to', queueItem.url.magenta);
              errors = true;
            }
          } catch (e) {
            grunt.log.error('The following URL was formatted incorrectly linked from ' + queueItem.referrer.cyan  + ' to', queueItem.url.magenta);
            errors = true;
          }

        }
      });

    crawler.start();
  });
};
<commit_msg>Fixed error reporting for initial link<commit_after>/*
 * grunt-link-checker
 * https://github.com/ChrisWren/grunt-link-checker
 *
 * Copyright (c) 2014 Chris Wren and contributors
 * Licensed under the MIT license.
 */

var Crawler = require('simplecrawler');
var cheerio = require('cheerio');
require('colors');

module.exports = function (grunt) {
  'use strict';
  grunt.registerMultiTask('link-checker', 'Checks your site for broken links after a build.', function () {

    var done = this.async();
    var options = this.options();
    var errors = false;
    var site = this.data.site;

    var crawler = new Crawler(site);

    Object.keys(options).forEach(function(key) {
      crawler[key] = options[key];
    });
    crawler
      .on('fetch404',function(queueItem) {
        errors = true;
        grunt.log.error('Resource not found linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
      })
      .on('fetcherror', function(queueItem) {
        errors = true;
        grunt.log.error('Trouble fetching the following resource linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
      })
      .on('fetchtimeout', function(queueItem) {
        errors = true;
        grunt.log.error('Timeout fetching the following resource linked from ' + queueItem.referrer.cyan + ' to', queueItem.url.magenta);
      })
      .on('fetchclienterror', function(queueItem) {
        grunt.log.error('Client error fetching the following resource linked from ' + queueItem.referrer ? queueItem.referrer.cyan : site + ' to', queueItem.url.magenta);
        errors = true;
      })
      .on('complete', function() {
        if (!errors) {
          grunt.log.ok('No broken links found at: ' + site);
        }
        done(!errors);
      })
      .on('fetchcomplete', function(queueItem, responseBuffer) {
        grunt.log.debug('Fetched: ' + queueItem.url);
        if (options.noFragment) {
          return;
        }
        var html = responseBuffer.toString();
        var $ = cheerio.load(html);

        $('a[href*="#"]').each(function(i, anchor) {
          crawler.queueURL($(anchor).attr('href'), queueItem);
        });

        if (queueItem.url.indexOf('#') !== -1) {
          try {
            if ($(queueItem.url.slice(queueItem.url.indexOf('#'))).length === 0) {
              grunt.log.error('Error finding content with the following fragment identifier linked from ' + queueItem.referrer.cyan  + ' to', queueItem.url.magenta);
              errors = true;
            }
          } catch (e) {
            grunt.log.error('The following URL was formatted incorrectly linked from ' + queueItem.referrer.cyan  + ' to', queueItem.url.magenta);
            errors = true;
          }
        }
      });

    crawler.start();
  });
};
<|endoftext|>


<commit_before>/*
 * grunt-maven-deploy
 * https://github.com/mrkelly/grunt-maven-deploy
 *
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('maven_deploy', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this);
    } else if (options.goal === 'install') {
      install(this);
    }

  });

  function install(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package',
      'maven_deploy:install-file');
  }

  function deploy(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package', 'maven_deploy:deploy-file');
  }

  grunt.registerTask('maven_deploy:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven_deploy:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = (options.type === 'jar') ? 'jar' : options.packaging;
    if (options.packaging === 'jar'){
        options.file = renameForJarTypeArtifacts(options.file);
    }

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
            args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  grunt.registerTask('maven_deploy:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = (options.type === 'jar') ? 'jar' : options.packaging;
    if (options.packaging === 'jar'){
        options.file = renameForJarTypeArtifacts(options.file);
    }

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }

    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = options.artifactId + '-' + options.version + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(options.artifactId + '-' + options.version, task.files);
    }
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForJarTypeArtifacts(filename) {
    var warFileName = filename.replace('zip', 'jar');
    try {
      fs.renameSync(filename, warFileName);
      return warFileName;
    } catch (e) {
      throw e;
    }
  }

};
<commit_msg>Support war packaging.<commit_after>/*
 * grunt-maven-deploy
 * https://github.com/mrkelly/grunt-maven-deploy
 *
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('maven_deploy', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this);
    } else if (options.goal === 'install') {
      install(this);
    }

  });

  function install(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package',
      'maven_deploy:install-file');
  }

  function deploy(task) {
    var pkg = grunt.file.readJSON('package.json');
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    if (options.snapshot) {
      options.version = options.version + "-SNAPSHOT";
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven_deploy:package', 'maven_deploy:deploy-file');
  }

  grunt.registerTask('maven_deploy:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven_deploy:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    if (options.type === 'jar' || options.type === 'war') {
      options.packaging = options.type;
      options.file = renameForArtifactType(options.file, options.type);
    }

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
            args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  grunt.registerTask('maven_deploy:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    if (options.type === 'jar' || options.type === 'war') {
      options.packaging = options.type;
      options.file = renameForArtifactType(options.file, options.type);
    }

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }

    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    var mavenCommand = grunt.util.spawn({ cmd: 'mvn', args: args }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });

    mavenCommand.stdout.on('data', function(buf) {
      grunt.verbose.write(String(buf));
    });
  });

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = options.artifactId + '-' + options.version + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      task.files = injectDestFolder(options.artifactId + '-' + options.version, task.files);
    }
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForArtifactType(filename, type) {
    var typeFilename = filename.replace('zip', type);
    try {
      fs.renameSync(filename, typeFilename);
      return typeFilename;
    } catch (e) {
      throw e;
    }
  }

};
<|endoftext|>


<commit_before>var painless = require('../../assertion/painless')
var test = painless.createGroup('Test array/findLast and collection/findLast')
var t = painless.assert

var findLast = require('../../../src/array/findLast')
var filast = require('../../../src/collection/findLast')

test('should return last match', function () {
  var obj = {a: 'b'}
  var arr = [123, 'foo', 'bar', obj]

  t.same(findLast(arr, function (val) {
    return val === 123
  }), 123)
  t.same(findLast(arr, function (val) {
    return typeof val === 'string'
  }), 'bar')
  t.same(findLast(arr, function (val) {
    return val.a === 'b'
  }), obj)
})

test('should return undefined if array is null/undefined', function () {
  var testFunc = function () {
    return true
  }

  t.is(findLast(null, testFunc), undefined)
  t.is(findLast(undefined, testFunc), undefined)
})

test('should support object shortcut syntax', function () {
  var obj = {a: 'b'}
  var arr = [123, 'foo', 'bar', obj]

  t.same(filast(arr, {a: 'b'}), obj)
})

test('should support string shortcut syntax', function () {
  var obj = {a: 'b'}
  var arr = [123, 'foo', 'bar', obj]

  t.same(filast(arr, 'a'), obj)
})
<commit_msg>update test array/findLast — coverage<commit_after>var painless = require('../../assertion/painless')
var test = painless.createGroup('Test array/findLast and collection/findLast')
var t = painless.assert

var findLast = require('../../../src/array/findLast')
var filast = require('../../../src/collection/findLast')

test('should return last match', function () {
  var obj = {a: 'b'}
  var arr = [123, 'foo', 'bar', obj]

  t.same(findLast(arr, function (val) {
    return val === 123
  }), 123)
  t.same(findLast(arr, function (val) {
    return typeof val === 'string'
  }), 'bar')
  t.same(findLast(arr, function (val) {
    return val.a === 'b'
  }), obj)
})

test('should return undefined if array is null/undefined', function () {
  var testFunc = function () {
    return true
  }

  t.is(findLast(null, testFunc), undefined)
  t.is(findLast(undefined, testFunc), undefined)
  t.is(filast(null, testFunc), undefined)
  t.is(filast(undefined, testFunc), undefined)
})

test('should support object shortcut syntax', function () {
  var obj = {a: 'b'}
  var arr = [123, 'foo', 'bar', obj]

  t.same(filast(arr, {a: 'b'}), obj)
})

test('should support string shortcut syntax', function () {
  var obj = {a: 'b'}
  var arr = [123, 'foo', 'bar', obj]

  t.same(filast(arr, 'a'), obj)
})
<|endoftext|>


<commit_before>var path = require('path');
var appRoot = path.dirname(path.dirname(__dirname));

module.exports = {
    index: {
        files: [
            {
                cwd: process.cwd(),
                src: path.join(appRoot, 'index.html'),
                dest: '<%= distDir %>/index.html'
            },
            {
                cwd: process.cwd(),
                src: path.join(appRoot, 'index.html'),
                dest: './index.html'
            }
        ]
    },
    assets: {
        files: [
            {
                expand: true,
                dot: true,
                cwd: '<%= coreDir %>',
                dest: '<%= distDir %>',
                src: ['images/**/*', 'scripts/**/*.json']
            }
        ]
    },
    'assets-docs': {
        files: [
            {
                expand: true,
                dot: true,
                cwd: '<%= coreDir %>',
                dest: 'docs/dist',
                src: ['images/**/*']
            },
            {
                cwd: process.cwd(),
                src: path.join(appRoot, 'docs/index.html'),
                dest: path.join(appRoot, 'docs/dist/index.html')
            }
        ]
    }
};
<commit_msg>ui(fix): copy svg images with assets. Should fix SD-5358<commit_after>var path = require('path');
var appRoot = path.dirname(path.dirname(__dirname));

module.exports = {
    index: {
        files: [
            {
                cwd: process.cwd(),
                src: path.join(appRoot, 'index.html'),
                dest: '<%= distDir %>/index.html'
            },
            {
                cwd: process.cwd(),
                src: path.join(appRoot, 'index.html'),
                dest: './index.html'
            }
        ]
    },
    assets: {
        files: [
            {
                expand: true,
                dot: true,
                cwd: '<%= coreDir %>',
                dest: '<%= distDir %>',
                src: ['images/**/*', 'scripts/**/*.{json,svg}']
            }
        ]
    },
    'assets-docs': {
        files: [
            {
                expand: true,
                dot: true,
                cwd: '<%= coreDir %>',
                dest: 'docs/dist',
                src: ['images/**/*']
            },
            {
                cwd: process.cwd(),
                src: path.join(appRoot, 'docs/index.html'),
                dest: path.join(appRoot, 'docs/dist/index.html')
            }
        ]
    }
};
<|endoftext|>


<commit_before>/* global describe, it, expect, xblocks, beforeEach, afterEach, vow */
/* jshint strict: false */

describe('xblocks - Изменение атрибутов ->', function() {

    xblocks.view.register('x-element-update', {
        propTypes: {
            'bool-attr': React.PropTypes.bool,
            'number-attr': React.PropTypes.number
        },

        render: function() {
            return React.DOM.div({
                className: (this.props['bool-attr'] ? 'bool' : '')
            });
        }
    });

    xblocks.create('x-element-update');

    beforeEach(function() {
        this.xElement = document.createElement('x-element-update');
    });

    afterEach(function() {
        if (this.xElement.parentNode) {
            this.xElement.parentNode.removeChild(this.xElement);
        }
    });

    it.only('Добавление атрибута вызывает перерисовку', function() {
        var that = this;

        return new vow.Promise(function(resolve) {
            that.xElement.addEventListener('xb-update', function() {
                expect(this.getAttribute('bool-attr')).to.be('true');
                expect(xblocks.dom.querySelector(this, '.bool')).not.to.be(null);
                resolve();
            }, false);

            that.xElement.addEventListener('xb-created', function() {
                expect(xblocks.dom.querySelector(this, '.bool')).to.be(null);
                that.xElement.setAttribute('bool-attr', 'true');
            }, false);

            document.body.appendChild(that.xElement);
        });
    });

});
<commit_msg>rm only<commit_after>/* global describe, it, expect, xblocks, beforeEach, afterEach, vow */
/* jshint strict: false */

describe('xblocks - Изменение атрибутов ->', function() {

    xblocks.view.register('x-element-update', {
        propTypes: {
            'bool-attr': React.PropTypes.bool,
            'number-attr': React.PropTypes.number
        },

        render: function() {
            return React.DOM.div({
                className: (this.props['bool-attr'] ? 'bool' : '')
            });
        }
    });

    xblocks.create('x-element-update');

    beforeEach(function() {
        this.xElement = document.createElement('x-element-update');
    });

    afterEach(function() {
        if (this.xElement.parentNode) {
            this.xElement.parentNode.removeChild(this.xElement);
        }
    });

    it('Добавление атрибута вызывает перерисовку', function() {
        var that = this;

        return new vow.Promise(function(resolve) {
            that.xElement.addEventListener('xb-update', function() {
                expect(this.getAttribute('bool-attr')).to.be('true');
                expect(xblocks.dom.querySelector(this, '.bool')).not.to.be(null);
                resolve();
            }, false);

            that.xElement.addEventListener('xb-created', function() {
                expect(xblocks.dom.querySelector(this, '.bool')).to.be(null);
                that.xElement.setAttribute('bool-attr', 'true');
            }, false);

            document.body.appendChild(that.xElement);
        });
    });

});
<|endoftext|>


<commit_before>/*
 * grunt-contrib-websquaremin
 * https://github.com/inswave/grunt-contrib-websquaremin
 *
 * Copyright (c) 2013 inswave
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
    'use strict';

    var pd = require('pretty-data').pd,
        helper = require('grunt-lib-contrib').init(grunt),
        uglify = require('uglify-js');

    grunt.registerMultiTask('websquaremin', 'Minify WebSquare XML', function() {
        var options = this.options({
			preserveComments: false
		});

        this.files.forEach(function (file) {
            var scriptRegex = /(<script[\s\S]*?type=[\"\']javascript[\"\'][\s\S]*?><!\[CDATA\[)([\s\S]*?)(\]\]><\/script>)/ig,
                tempArray = [],
                min,
                max = file.src.filter(function(filepath) {
                    // Warn on and remove invalid source files (if nonull was set).
                    if (!grunt.file.exists(filepath)) {
                        grunt.log.warn('Source file "' + filepath + '" not found.');
                        return false;
                    }

                    return true;
                })
                    .map(grunt.file.read)
                    .join(grunt.util.normalizelf(grunt.util.linefeed));

            try {
                while( ( tempArray = scriptRegex.exec(max) ) ) {
                    grunt.log.writeln('tempArray[2]\n' + tempArray[2]);
//                    scriptBody.push.apply( scriptBody, tempArray );
                }

                max = max.replace( scriptRegex, function( all, g1, g2, g3 ) {
                    return g1 + uglify.parse( g2, {} ).print_to_string() + g3;
                });
                grunt.log.writeln('max\n' + max);
            } catch (err) {
                grunt.warn(file.src + '\n' + err);
            }

            try {
                min = pd.xmlmin(max, options.preserveComments);
            } catch (err) {
                grunt.warn(file.src + '\n' + err);
            }

            if (min.length < 1) {
                grunt.log.warn('Destination not written because minified XML was empty.');
            } else {
                grunt.file.write(file.dest, min);
                grunt.log.writeln('File "' + file.dest + '" created.');
                helper.minMaxInfo(min, max);
            }
        });
    });
};
<commit_msg>event script 도 처리<commit_after>/*
 * grunt-contrib-websquaremin
 * https://github.com/inswave/grunt-contrib-websquaremin
 *
 * Copyright (c) 2013 inswave
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
    'use strict';

    var pd = require('pretty-data').pd,
        helper = require('grunt-lib-contrib').init(grunt),
        uglify = require('uglify-js');

    grunt.registerMultiTask('websquaremin', 'Minify WebSquare XML', function() {
        var options = this.options({
			preserveComments: false
		});

        this.files.forEach(function (file) {
            var scriptRegex = /(<script[\s\S]*?type=[\"\']javascript[\"\'][\s\S]*?><!\[CDATA\[)([\s\S]*?)(\]\]><\/script>)/ig,
                min,
                max = file.src.filter(function(filepath) {
                    // Warn on and remove invalid source files (if nonull was set).
                    if (!grunt.file.exists(filepath)) {
                        grunt.log.warn('Source file "' + filepath + '" not found.');
                        return false;
                    }

                    return true;
                })
                    .map(grunt.file.read)
                    .join(grunt.util.normalizelf(grunt.util.linefeed));

            try {
                max = max.replace( scriptRegex, function( all, g1, g2, g3 ) {
                    return g1 + uglify.parse( g2, {} ).print_to_string() + g3;
                });
            } catch (err) {
                grunt.warn(file.src + '\n' + err);
            }

            try {
                min = pd.xmlmin(max, options.preserveComments);
            } catch (err) {
                grunt.warn(file.src + '\n' + err);
            }

            if (min.length < 1) {
                grunt.log.warn('Destination not written because minified XML was empty.');
            } else {
                grunt.file.write(file.dest, min);
                grunt.log.writeln('File "' + file.dest + '" created.');
                helper.minMaxInfo(min, max);
            }
        });
    });
};
<|endoftext|>


<commit_before>describe("AstroPNG", function(){
  var ap, controlParameters, controlXNans, controlYNans, controlImageData;

  beforeEach(function () {
    controlParameters = [4.74645138e+00, 6.40677869e-01, 9.19648933e+00, 3.50437552e-01, 6.68422365e+00, 1.55459598e-01, 3.45721102e+00, 7.64741004e-01, 4.70446157e+00, 4.83958751e-01, 7.82636926e-04, 4.67643142e-01];
    controlXNans = [2, 5];
    controlYNans = [3, 3];
    controlImageData = [
      9.10320816e+01, 7.62198029e+01, 2.62453003e+01,
      4.74645138e+00, 7.36081848e+01, 3.28234215e+01,
      8.46166916e+01, 5.26928787e+01, 9.19648933e+00,
      6.53918991e+01, 4.15999374e+01, 7.01190567e+01,
      3.83415642e+01, 6.68422365e+00, 4.17485962e+01,
      6.86772690e+01, 5.88976631e+01, 9.30436478e+01,
      8.30965347e+01, 3.45721102e+00, Number.NaN,
      5.29700203e+01, 6.71149368e+01, Number.NaN,
      4.70446157e+00, 6.78864746e+01, 6.79296417e+01,
      9.34692917e+01, 3.83502083e+01, 5.19416389e+01,
      7.82636926e-04, 1.31537790e+01, 7.55605316e+01,
      4.58650131e+01, 5.32767220e+01, 2.18959179e+01
    ];

    var imageSource = "iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGEAAAAACVN2zXAAAFYGZJVFNTSU1QTEUgID0gICAgICAgICAgICAgICAgICAgIFQgLyBjb25mb3JtcyB0byBGSVRTIHN0YW5kYXJkICAgICAgICAgICAgICAgICAgICAgIApCSVRQSVggID0gICAgICAgICAgICAgICAgICAtMzIgLyBhcnJheSBkYXRhIHR5cGUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApOQVhJUyAgID0gICAgICAgICAgICAgICAgICAgIDIgLyBudW1iZXIgb2YgYXJyYXkgZGltZW5zaW9ucyAgICAgICAgICAgICAgICAgICAgIApOQVhJUzEgID0gICAgICAgICAgICAgICAgICAgIDYgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApOQVhJUzIgID0gICAgICAgICAgICAgICAgICAgIDYgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlBJWDEgID0gICAgICAgICAgICAgICAgICAyLjUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlBJWDIgID0gICAgICAgICAgICAgICAgICAyLjUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlZBTDEgID0gICAgICAgICAgIDIxMC44MDE4NjggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlZBTDIgID0gICAgICAgICAgICA1NC4zNDgxNzEgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDFfMSAgID0gICAgICAgIC0wLjAwMDI3OTgwOTQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDFfMiAgID0gICAgICAgICAgMS41NjM2NEUtMDUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDJfMSAgID0gICAgICAgICAgMS41NTgyM0UtMDUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDJfMiAgID0gICAgICAgICAwLjAwMDI3OTE5MDIgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVFlQRTEgID0gJ1JBLS0tVEFOJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVFlQRTIgID0gJ0RFQy0tVEFOJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVU5JVDEgID0gJ2RlZyAgICAgJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVU5JVDIgID0gJ2RlZyAgICAgJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGYK3rwAAAAwcUFOVECX4u4/JAN3QRMk0j6zbI1A1eUpPh8wzUBdQvI/Q8YRQJaK8z73yXE6TSngPu9u7B6iW8QAAAAIbkFOUwADAAMAAgAFY3q1WgAAAEtJREFUeJxjYGhjyGdQYmBgyGHQYWC4zlADZC5kiGFYx8BwBsh8yNjPGMCkzcCQwQACjgzBYJqhmaGJYQeDK0MSiCMD1JHEUMSgDwD6bQyJnTTvCgAAAABJRU5ErkJggg=="
    var decodedData = window.atob(imageSource);
    ap = new AstroPNG(decodedData);

    this.addMatchers({
        toBeBetween: function (rangeFloor, rangeCeiling) {
            if (rangeFloor > rangeCeiling) {
                var temp = rangeFloor;
                rangeFloor = rangeCeiling;
                rangeCeiling = temp;
            }
            return this.actual > rangeFloor && this.actual < rangeCeiling;
        }
    });
  });

  it("can read the IHDR chunk", function() {
    expect(ap.width).toEqual(6);
    expect(ap.height).toEqual(6);
    expect(ap.bitDepth).toEqual(16);
  });

  it("can read the FITS header", function() {
    header = ap.header;

    expect(header['SIMPLE']).toEqual('T');
    expect(header['BITPIX']).toEqual('-32');
    expect(header['NAXIS']).toEqual('2');
    expect(header['NAXIS1']).toEqual('6');
    expect(header['NAXIS2']).toEqual('6');
    expect(header['CRPIX1']).toEqual('2.5');
    expect(header['CRPIX2']).toEqual('2.5');
    expect(header['CRVAL1']).toEqual('210.801868');
    expect(header['CRVAL2']).toEqual('54.348171');
    expect(header['CD1_1']).toEqual('-0.0002798094');
    expect(header['CD1_2']).toEqual('1.56364E-05');
    expect(header['CD2_1']).toEqual('1.55823E-05');
    expect(header['CD2_2']).toEqual('0.0002791902');
    expect(header['CTYPE1']).toEqual('RA---TAN');
    expect(header['CTYPE2']).toEqual('DEC--TAN');
    expect(header['CUNIT1']).toEqual('deg');
    expect(header['CUNIT2']).toEqual('deg');
  });

  it("can read the quantization parameters", function() {
    var i;
    var parameters = ap.quantizationParameters;
    var precision = 6;
    var num_tiles = 6;

    for (i = 0; i < 2*num_tiles; i += 1)
      expect(parameters[i]).toBeCloseTo(controlParameters[i], precision);
  });

  it("can read the NAN locations", function() {
    var i;
    var xNaNs = ap.xNaN;
    var yNaNs = ap.yNaN

    for (i = 0; i < xNaNs.length; i += 1) {
      expect(xNaNs[i]).toEqual(controlXNans[i]);
      expect(yNaNs[i]).toEqual(controlYNans[i]);
    }
  });

  it("can read line by line of float image data", function() {
    var i, j, row, index;
    var tolerance = 0.5;

    for (j = 0; j < ap.height; j += 1) {
      row = ap.readLine();
      for (i = 0; i < ap.width; i += 1) {
        index = j * ap.width + i;
        if (isNaN(controlImageData[index])) {
          expect(isNaN(row[i])).toBeTruthy();
        } else {
          expect(row[i]).toBeBetween(controlImageData[index] - tolerance, controlImageData[index] + tolerance);
        }
      }
    }
  });

  it("can read all float image data", function() {
    var i;
    var tolerance = 0.5;

    ap.readImageData();
    for (i = 0; i < ap.imageData.length; i += 1) {
      if (isNaN(controlImageData[i])) {
        expect(isNaN(ap.imageData[i])).toBeTruthy();
      } else {
        expect(ap.imageData[i]).toBeBetween(controlImageData[i] - tolerance, controlImageData[i] + tolerance);
      }
    }
  });

  it("can compute image statistics", function() {
    var tolerance = 0.5;
    var precision = 6;

    ap.computeStatistics();
    expect(ap.minimumPixel).toBeBetween(0.00078263693 - tolerance, 0.00078263693 + tolerance);
    expect(ap.maximumPixel).toBeBetween(93.469292 - tolerance, 93.469292 + tolerance);
    expect(ap.mean).toBeBetween(49.304658777573529 - tolerance, 49.304658777573529 + tolerance);
    expect(ap.std).toBeBetween(28.376188349694765 - tolerance, 28.376188349694765 + tolerance);
  });

});
<commit_msg>Fixed tests<commit_after>describe("AstroPNG", function(){
  var ap, controlParameters, controlXNans, controlYNans, controlImageData;

  beforeEach(function () {
    controlParameters = [4.74645138e+00, 6.40677869e-01, 9.19648933e+00, 3.50437552e-01, 6.68422365e+00, 1.55459598e-01, 3.45721102e+00, 7.64741004e-01, 4.70446157e+00, 4.83958751e-01, 7.82636926e-04, 4.67643142e-01];
    controlXNans = [2, 5];
    controlYNans = [3, 3];
    controlImageData = [
      9.10320816e+01, 7.62198029e+01, 2.62453003e+01,
      4.74645138e+00, 7.36081848e+01, 3.28234215e+01,
      8.46166916e+01, 5.26928787e+01, 9.19648933e+00,
      6.53918991e+01, 4.15999374e+01, 7.01190567e+01,
      3.83415642e+01, 6.68422365e+00, 4.17485962e+01,
      6.86772690e+01, 5.88976631e+01, 9.30436478e+01,
      8.30965347e+01, 3.45721102e+00, Number.NaN,
      5.29700203e+01, 6.71149368e+01, Number.NaN,
      4.70446157e+00, 6.78864746e+01, 6.79296417e+01,
      9.34692917e+01, 3.83502083e+01, 5.19416389e+01,
      7.82636926e-04, 1.31537790e+01, 7.55605316e+01,
      4.58650131e+01, 5.32767220e+01, 2.18959179e+01
    ];

    var imageSource = "iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGEAAAAACVN2zXAAAFYGZJVFNTSU1QTEUgID0gICAgICAgICAgICAgICAgICAgIFQgLyBjb25mb3JtcyB0byBGSVRTIHN0YW5kYXJkICAgICAgICAgICAgICAgICAgICAgIApCSVRQSVggID0gICAgICAgICAgICAgICAgICAtMzIgLyBhcnJheSBkYXRhIHR5cGUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApOQVhJUyAgID0gICAgICAgICAgICAgICAgICAgIDIgLyBudW1iZXIgb2YgYXJyYXkgZGltZW5zaW9ucyAgICAgICAgICAgICAgICAgICAgIApOQVhJUzEgID0gICAgICAgICAgICAgICAgICAgIDYgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApOQVhJUzIgID0gICAgICAgICAgICAgICAgICAgIDYgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlBJWDEgID0gICAgICAgICAgICAgICAgICAyLjUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlBJWDIgID0gICAgICAgICAgICAgICAgICAyLjUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlZBTDEgID0gICAgICAgICAgIDIxMC44MDE4NjggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDUlZBTDIgID0gICAgICAgICAgICA1NC4zNDgxNzEgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDFfMSAgID0gICAgICAgIC0wLjAwMDI3OTgwOTQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDFfMiAgID0gICAgICAgICAgMS41NjM2NEUtMDUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDJfMSAgID0gICAgICAgICAgMS41NTgyM0UtMDUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDRDJfMiAgID0gICAgICAgICAwLjAwMDI3OTE5MDIgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVFlQRTEgID0gJ1JBLS0tVEFOJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVFlQRTIgID0gJ0RFQy0tVEFOJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVU5JVDEgID0gJ2RlZyAgICAgJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIApDVU5JVDIgID0gJ2RlZyAgICAgJyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGYK3rwAAAAwcUFOVECX4u4/JAN3QRMk0j6zbI1A1eUpPh8wzUBdQvI/Q8YRQJaK8z73yXE6TSngPu9u7B6iW8QAAAAIbkFOUwADAAMAAgAFY3q1WgAAAEtJREFUeJxjYGhjyGdQYmBgyGHQYWC4zlADZC5kiGFYx8BwBsh8yNjPGMCkzcCQwQACjgzBYJqhmaGJYQeDK0MSiCMD1JHEUMSgDwD6bQyJnTTvCgAAAABJRU5ErkJggg=="
    var decodedData = window.atob(imageSource);
    ap = new AstroPNG(decodedData);

    this.addMatchers({
        toBeBetween: function (rangeFloor, rangeCeiling) {
            if (rangeFloor > rangeCeiling) {
                var temp = rangeFloor;
                rangeFloor = rangeCeiling;
                rangeCeiling = temp;
            }
            return this.actual > rangeFloor && this.actual < rangeCeiling;
        }
    });
  });

  it("can read the IHDR chunk", function() {
    expect(ap.width).toEqual(6);
    expect(ap.height).toEqual(6);
    expect(ap.bitDepth).toEqual(16);
  });

  it("can read the FITS header", function() {
    header = ap.header;

    expect(header['SIMPLE']).toEqual('T');
    expect(header['BITPIX']).toEqual('-32');
    expect(header['NAXIS']).toEqual('2');
    expect(header['NAXIS1']).toEqual('6');
    expect(header['NAXIS2']).toEqual('6');
    expect(header['CRPIX1']).toEqual('2.5');
    expect(header['CRPIX2']).toEqual('2.5');
    expect(header['CRVAL1']).toEqual('210.801868');
    expect(header['CRVAL2']).toEqual('54.348171');
    expect(header['CD1_1']).toEqual('-0.0002798094');
    expect(header['CD1_2']).toEqual('1.56364E-05');
    expect(header['CD2_1']).toEqual('1.55823E-05');
    expect(header['CD2_2']).toEqual('0.0002791902');
    expect(header['CTYPE1']).toEqual('RA---TAN');
    expect(header['CTYPE2']).toEqual('DEC--TAN');
    expect(header['CUNIT1']).toEqual('deg');
    expect(header['CUNIT2']).toEqual('deg');
  });

  it("can read the quantization parameters", function() {
    var i;
    var parameters = ap.quantizationParameters;
    var precision = 6;
    var num_tiles = 6;

    for (i = 0; i < 2*num_tiles; i += 1)
      expect(parameters[i]).toBeCloseTo(controlParameters[i], precision);
  });

  it("can read the NAN locations", function() {
    var i;
    var xNaNs = ap.xNaN;
    var yNaNs = ap.yNaN

    for (i = 0; i < xNaNs.length; i += 1) {
      expect(xNaNs[i]).toEqual(controlXNans[i]);
      expect(yNaNs[i]).toEqual(controlYNans[i]);
    }
  });

  it("can read all float image data", function() {
    var i, val;
    var tolerance = 0.5;

    for (j = 0; j < ap.height; j += 1)
      ap.readLine();
    for (i = 0; i < ap.imageData.length; i += 1) {
      if (isNaN(controlImageData[i])) {
        expect(isNaN(ap.imageData[i])).toBeTruthy();
      } else {
        val = ap.imageData[i];
        expect(val).toBeBetween(controlImageData[i] - tolerance, controlImageData[i] + tolerance);
        console.log(val);
      }
    }
  });

  it("can compute image statistics", function() {
    var tolerance = 0.5;
    var precision = 6;
    for (j = 0; j < ap.height; j += 1)
      ap.readLine();
    ap.computeStatistics();

    expect(ap.minimumPixel).toBeBetween(0.00078263693 - tolerance, 0.00078263693 + tolerance);
    expect(ap.maximumPixel).toBeBetween(93.469292 - tolerance, 93.469292 + tolerance);
    expect(ap.mean).toBeBetween(49.304658777573529 - tolerance, 49.304658777573529 + tolerance);
    expect(ap.std).toBeBetween(28.376188349694765 - tolerance, 28.376188349694765 + tolerance);
  });

});
<|endoftext|>


<commit_before>var Entries = require('../app/models/entries');
var Entry = require('../app/models/entry');
var helper = require('../app/helper');
var forEach = helper.forEach;

var identifiers = process.argv.slice(2);
var get = require('./blog/get');

if (!identifiers.length) throw 'No identifier passed to script';

var only = [];

forEach(identifiers, function(id, next){

  get(id, function(user, blog){

    only.push(blog);

    next();
  });

}, function(){

  forEach(only, function(blog, nextBlog){

    console.log();
    console.log('BLOG:', blog.id, blog.handle);
    console.log('----------------------------');

    Entries.each(blog.id, function(entry, next){

      if (entry.deleted) return next();

      Entry.build(blog, entry.path, function(err, newEntry){

        if (err && err.code === 'ENOENT') {
          console.warn(entry.path, 'has no local file on disk');
          return next();
        }

        // don't know
        if (err) {
          console.log('-----> REBUILD ERROR');
          console.log(err);
          if (err.stack) console.log(err.stack);
          if (err.trace) console.log(err.trace);
          return next();
        }

        Entry.set(blog.id, entry.path, newEntry, function(err){

          if (err) throw err;

          next();
        });
      });
    }, nextBlog);
  }, process.exit);
});<commit_msg>logging to rebuild script<commit_after>var Entries = require('../app/models/entries');
var Entry = require('../app/models/entry');
var helper = require('../app/helper');
var forEach = helper.forEach;

var identifiers = process.argv.slice(2);
var get = require('./blog/get');

if (!identifiers.length) throw 'No identifier passed to script';

var only = [];

forEach(identifiers, function(id, next){

  get(id, function(user, blog){

    only.push(blog);

    next();
  });

}, function(){

  forEach(only, function(blog, nextBlog){

    console.log();
    console.log('BLOG:', blog.id, blog.handle);
    console.log('----------------------------');

    Entries.each(blog.id, function(entry, next){

      if (entry.deleted) return next();

      Entry.build(blog, entry.path, function(err, newEntry){

        if (err && err.code === 'ENOENT') {
          console.warn(entry.path, 'has no local file on disk');
          return next();
        }

        // don't know
        if (err) {
          console.log('-----> REBUILD ERROR');
          console.log(err);
          if (err.stack) console.log(err.stack);
          if (err.trace) console.log(err.trace);
          return next();
        }

        Entry.set(blog.id, entry.path, newEntry, function(err){

          if (err) throw err;

          console.log(entry.path, 'was rebuilt');
          next();
        });
      });
    }, nextBlog);
  }, process.exit);
});<|endoftext|>


<commit_before>
var util = require('./util');
var argv = require('minimist')(process.argv.slice(2));

if(argv._ && argv._.length > 0) //look release build
{

    var version;
    var cmd = "npm version --no-git-tag-version " + argv._[0];

    util.series(["npm test",

        "npm run build-release"],function(err){

        if(err)
        {
            console.log(err);
            process.exit(1);
        }
        else
        {
            require("child_process").exec(cmd,function(error,stdout,stdbffr){

                version = stdout.toString("utf8");
                version.replace(/(\r\n|\n|\r)/gm,"");

                if(error)
                {
                    console.log(err);
                    process.exit(1);
                }
                else
                {
                    util.series([

                        ["git add -A","Adding all the changed files after versioning"],

                        ['git commit -m "release"',"all changes committed..."],

                        ["git push","Pushed all file changes to remote repo.."],

                        ["git checkout -b release","Created local 'release' branch..."],

                        ["git add --f dist","dist folder added to release branch..."],

                        ['git commit -m "release"',"all changes committed..."],

                        ['git tag ' +version,"created version tag..."],

                        ['git push --tags', "all tags pushed..."],

                        ['git checkout master',"checked out master branch.."],

                        ['git branch -D release',"release branch deleted..release Done!!"]

                    ],function(err){

                        if(err)
                        {
                            util.exec("git branch -D release",function(error){
                                console.log(err);
                                process.exit(1);
                            })
                        }

                        process.exit(0);
                    });
                }

            });
        }
    });

}
else
{
    console.log("\n Cannot Recognize the type of release. Please see instructions below");
    console.log('\n Options:\n\n raapid-release [release-type]' +
        '      --- Give type of release:  major | minor | patch | premajor | preminor | prepatch | prerelease\n'
    );

    process.exit(1);
}

<commit_msg>fixing release script 1.0<commit_after>
var util = require('./util');
var argv = require('minimist')(process.argv.slice(2));

if(argv._ && argv._.length > 0) //look release build
{

    var version;
    var cmd = "npm version --no-git-tag-version " + argv._[0];

    util.series(["npm test",

        "npm run build-release"],function(err){

        if(err)
        {
            console.log(err);
            process.exit(1);
        }
        else
        {
            require("child_process").exec(cmd,function(error,stdout,stdbffr){

                var version = v+require("./package.json").version;
                console.log(version);

                if(error)
                {
                    console.log(err);
                    process.exit(1);
                }
                else
                {
                    util.series([

                        ["git add -A","Adding all the changed files after versioning"],

                        ['git commit -m "release"',"all changes committed..."],

                        ["git push","Pushed all file changes to remote repo.."],

                        ["git checkout -b release","Created local 'release' branch..."],

                        ["git add --f dist","dist folder added to release branch..."],

                        ['git commit -m "release"',"all changes committed..."],

                        ['git tag ' +version,"created version tag..."],

                        ['git push --tags', "all tags pushed..."],

                        ['git checkout master',"checked out master branch.."],

                        ['git branch -D release',"release branch deleted..release Done!!"]

                    ],function(err){

                        if(err)
                        {
                            util.series(["git checkout master","git branch -D release"],function(error){
                                console.log(err);
                                process.exit(1);
                            })
                        }

                        process.exit(0);
                    });
                }

            });
        }
    });

}
else
{
    console.log("\n Cannot Recognize the type of release. Please see instructions below");
    console.log('\n Options:\n\n raapid-release [release-type]' +
        '      --- Give type of release:  major | minor | patch | premajor | preminor | prepatch | prerelease\n'
    );

    process.exit(1);
}

<|endoftext|>


<commit_before>/* tslint:disable: no-console */
const exec = require('shell-utils').exec;
const semver = require('semver');
const fs = require('fs');
const _ = require('lodash');
const path = require('path');

// Workaround JS
const isRelease = process.env.RELEASE_BUILD === 'true';

const ONLY_ON_BRANCH = 'origin/master';
const VERSION_TAG = isRelease ? 'latest' : 'snapshot';
const VERSION_INC = 'patch';

function run() {
    if (!validateEnv()) {
        return;
    }
    setupGit();
    createNpmRc();
    versionTagAndPublish();
}

function validateEnv() {
    if (!process.env.JENKINS_CI) {
        throw new Error(`releasing is only available from CI`);
    }

    if (!process.env.JENKINS_MASTER) {
        console.log(`not publishing on a different build`);
        return false;
    }

    if (process.env.GIT_BRANCH !== ONLY_ON_BRANCH) {
        console.log(`not publishing on branch ${process.env.GIT_BRANCH}`);
        return false;
    }

    return true;
}

function setupGit() {
    exec.execSyncSilent(`git config --global push.default simple`);
    exec.execSyncSilent(`git config --global user.email "${process.env.GIT_EMAIL}"`);
    exec.execSyncSilent(`git config --global user.name "${process.env.GIT_USER}"`);
    const remoteUrl = new RegExp(`https?://(\\S+)`).exec(exec.execSyncRead(`git remote -v`))[1];
    exec.execSyncSilent(`git remote add deploy "https://${process.env.GIT_USER}:${process.env.GIT_TOKEN}@${remoteUrl}"`);
    // exec.execSync(`git checkout ${ONLY_ON_BRANCH}`);
}

function createNpmRc() {
    exec.execSync(`rm -f package-lock.json`);
    const content = `
email=\${NPM_EMAIL}
//registry.npmjs.org/:_authToken=\${NPM_TOKEN}
`;
    fs.writeFileSync(`.npmrc`, content);
}

function versionTagAndPublish() {
    const packageVersion = semver.clean(process.env.npm_package_version);
    console.log(`package version: ${packageVersion}`);

    const currentPublished = findCurrentPublishedVersion();
    console.log(`current published version: ${currentPublished}`);

    const version = isRelease
        ? process.env.VERSION
        : semver.gt(packageVersion, currentPublished)
            ? `${packageVersion}-snapshot.${process.env.BUILD_ID}`
            : `${currentPublished}-snapshot.${process.env.BUILD_ID}`;

    console.log(`Publishing version: ${version}`);

    tryPublishAndTag(version);
}

function findCurrentPublishedVersion() {
    return exec.execSyncRead(`npm view ${process.env.npm_package_name} dist-tags.latest`);
}

function tryPublishAndTag(version) {
    let theCandidate = version;
    for (let retry = 0; retry < 5; retry++) {
        try {
            tagAndPublish(theCandidate);
            console.log(`Released ${theCandidate}`);
            return;
        } catch (err) {
            const alreadyPublished = _.includes(err.toString(), 'You cannot publish over the previously published version');
            if (!alreadyPublished) {
                throw err;
            }
            console.log(`previously published. retrying with increased ${VERSION_INC}...`);
            theCandidate = semver.inc(theCandidate, VERSION_INC);
        }
    }
}

function tagAndPublish(newVersion) {
    console.log(`trying to publish ${newVersion}...`);
    exec.execSync(`npm --no-git-tag-version version ${newVersion}`);
    exec.execSync(`npm publish --tag ${VERSION_TAG}`);
    exec.execSync(`git tag -a ${newVersion} -m "${newVersion}"`);
    exec.execSyncSilent(`git push deploy ${newVersion} || true`);
    if (isRelease) {
      updatePackageJsonGit(newVersion);
    }
}

function getPackageJsonPath() {
    return `${process.cwd()}/package.json`;
}

function writePackageJson(packageJson) {
    fs.writeFileSync(getPackageJsonPath(), JSON.stringify(packageJson, null, 2));
}

function readPackageJson() {
    return JSON.parse(fs.readFileSync(getPackageJsonPath()));
}

function updatePackageJsonGit(version) {
    const packageJson = readPackageJson();
    packageJson.version = version;
    writePackageJson(packageJson);
    exec.execSync(`git add package.json`);
    exec.execSync(`git commit -m"Update package.json version to ${version} [ci skip]"`);
    exec.execSync(`git push`);
}

run();
<commit_msg>Update master checkout branch [ci skip]<commit_after>/* tslint:disable: no-console */
const exec = require('shell-utils').exec;
const semver = require('semver');
const fs = require('fs');
const _ = require('lodash');
const path = require('path');

// Workaround JS
const isRelease = process.env.RELEASE_BUILD === 'true';

const ONLY_ON_BRANCH = 'origin/master';
const VERSION_TAG = isRelease ? 'latest' : 'snapshot';
const VERSION_INC = 'patch';

function run() {
    if (!validateEnv()) {
        return;
    }
    setupGit();
    createNpmRc();
    versionTagAndPublish();
}

function validateEnv() {
    if (!process.env.JENKINS_CI) {
        throw new Error(`releasing is only available from CI`);
    }

    if (!process.env.JENKINS_MASTER) {
        console.log(`not publishing on a different build`);
        return false;
    }

    if (process.env.GIT_BRANCH !== ONLY_ON_BRANCH) {
        console.log(`not publishing on branch ${process.env.GIT_BRANCH}`);
        return false;
    }

    return true;
}

function setupGit() {
    exec.execSyncSilent(`git config --global push.default simple`);
    exec.execSyncSilent(`git config --global user.email "${process.env.GIT_EMAIL}"`);
    exec.execSyncSilent(`git config --global user.name "${process.env.GIT_USER}"`);
    const remoteUrl = new RegExp(`https?://(\\S+)`).exec(exec.execSyncRead(`git remote -v`))[1];
    exec.execSyncSilent(`git remote add deploy "https://${process.env.GIT_USER}:${process.env.GIT_TOKEN}@${remoteUrl}"`);
    // exec.execSync(`git checkout ${ONLY_ON_BRANCH}`);
}

function createNpmRc() {
    exec.execSync(`rm -f package-lock.json`);
    const content = `
email=\${NPM_EMAIL}
//registry.npmjs.org/:_authToken=\${NPM_TOKEN}
`;
    fs.writeFileSync(`.npmrc`, content);
}

function versionTagAndPublish() {
    const packageVersion = semver.clean(process.env.npm_package_version);
    console.log(`package version: ${packageVersion}`);

    const currentPublished = findCurrentPublishedVersion();
    console.log(`current published version: ${currentPublished}`);

    const version = isRelease
        ? process.env.VERSION
        : semver.gt(packageVersion, currentPublished)
            ? `${packageVersion}-snapshot.${process.env.BUILD_ID}`
            : `${currentPublished}-snapshot.${process.env.BUILD_ID}`;

    console.log(`Publishing version: ${version}`);

    tryPublishAndTag(version);
}

function findCurrentPublishedVersion() {
    return exec.execSyncRead(`npm view ${process.env.npm_package_name} dist-tags.latest`);
}

function tryPublishAndTag(version) {
    let theCandidate = version;
    for (let retry = 0; retry < 5; retry++) {
        try {
            tagAndPublish(theCandidate);
            console.log(`Released ${theCandidate}`);
            return;
        } catch (err) {
            const alreadyPublished = _.includes(err.toString(), 'You cannot publish over the previously published version');
            if (!alreadyPublished) {
                throw err;
            }
            console.log(`previously published. retrying with increased ${VERSION_INC}...`);
            theCandidate = semver.inc(theCandidate, VERSION_INC);
        }
    }
}

function tagAndPublish(newVersion) {
    console.log(`trying to publish ${newVersion}...`);
    exec.execSync(`npm --no-git-tag-version version ${newVersion}`);
    exec.execSync(`npm publish --tag ${VERSION_TAG}`);
    exec.execSync(`git tag -a ${newVersion} -m "${newVersion}"`);
    exec.execSyncSilent(`git push deploy ${newVersion} || true`);
    if (isRelease) {
      updatePackageJsonGit(newVersion);
    }
}

function getPackageJsonPath() {
    return `${process.cwd()}/package.json`;
}

function writePackageJson(packageJson) {
    fs.writeFileSync(getPackageJsonPath(), JSON.stringify(packageJson, null, 2));
}

function readPackageJson() {
    return JSON.parse(fs.readFileSync(getPackageJsonPath()));
}

function updatePackageJsonGit(version) {
    exec.execSync(`git checkout master`);
    const packageJson = readPackageJson();
    packageJson.version = version;
    writePackageJson(packageJson);
    exec.execSync(`git add package.json`);
    exec.execSync(`git commit -m"Update package.json version to ${version} [ci skip]"`);
    exec.execSync(`git push`);
}

run();
<|endoftext|>


<commit_before>class Zoom {
    constructor() {
        this.zoomUpperLimit = document.getElementById("zoomUpperLimit").innerText === "true";
        this.isWheelActionZoom = document.getElementById("wheelAction").innerText === "zoom";
        this.img = document.getElementById("image");
        this.imgContainer = document.getElementById("image-container");
        this.iconFit = document.getElementById("icon-fit");
        this.iconExpand = document.getElementById("icon-expand");
        this.naturalWidth = this.img.naturalWidth;
        this.naturalHeight = this.img.naturalHeight;
        this.status = undefined;
        let afterZoom = () => {
            this.setToggleIcon();
            saveStatus();
        }
        let resetZoom = () => {
            this.reset();
            this.setToggleIcon();
            saveStatus();
        }
        this.img.addEventListener("dblclick", () => {
            let mouseAt = this.getMousePointer();
            if (this.iconFit.style.display == "") {
                resetZoom();
            } else
                this.smoothZomm(100, mouseAt, afterZoom);
        })
        document.getElementById("btnZoomIn").addEventListener("click", () => {
            this.smoothZomm(this.status.zoom * 1.2, this.getWindowCenterMousePointer(), afterZoom);
        });
        document.getElementById("btnZoomOut").addEventListener("click", () => {
            this.smoothZomm(this.status.zoom / 1.2, this.getWindowCenterMousePointer(), afterZoom);
        });
        document.getElementById("btnZoomToggle").addEventListener("click", () => {
            if (this.iconFit.style.display == "") {
                resetZoom();
            } else
                this.smoothZomm(100, this.getWindowCenterMousePointer(), afterZoom);
        });
        document.body.addEventListener("mousewheel", () => {
            // console.log(event.ctrlKey, event.wheelDeltaX, event.wheelDeltaY);
            // scroll to zoom, or ctrl key pressed scroll
            if (this.isWheelActionZoom || event.ctrlKey) {
                // ctrlKey == true: pinch
                let delta = event.ctrlKey ? event.wheelDelta / 60 : event.wheelDelta / 12;
                let mouseAt = this.getMousePointer();
                if (this.zoomUpperLimit) {
                    this.setZoom(this.status.zoom + delta, mouseAt);
                } else {
                    // zoom level increase / decrease by 30% for each wheel scroll
                    this.setZoom(this.status.zoom * (delta / 50 + 1), mouseAt);
                }
                this.setToggleIcon();
                saveStatus();
                if (event.preventDefault) event.preventDefault();
                return false;
            }
        });
        window.addEventListener("mouseup", () => {
            this.status.x = document.body.scrollLeft;
            this.status.y = document.body.scrollTop;
            saveStatus();
        });
        window.addEventListener("resize", () => {
            this.reset();
            saveStatus();
        });
    }
    reset() {
        let mp = this.getWindowCenterMousePointer();
        mp.imageX = 0.5;
        mp.imageY = 0.5;
        this.setZoom(0, mp);
    }
    smoothZomm(to, mouseAt, callback, ...args) {
        mouseAt = mouseAt || this.getMousePointer();
        let winWidth = window.innerWidth;
        let minWidth = winWidth < this.naturalWidth ? winWidth : this.naturalWidth;
        let minZoom = minWidth / this.naturalWidth * 100;
        if (to < minZoom) to = minZoom;
        let from = this.status.zoom;
        if (from == to) return;
        const interval = 10;
        const level = 10;
        const delta = (to - from) / level;
        for (let i = 1; i <= level; i++) {
            setTimeout(() => {
                if (this.setZoom(from + delta * i, mouseAt) && callback) callback(...args);
            }, interval * i);
        }
    }
    setZoom(zoom, point) {
        let winWidth = window.innerWidth;
        let winHeight = window.innerHeight;
        let minWidth = winWidth < this.naturalWidth ? winWidth : this.naturalWidth;
        let minZoom = minWidth / this.naturalWidth * 100;
        const maxZoom = 100;

        if (this.zoomUpperLimit && zoom > maxZoom) zoom = maxZoom;
        if (zoom < minZoom) zoom = minZoom;

        let status = this.getPointZoomStatus(zoom, point);
        this.applyStatus(status);
        return true;
    }
    getPointZoomStatus(zoom, point) {
        let imgWidth = this.naturalWidth * zoom / 100;
        let imgHeight = this.naturalHeight * zoom / 100;

        let blankRight = window.innerWidth - imgWidth * (1 - point.imageX) - point.x;
        let blankLeft = point.x - imgWidth * point.imageX;
        let blankBottom = window.innerHeight - imgHeight * (1 - point.imageY) - point.y;
        let blankTop = point.y - imgHeight * point.imageY;
        blankRight = blankRight < 0 ? 0 : blankRight;
        blankLeft = blankLeft < 0 ? 0 : blankLeft;
        blankBottom = blankBottom < 0 ? 0 : blankBottom;
        blankTop = blankTop < 0 ? 0 : blankTop;

        let status = {};
        status.blankX = Math.max(blankLeft, blankRight);
        status.blankY = Math.max(blankBottom, blankTop);
        status.x = imgWidth * point.imageX + status.blankX - point.x;
        status.y = imgHeight * point.imageY + status.blankY - point.y;
        status.zoom = zoom
        return status;
    }
    applyStatus(status) {
        // console.log("apply status:", status);
        let imgWidth = this.naturalWidth * status.zoom / 100;
        let imgHeight = this.naturalHeight * status.zoom / 100;
        this.img.style.width = imgWidth + 'px';
        this.imgContainer.style.width = (status.blankX * 2 + imgWidth) + 'px'
        this.imgContainer.style.height = (status.blankY * 2 + imgHeight) + "px";
        document.body.scrollLeft = status.x;
        document.body.scrollTop = status.y;
        this.status = status;
    }
    getMousePointer(x, y) {
        let e = event || window.event;
        let clientX = x || e.clientX
        let clientY = y || e.clientY
        let mouseAt = {
            x: clientX,
            y: clientY,
            imageX: (clientX + document.body.scrollLeft - this.img.x) / this.img.clientWidth,
            imageY: (clientY + document.body.scrollTop - this.img.y) / this.img.clientHeight,
        }
        return mouseAt;
    }
    getWindowCenterMousePointer() {
        let x = window.innerWidth / 2;
        let y = window.innerHeight / 2;
        return this.getMousePointer(x, y);
    }
    setToggleIcon() {
        if (this.img.clientWidth >= this.naturalWidth || this.status.x != 0 || this.status.y != 0) {
            this.iconFit.style.display = "";
            this.iconExpand.style.display = "none";
        } else {
            this.iconFit.style.display = "none";
            this.iconExpand.style.display = "";
        }
    }
}<commit_msg>fix not calc fix/expand after restore status<commit_after>class Zoom {
    constructor() {
        this.zoomUpperLimit = document.getElementById("zoomUpperLimit").innerText === "true";
        this.isWheelActionZoom = document.getElementById("wheelAction").innerText === "zoom";
        this.img = document.getElementById("image");
        this.imgContainer = document.getElementById("image-container");
        this.iconFit = document.getElementById("icon-fit");
        this.iconExpand = document.getElementById("icon-expand");
        this.naturalWidth = this.img.naturalWidth;
        this.naturalHeight = this.img.naturalHeight;
        this.status = undefined;
        let afterZoom = () => {
            saveStatus();
        }
        let resetZoom = () => {
            this.reset();
            saveStatus();
        }
        this.img.addEventListener("dblclick", () => {
            let mouseAt = this.getMousePointer();
            if (this.iconFit.style.display == "") {
                resetZoom();
            } else
                this.smoothZomm(100, mouseAt, afterZoom);
        })
        document.getElementById("btnZoomIn").addEventListener("click", () => {
            this.smoothZomm(this.status.zoom * 1.2, this.getWindowCenterMousePointer(), afterZoom);
        });
        document.getElementById("btnZoomOut").addEventListener("click", () => {
            this.smoothZomm(this.status.zoom / 1.2, this.getWindowCenterMousePointer(), afterZoom);
        });
        document.getElementById("btnZoomToggle").addEventListener("click", () => {
            if (this.iconFit.style.display == "") {
                resetZoom();
            } else
                this.smoothZomm(100, this.getWindowCenterMousePointer(), afterZoom);
        });
        document.body.addEventListener("mousewheel", () => {
            // console.log(event.ctrlKey, event.wheelDeltaX, event.wheelDeltaY);
            // scroll to zoom, or ctrl key pressed scroll
            if (this.isWheelActionZoom || event.ctrlKey) {
                // ctrlKey == true: pinch
                let delta = event.ctrlKey ? event.wheelDelta / 60 : event.wheelDelta / 12;
                let mouseAt = this.getMousePointer();
                if (this.zoomUpperLimit) {
                    this.setZoom(this.status.zoom + delta, mouseAt);
                } else {
                    // zoom level increase / decrease by 30% for each wheel scroll
                    this.setZoom(this.status.zoom * (delta / 50 + 1), mouseAt);
                }
                saveStatus();
                if (event.preventDefault) event.preventDefault();
                return false;
            }
        });
        window.addEventListener("mouseup", () => {
            this.status.x = document.body.scrollLeft;
            this.status.y = document.body.scrollTop;
            saveStatus();
        });
        window.addEventListener("resize", () => {
            this.reset();
            saveStatus();
        });
    }
    reset() {
        let mp = this.getWindowCenterMousePointer();
        mp.imageX = 0.5;
        mp.imageY = 0.5;
        this.setZoom(0, mp);
    }
    smoothZomm(to, mouseAt, callback, ...args) {
        mouseAt = mouseAt || this.getMousePointer();
        let winWidth = window.innerWidth;
        let minWidth = winWidth < this.naturalWidth ? winWidth : this.naturalWidth;
        let minZoom = minWidth / this.naturalWidth * 100;
        if (to < minZoom) to = minZoom;
        let from = this.status.zoom;
        if (from == to) return;
        const interval = 10;
        const level = 10;
        const delta = (to - from) / level;
        for (let i = 1; i <= level; i++) {
            setTimeout(() => {
                if (this.setZoom(from + delta * i, mouseAt) && callback) callback(...args);
            }, interval * i);
        }
    }
    setZoom(zoom, point) {
        let winWidth = window.innerWidth;
        let winHeight = window.innerHeight;
        let minWidth = winWidth < this.naturalWidth ? winWidth : this.naturalWidth;
        let minZoom = minWidth / this.naturalWidth * 100;
        const maxZoom = 100;

        if (this.zoomUpperLimit && zoom > maxZoom) zoom = maxZoom;
        if (zoom < minZoom) zoom = minZoom;

        let status = this.getPointZoomStatus(zoom, point);
        this.applyStatus(status);
        return true;
    }
    getPointZoomStatus(zoom, point) {
        let imgWidth = this.naturalWidth * zoom / 100;
        let imgHeight = this.naturalHeight * zoom / 100;

        let blankRight = window.innerWidth - imgWidth * (1 - point.imageX) - point.x;
        let blankLeft = point.x - imgWidth * point.imageX;
        let blankBottom = window.innerHeight - imgHeight * (1 - point.imageY) - point.y;
        let blankTop = point.y - imgHeight * point.imageY;
        blankRight = blankRight < 0 ? 0 : blankRight;
        blankLeft = blankLeft < 0 ? 0 : blankLeft;
        blankBottom = blankBottom < 0 ? 0 : blankBottom;
        blankTop = blankTop < 0 ? 0 : blankTop;

        let status = {};
        status.blankX = Math.max(blankLeft, blankRight);
        status.blankY = Math.max(blankBottom, blankTop);
        status.x = imgWidth * point.imageX + status.blankX - point.x;
        status.y = imgHeight * point.imageY + status.blankY - point.y;
        status.zoom = zoom
        return status;
    }
    applyStatus(status) {
        // console.log("apply status:", status);
        let imgWidth = this.naturalWidth * status.zoom / 100;
        let imgHeight = this.naturalHeight * status.zoom / 100;
        this.img.style.width = imgWidth + 'px';
        this.imgContainer.style.width = (status.blankX * 2 + imgWidth) + 'px'
        this.imgContainer.style.height = (status.blankY * 2 + imgHeight) + "px";
        document.body.scrollLeft = status.x;
        document.body.scrollTop = status.y;
        this.status = status;
        this.setToggleIcon();
    }
    getMousePointer(x, y) {
        let e = event || window.event;
        let clientX = x || e.clientX
        let clientY = y || e.clientY
        let mouseAt = {
            x: clientX,
            y: clientY,
            imageX: (clientX + document.body.scrollLeft - this.img.x) / this.img.clientWidth,
            imageY: (clientY + document.body.scrollTop - this.img.y) / this.img.clientHeight,
        }
        return mouseAt;
    }
    getWindowCenterMousePointer() {
        let x = window.innerWidth / 2;
        let y = window.innerHeight / 2;
        return this.getMousePointer(x, y);
    }
    setToggleIcon() {
        if (this.img.clientWidth >= this.naturalWidth || this.status.x != 0 || this.status.y != 0) {
            this.iconFit.style.display = "";
            this.iconExpand.style.display = "none";
        } else {
            this.iconFit.style.display = "none";
            this.iconExpand.style.display = "";
        }
    }
}<|endoftext|>


<commit_before>export const onPreBuild = function({
  utils: {
    status: { show },
    git,
  },
  netlifyConfig,
}) {
  console.log(git)
  show({ summary: 'Test' })
  netlifyConfig.redirects.push({ from: '/one', to: '/two' })
  netlifyConfig.headers.push({ for: '/couleur', values: { BLUE: 'bleu' } })
}
<commit_msg>Revert "Test"<commit_after>export const onPreBuild = function({
  utils: {
    status: { show },
  },
  netlifyConfig,
}) {
  show({ summary: 'Test' })
  netlifyConfig.redirects.push({ from: '/one', to: '/two' })
  netlifyConfig.headers.push({ for: '/couleur', values: { BLUE: 'bleu' } })
}
<|endoftext|>


<commit_before>import Orbit from '../../src';
import { Promise } from 'rsvp';

Orbit.Promise = Promise;

Orbit.pluralize = function(original) {
  return original.match(/s$/) ? original : original + 's';
};

Orbit.singularize = function(original) {
  const match = original.match(/(.*)s$/);
  return match ? match[1] : original;
};
<commit_msg>Remove unnecessary setup of pluralize and singularize.<commit_after>import Orbit from '../../src';
import { Promise } from 'rsvp';

Orbit.Promise = Promise;
<|endoftext|>


<commit_before>(function(){
  CKEDITOR.plugins.add('btgrid', {
      lang: 'en',
      requires: 'widget,dialog',
      icons: 'btgrid',
      init: function(editor) {
       var maxGridColumns = 12;
       var lang = editor.lang.btgrid;

       CKEDITOR.dialog.add('btgrid',  this.path + 'dialogs/btgrid.js');

       editor.addContentsCss( this.path + 'styles/editor.css');
       // Add widget
       editor.ui.addButton('btgrid', {
         label: lang.createBtGrid,
         command: 'btgrid',
         icon: this.path + 'icons/btgrid.png'
       });
       editor.widgets.add('btgrid',
         {
           allowedContent: 'div(!btgrid);div(!row,!row-*);div(!col-*-*);div(!content)',
           requiredContent: 'div(btgrid)',
           parts: {
             btgrid: 'div.btgrid',
           },
           editables: {
             content: '',
           },
           template:
                   '
' +
                   '
',
           //button: lang.createBtGrid,
           dialog: 'btgrid',
           defaults: {
            //  colCount: 2,
            // rowCount: 1
          },
          // Before init.
           upcast: function(element) {
             return element.name == 'div' && element.hasClass('btgrid');
           },
           // initialize
           // Init function is useful after copy paste rebuild.
           init: function() {
             var rowNumber= 1;
             var rowCount = this.element.getChildCount();
             for (rowNumber; rowNumber <= rowCount;rowNumber++) {
               this.createEditable(maxGridColumns, rowNumber);
             }
           },
           // Prepare data
           data: function() {
             if (this.data.colCount && this.element.getChildCount() < 1) {
               var colCount = this.data.colCount;
               var rowCount = this.data.rowCount;
               var row = this.parts['btgrid'];
               for (var i= 1;i <= rowCount;i++) {
                 this.createGrid(colCount, row, i);
               }
             }
           },
           //Helper functions.
           // Create grid
           createGrid: function(colCount, row, rowNumber) {
             var content = '
';
             for (var i = 1; i <= colCount; i++) {
               content = content + '
' +
                                   '
' +
                                   '
Col ' + i + ' content area
' +
                                   '
' +
                                   '
';
             }
             content =content + '
';
             row.appendHtml(content);
             this.createEditable(colCount, rowNumber);
           },
           // Create editable.
           createEditable: function(colCount,rowNumber) {
             for (var i = 1; i <= colCount; i++) {
               this.initEditable( 'content'+ rowNumber + i, {
                  selector: '.row-'+ rowNumber +' > div:nth-child('+ i +') div.content'
                } );
              }
            }
          }
        );
      }
    }
  );

})();
<commit_msg>Add "ru" to languages list<commit_after>(function(){
  CKEDITOR.plugins.add('btgrid', {
      lang: 'en,ru',
      requires: 'widget,dialog',
      icons: 'btgrid',
      init: function(editor) {
       var maxGridColumns = 12;
       var lang = editor.lang.btgrid;

       CKEDITOR.dialog.add('btgrid',  this.path + 'dialogs/btgrid.js');

       editor.addContentsCss( this.path + 'styles/editor.css');
       // Add widget
       editor.ui.addButton('btgrid', {
         label: lang.createBtGrid,
         command: 'btgrid',
         icon: this.path + 'icons/btgrid.png'
       });
       editor.widgets.add('btgrid',
         {
           allowedContent: 'div(!btgrid);div(!row,!row-*);div(!col-*-*);div(!content)',
           requiredContent: 'div(btgrid)',
           parts: {
             btgrid: 'div.btgrid',
           },
           editables: {
             content: '',
           },
           template:
                   '
' +
                   '
',
           //button: lang.createBtGrid,
           dialog: 'btgrid',
           defaults: {
            //  colCount: 2,
            // rowCount: 1
          },
          // Before init.
           upcast: function(element) {
             return element.name == 'div' && element.hasClass('btgrid');
           },
           // initialize
           // Init function is useful after copy paste rebuild.
           init: function() {
             var rowNumber= 1;
             var rowCount = this.element.getChildCount();
             for (rowNumber; rowNumber <= rowCount;rowNumber++) {
               this.createEditable(maxGridColumns, rowNumber);
             }
           },
           // Prepare data
           data: function() {
             if (this.data.colCount && this.element.getChildCount() < 1) {
               var colCount = this.data.colCount;
               var rowCount = this.data.rowCount;
               var row = this.parts['btgrid'];
               for (var i= 1;i <= rowCount;i++) {
                 this.createGrid(colCount, row, i);
               }
             }
           },
           //Helper functions.
           // Create grid
           createGrid: function(colCount, row, rowNumber) {
             var content = '
';
             for (var i = 1; i <= colCount; i++) {
               content = content + '
' +
                                   '
' +
                                   '
Col ' + i + ' content area
' +
                                   '
' +
                                   '
';
             }
             content =content + '
';
             row.appendHtml(content);
             this.createEditable(colCount, rowNumber);
           },
           // Create editable.
           createEditable: function(colCount,rowNumber) {
             for (var i = 1; i <= colCount; i++) {
               this.initEditable( 'content'+ rowNumber + i, {
                  selector: '.row-'+ rowNumber +' > div:nth-child('+ i +') div.content'
                } );
              }
            }
          }
        );
      }
    }
  );

})();
<|endoftext|>


<commit_before>module.exports = function (name) {
  return {
    'name': `${name}`,
    'version': '1.0.0',
    'description': '',
    'main': 'index.js',
    'directories': {
      'test': 'test'
    },
    'dependencies': {
      'app-root-path': '^1.0.0',
      'ejs': '^2.4.1',
      'es5-shim': '^4.5.4',
      'express': '^4.13.4',
      'immutable': '^3.7.6',
      'node-sass': '^3.3.2',
      'pm2': '^1.0.0',
      'react': '^0.14.7',
      'react-dom': '^0.14.7',
      'react-router': '^2.0.0',
      'sal': '^1.1.13',
      'typescript': '^1.9.0-dev.20160210',
      'webpack': '^1.12.13',
      'welp': '^5.2.0',
      'winston': '^2.1.1'
    },
    'devDependencies': {
      'eslint': '^2.0.0-rc.0',
      'eslint-config-standard': '^5.1.0',
      'eslint-plugin-promise': '^1.0.8',
      'eslint-plugin-standard': '^1.3.2',
      'expect': '^1.14.0',
      'karma': '^0.13.8',
      'karma-browserstack-launcher': '^0.1.4',
      'karma-coverage': '^0.5.3',
      'karma-mocha': '^0.2.0',
      'karma-mocha-reporter': '^1.1.1',
      'karma-phantomjs-launcher': '^1.0.0',
      'karma-sourcemap-loader': '^0.3.5',
      'karma-webpack': '^1.7.0',
      'mocha': '^2.4.5',
      'phantomjs-prebuilt': '^2.1.6',
      'pre-commit': '^1.1.2'
    },
    'scripts': {
      'start': 'sal -pr',
      'test': 'NODE_ENV=test karma start ./config/karma.conf.js --single-run && mocha --timeout 10000'
    },
    'author': 'YOUR NAME HERE)',
    'license': 'MIT'
  }
}
<commit_msg>fixing prod build<commit_after>const sal_version = require('./../package.json').version
module.exports = function (name) {
  return {
    'name': `${name}`,
    'version': '1.0.0',
    'description': '',
    'main': 'index.js',
    'directories': {
      'test': 'test'
    },
    'dependencies': {
      'app-root-path': '^1.0.0',
      'ejs': '^2.4.1',
      'es5-shim': '^4.5.4',
      'express': '^4.13.4',
      'immutable': '^3.7.6',
      'node-sass': '^3.3.2',
      'pm2': '^1.0.0',
      'react': '^0.14.7',
      'react-dom': '^0.14.7',
      'react-router': '^2.0.0',
      'sal': `^${sal_version}`,
      'typescript': '^1.9.0-dev.20160210',
      'webpack': '^1.12.13',
      'welp': '^5.2.0',
      'winston': '^2.1.1'
    },
    'devDependencies': {
      'eslint': '^2.0.0-rc.0',
      'eslint-config-standard': '^5.1.0',
      'eslint-plugin-promise': '^1.0.8',
      'eslint-plugin-standard': '^1.3.2',
      'expect': '^1.14.0',
      'karma': '^0.13.8',
      'karma-browserstack-launcher': '^0.1.4',
      'karma-coverage': '^0.5.3',
      'karma-mocha': '^0.2.0',
      'karma-mocha-reporter': '^1.1.1',
      'karma-phantomjs-launcher': '^1.0.0',
      'karma-sourcemap-loader': '^0.3.5',
      'karma-webpack': '^1.7.0',
      'mocha': '^2.4.5',
      'phantomjs-prebuilt': '^2.1.6',
      'pre-commit': '^1.1.2'
    },
    'scripts': {
      'start': 'sal -pr',
      'test': 'NODE_ENV=test karma start ./config/karma.conf.js --single-run && mocha --timeout 10000'
    },
    'author': 'YOUR NAME HERE)',
    'license': 'MIT'
  }
}
<|endoftext|>


<commit_before>'use strict';
/* examples
   5d2e = (repeat-five-times (delete (repeat-two-times (from cursor to end of word))))
   2de = (repeat-two-times (delete (from cursor to end of word)))
   2e = (repeat-two-times (move-cursor (from cursor to end of word))) NB. implied "move" function
   2ce = (repeat-two-times (delete (from cursor to end of word)));(enter-insert-mode)
   ya) = (copy (from open-paren before cursor, to matching close paren after cursor, including the parens themselves))
 */
var Parser=(cur)=>{/* Convert keyboard events into Actions */
    var ParserCommand=()=>({c:'',p:''}),

        arrow=(dec)=>{
            switch(dec.code){
            case'D':cur.down(1);break;
            case'U':cur.up(1);break;
            case'R':cur.right(1,true);break;
            case'L':cur.left(1,true);break;
            default:break;
            }
        },

        insert=(t,dec)=>{
            var fd=0;// 'fd' escape sequence
            switch(dec.type){
            case'print':
                cur.ins(dec.code);cur.rowcol();
                if(dec.code==='f'){this.fd=-t;}
                if(dec.code==='d'&&this.fd<0&&t+this.fd<500){cur.esc(2);}
                if(dec.code==='['&&dec.mods[1]){cur.esc(1);}// 'C-['
                break;
            case'edit':
                if(dec.code==='B'){cur.del_backward();}// backspace
                else if(dec.code==='D'){cur.del_forward();}// forward delete
                break;
            case'escape':cur.esc();break;
            default:break;
            }
        },

        exec_atomic=(code)=>{
            var result=true;
            switch(code){
                // motions
            case'j':cur.down(1);break;
            case'k':cur.up(1);break;
            case'l':cur.right(1);break;
            case'h':cur.left(1);break;
            case'$':cur.to_eol();break;
            case'0':cur.to_bol();break;
            case'{':cur.backward_paragraph();break;
            case'}':cur.forward_paragraph();break;
            case'gg':cur.to_bob();break;
            case'G':cur.to_eob();break;
            case'b':cur.backward_word();break;
            case'e':cur.forward_word();break;
                // editing actions
            case'i':cur.insert_mode();break;
            case'a':cur.append_mode();break;
            case'x':cur.del_at_point();break;
            case'D':cur.del_to_eol();break;
                // leader key
            case' ':console.log('SPC-');break;// TODO SPC-prefixed functions a-la Spacemacs!
            default:result=false;break;
            }
            return result;
        },

        append_char=(d,c)=>{if(!(d.mods[0]||d.mods[1]||d.mods[2])){c.c+=d.code;}},// append non-shifted code

        modifier={type:'modifier',regex:/a|i/},
        motion={type:'motion',regex:/[beGhjklw$^]|gg|([fFtT].)/},
        repeat={type:'repeat',regex:/[1-9][0-9]*/},
        object={type:'object',regex:/[wWps(){}\[\]"'`]/},
        operator={type:'operator',regex:/[cdy]/},

        tokenize=(cmd)=>{
            var token_types=[modifier,motion,repeat,object,operator],
                rxmatch=(ro,s)=>{// (regex,string) -> [type, match, start, length]
                    var x=ro.regex.exec(s),y=[ro.type];
                    return y.concat(x?[x[0],x.index,x[0].length]:['',-1,0]);
                },
                bycolumn=(i)=>(x,y)=>x[i]<y[i]?-1:((x[i]>y[i])?1:0),
                consume=(arr,str)=>{/* build array of tokens until no match */
                    var tok=token_types.map(x=>rxmatch(x,str)).filter(x=>!x[2]);// first match
                    return(tok.length)?consume(arr.concat(tok),str.slice(tok[0][3])):arr;
                },
                hastype=(arr,type)=>arr.filter(x=>x[0]===type),
                ts=consume([],cmd).map(x=>[x[0],x[1]]),
                flat=ts.reduce((x,y)=>x.concat(y));
            /* if the resulting array has both an object and a motion:
               if there's a modifier:
               remove the motion; otherwise remove the object
            */
            if(flat.includes('motion')&&flat.includes('object')){
                ts=ts.filter(x=>x[0]!==(flat.includes('modifier')?'motion':'object'));
            }
            return ts;
        };

    return ({
        cmd:ParserCommand(),
        parse(t,dec){
            if(dec.type==='arrow'){arrow(dec);}// parse arrows in any mode
            if(cur.mode==='insert'){insert(t,dec);}
            else{
                append_char(dec,this.cmd);// build the command 1 char at a time
                if(exec_atomic(this.cmd.c)){this.cmd.c='';}// short-circuit if possible
                else{/* if the command contains a text object or motion, parse it */
                    if([motion,object].some(x=>x.regex.test(this.cmd.c))){

                        // tokenize
                        var tokens=tokenize(this.cmd.c);
                        console.log(JSON.stringify(tokens,null,4));

                        // TODO: parse the command
                        var times=parseInt(tokens[tokens.length-2][1]||1);
                        for(var i=0;i<times;++i){exec_atomic(dec.code);}

                        this.cmd={c:'',p:this.cmd.c};// keep last command in history, clear current one
                    }
                }
            }
        }
    });
};
<commit_msg>note that while tokenizing is done, parsing is not<commit_after>'use strict';
/* examples
   5d2e = (repeat-five-times (delete (repeat-two-times (from cursor to end of word))))
   2de = (repeat-two-times (delete (from cursor to end of word)))
   2e = (repeat-two-times (move-cursor (from cursor to end of word))) NB. implied "move" function
   2ce = (repeat-two-times (delete (from cursor to end of word)));(enter-insert-mode)
   ya) = (copy (from open-paren before cursor, to matching close paren after cursor, including the parens themselves))
 */
var Parser=(cur)=>{/* Convert keyboard events into Actions */
    var ParserCommand=()=>({c:'',p:''}),

        arrow=(dec)=>{
            switch(dec.code){
            case'D':cur.down(1);break;
            case'U':cur.up(1);break;
            case'R':cur.right(1,true);break;
            case'L':cur.left(1,true);break;
            default:break;
            }
        },

        insert=(t,dec)=>{
            var fd=0;// 'fd' escape sequence
            switch(dec.type){
            case'print':
                cur.ins(dec.code);cur.rowcol();
                if(dec.code==='f'){this.fd=-t;}
                if(dec.code==='d'&&this.fd<0&&t+this.fd<500){cur.esc(2);}
                if(dec.code==='['&&dec.mods[1]){cur.esc(1);}// 'C-['
                break;
            case'edit':
                if(dec.code==='B'){cur.del_backward();}// backspace
                else if(dec.code==='D'){cur.del_forward();}// forward delete
                break;
            case'escape':cur.esc();break;
            default:break;
            }
        },

        exec_one=(code)=>{
            var result=true;
            switch(code){
                // motions
            case'j':cur.down(1);break;
            case'k':cur.up(1);break;
            case'l':cur.right(1);break;
            case'h':cur.left(1);break;
            case'$':cur.to_eol();break;
            case'0':cur.to_bol();break;
            case'{':cur.backward_paragraph();break;
            case'}':cur.forward_paragraph();break;
            case'gg':cur.to_bob();break;
            case'G':cur.to_eob();break;
            case'b':cur.backward_word();break;
            case'e':cur.forward_word();break;
                // editing actions
            case'i':cur.insert_mode();break;
            case'a':cur.append_mode();break;
            case'x':cur.del_at_point();break;
            case'D':cur.del_to_eol();break;
                // leader key
            case' ':console.log('SPC-');break;// TODO SPC-prefixed functions a-la Spacemacs!
            default:result=false;break;
            }
            return result;
        },

        append_char=(d,c)=>{if(!(d.mods[0]||d.mods[1]||d.mods[2])){c.c+=d.code;}},// append non-shifted code

        modifier={type:'modifier',regex:/a|i/},
        motion={type:'motion',regex:/[beGhjklw$^]|gg|([fFtT].)/},
        repeat={type:'repeat',regex:/[1-9][0-9]*/},
        object={type:'object',regex:/[wWps()<>{}\[\]"'`]/},
        operator={type:'operator',regex:/[cdy]/},

        tokenize=(cmd)=>{
            var token_types=[modifier,motion,repeat,object,operator],
                rxmatch=(ro,s)=>{// (regex,string) -> [type, match, start, length]
                    var x=ro.regex.exec(s),y=[ro.type];
                    return y.concat(x?[x[0],x.index,x[0].length]:['',-1,0]);
                },
                bycolumn=(i)=>(x,y)=>x[i]<y[i]?-1:((x[i]>y[i])?1:0),
                consume=(arr,str)=>{/* build array of tokens until no match */
                    var tok=token_types.map(x=>rxmatch(x,str)).filter(x=>!x[2]);// first match
                    return(tok.length)?consume(arr.concat(tok),str.slice(tok[0][3])):arr;
                },
                hastype=(arr,type)=>arr.filter(x=>x[0]===type),
                ts=consume([],cmd).map(x=>[x[0],x[1]]),
                flat=ts.reduce((x,y)=>x.concat(y));
            /* if the resulting array has both an object and a motion, then:
               remove the (modifier?motion:object)
            */
            if(flat.includes('motion')&&flat.includes('object')){
                ts=ts.filter(x=>x[0]!==(flat.includes('modifier')?'motion':'object'));
            }
            return ts;
        },

        tree=(tokens)=>{
            // example:
            // test example sentence  with some normal words and a a a a a a bunch of short ones
            // 2y3e => test example sentence  with some normal
            //        (test example sentence)(with some normal) // yanked: (2 groups of (3e))
            var stack=[];
            tokens.slice().reverse().forEach(x=>{
                if(x[0]==='object'||x[0]==='motion'){stack.push(x);}// noun
                if(x[0]==='modifier'||x[0]==='repeat'||x[0]==='operator'){
                    stack.push(x.concat([stack.pop()]));
                }// verb
            });
            return stack;
        };
    return ({
        cmd:ParserCommand(),
        parse(t,dec){
            if(dec.type==='arrow'){arrow(dec);}// parse arrows in any mode
            if(cur.mode==='insert'){insert(t,dec);}
            else{
                append_char(dec,this.cmd);// build the command 1 char at a time
                if(exec_one(this.cmd.c)){this.cmd.c='';}// short-circuit if possible
                else{/* if the command contains a text object or motion, parse it */
                    if([motion,object].some(x=>x.regex.test(this.cmd.c))){

                        // tokenize
                        var tokens=tokenize(this.cmd.c);
                        console.log(JSON.stringify(tokens,null,2));
                        console.log(JSON.stringify(tree(tokens),null,2));
                        //console.log(JSON.stringify(tokens.slice().reverse().reduce((x,y)=>y.concat([x])),null,2));

                        // TODO: parse the command
                        // NOTE: once we have the tokens, we can apply rules, such as "rule: operator (motion|object)"
                        var times=parseInt(tokens[tokens.length-2][1]||1);
                        for(var i=0;i<times;++i){exec_one(tokens[tokens.length-1][1]);}

                        this.cmd={c:'',p:this.cmd.c};// keep last command in history, clear current one
                    }
                }
            }
        }
    });
};
<|endoftext|>