<commit_before>#!/usr/bin/env node

var async = require('async');
var argv = require('minimist')(process.argv.slice(2), {
  boolean: ['verbose']
});
var f = require('util').format;
var h = require('../lib/helpers');
var findupSync = require('findup-sync');
var fs = require('fs');
var read = fs.readFileSync;
var glob = require('glob');
var isDir = require('is-dir');
var isFile = require('is-file');
var path = require('path');
var basename = path.basename;
var dirname = path.dirname;
var resolve = path.resolve;
var sutil = require('spun-util');
var errors = sutil.errors;
var help = require('../lib/help');
var MODULE_NAME = 'spun';
var cli = new sutil.CLI(MODULE_NAME);
var DEFAULT_PROVIDER_NAME = 'spun-selenium-webdriver';
var DEFAULT_PROVIDER_PATH = resolve(__dirname, '..', 'node_modules', DEFAULT_PROVIDER_NAME);
var DEFAULT_GLOB = './test/**/*.' + MODULE_NAME;
var DEFAULT_WORKER_COUNT = 10;
var REAL_CWD = process.cwd();
var providerPackageJson;
var spunFiles = [];
var provider;
var providerPath;
var spunTasks;
var allowedBrowsers = 'chrome,ff,ie,opera,phantom,afari'.split(',');
var reporter = require('../lib/reporters/spec');

process.title = MODULE_NAME;

if(argv.h || argv.help) help(MODULE_NAME), exit(0);

if(argv.v) argv.verbose = true;

if(argv.version)
  cli.log(require('../package.json').version)
  , exit();

if(argv.browsers)
  if(argv.browsers.split(',').filter(function(browser){return allowedBrowsers.indexOf(browser) === -1;}).length)
    cli.error('--browsers argument only accepts chrome, ff, ie, opera, phantom, or safari.')
    , exit(1);
  else argv.browsers = argv.browsers.split(',');
else
  cli.log('No --browsers given, defaulting to chrome.')
  , argv.browsers = ['chrome'];

if('cwd' in argv){
  argv.cwd = resolve(argv.cwd);
  if(!isDir(argv.cwd)){
    cli.warn(argv.cwd + ' was not a directory.  Changing to ' + REAL_CWD);
  } else {
    cli.log('Changing current directory to  "' + argv.cwd + '"');
  }
} else {
  argv.cwd = REAL_CWD;
}

if(typeof argv.variables === 'string'){
  argv.variables = resolve(argv.cwd, argv.variables);

  if(!isFile(argv.variables))
    cli.error('--variables expects a file path.')
    , exit(1);
  else {
    try {
      argv.variables = JSON.parse(read(argv.variables));
    } catch(e) {
      cli.error(f('There was a problem parsing --variables %s', argv.variables));
      cli.error('Please ensure that the file contains valid json');
      exit(1);
    }
  }
}

argv.workerCount = parseInt(argv['worker-count']);
if(argv.workerCount)
  cli.log(f('Worker count set to %s.', argv.workerCount));
else
  argv.workerCount = DEFAULT_WORKER_COUNT;

if(!provider && argv.p)
  argv.p = resolve(argv.cwd, argv.p)
  , cli.log(f('Attempting to find a strategy provider starting at %s', argv.p))
  , provider = getProviderByArg('p', argv);

if(provider)argv.provider = argv.p;

if(!provider && argv.provider)
  argv.provider = resolve(argv.cwd, argv.provider)
  , cli.log(f('Attempting to find a strategy provider starting at %s', argv.provider))
  , provider = getProviderByArg('provider', argv);

if(!provider)
  providerPackageJson = findupSync('package.json', {cwd: argv.cwd});

if(!provider && providerPackageJson)
  cli.log(f('Attempting to find a strategy provider in package.json located at %s', providerPackageJson))
  , providerPath = getProviderPathFromPackageJson(providerPackageJson);

if(!provider)
  cli.log(f('Using the default provider ', DEFAULT_PROVIDER_NAME))
  , providerPath = DEFAULT_PROVIDER_PATH;

if(providerPath)
  cli.log(f('Attempting to load provider at %s', providerPath))
  , provider = require(providerPath);

if(provider)argv.provider = providerPath;

if(!provider)
  cli.error('No strategy provider found!')
  , argv.p && cli.error(f('  -p was %s', argv.p))
  , argv.provider && cli.error(f('  --provider was %s', argv.provider))
  , providerPackageJson && cli.error(f('  Searched this package.json file %s', providerPackageJson))
  , !argv.p && !argv.provider && !providerPackageJson && cli.error(
      f('Expected -p, --provider, or package.json to be found in %s or a parent directory.', argv.cwd)
    )
  , exit(1);

if(typeof provider !== 'function')
  cli.error('A strategy provider must be instantiable.')
  , exit(1);

if(argv._.length){
  argv._.forEach(function(pattern){
    spunFiles = spunFiles.concat(glob.sync(pattern, {cwd: argv.cwd}));
  });
} else spunFiles = glob.sync(DEFAULT_GLOB, {cwd: argv.cwd});

spunFiles = spunFiles.filter(byExtensions).map(toFullPath);

if(!spunFiles.length){
  if(argv._.length){
    cli.error(f('Couldn\'t find any ".%s" files using the following glob patterns: %j', MODULE_NAME,  argv._));
  } else {
    cli.error(f('No ".%s" files found using the default glob: %s', MODULE_NAME,  DEFAULT_GLOB));
  }
  exit(1);
}

if(argv.runner === 'false' || argv.r === 'false')
  delete argv.runner
  , delete argv.r
  , cli.log('--runner set to false.  Not running compiled spun files.');
else {
  if(typeof argv.runner !== 'string' && typeof argv.r === 'string')argv.runner = argv.r;
  else argv.runner = 'node';
}

function byExtensions(path){
  return path.indexOf('.' + MODULE_NAME) === path.length - MODULE_NAME.length - 1;
}

function byNamePrefix(name){
  return name.indexOf('spun-') === 0 && name.indexOf('spun-util') === -1;
}

function exit(code){
  if(code){
    cli.error(f('Run `%s -h` for usage.', MODULE_NAME));
  }
  process.exit(parseInt(code) || 0);
}

function getProviderByArg(argName, argv){
  var provider;
  var fullPath = resolve(argv.cwd, argv[argName]);
  try {
    provider = require(fullPath);
    cli.log(f('Found %s at %s', basename(fullPath), fullPath));
  } catch(e) {
    console.log(e);
    cli.error(f('Unable to locate provider using argv.%s = %s', argName, argv[argName]));
    cli.error(f('The following error occurred: %j', e));
  }
  return provider;
}

function getProviderPathFromPackageJson(providerPackageJson){
  var json = require(providerPackageJson);
  var dependencies = json.dependencies;
  var devDependencies = json.devDependencies;
  var peerDependencies = json.peerDependencies;
  var providerName;
  var provider;

  if(dependencies)
    providerName = Object.keys(dependencies)
    .filter(byNamePrefix)[0];

  if(!providerName && peerDependencies)
    providerName = Object.keys(peerDependencies)
    .filter(byNamePrefix)[0];

  if(!providerName && devDependencies)
    providerName = Object.keys(devDependencies)
    .filter(byNamePrefix)[0];

  if(providerName)
    cli.log(f('Found %s in %s', providerName, providerPackageJson))
    , provider = resolve(dirname(providerPackageJson), 'node_modules', providerName);

  return provider;
}

function toFullPath(path){
  return resolve(argv.cwd, path);
}

spunTasks = [
  require('../lib/parse')(argv, spunFiles),
  require('../lib/compile')(argv, provider)
];

if(argv.runner)spunTasks.push(require('../lib/run')(argv, reporter(argv, cli)));

async.waterfall(spunTasks, function(err, contexts){
  contexts = contexts || [];
  var failures = contexts.filter(h.byProp('error')).length;
  var method = 'praise';
  if(err) {
    if(err instanceof errors.SpunError){
      cli.error(f('%s: %s', err.constructor.super_.name, err.message));
      if(err.stack){
        err.stack.forEach(function(entry){
          cli.error('|  ' + entry);
        });
      }
    } else {
      cli.error(err.message);
      if(err.stack) console.error(err.stack);
    }
  }
  if(err || failures) method = 'error';

  cli[method](f('FINISHED!  %s passed %s failed', contexts.length - failures, failures));

  if(method === 'error' && !argv.verbose) cli.error('Run with --verbose to see the full output.');
});
<commit_msg>Fixing safari for --browsers<commit_after>#!/usr/bin/env node

var async = require('async');
var argv = require('minimist')(process.argv.slice(2), {
  boolean: ['verbose']
});
var f = require('util').format;
var h = require('../lib/helpers');
var findupSync = require('findup-sync');
var fs = require('fs');
var read = fs.readFileSync;
var glob = require('glob');
var isDir = require('is-dir');
var isFile = require('is-file');
var path = require('path');
var basename = path.basename;
var dirname = path.dirname;
var resolve = path.resolve;
var sutil = require('spun-util');
var errors = sutil.errors;
var help = require('../lib/help');
var MODULE_NAME = 'spun';
var cli = new sutil.CLI(MODULE_NAME);
var DEFAULT_PROVIDER_NAME = 'spun-selenium-webdriver';
var DEFAULT_PROVIDER_PATH = resolve(__dirname, '..', 'node_modules', DEFAULT_PROVIDER_NAME);
var DEFAULT_GLOB = './test/**/*.' + MODULE_NAME;
var DEFAULT_WORKER_COUNT = 10;
var REAL_CWD = process.cwd();
var providerPackageJson;
var spunFiles = [];
var provider;
var providerPath;
var spunTasks;
var allowedBrowsers = 'chrome,ff,ie,opera,phantom,safari'.split(',');
var reporter = require('../lib/reporters/spec');

process.title = MODULE_NAME;

if(argv.h || argv.help) help(MODULE_NAME), exit(0);

if(argv.v) argv.verbose = true;

if(argv.version)
  cli.log(require('../package.json').version)
  , exit();

if(argv.browsers)
  if(argv.browsers.split(',').filter(function(browser){return allowedBrowsers.indexOf(browser) === -1;}).length)
    cli.error('--browsers argument only accepts chrome, ff, ie, opera, phantom, or safari.')
    , exit(1);
  else argv.browsers = argv.browsers.split(',');
else
  cli.log('No --browsers given, defaulting to chrome.')
  , argv.browsers = ['chrome'];

if('cwd' in argv){
  argv.cwd = resolve(argv.cwd);
  if(!isDir(argv.cwd)){
    cli.warn(argv.cwd + ' was not a directory.  Changing to ' + REAL_CWD);
  } else {
    cli.log('Changing current directory to  "' + argv.cwd + '"');
  }
} else {
  argv.cwd = REAL_CWD;
}

if(typeof argv.variables === 'string'){
  argv.variables = resolve(argv.cwd, argv.variables);

  if(!isFile(argv.variables))
    cli.error('--variables expects a file path.')
    , exit(1);
  else {
    try {
      argv.variables = JSON.parse(read(argv.variables));
    } catch(e) {
      cli.error(f('There was a problem parsing --variables %s', argv.variables));
      cli.error('Please ensure that the file contains valid json');
      exit(1);
    }
  }
}

argv.workerCount = parseInt(argv['worker-count']);
if(argv.workerCount)
  cli.log(f('Worker count set to %s.', argv.workerCount));
else
  argv.workerCount = DEFAULT_WORKER_COUNT;

if(!provider && argv.p)
  argv.p = resolve(argv.cwd, argv.p)
  , cli.log(f('Attempting to find a strategy provider starting at %s', argv.p))
  , provider = getProviderByArg('p', argv);

if(provider)argv.provider = argv.p;

if(!provider && argv.provider)
  argv.provider = resolve(argv.cwd, argv.provider)
  , cli.log(f('Attempting to find a strategy provider starting at %s', argv.provider))
  , provider = getProviderByArg('provider', argv);

if(!provider)
  providerPackageJson = findupSync('package.json', {cwd: argv.cwd});

if(!provider && providerPackageJson)
  cli.log(f('Attempting to find a strategy provider in package.json located at %s', providerPackageJson))
  , providerPath = getProviderPathFromPackageJson(providerPackageJson);

if(!provider)
  cli.log(f('Using the default provider ', DEFAULT_PROVIDER_NAME))
  , providerPath = DEFAULT_PROVIDER_PATH;

if(providerPath)
  cli.log(f('Attempting to load provider at %s', providerPath))
  , provider = require(providerPath);

if(provider)argv.provider = providerPath;

if(!provider)
  cli.error('No strategy provider found!')
  , argv.p && cli.error(f('  -p was %s', argv.p))
  , argv.provider && cli.error(f('  --provider was %s', argv.provider))
  , providerPackageJson && cli.error(f('  Searched this package.json file %s', providerPackageJson))
  , !argv.p && !argv.provider && !providerPackageJson && cli.error(
      f('Expected -p, --provider, or package.json to be found in %s or a parent directory.', argv.cwd)
    )
  , exit(1);

if(typeof provider !== 'function')
  cli.error('A strategy provider must be instantiable.')
  , exit(1);

if(argv._.length){
  argv._.forEach(function(pattern){
    spunFiles = spunFiles.concat(glob.sync(pattern, {cwd: argv.cwd}));
  });
} else spunFiles = glob.sync(DEFAULT_GLOB, {cwd: argv.cwd});

spunFiles = spunFiles.filter(byExtensions).map(toFullPath);

if(!spunFiles.length){
  if(argv._.length){
    cli.error(f('Couldn\'t find any ".%s" files using the following glob patterns: %j', MODULE_NAME,  argv._));
  } else {
    cli.error(f('No ".%s" files found using the default glob: %s', MODULE_NAME,  DEFAULT_GLOB));
  }
  exit(1);
}

if(argv.runner === 'false' || argv.r === 'false')
  delete argv.runner
  , delete argv.r
  , cli.log('--runner set to false.  Not running compiled spun files.');
else {
  if(typeof argv.runner !== 'string' && typeof argv.r === 'string')argv.runner = argv.r;
  else argv.runner = 'node';
}

function byExtensions(path){
  return path.indexOf('.' + MODULE_NAME) === path.length - MODULE_NAME.length - 1;
}

function byNamePrefix(name){
  return name.indexOf('spun-') === 0 && name.indexOf('spun-util') === -1;
}

function exit(code){
  if(code){
    cli.error(f('Run `%s -h` for usage.', MODULE_NAME));
  }
  process.exit(parseInt(code) || 0);
}

function getProviderByArg(argName, argv){
  var provider;
  var fullPath = resolve(argv.cwd, argv[argName]);
  try {
    provider = require(fullPath);
    cli.log(f('Found %s at %s', basename(fullPath), fullPath));
  } catch(e) {
    console.log(e);
    cli.error(f('Unable to locate provider using argv.%s = %s', argName, argv[argName]));
    cli.error(f('The following error occurred: %j', e));
  }
  return provider;
}

function getProviderPathFromPackageJson(providerPackageJson){
  var json = require(providerPackageJson);
  var dependencies = json.dependencies;
  var devDependencies = json.devDependencies;
  var peerDependencies = json.peerDependencies;
  var providerName;
  var provider;

  if(dependencies)
    providerName = Object.keys(dependencies)
    .filter(byNamePrefix)[0];

  if(!providerName && peerDependencies)
    providerName = Object.keys(peerDependencies)
    .filter(byNamePrefix)[0];

  if(!providerName && devDependencies)
    providerName = Object.keys(devDependencies)
    .filter(byNamePrefix)[0];

  if(providerName)
    cli.log(f('Found %s in %s', providerName, providerPackageJson))
    , provider = resolve(dirname(providerPackageJson), 'node_modules', providerName);

  return provider;
}

function toFullPath(path){
  return resolve(argv.cwd, path);
}

spunTasks = [
  require('../lib/parse')(argv, spunFiles),
  require('../lib/compile')(argv, provider)
];

if(argv.runner)spunTasks.push(require('../lib/run')(argv, reporter(argv, cli)));

async.waterfall(spunTasks, function(err, contexts){
  contexts = contexts || [];
  var failures = contexts.filter(h.byProp('error')).length;
  var method = 'praise';
  if(err) {
    if(err instanceof errors.SpunError){
      cli.error(f('%s: %s', err.constructor.super_.name, err.message));
      if(err.stack){
        err.stack.forEach(function(entry){
          cli.error('|  ' + entry);
        });
      }
    } else {
      cli.error(err.message);
      if(err.stack) console.error(err.stack);
    }
  }
  if(err || failures) method = 'error';

  cli[method](f('FINISHED!  %s passed %s failed', contexts.length - failures, failures));

  if(method === 'error' && !argv.verbose) cli.error('Run with --verbose to see the full output.');
});
<|endoftext|>


<commit_before><commit_msg>remove getAllStyles<commit_after><|endoftext|>


<commit_before>import { model } from "scarletsframe";

// Create template model
model('benchmark', function(My){
    My.list = [];
    My.selectedItem = null;

    // Handle button
    My.run = function(){
        My.selectedItem = null;
        My.list.assign(Store.buildData(1000));
    }

    My.runlots = function(){
        My.selectedItem = null;
        My.list.assign(Store.buildData(10000));
    }

    My.add = function(){
        My.list.push(...Store.buildData(1000));
    }

    My.update = function(){
        for (var i = 0; i < My.list.length; i += 10)
            My.list[i].label += ' !!!';
    }

    My.clear = function(){
        My.list.splice(0);
        My.selectedItem = null;
    }

    My.swaprows = function(){
    	// Copy the object value
        var ref = Object.assign({}, My.list[1]);

        // Swap values between object
        My.list.assign(1, My.list[998]);
        My.list.assign(998, ref);
    }

    My.select = function(item){
        // Reset last item selection
        if(My.selectedItem !== item && My.selectedItem !== null)
            My.selectedItem.selected = false;

        // Select current item
        item.selected = true;
        My.selectedItem = item;
    }

    My.remove = function(item){
        // Find item index from the list
        var i = My.list.indexOf(item);

        // Remove item and the element
        if(i !== -1)
            My.list.splice(i, 1);

        // Invalidate the selected item
        if(My.selectedItem === item)
            My.selectedItem = null;
    }
});

// ==== Other stuff ====
const Store = new function(){
    const adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
    const colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
    const nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];

    const _random = (max)=> Math.round(Math.random() * 1000) % max;

    let nextId = 1;
    this.buildData = function(count){
        let data = new Array(count);
        for (let i = 0; i < count; i++){
            data[i] = {
                id: nextId++,
                label: `${adjectives[_random(adjectives.length)]} ${colours[_random(colours.length)]} ${nouns[_random(nouns.length)]}`
            };
        }

        return data;
    }
};<commit_msg>Use spread syntax to copy an object<commit_after>import { model } from "scarletsframe";

// Create template model
model('benchmark', function(My){
    My.list = [];
    My.selectedItem = null;

    // Handle button
    My.run = function(){
        My.selectedItem = null;
        My.list.assign(Store.buildData(1000));
    }

    My.runlots = function(){
        My.selectedItem = null;
        My.list.assign(Store.buildData(10000));
    }

    My.add = function(){
        My.list.push(...Store.buildData(1000));
    }

    My.update = function(){
        for (var i = 0; i < My.list.length; i += 10)
            My.list[i].label += ' !!!';
    }

    My.clear = function(){
        My.list.splice(0);
        My.selectedItem = null;
    }

    My.swaprows = function(){
    	// Copy the object value
        var ref = {...My.list[1]};

        // Swap values between object
        My.list.assign(1, My.list[998]);
        My.list.assign(998, ref);
    }

    My.select = function(item){
        // Reset last item selection
        if(My.selectedItem !== item && My.selectedItem !== null)
            My.selectedItem.selected = false;

        // Select current item
        item.selected = true;
        My.selectedItem = item;
    }

    My.remove = function(item){
        // Find item index from the list
        var i = My.list.indexOf(item);

        // Remove item and the element
        if(i !== -1)
            My.list.splice(i, 1);

        // Invalidate the selected item
        if(My.selectedItem === item)
            My.selectedItem = null;
    }
});

// ==== Other stuff ====
const Store = new function(){
    const adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
    const colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
    const nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];

    const _random = (max)=> Math.round(Math.random() * 1000) % max;

    let nextId = 1;
    this.buildData = function(count){
        let data = new Array(count);
        for (let i = 0; i < count; i++){
            data[i] = {
                id: nextId++,
                label: `${adjectives[_random(adjectives.length)]} ${colours[_random(colours.length)]} ${nouns[_random(nouns.length)]}`
            };
        }

        return data;
    }
};<|endoftext|>


<commit_before>frappe.ui.form.ControlColor = frappe.ui.form.ControlData.extend({
	make_input: function () {
		this._super();
		this.colors = [
			"#ffc4c4", "#ff8989", "#ff4d4d", "#a83333",
			"#ffe8cd", "#ffd19c", "#ffb868", "#a87945",
			"#ffd2c2", "#ffa685", "#ff7846", "#a85b5b",
			"#ffd7d7", "#ffb1b1", "#ff8989", "#a84f2e",
			"#fffacd", "#fff168", "#fff69c", "#a89f45",
			"#ebf8cc", "#d9f399", "#c5ec63", "#7b933d",
			"#cef6d1", "#9deca2", "#6be273", "#428b46",
			"#d2f8ed", "#a4f3dd", "#77ecca", "#49937e",
			"#d2f1ff", "#a6e4ff", "#78d6ff", "#4f8ea8",
			"#d2d2ff", "#a3a3ff", "#7575ff", "#4d4da8",
			"#dac7ff", "#b592ff", "#8e58ff", "#5e3aa8",
			"#f8d4f8", "#f3aaf0", "#ec7dea", "#934f92"
		];
		this.make_color_input();
	},
	make_color_input: function () {
		this.$wrapper
			.find('.control-input-wrapper')
			.append(`

`);
		this.$color_pallete = this.$wrapper.find('.color-picker-pallete');

		var color_html = this.colors.map(this.get_color_box).join("");
		this.$color_pallete.append(color_html);
		this.$color_pallete.hide();
		this.bind_events();
	},
	get_color_box: function (hex) {
		return `<div class="color-box" data-color="${hex}" style="background-color: ${hex}"></div>`;
	},
	set_formatted_input: function(value) {
		this._super(value);

		if (!value) value = '#FFFFFF';
		const contrast    = frappe.ui.color.get_contrast_color(value);

		this.$input.css({
			"background-color": value, "color": contrast
		});
	},
	bind_events: function () {
		var mousedown_happened = false;
		this.$wrapper.on("click", ".color-box", (e) => {
			mousedown_happened = false;

			var color_val = $(e.target).data("color");
			this.set_value(color_val);
			// set focus so that we can blur it later
			this.set_focus();
		});

		this.$wrapper.find(".color-box").mousedown(() => {
			mousedown_happened = true;
		});

		this.$input.on("focus", () => {
			this.$color_pallete.show();
		});
		this.$input.on("blur", () => {
			if (mousedown_happened) {
				// cancel the blur event
				mousedown_happened = false;
			} else {
				// blur event is okay
				$(this.$color_pallete).hide();
			}
		});
	},
	validate: function (value) {
		if(value === '') {
			return '';
		}
		var is_valid = /^#[0-9A-F]{6}$/i.test(value);
		if(is_valid) {
			return value;
		}
		return null;
	}
});
<commit_msg>fix: append color picker to wrapper<commit_after>frappe.ui.form.ControlColor = frappe.ui.form.ControlData.extend({
	make_input: function () {
		this._super();
		this.colors = [
			"#ffc4c4", "#ff8989", "#ff4d4d", "#a83333",
			"#ffe8cd", "#ffd19c", "#ffb868", "#a87945",
			"#ffd2c2", "#ffa685", "#ff7846", "#a85b5b",
			"#ffd7d7", "#ffb1b1", "#ff8989", "#a84f2e",
			"#fffacd", "#fff168", "#fff69c", "#a89f45",
			"#ebf8cc", "#d9f399", "#c5ec63", "#7b933d",
			"#cef6d1", "#9deca2", "#6be273", "#428b46",
			"#d2f8ed", "#a4f3dd", "#77ecca", "#49937e",
			"#d2f1ff", "#a6e4ff", "#78d6ff", "#4f8ea8",
			"#d2d2ff", "#a3a3ff", "#7575ff", "#4d4da8",
			"#dac7ff", "#b592ff", "#8e58ff", "#5e3aa8",
			"#f8d4f8", "#f3aaf0", "#ec7dea", "#934f92"
		];
		this.make_color_input();
	},
	make_color_input: function () {
		this.$wrapper
			.append(`

`);
		this.$color_pallete = this.$wrapper.find('.color-picker-pallete');

		var color_html = this.colors.map(this.get_color_box).join("");
		this.$color_pallete.append(color_html);
		this.$color_pallete.hide();
		this.bind_events();
	},
	get_color_box: function (hex) {
		return `<div class="color-box" data-color="${hex}" style="background-color: ${hex}"></div>`;
	},
	set_formatted_input: function(value) {
		this._super(value);

		if (!value) value = '#FFFFFF';
		const contrast    = frappe.ui.color.get_contrast_color(value);

		this.$input.css({
			"background-color": value, "color": contrast
		});
	},
	bind_events: function () {
		var mousedown_happened = false;
		this.$wrapper.on("click", ".color-box", (e) => {
			mousedown_happened = false;

			var color_val = $(e.target).data("color");
			this.set_value(color_val);
			// set focus so that we can blur it later
			this.set_focus();
		});

		this.$wrapper.find(".color-box").mousedown(() => {
			mousedown_happened = true;
		});

		this.$input.on("focus", () => {
			this.$color_pallete.show();
		});
		this.$input.on("blur", () => {
			if (mousedown_happened) {
				// cancel the blur event
				mousedown_happened = false;
			} else {
				// blur event is okay
				$(this.$color_pallete).hide();
			}
		});
	},
	validate: function (value) {
		if(value === '') {
			return '';
		}
		var is_valid = /^#[0-9A-F]{6}$/i.test(value);
		if(is_valid) {
			return value;
		}
		return null;
	}
});
<|endoftext|>


<commit_before>var list      = require('./list');
var Issue     = require('./issue');
var config    = require('../config');

var issues = {

	/**
	 * List
	 *
	 * List of all validator issues.
	 */
	list: list,

	/**
	 * Issue
	 *
	 * Issue constructor
	 */
	Issue: Issue,

    /**
     * Filter Fieldmaps
     *
     * Remove fieldmap related warnings if no fieldmaps
     * are present.
     */
    filterFieldMaps: function (issueList, summary) {
        if (summary.modalities.indexOf("fieldmap") > 0) {
            var filteredIssueList = [];
            var fieldmapRelatedCodes = ["6", "7", "8", "9"];
            for (var i = 0; i < issueList.length; i++) {
                if (fieldmapRelatedCodes.indexOf(issueList[i].code) < 0) {
                    filteredIssueList.push(issueList[i]);
                }
            }
            issueList = filteredIssueList;
        }
        return issueList
    },

	/**
     * Format Issues
     */
    format: function (issueList, summary, options) {
        var errors = [], warnings = [], ignored = [];

        issueList = this.filterFieldMaps(issueList, summary);

        // sort alphabetically by relative path of files
        issueList.sort(function (a,b) {
            var aPath = a.file ? a.file.relativePath : '';
            var bPath = b.file ? b.file.relativePath : '';
            return (aPath > bPath) ? 1 : ((bPath > aPath) ? -1 : 0);
        });

        // organize by issue code
        var categorized = {};
        var codes = []
        for (var i = 0; i < issueList.length; i++) {
            var issue = issueList[i];

            if (issue.file && config.ignoredFile(options.config, issue.file.relativePath)) {
                continue;
            }

            if (!categorized[issue.code]) {
                codes.push(issue.key);
                codes.push(issue.code);
                categorized[issue.code] = list[issue.code];
                categorized[issue.code].files = [];
                categorized[issue.code].additionalFileCount = 0;
            }
            if (options.verbose || (categorized[issue.code].files.length < 10)) {
                categorized[issue.code].files.push(issue);
            } else {
                categorized[issue.code].additionalFileCount++;
            }
        }

        var severityMap = config.interpret(codes, options.config);

        // organize by severity
        for (var key in categorized) {
            issue = categorized[key];
            issue.code = key;

            if (severityMap.hasOwnProperty(issue.code)) {
                issue.severity = severityMap[issue.code];
            }

            if (severityMap.hasOwnProperty(issue.key)) {
                issue.severity = severityMap[issue.key];
            }

            if (issue.severity === 'error') {
                errors.push(issue);
            } else if (issue.severity === 'warning' && !options.ignoreWarnings) {
                warnings.push(issue);
            } else if (issue.severity === 'ignore') {
                ignored.push(issue);
            }

        }

        return {errors: errors, warnings: warnings, ignored: ignored};
    },

    /**
     * Reformat
     *
     * Takes an already formatted set of issues, a
     * summary and a config object and returns the
     * same issues reformatted against the config.
     */
    reformat: function (issueList, summary, config) {
        var errors   = issueList.errors   ? issueList.errors   : [],
            warnings = issueList.warnings ? issueList.warnings : [],
            ignored  = issueList.ignored  ? issueList.ignored  : [];

        issueList = errors.concat(warnings).concat(ignored);
        var unformatted = [];
        for (var i = 0; i < issueList.length; i++) {
            var issue = issueList[i];
            for (var j = 0; j < issue.files.length; j++) {
                var file = issue.files[j];
                unformatted.push(file);
            }
        }
        return issues.format(unformatted, summary, {config: config});
    }
};

module.exports = issues;<commit_msg>fix casting, simplify<commit_after>var list      = require('./list');
var Issue     = require('./issue');
var config    = require('../config');

var issues = {

	/**
	 * List
	 *
	 * List of all validator issues.
	 */
	list: list,

	/**
	 * Issue
	 *
	 * Issue constructor
	 */
	Issue: Issue,

    /**
     * Filter Fieldmaps
     *
     * Remove fieldmap related warnings if no fieldmaps
     * are present.
     */
    filterFieldMaps: function (issueList, summary) {
        if (summary.modalities.indexOf("fieldmap") < 0) {
            var filteredIssueList = [];
            var fieldmapRelatedCodes = [6, 7, 8, 9];
            for (var i = 0; i < issueList.length; i++) {
                var issue = issueList[i];
                if (fieldmapRelatedCodes.indexOf(issue.code) < 0) {
                    filteredIssueList.push(issue);
                }
            }
            issueList = filteredIssueList;
        }
        return issueList
    },

	/**
     * Format Issues
     */
    format: function (issueList, summary, options) {
        var errors = [], warnings = [], ignored = [];

        issueList = this.filterFieldMaps(issueList, summary);

        // sort alphabetically by relative path of files
        issueList.sort(function (a,b) {
            var aPath = a.file ? a.file.relativePath : '';
            var bPath = b.file ? b.file.relativePath : '';
            return (aPath > bPath) ? 1 : ((bPath > aPath) ? -1 : 0);
        });

        // organize by issue code
        var categorized = {};
        var codes = []
        for (var i = 0; i < issueList.length; i++) {
            var issue = issueList[i];

            if (issue.file && config.ignoredFile(options.config, issue.file.relativePath)) {
                continue;
            }

            if (!categorized[issue.code]) {
                codes.push(issue.key);
                codes.push(issue.code);
                categorized[issue.code] = list[issue.code];
                categorized[issue.code].files = [];
                categorized[issue.code].additionalFileCount = 0;
            }
            if (options.verbose || (categorized[issue.code].files.length < 10)) {
                categorized[issue.code].files.push(issue);
            } else {
                categorized[issue.code].additionalFileCount++;
            }
        }

        var severityMap = config.interpret(codes, options.config);

        // organize by severity
        for (var key in categorized) {
            issue = categorized[key];
            issue.code = key;

            if (severityMap.hasOwnProperty(issue.code)) {
                issue.severity = severityMap[issue.code];
            }

            if (severityMap.hasOwnProperty(issue.key)) {
                issue.severity = severityMap[issue.key];
            }

            if (issue.severity === 'error') {
                errors.push(issue);
            } else if (issue.severity === 'warning' && !options.ignoreWarnings) {
                warnings.push(issue);
            } else if (issue.severity === 'ignore') {
                ignored.push(issue);
            }

        }

        return {errors: errors, warnings: warnings, ignored: ignored};
    },

    /**
     * Reformat
     *
     * Takes an already formatted set of issues, a
     * summary and a config object and returns the
     * same issues reformatted against the config.
     */
    reformat: function (issueList, summary, config) {
        var errors   = issueList.errors   ? issueList.errors   : [],
            warnings = issueList.warnings ? issueList.warnings : [],
            ignored  = issueList.ignored  ? issueList.ignored  : [];

        issueList = errors.concat(warnings).concat(ignored);
        var unformatted = [];
        for (var i = 0; i < issueList.length; i++) {
            var issue = issueList[i];
            for (var j = 0; j < issue.files.length; j++) {
                var file = issue.files[j];
                unformatted.push(file);
            }
        }
        return issues.format(unformatted, summary, {config: config});
    }
};

module.exports = issues;<|endoftext|>


<commit_before>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

module.exports = function (configuration) {
    var router = express.Router();

	var completeError = function(err, res) {
	    if (err) {
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

    router.get('/', (req, res, next) => {
		var route = '/tertulias';
		req['tertulias'] = {};
		req['route'] = route;
		req['resultsTag'] = 'tertulias';
		req.tertulias['query'] = queryTertulias;
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar }; // String -> sql.NVarChar; Number -> sql.Int; Boolean -> sql.Bit; Date -> sql.DateTime; Buffer -> sql.VarBinary; sql.Table -> sql.TVP
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id };
	    req.tertulias['links'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '" }, ' +
			'{ rel: "create", method: "POST", href: "' + route + '" }, ' +
			'{ rel: "searchPublic", method: "GET", href: "' + route + '/publicsearch" } ' +
		']';
	    req.tertulias['itemLinks'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "update", method: "PUT", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "delete", method: "DELETE", href: "' + route + '/:tertulia" } ' +
		']';
	    goGet(req, res, next);
    	/*
		*/
	});

	var goGet = function(req, res, next) {
		console.log('VAMOS AQUI: 1');
		var query = req.tertulias.query;
		var resultsTag = req.tertulias.resultsTag;
		var route = req.tertulias.route;
	    var paramsTypes = req.tertulias.paramsTypes;
	    var paramsValues = req.tertulias.paramsValues;
	    var links = req.tertulias.links;
	    var itemLinks = req.tertulias.itemLinks;
		console.log('VAMOS AQUI: 2');

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
			console.log('VAMOS AQUI: 3');
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsTypes)
	        	preparedStatement.input(key, paramsTypes[key]);
			console.log('VAMOS AQUI: 4');
	        preparedStatement.prepare(query, function(err) {
	            if (err) {
	            	completeError(err, res);
	            	return;
	            }
				console.log('VAMOS AQUI: 5');
	            preparedStatement.execute(paramsValues,
	                function(err, recordset, affected) {
						console.log('VAMOS AQUI: 6');
	                    if (err) {
	                    	completeError(err, res);
	                    	return;
	                    }
						console.log('VAMOS AQUI: 7');
	                    res.type('application/json');
                    	if (typeof itemLinks !== typeof undefined)
		                    recordset.forEach(function(elem) {
		                    	elem['links'] = JSON.parse(itemLinks.replace(/:tertulia/g, elem.tr_id));
	                    });
	                    preparedStatement.unprepare();
						console.log('VAMOS AQUI: 8');
	                    var results = {};
	                    results[resultsTag] = recordset;
						console.log('VAMOS AQUI: 9');
	                    results['links'] = links;
	                    console.log(results);
	                    res.json(results);
	                    next();
	                }
	            );
	        });
	    });
		/*
	    */
	}

    return router;

}
<commit_msg>wip save<commit_after>var express = require('express'),
	bodyParser = require('body-parser'),
    authenticate = require('azure-mobile-apps/src/express/middleware/authenticate'),
    authorize = require('azure-mobile-apps/src/express/middleware/authorize');

var sql = require('mssql');
var util = require('../util');

const queryTertulias = 'SELECT' +
' tr_id         AS id,' +
' tr_name       AS name,' +
' tr_subject    AS subject,' +
' ev_targetdate AS nextEventDate,' +
' lo_name       AS nextEventLocation,' +
' no_count      AS messages,' +
' nv_name       AS role ' +
' FROM Tertulias' +
' INNER JOIN Members ON mb_tertulia = tr_id' +
' INNER JOIN Enumvalues ON mb_role = nv_id' +
' INNER JOIN Users ON mb_user = us_id' +
' LEFT JOIN' +
' (SELECT * FROM' +
' (SELECT RANK() OVER(PARTITION BY ev_tertulia ORDER BY ev_targetdate DESC) AS "rank", * FROM Events' +
'  INNER JOIN Locations on ev_location = lo_id WHERE ev_targetdate > GETDATE()) AS a WHERE a.rank = 1) AS b' +
' ON ev_tertulia = tr_id' +
' LEFT JOIN (SELECT no_tertulia, count(*) AS no_count FROM Notifications WHERE no_id NOT IN' +
' (SELECT no_id FROM Notifications INNER JOIN Readnotifications ON rn_notification = no_id' +
' INNER JOIN Users ON rn_user = us_id WHERE us_sid = @sid)' +
' GROUP BY no_tertulia) AS c ON no_tertulia = tr_id' +
' WHERE tr_is_cancelled = 0 AND us_sid = @sid';

module.exports = function (configuration) {
    var router = express.Router();

	var completeError = function(err, res) {
	    if (err) {
	        console.error(err);
	        if (res) res.sendStatus(500);
	    }
	};

    router.get('/', (req, res, next) => {
		var route = '/tertulias';
		req['tertulias'] = {};
		req['route'] = route;
		req['resultsTag'] = 'tertulias';
		req.tertulias['query'] = queryTertulias;
	    req.tertulias['paramsTypes'] = { 'sid': sql.NVarChar }; // String -> sql.NVarChar; Number -> sql.Int; Boolean -> sql.Bit; Date -> sql.DateTime; Buffer -> sql.VarBinary; sql.Table -> sql.TVP
	    req.tertulias['paramsValues'] = { 'sid': req.azureMobile.user.id };
	    req.tertulias['links'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '" }, ' +
			'{ rel: "create", method: "POST", href: "' + route + '" }, ' +
			'{ rel: "searchPublic", method: "GET", href: "' + route + '/publicsearch" } ' +
		']';
	    req.tertulias['itemLinks'] = '[ ' +
			'{ rel: "self", method: "GET", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "update", method: "PUT", href: "' + route + '/:tertulia" }, ' +
			'{ rel: "delete", method: "DELETE", href: "' + route + '/:tertulia" } ' +
		']';
	    goGet(req, res, next);
    	/*
		*/
	});

	var goGet = function(req, res, next) {
		console.log('VAMOS AQUI: 1');
		var query = req.tertulias.query;
		var resultsTag = req.tertulias.resultsTag;
		var route = req.tertulias.route;
	    var paramsTypes = req.tertulias.paramsTypes;
	    var paramsValues = req.tertulias.paramsValues;
	    var links = req.tertulias.links;
	    var itemLinks = req.tertulias.itemLinks;
		console.log('VAMOS AQUI: 2');

		var connection = new sql.Connection(util.sqlConfiguration);
	    connection.connect(function(err) {
			console.log('VAMOS AQUI: 3');
	        var preparedStatement = new sql.PreparedStatement(connection);
	        for (var key in paramsTypes)
	        	preparedStatement.input(key, paramsTypes[key]);
			console.log('VAMOS AQUI: 4');
	        preparedStatement.prepare(query, function(err) {
	            if (err) {
	            	completeError(err, res);
	            	return;
	            }
				console.log('VAMOS AQUI: 5');
	            preparedStatement.execute(paramsValues,
	                function(err, recordset, affected) {
						console.log('VAMOS AQUI: 6');
	                    if (err) {
	                    	completeError(err, res);
	                    	return;
	                    }
						console.log('VAMOS AQUI: 7');
	                    res.type('application/json');
                    	if (typeof itemLinks !== typeof undefined) {
							console.log(itemLinks);
		                    recordset.forEach(function(elem) {
								console.log(elem);
		                    	elem['links'] = JSON.parse(itemLinks.replace(/:tertulia/g, elem.tr_id));
                    		});
	                    };
	                    preparedStatement.unprepare();
						console.log('VAMOS AQUI: 8');
	                    var results = {};
	                    results[resultsTag] = recordset;
						console.log('VAMOS AQUI: 9');
	                    results['links'] = links;
	                    console.log(results);
	                    res.json(results);
	                    next();
	                }
	            );
	        });
	    });
		/*
	    */
	}

    return router;

}
<|endoftext|>


<commit_before>// Phase2Solver implements the backbone of solvePhase2().
function Phase2Solver(heuristic, coords, deadline) {
  this.heuristic = heuristic;
  this.coords = coords;
  this.deadline = deadline;

  this.depth = 0;
  this.cubes = [];
}

// deepen prepares this solver for a deeper search.
Phase2Solver.prototype.deepen = function() {
  this.cubes[this.depth] = new Phase2Cube();
  this.depth++;
};

// solve runs a search at the current depth.
Phase2Solver.prototype.solve = function(cube) {
  try {
    return this._search(cube, 0, 0, -1);
  } catch (e) {
    if (e !== 'solve timed out') {
      throw e;
    }
    return null;
  }
};

Phase2Solver.prototype._checkExpired = function() {
  if (new Date().getTime() > this.deadline) {
    throw 'solve timed out';
  }
};

Phase2Solver.prototype._search = function(cube, depth, lastFace, lastAxis) {
  if (depth === this.depth) {
    if (cube.solved()) {
      this._checkExpired();
      return [];
    }
    return null;
  } else if (this.heuristic.lowerBound(cube, this.coords) > this.depth-depth) {
    return null;
  }

  var newCube = this.cubes[depth];
  for (var i = 0; i < 10; ++i) {
    var face = p2MoveFace(i);
    if (face === lastFace) {
      continue;
    }
    var axis = p2MoveAxis(i);
    if (axis === lastAxis && face >= lastFace) {
      // Avoid redundancies like L2 R2 L2 and enforce an ordering for moves on
      // the same axis.
      continue;
    }

    newCube.set(cube);
    newCube.move(i, this.coords);

    var res = this._search(newCube, depth+1, face, axis);
    if (res !== null) {
      res.splice(0, 0, i);
      return res;
    }

    if (this.depth - depth >= 7) {
      this._checkExpired();
    }
  }

  return null;
};

// solvePhase2 finds a solution to a Phase2Cube and returns it or returns null
// if no solution was found (either because no solution exists or because of a
// timeout).
function solvePhase2(cube, maxLen, heuristic, coords, timeout) {
  timeout = (timeout || 1000000);
  var deadline = new Date().getTime() + timeout;
  var solver = new Phase2Solver(heuristic, coords, deadline);
  for (var depth = 0; depth <= maxLen; ++depth) {
    var solution = solver.solve(cube);
    if (solution !== null) {
      return solution;
    }
    solver.deepen();
  }
  return null;
}

exports.solvePhase2 = solvePhase2;
<commit_msg>increased solver speed by not checking date often<commit_after>// Phase2Solver implements the backbone of solvePhase2().
function Phase2Solver(heuristic, coords, deadline) {
  this.heuristic = heuristic;
  this.coords = coords;
  this.deadline = deadline;

  this.depth = 0;
  this.cubes = [];

  this.nodesSinceDate = 0;
}

// deepen prepares this solver for a deeper search.
Phase2Solver.prototype.deepen = function() {
  this.cubes[this.depth] = new Phase2Cube();
  this.depth++;
};

// solve runs a search at the current depth.
Phase2Solver.prototype.solve = function(cube) {
  try {
    return this._search(cube, 0, 0, -1);
  } catch (e) {
    if (e !== 'solve timed out') {
      throw e;
    }
    return null;
  }
};

Phase2Solver.prototype._checkExpired = function() {
  if (new Date().getTime() > this.deadline) {
    throw 'solve timed out';
  }
};

Phase2Solver.prototype._search = function(cube, depth, lastFace, lastAxis) {
  if (++this.nodesSinceDate === 500000) {
    this.nodesSinceDate = 0;
    this._checkExpired();
  }

  if (depth === this.depth) {
    if (cube.solved()) {
      return [];
    }
    return null;
  } else if (this.heuristic.lowerBound(cube, this.coords) > this.depth-depth) {
    return null;
  }

  var newCube = this.cubes[depth];
  for (var i = 0; i < 10; ++i) {
    var face = p2MoveFace(i);
    if (face === lastFace) {
      continue;
    }
    var axis = p2MoveAxis(i);
    if (axis === lastAxis && face >= lastFace) {
      // Avoid redundancies like L2 R2 L2 and enforce an ordering for moves on
      // the same axis.
      continue;
    }

    newCube.set(cube);
    newCube.move(i, this.coords);

    var res = this._search(newCube, depth+1, face, axis);
    if (res !== null) {
      res.splice(0, 0, i);
      return res;
    }
  }

  return null;
};

// solvePhase2 finds a solution to a Phase2Cube and returns it or returns null
// if no solution was found (either because no solution exists or because of a
// timeout).
function solvePhase2(cube, maxLen, heuristic, coords, timeout) {
  timeout = (timeout || 1000000);
  var deadline = new Date().getTime() + timeout;
  var solver = new Phase2Solver(heuristic, coords, deadline);
  for (var depth = 0; depth <= maxLen; ++depth) {
    var solution = solver.solve(cube);
    if (solution !== null) {
      return solution;
    }
    solver.deepen();
  }
  return null;
}

exports.solvePhase2 = solvePhase2;
<|endoftext|>


<commit_before>var utils = require('./general'),
    log = require('./log');

function coloredStatus(status) {
    if (status == 'success') {
        return status.green;
    } else if (status == 'pending') {
        return status.yellow;
    } else {
        return status.red;
    }
}

function postNewNupicStatus(sha, statusDetails, repoClient) {
    log.info(sha + ': Posting new NuPIC Status ('
        + coloredStatus(statusDetails.state) + ') to github');
    // If the old status was created by nupic.tools, it will start with
    // "NuPIC Status:". But if it was created by Travis-CI, we want to add that
    // little prefix to the description string.
    var statusDescription = utils.normalizeStatusDescription(
        statusDetails.description
    );
    log.info(statusDescription);
    repoClient.github.statuses.create({
        user: repoClient.org,
        repo: repoClient.repo,
        sha: sha,
        state: statusDetails.state,
        description: statusDescription,
        target_url: statusDetails.target_url
    });
}

function triggerTravisBuildsOnAllOpenPullRequests(repoClient, callback) {
    repoClient.getAllOpenPullRequests(function(err, prs) {
        var total = prs.length,
            count = 0,
            errors = null;
        log('Found ' + prs.length + ' open pull requests...');
        prs.map(function(pr) { return pr.number; }).forEach(function(pr_number) {
            repoClient.triggerTravisForPullRequest(pr, function(err, success) {
                count++;
                if (err) {
                    if (! errors) {
                        errors = [];
                    }
                    errors.push(err);
                }
                if (count == prs.length) {
                    if (callback) {
                        callback(errors);
                    }
                }
            });
        });
    });
}

function performCompleteValidation(sha, githubUser, repoClient, validators, postStatus, cb) {
    var callback = cb;
    // default dummy callback for simpler code later
    if (! cb) {
        callback = function() {};
    }
    // if we should post the status to github, we'll wrap the callback with our
    // status posting logic
    if (postStatus) {
        callback = function() {
            postNewNupicStatus.apply(this, arguments);
            if (cb) {
                cb.apply(this, arguments);
            }
        };
    }

    log.debug('VALIDATING ' + sha);

    repoClient.getAllStatusesFor(sha, function(err, statusHistory) {
        if (err) {
            return cb(new Error('Error communicating with Github API.'));
        }

        log.verbose(statusHistory);

        // clone of the global validators array
        var commitValidators = validators.slice(0),
            validationFailed = false,
            target_url,
            highestPriority = -1,
            validatorsRun = [],
            validatorsSkipped = [],
            skippedMSG;

        function shouldSkipValidation(repoClient, validator) {
            return repoClient.hasOwnProperty('validators')
                && repoClient.validators.hasOwnProperty('excludes')
                && repoClient.validators.excludes.indexOf(validator.name) !== -1
        }

        function runNextValidation() {
            var validator,
                priority;
            if (validationFailed) return;
            validator = commitValidators.shift();
            if (validator) {
                if (shouldSkipValidation(repoClient, validator))   {
                    validatorsSkipped.push(validator);
                    log.debug(sha + ': Skipped validator "' + validator.name + '"');
                    runNextValidation();
                } else {
                    log(sha + ': Running commit validator: ' + validator.name);
                    validatorsRun.push(validator);
                    validator.validate(sha, githubUser, statusHistory, repoClient, function(err, result) {
                        if (err) {
                            console.error('Error running commit validator "' + validator.name + '"');
                            console.error(err);
                            return callback(sha, {
                                state: 'error',
                                description: 'Error running commit validator "' + validator.name + '": ' + err.message
                            }, repoClient);
                        }
                        log(sha + ': ' + validator.name + ' result was ' + coloredStatus(result.state));
                        if (result.state !== 'success') {
                            // Upon failure, we set a flag that will skip the
                            // remaining validators and post a failure status.
                            validationFailed = true;
                            callback(sha, result, repoClient);
                        }
                        // This code is just allowing the different validators to
                        // fight over which one will provide the "Details" URL
                        // that gets displayed on the Github PR.
                        if (validator.hasOwnProperty('priority')) {
                            priority = validator.priority;
                        } else {
                            priority = 0;
                        }
                        if (priority >= highestPriority) {
                            highestPriority = priority;
                            if (result.hasOwnProperty('target_url')) {
                                target_url = result.target_url;
                            }
                        };
                        log(sha + ': ' + validator.name + ' complete.');
                        runNextValidation();
                    });
                }
            } else {
                log(sha + ': Validation complete.');
                // No more validators left in the array, so we can complete the
                // validation successfully.
                if (validatorsSkipped.length > 0) {
                    skippedMSG = ' [' + validatorsSkipped.length + ' skipped])';
                } else {
                    skippedMSG = ')';
                }
                callback(sha, {
                    state: 'success',
                    description: 'All validations passed (' + validatorsRun.map(function(v) { return v.name; }).join(', ') + skippedMSG,
                    target_url: target_url
                }, repoClient);
            }
        }

        runNextValidation();

    });
}

module.exports = {
    performCompleteValidation: performCompleteValidation,
    triggerTravisBuildsOnAllOpenPullRequests: triggerTravisBuildsOnAllOpenPullRequests
};<commit_msg>Bug fix.<commit_after>var utils = require('./general'),
    log = require('./log');

function coloredStatus(status) {
    if (status == 'success') {
        return status.green;
    } else if (status == 'pending') {
        return status.yellow;
    } else {
        return status.red;
    }
}

function postNewNupicStatus(sha, statusDetails, repoClient) {
    log.info(sha + ': Posting new NuPIC Status ('
        + coloredStatus(statusDetails.state) + ') to github');
    // If the old status was created by nupic.tools, it will start with
    // "NuPIC Status:". But if it was created by Travis-CI, we want to add that
    // little prefix to the description string.
    var statusDescription = utils.normalizeStatusDescription(
        statusDetails.description
    );
    log.info(statusDescription);
    repoClient.github.statuses.create({
        user: repoClient.org,
        repo: repoClient.repo,
        sha: sha,
        state: statusDetails.state,
        description: statusDescription,
        target_url: statusDetails.target_url
    });
}

function triggerTravisBuildsOnAllOpenPullRequests(repoClient, callback) {
    repoClient.getAllOpenPullRequests(function(err, prs) {
        var total = prs.length,
            count = 0,
            errors = null;
        log('Found ' + prs.length + ' open pull requests...');
        prs.map(function(pr) { return pr.number; }).forEach(function(pr_number) {
            repoClient.triggerTravisForPullRequest(pr_number, function(err, success) {
                count++;
                if (err) {
                    if (! errors) {
                        errors = [];
                    }
                    errors.push(err);
                }
                if (count == prs.length) {
                    if (callback) {
                        callback(errors);
                    }
                }
            });
        });
    });
}

function performCompleteValidation(sha, githubUser, repoClient, validators, postStatus, cb) {
    var callback = cb;
    // default dummy callback for simpler code later
    if (! cb) {
        callback = function() {};
    }
    // if we should post the status to github, we'll wrap the callback with our
    // status posting logic
    if (postStatus) {
        callback = function() {
            postNewNupicStatus.apply(this, arguments);
            if (cb) {
                cb.apply(this, arguments);
            }
        };
    }

    log.debug('VALIDATING ' + sha);

    repoClient.getAllStatusesFor(sha, function(err, statusHistory) {
        if (err) {
            return cb(new Error('Error communicating with Github API.'));
        }

        log.verbose(statusHistory);

        // clone of the global validators array
        var commitValidators = validators.slice(0),
            validationFailed = false,
            target_url,
            highestPriority = -1,
            validatorsRun = [],
            validatorsSkipped = [],
            skippedMSG;

        function shouldSkipValidation(repoClient, validator) {
            return repoClient.hasOwnProperty('validators')
                && repoClient.validators.hasOwnProperty('excludes')
                && repoClient.validators.excludes.indexOf(validator.name) !== -1
        }

        function runNextValidation() {
            var validator,
                priority;
            if (validationFailed) return;
            validator = commitValidators.shift();
            if (validator) {
                if (shouldSkipValidation(repoClient, validator))   {
                    validatorsSkipped.push(validator);
                    log.debug(sha + ': Skipped validator "' + validator.name + '"');
                    runNextValidation();
                } else {
                    log(sha + ': Running commit validator: ' + validator.name);
                    validatorsRun.push(validator);
                    validator.validate(sha, githubUser, statusHistory, repoClient, function(err, result) {
                        if (err) {
                            console.error('Error running commit validator "' + validator.name + '"');
                            console.error(err);
                            return callback(sha, {
                                state: 'error',
                                description: 'Error running commit validator "' + validator.name + '": ' + err.message
                            }, repoClient);
                        }
                        log(sha + ': ' + validator.name + ' result was ' + coloredStatus(result.state));
                        if (result.state !== 'success') {
                            // Upon failure, we set a flag that will skip the
                            // remaining validators and post a failure status.
                            validationFailed = true;
                            callback(sha, result, repoClient);
                        }
                        // This code is just allowing the different validators to
                        // fight over which one will provide the "Details" URL
                        // that gets displayed on the Github PR.
                        if (validator.hasOwnProperty('priority')) {
                            priority = validator.priority;
                        } else {
                            priority = 0;
                        }
                        if (priority >= highestPriority) {
                            highestPriority = priority;
                            if (result.hasOwnProperty('target_url')) {
                                target_url = result.target_url;
                            }
                        };
                        log(sha + ': ' + validator.name + ' complete.');
                        runNextValidation();
                    });
                }
            } else {
                log(sha + ': Validation complete.');
                // No more validators left in the array, so we can complete the
                // validation successfully.
                if (validatorsSkipped.length > 0) {
                    skippedMSG = ' [' + validatorsSkipped.length + ' skipped])';
                } else {
                    skippedMSG = ')';
                }
                callback(sha, {
                    state: 'success',
                    description: 'All validations passed (' + validatorsRun.map(function(v) { return v.name; }).join(', ') + skippedMSG,
                    target_url: target_url
                }, repoClient);
            }
        }

        runNextValidation();

    });
}

module.exports = {
    performCompleteValidation: performCompleteValidation,
    triggerTravisBuildsOnAllOpenPullRequests: triggerTravisBuildsOnAllOpenPullRequests
};<|endoftext|>


<commit_before>/*
 * theme desc
 * TODO: add README in this folder to show some snapshot
 * 参考: http://enrmarc.github.io/atom-theme-gallery/
 * slackUI: https://atom.io/themes/slack-ui
 * Github: ...
 * gruvbox: https://atom.io/themes/gruvbox-syntax
 * Spacegray: https://atom.io/themes/spacegray-dark-neue-syntax
 * DuoTone Dark: https://atom.io/themes/duotone-dark-forest-syntax
 * DuoTone Dark2: https://atom.io/themes/duotone-dark-earth-syntax
 * Earthsung https://atom.io/themes/earthsung-by-jackson-syntax
 */

import R from 'ramda'

import Cyan from './Cyan'
import Purple from './Purple'
import SolarizedDark from './SolarizedDark'
import Github from './Github'
import Blue from './Blue'
import Yellow from './Yellow'
import Green from './Green'
import IronGreen from './IronGreen'

export const themeDict = {
  default: { ...Github },
  cyan: { ...Cyan },
  solarized: { ...SolarizedDark },
  purple: { ...Purple },
  yellow: { ...Yellow },
  github: { ...Github },
  blue: { ...Blue },
  green: { ...Green },
  ironGreen: { ...IronGreen },
}

export const themeKeys = R.keys(themeDict)

export const themeDescs = {
  cyan: 'inspired by the rethinkdb.com admin panel',
  default: 'inspired by the rethinkdb.com admin panel',
  solarized: 'inspired by Emacs solarized theme',
  purple: 'inspired ubuntu OS terminal',
  yellow: 'inspired by vimawesome.com',
  github: 'inspired by github.com',
  blue: 'inspired by myself i think ?',
  green: 'inspired by Olive theme from Vivaldi project',
  ironGreen: 'inspired by dribbble: shots/2478998-Forum-Concept',
}

export const themeCoverMap = R.map(R.path(['cover']), themeDict)
export const themeCoverIndexMap = R.map(R.path(['coverIndex']), themeDict)

// shorthand for style-components
export const theme = themepath =>
  R.path(['theme', ...R.split('.', themepath)]) || 'wheat'
<commit_msg>chore(theme): cyan as default<commit_after>/*
 * theme desc
 * TODO: add README in this folder to show some snapshot
 * 参考: http://enrmarc.github.io/atom-theme-gallery/
 * slackUI: https://atom.io/themes/slack-ui
 * Github: ...
 * gruvbox: https://atom.io/themes/gruvbox-syntax
 * Spacegray: https://atom.io/themes/spacegray-dark-neue-syntax
 * DuoTone Dark: https://atom.io/themes/duotone-dark-forest-syntax
 * DuoTone Dark2: https://atom.io/themes/duotone-dark-earth-syntax
 * Earthsung https://atom.io/themes/earthsung-by-jackson-syntax
 */

import R from 'ramda'

import Cyan from './Cyan'
import Purple from './Purple'
import SolarizedDark from './SolarizedDark'
import Github from './Github'
import Blue from './Blue'
import Yellow from './Yellow'
import Green from './Green'
import IronGreen from './IronGreen'

export const themeDict = {
  default: { ...Cyan },
  /* cyan: { ...Cyan }, */
  solarized: { ...SolarizedDark },
  purple: { ...Purple },
  yellow: { ...Yellow },
  github: { ...Github },
  blue: { ...Blue },
  green: { ...Green },
  ironGreen: { ...IronGreen },
}

export const themeKeys = R.keys(themeDict)

export const themeDescs = {
  cyan: 'inspired by the rethinkdb.com admin panel',
  default: 'inspired by the rethinkdb.com admin panel',
  solarized: 'inspired by Emacs solarized theme',
  purple: 'inspired ubuntu OS terminal',
  yellow: 'inspired by vimawesome.com',
  github: 'inspired by github.com',
  blue: 'inspired by myself i think ?',
  green: 'inspired by Olive theme from Vivaldi project',
  ironGreen: 'inspired by dribbble: shots/2478998-Forum-Concept',
}

export const themeCoverMap = R.map(R.path(['cover']), themeDict)
export const themeCoverIndexMap = R.map(R.path(['coverIndex']), themeDict)

// shorthand for style-components
export const theme = themepath =>
  R.path(['theme', ...R.split('.', themepath)]) || 'wheat'
<|endoftext|>


<commit_before>/**
 * @fileoverview Build file
 * @author nzakas
 */
/*global target, exec, echo, find, cat, rm, mv*/

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

require("shelljs/make");

var path = require("path"),
    dateformat = require("dateformat"),
    nodeCLI = require("shelljs-nodecli"),
    os = require("os");

//------------------------------------------------------------------------------
// Settings
//------------------------------------------------------------------------------

/*
 * A little bit fuzzy. My computer has a first CPU speed of 3093 and the perf test
 * always completes in < 2000ms. However, Travis is less predictable due to
 * multiple different VM types. So I'm fudging this for now in the hopes that it
 * at least provides some sort of useful signal.
 */
var PERF_MULTIPLIER = 7.5e6;

//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------

var NODE = "node ", // intentional extra space
    NODE_MODULES = "./node_modules/",
    TEMP_DIR = "./tmp/",
    BUILD_DIR = "./build/",

    // Utilities - intentional extra space at the end of each string
    MOCHA = NODE_MODULES + "mocha/bin/_mocha ",
    ESLINT = NODE + " bin/eslint.js ",

    // Files
    JS_FILES = find("lib/").filter(fileType("js")).join(" "),
    JSON_FILES = find("conf/").filter(fileType("json")).join(" ") + " .eslintrc",
    TEST_FILES = find("tests/lib/").filter(fileType("js")).join(" ");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Generates a function that matches files with a particular extension.
 * @param {string} extension The file extension (i.e. "js")
 * @returns {Function} The function to pass into a filter method.
 * @private
 */
function fileType(extension) {
    return function(filename) {
        return filename.substring(filename.lastIndexOf(".") + 1) === extension;
    };
}

/**
 * Generates a static file that includes each rule by name rather than dynamically
 * looking up based on directory. This is used for the browser version of ESLint.
 * @param {string} basedir The directory in which to look for code.
 * @returns {void}
 */
function generateRulesIndex(basedir) {
    var output = "module.exports = function() {\n";
    output += "    var rules = Object.create(null);\n";

    find(basedir + "rules/").filter(fileType("js")).forEach(function(filename) {
        var basename = path.basename(filename, ".js");
        output += "    rules[\"" + basename + "\"] = require(\"./rules/" + basename + "\");\n";
    });

    output += "\n    return rules;\n};";
    output.to(basedir + "load-rules.js");
}

/**
 * Creates a release version tag and pushes to origin.
 * @param {string} type The type of release to do (patch, minor, major)
 * @returns {void}
 */
function release(type) {
    target.test();
    exec("npm version " + type);
    target.changelog();
    exec("git push origin master --tags");
    exec("npm publish");
    target.gensite();
}

//------------------------------------------------------------------------------
// Tasks
//------------------------------------------------------------------------------

target.all = function() {
    target.test();
};

target.lint = function() {
    echo("Validating JSON Files");
    nodeCLI.exec("jsonlint", "-q -c", JSON_FILES);

    echo("Validating JavaScript files");
    exec(ESLINT + JS_FILES);

    echo("Validating JavaScript test files");
    exec(ESLINT + TEST_FILES);
};

target.test = function() {
    target.lint();
    target.checkRuleFiles();
    var errors = 0,
        lastReturn;

    // exec(ISTANBUL + " cover " + MOCHA + "-- -c " + TEST_FILES);
    lastReturn = nodeCLI.exec("istanbul", "cover", MOCHA, "-- -c", TEST_FILES);
    if (lastReturn.code !== 0) {
      errors++;
    }

    // exec(ISTANBUL + "check-coverage --statement 99 --branch 98 --function 99 --lines 99");
    lastReturn = nodeCLI.exec("istanbul", "check-coverage", "--statement 99 --branch 98 --function 99 --lines 99");
    if (lastReturn.code !== 0) {
      errors++;
    }

    target.browserify();

    lastReturn = nodeCLI.exec("mocha-phantomjs", "-R dot", "tests/tests.htm");
    if (lastReturn.code !== 0) {
      errors++;
    }

    if (errors) {
        exit(1);
    }
};

target.docs = function() {
    echo("Generating documentation");
    nodeCLI.exec("jsdoc", "-d jsdoc lib");
    echo("Documentation has been output to /jsdoc");
};

target.gensite = function() {

    echo("Generating eslint.org");
    var docsDir = "../eslint.github.io/docs",
        currentDir = pwd();

    rm("-r", docsDir);
    mkdir(docsDir);
    cp("-rf", "docs/*", docsDir);

    find(docsDir).forEach(function(filename) {
        if (test("-f", filename)) {
            var text = cat(filename);
            text = "---\ntitle: ESLint\nlayout: doc\n---\n<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->\n" + text;
            text.replace(/.md\)/g, ".html)").replace("README.html", "index.html").to(filename.replace("README.md", "index.md"));
        }
    });

    cd(docsDir);
    exec("git add -A .");
    exec("git commit -m \"Autogenerated new docs at " + dateformat(new Date()) + "\"");
    exec("git fetch origin && git rebase origin/master");
    exec("git push origin master");
    cd(currentDir);

};

target.browserify = function() {

    // 1. create temp and build directory
    if (!test("-d", TEMP_DIR)) {
        mkdir(TEMP_DIR);
    }

    if (!test("-d", BUILD_DIR)) {
        mkdir(BUILD_DIR);
    }

    // 2. copy files into temp directory
    cp("-r", "lib/*", TEMP_DIR);

    // 3. delete the load-rules.js file
    rm(TEMP_DIR + "load-rules.js");

    // 4. create new load-rule.js with hardcoded requires
    generateRulesIndex(TEMP_DIR);

    // 5. browserify the temp directory
    nodeCLI.exec("browserify", TEMP_DIR + "eslint.js", "-o", BUILD_DIR + "eslint.js", "-s eslint")
    // exec(BROWSERIFY + TEMP_DIR + "eslint.js -o " + BUILD_DIR + "eslint.js -s eslint");

    // 6. remove temp directory
    rm("-r", TEMP_DIR);
};

target.changelog = function() {

    // get most recent two tags
    var tags = exec("git tag", { silent: true }).output.trim().split(/\s/g),
        rangeTags = tags.slice(tags.length - 2),
        now = new Date(),
        timestamp = dateformat(now, "mmmm d, yyyy");

    // output header
    (rangeTags[1] + " - " + timestamp + "\n").to("CHANGELOG.tmp");

    // get log statements
    var logs = exec("git log --pretty=format:\"* %s (%an)\" " + rangeTags.join(".."), {silent:true}).output.split(/\n/g);
    logs = logs.filter(function(line) {
        return line.indexOf("Merge pull request") === -1 && line.indexOf("Merge branch") === -1;
    });
    logs.push(""); // to create empty lines
    logs.unshift("");

    // output log statements
    logs.join("\n").toEnd("CHANGELOG.tmp");

    // switch-o change-o
    cat("CHANGELOG.tmp", "CHANGELOG.md").to("CHANGELOG.md.tmp");
    rm("CHANGELOG.tmp");
    rm("CHANGELOG.md");
    mv("CHANGELOG.md.tmp", "CHANGELOG.md");

    // add into commit
    exec("git add CHANGELOG.md");
    exec("git commit --amend --no-edit");

};

target.checkRuleFiles = function() {

    echo("Validating rules");

    var ruleFiles = find("lib/rules/").filter(fileType("js")),
        rulesIndexText = cat("docs/rules/README.md"),
        confRules = require("./conf/eslint.json").rules,
        errors = 0;

    ruleFiles.forEach(function(filename) {
        var basename = path.basename(filename, ".js"),
            isOffInIndex = rulesIndexText.search("(\\[" + basename + "\\])(\.)+\(off by default\)") !== -1,
            isOffInConfig = confRules[basename] === 0 || (confRules[basename] && confRules[basename][0] === 0);

        // check for docs
        if (!test("-f", "docs/rules/" + basename + ".md")) {
            console.error("Missing documentation for rule %s", basename);
            errors++;
        } else {

            // check for entry in docs index
            if (rulesIndexText.indexOf("(" + basename + ".md)") === -1) {
                console.error("Missing link to documentation for rule %s in index", basename);
                errors++;
            }
        }

        // check for default configuration
        if (!confRules.hasOwnProperty(basename)) {
            console.error("Missing default setting for %s in eslint.json", basename);
            errors++;
        }

        // 'off by default' is not in index and the rule is disabled in config
        if (!isOffInIndex && isOffInConfig) {
            console.error("Missing '(off by default)' for rule %s in index", basename);
            errors++;
        }

        // 'off by default' is in index and the rule is enabled in config
        if (isOffInIndex && !isOffInConfig) {
            console.error("Rule documentation says that %s is off by default but it is enabled in eslint.json.", basename);
            errors++;
        }

        // check for tests
        if (!test("-f", "tests/lib/rules/" + basename + ".js")) {
            console.error("Missing tests for rule %s", basename);
            errors++;
        }

    });

    if (errors) {
        exit(1);
    }

};

function time(cmd, runs, runNumber, results, cb) {
    var start = process.hrtime();
    exec(cmd, { silent: true }, function() {
        var diff = process.hrtime(start),
            actual = (diff[0] * 1e3 + diff[1] / 1e6); // ms

        results.push(actual);
        echo("Performance Run #" + runNumber + ":  %dms", actual);
        if(runs > 1) {
            time(cmd, runs - 1, runNumber + 1, results, cb);
        } else {
            cb(results)
        }
    });

}

target.perf = function() {
    var cpuSpeed = os.cpus()[0].speed,
        max = PERF_MULTIPLIER / cpuSpeed,
        cmd = ESLINT + "./tests/performance/jshint.js";

    echo("CPU Speed is %d with multiplier %d", cpuSpeed, PERF_MULTIPLIER);

    time(cmd, 5, 1, [], function(results) {
        results.sort(function(a, b) {
            return a - b;
        });

        var median = results[~~(results.length / 2)];

        if (median > max) {
            echo("Performance budget exceeded: %dms (limit: %dms)", median, max);
            exit(1);
        } else {
            echo("Performance budget ok:  %dms (limit: %dms)", median, max);
        }
    });

};

target.patch = function() {
    release("patch");
};

target.minor = function() {
    release("minor");
};

target.major = function() {
    release("major");
};
<commit_msg>Add linting Makefile.js (fixes #870)<commit_after>/**
 * @fileoverview Build file
 * @author nzakas
 */
/*global cat, cd, cp, echo, exec, exit, find, mkdir, mv, pwd, rm, target, test*/

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

require("shelljs/make");

var path = require("path"),
    dateformat = require("dateformat"),
    nodeCLI = require("shelljs-nodecli"),
    os = require("os");

//------------------------------------------------------------------------------
// Settings
//------------------------------------------------------------------------------

/*
 * A little bit fuzzy. My computer has a first CPU speed of 3093 and the perf test
 * always completes in < 2000ms. However, Travis is less predictable due to
 * multiple different VM types. So I'm fudging this for now in the hopes that it
 * at least provides some sort of useful signal.
 */
var PERF_MULTIPLIER = 7.5e6;

//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------

var NODE = "node ", // intentional extra space
    NODE_MODULES = "./node_modules/",
    TEMP_DIR = "./tmp/",
    BUILD_DIR = "./build/",

    // Utilities - intentional extra space at the end of each string
    MOCHA = NODE_MODULES + "mocha/bin/_mocha ",
    ESLINT = NODE + " bin/eslint.js ",

    // Files
    MAKEFILE = "./Makefile.js",
    /*eslint-disable no-use-before-define */
    JS_FILES = find("lib/").filter(fileType("js")).join(" "),
    JSON_FILES = find("conf/").filter(fileType("json")).join(" ") + " .eslintrc",
    TEST_FILES = find("tests/lib/").filter(fileType("js")).join(" ");
    /*eslint-enable no-use-before-define */

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Generates a function that matches files with a particular extension.
 * @param {string} extension The file extension (i.e. "js")
 * @returns {Function} The function to pass into a filter method.
 * @private
 */
function fileType(extension) {
    return function(filename) {
        return filename.substring(filename.lastIndexOf(".") + 1) === extension;
    };
}

/**
 * Generates a static file that includes each rule by name rather than dynamically
 * looking up based on directory. This is used for the browser version of ESLint.
 * @param {string} basedir The directory in which to look for code.
 * @returns {void}
 */
function generateRulesIndex(basedir) {
    var output = "module.exports = function() {\n";
    output += "    var rules = Object.create(null);\n";

    find(basedir + "rules/").filter(fileType("js")).forEach(function(filename) {
        var basename = path.basename(filename, ".js");
        output += "    rules[\"" + basename + "\"] = require(\"./rules/" + basename + "\");\n";
    });

    output += "\n    return rules;\n};";
    output.to(basedir + "load-rules.js");
}

/**
 * Creates a release version tag and pushes to origin.
 * @param {string} type The type of release to do (patch, minor, major)
 * @returns {void}
 */
function release(type) {
    target.test();
    exec("npm version " + type);
    target.changelog();
    exec("git push origin master --tags");
    exec("npm publish");
    target.gensite();
}

//------------------------------------------------------------------------------
// Tasks
//------------------------------------------------------------------------------

target.all = function() {
    target.test();
};

target.lint = function() {
    echo("Validating Makefile.js");
    exec(ESLINT + MAKEFILE);

    echo("Validating JSON Files");
    nodeCLI.exec("jsonlint", "-q -c", JSON_FILES);

    echo("Validating JavaScript files");
    exec(ESLINT + JS_FILES);

    echo("Validating JavaScript test files");
    exec(ESLINT + TEST_FILES);
};

target.test = function() {
    target.lint();
    target.checkRuleFiles();
    var errors = 0,
        lastReturn;

    // exec(ISTANBUL + " cover " + MOCHA + "-- -c " + TEST_FILES);
    lastReturn = nodeCLI.exec("istanbul", "cover", MOCHA, "-- -c", TEST_FILES);
    if (lastReturn.code !== 0) {
      errors++;
    }

    // exec(ISTANBUL + "check-coverage --statement 99 --branch 98 --function 99 --lines 99");
    lastReturn = nodeCLI.exec("istanbul", "check-coverage", "--statement 99 --branch 98 --function 99 --lines 99");
    if (lastReturn.code !== 0) {
      errors++;
    }

    target.browserify();

    lastReturn = nodeCLI.exec("mocha-phantomjs", "-R dot", "tests/tests.htm");
    if (lastReturn.code !== 0) {
      errors++;
    }

    if (errors) {
        exit(1);
    }
};

target.docs = function() {
    echo("Generating documentation");
    nodeCLI.exec("jsdoc", "-d jsdoc lib");
    echo("Documentation has been output to /jsdoc");
};

target.gensite = function() {

    echo("Generating eslint.org");
    var docsDir = "../eslint.github.io/docs",
        currentDir = pwd();

    rm("-r", docsDir);
    mkdir(docsDir);
    cp("-rf", "docs/*", docsDir);

    find(docsDir).forEach(function(filename) {
        if (test("-f", filename)) {
            var text = cat(filename);
            text = "---\ntitle: ESLint\nlayout: doc\n---\n<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->\n" + text;
            text.replace(/.md\)/g, ".html)").replace("README.html", "index.html").to(filename.replace("README.md", "index.md"));
        }
    });

    cd(docsDir);
    exec("git add -A .");
    exec("git commit -m \"Autogenerated new docs at " + dateformat(new Date()) + "\"");
    exec("git fetch origin && git rebase origin/master");
    exec("git push origin master");
    cd(currentDir);

};

target.browserify = function() {

    // 1. create temp and build directory
    if (!test("-d", TEMP_DIR)) {
        mkdir(TEMP_DIR);
    }

    if (!test("-d", BUILD_DIR)) {
        mkdir(BUILD_DIR);
    }

    // 2. copy files into temp directory
    cp("-r", "lib/*", TEMP_DIR);

    // 3. delete the load-rules.js file
    rm(TEMP_DIR + "load-rules.js");

    // 4. create new load-rule.js with hardcoded requires
    generateRulesIndex(TEMP_DIR);

    // 5. browserify the temp directory
    nodeCLI.exec("browserify", TEMP_DIR + "eslint.js", "-o", BUILD_DIR + "eslint.js", "-s eslint");
    // exec(BROWSERIFY + TEMP_DIR + "eslint.js -o " + BUILD_DIR + "eslint.js -s eslint");

    // 6. remove temp directory
    rm("-r", TEMP_DIR);
};

target.changelog = function() {

    // get most recent two tags
    var tags = exec("git tag", { silent: true }).output.trim().split(/\s/g),
        rangeTags = tags.slice(tags.length - 2),
        now = new Date(),
        timestamp = dateformat(now, "mmmm d, yyyy");

    // output header
    (rangeTags[1] + " - " + timestamp + "\n").to("CHANGELOG.tmp");

    // get log statements
    var logs = exec("git log --pretty=format:\"* %s (%an)\" " + rangeTags.join(".."), {silent:true}).output.split(/\n/g);
    logs = logs.filter(function(line) {
        return line.indexOf("Merge pull request") === -1 && line.indexOf("Merge branch") === -1;
    });
    logs.push(""); // to create empty lines
    logs.unshift("");

    // output log statements
    logs.join("\n").toEnd("CHANGELOG.tmp");

    // switch-o change-o
    cat("CHANGELOG.tmp", "CHANGELOG.md").to("CHANGELOG.md.tmp");
    rm("CHANGELOG.tmp");
    rm("CHANGELOG.md");
    mv("CHANGELOG.md.tmp", "CHANGELOG.md");

    // add into commit
    exec("git add CHANGELOG.md");
    exec("git commit --amend --no-edit");

};

target.checkRuleFiles = function() {

    echo("Validating rules");

    var confRules = require("./conf/eslint.json").rules;

    var ruleFiles = find("lib/rules/").filter(fileType("js")),
        rulesIndexText = cat("docs/rules/README.md"),
        errors = 0;

    ruleFiles.forEach(function(filename) {
        var basename = path.basename(filename, ".js"),
            isOffInIndex = rulesIndexText.search("(\\[" + basename + "\\])(.)+(off by default)") !== -1,
            isOffInConfig = confRules[basename] === 0 || (confRules[basename] && confRules[basename][0] === 0);

        // check for docs
        if (!test("-f", "docs/rules/" + basename + ".md")) {
            console.error("Missing documentation for rule %s", basename);
            errors++;
        } else {

            // check for entry in docs index
            if (rulesIndexText.indexOf("(" + basename + ".md)") === -1) {
                console.error("Missing link to documentation for rule %s in index", basename);
                errors++;
            }
        }

        // check for default configuration
        if (!confRules.hasOwnProperty(basename)) {
            console.error("Missing default setting for %s in eslint.json", basename);
            errors++;
        }

        // 'off by default' is not in index and the rule is disabled in config
        if (!isOffInIndex && isOffInConfig) {
            console.error("Missing '(off by default)' for rule %s in index", basename);
            errors++;
        }

        // 'off by default' is in index and the rule is enabled in config
        if (isOffInIndex && !isOffInConfig) {
            console.error("Rule documentation says that %s is off by default but it is enabled in eslint.json.", basename);
            errors++;
        }

        // check for tests
        if (!test("-f", "tests/lib/rules/" + basename + ".js")) {
            console.error("Missing tests for rule %s", basename);
            errors++;
        }

    });

    if (errors) {
        exit(1);
    }

};

function time(cmd, runs, runNumber, results, cb) {
    var start = process.hrtime();
    exec(cmd, { silent: true }, function() {
        var diff = process.hrtime(start),
            actual = (diff[0] * 1e3 + diff[1] / 1e6); // ms

        results.push(actual);
        echo("Performance Run #" + runNumber + ":  %dms", actual);
        if(runs > 1) {
            time(cmd, runs - 1, runNumber + 1, results, cb);
        } else {
            cb(results);
        }
    });

}

target.perf = function() {
    var cpuSpeed = os.cpus()[0].speed,
        max = PERF_MULTIPLIER / cpuSpeed,
        cmd = ESLINT + "./tests/performance/jshint.js";

    echo("CPU Speed is %d with multiplier %d", cpuSpeed, PERF_MULTIPLIER);

    time(cmd, 5, 1, [], function(results) {
        results.sort(function(a, b) {
            return a - b;
        });

        var median = results[~~(results.length / 2)];

        if (median > max) {
            echo("Performance budget exceeded: %dms (limit: %dms)", median, max);
            exit(1);
        } else {
            echo("Performance budget ok:  %dms (limit: %dms)", median, max);
        }
    });

};

target.patch = function() {
    release("patch");
};

target.minor = function() {
    release("minor");
};

target.major = function() {
    release("major");
};
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
This file contains a function that duplicates the input image
by using the storage client library's .copy method to upload
it to a different bucket.
 */

const StorageApi = require('@google-cloud/storage');
const storage = new StorageApi();

// creates a the name of the file to be used for the
// result of the function. Must be distrinct from the
// input file name
const createOutputFileName = (prefix = "", fileName) =>
    prefix
    // if a prefix was specified use that
    ? `${prefix}-${path.parse(fileName).base}`
    // else, append .out
    : `${path.parse(fileName).base}.out`

/*
Create a copy of an image and upload the result to an
output bucket
 */
const copyImage = (file, parameters) => {
    // extract the output bucket from the paramters
    const outputBucketName = parameters.outputBucketName
    // use the output prefix to create eh name of the output file
    const outputFileName = createOutputFileName(parameters.outputPrefix, file.name)
    //  construct the output file using the GCS client library
    const outputFile = storage.bucket(outputBucketName).file(outputFileName)

    // use the GCS client library's "copy" method to
    // upload to the output bucket.
    return file
        .copy(outputFile)
        .catch(console.error)
        // resolve with the outputfile
        .then(() => outputFile)
}

copyImage.parameters = {
    outputBucketName: {
        defaultValue: 'outputs-copied',
        validate: () => true,
    },
    outputPrefix: {
        defaultValue: 'copied',
        validate: () => true,
    },
}

module.exports = copyImage
<commit_msg>was missing path<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
This file contains a function that duplicates the input image
by using the storage client library's .copy method to upload
it to a different bucket.
 */

const StorageApi = require('@google-cloud/storage');
const storage = new StorageApi();
const path = require("path");

// creates a the name of the file to be used for the
// result of the function. Must be distrinct from the
// input file name
const createOutputFileName = (prefix = "", fileName) =>
    prefix
    // if a prefix was specified use that
    ? `${prefix}-${path.parse(fileName).base}`
    // else, append .out
    : `${path.parse(fileName).base}.out`

/*
Create a copy of an image and upload the result to an
output bucket
 */
const copyImage = (file, parameters) => {
    // extract the output bucket from the paramters
    const outputBucketName = parameters.outputBucketName
    // use the output prefix to create eh name of the output file
    const outputFileName = createOutputFileName(parameters.outputPrefix, file.name)
    //  construct the output file using the GCS client library
    const outputFile = storage.bucket(outputBucketName).file(outputFileName)

    // use the GCS client library's "copy" method to
    // upload to the output bucket.
    return file
        .copy(outputFile)
        .catch(console.error)
        // resolve with the outputfile
        .then(() => outputFile)
}

copyImage.parameters = {
    outputBucketName: {
        defaultValue: 'outputs-copied',
        validate: () => true,
    },
    outputPrefix: {
        defaultValue: 'copied',
        validate: () => true,
    },
}

module.exports = copyImage
<|endoftext|>


<commit_before>/*
 *  Manifest - organize a program of songs for an ensemble
 */

function Manifest(manifest) {

	var manifest = manifest ;

	var __Manifest = function(that) {
		that.manifest = this.manifest ;
		console.log('Creating manifest ', that.manifest) ;
	}(this) ;

	this.getBaseUrl = function(song) {

		if ( song.hasOwnProperty('baseUrl') && song.baseUrl !== '' ) {
			return song.baseUrl ;
		}
		if ( this.manifest.hasOwnProperty('baseUrl') && this.manifest.baseUrl !== '' ) {
			return this.manifest.baseUrl ;
		}
		return '' ;
	} ;

    this.displaySong = function(manifest, song) {

		var scoreIndex,
		    songIndex,
		    score,
		    part,
		    href,
			webDir = manifest.getBaseUrl(song) + song.fileLocation + '/pdf/',
		    html = '
' + song.title + '
' +
				"
Composed by " + song.composer ;

		if ( song.hasOwnProperty('arranger') &&
			 song.arranger !== '' &&
			 song.composer !== song.arranger ) {
			html += ', Arranged by ' + song.arranger ;
		}

		html += "
\n" ;

		if ( song.hasOwnProperty('recordings') ) {
			html += this.displayRecordings(song) ;
		}

		html += this.displayScoresAndParts(song) ;

		return html ;
	} ;

	this.displayRecordings = function(song) {

		var name,
			recording,
			href,
			html = "
Recordings
\n
\n" ;

		for ( name in song.recordings ) {
	 		recording = song.recordings[name] ;
			href = song.recordings[name] ;
			html += '
' + name + "
\n" ;
		};

		html += "
\n" ;

		return html ;
	} ;

	this.displayScoresAndParts = function(song) {

		var name,
			score,
			href,
			html = "
Scores
\n
\n" ;

		for ( name in song.scores ) {
	 		score = song.scores[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + score.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		}

		html += "
\n
Parts
\n" ;

		for ( name in song.parts ) {
			part = song.parts[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + part.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		};
		html += "
\n" ;

		return html ;
	} ;

	this.displayProgram = function() {

		console.log('in displayProgram with' +
			"\n    this", this,
		    "\n    and this.manifest", this.manifest,
		    "\n    and this.manifest.songs ", this.manifest.songs,
		    "\n    and this.manifest.programOrder ", this.manifest.programOrder,
		    "\n    and this.manifest.programOrder.length ", this.manifest.programOrder.length ) ;

		var programIndex, number, songIndex, song, baseUrl, html ;
		for ( programIndex = 0 ; programIndex < this.manifest.programOrder.length ; programIndex++ ) {

			number = this.manifest.programOrder[programIndex] ;
			songIndex = this.manifest.program[number] ;
			song = this.manifest.songs[songIndex] ;
			html += this.displaySong(this, song) ;
		}

		return html ;
	} ;

	this.displayPartsInBook = function(manifest, chair, partsLists) {

		var songId,
			song,
			partsList,
			partIndex,
			part,
			href,
			html = '
' + chair + '
' +
				"\n\n
\n" ;

		Object.keys(partsLists).forEach(function(songId) {

	    	song = this.manifest.songs[songId] ;
			partsList = partsLists[songId] ;
			html += '
' + song.title ;
			for ( partIndex = 0 ; partIndex < partsList.length ; partIndex++ ) {
				part = partsList[partIndex] ;
				href = manifest.getBaseUrl(song) + song.filePrefix + song.parts[part].fileSuffix + '.pdf' ;
				html += ' ' + part + '' ;
				if ( partIndex+1 < partsList.length ) {
					html += ',' ;
				}
			}
			html += "
\n" ;
		});

		html += "
\n" ;

		return html ;
	} ;

	this.displayPartsInBooks = function() {

		var html, key,
			books = this.manifest.partsInBooks ;

		for ( key in books ) {

			if ( books.hasOwnProperty(key) ) {

				html += this.displayPartsInBook( this, key, books[key] ) ;

			}
		}
	} ;

	this.displayManifest = function() {
		this.displayProgram() ;
		this.displayPartsInBooks() ;
	}
}

<commit_msg>incremental edits<commit_after>/*
 *  Manifest - organize a program of songs for an ensemble
 */

function Manifest(manifest) {

	var manifest = manifest ;

	var __Manifest = function(that) {
		that.manifest = this.manifest ;
		console.log('Creating manifest ', that.manifest) ;
	}(this) ;

	this.getBaseUrl = function(song) {

		if ( song.hasOwnProperty('baseUrl') && song.baseUrl !== '' ) {
			return song.baseUrl ;
		}
		if ( this.manifest.hasOwnProperty('baseUrl') && this.manifest.baseUrl !== '' ) {
			return this.manifest.baseUrl ;
		}
		return '' ;
	} ;

    this.displaySong = function(manifest, song) {

		var scoreIndex,
		    songIndex,
		    score,
		    part,
		    href,
			webDir = manifest.getBaseUrl(song) + song.fileLocation + '/pdf/',
		    html = '
' + song.title + '
' +
				"
Composed by " + song.composer ;

		if ( song.hasOwnProperty('arranger') &&
			 song.arranger !== '' &&
			 song.composer !== song.arranger ) {
			html += ', Arranged by ' + song.arranger ;
		}

		html += "
\n" ;

		if ( song.hasOwnProperty('recordings') ) {
			html += this.displayRecordings(song) ;
		}

		html += this.displayScoresAndParts(song) ;

		return html ;
	} ;

	this.displayRecordings = function(song) {

		var name,
			recording,
			href,
			html = "
Recordings
\n
\n" ;

		for ( name in song.recordings ) {
	 		recording = song.recordings[name] ;
			href = song.recordings[name] ;
			html += '
' + name + "
\n" ;
		};

		html += "
\n" ;

		return html ;
	} ;

	this.displayScoresAndParts = function(song) {

		var name,
			score,
			href,
			html = "
Scores
\n
\n" ;

		for ( name in song.scores ) {
	 		score = song.scores[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + score.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		}

		html += "
\n
Parts
\n" ;

		for ( name in song.parts ) {
			part = song.parts[name] ;
			href = this.getBaseUrl(song) + song.filePrefix + part.fileSuffix + '.pdf' ;
			html += '
' + name + "
\n" ;
		};
		html += "
\n" ;

		return html ;
	} ;

	this.displayProgram = function() {

		console.log('in displayProgram with' +
			"\n    this", this,
		    "\n    and this.manifest", this.manifest,
		    "\n    and this.manifest.songs ", this.manifest.songs,
		    "\n    and this.manifest.programOrder ", this.manifest.programOrder,
		    "\n    and this.manifest.programOrder.length ", this.manifest.programOrder.length ) ;

		var programIndex, number, songIndex, song, baseUrl, html ;
		for ( programIndex = 0 ; programIndex < this.manifest.programOrder.length ; programIndex++ ) {

			number = this.manifest.programOrder[programIndex] ;
			songIndex = this.manifest.program[number] ;
			song = this.manifest.songs[songIndex] ;
			html += this.displaySong(this, song) ;
		}

		return html ;
	} ;

	this.displayPartsInBook = function(manifest, chair, partsLists) {

		var songId,
			song,
			partsList,
			partIndex,
			part,
			href,
			html = '
' + chair + '
' +
				"\n\n
\n" ;

		Object.keys(partsLists).forEach(function(songId) {

	    	song = this.manifest.songs[songId] ;
			partsList = partsLists[songId] ;
			html += '
' + song.title ;
			for ( partIndex = 0 ; partIndex < partsList.length ; partIndex++ ) {
				part = partsList[partIndex] ;
				href = manifest.getBaseUrl(song) + song.filePrefix + song.parts[part].fileSuffix + '.pdf' ;
				html += ' ' + part + '' ;
				if ( partIndex+1 < partsList.length ) {
					html += ',' ;
				}
			}
			html += "
\n" ;
		});

		html += "
\n" ;

		return html ;
	} ;

	this.displayPartsInBooks = function() {

		var html, key,
			books = this.manifest.partsInBooks ;

		for ( key in books ) {

			if ( books.hasOwnProperty(key) ) {

				html += this.displayPartsInBook( this, key, books[key] ) ;

			}
		}

		return html ;
	} ;

	this.displayManifest = function() {
		var html = this.displayProgram() +
			this.displayPartsInBooks() ;
	}
}

<|endoftext|>


<commit_before>var remote
try {
  remote = require('electron').remote
} catch (e) {
  remote = require('remote')
}
var remoteConsole = remote.require('console')

// we have to do this so that mocha output doesn't look like shit
console.log = function () {
  remoteConsole.log.apply(remoteConsole, arguments)
}

console.dir = function () {
  remoteConsole.dir.apply(remoteConsole, arguments)
}

// if we don't do this, we get socket errors and our tests crash
Object.defineProperty(process, 'stdout', {
  value: remote.process.stdout
})
<commit_msg>Remove unused file<commit_after><|endoftext|>