<commit_before>var nextMovieId = 0;
var ratings = ["Unrated", "G", "PG", "PG-13", "R"];
var firstNames = ["Charlsie", "Ofelia", "Jerome", "Leana", "Harlan", "Annalisa", "Leida", "Dessie", "Valrie", "Sharen", "Sergio", "Mitzie", "Celia", "Debbra", "Florida", "Kara", "Jacquie", "Sherley", "Carson", "Staci", "Paula", "Dann", "Linette", "Meri", "Almeta", "Detra", "Lupe", "Neville", "Marivel", "Carmine", "Carina", "Laureen", "Lourdes", "Laverne", "Verona", "Gertha", "Jene", "Joslyn", "Jone", "Latoya", "Margurite", "Emmett", "Wallace", "Elana", "Xiomara", "Sabra", "Ouida", "Kenton", "Norene", "Raul"];
var lastNames = ["Avey", "Crofoot", "Flor", "Barletta", "Zoller", "Rosson", "Coomes", "Wilken", "Withey", "Ojeda", "Mennella", "Gauer", "Puccio", "Zimmerer", "Cottrell", "Bridgman", "Gershman", "Tinoco", "Ayoub", "Fournier", "Marcella", "Melrose", "Lafontaine", "Cathcart", "Cioffi", "Sands", "Lei", "Cardoso", "Dela", "Metcalfe", "Ethridge", "Fryer", "Warden", "Madson", "Gonsales", "Tobey", "Knecht", "Gallion", "Thibault", "Brockington", "Baney", "Haddox", "Kang", "Galyean", "Riccio", "Lake", "Mirabella", "Frechette", "Rearick", "Carmouche"];
var loremIpsum = [
	"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
	"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur",
	"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?",
	"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",
	"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.",
];
var words = loremIpsum.join(" ").replace(/,|!|\?|\./g, "").replace(/-/g, " ").split(" ");

var posterWidth = 153;
var posterHeight = 243;
var _canvas;
function makePoster(color) {
	if (!_canvas) {
		_canvas = document.createElement("canvas");
		_canvas.width = posterWidth;
		_canvas.height = posterHeight;
	}
	var ctxt = _canvas.getContext("2d");
	ctxt.fillStyle = color;
	ctxt.fillRect(0, 0, posterWidth, posterHeight);
	return _canvas.toDataURL();
}

var posterColors = [
	[68, 34, 87], [100, 66, 119], [132, 98, 151],
	[164, 162, 165], [196, 194, 197], [228, 226, 229]
];
var posters = posterColors.map(function (color) {
	return makePoster("rgb(" + color.join(", ") + ")");
});

function randomInt(first, last) {
	return Math.round(Math.random() * (last - first)) + first;
}

function randomElement(array) {
	return array[randomInt(0, array.length - 1)];
}

function genArray(minLength, maxLength, genElement) {
	var len = randomInt(minLength, maxLength);
	var result = new Array(len);
	for (var i = 0; i < len; i++) {
		result[i] = genElement();
	}
	return result;
}

function genActor() {
	return { name: randomElement(firstNames) + " " + randomElement(lastNames) };
}

function genTitleWord() {
	var word = randomElement(words).toLowerCase();
	return word[0].toUpperCase() + word.substr(1);
}

function genMovie() {
	return {
		id: nextMovieId++,
		title: (nextMovieId - 1 + " ") + genArray(1, 5, genTitleWord).join(" "),
		year: randomInt(1950, 2015),
		mpaa_rating: randomElement(ratings),
		synopsis: randomElement(loremIpsum),
		posters: {
			detailed: randomElement(posters)
		},
		ratings: {
			critics_score: randomInt(0, 100),
			audience_score: randomInt(0, 100)
		},
		abridged_cast: genArray(1, 8, genActor)
	};
}

var movieCount = 1000;
var movies = genArray(movieCount, movieCount, genMovie);
var moviesPerPage = 20;
var fetchDelay = 500;

function getSearchResults(query, page) {
	query = query.toLowerCase();
	var start = (page - 1) * moviesPerPage;
	var results = movies.filter(function (m) {
		return m.title.toLowerCase().indexOf(query) !== -1;
	});
	return WinJS.Promise.timeout(fetchDelay).then(function () {
		return {
			movies: results.slice(start, start + moviesPerPage),
			total: results.length
		};
	});
}

function getInTheaters(page) {
	var start = (page - 1) * moviesPerPage;
	return WinJS.Promise.timeout(fetchDelay).then(function () {
		return {
			movies: movies.slice(start, start + moviesPerPage),
			total: movies.length
		};
	});
}

module.exports = {
	getSearchResults: getSearchResults,
	getInTheaters: getInTheaters
};<commit_msg>Fix indentation<commit_after>var nextMovieId = 0;
var ratings = ["Unrated", "G", "PG", "PG-13", "R"];
var firstNames = ["Charlsie", "Ofelia", "Jerome", "Leana", "Harlan", "Annalisa", "Leida", "Dessie", "Valrie", "Sharen", "Sergio", "Mitzie", "Celia", "Debbra", "Florida", "Kara", "Jacquie", "Sherley", "Carson", "Staci", "Paula", "Dann", "Linette", "Meri", "Almeta", "Detra", "Lupe", "Neville", "Marivel", "Carmine", "Carina", "Laureen", "Lourdes", "Laverne", "Verona", "Gertha", "Jene", "Joslyn", "Jone", "Latoya", "Margurite", "Emmett", "Wallace", "Elana", "Xiomara", "Sabra", "Ouida", "Kenton", "Norene", "Raul"];
var lastNames = ["Avey", "Crofoot", "Flor", "Barletta", "Zoller", "Rosson", "Coomes", "Wilken", "Withey", "Ojeda", "Mennella", "Gauer", "Puccio", "Zimmerer", "Cottrell", "Bridgman", "Gershman", "Tinoco", "Ayoub", "Fournier", "Marcella", "Melrose", "Lafontaine", "Cathcart", "Cioffi", "Sands", "Lei", "Cardoso", "Dela", "Metcalfe", "Ethridge", "Fryer", "Warden", "Madson", "Gonsales", "Tobey", "Knecht", "Gallion", "Thibault", "Brockington", "Baney", "Haddox", "Kang", "Galyean", "Riccio", "Lake", "Mirabella", "Frechette", "Rearick", "Carmouche"];
var loremIpsum = [
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur",
    "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?",
    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",
    "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.",
];
var words = loremIpsum.join(" ").replace(/,|!|\?|\./g, "").replace(/-/g, " ").split(" ");

var posterWidth = 153;
var posterHeight = 243;
var _canvas;
function makePoster(color) {
    if (!_canvas) {
        _canvas = document.createElement("canvas");
        _canvas.width = posterWidth;
        _canvas.height = posterHeight;
    }
    var ctxt = _canvas.getContext("2d");
    ctxt.fillStyle = color;
    ctxt.fillRect(0, 0, posterWidth, posterHeight);
    return _canvas.toDataURL();
}

var posterColors = [
    [68, 34, 87], [100, 66, 119], [132, 98, 151],
    [164, 162, 165], [196, 194, 197], [228, 226, 229]
];
var posters = posterColors.map(function (color) {
    return makePoster("rgb(" + color.join(", ") + ")");
});

function randomInt(first, last) {
    return Math.round(Math.random() * (last - first)) + first;
}

function randomElement(array) {
    return array[randomInt(0, array.length - 1)];
}

function genArray(minLength, maxLength, genElement) {
    var len = randomInt(minLength, maxLength);
    var result = new Array(len);
    for (var i = 0; i < len; i++) {
        result[i] = genElement();
    }
    return result;
}

function genActor() {
    return { name: randomElement(firstNames) + " " + randomElement(lastNames) };
}

function genTitleWord() {
    var word = randomElement(words).toLowerCase();
    return word[0].toUpperCase() + word.substr(1);
}

function genMovie() {
    return {
        id: nextMovieId++,
        title: (nextMovieId - 1 + " ") + genArray(1, 5, genTitleWord).join(" "),
        year: randomInt(1950, 2015),
        mpaa_rating: randomElement(ratings),
        synopsis: randomElement(loremIpsum),
        posters: {
            detailed: randomElement(posters)
        },
        ratings: {
            critics_score: randomInt(0, 100),
            audience_score: randomInt(0, 100)
        },
        abridged_cast: genArray(1, 8, genActor)
    };
}

var movieCount = 1000;
var movies = genArray(movieCount, movieCount, genMovie);
var moviesPerPage = 20;
var fetchDelay = 500;

function getSearchResults(query, page) {
    query = query.toLowerCase();
    var start = (page - 1) * moviesPerPage;
    var results = movies.filter(function (m) {
        return m.title.toLowerCase().indexOf(query) !== -1;
    });
    return WinJS.Promise.timeout(fetchDelay).then(function () {
        return {
            movies: results.slice(start, start + moviesPerPage),
            total: results.length
        };
    });
}

function getInTheaters(page) {
    var start = (page - 1) * moviesPerPage;
    return WinJS.Promise.timeout(fetchDelay).then(function () {
        return {
            movies: movies.slice(start, start + moviesPerPage),
            total: movies.length
        };
    });
}

module.exports = {
    getSearchResults: getSearchResults,
    getInTheaters: getInTheaters
};<|endoftext|>


<commit_before>var path = require ( 'path' );

/**
 * List of grunt tasks.
 * @namespace gruntfile
 */
module.exports = function ( grunt ) {
	// We are checking how much time took each grunt task:
	require ( 'time-grunt' ) ( grunt );

	function lastModified ( minutes ) {
		return function ( filepath ) {
			var filemod = ( require ( 'fs' ).statSync ( filepath ) ).mtime;
			var timeago = ( new Date () ).setDate ( (new Date () ).getMinutes () - minutes );
			return ( filemod > timeago );
		};
	}

	grunt.initConfig ({
		pkg: grunt.file.readJSON ( 'package.json' ),

		jshint: {
			// List of all the source files to test:
			files: [
				'gruntfile.js',
				'lib/**/*.js'
			],

			// Configure JSHint (documented at http://www.jshint.com/docs/):
			options: {
				evil: false,
				multistr: true, // We need to take care about it.
				globals: {
					console: true,
					module: true
				}
			}
		},

		jsdoc : {
			dist : {
				src: [
					'gruntfile.js',
					'lib/**/*.js'
				],
				options: {
					'destination': 'doc',
					'package': 'package.json',
					'readme': 'README.md'
					// template : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template",
					// configure : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template/jsdoc.conf.json"
				}
			}
		}
	});

	//
	// The default task:
	//

	/**
	 * The default grunt task.
	 * @name default
	 * @memberof gruntfile
	 * @kind function
	 */
	grunt.registerTask ( 'default', [
		'jshint'
	]);

	//
	// More Grunt tasks:
	//

	//
	// Load all the modules that we need:
	//

	grunt.loadNpmTasks ( 'grunt-contrib-jshint' );
	grunt.loadNpmTasks ( 'grunt-jsdoc' );
};
<commit_msg>Minor fix in Gruntfile.js<commit_after>var path = require ( 'path' );

/**
 * List of grunt tasks.
 * @namespace gruntfile
 */
module.exports = function ( grunt ) {
	// We are checking how much time took each grunt task:
	require ( 'time-grunt' ) ( grunt );

	function lastModified ( minutes ) {
		return function ( filepath ) {
			var filemod = ( require ( 'fs' ).statSync ( filepath ) ).mtime;
			var timeago = ( curDate ).setMinutes ( ( curDate ).getMinutes () - minutes );
			return ( filemod > timeago );
		};
	}

	grunt.initConfig ({
		pkg: grunt.file.readJSON ( 'package.json' ),

		jshint: {
			files: {
				// List of all the source files to test:
				src: [
					'gruntfile.js',
					'lib/**/*.js'
				],

				// Run only on files been modified on the last day:
				filter: lastModified ( 24 * 60 )
			},

			// Configure JSHint (documented at http://www.jshint.com/docs/):
			options: {
				evil: false,
				multistr: true, // We need to take care about it.
				globals: {
					console: true,
					module: true
				}
			}
		},

		jsdoc : {
			dist : {
				src: [
					'gruntfile.js',
					'lib/**/*.js'
				],
				options: {
					'destination': 'doc',
					'package': 'package.json',
					'readme': 'README.md'
					// template : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template",
					// configure : "node_modules/grunt-jsdoc/node_modules/ink-docstrap/template/jsdoc.conf.json"
				}
			}
		}
	});

	//
	// The default task:
	//

	/**
	 * The default grunt task.
	 * @name default
	 * @memberof gruntfile
	 * @kind function
	 */
	grunt.registerTask ( 'default', [
		'jshint'
	]);

	//
	// More Grunt tasks:
	//

	//
	// Load all the modules that we need:
	//

	grunt.loadNpmTasks ( 'grunt-contrib-jshint' );
	grunt.loadNpmTasks ( 'grunt-jsdoc' );
};
<|endoftext|>


<commit_before>/*
 *     Copyright (c) 2012-2013 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global Wirecloud*/

(function () {

    "use strict";

    var VERSION_RE = /^((?:[1-9]\d*\.|0\.)*(?:[1-9]\d*|0))((?:a|b|rc)[1-9]\d*)?$/;

    var Version = function Version(version, source) {
        var groups;
        if (typeof version == 'string') {
            groups = version.match(VERSION_RE);
            this.array = groups[1].split('.').map(function (x) { return parseInt(x, 10); });
            this.pre_version = groups[2] != null ? groups[2] : null;
            this.text = version;
        } else if (version instanceof Array) {
            this.array = version;
            this.pre_version = null;
            this.text = version.join('.');
        } else {
            throw new TypeError();
        }
        this.source = source;
        Object.freeze(this);
    };

    Version.prototype.compareTo = function compareTo(version) {
        var len, value1, value2, pre_version1, pre_version2, i;

        len = Math.max(this.array.length, version.array.length);

        for (i = 0; i < len; i += 1) {
            value1 = this.array[i] != null ? this.array[i] : 0;
            value2 = version.array[i] != null ? version.array[i] : 0;

            if (value1 !== value2) {
                return value1 - value2;
            }
        }

        pre_version1 = this.pre_version;
        if (pre_version1 == null) {
            pre_version1 = "z";
        }
        pre_version2 = version.pre_version;
        if (pre_version2 == null) {
            pre_version2 = "z";
        }

        if (pre_version1 < pre_version2) {
            return -1;
        } else if (pre_version1 > pre_version2) {
            return 1;
        } else {
            return 0;
        }
    };

    Version.prototype.toString = function toString() {
        return this.text;
    };

    Wirecloud.Version = Version;
})();
<commit_msg>Fix version regular expression in frontend code<commit_after>/*
 *     Copyright (c) 2012-2013 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global Wirecloud*/

(function () {

    "use strict";

    var VERSION_RE = /^((?:[1-9]\d*\.|0\.)*(?:[1-9]\d*|0))((?:a|b|rc)[1-9]\d*)?(-dev)?.*$/; // Hangs the server if it doesn't match the RE

    var Version = function Version(version, source) {
        var groups;
        if (typeof version == 'string') {
            groups = version.match(VERSION_RE);
            this.array = groups[1].split('.').map(function (x) { return parseInt(x, 10); });
            this.pre_version = groups[2] != null ? groups[2] : null;
            this.text = version;
        } else if (version instanceof Array) {
            this.array = version;
            this.pre_version = null;
            this.text = version.join('.');
        } else {
            throw new TypeError();
        }
        this.source = source;
        Object.freeze(this);
    };

    Version.prototype.compareTo = function compareTo(version) {
        var len, value1, value2, pre_version1, pre_version2, i;

        len = Math.max(this.array.length, version.array.length);

        for (i = 0; i < len; i += 1) {
            value1 = this.array[i] != null ? this.array[i] : 0;
            value2 = version.array[i] != null ? version.array[i] : 0;

            if (value1 !== value2) {
                return value1 - value2;
            }
        }

        pre_version1 = this.pre_version;
        if (pre_version1 == null) {
            pre_version1 = "z";
        }
        pre_version2 = version.pre_version;
        if (pre_version2 == null) {
            pre_version2 = "z";
        }

        if (pre_version1 < pre_version2) {
            return -1;
        } else if (pre_version1 > pre_version2) {
            return 1;
        } else {
            return 0;
        }
    };

    Version.prototype.toString = function toString() {
        return this.text;
    };

    Wirecloud.Version = Version;
})();
<|endoftext|>


<commit_before>(function() {

	var _DEBUG = 		false,
 		_SHOW_PATH = 	false;

	CAAT.Enemy = function( ){
		CAAT.Enemy.superclass.constructor.call( this );
		this.target = game.player;
		return this;
	};

	CAAT.Enemy.prototype = {

		id:				0,
		index:			-1,
		level:			1,
		hitDice:		6,
		hp:				10,
		wounds: 		0,
		type:			'unknown',
		role: 			"melee",
		speed:			1,
		attackSpeed:	6,
		cooldown:		6,
		element:		"physical",
		range:			150,
		moving:			false,
		dropTable:		null,
		tick_done:		0,
		summoned:		false,
		_dest:			{ x:0, y:0 },
		_t:				0,

		setup : function( ) {

			var data = game.enemiesBook[ this.type ];
			for ( p in data ) {
				this[ p ] = data[ p ];
			}
			this.buffs = [];
			this.modifiers = { hp: 0, speed: 0 };
			this.hp = roll( this.level, this.hitDice, this.level );
			this.id = this.type+roll( 1, 999 );
		},

		add : function( type, summoned ) {

			this.type = type;
			this.summoned = summoned;
			this.setup( );

			this.x = director.width + this.width;
			this.y = (director.height/4)+Math.random()*(director.height*3/4);

			this.sprite = new CAAT.Foundation.SpriteImage().initialize(
				director.getImage( this.type ),
				this.frameH || 1,
				this.frameW || 1
			);

			if ( this.animations && this.animations !== {} ){

				var a = null;
				for ( id in this.animations ) {
					a = this.animations[ id ];
					if ( a ) {
						if ( id === 'attack' && !a.reset ) {
							a.reset = function ( s ) { s.playAnimation( 'stand' ) };
						}
						this.sprite.addAnimation( id, a.frames, a.duration, a.reset );
					}
				}
			}

			this.setBackgroundImage( this.sprite, true ).
				enableEvents( false ).
				setPositionAnchor( 0.5, 0.5 );

			game.bg.addChild( this );
			this.index = game.enemies.push( this );
			this.playAnimation( 'stand' );

			if( _DEBUG ) CAAT.log("[Enemy] "+this.id+" is added" );
		},

		getDamage: function( ) {
			return roll();
		},

		getHp: function(){

			var mods = [0];
			for ( b in this.buffs ) {
				 if ( this.buffs[b].modSpeed ) {
					 mods.push( this.buffs[b].modHp );
				 }
			}
			return this.hp - this.wounds + _.max( mods );
		},

		/*
			getSpeed()
			returns the current speed of the entity

			to calculate the speed multiplier:
			1. only the most strong buff counts, ex:
				speedBuffs= [ 1.1, 1.1, 1.2, 1.5 ] my resulting speed will be 1.5x
				speedBuffs= [ 0.2, 0.9, 0.3 ] my resulting speed will be 0.2x

			2. with Buffs with opposite sign, you subtract the resulting multipliers in both signs
				speedBuffs= [ 0.3, 1.5 ] my resulting speed will be +1.5 -( 1 -0.3 ) = 1,5 - 0.7 = 0.8x
				speedBuffs= [ 0.9, 1.2, 1.9 ] my resulting speed will be +1.9 -( 1 -0.9 ) = 1,9 - 0.1 = 1.8x
		*/

		getSpeed: function(){

			var mods = [ this.speed ];
			for ( b in this.buffs ) {
				 if ( this.buffs[b].modSpeed ) {
					 mods.push( this.buffs[b].modSpeed );
				 }
			}
			var speed_mult = _.max( mods ) - ( this.speed - _.min( mods ) );
			return speed_mult;
		},

		refreshSpeed: function() {

			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' refresh his speed' );
			this.move( this._dest.x, this._dest.y );
		},

		halt: function () {

			if( _DEBUG ) CAAT.log("[Enemy] "+this.id+" halts at "+this.x+","+this.y );
			this.moving = false;
			this.emptyBehaviorList();
			this.playAnimation( 'stand' );
		},

		move: function ( x, y ) {

			if ( this.target ) {
				this._dest.x = x || this.target.x + this.target.width/2;
				this._dest.y = y || this.target.y + this.target.height/4 + roll( 1, this.target.height/2 );
			}
			if( _DEBUG ) CAAT.log("[Enemy] "+this.id+" is moving to "+this._dest.x+","+this._dest.y );

			this.path = new CAAT.PathUtil.Path().setLinear(
				this.x, this.y, this._dest.x, this._dest.y
			);
			this._t = ( game.options.enemies.baseSpeed * this.path.getLength() / this.getSpeed() );
			var e = this;
			this.pathBehavior = new CAAT.Behavior.PathBehavior().
				setFrameTime( gameScene.time, this._t ).
				setInterpolator( new CAAT.Behavior.Interpolator().createLinearInterpolator(false) ).
				setPath( this.path );

			this.addBehavior( this.pathBehavior );
			this.moving = true;
			this.playAnimation( 'walk' );
		},

		say: function( text ) {
			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' says: "'+text+'"' );
			game.player.notifyAt( text, this );
		},

		attack: function( amount ) {

			if ( this.cooldown-- > 0 ) {
				return;
			} else {
				this.cooldown = this.attackSpeed;
			}

			if ( !amount ) {
				amount = this.getDamage();
			}
			this.target.damage( this.getDamage(), this.element );
			this.playAnimation( 'attack' );
			if ( _DEBUG ) CAAT.log( "[Enemy] "+this.id+" is attacking "+this.target+" for "+amount+" damage!" );
		},

		damage: function( amount, element ) {

			if ( this.damageFilter ) {
				amount = Math.round( this.damageFilter( amount, element ) );
			}
			this.wounds += amount;
			this.say( amount );
			if ( this.getHp() < this.wounds ) {
				this.die();
			}
			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' receives '+amount+' hp of '+element+' damage ( status: '+this.wounds+'/'+this.hp+' )' );
		},

		heal: function( amount ) {

			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' heals '+amount+' hp' );
			this.wounds -= amount;
			if ( this.wounds < 0 ){
				this.wounds = 0;
			}
		},

		die: function( opts ) {

			if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+' is now dead!' );
			// this.playAnimation( 'die' );
			for ( var i = game.enemies.length - 1; i >= 0; i-- ) {
				if ( game.enemies[i].id === this.id ) {
					if ( !this.summoned ) { //only genuine enemies do count, summoned ones don't
						game.killCount++;
					}
					game.enemies.splice( i, 1 );
					game.bg.removeChild( this );

					if ( !this.dropTable )
						return false;
					for ( i in this.dropTable ) {
						var item = this.dropTable[ i ];
						if ( roll( 1, 100 ) < item.chance ) {
							var drop, qty;
							qty = roll( 1, item.qty || 1 );
							for ( var i=0; i < qty; i++ ) {
								new CAAT.Drop().add( item.id, this.x, this.y );
							}
						}
					}
					return true;
				}
			}
		},

		getDistance: function( entity ){

			if ( !entity ) {
				entity = this.target;
			}
			return getDistance( this, entity );
		},

		ai: function() {

			if ( this.range < this.getDistance( ) || this.cooldown > 0 ) {
				if ( !this.moving ) {
					this.move( );
				}
			} else {
				this.attack( this.getDamage() );
			}

		},

		addBuff: function( buff ) {

			if( _DEBUG ) CAAT.log( "[Enemy] added a buff: ", buff );
			buff.setTarget( this );
			//TODO resistances
			// if( buff.isHarmful() && buff.allowResist() && roll( 1, 100 ) > this.resistances[ buff.element ] ) { return; }
			this.buffs.push( buff );
		},

		tick : function() {

			this.tick_done++;
			this.ai();

			if ( this.cooldown > 0 )
				this.cooldown--;

			for ( var i=0; i < this.buffs.length; i++ ) {
				if ( this.moving && this.buffs[i].modSpeed ) {
					if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+"'s buff "+i+" changes target's speed" );
					this.move( );
				}
				if ( this.buffs[i].isActive() ) {
					this.buffs[i].tick();
					if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+"'s buff "+i+" ticks..." );
				} else {
					this.buffs.splice( i, 1 );
					this.refreshSpeed();
					if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+"'s buff "+i+" ends" );
				}
			}

			if ( _DEBUG && _SHOW_PATH ) {
				game.bg.addChild( new CAAT.PathActor().
					setPath( this.path ).
					setFrameTime( gameScene.time, 400 ).
					setBounds( 0, 0, director.width, director.height ).
					setInteractive( false )
				);
			}
		}
	};
	extend( CAAT.Enemy, CAAT.Actor );

	CAAT.RangedEnemy = function( ){
		CAAT.RangedEnemy.superclass.constructor.call( this );
		return this;
	};

	CAAT.RangedEnemy.prototype = {};
	extend( CAAT.RangedEnemy, CAAT.Enemy );
})();<commit_msg>fix<commit_after>(function() {

	var _DEBUG = 		false,
 		_SHOW_PATH = 	false;

	CAAT.Enemy = function( ){
		CAAT.Enemy.superclass.constructor.call( this );
		this.target = game.player;
		return this;
	};

	CAAT.Enemy.prototype = {

		id:				0,
		index:			-1,
		level:			1,
		hitDice:		6,
		hp:				10,
		wounds: 		0,
		type:			'unknown',
		role: 			"melee",
		speed:			1,
		attackSpeed:	6,
		cooldown:		6,
		element:		"physical",
		range:			150,
		moving:			false,
		dropTable:		null,
		tick_done:		0,
		summoned:		false,
		_dest:			{ x:0, y:0 },
		_t:				0,

		setup : function( ) {

			var data = game.enemiesBook[ this.type ];
			for ( p in data ) {
				this[ p ] = data[ p ];
			}
			this.buffs = [];
			this.modifiers = { hp: 0, speed: 0 };
			this.hp = roll( this.level, this.hitDice, this.level );
			this.id = this.type+roll( 1, 999 );
		},

		add : function( type, summoned ) {

			this.type = type;
			this.summoned = summoned;
			this.setup( );

			this.x = director.width + this.width;
			this.y = (director.height/4)+Math.random()*(director.height*3/4);

			this.sprite = new CAAT.Foundation.SpriteImage().initialize(
				director.getImage( this.type ),
				this.frameH || 1,
				this.frameW || 1
			);

			if ( this.animations && this.animations !== {} ){

				var a = null;
				for ( id in this.animations ) {
					a = this.animations[ id ];
					if ( a ) {
						if ( id === 'attack' && !a.reset ) {
							a.reset = function ( s ) { s.playAnimation( 'stand' ) };
						}
						this.sprite.addAnimation( id, a.frames, a.duration, a.reset );
					}
				}
			}

			this.setBackgroundImage( this.sprite, true ).
				enableEvents( false ).
				setPositionAnchor( 0.5, 0.5 );

			game.bg.addChild( this );
			this.index = game.enemies.push( this );
			this.playAnimation( 'stand' );

			if( _DEBUG ) CAAT.log("[Enemy] "+this.id+" is added" );
		},

		getDamage: function( ) {
			return roll();
		},

		getHp: function(){

			var mods = [0];
			for ( b in this.buffs ) {
				 if ( this.buffs[b].modSpeed ) {
					 mods.push( this.buffs[b].modHp );
				 }
			}
			return this.hp - this.wounds + _.max( mods );
		},

		/*
			getSpeed()
			returns the current speed of the entity

			to calculate the speed multiplier:
			1. only the most strong buff counts, ex:
				speedBuffs= [ 1.1, 1.1, 1.2, 1.5 ] my resulting speed will be 1.5x
				speedBuffs= [ 0.2, 0.9, 0.3 ] my resulting speed will be 0.2x

			2. with Buffs with opposite sign, you subtract the resulting multipliers in both signs
				speedBuffs= [ 0.3, 1.5 ] my resulting speed will be +1.5 -( 1 -0.3 ) = 1,5 - 0.7 = 0.8x
				speedBuffs= [ 0.9, 1.2, 1.9 ] my resulting speed will be +1.9 -( 1 -0.9 ) = 1,9 - 0.1 = 1.8x
		*/

		getSpeed: function(){

			var mods = [ this.speed ];
			for ( b in this.buffs ) {
				 if ( this.buffs[b].modSpeed ) {
					 mods.push( this.buffs[b].modSpeed );
				 }
			}
			var speed_mult = _.max( mods ) - ( this.speed - _.min( mods ) );
			return speed_mult;
		},

		refreshSpeed: function() {

			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' refresh his speed' );
			this.move( this._dest.x, this._dest.y );
		},

		halt: function () {

			if( _DEBUG ) CAAT.log("[Enemy] "+this.id+" halts at "+this.x+","+this.y );
			this.moving = false;
			this.playAnimation( 'stand' );
			this.emptyBehaviorList();
		},

		move: function ( x, y ) {

			if ( this.target ) {
				this._dest.x = x || this.target.x + this.target.width/2;
				this._dest.y = y || this.target.y + this.target.height/4 + roll( 1, this.target.height/2 );
			}
			if( _DEBUG ) CAAT.log("[Enemy] "+this.id+" is moving to "+this._dest.x+","+this._dest.y );

			this.path = new CAAT.PathUtil.Path().setLinear(
				this.x, this.y, this._dest.x, this._dest.y
			);
			this._t = ( game.options.enemies.baseSpeed * this.path.getLength() / this.getSpeed() );
			var e = this;
			this.pathBehavior = new CAAT.Behavior.PathBehavior().
				setFrameTime( gameScene.time, this._t ).
				setInterpolator( new CAAT.Behavior.Interpolator().createLinearInterpolator(false) ).
				setPath( this.path ).
				addListener( {
					behaviorExpired : function( behaviour, time ) {
						e.moving = false;
						e.playAnimation( 'stand' );
					}
				} );

			this.addBehavior( this.pathBehavior );
			this.moving = true;
			this.playAnimation( 'walk' );
		},

		say: function( text ) {
			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' says: "'+text+'"' );
			game.player.notifyAt( text, this );
		},

		attack: function( amount ) {

			if ( this.cooldown-- > 0 ) {
				return;
			} else {
				this.cooldown = this.attackSpeed;
			}

			if ( !amount ) {
				amount = this.getDamage();
			}
			this.target.damage( this.getDamage(), this.element );
			this.playAnimation( 'attack' );
			if ( _DEBUG ) CAAT.log( "[Enemy] "+this.id+" is attacking "+this.target+" for "+amount+" damage!" );
		},

		damage: function( amount, element ) {

			if ( this.damageFilter ) {
				amount = Math.round( this.damageFilter( amount, element ) );
			}
			this.wounds += amount;
			this.say( amount );
			if ( this.getHp() < this.wounds ) {
				this.die();
			}
			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' receives '+amount+' hp of '+element+' damage ( status: '+this.wounds+'/'+this.hp+' )' );
		},

		heal: function( amount ) {

			if ( _DEBUG ) CAAT.log( '[Enemy] '+this.id+' heals '+amount+' hp' );
			this.wounds -= amount;
			if ( this.wounds < 0 ){
				this.wounds = 0;
			}
		},

		die: function( opts ) {

			if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+' is now dead!' );
			// this.playAnimation( 'die' );
			for ( var i = game.enemies.length - 1; i >= 0; i-- ) {
				if ( game.enemies[i].id === this.id ) {
					if ( !this.summoned ) { //only genuine enemies do count, summoned ones don't
						game.killCount++;
					}
					game.enemies.splice( i, 1 );
					game.bg.removeChild( this );

					if ( !this.dropTable )
						return false;
					for ( i in this.dropTable ) {
						var item = this.dropTable[ i ];
						if ( roll( 1, 100 ) < item.chance ) {
							var drop, qty;
							qty = roll( 1, item.qty || 1 );
							for ( var i=0; i < qty; i++ ) {
								new CAAT.Drop().add( item.id, this.x, this.y );
							}
						}
					}
					return true;
				}
			}
		},

		getDistance: function( entity ){

			if ( !entity ) {
				entity = this.target;
			}
			return getDistance( this, entity );
		},

		ai: function() {

			if ( this.range < this.getDistance( ) || this.cooldown > 0 ) {
				if ( !this.moving ) {
					this.move( );
				}
			} else {
				this.attack( this.getDamage() );
			}

		},

		addBuff: function( buff ) {

			if( _DEBUG ) CAAT.log( "[Enemy] added a buff: ", buff );
			buff.setTarget( this );
			//TODO resistances
			// if( buff.isHarmful() && buff.allowResist() && roll( 1, 100 ) > this.resistances[ buff.element ] ) { return; }
			this.buffs.push( buff );
		},

		tick : function() {

			this.tick_done++;
			this.ai();

			if ( this.cooldown > 0 )
				this.cooldown--;

			for ( var i=0; i < this.buffs.length; i++ ) {
				if ( this.moving && this.buffs[i].modSpeed ) {
					if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+"'s buff "+i+" changes target's speed" );
					this.move( );
				}
				if ( this.buffs[i].isActive() ) {
					this.buffs[i].tick();
					if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+"'s buff "+i+" ticks..." );
				} else {
					this.buffs.splice( i, 1 );
					this.refreshSpeed();
					if( _DEBUG ) CAAT.log( "[Enemy] "+this.id+"'s buff "+i+" ends" );
				}
			}

			if ( _DEBUG && _SHOW_PATH ) {
				game.bg.addChild( new CAAT.PathActor().
					setPath( this.path ).
					setFrameTime( gameScene.time, 400 ).
					setBounds( 0, 0, director.width, director.height ).
					setInteractive( false )
				);
			}
		}
	};
	extend( CAAT.Enemy, CAAT.Actor );

	CAAT.RangedEnemy = function( ){
		CAAT.RangedEnemy.superclass.constructor.call( this );
		return this;
	};

	CAAT.RangedEnemy.prototype = {};
	extend( CAAT.RangedEnemy, CAAT.Enemy );
})();<|endoftext|>


<commit_before>var resolvers = require('../resolvers');

module.exports = function(base, files, config) {
  var hash, i, l, file, resolve;

  if (files.length === 0) {
    return '[]';
  }

  // map every matched file using resolve
  hash = {};
  for (var i = 0, l = files.length, file = files[i]; i < l; file = files[++i]) {
    hash[file] = file;
  }

  for (var i = 0,
      l = config.resolve.length,
      resolve = config.resolve[i]; i < l; resolve = config.resolve[++i]) {
    if (typeof resolve !== 'function') {
      if (resolvers.hasOwnProperty(resolve)) {
        resolve = resolvers[resolve];
      } else {
        throw "Unknown key resolve: " + resolve;
      }
    }
    hash = resolve(base, hash, config);
  }

  // return object-mapped string
  return "[" + files.reduce(
    function(acc, file, idx, arr) {
      return [
        (acc ? acc + "," : ""),
        "{",
        "name: '" + hash[file].replace(/\\/g, '/') + "'",
        ",",
        "module:require('" + file + "')",
        "}"
      ].join('');
    }, false) + "]";

};
<commit_msg>Removed an aesthetic space to make the result more compact<commit_after>var resolvers = require('../resolvers');

module.exports = function(base, files, config) {
  var hash, i, l, file, resolve;

  if (files.length === 0) {
    return '[]';
  }

  // map every matched file using resolve
  hash = {};
  for (var i = 0, l = files.length, file = files[i]; i < l; file = files[++i]) {
    hash[file] = file;
  }

  for (var i = 0,
      l = config.resolve.length,
      resolve = config.resolve[i]; i < l; resolve = config.resolve[++i]) {
    if (typeof resolve !== 'function') {
      if (resolvers.hasOwnProperty(resolve)) {
        resolve = resolvers[resolve];
      } else {
        throw "Unknown key resolve: " + resolve;
      }
    }
    hash = resolve(base, hash, config);
  }

  // return object-mapped string
  return "[" + files.reduce(
    function(acc, file, idx, arr) {
      return [
        (acc ? acc + "," : ""),
        "{",
        "name:'" + hash[file].replace(/\\/g, '/') + "'",
        ",",
        "module:require('" + file + "')",
        "}"
      ].join('');
    }, false) + "]";

};
<|endoftext|>


<commit_before>module.exports = function (grunt) {

	// Project configuration.
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		concat: {
			options: {
				separator: ';'
			},
			browser: {
				src: [
						 "js/tabState.js",
						"js/util/urlParser.js",
						"js/webviews.js",
						 "js/webviewMenu.js",
						"js/bookmarksHistory/bookmarksHistory.js",
						 "js/api-wrapper.js",
						 "js/searchbar/searchbar.js",
							"js/searchbar/history.js",
							"js/searchbar/bookmarks.js",
							"js/searchbar/duckduckgo.js",
							"js/searchbar/tabsearch.js",
							"js/readerView.js",
						 "js/navbar/tabActivity.js",
							"js/navbar/tabcolor.js",
						 "js/navbar/navbarTabs.js",
							"js/navbar/expandedTabMode.js",
							"js/navbar/addTabButton.js",
						 "js/keybindings.js",
						 "js/fileDownloadManager.js",
						 "js/findinpage.js",
							"js/sessionRestore.js",
							"js/focusMode.js",

						 ],
				dest: 'dist/build.js'
			},
			webview: {
				src: [
						"js/webview/default.js",
						"js/webview/bookmarksExtractor.js",
						"js/webview/contextMenu.js",
						"js/webview/phishDetector.js",
						"js/webview/readerDetector.js",
						"js/webview/swipeEvents.js",
						"js/webview/zoom.js",
						"js/webview/keywordExtractor.js",
						"js/webview/fileViewer.js"
						 ],
				dest: 'dist/webview.js'
			}
		},
		uglify: {
			options: {
				banner: '/*! <%= grunt.template.today("mm-dd-yyyy") %> */\n'
			},
			browser: {
				src: 'dist/build.js',
				dest: 'dist/build.min.js'
			},
			webview: {
				src: 'dist/webview.js',
				dest: 'dist/webview.min.js'
			}
		},
		electron: {
			osxBuild: {
				options: {
					name: 'Min',
					dir: '',
					out: 'dist/app',
					version: '0.36.8',
					'app-version': '1.0.1',
					platform: 'darwin',
					arch: 'x64',
					icon: "icon.icns",
				}
			},
			windowsBuild: {
				options: {
					name: 'Min',
					dir: '',
					out: 'dist/app',
					version: '0.36.8',
					'app-version': '1.0.1',
					platform: 'win32',
					arch: 'all',
				}
			},
			linuxBuild: {
				options: {
					name: 'Min',
					dir: '',
					out: 'dist/app',
					version: '0.36.8',
					'app-version': '1.0.1',
					platform: 'linux',
					arch: 'all',
				}
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-electron');

	grunt.registerTask('default', ['concat:browser', 'uglify:browser', 'concat:webview', 'uglify:webview']);
	grunt.registerTask('browser', ['concat:browser', 'uglify:browser']);
	grunt.registerTask('webview', ['concat:webview', 'uglify:webview']);
	grunt.registerTask('build', ['concat:browser', 'uglify:browser', 'concat:webview', 'uglify:webview', 'electron:osxBuild', 'electron:windowsBuild', 'electron:linuxBuild'])

};
<commit_msg>bug fix<commit_after>module.exports = function (grunt) {

	// Project configuration.
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		concat: {
			options: {
				separator: ';'
			},
			browser: {
				src: [
						 "js/tabState.js",
						"js/util/urlParser.js",
						"js/webviews.js",
						 "js/webviewMenu.js",
						"js/bookmarksHistory/bookmarksHistory.js",
						 "js/api-wrapper.js",
						 "js/searchbar/searchbar.js",
							"js/searchbar/history.js",
							"js/searchbar/bookmarks.js",
							"js/searchbar/duckduckgo.js",
							"js/searchbar/tabsearch.js",
							"js/readerView.js",
						 "js/navbar/tabActivity.js",
							"js/navbar/tabcolor.js",
						 "js/navbar/navbarTabs.js",
							"js/navbar/expandedTabMode.js",
							"js/navbar/addTabButton.js",
						 "js/keybindings.js",
						 "js/fileDownloadManager.js",
						 "js/findinpage.js",
							"js/sessionRestore.js",
							"js/focusMode.js",

						 ],
				dest: 'dist/build.js'
			},
			webview: {
				src: [
						"js/webview/default.js",
						"js/webview/bookmarksExtractor.js",
						"js/webview/contextMenu.js",
						"js/webview/phishDetector.js",
						"js/webview/readerDetector.js",
						"js/webview/swipeEvents.js",
						"js/webview/zoom.js",
						"js/webview/keywordExtractor.js",
						"js/webview/fileViewer.js"
						 ],
				dest: 'dist/webview.js'
			}
		},
		uglify: {
			options: {
				banner: '/*! <%= grunt.template.today("mm-dd-yyyy") %> */\n'
			},
			browser: {
				src: 'dist/build.js',
				dest: 'dist/build.min.js'
			},
			webview: {
				src: 'dist/webview.js',
				dest: 'dist/webview.min.js'
			}
		},
		electron: {
			osxBuild: {
				options: {
					name: 'Min',
					dir: '',
					out: 'dist/app',
					version: '0.36.8',
					'app-version': '1.0.1',
					platform: 'darwin',
					arch: 'x64',
					icon: "icon.icns",
					ignore: 'dist/app',
				}
			},
			windowsBuild: {
				options: {
					name: 'Min',
					dir: '',
					out: 'dist/app',
					version: '0.36.8',
					'app-version': '1.0.1',
					platform: 'win32',
					arch: 'all',
					ignore: 'dist/app',
				}
			},
			linuxBuild: {
				options: {
					name: 'Min',
					dir: '',
					out: 'dist/app',
					version: '0.36.8',
					'app-version': '1.0.1',
					platform: 'linux',
					arch: 'all',
					ignore: 'dist/app',
				}
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-electron');

	grunt.registerTask('default', ['concat:browser', 'uglify:browser', 'concat:webview', 'uglify:webview']);
	grunt.registerTask('browser', ['concat:browser', 'uglify:browser']);
	grunt.registerTask('webview', ['concat:webview', 'uglify:webview']);
	grunt.registerTask('build', ['concat:browser', 'uglify:browser', 'concat:webview', 'uglify:webview', 'electron:osxBuild', 'electron:windowsBuild', 'electron:linuxBuild'])

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.registerTask('default', ['build']);
  grunt.registerTask('build', ['clean', 'less', 'replace', 'kss', 'copy:main', 'copy:dist', 'usebanner']);
  grunt.registerTask('serve', ['connect', 'watch']);
  grunt.registerTask('deploy', ['clean', 'build', 'gh-pages']);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['build', 'dist'],
    connect: {
      all: {
        options: {port: 8500, hostname: "0.0.0.0"}
      }
    },
    usebanner: {
      options: {
        position: 'top',
        banner: '/*\n  kungbib-styles <%= pkg.version %>\n  Stylesheet accompanying the style guide for web development at the National Library of Sweden.\n  https://kungbib.github.io/frontend-guide\n*/\n',
        linebreak: true
      },
      files: {
        src: ['dist/css/kb-style.css', 'dist/less/kb-style.less']
      }
    },
    watch: {
      files: ["custom/**/*", "template/**/*", "examples/**/*", "package.json"],
      tasks: ['default'],
      options: {
        nospawn: true,
        livereload: 35790
      }
    },
    less: {
      development: {
        options: {
          compress: true,
          yucompress: true,
          optimization: 2
        },
        files: {
          "build/css/kb-style.css": "theme/theme.less"
        }
      },
      kssdev: {
        options: {
          compress: true,
          yucompress: true,
          optimization: 2
        },
        files: {
          "template/public/kss.css": "template/public/kss.less"
        }
      }
    },
    kss: {
      options: {
        // css: './css/kb-style.css',
        template: 'template'
      },
      dist: {
          files: {
            'build': ['custom']
          }
      }
    },
    replace: {
      dist: {
        options: {
          patterns: [
            {
              match: 'timestamp',
              replacement: '<%= grunt.template.today("yyyy-mm-dd - HH:MM") %>'
            },
            {
              match: 'version',
              replacement: '<%= pkg.version %>'
            }
          ]
        },
        files: [
          {expand: true, flatten: true, src: ['template/tmphtml/index.html'], dest: 'template/'}
        ]
      }
    },
    copy: {
      main: {
        files: [
          {expand: true, src: ['examples/**'], dest: 'build/'},
          {expand: true, src: ['assets/**'], dest: 'build/'},
          {expand: true, flatten: true, src: ['node_modules/bootstrap/dist/js/bootstrap.min.js'], dest: 'build/vendor/'},
          {expand: true, flatten: true, src: ['node_modules/jquery/dist/jquery.min.js'], dest: 'build/vendor/'},
        ]
      },
      dist: {
        files: [
          {expand: true, cwd: 'assets/', src: ['*'], dest: 'dist/assets/'},
          {expand: true, cwd: 'build/css/', src: ['*'], dest: 'dist/css/'},
          {expand: true, cwd: 'custom/', src: ['**/*.less'], dest: 'dist/less/'}
        ]
      }
    },
    'gh-pages': {
      options: {
        base: 'build'
      },
      src: '**/*'
    }
  });

};
<commit_msg>Pull more banner text from package.json<commit_after>module.exports = function(grunt) {

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.registerTask('default', ['build']);
  grunt.registerTask('build', ['clean', 'less', 'replace', 'kss', 'copy:main', 'copy:dist', 'usebanner']);
  grunt.registerTask('serve', ['connect', 'watch']);
  grunt.registerTask('deploy', ['clean', 'build', 'gh-pages']);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['build', 'dist'],
    connect: {
      all: {
        options: {port: 8500, hostname: "0.0.0.0"}
      }
    },
    usebanner: {
      options: {
        position: 'top',
        banner: '/*\n  kungbib-styles <%= pkg.version %>\n  <%= pkg.description %>\n  <%= pkg.homepage %>\n*/\n',
        linebreak: true
      },
      files: {
        src: ['dist/css/kb-style.css', 'dist/less/kb-style.less']
      }
    },
    watch: {
      files: ["custom/**/*", "template/**/*", "examples/**/*", "package.json"],
      tasks: ['default'],
      options: {
        nospawn: true,
        livereload: 35790
      }
    },
    less: {
      development: {
        options: {
          compress: true,
          yucompress: true,
          optimization: 2
        },
        files: {
          "build/css/kb-style.css": "theme/theme.less"
        }
      },
      kssdev: {
        options: {
          compress: true,
          yucompress: true,
          optimization: 2
        },
        files: {
          "template/public/kss.css": "template/public/kss.less"
        }
      }
    },
    kss: {
      options: {
        // css: './css/kb-style.css',
        template: 'template'
      },
      dist: {
          files: {
            'build': ['custom']
          }
      }
    },
    replace: {
      dist: {
        options: {
          patterns: [
            {
              match: 'timestamp',
              replacement: '<%= grunt.template.today("yyyy-mm-dd - HH:MM") %>'
            },
            {
              match: 'version',
              replacement: '<%= pkg.version %>'
            }
          ]
        },
        files: [
          {expand: true, flatten: true, src: ['template/tmphtml/index.html'], dest: 'template/'}
        ]
      }
    },
    copy: {
      main: {
        files: [
          {expand: true, src: ['examples/**'], dest: 'build/'},
          {expand: true, src: ['assets/**'], dest: 'build/'},
          {expand: true, flatten: true, src: ['node_modules/bootstrap/dist/js/bootstrap.min.js'], dest: 'build/vendor/'},
          {expand: true, flatten: true, src: ['node_modules/jquery/dist/jquery.min.js'], dest: 'build/vendor/'},
        ]
      },
      dist: {
        files: [
          {expand: true, cwd: 'assets/', src: ['*'], dest: 'dist/assets/'},
          {expand: true, cwd: 'build/css/', src: ['*'], dest: 'dist/css/'},
          {expand: true, cwd: 'custom/', src: ['**/*.less'], dest: 'dist/less/'}
        ]
      }
    },
    'gh-pages': {
      options: {
        base: 'build'
      },
      src: '**/*'
    }
  });

};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { Map } from 'immutable';
import { partial } from 'lodash';
import c from 'classnames';
import { resolveWidget } from 'Lib/registry';
import { Icon } from 'UI';
import EditorControl from 'Editor/EditorControlPane/EditorControl';

const TopBar = ({ collapsed, onCollapseToggle }) => (

      <button className="nc-listControl-listCollapseToggleButton" onClick={onCollapseToggle}>
        <Icon type="chevron" direction={collapsed ? 'right' : 'down'} size="small" />
      </button>

);

export default class ObjectControl extends Component {
  static propTypes = {
    onChangeObject: PropTypes.func.isRequired,
    onOpenMediaLibrary: PropTypes.func.isRequired,
    mediaPaths: ImmutablePropTypes.map.isRequired,
    onAddAsset: PropTypes.func.isRequired,
    onRemoveInsertedMedia: PropTypes.func.isRequired,
    getAsset: PropTypes.func.isRequired,
    value: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.object,
      PropTypes.bool,
    ]),
    field: PropTypes.object,
    forID: PropTypes.string,
    classNameWrapper: PropTypes.string.isRequired,
    forList: PropTypes.bool,
  };

  static defaultProps = {
    value: Map(),
  };

  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
    };
  }

  /*
   * Always update so that each nested widget has the option to update. This is
   * required because ControlHOC provides a default `shouldComponentUpdate`
   * which only updates if the value changes, but every widget must be allowed
   * to override this.
   */
  shouldComponentUpdate() {
    return true;
  }

  controlFor(field, key) {
    const {
      onAddAsset,
      onOpenMediaLibrary,
      mediaPaths,
      onRemoveInsertedMedia,
      getAsset,
      value,
      onChangeObject,
    } = this.props;

    if (field.get('widget') === 'hidden') {
      return null;
    }
    const widgetName = field.get('widget') || 'string';
    const widget = resolveWidget(widgetName);
    const fieldName = field.get('name');
    const fieldValue = value && Map.isMap(value) ? value.get(fieldName) : value;

    return (
      <EditorControl
        key={key}
        field={field}
        value={fieldValue}
        mediaPaths={mediaPaths}
        getAsset={getAsset}
        onChange={onChangeObject}
        onOpenMediaLibrary={onOpenMediaLibrary}
        onAddAsset={onAddAsset}
        onRemoveInsertedMedia={onRemoveInsertedMedia}
      />
    );
  }

  handleCollapseToggle = () => {
    this.setState({ collapsed: !this.state.collapsed });
  }

  render() {
    const { field, forID, classNameWrapper, forList } = this.props;
    const { collapsed } = this.state;
    const multiFields = field.get('fields');
    const singleField = field.get('field');

    if (multiFields) {
      return (

          { forList ? null : <TopBar collapsed={collapsed} onCollapseToggle={this.handleCollapseToggle} /> }
          { collapsed ? null : multiFields.map((f, idx) => this.controlFor(f, idx)) }

      );
    } else if (singleField) {
      return this.controlFor(singleField);
    }

    return
No field(s) defined for this widget
;
  }
}
<commit_msg>Make object control pure (no extra imports). (#1446)<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { Map } from 'immutable';
import { partial } from 'lodash';
import c from 'classnames';
import { resolveWidget } from 'Lib/registry';
import { Icon } from 'UI';

const TopBar = ({ collapsed, onCollapseToggle }) => (

      <button className="nc-listControl-listCollapseToggleButton" onClick={onCollapseToggle}>
        <Icon type="chevron" direction={collapsed ? 'right' : 'down'} size="small" />
      </button>

);

export default class ObjectControl extends Component {
  static propTypes = {
    onChangeObject: PropTypes.func.isRequired,
    onOpenMediaLibrary: PropTypes.func.isRequired,
    mediaPaths: ImmutablePropTypes.map.isRequired,
    onAddAsset: PropTypes.func.isRequired,
    onRemoveInsertedMedia: PropTypes.func.isRequired,
    getAsset: PropTypes.func.isRequired,
    value: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.object,
      PropTypes.bool,
    ]),
    field: PropTypes.object,
    forID: PropTypes.string,
    classNameWrapper: PropTypes.string.isRequired,
    forList: PropTypes.bool,
    editorControl: PropTypes.func.isRequired,
  };

  static defaultProps = {
    value: Map(),
  };

  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
    };
  }

  /*
   * Always update so that each nested widget has the option to update. This is
   * required because ControlHOC provides a default `shouldComponentUpdate`
   * which only updates if the value changes, but every widget must be allowed
   * to override this.
   */
  shouldComponentUpdate() {
    return true;
  }

  controlFor(field, key) {
    const {
      onAddAsset,
      onOpenMediaLibrary,
      mediaPaths,
      onRemoveInsertedMedia,
      getAsset,
      value,
      onChangeObject,
      editorControl: EditorControl,
    } = this.props;

    if (field.get('widget') === 'hidden') {
      return null;
    }
    const widgetName = field.get('widget') || 'string';
    const widget = resolveWidget(widgetName);
    const fieldName = field.get('name');
    const fieldValue = value && Map.isMap(value) ? value.get(fieldName) : value;

    return (
      <EditorControl
        key={key}
        field={field}
        value={fieldValue}
        mediaPaths={mediaPaths}
        getAsset={getAsset}
        onChange={onChangeObject}
        onOpenMediaLibrary={onOpenMediaLibrary}
        onAddAsset={onAddAsset}
        onRemoveInsertedMedia={onRemoveInsertedMedia}
      />
    );
  }

  handleCollapseToggle = () => {
    this.setState({ collapsed: !this.state.collapsed });
  }

  render() {
    const { field, forID, classNameWrapper, forList } = this.props;
    const { collapsed } = this.state;
    const multiFields = field.get('fields');
    const singleField = field.get('field');

    if (multiFields) {
      return (

          { forList ? null : <TopBar collapsed={collapsed} onCollapseToggle={this.handleCollapseToggle} /> }
          { collapsed ? null : multiFields.map((f, idx) => this.controlFor(f, idx)) }

      );
    } else if (singleField) {
      return this.controlFor(singleField);
    }

    return
No field(s) defined for this widget
;
  }
}
<|endoftext|>


<commit_before>new tabris.Button({
  left: 16, right: 16, bottom: 16,
  text: 'Send message to WebView'
}).on('select', function () {
  webView.postMessage('Hello from Tabris.js', '*');
}).appendTo(tabris.ui.contentView);

var statusTextView = new tabris.TextView({
  left: 16, right: 16, bottom: 'prev()', height: 48,
  alignment: 'center',
  text: 'No message received from WebView'
}).appendTo(tabris.ui.contentView);

new tabris.Composite({
  left: 0, right: 0, bottom: 'prev()', height: 1,
  background: '#e1e1e1'
}).appendTo(tabris.ui.contentView);

var webView = new tabris.WebView({
  left: 0, top: 0, right: 0, bottom: 'prev()'
}).appendTo(tabris.ui.contentView);

fetch('./html/website.html').then(function(result) {
  return result.text();
}).then(function(text) {
  webView.set('html', text);
});

webView.on('message', function(widget, event) {
  statusTextView.set('text', 'Message received: ' + event.data);
});
<commit_msg>Modernize webview-webmessaging snippet<commit_after>new tabris.Button({
  left: 16, right: 16, bottom: 16,
  text: 'Send message to WebView'
}).on('select', function () {
  webView.postMessage('Hello from Tabris.js', '*');
}).appendTo(tabris.ui.contentView);

var statusTextView = new tabris.TextView({
  left: 16, right: 16, bottom: 'prev()', height: 48,
  alignment: 'center',
  text: 'No message received from WebView'
}).appendTo(tabris.ui.contentView);

new tabris.Composite({
  left: 0, right: 0, bottom: 'prev()', height: 1,
  background: '#e1e1e1'
}).appendTo(tabris.ui.contentView);

var webView = new tabris.WebView({
  left: 0, top: 0, right: 0, bottom: 'prev()'
}).appendTo(tabris.ui.contentView);

fetch('./html/website.html').then(function(result) {
  return result.text();
}).then(function(text) {
  webView.html = text;
});

webView.on('message', function(widget, event) {
  statusTextView.text = 'Message received: ' + event.data;
});
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    shell: {},
    env: {
      dev: {
        NODE_ENV: 'development',
      },
      build: {
        NODE_ENV: 'production'
      }
    },
    clean: {
      build: ['build'],
      sassCache: ['.sass-cache'],
      bundle: ['build/bundle.js'],
      bundleMin: ['build/bundle.min.js']
    },
    copy: {
      main: {
        files: [{
          expand: true,
          src: ['app/**/*.html', '*.md', 'humans.txt', 'robots.txt', 'sitemap.xml'],
          dest: 'build/',
          flatten: true,
          filter: 'isFile'
        }, {
          expand: true,
          cwd: 'app/',
          src: ['media/fonts/**/*'],
          dest: 'build/',
          filter: 'isFile'
        }]
      }
    },
    imagemin: {
      dynamic: {
        files: [{
          expand: true,
          cwd: 'app/',
          src: ['favicon.*', 'media/**/*.{png,jpg,svg}'],
          dest: 'build/'
        }]
      }
    },
    replace: {
      build: {
        src: ['build/index.html'],
        overwrite: true,
        replacements: [{
          from: 'main.css',
          to: 'main.min.css'
        }, {
          from: 'bundle.js',
          to: 'bundle.min.js'
        }]
      }
    },
    watch: {
      css: {
        files: [
          'app/styles/**/*.scss',
          'app/styles/**/*.sass'
        ],
        tasks: ['newer:sass']
      },
      js: {
        files: [
          'app/**/*.js',
          'Gruntfile.js'
        ],
        tasks: ['newer:eslint', 'newer:browserify']
      },
      media: {
        files: ['app/media/**/*', 'app/favicon.*'],
        tasks: ['newer:imagemin']
      },
      other: {
        files: [
          'app/**/*.html',
          './**/*.md',
          'humans.txt',
          'robots.txt',
          'sitemap.xml'
        ],
        tasks: ['newer:copy']
      },
      livereload: {
        files: ['build/**/*'],
        options: {
          livereload: true
        }
      }
    },
    sass: {
      dev: {
        options: {
          style: 'expanded'
        },
        files: {
          'build/main.css': 'app/styles/main.scss'
        }
      },
      build: {
        options: {
          sourcemap: 'none',
          style: 'compressed'
        },
        files: {
          'build/main.min.css': 'app/styles/main.scss'
        }
      }
    },
    eslint: {
      options: {
        silent: true,
        configFile: 'config/eslintConfig.json'
      },
      src: ['Gruntfile.js', 'app/**/*.js']
    },
    browserify: {
      dist: {
        src: ['app/**/*.js'],
        dest: 'build/bundle.js',
        options: {
          transform: ['reactify'],
          debug: true
        }
      },
    },
    connect: {
      livereload: {
        options: {
          open: true,
          base: 'build'
        }
      }
    },
    uglify: {
      build: {
        files: {
          'build/bundle.min.js': ['build/bundle.js']
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-newer');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-env');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-text-replace');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('gruntify-eslint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  var devTaskList = ['env:dev', 'clean', 'imagemin', 'copy', 'sass:dev', 'eslint', 'browserify', 'connect', 'watch'];
  var prodTaskList = ['env:build', 'clean', 'imagemin', 'copy', 'sass:build', 'eslint', 'browserify', 'uglify', 'clean:bundle', 'replace'];

  grunt.registerTask('default', devTaskList);
  grunt.registerTask('ci', prodTaskList);
  grunt.registerTask('build', prodTaskList);
};
<commit_msg>Added additional optimization options for imagemin<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    shell: {},
    env: {
      dev: {
        NODE_ENV: 'development',
      },
      build: {
        NODE_ENV: 'production'
      }
    },
    clean: {
      build: ['build'],
      sassCache: ['.sass-cache'],
      bundle: ['build/bundle.js'],
      bundleMin: ['build/bundle.min.js']
    },
    copy: {
      main: {
        files: [{
          expand: true,
          src: ['app/**/*.html', '*.md', 'humans.txt', 'robots.txt', 'sitemap.xml'],
          dest: 'build/',
          flatten: true,
          filter: 'isFile'
        }, {
          expand: true,
          cwd: 'app/',
          src: ['media/fonts/**/*'],
          dest: 'build/',
          filter: 'isFile'
        }]
      }
    },
    imagemin: {
      dynamic: {
        files: [{
          expand: true,
          options: {
            optimizationLevel: 7,
            progressive: true
          },
          cwd: 'app/',
          src: ['favicon.*', 'media/**/*.{png,jpg,svg}'],
          dest: 'build/'
        }]
      }
    },
    replace: {
      build: {
        src: ['build/index.html'],
        overwrite: true,
        replacements: [{
          from: 'main.css',
          to: 'main.min.css'
        }, {
          from: 'bundle.js',
          to: 'bundle.min.js'
        }]
      }
    },
    watch: {
      css: {
        files: [
          'app/styles/**/*.scss',
          'app/styles/**/*.sass'
        ],
        tasks: ['newer:sass']
      },
      js: {
        files: [
          'app/**/*.js',
          'Gruntfile.js'
        ],
        tasks: ['newer:eslint', 'newer:browserify']
      },
      media: {
        files: ['app/media/**/*', 'app/favicon.*'],
        tasks: ['newer:imagemin']
      },
      other: {
        files: [
          'app/**/*.html',
          './**/*.md',
          'humans.txt',
          'robots.txt',
          'sitemap.xml'
        ],
        tasks: ['newer:copy']
      },
      livereload: {
        files: ['build/**/*'],
        options: {
          livereload: true
        }
      }
    },
    sass: {
      dev: {
        options: {
          style: 'expanded'
        },
        files: {
          'build/main.css': 'app/styles/main.scss'
        }
      },
      build: {
        options: {
          sourcemap: 'none',
          style: 'compressed'
        },
        files: {
          'build/main.min.css': 'app/styles/main.scss'
        }
      }
    },
    eslint: {
      options: {
        silent: true,
        configFile: 'config/eslintConfig.json'
      },
      src: ['Gruntfile.js', 'app/**/*.js']
    },
    browserify: {
      dist: {
        src: ['app/**/*.js'],
        dest: 'build/bundle.js',
        options: {
          transform: ['reactify'],
          debug: true
        }
      },
    },
    connect: {
      livereload: {
        options: {
          open: true,
          base: 'build'
        }
      }
    },
    uglify: {
      build: {
        files: {
          'build/bundle.min.js': ['build/bundle.js']
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-newer');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-env');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-text-replace');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('gruntify-eslint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  var devTaskList = ['env:dev', 'clean', 'imagemin', 'copy', 'sass:dev', 'eslint', 'browserify', 'connect', 'watch'];
  var prodTaskList = ['env:build', 'clean', 'imagemin', 'copy', 'sass:build', 'eslint', 'browserify', 'uglify', 'clean:bundle', 'replace'];

  grunt.registerTask('default', devTaskList);
  grunt.registerTask('ci', prodTaskList);
  grunt.registerTask('build', prodTaskList);
};
<|endoftext|>


<commit_before>/* Copyright 2015 Dietrich Epp.

   This file is part of Dash and the Jetpack Space Pirates.  The Dash
   and the Jetpack Space Pirates source code is distributed under the
   terms of the MIT license.  See LICENSE.txt for details. */
'use strict';

var glm = require('gl-matrix');
var vec2 = glm.vec2;
var vec4 = glm.vec4;

var color = require('./color');
var entity = require('./entity');
var param = require('./param');
var physics = require('./physics');
var util = require('./physics');

var StunTime = 0.3;

var shotDir = vec2.create();

function towardsPlayer(game, body, leading) {
	if (isNaN(leading)) {
		leading = 0.5;
	}
	var v = shotDir;
	var player = game.scan({
		team: 'player',
		position: body.position,
		angle: Math.PI,
	});
	if (!player || !player.body) {
		return null;
	}
	var pb = player.body;
	vec2.scale(v, pb.velocity, leading);
	vec2.add(v, v, pb.position);
	vec2.subtract(v, v, body.position);
	var len2 = vec2.squaredLength(v);
	if (len2 < 0.01) {
		return null;
	}
	return v;
}

function randomDirection() {
	var a = Math.random() * 2 * Math.PI;
	vec2.set(shotDir, Math.cos(a), Math.sin(a));
	return shotDir;
}

function emitEnemy(obj, game) {
	var type = obj.type;
	game.sprites.add({
		position: obj.body.interpolatedPosition,
		radius: 1.5,
		color: obj.color,
		sprite: type.sprite,
		angle: obj.body.interpolatedAngle - Math.PI * 0.5,
	});
}

/*
 * Class for enemy corpses.
 */
function Corpse(game, body, type) {
	body.gravityScale = 1;
	body.mass *= 0.5;
	body.updateMassProperties();
	_.forEach(body.shapes, function(s) {
		s.material = physics.Material.Bouncy;
	});
	this.body = body;
	this.type = type;
	this.color = vec4.clone(color.White);
}
Corpse.prototype = {
	emit: function(game) {
		emitEnemy(this, game);
	},
	lifespan: 3,
};

/*
 * Base mixin for enemies.
 *
 * Spawn properties:
 * position: Enemy position
 */
function Enemy(game, args, type) {
	var position = args.position;
	var body = new p2.Body({
		position: args.position,
		angle: Math.PI * 0.5,
		mass: type.mass,
		gravityScale: 0,
	});
	var shape = new p2.Circle({ radius: 1 });
	shape.collisionGroup = physics.Mask.Enemy;
	shape.collisionMask = physics.Mask.World | physics.Mask.Player;
	body.addShape(shape);
	this.body = body;
	this.hurtTween = null;
	this.color = vec4.clone(type.color);
	this.type = type;
	this.health = type.health;
	this.lockCount = 0;
}
Enemy.prototype = {
	step: function(game) {
		this.type.step(game, this);
	},
	emit: function(game) {
		emitEnemy(this, game);
	},
	onDamage: function(game, amt) {
		if (this.health <= 0) {
			return;
		}
		this.health -= amt;
		if (this.health > 0) {
			this.hurtTween =
				(this.hurtTween ? this.hurtTween.reset() : game.tween(this))
				.to({ color: color.White }, 0.1)
				.to({ color: this.type.color, hurtTween: null }, StunTime)
				.start();
		} else {
			this.die(game);
		}
	},
	die: function(game) {
		game.spawnObj(new Corpse(game, this.body, this.type));
	},
	team: 'enemy',
};

/**********************************************************************/

var tempv0 = vec2.create();

function drive(amt) {
	return 1 - Math.pow(1 - amt, 1 / param.Rate);
}

function Glider() {
	// up, left, down, left
	this.state = 0;
	this.period = Math.round(0.75 * param.Rate);
	this.rem = 0;
	var a = Math.atan(this.slope), h = Math.PI;
	this.angles = [h - a, h, h + a, h];
}
Glider.prototype = {
	color: color.hex(0xDCE800),
	sprite: 'EGlider',
	mass: 2,
	health: 2,
	drive: drive(0.7),

	slope: 3,
	speed: 15,
	turnRate: 4,
	accel: 10,
	step: function(game, ent) {
		var y = ent.body.position[1] / param.Level.MaxGap;
		// console.log(y);
		switch (this.state) {
		default:
		case 0:
			if (y >= 0.1) {
				this.state++;
				this.rem = this.period;
			}
			break;
		case 3:
		case 1:
			if (--this.rem < 0) {
				this.state++;
			}
			break;
		case 2:
			if (y <= -0.1) {
				this.state++;
				this.rem = this.period;
			}
			break;
		}
		this.state = this.state & 3;
		var a = this.angles[this.state];
		physics.adjustAngle(ent.body, a, this.turnRate);
		a = ent.body.angle;
		var v = tempv0;
		v[0] = Math.cos(a) * this.speed;
		v[1] = Math.sin(a) * this.speed;
		physics.adjustVelocity(ent.body, v, this.accel);
	},
};

function Horiz() {}
Horiz.prototype = {
	color: color.hex(0x1C72FC),
	sprite: 'EHoriz',
	mass: 5,
	health: 2,
};

function Diamond() {}
Diamond.prototype = {
	color: color.hex(0x54EBB9),
	sprite: 'EDiamond',
	mass: 5,
	health: 2,
};

function Star() {}
Star.prototype = {
	color: color.hex(0xFFF8C4),
	sprite: 'EStar',
	mass: 5,
	health: 2,
};

function Ace() {}
Ace.prototype = {
	color: color.hex(0xCB30FF),
	sprite: 'EAce',
	mass: 5,
	health: 2,
};

function Silo() {}
Silo.prototype = {
	color: color.hex(0xA7A4B3),
	sprite: 'ESilo',
	mass: 0,
	health: 5,
};

function Turret() {
	this.reset();
}
Turret.prototype = {
	color: color.hex(0xAB8249),
	sprite: 'ETurret',
	mass: 100,
	health: 5,

	period1: 1.5 * param.Rate,
	period2: 0.5 * param.Rate,
	count: 2,
	reset: function() {
		this.state = 0;
		this.rem = Math.ceil((0.8 + 0.4 * Math.random()) * this.period1);
	},
	step: function(game, ent) {
		this.rem--;
		if (this.rem <= 0) {
			this.state++;
			if (this.state >= this.count) {
				this.reset();
			} else {
				this.rem = Math.ceil(this.period2);
			}
			game.spawn('Shot.SlowBullet', {
				source: ent.body,
				direction: towardsPlayer(game, ent.body, 0.5) || randomDirection(),
				isEnemy: true,
			});
		}
	},
};

var Enemies = {
	Glider: Glider,
	Horiz: Horiz,
	Diamond: Diamond,
	Star: Star,
	Ace: Ace,
	Silo: Silo,
	Turret: Turret,
};

entity.registerTypes(
	_.mapValues(Enemies, function(value) {
		return function(game, args) {
			/*jshint newcap:false*/
			return new Enemy(game, args, new value());
		};
	}), 'Enemy');
<commit_msg>refactor out periodic firing<commit_after>/* Copyright 2015 Dietrich Epp.

   This file is part of Dash and the Jetpack Space Pirates.  The Dash
   and the Jetpack Space Pirates source code is distributed under the
   terms of the MIT license.  See LICENSE.txt for details. */
'use strict';

var glm = require('gl-matrix');
var vec2 = glm.vec2;
var vec4 = glm.vec4;

var color = require('./color');
var entity = require('./entity');
var param = require('./param');
var physics = require('./physics');
var util = require('./physics');

var StunTime = 0.3;

var shotDir = vec2.create();

function towardsPlayer(game, body, leading) {
	if (isNaN(leading)) {
		leading = 0.5;
	}
	var v = shotDir;
	var player = game.scan({
		team: 'player',
		position: body.position,
		angle: Math.PI,
	});
	if (!player || !player.body) {
		return null;
	}
	var pb = player.body;
	vec2.scale(v, pb.velocity, leading);
	vec2.add(v, v, pb.position);
	vec2.subtract(v, v, body.position);
	var len2 = vec2.squaredLength(v);
	if (len2 < 0.01) {
		return null;
	}
	return v;
}

function randomDirection() {
	var a = Math.random() * 2 * Math.PI;
	vec2.set(shotDir, Math.cos(a), Math.sin(a));
	return shotDir;
}

function emitEnemy(obj, game) {
	var type = obj.type;
	game.sprites.add({
		position: obj.body.interpolatedPosition,
		radius: 1.5,
		color: obj.color,
		sprite: type.sprite,
		angle: obj.body.interpolatedAngle - Math.PI * 0.5,
	});
}

/*
 * Class for enemy corpses.
 */
function Corpse(game, body, type) {
	body.gravityScale = 1;
	body.mass *= 0.5;
	body.updateMassProperties();
	_.forEach(body.shapes, function(s) {
		s.material = physics.Material.Bouncy;
	});
	this.body = body;
	this.type = type;
	this.color = vec4.clone(color.White);
}
Corpse.prototype = {
	emit: function(game) {
		emitEnemy(this, game);
	},
	lifespan: 3,
};

/*
 * Base mixin for enemies.
 *
 * Spawn properties:
 * position: Enemy position
 */
function Enemy(game, args, type) {
	var position = args.position;
	var body = new p2.Body({
		position: args.position,
		angle: Math.PI * 0.5,
		mass: type.mass,
		gravityScale: 0,
	});
	var shape = new p2.Circle({ radius: 1 });
	shape.collisionGroup = physics.Mask.Enemy;
	shape.collisionMask = physics.Mask.World | physics.Mask.Player;
	body.addShape(shape);
	this.body = body;
	this.hurtTween = null;
	this.color = vec4.clone(type.color);
	this.type = type;
	this.health = type.health;
	this.lockCount = 0;
}
Enemy.prototype = {
	step: function(game) {
		this.type.step(game, this);
	},
	emit: function(game) {
		emitEnemy(this, game);
	},
	onDamage: function(game, amt) {
		if (this.health <= 0) {
			return;
		}
		this.health -= amt;
		if (this.health > 0) {
			this.hurtTween =
				(this.hurtTween ? this.hurtTween.reset() : game.tween(this))
				.to({ color: color.White }, 0.1)
				.to({ color: this.type.color, hurtTween: null }, StunTime)
				.start();
		} else {
			this.die(game);
		}
	},
	die: function(game) {
		game.spawnObj(new Corpse(game, this.body, this.type));
	},
	team: 'enemy',
};

/**********************************************************************/

function PeriodicFire(delay, rate, count) {
	this.delay = delay * param.Rate;
	this.rate = rate * param.Rate;
	this.count = count;
	this.reset();
}
PeriodicFire.prototype.reset = function() {
	this.state = 0;
	this.rem = Math.ceil((0.8 + 0.4 * Math.random()) * this.delay);
};
PeriodicFire.prototype.step = function() {
	this.rem--;
	if (this.rem > 0) {
		return false;
	}
	this.state++;
	if (this.state >= this.count) {
		this.reset();
	} else {
		this.rem = Math.ceil(this.rate);
	}
	return true;
};

var tempv0 = vec2.create();

function drive(amt) {
	return 1 - Math.pow(1 - amt, 1 / param.Rate);
}

function Glider() {
	// up, left, down, left
	this.state = 0;
	this.period = Math.round(0.75 * param.Rate);
	this.rem = 0;
	var a = Math.atan(this.slope), h = Math.PI;
	this.angles = [h - a, h, h + a, h];
}
Glider.prototype = {
	color: color.hex(0xDCE800),
	sprite: 'EGlider',
	mass: 2,
	health: 2,
	drive: drive(0.7),

	slope: 3,
	speed: 15,
	turnRate: 4,
	accel: 10,
	step: function(game, ent) {
		var y = ent.body.position[1] / param.Level.MaxGap;
		// console.log(y);
		switch (this.state) {
		default:
		case 0:
			if (y >= 0.1) {
				this.state++;
				this.rem = this.period;
			}
			break;
		case 3:
		case 1:
			if (--this.rem < 0) {
				this.state++;
			}
			break;
		case 2:
			if (y <= -0.1) {
				this.state++;
				this.rem = this.period;
			}
			break;
		}
		this.state = this.state & 3;
		var a = this.angles[this.state];
		physics.adjustAngle(ent.body, a, this.turnRate);
		a = ent.body.angle;
		var v = tempv0;
		v[0] = Math.cos(a) * this.speed;
		v[1] = Math.sin(a) * this.speed;
		physics.adjustVelocity(ent.body, v, this.accel);
	},
};

function Horiz() {}
Horiz.prototype = {
	color: color.hex(0x1C72FC),
	sprite: 'EHoriz',
	mass: 5,
	health: 2,
};

function Diamond() {}
Diamond.prototype = {
	color: color.hex(0x54EBB9),
	sprite: 'EDiamond',
	mass: 5,
	health: 2,
};

function Star() {}
Star.prototype = {
	color: color.hex(0xFFF8C4),
	sprite: 'EStar',
	mass: 5,
	health: 2,
};

function Ace() {}
Ace.prototype = {
	color: color.hex(0xCB30FF),
	sprite: 'EAce',
	mass: 5,
	health: 2,
};

function Silo() {}
Silo.prototype = {
	color: color.hex(0xA7A4B3),
	sprite: 'ESilo',
	mass: 0,
	health: 5,
};

function Turret() {
	this.pfire = new PeriodicFire(1.5, 0.5, 2);
}
Turret.prototype = {
	color: color.hex(0xAB8249),
	sprite: 'ETurret',
	mass: 100,
	health: 5,

	step: function(game, ent) {
		if (this.pfire.step()) {
			game.spawn('Shot.SlowBullet', {
				source: ent.body,
				direction: towardsPlayer(game, ent.body, 0.5) || randomDirection(),
				isEnemy: true,
			});
		}
	},
};

var Enemies = {
	Glider: Glider,
	Horiz: Horiz,
	Diamond: Diamond,
	Star: Star,
	Ace: Ace,
	Silo: Silo,
	Turret: Turret,
};

entity.registerTypes(
	_.mapValues(Enemies, function(value) {
		return function(game, args) {
			/*jshint newcap:false*/
			return new Enemy(game, args, new value());
		};
	}), 'Enemy');
<|endoftext|>