<commit_before>(function() {
	/* jshint node: true */
	var
		fs = require("fs"),
		path = require("path"),
		walker = require("walker"),
		uglify = require("uglify-js"),
		nopt = require("nopt"),
		less = require("less");

	var basename = path.basename(__filename),
		w = console.log,
		e = console.error,
		opt;

	// Shimming path.relative with 0.8.8's version if it doesn't exist
	if(!path.relative){
		path.relative = require('./path-relative-shim').relative;
	}

	function printUsage() {
		w("Enyo 2.0 Minifier");
		w("Flags:");
		w("-no-less:", "Don't compile less; instad substitute css for less");
		w("-no-alias:", "Don't use path macros");
		w("-alias:", "Give paths a macroized alias");
		w("-enyo ENYOPATH:", "Path to enyo loader (enyo/enyo.js)");
		w("-output PATH/NAME:", "name of output file, prepend folder paths to change output directory");
		w("--beautify:", "Output pretty version that's less compressed but has code on separate lines");
		w("-h, -?, -help:", "Show this message");
	}

	// properly split path based on platform
	function pathSplit(inPath) {
		var sep = process.platform == "win32" ? "\\" : "/";
		return inPath.split(sep);
	}

	function buildPathBlock(loader) {
		var p$ = [];
		for (var i=0, p; (p=loader.packages[i]); i++) {
			if (p.name.indexOf("-") == -1) {
				p$.push(p.name + ': "' + p.folder + '"');
			}
		}
		p = p$.join(', ');
		return !p ? "" : "// minifier: path aliases\nenyo.path.addPaths({" + p + "});\n";
	}

	function concatCss(loader, doneCB) {
		w("");
		var blob = "";
		var addToBlob = function(sheet, code) {
			// fix url paths
			code = code.replace(/url\([^)]*\)/g, function(inMatch) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(inMatch);
				var urlPath = matches[3] || matches[5] || matches[6];
				// skip data urls
				if (/^data:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// skip an external link
				if (/^http(:?s)?:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// get absolute path to referenced asset
				var normalizedUrlPath = path.join(sheet, "..", urlPath);
				// Make relative asset path to built css
				var relPath = path.relative(path.dirname(opt.output || "build"), normalizedUrlPath);
				if (process.platform == "win32") {
					relPath = pathSplit(relPath).join("/");
				}
				return "url(" + relPath + ")";
			});
			blob += "\n/* " + sheet + " */\n\n" + code + "\n";
		};
		// Pops one sheet off the sheets[] array, reads (and parses if less), and then
		// recurses again from the async callback until no sheets left, then calls doneCB
		function readAndParse(sheets) {
			var sheet = sheets.shift();
			if (sheet) {
				w(sheet);
				var isLess = (sheet.slice(-4) == "less");
				if (isLess && (opt.less !== true)) {
					sheet = sheet.slice(0, sheet.length-4) + "css";
					isLess = false;
					w(" (Substituting CSS: " + sheet + ")");
				}
				var code = fs.readFileSync(sheet, "utf8");
				if (isLess) {
					var parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
					parser.parse(code, function (err, tree) {
						if (err) {
							console.error(err);
						} else {
							addToBlob(sheet, tree.toCSS());
						}
						readAndParse(sheets);
					});
				} else {
					addToBlob(sheet, code);
					readAndParse(sheets);
				}
			} else {
				doneCB(blob);
			}
		}
		readAndParse(loader.sheets);
	}

	var concatJs = function(loader) {
		w("");
		var blob = "";
		for (var i=0, m; (m=loader.modules[i]); i++) {
			if (typeof opt.alias === 'undefined' || opt.alias) {
				w("* inserting path aliases");
				blob += buildPathBlock(loader);
				opt.alias = false;
			}
			w(m.path);
			blob += "\n// " + m.rawPath + "\n" + compressJsFile(m.path) + "\n";
			if (opt.alias == m.rawPath) {
				w("* inserting path aliases");
				blob += buildPathBlock(loader);
			}
		}
		return blob;
	};

	var compressJsFile = function(inPath) {
		var outputOpts = {
//			beautify: false,
//			indent_level: 4,
			ascii_only: true
		};
		if (opt.beautify) {
			outputOpts.beautify = true;
			outputOpts.indent_level = 4;
		}
		var result = uglify.minify(inPath, {output: outputOpts});
		return result.code;
	};

	var finish = function(loader) {
		//w(loader.packages);
		//w('');
		//
		var output = opt.output || "build";
		var outfolder = path.dirname(output);
		var exists = fs.existsSync || path.existsSync;
		if (outfolder != "." && !exists(outfolder)) {
			fs.mkdirSync(outfolder);
		}
		// Unfortunately, less parsing is asynchronous, so concatCSS is now as well
		concatCss(loader, function(css) {
			if (css.length) {
				w("");
				fs.writeFileSync(output + ".css", css, "utf8");
			}
			//
			var js = concatJs(loader);
			/*
			if (css.length) {
				js += "\n// " + "minifier: load css" + "\n\n";
				js += 'enyo.machine.sheet("' + output + '.css");\n';
			}
			*/
			if (js.length) {
				w("");
				fs.writeFileSync(output + ".js", js, "utf8");
			}
			//
			w("");
			w("done.");
			w("");

			// required to properly terminate a
			// node.process.fork() call, as defined by
			// <http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options>
			process.exit(0);
		});
	};

	var knownOpts = {
		"alias": Boolean,
		"enyo": String,
		"output": String,
		"help": Boolean,
		"beautify": Boolean
	};

	var shortHands = {
		"alias": ['--alias'],
		"enyo": ['--enyo'],
		"output": ['--output'],
		"h": ['--help'],
		"?": ['--help'],
		"help": ['--help'],
		"beautify": ['--beautify']
	};

	opt = nopt(knownOpts, shortHands, process.argv, 2);
	opt.source = opt.argv.remain[0];
	w(opt);
	w("");

	w("");

	if (opt.help) {
		printUsage();
		process.exit();
	}

	// Send message to parent node process, if any
	process.on('uncaughtException', function (err) {
		e(err.stack);
		if (process.send) {
			// only available if parent-process is node
			process.send({error: err});
		}
		process.exit(1);
	});
	// receive error messages from child node processes
	process.on('message', function(msg) {
		console.dir(basename, msg);
		if (msg.error && msg.error.stack) {
			console.error(basename, msg.error.stack);
		}
		if (process.send) {
			process.send(msg);
		}
	});

	walker.init(opt.enyo);
	walker.walk(opt.source, finish);

})();<commit_msg>ENYO-2465: add quotes to the key names for addPath calls generated by minifier to handle cases where filenames aren't valid JS identifiers<commit_after>(function() {
	/* jshint node: true */
	var
		fs = require("fs"),
		path = require("path"),
		walker = require("walker"),
		uglify = require("uglify-js"),
		nopt = require("nopt"),
		less = require("less");

	var basename = path.basename(__filename),
		w = console.log,
		e = console.error,
		opt;

	// Shimming path.relative with 0.8.8's version if it doesn't exist
	if(!path.relative){
		path.relative = require('./path-relative-shim').relative;
	}

	function printUsage() {
		w("Enyo 2.0 Minifier");
		w("Flags:");
		w("-no-less:", "Don't compile less; instad substitute css for less");
		w("-no-alias:", "Don't use path macros");
		w("-alias:", "Give paths a macroized alias");
		w("-enyo ENYOPATH:", "Path to enyo loader (enyo/enyo.js)");
		w("-output PATH/NAME:", "name of output file, prepend folder paths to change output directory");
		w("--beautify:", "Output pretty version that's less compressed but has code on separate lines");
		w("-h, -?, -help:", "Show this message");
	}

	// properly split path based on platform
	function pathSplit(inPath) {
		var sep = process.platform == "win32" ? "\\" : "/";
		return inPath.split(sep);
	}

	function buildPathBlock(loader) {
		var p$ = [];
		for (var i=0, p; (p=loader.packages[i]); i++) {
			if (p.name.indexOf("-") == -1) {
				p$.push('"' + p.name + '": "' + p.folder + '"');
			}
		}
		p = p$.join(', ');
		return !p ? "" : "// minifier: path aliases\nenyo.path.addPaths({" + p + "});\n";
	}

	function concatCss(loader, doneCB) {
		w("");
		var blob = "";
		var addToBlob = function(sheet, code) {
			// fix url paths
			code = code.replace(/url\([^)]*\)/g, function(inMatch) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(inMatch);
				var urlPath = matches[3] || matches[5] || matches[6];
				// skip data urls
				if (/^data:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// skip an external link
				if (/^http(:?s)?:/.test(urlPath)) {
					return "url(" + urlPath + ")";
				}
				// get absolute path to referenced asset
				var normalizedUrlPath = path.join(sheet, "..", urlPath);
				// Make relative asset path to built css
				var relPath = path.relative(path.dirname(opt.output || "build"), normalizedUrlPath);
				if (process.platform == "win32") {
					relPath = pathSplit(relPath).join("/");
				}
				return "url(" + relPath + ")";
			});
			blob += "\n/* " + sheet + " */\n\n" + code + "\n";
		};
		// Pops one sheet off the sheets[] array, reads (and parses if less), and then
		// recurses again from the async callback until no sheets left, then calls doneCB
		function readAndParse(sheets) {
			var sheet = sheets.shift();
			if (sheet) {
				w(sheet);
				var isLess = (sheet.slice(-4) == "less");
				if (isLess && (opt.less !== true)) {
					sheet = sheet.slice(0, sheet.length-4) + "css";
					isLess = false;
					w(" (Substituting CSS: " + sheet + ")");
				}
				var code = fs.readFileSync(sheet, "utf8");
				if (isLess) {
					var parser = new(less.Parser)({filename:sheet, paths:[path.dirname(sheet)]});
					parser.parse(code, function (err, tree) {
						if (err) {
							console.error(err);
						} else {
							addToBlob(sheet, tree.toCSS());
						}
						readAndParse(sheets);
					});
				} else {
					addToBlob(sheet, code);
					readAndParse(sheets);
				}
			} else {
				doneCB(blob);
			}
		}
		readAndParse(loader.sheets);
	}

	var concatJs = function(loader) {
		w("");
		var blob = "";
		for (var i=0, m; (m=loader.modules[i]); i++) {
			if (typeof opt.alias === 'undefined' || opt.alias) {
				w("* inserting path aliases");
				blob += buildPathBlock(loader);
				opt.alias = false;
			}
			w(m.path);
			blob += "\n// " + m.rawPath + "\n" + compressJsFile(m.path) + "\n";
			if (opt.alias == m.rawPath) {
				w("* inserting path aliases");
				blob += buildPathBlock(loader);
			}
		}
		return blob;
	};

	var compressJsFile = function(inPath) {
		var outputOpts = {
//			beautify: false,
//			indent_level: 4,
			ascii_only: true
		};
		if (opt.beautify) {
			outputOpts.beautify = true;
			outputOpts.indent_level = 4;
		}
		var result = uglify.minify(inPath, {output: outputOpts});
		return result.code;
	};

	var finish = function(loader) {
		//w(loader.packages);
		//w('');
		//
		var output = opt.output || "build";
		var outfolder = path.dirname(output);
		var exists = fs.existsSync || path.existsSync;
		if (outfolder != "." && !exists(outfolder)) {
			fs.mkdirSync(outfolder);
		}
		// Unfortunately, less parsing is asynchronous, so concatCSS is now as well
		concatCss(loader, function(css) {
			if (css.length) {
				w("");
				fs.writeFileSync(output + ".css", css, "utf8");
			}
			//
			var js = concatJs(loader);
			/*
			if (css.length) {
				js += "\n// " + "minifier: load css" + "\n\n";
				js += 'enyo.machine.sheet("' + output + '.css");\n';
			}
			*/
			if (js.length) {
				w("");
				fs.writeFileSync(output + ".js", js, "utf8");
			}
			//
			w("");
			w("done.");
			w("");

			// required to properly terminate a
			// node.process.fork() call, as defined by
			// <http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options>
			process.exit(0);
		});
	};

	var knownOpts = {
		"alias": Boolean,
		"enyo": String,
		"output": String,
		"help": Boolean,
		"beautify": Boolean
	};

	var shortHands = {
		"alias": ['--alias'],
		"enyo": ['--enyo'],
		"output": ['--output'],
		"h": ['--help'],
		"?": ['--help'],
		"help": ['--help'],
		"beautify": ['--beautify']
	};

	opt = nopt(knownOpts, shortHands, process.argv, 2);
	opt.source = opt.argv.remain[0];
	w(opt);
	w("");

	w("");

	if (opt.help) {
		printUsage();
		process.exit();
	}

	// Send message to parent node process, if any
	process.on('uncaughtException', function (err) {
		e(err.stack);
		if (process.send) {
			// only available if parent-process is node
			process.send({error: err});
		}
		process.exit(1);
	});
	// receive error messages from child node processes
	process.on('message', function(msg) {
		console.dir(basename, msg);
		if (msg.error && msg.error.stack) {
			console.error(basename, msg.error.stack);
		}
		if (process.send) {
			process.send(msg);
		}
	});

	walker.init(opt.enyo);
	walker.walk(opt.source, finish);

})();<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const program = require('commander');

function sortDictionary(words) {
    function prepare(word) {
        return word.toLowerCase().replace(/[()[\]|?+.]/g, '');
    }

    words.sort(function(a, b) {
        return prepare(a).localeCompare(prepare(b));
    });
}

program.parse(process.argv);
program.parse(process.argv);

const filename = program.args[0];
let dict = JSON.parse(fs.readFileSync(filename).toString());
sortDictionary(dict);
dict = Array.from(new Set(dict)); // unique values

fs.writeFileSync(filename, JSON.stringify(dict, null, '  '));
<commit_msg>Remove unnecessary code<commit_after>'use strict';

const fs = require('fs');
const program = require('commander');

function sortDictionary(words) {
    function prepare(word) {
        return word.toLowerCase().replace(/[()[\]|?+.]/g, '');
    }

    words.sort(function(a, b) {
        return prepare(a).localeCompare(prepare(b));
    });
}

program.parse(process.argv);

const filename = program.args[0];
let dict = JSON.parse(fs.readFileSync(filename).toString());
sortDictionary(dict);
dict = Array.from(new Set(dict)); // unique values

fs.writeFileSync(filename, JSON.stringify(dict, null, '  '));
<|endoftext|>


<commit_before>

//console.log(JSON.stringify(JSON.parse(input)));

// function sortFactory(prop) {
//    return function(a,b){ return a[prop].localeCompare(b[prop]); };
// }
// input.sort(function(a, b) {
//     return a.A.localeCompare(b.B);
// });

//console.log(obj);
// console.log(obj.sort(sortFactory('A'))); // sort by name property
// console.log(obj.sort(sortFactory('A'))); // sort by surname property
//this is a json string used by matrix-org for test purposes

// input.sort(function(a, b) {
//     return a.b.localeCompare(b.a);
// });

function sortJSON(input) {
    JSON.stringify(input, Object.keys(obj).sort());

} // has to be a function called sort SortJson

//console.log(JSON.stringify(input, Object.keys(obj).sort()));

function canonicalJSON(input, err) {
    for (var i = 0; i < input.length; i++) { // i guess i have to use slices innstes creating forloops
        var sorted = sortJSON(input);

        if (err != null) {
            return null;
        }
    }
    for (var j = 0; j < sorted.length; i++) {
        return compactJSON(sorted);
    }
}

function compactJSON(input, output) {
    var i;
    for (i = 0; i < input.length; i++) {
        var c = input[i];
        if (c <= ' ') {
            continue;
        }
        output.push(c);
        if (c == '""') {
            for (i = 0; i < input.length; i++) {
                c = input[i];
                if (c == "\\") {
                    var escape = input[i];
                    if (escape == "u") {
                        compactUnicodeEscape(input, output, i);
                    } else if (escape == "/") {
                        output.push(escape);
                    } else {
                        output.push("\\", escape);
                    }
                    if (c == '""') {
                        break;
                    }
                }
            }
        }
        return output;
    }
}

function compactUnicodeEscape(input, output, index) {
    const ESCAPES = "uuuuuuuubtnufruuuuuuuuuuuuuuuuuu";
    const HEX = "0123456789ABCDEF";
    var inputLength = input.length;
    if (inputLength - index < 4) {
        return output, inputLength;
    }
    c = readHexDigits(input[index]);
    index += 4;
    if (c < ' ') {
        escape = ESCAPES[c];
        output.push(output, '\\', escape);
    }
    if (escape == 'u') {
        output.push("0", "0", ('0' + (c >> 4)), HEX[c & 0xF]);
    } else if (c == '\\' || c == '"') {
        // Otherwise the character only needs escaping if it is a QUOTE '"' or BACKSLASH '\\'.
        output.push(output, '\\', c);
    } else if (c < 0xD800 || c >= 0xE000) {
        // If the character isn't a surrogate pair then encoded it directly as UTF-8.
        var buffer;
        //n := utf8.EncodeRune(buffer[:], rune(c))
        //output = append(output, buffer[:n]...)
    } else {

        if (inputLength - index < 6) {
            return output, inputLength;
        }
        // Decode the 4 hex digits from the '\uXXXX'.
        var surrogate = readHexDigits(input[index + 2]);
        index += 6;
        // Reconstruct the UCS4 codepoint from the surrogates.
        var codepoint = 0x10000 + (((c & 0x3FF) << 10) | (surrogate & 0x3FF));
        // Encode the charater as UTF-8.
        var buffer;
        //n := utf8.EncodeRune(buffer[:], rune(codepoint))
        //output = append(output, buffer[:n]...)
    }
    return output, index;
}
//the basic idea is to reencode json and then arrange them into lexicographical order.
//gophers has a very copmplex way to do it,but JS is somewhat simple :)
// i guess there is nno need to use interfaces in js,as gophers use it to handle loosely handled or non-strictly typed json.<commit_msg>changes in json.js<commit_after>

//console.log(JSON.stringify(JSON.parse(input)));

// function sortFactory(prop) {
//    return function(a,b){ return a[prop].localeCompare(b[prop]); };
// }
// input.sort(function(a, b) {
//     return a.A.localeCompare(b.B);
// });

//console.log(obj);
// console.log(obj.sort(sortFactory('A'))); // sort by name property
// console.log(obj.sort(sortFactory('A'))); // sort by surname property
//this is a json string used by matrix-org for test purposes

// input.sort(function(a, b) {
//     return a.b.localeCompare(b.a);
// });

function sortJSON(input) {
    JSON.stringify(input, Object.keys(input).sort());

} // has to be a function called sort SortJson

//console.log(JSON.stringify(input, Object.keys(obj).sort()));

// function canonicalJSON(input, err) {
//     for (var i = 0; i < input.length; i++) { // i guess i have to use slices innstes creating forloops
//         var sorted = sortJSON(input);

//         if (err != null) {
//             return null;
//         }
//     }
//     for (var j = 0; j < sorted.length; i++) {
//         return compactJSON(sorted);
//     }
// }

function compactJSON(input, output) {
    var i;
    var c;
    for (i = 0; i < input.length; i++) {
        var c = input[i];
        if (c <= " ") {
            continue;
        }
        output.push(c);
        if (c == """") {
            for (i = 0; i < input.length; i++) {
                c = input[i];
                if (c == "\\") {
                    var escape = input[i];
                    if (escape == "u") {
                        compactUnicodeEscape(input, output, i);
                    } else if (escape == "/") {
                        output.push(escape);
                    } else {
                        output.push("\\", escape);
                    }
                    if (c == """") {
                        break;
                    }
                }
            }
        }
        return output;
    }
}

function compactUnicodeEscape(input, output, index) {
	var c;
    const ESCAPES = "uuuuuuuubtnufruuuuuuuuuuuuuuuuuu";
    const HEX = "0123456789ABCDEF";
    var inputLength = input.length;
    if (inputLength - index < 4) {
        return output, inputLength;
    }
    c = readHexDigits(input[index]);
    index += 4;
    if (c < " ") {
        escape = ESCAPES[c];
        output.push(output, "\\", escape);
    }
    if (escape == "u") {
        output.push("0", "0", ("0" + (c >> 4)), HEX[c & 0xF]);
    } else if (c == '\\' || c == '"') {
        // Otherwise the character only needs escaping if it is a QUOTE '"' or BACKSLASH '\\'.
        output.push(output, "\\", c);
    } else if (c < 0xD800 || c >= 0xE000) {
        // If the character isn't a surrogate pair then encoded it directly as UTF-8.
        var buffer;
        //n := utf8.EncodeRune(buffer[:], rune(c))
        //output = append(output, buffer[:n]...)
    } else {

        if (inputLength - index < 6) {
            return output, inputLength;
        }
        // Decode the 4 hex digits from the '\uXXXX'.
        var surrogate = readHexDigits(input[index + 2]);
        index += 6;
        // Reconstruct the UCS4 codepoint from the surrogates.
        var codepoint = 0x10000 + (((c & 0x3FF) << 10) | (surrogate & 0x3FF));
        // Encode the charater as UTF-8.
        var buffer;
        //n := utf8.EncodeRune(buffer[:], rune(codepoint))
        //output = append(output, buffer[:n]...)
    }
    return output, index;
}
//the basic idea is to reencode json and then arrange them into lexicographical order.
//gophers has a very copmplex way to do it,but JS is somewhat simple :)
// i guess there is nno need to use interfaces in js,as gophers use it to handle loosely handled or non-strictly typed json.<|endoftext|>


<commit_before>var getopt = require('node-getopt')
    , q = require('q')
    , _ = require('underscore')
    , util = require('util')
    , fs = require('fs')
    , novaform = require('novaform')
    , novastl = require('novastl')
    , AWS = require('aws-sdk')
    , uuid = require('node-uuid')
    , moment = require('moment')
    , stackUtils = require('../stack-utils');

var cmdopts = module.exports.opts = getopt.create([
    ['w', 'wait', 'Wait for completion'],
    ['h', 'help', 'Display help']
]);

cmdopts.setHelp('[[OPTIONS]]\n');

function Command(config, commonOptions, args, helpCallback) {
    if (!(this instanceof Command)) {
        return new Command(name, properties);
    }

    this.config = config;
    this.displayHelpAndExit = helpCallback;

    var opts = this.opts = cmdopts.parse(args);
    this.commonOptions = commonOptions;
    this.commandOptions = this.opts.options;

    if (opts.options.help) {
        helpCallback();
        return;
    }

    if (_(opts.argv).isEmpty()) {
        helpCallback('Missing project/component reference');
        return;
    } else if (opts.argv.length !== 1) {
        helpCallback('Too many project/component references specified');
        return;
    }

    var ref = opts.argv[0];
    ref = this.ref = Ref.parse(ref);
    if (!this.ref) {
        helpCallback('Invalid project ref');
        return;
    }
    if (!this.ref.component) {
        helpCallback('Component was not specified')
        return;
    }

    this.project = Project.load(this.ref.project, function(e) {
        helpCallback(util.format('Failed to load project "%s": %s', ref.project, e.message));
    });
    if (!this.project) {
        helpCallback(util.format('Could not find project "%s"', this.ref.project));
        return;
    }

    this.component = this.project.findComponent(this.ref.component);
    if (!this.component) {
        helpCallback(util.format('Component "%s" does not exist', this.ref.component));
        return;
    }
}

Command.prototype.execute = function() {
    var that = this;
    return q().then(function() {
        // TODO: validate project's components, make sure dependencies exist
    }).then(function() {
        // TODO: fetch output for each dependant component
    }).then(function() {
        // TODO: inject dependencies into the component
        var dependencies = {
            // infrastructure: { vpc: 'vpc-123' }
        };

        return dependencies;
    }).then(function(dependencies) {
        // build cloudformation resources
        if (that.commonOptions.verbose) {
            console.log('Generating cloudformation template...');
        }

        var stackName = that.ref.makeStackName();
        var deploymentDate = moment.utc();
        var deploymentId = uuid.v4();

        var result = that.component.build(dependencies);
        var stack = novaform.Stack(stackName);
        stack.add(result.resourceGroups);
        stack.add(result.outputs);

        var templateBody = stack.toJson();
        return {
            projectName: that.ref.project,
            componentName: that.ref.component,
            deploymentDate: deploymentDate,
            deploymentId: deploymentId,
            stackName: stackName,
            templateBody: templateBody,
        };
    }).then(function(deploymentConfig) {
        if (that.commonOptions.verbose) {
            console.log('Uploading cloudformation template to S3...');
        }

        var bucketname = that.config.s3.bucket;
        var region = that.config.s3.region;
        var datestring = deploymentConfig.deploymentDate.format();
        var keypath = util.format('%s%s/%s-%s',
            that.config.s3.keyPrefix, that.ref.project,
            deploymentConfig.stackName, datestring);

        var params = {
            Bucket: bucketname,
            Key: keypath,
            Body: deploymentConfig.templateBody,
        };

        function s3_endpoint(region) {
            if (!region) {
                return 'https://s3.amazonaws.com';
            }
            return util.format('https://s3-%s.amazonaws.com', region);
        }

        var s3 = new AWS.S3({ region : region });
        var s3upload = q.nbind(s3.upload, s3);
        return s3upload(params).then(function() {
            var s3endpoint = s3_endpoint(that.config.s3.region);
            var url = util.format('%s/%s/%s', s3endpoint, bucketname, keypath);
            return _.extend(deploymentConfig, {
                templateUrl: url,
            });
        }).catch(function(e) {
            throw new Error(util.format('Failed to upload to S3: %s', JSON.stringify(e)));
        });
    }).then(function(deploymentConfig) {
        if (that.commonOptions.verbose) {
            console.log('Deploying cloudformation stack...');
        }
        // TODO: initiate cloudformation deployment
        var region = that.config.s3.region;
        var cfn = new AWS.CloudFormation({ region : region });
        var getStackStatus = q.nbind(stackUtils.getStackStatus, stackUtils);
        return getStackStatus(cfn, deploymentConfig.stackName).then(function(status) {
            if (status === stackUtils.Status.DOES_NOT_EXIST) {
                // create a new stack
                var createStack = q.nbind(cfn.createStack, cfn);
                return createStack({
                    Capabilities: [ 'CAPABILITY_IAM' ], // TODO: this is only needed for some stacks that create iam roles, hm.
                    StackName: deploymentConfig.stackName,
                    TemplateURL: deploymentConfig.templateUrl,
                    Tags: [
                        { Key: 'deployment-id', Value: deploymentConfig.deploymentId },
                    ],
                }).then(function(data) {
                    return _.extend(deploymentConfig, {
                        cfn: cfn,
                        stackId: data.StackId,
                    });
                }).catch(function(err) {
                    throw new Error(util.format('Failed to initiate stack creation:\n%j', err));
                });
            } else {
                if (!stackUtils.isStatusComplete(status)) {
                    // already in progress?
                    throw new Error(util.format('Stack is not in a valid state for deployment (%s)', status));
                }
                // TODO: update
                return deploymentConfig;
            }
        });
    }).then(function(deploymentConfig) {
        // wait for completion
        if (that.commandOptions.wait) {
            var cfn = deploymentConfig.cfn;

            var maxWaitSeconds = 15 * 60;
            var start = moment();
            var maxEnd = moment(start);
            maxEnd.add(maxWaitSeconds, 'seconds');

            var getStackStatus = q.nbind(stackUtils.getStackStatus, stackUtils);

            if (that.commonOptions.verbose) {
                console.log('Waiting for deployment to complete...');
            }

            var f = function() {
                return getStackStatus(cfn, deploymentConfig.stackName).then(function(status) {
                    if (stackUtils.isStatusFailed(status)
                        || stackUtils.isStatusRolledBack(status)
                        || stackUtils.isStatusRollingback(status)) {
                        throw new Error('Stack deployment failed');
                    }
                    if (!stackUtils.isStatusComplete(status)) {
                        if (moment().isAfter(maxEnd)) {
                            throw new Error('Timeout');
                        }

                        if (that.commonOptions.verbose) {
                            console.log('Still waiting...');
                        }
                        return q.delay(1000).then(f);
                    }
                    return deploymentConfig;
                });
            };

            return f();
        }
        return deploymentConfig;
    }).then(function(deploymentConfig) {
        // TODO: fetch stack output and print it
        var output = {
            project: deploymentConfig.projectName,
            component: deploymentConfig.componentName,
            deploymentId: deploymentConfig.deploymentId,
            stackId: deploymentConfig.stackId,
        };

        if (that.commonOptions['output-format'] == 'json') {
            console.log(output);
        } else if (that.commonOptions['output-format'] == 'text') {
            console.log('Output:\n')
            for (var key in output) {
                var value = output[key];
                console.log(util.format('%s: %s', key, value));
            }
        }
    }).catch(function(e) {
        // TODO: differentiate between internal errors and valid exits like timeout or stack deployment failed
        console.error(util.format('Internal error: %s', e.message));
    });
}

Command.usageText = '[options] <project>/<component>'
Command.descriptionText = 'Deploys project component';
Command.optionsText = cmdopts.getHelp();

module.exports = Command;

// helpers
// TODO: this should probably be shared in lib/shared ?

function Ref(project, component) {
    this.project = project;
    this.component = component;
}

Ref.parse = function(ref) {
    var project;
    var component;

    if (typeof ref !== 'string') {
        return undefined;
    }
    var l = ref.split('/');
    if (l.length > 2) {
        return undefined;
    }
    project = l[0];
    component = l[1];

    return new Ref(project, component);
}

Ref.prototype.makeStackName = function() {
    // TODO: make camel case and validate limits
    return this.project + this.component;
};

function Project(config) {
    this.config = config;
}
Project.searchPaths = [process.cwd()];
Project.load = function(name, callback) {
    for (var i = 0; i < Project.searchPaths.length; ++i) {
        var searchPath = Project.searchPaths[i];
        var filepath = searchPath + '/' + name;

        if (fs.existsSync(filepath) || fs.existsSync(filepath + '.js')) {
            try {
                var module = require(filepath);
                var config = module(novaform, novastl);
                return new Project(config);
            } catch (e) {
                if (callback) {
                    callback(e);
                }
            }
            return null;
        }
    }
    return null;
};
Project.prototype.findComponent = function(name) {
    var component = _.findWhere(this.config.components, { name : name })
    return component;
}
<commit_msg>Implemented updating stacks and other deployment improvements.<commit_after>var getopt = require('node-getopt')
    , q = require('q')
    , _ = require('underscore')
    , util = require('util')
    , fs = require('fs')
    , novaform = require('novaform')
    , novastl = require('novastl')
    , AWS = require('aws-sdk')
    , uuid = require('node-uuid')
    , moment = require('moment')
    , stackUtils = require('../stack-utils');

var cmdopts = module.exports.opts = getopt.create([
    ['w', 'wait', 'Wait for completion'],
    ['h', 'help', 'Display help']
]);

cmdopts.setHelp('[[OPTIONS]]\n');

function Command(config, commonOptions, args, helpCallback) {
    if (!(this instanceof Command)) {
        return new Command(name, properties);
    }

    this.config = config;
    this.displayHelpAndExit = helpCallback;

    var opts = this.opts = cmdopts.parse(args);
    this.commonOptions = commonOptions;
    this.commandOptions = this.opts.options;

    if (opts.options.help) {
        helpCallback();
        return;
    }

    if (_(opts.argv).isEmpty()) {
        helpCallback('Missing project/component reference');
        return;
    } else if (opts.argv.length !== 1) {
        helpCallback('Too many project/component references specified');
        return;
    }

    var ref = opts.argv[0];
    ref = this.ref = Ref.parse(ref);
    if (!this.ref) {
        helpCallback('Invalid project ref');
        return;
    }
    if (!this.ref.component) {
        helpCallback('Component was not specified')
        return;
    }

    this.project = Project.load(this.ref.project, function(e) {
        helpCallback(util.format('Failed to load project "%s": %s', ref.project, e.message));
    });
    if (!this.project) {
        helpCallback(util.format('Could not find project "%s"', this.ref.project));
        return;
    }

    this.component = this.project.findComponent(this.ref.component);
    if (!this.component) {
        helpCallback(util.format('Component "%s" does not exist', this.ref.component));
        return;
    }
}

Command.prototype._waitForStack = function(options, shouldStopCallback) {
    var cfn = options.cfn;
    var stackName = options.stackName;
    var maxWaitSeconds = options.maxWaitSeconds || 15 * 60;
    var waitSeconds = options.waitSeconds || 1;

    var start = moment();
    var maxEnd = moment(start);
    maxEnd.add(maxWaitSeconds, 'seconds');

    var getStackStatus = q.nbind(stackUtils.getStackStatus, stackUtils);

    var f = function() {
        return getStackStatus(cfn, stackName).then(function(status) {
            var callbackResult = shouldStopCallback(status);
            if (callbackResult) {
                return callbackResult;
            }
            if (moment().isAfter(maxEnd)) {
                throw new Error('Timeout');
            }
            return q.delay(waitSeconds * 1000).then(f);
        });
    };

    return f();
};

Command.prototype.execute = function() {
    var that = this;
    return q().then(function() {
        // TODO: validate project's components, make sure dependencies exist
    }).then(function() {
        // TODO: fetch output for each dependant component
    }).then(function() {
        // TODO: inject dependencies into the component
        var dependencies = {
            // infrastructure: { vpc: 'vpc-123' }
        };

        return dependencies;
    }).then(function(dependencies) {
        // build cloudformation resources
        if (that.commonOptions.verbose) {
            console.log('Generating cloudformation template...');
        }

        var stackName = that.ref.makeStackName();
        var deploymentDate = moment.utc();
        var deploymentId = uuid.v4();

        var result = that.component.build(dependencies);
        var stack = novaform.Stack(stackName);
        stack.add(result.resourceGroups);
        stack.add(result.outputs);

        var templateBody = stack.toJson();
        return {
            projectName: that.ref.project,
            componentName: that.ref.component,
            deploymentDate: deploymentDate,
            deploymentId: deploymentId,
            stackName: stackName,
            templateBody: templateBody,
        };
    }).then(function(deploymentConfig) {
        if (that.commonOptions.verbose) {
            console.log('Uploading cloudformation template to S3...');
        }

        var bucketname = that.config.s3.bucket;
        var region = that.config.s3.region;
        var datestring = deploymentConfig.deploymentDate.format();
        var keypath = util.format('%s%s/%s-%s',
            that.config.s3.keyPrefix, that.ref.project,
            deploymentConfig.stackName, datestring);

        var params = {
            Bucket: bucketname,
            Key: keypath,
            Body: deploymentConfig.templateBody,
        };

        function s3_endpoint(region) {
            if (!region) {
                return 'https://s3.amazonaws.com';
            }
            return util.format('https://s3-%s.amazonaws.com', region);
        }

        var s3 = new AWS.S3({ region : region });
        var s3upload = q.nbind(s3.upload, s3);
        return s3upload(params).then(function() {
            var s3endpoint = s3_endpoint(that.config.s3.region);
            var url = util.format('%s/%s/%s', s3endpoint, bucketname, keypath);
            return _.extend(deploymentConfig, {
                templateUrl: url,
            });
        }).catch(function(e) {
            throw new Error(util.format('Failed to upload to S3: %s', JSON.stringify(e)));
        });
    }).then(function(deploymentConfig) {
        // initiate cloudformation deployment
        var region = that.component.region;
        var cfn = that.cfn = new AWS.CloudFormation({ region : region });
        var getStackStatus = q.nbind(stackUtils.getStackStatus, stackUtils);
        if (that.commonOptions.verbose) {
            console.log('Checking cloudformation stack status...');
        }
        return getStackStatus(cfn, deploymentConfig.stackName).then(function(status) {
            if (status !== stackUtils.Status.ROLLBACK_COMPLETE) {
                // all good, nothing to do here.
                return status;
            }

            if (that.commonOptions.verbose) {
                console.log('Stack was stuck in a rollback state, deleting it before deploying...');
            }

            // oh, previous stack creation failed and we cannot update failed stack
            // the only option is to delete the stack and create it again.
            var deleteStack = q.nbind(cfn.deleteStack, cfn);
            return deleteStack({
                StackName: deploymentConfig.stackName
            }).then(function(data) {
                return that._waitForStack({
                    cfn: cfn,
                    stackName: deploymentConfig.stackName,
                }, function(status) {
                    if (status === stackUtils.Status.DOES_NOT_EXIST) {
                        return status;
                    }
                    console.log('Still waiting...');
                    return null;
                });
            }).catch(function(err) {
                throw new Error(util.format('Failed to delete stack "%s": %j', deploymentConfig.stackName, err));
            });
        }).then(function(status) {
            if (that.commonOptions.verbose) {
                console.log('Deploying cloudformation stack...');
            }
            if (status === stackUtils.Status.DOES_NOT_EXIST) {
                // create a new stack
                var createStack = q.nbind(cfn.createStack, cfn);
                return createStack({
                    Capabilities: [ 'CAPABILITY_IAM' ], // TODO: this is only needed for some stacks that create iam roles, hm.
                    StackName: deploymentConfig.stackName,
                    TemplateURL: deploymentConfig.templateUrl,
                    Tags: [
                        { Key: 'nova-project', Value: deploymentConfig.projectName },
                        { Key: 'nova-component', Value: deploymentConfig.componentName },
                    ],
                }).then(function(data) {
                    return _.extend(deploymentConfig, {
                        cfn: cfn,
                        stackId: data.StackId,
                    });
                }).catch(function(err) {
                    throw new Error(util.format('Failed to initiate stack creation:\n%j', err));
                });
            } else {
                if (!stackUtils.isStatusComplete(status)) {
                    // already in progress?
                    throw new Error(util.format('Stack is not in a valid state for deployment (%s)', status));
                }

                // update an existing stack
                var updateStack = q.nbind(cfn.updateStack, cfn);
                return updateStack({
                    Capabilities: [ 'CAPABILITY_IAM' ], // TODO: this is only needed for some stacks that create iam roles, hm.
                    StackName: deploymentConfig.stackName,
                    TemplateURL: deploymentConfig.templateUrl,
                }).then(function(data) {
                    return _.extend(deploymentConfig, {
                        cfn: cfn,
                        stackId: data.StackId,
                    });
                }).catch(function(err) {
                    throw new Error(util.format('Failed to initiate stack creation:\n%j', err));
                });
            }
        });
    }).then(function(deploymentConfig) {
        // wait for completion
        if (that.commandOptions.wait) {
            if (that.commonOptions.verbose) {
                console.log('Waiting for deployment to complete...');
            }

            return that._waitForStack({
                cfn: deploymentConfig.cfn,
                stackName: deploymentConfig.stackName,
            }, function(status) {
                if (stackUtils.isStatusFailed(status)
                    || stackUtils.isStatusRolledBack(status)
                    || stackUtils.isStatusRollingback(status)) {
                    throw new Error('Stack deployment failed');
                }
                if (!stackUtils.isStatusComplete(status)) {
                    if (that.commonOptions.verbose) {
                        console.log('Still waiting...');
                    }
                    return null;
                }
                return deploymentConfig;
            });
        }
        return deploymentConfig;
    }).then(function(deploymentConfig) {
        // TODO: fetch stack output and print it
        var output = {
            project: deploymentConfig.projectName,
            component: deploymentConfig.componentName,
            deploymentId: deploymentConfig.deploymentId,
            stackId: deploymentConfig.stackId,
        };

        if (that.commonOptions['output-format'] == 'json') {
            console.log(output);
        } else if (that.commonOptions['output-format'] == 'text') {
            console.log('Output:\n')
            for (var key in output) {
                var value = output[key];
                console.log(util.format('%s: %s', key, value));
            }
        }
    }).catch(function(e) {
        // TODO: differentiate between internal errors and valid exits like timeout or stack deployment failed
        console.error(util.format('Internal error: %s', e.stack));
    });
}

Command.usageText = '[options] <project>/<component>'
Command.descriptionText = 'Deploys project component';
Command.optionsText = cmdopts.getHelp();

module.exports = Command;

// helpers
// TODO: this should probably be shared in lib/shared ?

function Ref(project, component) {
    this.project = project;
    this.component = component;
}

Ref.parse = function(ref) {
    var project;
    var component;

    if (typeof ref !== 'string') {
        return undefined;
    }
    var l = ref.split('/');
    if (l.length > 2) {
        return undefined;
    }
    project = l[0];
    component = l[1];

    return new Ref(project, component);
}

Ref.prototype.makeStackName = function() {
    // TODO: make camel case and validate limits
    return this.project + this.component;
};

function Project(config) {
    this.config = config;
}
Project.searchPaths = [process.cwd()];
Project.load = function(name, callback) {
    for (var i = 0; i < Project.searchPaths.length; ++i) {
        var searchPath = Project.searchPaths[i];
        var filepath = searchPath + '/' + name;

        if (fs.existsSync(filepath) || fs.existsSync(filepath + '.js')) {
            try {
                var module = require(filepath);
                var config = module(novaform, novastl);
                return new Project(config);
            } catch (e) {
                if (callback) {
                    callback(e);
                }
            }
            return null;
        }
    }
    return null;
};
Project.prototype.findComponent = function(name) {
    var component = _.findWhere(this.config.components, { name : name })
    return component;
}
<|endoftext|>


<commit_before>pref("extensions.hupper.filtertrolls", true);
pref("extensions.hupper.trolls", '');
pref("extensions.hupper.trollfiltermethod", 'hilight');
pref("extensions.hupper.hidetrollanswers", true);
pref("extensions.hupper.trollcolor", '#CFB2A7');

pref("extensions.hupper.huppers", '');
pref("extensions.hupper.filterhuppers", true);
pref("extensions.hupper.huppercolor", '#B5D7BE');

pref("extensions.hupper.replacenewcommenttext", true);
pref("extensions.hupper.newcommenttext", '[new]');

pref("extensions.hupper.prevnextlinks", true);

pref("extensions.hupper.tags", "{}");
pref("extensions.hupper.extracommentlinks", true);
pref("extensions.hupper.hilightforumlinesonhover", true);

pref("extensions.hupper.insertpermalink", false);

pref("extensions.hupper.insertnewtexttonode", true);
pref("extensions.hupper.fadeparentcomment", true);

pref("extensions.hupper.showqnavbox", true);

pref("extensions.hupper.hideads", false);
pref("extensions.hupper.highlightusers", "username:#fff999,username2:#999fff");
pref("extensions.hupper.username", '');

pref("extensions.hupper.hidetaxonomy", '');
pref("extensions.hupper.showinstatusbar", true);

pref("extensions.hupper.blocks", '({})');
<commit_msg> - add parseblocks preference<commit_after>pref("extensions.hupper.filtertrolls", true);
pref("extensions.hupper.trolls", '');
pref("extensions.hupper.trollfiltermethod", 'hilight');
pref("extensions.hupper.hidetrollanswers", true);
pref("extensions.hupper.trollcolor", '#CFB2A7');

pref("extensions.hupper.huppers", '');
pref("extensions.hupper.filterhuppers", true);
pref("extensions.hupper.huppercolor", '#B5D7BE');

pref("extensions.hupper.replacenewcommenttext", true);
pref("extensions.hupper.newcommenttext", '[new]');

pref("extensions.hupper.prevnextlinks", true);

pref("extensions.hupper.tags", "{}");
pref("extensions.hupper.extracommentlinks", true);
pref("extensions.hupper.hilightforumlinesonhover", true);

pref("extensions.hupper.insertpermalink", false);

pref("extensions.hupper.insertnewtexttonode", true);
pref("extensions.hupper.fadeparentcomment", true);

pref("extensions.hupper.showqnavbox", true);

pref("extensions.hupper.hideads", false);
pref("extensions.hupper.highlightusers", "username:#fff999,username2:#999fff");
pref("extensions.hupper.username", '');

pref("extensions.hupper.hidetaxonomy", '');
pref("extensions.hupper.showinstatusbar", true);

pref("extensions.hupper.blocks", '({})');
pref("extensions.hupper.parseblocks", true);
<|endoftext|>


<commit_before>pref("extensions.tbsync.log.toconsole",false);
pref("extensions.tbsync.log.tofile",false);
pref("extensions.tbsync.log.easdata",true);

pref("extensions.tbsync.eas.timeout", 90000);
pref("extensions.tbsync.eas.synclimit", 0);

pref("extensions.tbsync.maxnumbertosend",50);
pref("extensions.tbsync.hidephones",false);
pref("extensions.tbsync.showanniversary",false);
pref("extensions.tbsync.provider.eas", "Exchange Active Sync");
pref("extensions.tbsync.provider.dav", "CalDAV/CardDAV (sabre/dav, ownCloud, Nextcloud)");

pref("extensions.tbsync.clientID.type", "");
pref("extensions.tbsync.clientID.useragent", "");
<commit_msg>Setting default sync period to 6 month (max value for EAS)<commit_after>pref("extensions.tbsync.log.toconsole",false);
pref("extensions.tbsync.log.tofile",false);
pref("extensions.tbsync.log.easdata",true);

pref("extensions.tbsync.eas.timeout", 90000);
pref("extensions.tbsync.eas.synclimit", 7);

pref("extensions.tbsync.maxnumbertosend",50);
pref("extensions.tbsync.hidephones",false);
pref("extensions.tbsync.showanniversary",false);
pref("extensions.tbsync.provider.eas", "Exchange Active Sync");
pref("extensions.tbsync.provider.dav", "CalDAV/CardDAV (sabre/dav, ownCloud, Nextcloud)");

pref("extensions.tbsync.clientID.type", "");
pref("extensions.tbsync.clientID.useragent", "");
<|endoftext|>


<commit_before>// This is a port of the Docker 0.7.x go code that generates names from notable scientists and hackers.
// https://github.com/dotcloud/docker/blob/master/pkg/namesgenerator/names-generator.go
// docker license: Apache v 2.0 (https://github.com/dotcloud/docker/blob/master/LICENSE)

// Docker 0.7.x generates names from notable scientists and hackers.
//
// Ada Lovelace invented the first algorithm. http://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull)
// Alan Turing was a founding father of computer science. http://en.wikipedia.org/wiki/Alan_Turing.
// Albert Einstein invented the general theory of relativity. http://en.wikipedia.org/wiki/Albert_Einstein
// Ambroise Pare invented modern surgery. http://en.wikipedia.org/wiki/Ambroise_Par%C3%A9
// Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. http://en.wikipedia.org/wiki/Archimedes
// Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod.
// Charles Babbage invented the concept of a programmable computer. http://en.wikipedia.org/wiki/Charles_Babbage.
// Charles Darwin established the principles of natural evolution. http://en.wikipedia.org/wiki/Charles_Darwin.
// Dennis Ritchie and Ken Thompson created UNIX and the C programming language. http://en.wikipedia.org/wiki/Dennis_Ritchie http://en.wikipedia.org/wiki/Ken_Thompson
// Douglas Engelbart gave the mother of all demos: http://en.wikipedia.org/wiki/Douglas_Engelbart
// Emmett Brown invented time travel. http://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff)
// Enrico Fermi invented the first nuclear reactor. http://en.wikipedia.org/wiki/Enrico_Fermi.
// Euclid invented geometry. http://en.wikipedia.org/wiki/Euclid
// Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth.  http://en.wikipedia.org/wiki/Galileo_Galilei
// Henry Poincare made fundamental contributions in several fields of mathematics. http://en.wikipedia.org/wiki/Henri_Poincar%C3%A9
// Isaac Newton invented classic mechanics and modern optics. http://en.wikipedia.org/wiki/Isaac_Newton
// John McCarthy invented LISP: http://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)
// Leonardo Da Vinci invented too many things to list here. http://en.wikipedia.org/wiki/Leonardo_da_Vinci.
// Linus Torvalds invented Linux and Git. http://en.wikipedia.org/wiki/Linus_Torvalds
// Louis Pasteur discovered vaccination, fermentation and pasteurization. http://en.wikipedia.org/wiki/Louis_Pasteur.
// Malcolm McLean invented the modern shipping container: http://en.wikipedia.org/wiki/Malcom_McLean
// Marie Curie discovered radioactivity. http://en.wikipedia.org/wiki/Marie_Curie.
// Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. http://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB
// Niels Bohr is the father of quantum theory. http://en.wikipedia.org/wiki/Niels_Bohr.
// Nikola Tesla invented the AC electric system and every gaget ever used by a James Bond villain. http://en.wikipedia.org/wiki/Nikola_Tesla
// Pierre de Fermat pioneered several aspects of modern mathematics. http://en.wikipedia.org/wiki/Pierre_de_Fermat
// Richard Feynman was a key contributor to quantum mechanics and particle physics. http://en.wikipedia.org/wiki/Richard_Feynman
// Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. http://en.wikipedia.org/wiki/Rob_Pike
// Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. http://en.wikipedia.org/wiki/Stephen_Hawking
// Steve Wozniak invented the Apple I and Apple II. http://en.wikipedia.org/wiki/Steve_Wozniak
// Werner Heisenberg was a founding father of quantum mechanics. http://en.wikipedia.org/wiki/Werner_Heisenberg
// William Shockley, Walter Houser Brattain and John Bardeen co-invented the transistor (thanks Brian Goff).
//        http://en.wikipedia.org/wiki/John_Bardeen
//        http://en.wikipedia.org/wiki/Walter_Houser_Brattain
//        http://en.wikipedia.org/wiki/William_Shockley

var left = [ "happy", "jolly", "dreamy", "sad", "angry",
    "pensive", "focused", "sleepy", "grave", "distracted",
    "determined", "stoic", "stupefied", "sharp", "agitated",
    "cocky", "tender", "goofy", "furious", "desperate",
    "hopeful", "compassionate", "silly", "lonely", "condescending",
    "naughty", "kickass", "drunk", "boring", "nostalgic",
    "ecstatic", "insane", "cranky", "mad", "jovial",
    "sick", "hungry", "thirsty", "elegant", "backstabbing",
    "clever", "trusting", "loving", "suspicious", "berserk",
    "high", "romantic", "prickly", "evil" ]
  , right = [ "lovelace", "franklin", "tesla", "einstein", "bohr",
    "davinci", "pasteur", "nobel", "curie", "darwin",
    "turing", "ritchie", "torvalds", "pike", "thompson",
    "wozniak", "galileo", "euclid", "newton", "fermat",
    "archimedes", "poincare", "heisenberg", "feynman", "hawking",
    "fermi", "pare", "mccarthy", "engelbart", "babbage",
    "albattani", "ptolemy", "bell", "wright", "lumiere",
    "morse", "mclean", "brown", "bardeen", "brattain",
    "shockley" ]
  ;

// Generates names from notable scientists and hackers.
// checker is a function that takes a name (string) and
// returns true if the name exists, else false.
// retries is the number of attempts to make to generate
// a random name before failing.
// Returns name or null if unable to generate a name that
// doesn't exist after the specified number of retries.
(function () {
  'use strict';

  if(!Utils) {
    Utils = {};
  }

  Utils.NamesGenerator = function () {
    function randnum(n) {
      var min = 0
        , max = n;

      return Math.floor(Math.random() * (max - min + 1) + min);
    }

    function randelem(a) {
      return a[randnum(a.length)];
    }

    return randelem(left) + _ + randelem(right);
  };
})();

module.exports = function (checker) {
  var name
    , retry = arguments.length > 1 && typeof arguments[1] == 'number' ?
      arguments[1] : 5;

  name = util.format('%s_%s', randelem(left), randelem(right));

  while (checker && checker(name) && retry) {
    name = util.format('%s%d', name, randnum(10));
    retry--;
  }

  return retry ? name : null;
};

<commit_msg>- Testing b2b demo.<commit_after>// This is a port of the Docker 0.7.x go code that generates names from notable scientists and hackers.
// https://github.com/dotcloud/docker/blob/master/pkg/namesgenerator/names-generator.go
// docker license: Apache v 2.0 (https://github.com/dotcloud/docker/blob/master/LICENSE)

// Docker 0.7.x generates names from notable scientists and hackers.
//
// Ada Lovelace invented the first algorithm. http://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull)
// Alan Turing was a founding father of computer science. http://en.wikipedia.org/wiki/Alan_Turing.
// Albert Einstein invented the general theory of relativity. http://en.wikipedia.org/wiki/Albert_Einstein
// Ambroise Pare invented modern surgery. http://en.wikipedia.org/wiki/Ambroise_Par%C3%A9
// Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. http://en.wikipedia.org/wiki/Archimedes
// Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod.
// Charles Babbage invented the concept of a programmable computer. http://en.wikipedia.org/wiki/Charles_Babbage.
// Charles Darwin established the principles of natural evolution. http://en.wikipedia.org/wiki/Charles_Darwin.
// Dennis Ritchie and Ken Thompson created UNIX and the C programming language. http://en.wikipedia.org/wiki/Dennis_Ritchie http://en.wikipedia.org/wiki/Ken_Thompson
// Douglas Engelbart gave the mother of all demos: http://en.wikipedia.org/wiki/Douglas_Engelbart
// Emmett Brown invented time travel. http://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff)
// Enrico Fermi invented the first nuclear reactor. http://en.wikipedia.org/wiki/Enrico_Fermi.
// Euclid invented geometry. http://en.wikipedia.org/wiki/Euclid
// Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth.  http://en.wikipedia.org/wiki/Galileo_Galilei
// Henry Poincare made fundamental contributions in several fields of mathematics. http://en.wikipedia.org/wiki/Henri_Poincar%C3%A9
// Isaac Newton invented classic mechanics and modern optics. http://en.wikipedia.org/wiki/Isaac_Newton
// John McCarthy invented LISP: http://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)
// Leonardo Da Vinci invented too many things to list here. http://en.wikipedia.org/wiki/Leonardo_da_Vinci.
// Linus Torvalds invented Linux and Git. http://en.wikipedia.org/wiki/Linus_Torvalds
// Louis Pasteur discovered vaccination, fermentation and pasteurization. http://en.wikipedia.org/wiki/Louis_Pasteur.
// Malcolm McLean invented the modern shipping container: http://en.wikipedia.org/wiki/Malcom_McLean
// Marie Curie discovered radioactivity. http://en.wikipedia.org/wiki/Marie_Curie.
// Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. http://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB
// Niels Bohr is the father of quantum theory. http://en.wikipedia.org/wiki/Niels_Bohr.
// Nikola Tesla invented the AC electric system and every gaget ever used by a James Bond villain. http://en.wikipedia.org/wiki/Nikola_Tesla
// Pierre de Fermat pioneered several aspects of modern mathematics. http://en.wikipedia.org/wiki/Pierre_de_Fermat
// Richard Feynman was a key contributor to quantum mechanics and particle physics. http://en.wikipedia.org/wiki/Richard_Feynman
// Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. http://en.wikipedia.org/wiki/Rob_Pike
// Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. http://en.wikipedia.org/wiki/Stephen_Hawking
// Steve Wozniak invented the Apple I and Apple II. http://en.wikipedia.org/wiki/Steve_Wozniak
// Werner Heisenberg was a founding father of quantum mechanics. http://en.wikipedia.org/wiki/Werner_Heisenberg
// William Shockley, Walter Houser Brattain and John Bardeen co-invented the transistor (thanks Brian Goff).
//        http://en.wikipedia.org/wiki/John_Bardeen
//        http://en.wikipedia.org/wiki/Walter_Houser_Brattain
//        http://en.wikipedia.org/wiki/William_Shockley

var left = [ "happy", "jolly", "dreamy", "sad", "angry",
    "pensive", "focused", "sleepy", "grave", "distracted",
    "determined", "stoic", "stupefied", "sharp", "agitated",
    "cocky", "tender", "goofy", "furious", "desperate",
    "hopeful", "compassionate", "silly", "lonely", "condescending",
    "naughty", "kickass", "drunk", "boring", "nostalgic",
    "ecstatic", "insane", "cranky", "mad", "jovial",
    "sick", "hungry", "thirsty", "elegant", "backstabbing",
    "clever", "trusting", "loving", "suspicious", "berserk",
    "high", "romantic", "prickly", "evil" ]
  , right = [ "lovelace", "franklin", "tesla", "einstein", "bohr",
    "davinci", "pasteur", "nobel", "curie", "darwin",
    "turing", "ritchie", "torvalds", "pike", "thompson",
    "wozniak", "galileo", "euclid", "newton", "fermat",
    "archimedes", "poincare", "heisenberg", "feynman", "hawking",
    "fermi", "pare", "mccarthy", "engelbart", "babbage",
    "albattani", "ptolemy", "bell", "wright", "lumiere",
    "morse", "mclean", "brown", "bardeen", "brattain",
    "shockley" ]
  ;

// Generates names from notable scientists and hackers.
// checker is a function that takes a name (string) and
// returns true if the name exists, else false.
// retries is the number of attempts to make to generate
// a random name before failing.
// Returns name or null if unable to generate a name that
// doesn't exist after the specified number of retries.
(function (win) {
  'use strict';

  if(!win.Utils) {
    win.Utils = {};
  }

  Utils.NamesGenerator = function () {
    function randnum(n) {
      var min = 0
        , max = n;

      return Math.floor(Math.random() * (max - min + 1) + min);
    }

    function randelem(a) {
      return a[randnum(a.length)];
    }

    return randelem(left) + _ + randelem(right);
  };
})(window);

<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router-dom';

import Icon from 'components/Icon';
import Pagination from 'components/Pagination';

export default class RoleList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filter: props.filter,
      reverseSort: props.reverseSort || false,
      sortBy: props.sortBy || 'role'
    };
  }

  setFilter(e) {
    this.setState({filter: e.target.value, sortBy: 'role'});
  }

  setSort(sortBy) {
    // If they change sort key, it's always ascending the first time.
    const reverseSort = (sortBy === this.state.sortBy) ? !this.state.reverseSort : false;
    this.setState({reverseSort, sortBy});
  }

  _renderRow(r) {
    return (

      <Link to={`/scheduler/${r.role}`}>{r.role}</Link>
      {r.jobCount}
      {r.cronJobCount}

);
  }

  render() {
    return (

        <Icon name='search' />
        <input
          autoFocus
          onChange={(e) => this.setFilter(e)}
          placeholder='Search for roles'
          type='text' />

             this.setSort('role')}>Role
             this.setSort('jobCount')}>Jobs
             this.setSort('cronJobCount')}>Crons

        <Pagination
          data={this.props.roles}
          filter={(r) => (this.state.filter) ? r.role.startsWith(this.state.filter) : true}
          hideIfSinglePage
          isTable
          numberPerPage={25}
          renderer={this._renderRow}
          reverseSort={this.state.reverseSort}
          sortBy={this.state.sortBy} />

);
  }
}
<commit_msg>Revert role searching in UI to old behavior<commit_after>import React from 'react';
import { Link } from 'react-router-dom';

import Icon from 'components/Icon';
import Pagination from 'components/Pagination';

export default class RoleList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filter: props.filter,
      reverseSort: props.reverseSort || false,
      sortBy: props.sortBy || 'role'
    };
  }

  setFilter(e) {
    this.setState({filter: e.target.value, sortBy: 'role'});
  }

  setSort(sortBy) {
    // If they change sort key, it's always ascending the first time.
    const reverseSort = (sortBy === this.state.sortBy) ? !this.state.reverseSort : false;
    this.setState({reverseSort, sortBy});
  }

  _renderRow(r) {
    return (

      <Link to={`/scheduler/${r.role}`}>{r.role}</Link>
      {r.jobCount}
      {r.cronJobCount}

);
  }

  render() {
    return (

        <Icon name='search' />
        <input
          autoFocus
          onChange={(e) => this.setFilter(e)}
          placeholder='Search for roles'
          type='text' />

             this.setSort('role')}>Role
             this.setSort('jobCount')}>Jobs
             this.setSort('cronJobCount')}>Crons

        <Pagination
          data={this.props.roles}
          filter={(r) => (this.state.filter) ? r.role.includes(this.state.filter) : true}
          hideIfSinglePage
          isTable
          numberPerPage={25}
          renderer={this._renderRow}
          reverseSort={this.state.reverseSort}
          sortBy={this.state.sortBy} />

);
  }
}
<|endoftext|>


<commit_before>/* eslint-disable qunit/require-expect */
import { click, currentURL } from '@ember/test-helpers';
import { run } from '@ember/runloop';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';
import a11yAudit from 'nomad-ui/tests/helpers/a11y-audit';
import TaskLogs from 'nomad-ui/tests/pages/allocations/task/logs';
import percySnapshot from '@percy/ember';
import faker from 'nomad-ui/mirage/faker';

let allocation;
let task;
let job;

module('Acceptance | task logs', function (hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(async function () {
    faker.seed(1);
    server.create('agent');
    server.create('node', 'forceIPv4');
    job = server.create('job', { createAllocations: false });

    allocation = server.create('allocation', {
      jobId: job.id,
      clientStatus: 'running',
    });
    task = server.db.taskStates.where({ allocationId: allocation.id })[0];

    run.later(run, run.cancelTimers, 1000);
  });

  test('it passes an accessibility audit', async function (assert) {
    await TaskLogs.visit({ id: allocation.id, name: task.name });
    await a11yAudit(assert);
  });

  test('/allocation/:id/:task_name/logs should have a log component', async function (assert) {
    await TaskLogs.visit({ id: allocation.id, name: task.name });
    assert.equal(
      currentURL(),
      `/allocations/${allocation.id}/${task.name}/logs`,
      'No redirect'
    );
    assert.ok(TaskLogs.hasTaskLog, 'Task log component found');
    assert.equal(document.title, `Task ${task.name} logs - Nomad`);
  });

  test('the stdout log immediately starts streaming', async function (assert) {
    await TaskLogs.visit({ id: allocation.id, name: task.name });
    const node = server.db.nodes.find(allocation.nodeId);
    const logUrlRegex = new RegExp(
      `${node.httpAddr}/v1/client/fs/logs/${allocation.id}`
    );
    assert.ok(
      server.pretender.handledRequests.filter((req) =>
        logUrlRegex.test(req.url)
      ).length,
      'Log requests were made'
    );
  });

  test('logs are accessible in a sidebar context', async function (assert) {
    await TaskLogs.visitParentJob({
      id: job.id,
      allocationId: allocation.id,
      name: task.name,
    });
    assert.notOk(TaskLogs.sidebarIsPresent, 'Sidebar is not present');

    run.later(() => {
      run.cancelTimers();
    }, 500);

    await click('button.logs-sidebar-trigger');

    assert.ok(TaskLogs.sidebarIsPresent, 'Sidebar is present');
    assert
      .dom('.task-context-sidebar h1.title')
      .includesText(task.name, 'Sidebar title is correct');
    assert
      .dom('.task-context-sidebar h1.title')
      .includesText(task.state, 'Task state is correctly displayed');
    await percySnapshot(assert);

    await click('.sidebar button.close');
    assert.notOk(TaskLogs.sidebarIsPresent, 'Sidebar is not present');
  });
});
<commit_msg>task logs page snapshot (#14709)<commit_after>/* eslint-disable qunit/require-expect */
import { click, currentURL } from '@ember/test-helpers';
import { run } from '@ember/runloop';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';
import a11yAudit from 'nomad-ui/tests/helpers/a11y-audit';
import TaskLogs from 'nomad-ui/tests/pages/allocations/task/logs';
import percySnapshot from '@percy/ember';
import faker from 'nomad-ui/mirage/faker';

let allocation;
let task;
let job;

module('Acceptance | task logs', function (hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(async function () {
    faker.seed(1);
    server.create('agent');
    server.create('node', 'forceIPv4');
    job = server.create('job', { createAllocations: false });

    allocation = server.create('allocation', {
      jobId: job.id,
      clientStatus: 'running',
    });
    task = server.db.taskStates.where({ allocationId: allocation.id })[0];

    run.later(run, run.cancelTimers, 1000);
  });

  test('it passes an accessibility audit', async function (assert) {
    await TaskLogs.visit({ id: allocation.id, name: task.name });
    await a11yAudit(assert);
    await percySnapshot(assert);
  });

  test('/allocation/:id/:task_name/logs should have a log component', async function (assert) {
    await TaskLogs.visit({ id: allocation.id, name: task.name });
    assert.equal(
      currentURL(),
      `/allocations/${allocation.id}/${task.name}/logs`,
      'No redirect'
    );
    assert.ok(TaskLogs.hasTaskLog, 'Task log component found');
    assert.equal(document.title, `Task ${task.name} logs - Nomad`);
  });

  test('the stdout log immediately starts streaming', async function (assert) {
    await TaskLogs.visit({ id: allocation.id, name: task.name });
    const node = server.db.nodes.find(allocation.nodeId);
    const logUrlRegex = new RegExp(
      `${node.httpAddr}/v1/client/fs/logs/${allocation.id}`
    );
    assert.ok(
      server.pretender.handledRequests.filter((req) =>
        logUrlRegex.test(req.url)
      ).length,
      'Log requests were made'
    );
  });

  test('logs are accessible in a sidebar context', async function (assert) {
    await TaskLogs.visitParentJob({
      id: job.id,
      allocationId: allocation.id,
      name: task.name,
    });
    assert.notOk(TaskLogs.sidebarIsPresent, 'Sidebar is not present');

    run.later(() => {
      run.cancelTimers();
    }, 500);

    await click('button.logs-sidebar-trigger');

    assert.ok(TaskLogs.sidebarIsPresent, 'Sidebar is present');
    assert
      .dom('.task-context-sidebar h1.title')
      .includesText(task.name, 'Sidebar title is correct');
    assert
      .dom('.task-context-sidebar h1.title')
      .includesText(task.state, 'Task state is correctly displayed');
    await percySnapshot(assert);

    await click('.sidebar button.close');
    assert.notOk(TaskLogs.sidebarIsPresent, 'Sidebar is not present');
  });
});
<|endoftext|>


<commit_before>var PropTypes = require('react/lib/ReactPropTypes');
var assign = require('object-assign');

var stringOrNumber = PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]);

// properties that match media queries
var matchers = {
  orientation: PropTypes.oneOf([
    'portrait',
    'landscape'
  ]),

  scan: PropTypes.oneOf([
    'progressive',
    'interlace'
  ]),

  aspectRatio: PropTypes.string,
  deviceAspectRatio: PropTypes.string,

  height: stringOrNumber,
  deviceHeight: stringOrNumber,

  width: stringOrNumber,
  deviceWidth: stringOrNumber,

  color: PropTypes.bool,

  colorIndex: PropTypes.bool,

  monochrome: PropTypes.bool,
  resolution: stringOrNumber
};

// media features
var features = {
  minAspectRatio: PropTypes.string,
  maxAspectRatio: PropTypes.string,
  minDeviceAspectRatio: PropTypes.string,
  maxDeviceAspectRatio: PropTypes.string,

  minHeight: stringOrNumber,
  maxHeight: stringOrNumber,
  minDeviceHeight: stringOrNumber,
  maxDeviceHeight: stringOrNumber,

  minWidth: stringOrNumber,
  maxWidth: stringOrNumber,
  minDeviceWidth: stringOrNumber,
  maxDeviceWidth: stringOrNumber,

  minColor: PropTypes.number,
  maxColor: PropTypes.number,

  minColorIndex: PropTypes.number,
  maxColorIndex: PropTypes.number,

  minMonochrome: PropTypes.number,
  maxMonochrome: PropTypes.number,

  minResolution: stringOrNumber,
  maxResolution: stringOrNumber
};

assign(features, matchers);

// media types
var types = {
  grid: PropTypes.bool,
  aural: PropTypes.bool,
  braille: PropTypes.bool,
  handheld: PropTypes.bool,
  print: PropTypes.bool,
  projection: PropTypes.bool,
  screen: PropTypes.bool,
  tty: PropTypes.bool,
  tv: PropTypes.bool,
  embossed: PropTypes.bool
};

var all = {};
assign(all, types);
assign(all, features);

module.exports = {
  all: all,
  types: types,
  matchers: matchers,
  features: features
};
<commit_msg>add type property<commit_after>var PropTypes = require('react/lib/ReactPropTypes');
var assign = require('object-assign');

var stringOrNumber = PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]);

// properties that match media queries
var matchers = {
  orientation: PropTypes.oneOf([
    'portrait',
    'landscape'
  ]),

  scan: PropTypes.oneOf([
    'progressive',
    'interlace'
  ]),

  aspectRatio: PropTypes.string,
  deviceAspectRatio: PropTypes.string,

  height: stringOrNumber,
  deviceHeight: stringOrNumber,

  width: stringOrNumber,
  deviceWidth: stringOrNumber,

  color: PropTypes.bool,

  colorIndex: PropTypes.bool,

  monochrome: PropTypes.bool,
  resolution: stringOrNumber
};

// media features
var features = {
  minAspectRatio: PropTypes.string,
  maxAspectRatio: PropTypes.string,
  minDeviceAspectRatio: PropTypes.string,
  maxDeviceAspectRatio: PropTypes.string,

  minHeight: stringOrNumber,
  maxHeight: stringOrNumber,
  minDeviceHeight: stringOrNumber,
  maxDeviceHeight: stringOrNumber,

  minWidth: stringOrNumber,
  maxWidth: stringOrNumber,
  minDeviceWidth: stringOrNumber,
  maxDeviceWidth: stringOrNumber,

  minColor: PropTypes.number,
  maxColor: PropTypes.number,

  minColorIndex: PropTypes.number,
  maxColorIndex: PropTypes.number,

  minMonochrome: PropTypes.number,
  maxMonochrome: PropTypes.number,

  minResolution: stringOrNumber,
  maxResolution: stringOrNumber
};

assign(features, matchers);

// media types
var types = {
  grid: PropTypes.bool,
  aural: PropTypes.bool,
  braille: PropTypes.bool,
  handheld: PropTypes.bool,
  print: PropTypes.bool,
  projection: PropTypes.bool,
  screen: PropTypes.bool,
  tty: PropTypes.bool,
  tv: PropTypes.bool,
  embossed: PropTypes.bool
};

var all = {};
assign(all, types);
assign(all, features);

// add the type property
assign(matchers, { type: Object.keys(types) });

module.exports = {
  all: all,
  types: types,
  matchers: matchers,
  features: features
};
<|endoftext|>


<commit_before>import * as core from '../core';
import Mesh from './Mesh';

/**
 * The Plane allows you to draw a texture across several points and them manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points);
 *  ```
 *
 * @class
 * @extends PIXI.mesh.Mesh
 * @memberof PIXI.mesh
 *
 */
export default class Plane extends Mesh
{
    /**
     * @param {PIXI.Texture} texture - The texture to use on the Plane.
     * @param {number} [verticesX=2] - The number of vertices in the x-axis
     * @param {number} [verticesY=2] - The number of vertices in the y-axis
     * @param {number} [direction=0] - Direction of the mesh. See {@link PIXI.GroupD8} for explanation
     */
    constructor(texture, verticesX, verticesY, direction)
    {
        super(texture);

        this._verticesX = verticesX || 2;
        this._verticesY = verticesY || 2;

        this._direction = (direction || 0) & (~1);

        this._lastWidth = texture.orig.width;
        this._lastHeight = texture.orig.height;

        this._width = 0;
        this._height = 0;

        /**
         *  Version counter for verticesX/verticesY change
         *
         * @member {number}
         * @private
         */
        this._dimensionsID = 0;

        this._lastDimensionsID = -1;

        /*
         * @member {Float32Array} Generated vertices positions, useful as starting position for vertices
         */
        this.calculatedVertices = null;

        /**
         *  Version counter for vertices updates
         *
         * @member {number}
         * @private
         */
        this._verticesID = 0;

        this._lastVerticesID = -1;

        /**
         *  Version counter for uvs updates
         *
         * @member {number}
         * @private
         */
        this._uvsID = 0;

        this._lastUvsID = -1;

        /**
         * anchor for a plane
         *
         * @member {PIXI.ObservablePoint}
         * @private
         */
        this._anchor = new core.ObservablePoint(this._onAnchorUpdate, this);

        this.drawMode = Mesh.DRAW_MODES.TRIANGLES;

        /**
         * reset the points on dimensions change
         * @member {boolean}
         * @default true
         */
        this.autoResetVertices = true;

        this.refresh();
    }

    /**
     * The width of the sprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     */
    get verticesX()
    {
        return this._verticesX;
    }

    set verticesX(value) // eslint-disable-line require-jsdoc
    {
        if (this._verticesX === value)
        {
            return;
        }
        this._verticesX = value;
        this._dimensionsID++;
    }

    /**
     * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     */
    get verticesY()
    {
        return this._verticesY;
    }

    set verticesY(value) // eslint-disable-line require-jsdoc
    {
        if (this._verticesY === value)
        {
            return;
        }
        this._verticesY = value;
        this._dimensionsID++;
    }

    /**
     * Direction of the mesh, see {@link PIXI.GroupD8} for explanation
     *
     * @param {number} [direction=0] - Direction of the mesh.
     */
    get direction()
    {
        return this._direction;
    }

    set direction(value) // eslint-disable-line require-jsdoc
    {
        if (value % 2 !== 0)
        {
            throw new Error('plane does not support diamond shape yet');
        }

        if (this._direction === value)
        {
            return;
        }
        this._direction = value;
        this._verticesID++;
    }

    /**
     * The width of the Plane, settings this wont modify the scale, but vertices will be cleared
     *
     * @member {number}
     */
    get width()
    {
        return this._width || this.texture.orig.width;
    }

    set width(value) // eslint-disable-line require-jsdoc
    {
        if (this._width === value)
        {
            return;
        }
        this._width = value;
        this._verticesID++;
    }

    /**
     * The height of the Plane, settings this wont modify the scale, but vertices will be cleared
     *
     * @member {number}
     */
    get height()
    {
        return this._height || this.texture.orig.height;
    }

    set height(value) // eslint-disable-line require-jsdoc
    {
        if (this._height === value)
        {
            return;
        }
        this._height = value;
        this._verticesID++;
    }

    /**
     * The anchor sets the origin point of the texture.
     * The default is 0,0 this means the texture's origin is the top left
     * Setting the anchor to 0.5,0.5 means the texture's origin is centered
     * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner
     *
     * @member {PIXI.ObservablePoint}
     */
    get anchor()
    {
        return this._anchor;
    }

    set anchor(value) // eslint-disable-line require-jsdoc
    {
        this._anchor.copy(value);
    }

    /**
     * updates vertices after anchor changes
     *
     * @private
     */
    _onAnchorUpdate()
    {
        this._verticesID++;
    }

    /**
     * Call when you updated some parameters manually
     */
    invalidateVertices()
    {
        this._verticesID++;
    }

    /**
     * Call when you updated some parameters manually
     */
    invalidateUvs()
    {
        this._uvsID++;
    }

    /**
     * Call when you updated some parameters manually
     */
    invalidate()
    {
        this._verticesID++;
        this._uvsID++;
    }

    /**
     * Refreshes the plane mesh
     *
     * @param {boolean} [forceUpdate=false] if true, everything will be updated in any case
     */
    refresh(forceUpdate)
    {
        this.refreshDimensions(forceUpdate);

        if (this._texture.noFrame)
        {
            return;
        }

        if (this._lastWidth !== this.width
            || this._lastHeight !== this.height)
        {
            this._lastWidth = this.width;
            this._lastHeight = this.height;
            if (this.autoResetVertices)
            {
                this._verticesID++;
            }
        }

        if (this._uvTransform.update(forceUpdate))
        {
            this._uvsID++;
        }

        if (this._uvsID !== this._lastUvsID)
        {
            this._refreshUvs();
        }

        this.refreshVertices();
    }

    /**
     * Refreshes structure of the plane mesh
     * when its done, refreshes vertices and uvs too
     *
     * @param {boolean} [forceUpdate=false] if true, dimensions will be updated any case
     */
    refreshDimensions(forceUpdate)
    {
        // won't be overwritten, that's why there's no private method

        if (!forceUpdate && this._lastDimensionsID === this._dimensionsID)
        {
            return;
        }

        this._lastDimensionsID = this._dimensionsID;
        this._verticesID++;
        this._uvsID++;

        const total = this._verticesX * this._verticesY;

        const segmentsX = this._verticesX - 1;
        const segmentsY = this._verticesY - 1;

        const indices = [];
        const totalSub = segmentsX * segmentsY;

        for (let i = 0; i < totalSub; i++)
        {
            const xpos = i % segmentsX;
            const ypos = (i / segmentsX) | 0;

            const value = (ypos * this._verticesX) + xpos;
            const value2 = (ypos * this._verticesX) + xpos + 1;
            const value3 = ((ypos + 1) * this._verticesX) + xpos;
            const value4 = ((ypos + 1) * this._verticesX) + xpos + 1;

            indices.push(value, value2, value3);
            indices.push(value2, value4, value3);
        }
        this.indices = new Uint16Array(indices);
        this.uvs = new Float32Array(total * 2);
        this.vertices = new Float32Array(total * 2);
        this.calculatedVertices = new Float32Array(total * 2);

        this.indexDirty++;
    }

    /**
     * Refreshes plane vertices coords
     * by default, makes them uniformly distributed
     *
     * @param {boolean} [forceUpdate=false] if true, vertices will be updated any case
     */
    refreshVertices(forceUpdate)
    {
        const texture = this._texture;

        if (texture.noFrame)
        {
            return;
        }

        if (forceUpdate || this._lastVerticesID !== this._verticesID)
        {
            this._lastVerticesID = this._verticesID;
            this._refreshVertices();
        }
    }

    /**
     * Refreshes plane UV coordinates
     *
     */
    _refreshUvs()
    {
        this._uvsID = this._lastUvsID;

        const total = this._verticesX * this._verticesY;
        const uvs = this.uvs;

        const direction = this._direction;

        const ux = core.GroupD8.uX(direction);
        const uy = core.GroupD8.uY(direction);
        const vx = core.GroupD8.vX(direction);
        const vy = core.GroupD8.vY(direction);

        const factorU = 1.0 / (this._verticesX - 1);
        const factorV = 1.0 / (this._verticesY - 1);

        for (let i = 0; i < total; i++)
        {
            let x = (i % this._verticesX);
            let y = ((i / this._verticesX) | 0);

            x = (x * factorU) - 0.5;
            y = (y * factorV) - 0.5;

            uvs[i * 2] = (ux * x) + (vx * y) + 0.5;
            uvs[(i * 2) + 1] = (uy * x) + (vy * y) + 0.5;
        }

        this.dirty++;

        this.multiplyUvs();
    }

    /**
     * calculates supposed position of vertices
     */
    calcVertices()
    {
        const total = this._verticesX * this._verticesY;
        const vertices = this.calculatedVertices;

        const width = this.width;
        const height = this.height;
        const direction = this._direction;

        let ux = core.GroupD8.uX(direction);
        let uy = core.GroupD8.uY(direction);
        let vx = core.GroupD8.vX(direction);
        let vy = core.GroupD8.vY(direction);

        const offsetX = (0.5 * (1 - (ux + vx))) - this._anchor._x;
        const offsetY = (0.5 * (1 - (uy + vy))) - this._anchor._y;
        const factorU = 1.0 / (this._verticesX - 1);
        const factorV = 1.0 / (this._verticesY - 1);

        ux *= factorU;
        uy *= factorU;
        vx *= factorV;
        vy *= factorV;

        for (let i = 0; i < total; i++)
        {
            const x = (i % this._verticesX);
            const y = ((i / this._verticesX) | 0);

            vertices[i * 2] = ((ux * x) + (vx * y) + offsetX) * width;
            vertices[(i * 2) + 1] = ((uy * x) + (vy * y) + offsetY) * height;
        }
    }

    /**
     * Refreshes vertices of Plane mesh
     * by default, makes them uniformly distributed
     *
     * @private
     */
    _refreshVertices()
    {
        this.calcVertices();

        const vertices = this.vertices;
        const calculatedVertices = this.calculatedVertices;
        const len = vertices.length;

        for (let i = 0; i < len; i++)
        {
            vertices[i] = calculatedVertices[i];
        }
    }

    /**
     * resets everything to defaults
     */
    reset()
    {
        if (!this.texture.noFrame)
        {
            this._refreshUvs();
            this.refreshVertices(true);
        }
    }
}
<commit_msg>cosmetic<commit_after>import * as core from '../core';
import Mesh from './Mesh';

/**
 * The Plane allows you to draw a texture across several points and them manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points);
 *  ```
 *
 * @class
 * @extends PIXI.mesh.Mesh
 * @memberof PIXI.mesh
 *
 */
export default class Plane extends Mesh
{
    /**
     * @param {PIXI.Texture} texture - The texture to use on the Plane.
     * @param {number} [verticesX=2] - The number of vertices in the x-axis
     * @param {number} [verticesY=2] - The number of vertices in the y-axis
     * @param {number} [direction=0] - Direction of the mesh. See {@link PIXI.GroupD8} for explanation
     */
    constructor(texture, verticesX, verticesY, direction)
    {
        super(texture);

        this._verticesX = verticesX || 2;
        this._verticesY = verticesY || 2;

        this._direction = (direction || 0) & (~1);

        this._lastWidth = texture.orig.width;
        this._lastHeight = texture.orig.height;

        this._width = 0;
        this._height = 0;

        /**
         *  Version counter for verticesX/verticesY change
         *
         * @member {number}
         * @private
         */
        this._dimensionsID = 0;

        this._lastDimensionsID = -1;

        /**
         *  Version counter for vertices updates
         *
         * @member {number}
         * @private
         */
        this._verticesID = 0;

        this._lastVerticesID = -1;

        /*
         * @member {Float32Array} Generated vertices positions, useful as starting position for vertices
         */
        this.calculatedVertices = null;

        /**
         *  Version counter for uvs updates
         *
         * @member {number}
         * @private
         */
        this._uvsID = 0;

        this._lastUvsID = -1;

        /**
         * anchor for a plane
         *
         * @member {PIXI.ObservablePoint}
         * @private
         */
        this._anchor = new core.ObservablePoint(this._onAnchorUpdate, this);

        this.drawMode = Mesh.DRAW_MODES.TRIANGLES;

        /**
         * reset the points on dimensions change
         * @member {boolean}
         * @default true
         */
        this.autoResetVertices = true;

        this.refresh();
    }

    /**
     * The width of the sprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     */
    get verticesX()
    {
        return this._verticesX;
    }

    set verticesX(value) // eslint-disable-line require-jsdoc
    {
        if (this._verticesX === value)
        {
            return;
        }
        this._verticesX = value;
        this._dimensionsID++;
    }

    /**
     * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     */
    get verticesY()
    {
        return this._verticesY;
    }

    set verticesY(value) // eslint-disable-line require-jsdoc
    {
        if (this._verticesY === value)
        {
            return;
        }
        this._verticesY = value;
        this._dimensionsID++;
    }

    /**
     * Direction of the mesh, see {@link PIXI.GroupD8} for explanation
     *
     * @param {number} [direction=0] - Direction of the mesh.
     */
    get direction()
    {
        return this._direction;
    }

    set direction(value) // eslint-disable-line require-jsdoc
    {
        if (value % 2 !== 0)
        {
            throw new Error('plane does not support diamond shape yet');
        }

        if (this._direction === value)
        {
            return;
        }
        this._direction = value;
        this._verticesID++;
    }

    /**
     * The width of the Plane, settings this wont modify the scale, but vertices will be cleared
     *
     * @member {number}
     */
    get width()
    {
        return this._width || this.texture.orig.width;
    }

    set width(value) // eslint-disable-line require-jsdoc
    {
        if (this._width === value)
        {
            return;
        }
        this._width = value;
        this._verticesID++;
    }

    /**
     * The height of the Plane, settings this wont modify the scale, but vertices will be cleared
     *
     * @member {number}
     */
    get height()
    {
        return this._height || this.texture.orig.height;
    }

    set height(value) // eslint-disable-line require-jsdoc
    {
        if (this._height === value)
        {
            return;
        }
        this._height = value;
        this._verticesID++;
    }

    /**
     * The anchor sets the origin point of the texture.
     * The default is 0,0 this means the texture's origin is the top left
     * Setting the anchor to 0.5,0.5 means the texture's origin is centered
     * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner
     *
     * @member {PIXI.ObservablePoint}
     */
    get anchor()
    {
        return this._anchor;
    }

    set anchor(value) // eslint-disable-line require-jsdoc
    {
        this._anchor.copy(value);
    }

    /**
     * updates vertices after anchor changes
     *
     * @private
     */
    _onAnchorUpdate()
    {
        this._verticesID++;
    }

    /**
     * Call when you updated some parameters manually
     */
    invalidateVertices()
    {
        this._verticesID++;
    }

    /**
     * Call when you updated some parameters manually
     */
    invalidateUvs()
    {
        this._uvsID++;
    }

    /**
     * Call when you updated some parameters manually
     */
    invalidate()
    {
        this._verticesID++;
        this._uvsID++;
    }

    /**
     * Refreshes the plane mesh
     *
     * @param {boolean} [forceUpdate=false] if true, everything will be updated in any case
     */
    refresh(forceUpdate)
    {
        this.refreshDimensions(forceUpdate);

        if (this._texture.noFrame)
        {
            return;
        }

        if (this._lastWidth !== this.width
            || this._lastHeight !== this.height)
        {
            this._lastWidth = this.width;
            this._lastHeight = this.height;
            if (this.autoResetVertices)
            {
                this._verticesID++;
            }
        }

        if (this._uvTransform.update(forceUpdate))
        {
            this._uvsID++;
        }

        if (this._uvsID !== this._lastUvsID)
        {
            this._refreshUvs();
        }

        this.refreshVertices();
    }

    /**
     * Refreshes structure of the plane mesh
     * when its done, refreshes vertices and uvs too
     *
     * @param {boolean} [forceUpdate=false] if true, dimensions will be updated any case
     */
    refreshDimensions(forceUpdate)
    {
        // won't be overwritten, that's why there's no private method

        if (!forceUpdate && this._lastDimensionsID === this._dimensionsID)
        {
            return;
        }

        this._lastDimensionsID = this._dimensionsID;
        this._verticesID++;
        this._uvsID++;

        const total = this._verticesX * this._verticesY;

        const segmentsX = this._verticesX - 1;
        const segmentsY = this._verticesY - 1;

        const indices = [];
        const totalSub = segmentsX * segmentsY;

        for (let i = 0; i < totalSub; i++)
        {
            const xpos = i % segmentsX;
            const ypos = (i / segmentsX) | 0;

            const value = (ypos * this._verticesX) + xpos;
            const value2 = (ypos * this._verticesX) + xpos + 1;
            const value3 = ((ypos + 1) * this._verticesX) + xpos;
            const value4 = ((ypos + 1) * this._verticesX) + xpos + 1;

            indices.push(value, value2, value3);
            indices.push(value2, value4, value3);
        }
        this.indices = new Uint16Array(indices);
        this.uvs = new Float32Array(total * 2);
        this.vertices = new Float32Array(total * 2);
        this.calculatedVertices = new Float32Array(total * 2);

        this.indexDirty++;
    }

    /**
     * Refreshes plane vertices coords
     * by default, makes them uniformly distributed
     *
     * @param {boolean} [forceUpdate=false] if true, vertices will be updated any case
     */
    refreshVertices(forceUpdate)
    {
        const texture = this._texture;

        if (texture.noFrame)
        {
            return;
        }

        if (forceUpdate || this._lastVerticesID !== this._verticesID)
        {
            this._lastVerticesID = this._verticesID;
            this._refreshVertices();
        }
    }

    /**
     * Refreshes plane UV coordinates
     *
     */
    _refreshUvs()
    {
        this._uvsID = this._lastUvsID;

        const total = this._verticesX * this._verticesY;
        const uvs = this.uvs;

        const direction = this._direction;

        const ux = core.GroupD8.uX(direction);
        const uy = core.GroupD8.uY(direction);
        const vx = core.GroupD8.vX(direction);
        const vy = core.GroupD8.vY(direction);

        const factorU = 1.0 / (this._verticesX - 1);
        const factorV = 1.0 / (this._verticesY - 1);

        for (let i = 0; i < total; i++)
        {
            let x = (i % this._verticesX);
            let y = ((i / this._verticesX) | 0);

            x = (x * factorU) - 0.5;
            y = (y * factorV) - 0.5;

            uvs[i * 2] = (ux * x) + (vx * y) + 0.5;
            uvs[(i * 2) + 1] = (uy * x) + (vy * y) + 0.5;
        }

        this.dirty++;

        this.multiplyUvs();
    }

    /**
     * calculates supposed position of vertices
     */
    calcVertices()
    {
        const total = this._verticesX * this._verticesY;
        const vertices = this.calculatedVertices;

        const width = this.width;
        const height = this.height;
        const direction = this._direction;

        let ux = core.GroupD8.uX(direction);
        let uy = core.GroupD8.uY(direction);
        let vx = core.GroupD8.vX(direction);
        let vy = core.GroupD8.vY(direction);

        const offsetX = (0.5 * (1 - (ux + vx))) - this._anchor._x;
        const offsetY = (0.5 * (1 - (uy + vy))) - this._anchor._y;
        const factorU = 1.0 / (this._verticesX - 1);
        const factorV = 1.0 / (this._verticesY - 1);

        ux *= factorU;
        uy *= factorU;
        vx *= factorV;
        vy *= factorV;

        for (let i = 0; i < total; i++)
        {
            const x = (i % this._verticesX);
            const y = ((i / this._verticesX) | 0);

            vertices[i * 2] = ((ux * x) + (vx * y) + offsetX) * width;
            vertices[(i * 2) + 1] = ((uy * x) + (vy * y) + offsetY) * height;
        }
    }

    /**
     * Refreshes vertices of Plane mesh
     * by default, makes them uniformly distributed
     *
     * @private
     */
    _refreshVertices()
    {
        this.calcVertices();

        const vertices = this.vertices;
        const calculatedVertices = this.calculatedVertices;
        const len = vertices.length;

        for (let i = 0; i < len; i++)
        {
            vertices[i] = calculatedVertices[i];
        }
    }

    /**
     * resets everything to defaults
     */
    reset()
    {
        if (!this.texture.noFrame)
        {
            this._refreshUvs();
            this.refreshVertices(true);
        }
    }
}
<|endoftext|>