<commit_before>/* jshint eqnull:true, noarg:true, noempty:true, eqeqeq:true, bitwise:false, strict:true, undef:true, curly:false, node:true, browser:true, devel:true, newcap:false, maxerr:50 */
(function (module) {
	"use strict";

	var Complexion = require("complexion"),
		ComplexionJS = require("complexion-js");

	// begin_debug

	var wrap_setup_simple = function () {
		var error_node = null;
		var format_stack = function (stack) {
			var output = "",
				line, i, ii;
			stack = stack.trim().replace(/\r\n/g, "\n").split("\n");
			for (i = 0, ii = stack.length; i < ii; ++i) {
				line = stack[i];
				line = line.replace(/(@file:)(?:.*?)([^\/\\\\]+)$/, "$1$2");
				if (i > 0) output += "\n";
				output += line;
			}
			return output;
		};
		var log = function (exception) {
			if (error_node === null) {
				var n0 = document.body || document.documentElement,
					n1 = document.createElement("div"),
					n2 = document.createElement("textarea");

				n1.setAttribute("style", "position:fixed!important;right:0!important;top:0!important;bottom:0!important;width:20em!important;opacity:0.8!important;background:#fff!important;color:#000!important;z-index:999999999!important;");
				n2.setAttribute("style", "position:absolute!important;left:0!important;top:0!important;width:100%!important;height:100%!important;padding:0.5em!important;margin:0!important;color:inherit!important;background:transparent!important;font-family:inherit!important;font-size:8px!important;line-height:1.1em!important;border:none!important;resize:none!important;font-family:Courier,monospace!important;box-sizing:border-box!important;");
				n2.spellcheck = false;
				n2.readOnly = true;
				n2.wrap = "off";
				n1.appendChild(n2);
				if (n0) n0.appendChild(n1);

				error_node = n2;
			}

			var s = "";
			if (error_node.value.length > 0) s += "\n====================\n";
			s += "" + exception + "\n" + (format_stack("" + exception.stack));
			error_node.value += s;

			console.log("Exception:", exception);
		};

		Function.prototype._w = function () {
			var fn = this;
			return function () {
				try {
					return fn.apply(this, arguments);
				}
				catch (e) {
					log(e);
					throw e;
				}
			};
		};
	};

	var wrap_setup = function () {
		var error_node = null;
		var function_names = [];
		var total_counter = 0;
		var function_counters = {};
		var format_stack = function (stack) {
			var output = "",
				line, i, ii;
			stack = stack.trim().replace(/\r\n/g, "\n").split("\n");
			for (i = 0, ii = stack.length; i < ii; ++i) {
				line = stack[i];
				line = line.replace(/(@file:)(?:.*?)([^\/\\\\]+)$/, "$1$2");
				if (i > 0) output += "\n";
				output += line;
			}
			return output;
		};
		var log = function (exception) {
			if (error_node === null) {
				var n0 = document.body || document.documentElement,
					n1 = document.createElement("div"),
					n2 = document.createElement("textarea");

				n1.setAttribute("style", "position:fixed!important;right:0!important;top:0!important;bottom:0!important;width:20em!important;opacity:0.8!important;background:#fff!important;color:#000!important;z-index:999999999!important;");
				n2.setAttribute("style", "position:absolute!important;left:0!important;top:0!important;width:100%!important;height:100%!important;padding:0.5em!important;margin:0!important;color:inherit!important;background:transparent!important;font-family:inherit!important;font-size:8px!important;line-height:1.1em!important;border:none!important;resize:none!important;font-family:Courier,monospace!important;box-sizing:border-box!important;");
				n2.spellcheck = false;
				n2.readOnly = true;
				n2.wrap = "off";
				n1.appendChild(n2);
				if (n0) n0.appendChild(n1);

				error_node = n2;
			}

			var s = "";
			if (error_node.value.length > 0) s += "\n====================\n";
			s += "" + exception + "\n" + (format_stack("" + exception.stack));
			error_node.value += s;

			console.log("Exception:", exception);
		};

		Function.prototype._w = function (fn_index) {
			var fn = this;
			return function () {
				++total_counter;
				if (fn_index in function_counters) {
					++function_counters[fn_index];
				}
				else {
					function_counters[fn_index] = 1;
				}

				try {
					return fn.apply(this, arguments);
				}
				catch (e) {
					log(e);
					throw e;
				}
			};
		};

		// Performance checking loop
		var check_interval_index = 0;
		setInterval(function () {
			++check_interval_index;
			if (total_counter === 0) return;

			var keys = Object.keys(function_counters),
				sortable = [],
				i;

			for (i = 0; i < keys.length; ++i) {
				sortable.push([ function_counters[keys[i]], parseInt(keys[i], 10) ]);
			}

			sortable.sort(function (a, b) {
				if (a[0] > b[0]) return -1;
				if (a[0] < b[0]) return 1;
				if (a[1] > b[1]) return -1;
				if (a[1] < b[1]) return 1;
				return 0;
			});

			for (i = 0; i < sortable.length; ++i) {
				sortable[i] = function_names[sortable[i][1]] + ": " + sortable[i][0];
			}

			console.log("========================================");
			console.log("Debug Function Call Counter:", "Init + " + check_interval_index + "s: " + total_counter + " calls");
			console.log("Debug Function Call Counter:", sortable);
			console.log("========================================");
			total_counter = 0;
			function_counters = {};
		}, 1000);
	};

	var stringify_function = function (fn, indent) {
		return fn.toString().replace(/\n\t/g, "\n" + indent);
	};

	var debug_wrap_code = function (source, simple) {
		var instance = new Complexion(),
			parens = 0,
			start_parens = -1,
			token_pre = null,
			token_pre_name = null,
			function_starts = [],
			output = "",
			function_names = [],
			function_name_pos = -1,
			tokens, token, before, after, indent, name, fs, t, c, i;

		ComplexionJS(instance);
		tokens = instance.tokenize(source);

		for (i = 0; i < tokens.length; ++i) {
			token = tokens[i];
			before = "";
			after = "";
			c = token.content;

			if (!token.isAnyType([ "WHITESPACE", "LINE_TERMINATOR", "SINGLE_LINE_COMMENT", "MULTI_LINE_COMMENT", "BOM", "SHEBANG", "UNKNOWN" ])) {
				if (token.isType("KEYWORD")) {
					if (c === "function") {
						name = (token_pre_name === null ? "?" : token_pre_name.content);
						t = (function_starts.length > 0 ? function_names[function_starts[function_starts.length - 1][1]] : "?");
						if (t !== "?") name = t + "." + name;
						function_starts.push([ parens, function_names.length ]);
						function_names.push(name);
					}
				}
				else if (token.isType("PUNCTUATOR")) {
					if (c === "[" || c === "(" || c === "{") {
						++parens;
					}
					else if (c === "]" || c === ")" || c === "}") {
						--parens;
						if (
							c === "}" &&
							function_starts.length > 0 &&
							(fs = function_starts[function_starts.length - 1])[0] === parens
						) {
							function_starts.pop();
							if (start_parens >= 0 && parens >= start_parens) {
								after = "._w(" + fs[1] + ")";
							}
						}
					}
				}

				if (token.isAnyType([ "KEYWORD", "NULL_LITERAL", "NUMERIC_LITERAL", "IDENTIFIER_NAME" ])) {
					token_pre_name = token;
				}
				else if (token.isAnyType([ "PUNCTUATOR" ])) {
					if (c !== "[" && c !== "(" && c !== "{" && c !== ":" && c !== "=") {
						token_pre_name = null;
					}
				}
				else {
					token_pre_name = null;
				}

				token_pre = token;
			}
			else if (start_parens < 0 && token.isType("SINGLE_LINE_COMMENT")) {
				if (/\/\/\s*begin_debug\s*/.test(c)) {
					start_parens = parens;
					indent = /(?:^|\n)([\t ]*)$/.exec(output);
					indent = (indent === null) ? "" : indent[1];
					c = "(" + stringify_function(simple ? wrap_setup_simple : wrap_setup, indent) + ")();";

					// Position
					if (!simple) {
						function_name_pos = c.indexOf("var function_names = [];");
						if (function_name_pos >= 0) {
							function_name_pos += output.length + before.length + ("var function_names = ").length;
						}
					}
				}
			}

			// Output
			output += before;
			output += c;
			output += after;
		}

		if (function_name_pos >= 0) {
			output = output.substr(0, function_name_pos) + JSON.stringify(function_names) + output.substr(function_name_pos + 2);
		}

		return output;
	};

	module.exports = {
		debug_wrap_code: debug_wrap_code
	};

})(module);

<commit_msg>Function call debugging changes<commit_after>/* jshint eqnull:true, noarg:true, noempty:true, eqeqeq:true, bitwise:false, strict:true, undef:true, curly:false, node:true, browser:true, devel:true, newcap:false, maxerr:50 */
(function (module) {
	"use strict";

	var Complexion = require("complexion"),
		ComplexionJS = require("complexion-js");

	// begin_debug

	var timing = function () { return 0; };

	var wrap_setup_simple = function () {
		var error_node = null;

		var format_stack = function (stack) {
			var output = "",
				line, i, ii;
			stack = stack.trim().replace(/\r\n/g, "\n").split("\n");
			for (i = 0, ii = stack.length; i < ii; ++i) {
				line = stack[i];
				line = line.replace(/(@file:)(?:.*?)([^\/\\\\]+)$/, "$1$2");
				if (i > 0) output += "\n";
				output += line;
			}
			return output;
		};
		var log = function (exception) {
			if (error_node === null) {
				var n0 = document.body || document.documentElement,
					n1 = document.createElement("div"),
					n2 = document.createElement("textarea");

				n1.setAttribute("style", "position:fixed!important;right:0!important;top:0!important;bottom:0!important;width:20em!important;opacity:0.8!important;background:#fff!important;color:#000!important;z-index:999999999!important;");
				n2.setAttribute("style", "position:absolute!important;left:0!important;top:0!important;width:100%!important;height:100%!important;padding:0.5em!important;margin:0!important;color:inherit!important;background:transparent!important;font-family:inherit!important;font-size:8px!important;line-height:1.1em!important;border:none!important;resize:none!important;font-family:Courier,monospace!important;box-sizing:border-box!important;");
				n2.spellcheck = false;
				n2.readOnly = true;
				n2.wrap = "off";
				n1.appendChild(n2);
				if (n0) n0.appendChild(n1);

				error_node = n2;
			}

			var s = "";
			if (error_node.value.length > 0) s += "\n====================\n";
			s += "" + exception + "\n" + (format_stack("" + exception.stack));
			error_node.value += s;

			console.log("Exception:", exception);
		};

		Function.prototype._w = function () {
			var fn = this;
			return function () {
				try {
					return fn.apply(this, arguments);
				}
				catch (e) {
					log(e);
					throw e;
				}
			};
		};
	};

	var wrap_setup = function () {
		var error_node = null,
			function_names = [],
			total_counter = 0,
			function_counters = {},
			timing_init = timing();

		var set_timeout_0ms = (function () {
			var callbacks = {},
				origin = window.location.protocol + "//" + window.location.host;

			var random_gen = function (count) {
				var s = "",
					i;

				for (i = 0; i < count; ++i) s += ("" + Math.random()).replace(/\./, "");

				return s;
			};

			window.addEventListener("message", function (event) {
				if (event.origin === origin && event.data !== null && typeof(event.data) === "object") {
					var key = event.data.set_timeout_0ms;
					if (key in callbacks) {
						callbacks[key].call(null);
						delete callbacks[key];
					}
				}
			}, false);

			var fn = function (callback) {
				var key = random_gen(4);
				callbacks[key] = callback;
				window.postMessage({ set_timeout_0ms: key }, origin);
				return key;
			};
			fn.clear = function (key) {
				delete callbacks[key];
			};
			return fn;
		})();

		var format_stack = function (stack) {
			var output = "",
				line, i, ii;
			stack = stack.trim().replace(/\r\n/g, "\n").split("\n");
			for (i = 0, ii = stack.length; i < ii; ++i) {
				line = stack[i];
				line = line.replace(/(@file:)(?:.*?)([^\/\\\\]+)$/, "$1$2");
				if (i > 0) output += "\n";
				output += line;
			}
			return output;
		};
		var log = function (exception) {
			if (error_node === null) {
				var n0 = document.body || document.documentElement,
					n1 = document.createElement("div"),
					n2 = document.createElement("textarea");

				n1.setAttribute("style", "position:fixed!important;right:0!important;top:0!important;bottom:0!important;width:20em!important;opacity:0.8!important;background:#fff!important;color:#000!important;z-index:999999999!important;");
				n2.setAttribute("style", "position:absolute!important;left:0!important;top:0!important;width:100%!important;height:100%!important;padding:0.5em!important;margin:0!important;color:inherit!important;background:transparent!important;font-family:inherit!important;font-size:8px!important;line-height:1.1em!important;border:none!important;resize:none!important;font-family:Courier,monospace!important;box-sizing:border-box!important;");
				n2.spellcheck = false;
				n2.readOnly = true;
				n2.wrap = "off";
				n1.appendChild(n2);
				if (n0) n0.appendChild(n1);

				error_node = n2;
			}

			var s = "";
			if (error_node.value.length > 0) s += "\n====================\n";
			s += "" + exception + "\n" + (format_stack("" + exception.stack));
			error_node.value += s;

			console.log("Exception:", exception);
		};

		var increase_counter = function (fn_index) {
			++total_counter;
			if (fn_index in function_counters) {
				++function_counters[fn_index];
			}
			else {
				function_counters[fn_index] = 1;

				if (log_calls_timer === null) {
					log_calls_timer = set_timeout_0ms(log_calls);
				}
			}
		};

		var log_calls_timer = null;
		var log_calls = function () {
			log_calls_timer = null;

			// Sort keys by name
			var time_diff = timing() - timing_init,
				keys = Object.keys(function_counters),
				sortable = [],
				count, i;

			for (i = 0; i < keys.length; ++i) {
				sortable.push([ function_counters[keys[i]], parseInt(keys[i], 10) ]);
			}

			sortable.sort(function (a, b) {
				if (a[0] > b[0]) return -1;
				if (a[0] < b[0]) return 1;
				if (a[1] > b[1]) return -1;
				if (a[1] < b[1]) return 1;
				return 0;
			});

			for (i = 0; i < sortable.length; ++i) {
				sortable[i] = function_names[sortable[i][1]] + ": " + sortable[i][0];
			}

			count = total_counter;
			total_counter = 0;
			function_counters = {};

			if (time_diff >= 10000) {
				time_diff = (time_diff / 1000).toFixed(1) + "s";
			}
			else {
				time_diff = time_diff.toFixed(0) + "ms";
			}

			// Log
			console.log("[Debug Function Call Counter] Init+" + time_diff + ": call_count=" + count + ";", sortable);
		};

		Function.prototype._w = function (fn_index) {
			var fn = this;
			return function () {
				increase_counter(fn_index);

				try {
					return fn.apply(this, arguments);
				}
				catch (e) {
					log(e);
					throw e;
				}
			};
		};
	};

	var stringify_function = function (fn, indent) {
		return fn.toString().replace(/\n\t/g, "\n" + indent);
	};

	var debug_wrap_code = function (source, simple) {
		var instance = new Complexion(),
			parens = 0,
			start_parens = -1,
			token_pre = null,
			token_pre_name = null,
			function_starts = [],
			output = "",
			function_names = [],
			function_name_pos = -1,
			tokens, token, before, after, indent, name, fs, t, c, i;

		ComplexionJS(instance);
		tokens = instance.tokenize(source);

		for (i = 0; i < tokens.length; ++i) {
			token = tokens[i];
			before = "";
			after = "";
			c = token.content;

			if (!token.isAnyType([ "WHITESPACE", "LINE_TERMINATOR", "SINGLE_LINE_COMMENT", "MULTI_LINE_COMMENT", "BOM", "SHEBANG", "UNKNOWN" ])) {
				if (token.isType("KEYWORD")) {
					if (c === "function") {
						name = (token_pre_name === null ? "?" : token_pre_name.content);
						t = (function_starts.length > 0 ? function_names[function_starts[function_starts.length - 1][1]] : "?");
						if (t !== "?") name = t + "." + name;
						function_starts.push([ parens, function_names.length ]);
						function_names.push(name);
					}
				}
				else if (token.isType("PUNCTUATOR")) {
					if (c === "[" || c === "(" || c === "{") {
						++parens;
					}
					else if (c === "]" || c === ")" || c === "}") {
						--parens;
						if (
							c === "}" &&
							function_starts.length > 0 &&
							(fs = function_starts[function_starts.length - 1])[0] === parens
						) {
							function_starts.pop();
							if (start_parens >= 0 && parens >= start_parens) {
								after = "._w(" + fs[1] + ")";
							}
						}
					}
				}

				if (token.isAnyType([ "KEYWORD", "NULL_LITERAL", "NUMERIC_LITERAL", "IDENTIFIER_NAME" ])) {
					token_pre_name = token;
				}
				else if (token.isAnyType([ "PUNCTUATOR" ])) {
					if (c !== "[" && c !== "(" && c !== "{" && c !== ":" && c !== "=") {
						token_pre_name = null;
					}
				}
				else {
					token_pre_name = null;
				}

				token_pre = token;
			}
			else if (start_parens < 0 && token.isType("SINGLE_LINE_COMMENT")) {
				if (/\/\/\s*begin_debug\s*/.test(c)) {
					start_parens = parens;
					indent = /(?:^|\n)([\t ]*)$/.exec(output);
					indent = (indent === null) ? "" : indent[1];
					c = "(" + stringify_function(simple ? wrap_setup_simple : wrap_setup, indent) + ")();";

					// Position
					if (!simple) {
						function_name_pos = c.indexOf("function_names = []");
						if (function_name_pos >= 0) {
							function_name_pos += output.length + before.length + ("function_names = ").length;
						}
					}
				}
			}

			// Output
			output += before;
			output += c;
			output += after;
		}

		if (function_name_pos >= 0) {
			output = output.substr(0, function_name_pos) + JSON.stringify(function_names) + output.substr(function_name_pos + 2);
		}

		return output;
	};

	module.exports = {
		debug_wrap_code: debug_wrap_code
	};

})(module);

<|endoftext|>


<commit_before>import DEFAULT_STATES from '../consts/default_states';
import { NOTIFS } from '../consts/types';

export default (state = DEFAULT_STATES.notifs, action) => {
  switch (action.type) {
    case NOTIFS.FETCH:
      return action.notifs;
    case NOTIFS.CLEAR:
      return { ...state, items: action.items, num_unread: action.num_unread };
    case NOTIFS.CLEARALL:
      return { ...state, num_unread: 0 };
    default:
      return state;
  }
};
<commit_msg>test(reducers): remove unused notifs clear reducer step<commit_after>import DEFAULT_STATES from '../consts/default_states';
import { NOTIFS } from '../consts/types';

export default (state = DEFAULT_STATES.notifs, action) => {
  switch (action.type) {
    case NOTIFS.FETCH:
      return action.notifs;
    /* case NOTIFS.CLEAR:
      return { ...state, items: action.items, num_unread: action.num_unread }; */
    case NOTIFS.CLEARALL:
      return { ...state, num_unread: 0 };
    default:
      return state;
  }
};
<|endoftext|>


<commit_before>{
        'type': 'game', // game or console
        'name': 'DeathRace',
        'authors': ['Howell Ivy',
        'company': ['Exidy'],
        'year': '1976',
        'date': '1976', // Day, Month, Year
        'headline': 'um dos Primeiros jogos a causar uma grande polemica ',
        'resume':
            'Você sabia, que o jogo Death Race Foi “culpado” Por causar Alguns dos vários Problemas No Mundo?, ',
            'Para um jogo simples onde a única finalidade era atropelar Gremlins No começo parecia uma , ',
            'ideia genial, o único problema era que os vulgos “gremlins” pareciam muito com Humanos , ',
            'Como o gráfico era muito primitivo essa associação era muito “comum”   Claro que isso não , ',
            'pegou muito bem Pois quando um gremlin era morto , Aparecia uma lapide no lugar assim , ',
            'Deixando a ligação entre Gremlin – Humano '
        ].join(''),
        'full_text': [
            'O jogo em si, Pedestrian foi inspirado em um filme que se chamava Death Race 2000.  Ao passar do , ',
            'tempo em que o jogo era desenvolvido sua produtora Exidy decidiu adotar o nome Death Race e assim , ',
            'esquecendo o pedestrian, e batizando o jogo como Death Race, ',
            'Assim como uma ilustração da Morte no panfleto promocional do game ou os esqueletos nos lados do , ',
            'arcade do game. Num mundo onde videogames eram apenas uns bloquinhos coloridos feitos para  ',
            'crianças, esse era um jogo muito adulto E assim claro a mídia que na época era muito conservadora não  ',
            'gostou muito da ideia, claro Com a mídia muito agitada Surgiu várias reportagens mostrando o perigo e, ',
            'um impacto psicológico que o game causava na mente de seus jogadores. ',
            'E com isso um ex funcionário da Exidy afirmou que nessa polemica sobre o jogo fez que suas vendas , ',
            'Triplicassem o Próprio presidente afirmou que quanto mais controvérsia existia  mais suas vendas aumentavam, ',
            'A Exidy já faliu a muitos e muitos anos, mas sua franquia de death race Sobreviveu por muito tempo  o, ' ,
            'game foi relançado para NES e mais de 20 anos depois Ganhou sua versão para PCs .'
        ].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'DeathRaceArcade.png', 'caption': "description"},
        'images': [
            {'name': 'main_picture.png', 'caption': "jogo"},
            {'name': 'picture1.png', 'caption': "interface"},
            {'name': 'picture2.png', 'caption': "Tela do jogo"}
        ],
        'video_gameplay': [
            { 'url' : 'https://www.youtube.com/watch?v=aBBtt72aJLA' , "caption"  : "Gameplay do jogo "}
        ],

        ],
        'references': [
            {'url': "http://www.kotaku.com.br" , 'caption': " Death Race, the World\'s First Scandalous Video Game "},
            {'url': "http://omelete.uol.com.br", 'caption': " Omelete"}

        ]
<commit_msg>Update DeathRace_temp.js<commit_after>{
        'type': 'arcade ', // game or console
        'name': 'DeathRace',
        'authors': ['Exidy  . Designed by : Howell Ivy. ',
        'company': ['Exidy'],
        'year': '1976',
        'date': '1976', // Day, Month, Year
        'headline': 'um dos Primeiros jogos a causar uma grande polemica ',
        'resume':
            'Você sabia, que o jogo Death Race Foi “culpado” Por causar Alguns dos vários Problemas No Mundo?, ',
            'Para um jogo simples onde a única finalidade era atropelar Gremlins No começo parecia uma , ',
            'ideia genial, o único problema era que os vulgos “gremlins” pareciam muito com Humanos , ',
            'Como o gráfico era muito primitivo essa associação era muito “comum”   Claro que isso não , ',
            'pegou muito bem Pois quando um gremlin era morto , Aparecia uma lapide no lugar assim , ',
            'Deixando a ligação entre Gremlin – Humano '
        ].join(''),
        'full_text': [
            'O jogo em si, Pedestrian foi inspirado em um filme que se chamava Death Race 2000.  Ao passar do , ',
            'tempo em que o jogo era desenvolvido sua produtora Exidy decidiu adotar o nome Death Race e assim , ',
            'esquecendo o pedestrian, e batizando o jogo como Death Race, ',
            'Assim como uma ilustração da Morte no panfleto promocional do game ou os esqueletos nos lados do , ',
            'arcade do game. Num mundo onde videogames eram apenas uns bloquinhos coloridos feitos para  ',
            'crianças, esse era um jogo muito adulto E assim claro a mídia que na época era muito conservadora não  ',
            'gostou muito da ideia, claro Com a mídia muito agitada Surgiu várias reportagens mostrando o perigo e, ',
            'um impacto psicológico que o game causava na mente de seus jogadores. ',
            'E com isso um ex funcionário da Exidy afirmou que nessa polemica sobre o jogo fez que suas vendas , ',
            'Triplicassem o Próprio presidente afirmou que quanto mais controvérsia existia  mais suas vendas aumentavam, ',
            'A Exidy já faliu a muitos e muitos anos, mas sua franquia de death race Sobreviveu por muito tempo  o, ' ,
            'game foi relançado para NES e mais de 20 anos depois Ganhou sua versão para PCs .'
        ].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'DeathRaceArcade.png', 'caption': "description"},
        'images': [
            {'name': 'main_picture.png', 'caption': "jogo"},
            {'name': 'picture1.png', 'caption': "interface"},
            {'name': 'picture2.png', 'caption': "Tela do jogo"}
        ],
        'video_gameplay': [
            { 'url' : 'https://www.youtube.com/watch?v=aBBtt72aJLA' , "caption"  : "Gameplay do jogo "
        ],

        ],
        'references': [
            {'url': "http://kotaku.com/5889166/death-race-the-first-scandalous-video-gamer" , 'caption': " Death Race, the World's First Scandalous Video Game "},

            {'url': "http://omelete.uol.com.br/games/artigo/os-games-mais-polemicos-ja-criados/", 'caption': " OS GAMES MAIS POLÊMICOS DA HISTÓRIA"},

        ]
<|endoftext|>


<commit_before>const path = require('path');
const TextBuffer = require ('../src/text-buffer');

describe('when a buffer is already open', () => {
  it('replaces foo( with bar( using /\bfoo\(\b/gim', () => {
    const filePath = path.join(__dirname, 'fixtures','sample.js');
    const buffer = new TextBuffer();
    buffer.setPath(filePath);
    buffer.setText('foo(x)');
    buffer.replace(/\bfoo\(\b/gim,'bar(');

    expect(buffer.getText()).toBe('bar(x)');
  });
});
<commit_msg>fixed lint<commit_after>const path = require('path')
const TextBuffer = require('../src/text-buffer')

describe('when a buffer is already open', () => {
  it('replaces foo( with bar( using /\bfoo\\(\b/gim', () => {
    const filePath = path.join(__dirname, 'fixtures', 'sample.js')
    const buffer = new TextBuffer()
    buffer.setPath(filePath)
    buffer.setText('foo(x)')
    buffer.replace(/\bfoo\(\b/gim, 'bar(')

    expect(buffer.getText()).toBe('bar(x)')
  })
})
<|endoftext|>


<commit_before>// Custom reveal.js integration
(function(){
	var isEnabled = true;

	/*document.querySelector( '.reveal .slides' ).addEventListener( 'mousedown', function( event ) {
		var modifier = ( Reveal.getConfig().zoomKey ? Reveal.getConfig().zoomKey : 'alt' ) + 'Key';

		var zoomPadding = 20;
		var revealScale = Reveal.getScale();

		if( event[ modifier ] && isEnabled ) {
			event.preventDefault();

			var bounds = event.target.getBoundingClientRect();

			zoom.to({
				x: ( bounds.left * revealScale ) - zoomPadding,
				y: ( bounds.top * revealScale ) - zoomPadding,
				width: ( bounds.width * revealScale ) + ( zoomPadding * 2 ),
				height: ( bounds.height * revealScale ) + ( zoomPadding * 2 ),
				pan: false
			});
		}
	} );*/

	var pressTimer;

	document.querySelector( '.reveal .slides').addEventListener( 'mouseup', function ( event ) {
		clearTimeout(pressTimer);
	} );

	document.querySelector( '.reveal .slides' ).addEventListener( 'mousedown', function ( event ) {
		pressTimer = setTimeout( function() {
			var zoomPadding = 20;
			var revealScale = Reveal.getScale();

			var bounds = event.target.getBoundingClientRect();

			zoom.to({
				x: ( bounds.left * revealScale ) - zoomPadding,
				y: ( bounds.top * revealScale) - zoomPadding,
				width: ( bounds.width * revealScale ) + ( zoomPadding * 2),
				height: ( bounds.height * revealScale ) + ( zoomPadding * 2),
				pan: false
			});
		}, 1000);
	} );

	document.querySelector( '.reveal .slides').addEventListener( 'touchend', function ( event ) {
		clearTimeout(pressTimer);
	} );

	document.querySelector( '.reveal .slides' ).addEventListener( 'touchstart', function ( event ) {
		pressTimer = setTimeout( function() {
			var zoomPadding = 20;
			var revealScale = Reveal.getScale();

			var bounds = event.target.getBoundingClientRect();

			zoom.to({
				x: ( bounds.left * revealScale ) - zoomPadding,
				y: ( bounds.top * revealScale) - zoomPadding,
				width: ( bounds.width * revealScale ) + ( zoomPadding * 2),
				height: ( bounds.height * revealScale ) + ( zoomPadding * 2),
				pan: false
			});
		}, 1000);
	} );

	Reveal.addEventListener( 'overviewshown', function() { isEnabled = false; } );
	Reveal.addEventListener( 'overviewhidden', function() { isEnabled = true; } );
})();

/*!
 * zoom.js 0.3 (modified for use with reveal.js)
 * http://lab.hakim.se/zoom-js
 * MIT licensed
 *
 * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se
 */
var zoom = (function(){

	// The current zoom level (scale)
	var level = 1;

	// The current mouse position, used for panning
	var mouseX = 0,
		mouseY = 0;

	// Timeout before pan is activated
	var panEngageTimeout = -1,
		panUpdateInterval = -1;

	// Check for transform support so that we can fallback otherwise
	var supportsTransforms = 	'WebkitTransform' in document.body.style ||
								'MozTransform' in document.body.style ||
								'msTransform' in document.body.style ||
								'OTransform' in document.body.style ||
								'transform' in document.body.style;

	if( supportsTransforms ) {
		// The easing that will be applied when we zoom in/out
		document.body.style.transition = 'transform 0.8s ease';
		document.body.style.OTransition = '-o-transform 0.8s ease';
		document.body.style.msTransition = '-ms-transform 0.8s ease';
		document.body.style.MozTransition = '-moz-transform 0.8s ease';
		document.body.style.WebkitTransition = '-webkit-transform 0.8s ease';
	}

	// Zoom out if the user hits escape
	document.addEventListener( 'keyup', function( event ) {
		if( level !== 1 && event.keyCode === 27 ) {
			zoom.out();
		}
	} );

	// Monitor mouse movement for panning
	document.addEventListener( 'mousemove', function( event ) {
		if( level !== 1 ) {
			mouseX = event.clientX;
			mouseY = event.clientY;
		}
	} );

	/**
	 * Applies the CSS required to zoom in, prefers the use of CSS3
	 * transforms but falls back on zoom for IE.
	 *
	 * @param {Object} rect
	 * @param {Number} scale
	 */
	function magnify( rect, scale ) {

		var scrollOffset = getScrollOffset();

		// Ensure a width/height is set
		rect.width = rect.width || 1;
		rect.height = rect.height || 1;

		// Center the rect within the zoomed viewport
		rect.x -= ( window.innerWidth - ( rect.width * scale ) ) / 2;
		rect.y -= ( window.innerHeight - ( rect.height * scale ) ) / 2;

		if( supportsTransforms ) {
			// Reset
			if( scale === 1 ) {
				document.body.style.transform = '';
				document.body.style.OTransform = '';
				document.body.style.msTransform = '';
				document.body.style.MozTransform = '';
				document.body.style.WebkitTransform = '';
			}
			// Scale
			else {
				var origin = scrollOffset.x +'px '+ scrollOffset.y +'px',
					transform = 'translate('+ -rect.x +'px,'+ -rect.y +'px) scale('+ scale +')';

				document.body.style.transformOrigin = origin;
				document.body.style.OTransformOrigin = origin;
				document.body.style.msTransformOrigin = origin;
				document.body.style.MozTransformOrigin = origin;
				document.body.style.WebkitTransformOrigin = origin;

				document.body.style.transform = transform;
				document.body.style.OTransform = transform;
				document.body.style.msTransform = transform;
				document.body.style.MozTransform = transform;
				document.body.style.WebkitTransform = transform;
			}
		}
		else {
			// Reset
			if( scale === 1 ) {
				document.body.style.position = '';
				document.body.style.left = '';
				document.body.style.top = '';
				document.body.style.width = '';
				document.body.style.height = '';
				document.body.style.zoom = '';
			}
			// Scale
			else {
				document.body.style.position = 'relative';
				document.body.style.left = ( - ( scrollOffset.x + rect.x ) / scale ) + 'px';
				document.body.style.top = ( - ( scrollOffset.y + rect.y ) / scale ) + 'px';
				document.body.style.width = ( scale * 100 ) + '%';
				document.body.style.height = ( scale * 100 ) + '%';
				document.body.style.zoom = scale;
			}
		}

		level = scale;

		if( document.documentElement.classList ) {
			if( level !== 1 ) {
				document.documentElement.classList.add( 'zoomed' );
			}
			else {
				document.documentElement.classList.remove( 'zoomed' );
			}
		}
	}

	/**
	 * Pan the document when the mosue cursor approaches the edges
	 * of the window.
	 */
	function pan() {
		var range = 0.12,
			rangeX = window.innerWidth * range,
			rangeY = window.innerHeight * range,
			scrollOffset = getScrollOffset();

		// Up
		if( mouseY < rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) );
		}
		// Down
		else if( mouseY > window.innerHeight - rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) );
		}

		// Left
		if( mouseX < rangeX ) {
			window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y );
		}
		// Right
		else if( mouseX > window.innerWidth - rangeX ) {
			window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y );
		}
	}

	function getScrollOffset() {
		return {
			x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset,
			y: window.scrollY !== undefined ? window.scrollY : window.pageYOffset
		}
	}

	return {
		/**
		 * Zooms in on either a rectangle or HTML element.
		 *
		 * @param {Object} options
		 *   - element: HTML element to zoom in on
		 *   OR
		 *   - x/y: coordinates in non-transformed space to zoom in on
		 *   - width/height: the portion of the screen to zoom in on
		 *   - scale: can be used instead of width/height to explicitly set scale
		 */
		to: function( options ) {

			// Due to an implementation limitation we can't zoom in
			// to another element without zooming out first
			if( level !== 1 ) {
				zoom.out();
			}
			else {
				options.x = options.x || 0;
				options.y = options.y || 0;

				// If an element is set, that takes precedence
				if( !!options.element ) {
					// Space around the zoomed in element to leave on screen
					var padding = 20;
					var bounds = options.element.getBoundingClientRect();

					options.x = bounds.left - padding;
					options.y = bounds.top - padding;
					options.width = bounds.width + ( padding * 2 );
					options.height = bounds.height + ( padding * 2 );
				}

				// If width/height values are set, calculate scale from those values
				if( options.width !== undefined && options.height !== undefined ) {
					options.scale = Math.max( Math.min( window.innerWidth / options.width, window.innerHeight / options.height ), 1 );
				}

				if( options.scale > 1 ) {
					options.x *= options.scale;
					options.y *= options.scale;

					magnify( options, options.scale );

					if( options.pan !== false ) {

						// Wait with engaging panning as it may conflict with the
						// zoom transition
						panEngageTimeout = setTimeout( function() {
							panUpdateInterval = setInterval( pan, 1000 / 60 );
						}, 800 );

					}
				}
			}
		},

		/**
		 * Resets the document zoom state to its default.
		 */
		out: function() {
			clearTimeout( panEngageTimeout );
			clearInterval( panUpdateInterval );

			magnify( { x: 0, y: 0 }, 1 );

			level = 1;
		},

		// Alias
		magnify: function( options ) { this.to( options ) },
		reset: function() { this.out() },

		zoomLevel: function() {
			return level;
		}
	}

})();

<commit_msg>Readded zoomjs<commit_after>// Custom reveal.js integration
(function(){
	var isEnabled = true;

	/*document.querySelector( '.reveal .slides' ).addEventListener( 'mousedown', function( event ) {
		var modifier = ( Reveal.getConfig().zoomKey ? Reveal.getConfig().zoomKey : 'alt' ) + 'Key';

		var zoomPadding = 20;
		var revealScale = Reveal.getScale();

		if( event[ modifier ] && isEnabled ) {
			event.preventDefault();

			var bounds = event.target.getBoundingClientRect();

			zoom.to({
				x: ( bounds.left * revealScale ) - zoomPadding,
				y: ( bounds.top * revealScale ) - zoomPadding,
				width: ( bounds.width * revealScale ) + ( zoomPadding * 2 ),
				height: ( bounds.height * revealScale ) + ( zoomPadding * 2 ),
				pan: false
			});
		}
	} );*/

	var pressTimer;

	document.querySelector( '.reveal .slides').addEventListener( 'mouseup', function ( event ) {
		event.preventDefault();
		clearTimeout(pressTimer);
	} );

	document.querySelector( '.reveal .slides' ).addEventListener( 'mousedown', function ( event ) {
		event.preventDefault();

		pressTimer = setTimeout( function() {
			var zoomPadding = 20;
			var revealScale = Reveal.getScale();

			var bounds = event.target.getBoundingClientRect();

			zoom.to({
				x: ( bounds.left * revealScale ) - zoomPadding,
				y: ( bounds.top * revealScale) - zoomPadding,
				width: ( bounds.width * revealScale ) + ( zoomPadding * 2),
				height: ( bounds.height * revealScale ) + ( zoomPadding * 2),
				pan: false
			});
		}, 1000);
	} );

	document.querySelector( '.reveal .slides').addEventListener( 'touchend', function ( event ) {
		event.preventDefault();
		clearTimeout(pressTimer);
	} );

	document.querySelector( '.reveal .slides' ).addEventListener( 'touchstart', function ( event ) {
		event.preventDefault();

		pressTimer = setTimeout( function() {
			var zoomPadding = 20;
			var revealScale = Reveal.getScale();

			var bounds = event.target.getBoundingClientRect();

			zoom.to({
				x: ( bounds.left * revealScale ) - zoomPadding,
				y: ( bounds.top * revealScale) - zoomPadding,
				width: ( bounds.width * revealScale ) + ( zoomPadding * 2),
				height: ( bounds.height * revealScale ) + ( zoomPadding * 2),
				pan: false
			});
		}, 1000);
	} );

	Reveal.addEventListener( 'overviewshown', function() { isEnabled = false; } );
	Reveal.addEventListener( 'overviewhidden', function() { isEnabled = true; } );
})();

/*!
 * zoom.js 0.3 (modified for use with reveal.js)
 * http://lab.hakim.se/zoom-js
 * MIT licensed
 *
 * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se
 */
var zoom = (function(){

	// The current zoom level (scale)
	var level = 1;

	// The current mouse position, used for panning
	var mouseX = 0,
		mouseY = 0;

	// Timeout before pan is activated
	var panEngageTimeout = -1,
		panUpdateInterval = -1;

	// Check for transform support so that we can fallback otherwise
	var supportsTransforms = 	'WebkitTransform' in document.body.style ||
								'MozTransform' in document.body.style ||
								'msTransform' in document.body.style ||
								'OTransform' in document.body.style ||
								'transform' in document.body.style;

	if( supportsTransforms ) {
		// The easing that will be applied when we zoom in/out
		document.body.style.transition = 'transform 0.8s ease';
		document.body.style.OTransition = '-o-transform 0.8s ease';
		document.body.style.msTransition = '-ms-transform 0.8s ease';
		document.body.style.MozTransition = '-moz-transform 0.8s ease';
		document.body.style.WebkitTransition = '-webkit-transform 0.8s ease';
	}

	// Zoom out if the user hits escape
	document.addEventListener( 'keyup', function( event ) {
		if( level !== 1 && event.keyCode === 27 ) {
			zoom.out();
		}
	} );

	// Monitor mouse movement for panning
	document.addEventListener( 'mousemove', function( event ) {
		if( level !== 1 ) {
			mouseX = event.clientX;
			mouseY = event.clientY;
		}
	} );

	/**
	 * Applies the CSS required to zoom in, prefers the use of CSS3
	 * transforms but falls back on zoom for IE.
	 *
	 * @param {Object} rect
	 * @param {Number} scale
	 */
	function magnify( rect, scale ) {

		var scrollOffset = getScrollOffset();

		// Ensure a width/height is set
		rect.width = rect.width || 1;
		rect.height = rect.height || 1;

		// Center the rect within the zoomed viewport
		rect.x -= ( window.innerWidth - ( rect.width * scale ) ) / 2;
		rect.y -= ( window.innerHeight - ( rect.height * scale ) ) / 2;

		if( supportsTransforms ) {
			// Reset
			if( scale === 1 ) {
				document.body.style.transform = '';
				document.body.style.OTransform = '';
				document.body.style.msTransform = '';
				document.body.style.MozTransform = '';
				document.body.style.WebkitTransform = '';
			}
			// Scale
			else {
				var origin = scrollOffset.x +'px '+ scrollOffset.y +'px',
					transform = 'translate('+ -rect.x +'px,'+ -rect.y +'px) scale('+ scale +')';

				document.body.style.transformOrigin = origin;
				document.body.style.OTransformOrigin = origin;
				document.body.style.msTransformOrigin = origin;
				document.body.style.MozTransformOrigin = origin;
				document.body.style.WebkitTransformOrigin = origin;

				document.body.style.transform = transform;
				document.body.style.OTransform = transform;
				document.body.style.msTransform = transform;
				document.body.style.MozTransform = transform;
				document.body.style.WebkitTransform = transform;
			}
		}
		else {
			// Reset
			if( scale === 1 ) {
				document.body.style.position = '';
				document.body.style.left = '';
				document.body.style.top = '';
				document.body.style.width = '';
				document.body.style.height = '';
				document.body.style.zoom = '';
			}
			// Scale
			else {
				document.body.style.position = 'relative';
				document.body.style.left = ( - ( scrollOffset.x + rect.x ) / scale ) + 'px';
				document.body.style.top = ( - ( scrollOffset.y + rect.y ) / scale ) + 'px';
				document.body.style.width = ( scale * 100 ) + '%';
				document.body.style.height = ( scale * 100 ) + '%';
				document.body.style.zoom = scale;
			}
		}

		level = scale;

		if( document.documentElement.classList ) {
			if( level !== 1 ) {
				document.documentElement.classList.add( 'zoomed' );
			}
			else {
				document.documentElement.classList.remove( 'zoomed' );
			}
		}
	}

	/**
	 * Pan the document when the mosue cursor approaches the edges
	 * of the window.
	 */
	function pan() {
		var range = 0.12,
			rangeX = window.innerWidth * range,
			rangeY = window.innerHeight * range,
			scrollOffset = getScrollOffset();

		// Up
		if( mouseY < rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) );
		}
		// Down
		else if( mouseY > window.innerHeight - rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) );
		}

		// Left
		if( mouseX < rangeX ) {
			window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y );
		}
		// Right
		else if( mouseX > window.innerWidth - rangeX ) {
			window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y );
		}
	}

	function getScrollOffset() {
		return {
			x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset,
			y: window.scrollY !== undefined ? window.scrollY : window.pageYOffset
		}
	}

	return {
		/**
		 * Zooms in on either a rectangle or HTML element.
		 *
		 * @param {Object} options
		 *   - element: HTML element to zoom in on
		 *   OR
		 *   - x/y: coordinates in non-transformed space to zoom in on
		 *   - width/height: the portion of the screen to zoom in on
		 *   - scale: can be used instead of width/height to explicitly set scale
		 */
		to: function( options ) {

			// Due to an implementation limitation we can't zoom in
			// to another element without zooming out first
			if( level !== 1 ) {
				zoom.out();
			}
			else {
				options.x = options.x || 0;
				options.y = options.y || 0;

				// If an element is set, that takes precedence
				if( !!options.element ) {
					// Space around the zoomed in element to leave on screen
					var padding = 20;
					var bounds = options.element.getBoundingClientRect();

					options.x = bounds.left - padding;
					options.y = bounds.top - padding;
					options.width = bounds.width + ( padding * 2 );
					options.height = bounds.height + ( padding * 2 );
				}

				// If width/height values are set, calculate scale from those values
				if( options.width !== undefined && options.height !== undefined ) {
					options.scale = Math.max( Math.min( window.innerWidth / options.width, window.innerHeight / options.height ), 1 );
				}

				if( options.scale > 1 ) {
					options.x *= options.scale;
					options.y *= options.scale;

					magnify( options, options.scale );

					if( options.pan !== false ) {

						// Wait with engaging panning as it may conflict with the
						// zoom transition
						panEngageTimeout = setTimeout( function() {
							panUpdateInterval = setInterval( pan, 1000 / 60 );
						}, 800 );

					}
				}
			}
		},

		/**
		 * Resets the document zoom state to its default.
		 */
		out: function() {
			clearTimeout( panEngageTimeout );
			clearInterval( panUpdateInterval );

			magnify( { x: 0, y: 0 }, 1 );

			level = 1;
		},

		// Alias
		magnify: function( options ) { this.to( options ) },
		reset: function() { this.out() },

		zoomLevel: function() {
			return level;
		}
	}

})();

<|endoftext|>


<commit_before>Package.describe({
  summary: "Async provides straight-forward, powerful functions for working with asynchronous JavaScript",
  version: '0.9.0-2',
  name: 'peerlibrary:async',
  git: 'https://github.com/peerlibrary/meteor-async.git'
});

Package.on_use(function (api) {
  api.versionsFrom("METEOR@0.9.1");
  api.export('async');

  api.add_files([
    'async/lib/async.js',
    'export-async.js'
  ], ['client', 'server']);
});

Package.on_test(function (api) {
  api.use(["peerlibrary:async", 'tinytest', 'test-helpers'], ['client', 'server']);
  api.add_files('tests.js', ['client', 'server']);
});
<commit_msg>Style.<commit_after>Package.describe({
  summary: "Async provides straight-forward, powerful functions for working with asynchronous JavaScript",
  version: '0.9.0-2',
  name: 'peerlibrary:async',
  git: 'https://github.com/peerlibrary/meteor-async.git'
});

Package.on_use(function (api) {
  api.versionsFrom("METEOR@0.9.1");
  api.export('async');

  api.add_files([
    'async/lib/async.js',
    'export-async.js'
  ], ['client', 'server']);
});

Package.on_test(function (api) {
  api.use(['peerlibrary:async', 'tinytest', 'test-helpers'], ['client', 'server']);
  api.add_files('tests.js', ['client', 'server']);
});
<|endoftext|>


<commit_before>/*
 * grunt-rt-deployinator
 * https://github.com/michael/grunt-rt-deployinator
 *
 * Copyright (c) 2014 Michael Klein
 * Licensed under the MIT license.
 */

'use strict';

var Deploy = require('deployinator');

module.exports = function(grunt) {

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

  grunt.registerMultiTask('rt_deployinator', 'Grunt task for lightning fast deployments of JavaScript Apps.', function() {
    var done = this.async();

    var options = this.options({});

    var deploy = new Deploy(options);

    var success = function(value) {
      console.log(value);
      grunt.log.ok('Deploy successful!');
      done();
    };

    var error = function() {
      grunt.log.error('Error: Deploy not successful!');
    };

    deploy.deploy('deployed with options')
      .then(success, error);

    // Iterate over all specified file groups.
    // this.files.forEach(function(f) {
      // // Concat specified files.
      // var src = f.src.filter(function(filepath) {
        // // Warn on and remove invalid source files (if nonull was set).
        // if (!grunt.file.exists(filepath)) {
          // grunt.log.warn('Source file "' + filepath + '" not found.');
          // return false;
        // } else {
          // return true;
        // }
      // }).map(function(filepath) {
        // // Read file source.
        // return grunt.file.read(filepath);
      // }).join(grunt.util.normalizelf(options.separator));

      // // Handle options.
      // src += options.punctuation;

      // // Write the destination file.
      // grunt.file.write(f.dest, src);

      // // Print a success message.
      // grunt.log.writeln('File "' + f.dest + '" created.');
    // });
  });

};
<commit_msg>Tasks finished.<commit_after>/*
 * grunt-rt-deployinator
 * https://github.com/michael/grunt-rt-deployinator
 *
 * Copyright (c) 2014 Michael Klein
 * Licensed under the MIT license.
 */

'use strict';

var Deploy = require('deployinator');
var RSVP = require('rsvp');

module.exports = function(grunt) {

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

  grunt.registerMultiTask('upload', 'Grunt task for lightning fast deployments of JavaScript Apps.', function() {
    var done = this.async();

    var options = this.options({});

    var deploy = new Deploy(options);

    var success = function(value) {
      grunt.log.ok('Deploy: ' + deploy.key +  ' successful!');
      done();
    };

    var error = function(error) {
      grunt.log.error('Error! Deploy not successful! Reason: '+ error);
    };

    var fileExists = function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    };

    var deployFileContent = function(filepath) {
      deploy.upload(grunt.file.read(filepath))
        .then(success, error);
    };

    var deployFile = function(file) {
      file.src.filter(fileExists).forEach(deployFileContent);
    };

    this.files.forEach(deployFile);
  });

  grunt.registerMultiTask('listUploads', 'Grunt task to list all <manifestSize> deploys', function() {
    var done = this.async();

    var options = this.options({});

    var deploy = new Deploy(options);

    var promises = {
      uploads: deploy.listUploads(),
      current: deploy.getCurrent()
    };

    RSVP.hash(promises).then(function(results) {
      grunt.log.ok('Last ' + deploy.manifestSize + ' deploys:\n');
      grunt.log.ok('');
      grunt.log.ok('|    Git-SHA');
      grunt.log.ok('|');
      results.uploads.forEach(function(key) {
        var prefix = (key === results.current) ? '| => ' : '|    ';
        grunt.log.ok(prefix + key + '\n');
      });
      grunt.log.ok('');
      grunt.log.ok('# => - current');
      done();
    });
  });

  grunt.registerMultiTask('deploy', 'Deploy this shit', function(key) {
    var done = this.async();

    var options = this.options({});

    var deploy = new Deploy(options);

    var success = function() {
      grunt.log.ok('Deploy successfull!');
      grunt.log.ok('Run `grunt listUploads` to see which revision is current');
      done();
    };

    var error = function() {
      grunt.log.error('Deploy failed!');
      grunt.log.error('You have to specify a valid manifest...');
      grunt.log.error('Please run `grunt listUploads` to see valid options');
      done();
    };

    deploy.setCurrent(key)
      .then(success, error);
  });

  grunt.loadNpmTasks('grunt-git-describe');

};
<|endoftext|>


<commit_before>require(__dirname + "/../sequelize")

module.exports = {
  'test constants': function(assert) {
    assert.isNotUndefined(Sequelize.STRING)
    assert.isNotNull(Sequelize.STRING)
    assert.isNotUndefined(Sequelize.TEXT)
    assert.isNotNull(Sequelize.TEXT)
    assert.isNotUndefined(Sequelize.INTEGER)
    assert.isNotNull(Sequelize.INTEGER)
  },
  'the constructor sets config correctly': function(assert){
    var s = new Sequelize('sequelize_test', 'test', 'test')
    assert.equal(s.config.database, 'sequelize_test')
    assert.equal(s.config.username, 'test')
    assert.equal(s.config.password, 'test')
  },
  'the constructor initializes empty tables hash': function(assert) {
    var s = new Sequelize('sequelize_test', 'test', 'test')
    assert.isNotUndefined(s.tables)
    assert.isNotNull(s.tables)
    assert.eql(s.tables, {})
  },
  'define should return a function': function(assert){
    var s = new Sequelize('sequelize_test', 'test', 'test')
    var Day = s.define('Day', { name: Sequelize.TEXT })
    assert.equal(typeof Day, 'function')
  },
  'define should store attributes': function(assert) {
    var s = new Sequelize('sequelize_test', 'test', 'test')
    var Day = s.define('Day', { name: Sequelize.TEXT })
    assert.isNotUndefined(Day.attributes)
    assert.isNotNull(Day.attributes)
    assert.eql(Day.attributes, { name: Sequelize.TEXT, createdAt: "DATETIME NOT NULL", updatedAt: "DATETIME NOT NULL"})
  },
  'define should add new table to tables': function(assert) {
    var s = new Sequelize('sequelize_test', 'test', 'test')
    var Day = s.define('Day', { name: Sequelize.TEXT })
    assert.includes(SequelizeHelper.Hash.keys(Day.sequelize.tables), 'Day')
  },
  'tableNames should be an empty array if no tables are specified': function(assert){
    var s = new Sequelize('sequelize_test', 'test', 'test')
    assert.deepEqual(s.tableNames, [])
  },
  'tableNames should be no empty array if tables are specified': function(assert) {
    var s = new Sequelize('sequelize_test', 'test', 'test')
    s.define('Day', { name: Sequelize.TEXT })
    assert.deepEqual(s.tableNames, ['Days'])
  }
}<commit_msg>moved Sequelize instantiation to global variable + tests for sqlQueryFor<commit_after>require(__dirname + "/../sequelize")

var s = new Sequelize('sequelize_test', 'test', 'test')

module.exports = {
  'test constants': function(assert) {
    assert.isNotUndefined(Sequelize.STRING)
    assert.isNotNull(Sequelize.STRING)
    assert.isNotUndefined(Sequelize.TEXT)
    assert.isNotNull(Sequelize.TEXT)
    assert.isNotUndefined(Sequelize.INTEGER)
    assert.isNotNull(Sequelize.INTEGER)
  },
  'the constructor sets config correctly': function(assert){
    assert.equal(s.config.database, 'sequelize_test')
    assert.equal(s.config.username, 'test')
    assert.equal(s.config.password, 'test')
  },
  'the constructor initializes empty tables hash': function(assert) {
    assert.isNotUndefined(s.tables)
    assert.isNotNull(s.tables)
    assert.eql(s.tables, {})
  },
  'define should return a function': function(assert){
    var Day = s.define('Day', { name: Sequelize.TEXT })
    assert.equal(typeof Day, 'function')
  },
  'define should store attributes': function(assert) {
    var Day = s.define('Day', { name: Sequelize.TEXT })
    assert.isNotUndefined(Day.attributes)
    assert.isNotNull(Day.attributes)
    assert.eql(Day.attributes, { name: Sequelize.TEXT, createdAt: "DATETIME NOT NULL", updatedAt: "DATETIME NOT NULL"})
  },
  'define should add new table to tables': function(assert) {
    var Day = s.define('Day', { name: Sequelize.TEXT })
    assert.includes(SequelizeHelper.Hash.keys(Day.sequelize.tables), 'Day')
  },
  'tableNames should be an empty array if no tables are specified': function(assert){
    var s2 = new Sequelize('sequelize_test', 'test', 'test')
    assert.deepEqual(s2.tableNames, [])
  },
  'tableNames should be no empty array if tables are specified': function(assert) {
    s.define('Day', { name: Sequelize.TEXT })
    assert.deepEqual(s.tableNames, ['Days'])
  },
  'sqlQueryFor: create': function(assert) {
    var query = Sequelize.sqlQueryFor('create', { table: 'Foo', fields: 'a INT' })
    assert.equal(query, "CREATE TABLE IF NOT EXISTS Foo (a INT)")
  },
  'sqlQueryFor: drop': function(assert) {
    var query = Sequelize.sqlQueryFor('drop', { table: 'Foo' })
    assert.equal(query, "DROP TABLE IF EXISTS Foo")
  },
  'sqlQueryFor: select': function(assert) {
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo'}), "SELECT * FROM Foo")
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo', fields: 'id'}), "SELECT id FROM Foo")
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo', where: 'id = 1'}), "SELECT * FROM Foo WHERE id = 1")
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo', order: 'id DESC'}), "SELECT * FROM Foo ORDER BY id DESC")
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo', group: 'name'}), "SELECT * FROM Foo GROUP BY name")
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo', limit: 1}), "SELECT * FROM Foo LIMIT 1")
    assert.equal(Sequelize.sqlQueryFor('select', { table: 'Foo', offset: 10, limit: 1}), "SELECT * FROM Foo LIMIT 10, 1")
  },
  'sqlQueryFor: insert': function(assert) {
    var query = Sequelize.sqlQueryFor('insert', { table: 'Foo', fields: 'foo', values: "'bar'" })
    assert.equal(query, "INSERT INTO Foo (foo) VALUES ('bar')")
  },
  'sqlQueryFor: update': function(assert) {
    var query = Sequelize.sqlQueryFor('update', { table: 'Foo', values: "foo=1", id: 2 })
    assert.equal(query, "UPDATE Foo SET foo=1 WHERE id = 2")
  },
  'sqlQueryFor: delete': function(assert) {
    var query = Sequelize.sqlQueryFor('delete', {table: 'Foo', id: 2})
    assert.equal(query, "DELETE FROM Foo WHERE id = 2 LIMIT 1")
  }
}<|endoftext|>


<commit_before>define([
    'knockout',
    'md5',
    'kb_common/html',
    'kb_knockout/registry',
    'kb_knockout/lib/generators',
    'kb_knockout/lib/viewModelBase',
    './countdownClock'
], function (
    ko,
    md5,
    html,
    reg,
    gen,
    ViewModelBase,
    CountdownClockComponent
) {
    'use strict';

    let t = html.tag,
        p = t('p'),
        button = t('button'),
        span = t('span'),
        div = t('div');

    let styles = html.makeStyles({
        component: {
            css: {
            }
        },
        wrapper: {
            css: {
                margin: '0 10px 10px 10px',
            }
        }
    });

    class ViewModel extends ViewModelBase {
        constructor(params) {
            super(params);

            this.systemStatus = params.systemStatus;
            this.error = params.error;

            this._maintenanceNotifications = ko.observableArray();

            this.now = ko.observable(Date.now());

            this.maintenanceNotifications = ko.pureComputed(() => {
                return this._maintenanceNotifications()
                    .filter((notification) => {
                        let endTime = notification.endAt.getTime();
                        let now = this.now();
                        if ( (now - endTime) > 60000) {
                            return false;
                        }
                        return true;
                    })
                    .sort((a, b) => {
                        return (a.startAt.getTime() - b.startAt.getTime());
                    });
            });

            this.hiddenMaintenanceNotificationCount = ko.pureComputed(() => {
                return this._maintenanceNotifications()
                    .filter((notification) => {
                        return notification.read();
                    }).length;
            });

            this.subscribe(this.systemStatus, (newValue) => {
                if (!newValue) {
                    return [];
                }

                let hashes = [];
                newValue.upcomingMaintenanceWindows
                    .forEach((notification) => {
                        let hash = md5.hash(JSON.stringify(notification));
                        hashes.push(hash);
                        let existing = this._maintenanceNotifications().some((item) => {
                            return item.hash === hash;
                        });
                        if (existing) {
                            // ignore existing and identical notifications.
                            return;
                        }

                        // add new ones.
                        let newNotification = {
                            startAt: new Date(notification.startAt),
                            endAt: new Date(notification.endAt),
                            title: notification.title,
                            message: notification.message,
                            read: ko.observable(false),
                            hash: hash
                        };
                        this._maintenanceNotifications.push(newNotification);
                    });

                this._maintenanceNotifications().forEach((item) => {
                    if (hashes.indexOf(item.hash) === -1) {
                        this._maintenanceNotifications.remove(item);
                    }
                });
            });

            // monitor for expired ones and remove them
            this.timer = window.setInterval(() => {
                this.now(Date.now());
            }, 10000);
        }

        doShowHidden() {
            this._maintenanceNotifications().forEach((notification) => {
                notification.read(false);
            });
        }

        dispose() {
            if (this.timer) {
                window.clearInterval(this.timer);
            }
        }
    }

    function buildError() {
        return div({
            class: 'alert alert-danger',
            dataBind: {
                text: 'error'
            }
        });
    }

    function buildMaintenanceNotification() {
        return div({
            class: 'panel panel-danger',
            style: {
                borderRadius: '0px',
                marginBottom: '0px'
                // position: 'relative'
            }
        }, [
            div({
                class: 'panel-heading',
                style: {
                    position: 'relative'
                }
            }, [
                span({
                    dataBind: {
                        text: '$data.title || "Upcoming System Maintenance"'
                    },
                    style: {
                        fontWeight: 'bold'
                    }
                }),
                button({
                    type: 'button',
                    class: 'close',
                    ariaLabel: 'Close',
                    dataBind: {
                        click: 'function(d,e){d.read(true);}'
                    },
                    style: {
                        fontSize: '80%',
                        position: 'absolute',
                        right: '8px',
                        top: '8px'
                    },
                    title: 'Use this button close the alert; when you reload the browser it will reappear; it will be permanently removed when it expires.'
                }, span({
                    class: 'fa fa-times'
                })),
            ]),
            div({
                class: 'panel-body'
            }, [
                div({
                    style: {
                        display: 'inline-block',
                        verticalAlign: 'top',
                        width: '50%'
                    }
                }, [

                    div({
                        dataBind: {
                            foreach: 'message'
                        }
                    }, p({
                        dataBind: {
                            text: '$data'
                        }
                    }))
                ]),
                div({
                    style: {
                        display: 'inline-block',
                        verticalAlign: 'top',
                        width: '50%',
                        textAlign: 'right'
                    }
                }, [
                    div([
                        span({
                            dataBind: {
                                typedText: {
                                    type: '"date-range"',
                                    format: '"nice-range"',
                                    value: {
                                        startDate: 'startAt',
                                        endDate: 'endAt'
                                    }
                                }
                            }
                        })
                    ]),
                    div([
                        span({
                            dataBind: {
                                component: {
                                    name: CountdownClockComponent.quotedName(),
                                    params: {
                                        startAt: 'startAt',
                                        endAt: 'endAt'
                                    }
                                }
                            }
                        })
                    ])
                ])
            ])
        ]);
    }

    function buildHeader() {
        return div({
            class: 'bg-danger text-danger',
            style: {
                // border: '1px red solid',
                // backgroundColor: 'red',
                // color: '#FFF',
                padding: '10px 15px'
            }
        }, [
            div({
                style: {
                    display: 'inline-block',
                    width: '50%'
                }
            }, span({
                style: {
                    fontWeight: 'bold'
                }
            }, [
                'System',
                gen.plural('maintenanceNotifications().length === 1', ' Alert', ' Alerts')
            ])),
            div({
                style: {
                    display: 'inline-block',
                    width: '50%',
                    textAlign: 'right'
                }
            }, [
                span({
                    dataBind: {
                        text: 'maintenanceNotifications().length'
                    }
                }),
                gen.plural('maintenanceNotifications().length', ' alert', ' alerts'),
                gen.if('hiddenMaintenanceNotificationCount() > 0',
                    [
                        ' (',
                        span({
                            dataBind: {
                                text: 'hiddenMaintenanceNotificationCount()'
                            }
                        }),
                        ' hidden ',
                        button({
                            type: 'button',
                            class: 'btn btn-default btn-xs',
                            dataBind: {
                                click: 'function(...args){$component.doShowHidden.apply($component, args);}'
                            }
                        }, span([
                            'show',
                            gen.plural('hiddenMaintenanceNotificationCount()', ' it', ' them')
                        ])),

                        ')'
                    ])
            ])
        ]);
    }

    function template() {
        // return div('hi from the notification banner');
        return div({
            class: styles.classes.component
        }, [
            gen.if('error()',
                div({
                    class: styles.classes.wrapper
                }, buildError()),
                gen.if('maintenanceNotifications().length > 0',
                    div({
                        class: styles.classes.wrapper
                    }, [
                        buildHeader(),
                        gen.foreach('maintenanceNotifications()',
                            gen.ifnot('read', buildMaintenanceNotification()))
                    ])))
        ]);
    }

    function component() {
        return {
            viewModel: ViewModel,
            template: template(),
            stylesheet: styles.sheet
        };
    }

    return reg.registerComponent(component);
});<commit_msg>try full width, fixe plural handling for title [SCT-713]<commit_after>define([
    'knockout',
    'md5',
    'kb_common/html',
    'kb_knockout/registry',
    'kb_knockout/lib/generators',
    'kb_knockout/lib/viewModelBase',
    './countdownClock'
], function (
    ko,
    md5,
    html,
    reg,
    gen,
    ViewModelBase,
    CountdownClockComponent
) {
    'use strict';

    let t = html.tag,
        p = t('p'),
        button = t('button'),
        span = t('span'),
        div = t('div');

    let styles = html.makeStyles({
        component: {
            css: {
            }
        },
        wrapper: {
            css: {
                margin: '0 0px 10px 0px',
            }
        }
    });

    class ViewModel extends ViewModelBase {
        constructor(params) {
            super(params);

            this.systemStatus = params.systemStatus;
            this.error = params.error;

            this._maintenanceNotifications = ko.observableArray();

            this.now = ko.observable(Date.now());

            this.maintenanceNotifications = ko.pureComputed(() => {
                return this._maintenanceNotifications()
                    .filter((notification) => {
                        let endTime = notification.endAt.getTime();
                        let now = this.now();
                        if ( (now - endTime) > 60000) {
                            return false;
                        }
                        return true;
                    })
                    .sort((a, b) => {
                        return (a.startAt.getTime() - b.startAt.getTime());
                    });
            });

            this.hiddenMaintenanceNotificationCount = ko.pureComputed(() => {
                return this._maintenanceNotifications()
                    .filter((notification) => {
                        return notification.read();
                    }).length;
            });

            this.subscribe(this.systemStatus, (newValue) => {
                if (!newValue) {
                    return [];
                }

                let hashes = [];
                newValue.upcomingMaintenanceWindows
                    .forEach((notification) => {
                        let hash = md5.hash(JSON.stringify(notification));
                        hashes.push(hash);
                        let existing = this._maintenanceNotifications().some((item) => {
                            return item.hash === hash;
                        });
                        if (existing) {
                            // ignore existing and identical notifications.
                            return;
                        }

                        // add new ones.
                        let newNotification = {
                            startAt: new Date(notification.startAt),
                            endAt: new Date(notification.endAt),
                            title: notification.title,
                            message: notification.message,
                            read: ko.observable(false),
                            hash: hash
                        };
                        this._maintenanceNotifications.push(newNotification);
                    });

                this._maintenanceNotifications().forEach((item) => {
                    if (hashes.indexOf(item.hash) === -1) {
                        this._maintenanceNotifications.remove(item);
                    }
                });
            });

            // monitor for expired ones and remove them
            this.timer = window.setInterval(() => {
                this.now(Date.now());
            }, 10000);
        }

        doShowHidden() {
            this._maintenanceNotifications().forEach((notification) => {
                notification.read(false);
            });
        }

        dispose() {
            if (this.timer) {
                window.clearInterval(this.timer);
            }
        }
    }

    function buildError() {
        return div({
            class: 'alert alert-danger',
            dataBind: {
                text: 'error'
            }
        });
    }

    function buildMaintenanceNotification() {
        return div({
            class: 'panel panel-danger',
            style: {
                borderRadius: '0px',
                marginBottom: '0px'
                // position: 'relative'
            }
        }, [
            div({
                class: 'panel-heading',
                style: {
                    position: 'relative'
                }
            }, [
                span({
                    dataBind: {
                        text: '$data.title || "Upcoming System Maintenance"'
                    },
                    style: {
                        fontWeight: 'bold'
                    }
                }),
                button({
                    type: 'button',
                    class: 'close',
                    ariaLabel: 'Close',
                    dataBind: {
                        click: 'function(d,e){d.read(true);}'
                    },
                    style: {
                        fontSize: '80%',
                        position: 'absolute',
                        right: '8px',
                        top: '8px'
                    },
                    title: 'Use this button close the alert; when you reload the browser it will reappear; it will be permanently removed when it expires.'
                }, span({
                    class: 'fa fa-times'
                })),
            ]),
            div({
                class: 'panel-body'
            }, [
                div({
                    style: {
                        display: 'inline-block',
                        verticalAlign: 'top',
                        width: '50%'
                    }
                }, [

                    div({
                        dataBind: {
                            foreach: 'message'
                        }
                    }, p({
                        dataBind: {
                            text: '$data'
                        }
                    }))
                ]),
                div({
                    style: {
                        display: 'inline-block',
                        verticalAlign: 'top',
                        width: '50%',
                        textAlign: 'right'
                    }
                }, [
                    div([
                        span({
                            dataBind: {
                                typedText: {
                                    type: '"date-range"',
                                    format: '"nice-range"',
                                    value: {
                                        startDate: 'startAt',
                                        endDate: 'endAt'
                                    }
                                }
                            }
                        })
                    ]),
                    div([
                        span({
                            dataBind: {
                                component: {
                                    name: CountdownClockComponent.quotedName(),
                                    params: {
                                        startAt: 'startAt',
                                        endAt: 'endAt'
                                    }
                                }
                            }
                        })
                    ])
                ])
            ])
        ]);
    }

    function buildHeader() {
        return div({
            class: 'bg-danger text-danger',
            style: {
                // border: '1px red solid',
                // backgroundColor: 'red',
                // color: '#FFF',
                padding: '10px 15px'
            }
        }, [
            div({
                style: {
                    display: 'inline-block',
                    width: '50%'
                }
            }, span({
                style: {
                    fontWeight: 'bold'
                }
            }, [
                'System',
                gen.plural('maintenanceNotifications().length', ' Alert', ' Alerts')
            ])),
            div({
                style: {
                    display: 'inline-block',
                    width: '50%',
                    textAlign: 'right'
                }
            }, [
                span({
                    dataBind: {
                        text: 'maintenanceNotifications().length'
                    }
                }),
                gen.plural('maintenanceNotifications().length', ' alert', ' alerts'),
                gen.if('hiddenMaintenanceNotificationCount() > 0',
                    [
                        ' (',
                        span({
                            dataBind: {
                                text: 'hiddenMaintenanceNotificationCount()'
                            }
                        }),
                        ' hidden ',
                        button({
                            type: 'button',
                            class: 'btn btn-default btn-xs',
                            dataBind: {
                                click: 'function(...args){$component.doShowHidden.apply($component, args);}'
                            }
                        }, span([
                            'show',
                            gen.plural('hiddenMaintenanceNotificationCount()', ' it', ' them')
                        ])),

                        ')'
                    ])
            ])
        ]);
    }

    function template() {
        // return div('hi from the notification banner');
        return div({
            class: styles.classes.component
        }, [
            gen.if('error()',
                div({
                    class: styles.classes.wrapper
                }, buildError()),
                gen.if('maintenanceNotifications().length > 0',
                    div({
                        class: styles.classes.wrapper
                    }, [
                        buildHeader(),
                        gen.foreach('maintenanceNotifications()',
                            gen.ifnot('read', buildMaintenanceNotification()))
                    ])))
        ]);
    }

    function component() {
        return {
            viewModel: ViewModel,
            template: template(),
            stylesheet: styles.sheet
        };
    }

    return reg.registerComponent(component);
});<|endoftext|>


<commit_before>import { SERVER_API_BASE as serverApiBase } from 'config';

import { get, post, patch, deleteRequest } from './requests';

import {
  TOGGLE_MODAL,
  SET_ASSESSMENTS,
  SHOW_ASSESSMENT_LOADING,
  CLOSE_ASSESSMENT_LOADING,
  SET_ASSESSMENT,
  SET_EDIT_ASSESSMENT_ID,
  SELECT_ASSESSMENT,
  CREATE_ASSESSMENT_ERROR,
  SET_RESPONDENT_TYPES,
} from './types';
import { closeConfirmModal } from './index';

export const toggleEditAssessmentModal = () => {
  return (dispatch) => {
    dispatch({
      type: TOGGLE_MODAL,
      modal: 'editAssessment',
    });
    dispatch({
      type: CREATE_ASSESSMENT_ERROR,
      value: {},
    });
  };
};

export const toggleCreateAssessmentModal = () => {
  return (dispatch) => {
    dispatch({
      type: TOGGLE_MODAL,
      modal: 'createAssessment',
    });
    dispatch({
      type: CREATE_ASSESSMENT_ERROR,
      value: {},
    });
  };
};

export const showAssessmentLoading = () => {
  return {
    type: SHOW_ASSESSMENT_LOADING,
  };
};

export const closeAssessmentLoading = () => {
  return {
    type: CLOSE_ASSESSMENT_LOADING,
  };
};

export const selectAssessment = (id) => {
  return (dispatch, getState) => {
    const state = getState();
    const { selectedAssessments } = state.assessments;
    const exist = selectedAssessments.includes(id);

    if (exist) {
      dispatch({
        type: SELECT_ASSESSMENT,
        value: selectedAssessments.filter((ass) => {
          return ass !== id;
        }),
      });
    } else {
      dispatch({
        type: SELECT_ASSESSMENT,
        value: [...selectedAssessments, id],
      });
    }
  };
};

export const assessmentCreated = (value) => {
  return {
    type: SET_ASSESSMENT,
    value,
  };
};

export const setAssessments = (value) => {
  return {
    type: SET_ASSESSMENTS,
    value,
  };
};

export const getAssessments = (programId) => {
  return (dispatch) => {
    dispatch(showAssessmentLoading());
    const fetchAssessmentsURL = `${serverApiBase}surveys/${programId}/questiongroup/`;
    get(fetchAssessmentsURL).then(({ data }) => {
      dispatch(setAssessments(data.results));
      dispatch(closeAssessmentLoading());
    });
  };
};

export const openAddAssessmentModal = () => {
  return (dispatch) => {
    dispatch({
      type: TOGGLE_MODAL,
      modal: 'createAssessment',
    });
  };
};

export const openEditAssessmentModal = (value) => {
  return (dispatch) => {
    dispatch({
      type: SET_EDIT_ASSESSMENT_ID,
      value,
    });

    dispatch({
      type: TOGGLE_MODAL,
      modal: 'editAssessment',
    });
  };
};

export const saveNewAssessment = (options) => {
  return (dispatch, getState) => {
    // dispatch(showAssessmentLoading());

    const state = getState();
    const programId = state.programs.selectedProgram;
    const createAssessmentURL = `${serverApiBase}surveys/${programId}/questiongroup/`;
    post(createAssessmentURL, options).then((response) => {
      if (response.status === 201) {
        dispatch(assessmentCreated(response.data));
        dispatch({
          type: TOGGLE_MODAL,
          modal: 'createAssessment',
        });
        dispatch({
          type: CREATE_ASSESSMENT_ERROR,
          value: {},
        });
      } else {
        dispatch({
          type: CREATE_ASSESSMENT_ERROR,
          value: response.data,
        });
      }
    });
  };
};

export const saveAssessment = (options) => {
  return (dispatch, getState) => {
    dispatch(showAssessmentLoading());

    const state = getState();
    const { selectedProgram } = state.programs;
    const { editAssessmentId } = state.assessments;
    const editAssessmentURL = `${serverApiBase}surveys/${selectedProgram}/questiongroup/${editAssessmentId}/`;

    patch(editAssessmentURL, options).then(({ data }) => {
      dispatch(assessmentCreated(data));
      dispatch({
        type: TOGGLE_MODAL,
        modal: 'editAssessment',
      });
      dispatch(closeAssessmentLoading());
    });
  };
};

export const deactivateAssessments = () => {
  return (dispatch, getState) => {
    dispatch(showAssessmentLoading());
    dispatch(closeConfirmModal());

    const state = getState();
    const { selectedProgram } = state.programs;
    const { selectedAssessments } = state.assessments;
    const promises = selectedAssessments.map((id) => {
      const url = `${serverApiBase}surveys/${selectedProgram}/questiongroup/${id}/`;
      return patch(url, {
        status: 'IA',
      });
    });

    Promise.all(promises).then(() => {
      dispatch({
        type: SELECT_ASSESSMENT,
        value: [],
      });
      dispatch(getAssessments(selectedProgram));
    });
  };
};

export const deleteAssessments = () => {
  return (dispatch, getState) => {
    dispatch(showAssessmentLoading());
    dispatch(closeConfirmModal());

    const state = getState();
    const { selectedProgram } = state.programs;
    const { selectedAssessments } = state.assessments;
    const promises = selectedAssessments.map((id) => {
      const url = `${serverApiBase}surveys/${selectedProgram}/questiongroup/${id}/`;
      return deleteRequest(url);
    });

    Promise.all(promises).then(() => {
      dispatch(getAssessments(selectedProgram));
      dispatch(closeAssessmentLoading());
    });
  };
};

export const fetchRespondentTypes = () => {
  return (dispatch, getState) => {
    const state = getState();
    const { state_code } = state.profile;

    const url = `${serverApiBase}respondenttype/?state=${state_code}`;
    get(url).then(({ data }) => {
      dispatch({
        type: SET_RESPONDENT_TYPES,
        value: data.results,
      });
    });
  };
};
<commit_msg>fix: tried editing the question_group_type from assessment to perception and got this error<commit_after>import { SERVER_API_BASE as serverApiBase } from 'config';

import { get, post, patch, deleteRequest } from './requests';

import {
  TOGGLE_MODAL,
  SET_ASSESSMENTS,
  SHOW_ASSESSMENT_LOADING,
  CLOSE_ASSESSMENT_LOADING,
  SET_ASSESSMENT,
  SET_EDIT_ASSESSMENT_ID,
  SELECT_ASSESSMENT,
  CREATE_ASSESSMENT_ERROR,
  SET_RESPONDENT_TYPES,
} from './types';
import { closeConfirmModal } from './index';

export const toggleEditAssessmentModal = () => {
  return (dispatch) => {
    dispatch({
      type: TOGGLE_MODAL,
      modal: 'editAssessment',
    });
    dispatch({
      type: CREATE_ASSESSMENT_ERROR,
      value: {},
    });
  };
};

export const toggleCreateAssessmentModal = () => {
  return (dispatch) => {
    dispatch({
      type: TOGGLE_MODAL,
      modal: 'createAssessment',
    });
    dispatch({
      type: CREATE_ASSESSMENT_ERROR,
      value: {},
    });
  };
};

export const showAssessmentLoading = () => {
  return {
    type: SHOW_ASSESSMENT_LOADING,
  };
};

export const closeAssessmentLoading = () => {
  return {
    type: CLOSE_ASSESSMENT_LOADING,
  };
};

export const selectAssessment = (id) => {
  return (dispatch, getState) => {
    const state = getState();
    const { selectedAssessments } = state.assessments;
    const exist = selectedAssessments.includes(id);

    if (exist) {
      dispatch({
        type: SELECT_ASSESSMENT,
        value: selectedAssessments.filter((ass) => {
          return ass !== id;
        }),
      });
    } else {
      dispatch({
        type: SELECT_ASSESSMENT,
        value: [...selectedAssessments, id],
      });
    }
  };
};

export const assessmentCreated = (value) => {
  return {
    type: SET_ASSESSMENT,
    value,
  };
};

export const setAssessments = (value) => {
  return {
    type: SET_ASSESSMENTS,
    value,
  };
};

export const getAssessments = (programId) => {
  return (dispatch) => {
    dispatch(showAssessmentLoading());
    const fetchAssessmentsURL = `${serverApiBase}surveys/${programId}/questiongroup/`;
    get(fetchAssessmentsURL).then(({ data }) => {
      dispatch(setAssessments(data.results));
      dispatch(closeAssessmentLoading());
    });
  };
};

export const openAddAssessmentModal = () => {
  return (dispatch) => {
    dispatch({
      type: TOGGLE_MODAL,
      modal: 'createAssessment',
    });
  };
};

export const openEditAssessmentModal = (value) => {
  return (dispatch) => {
    dispatch({
      type: SET_EDIT_ASSESSMENT_ID,
      value,
    });

    dispatch({
      type: TOGGLE_MODAL,
      modal: 'editAssessment',
    });
  };
};

export const saveNewAssessment = (options) => {
  return (dispatch, getState) => {
    // dispatch(showAssessmentLoading());

    const state = getState();
    const programId = state.programs.selectedProgram;
    const createAssessmentURL = `${serverApiBase}surveys/${programId}/questiongroup/`;
    post(createAssessmentURL, options).then((response) => {
      if (response.status === 201) {
        dispatch(assessmentCreated(response.data));
        dispatch({
          type: TOGGLE_MODAL,
          modal: 'createAssessment',
        });
        dispatch({
          type: CREATE_ASSESSMENT_ERROR,
          value: {},
        });
      } else {
        dispatch({
          type: CREATE_ASSESSMENT_ERROR,
          value: response.data,
        });
      }
    });
  };
};

export const saveAssessment = (options) => {
  return (dispatch, getState) => {
    dispatch(showAssessmentLoading());

    const state = getState();
    const { selectedProgram } = state.programs;
    const { editAssessmentId } = state.assessments;
    const editAssessmentURL = `${serverApiBase}surveys/${selectedProgram}/questiongroup/${editAssessmentId}/`;

    dispatch({
      type: CREATE_ASSESSMENT_ERROR,
      value: {},
    });

    patch(editAssessmentURL, options).then((response) => {
      if (response.status === 200) {
        dispatch(assessmentCreated(response.data));
        dispatch({
          type: TOGGLE_MODAL,
          modal: 'editAssessment',
        });
        dispatch(closeAssessmentLoading());
      } else {
        dispatch({
          type: CREATE_ASSESSMENT_ERROR,
          value: response.data,
        });
      }
    });
  };
};

export const deactivateAssessments = () => {
  return (dispatch, getState) => {
    dispatch(showAssessmentLoading());
    dispatch(closeConfirmModal());

    const state = getState();
    const { selectedProgram } = state.programs;
    const { selectedAssessments } = state.assessments;
    const promises = selectedAssessments.map((id) => {
      const url = `${serverApiBase}surveys/${selectedProgram}/questiongroup/${id}/`;
      return patch(url, {
        status: 'IA',
      });
    });

    Promise.all(promises).then(() => {
      dispatch({
        type: SELECT_ASSESSMENT,
        value: [],
      });
      dispatch(getAssessments(selectedProgram));
    });
  };
};

export const deleteAssessments = () => {
  return (dispatch, getState) => {
    dispatch(showAssessmentLoading());
    dispatch(closeConfirmModal());

    const state = getState();
    const { selectedProgram } = state.programs;
    const { selectedAssessments } = state.assessments;
    const promises = selectedAssessments.map((id) => {
      const url = `${serverApiBase}surveys/${selectedProgram}/questiongroup/${id}/`;
      return deleteRequest(url);
    });

    Promise.all(promises).then(() => {
      dispatch(getAssessments(selectedProgram));
      dispatch(closeAssessmentLoading());
    });
  };
};

export const fetchRespondentTypes = () => {
  return (dispatch, getState) => {
    const state = getState();
    const { state_code } = state.profile;

    const url = `${serverApiBase}respondenttype/?state=${state_code}`;
    get(url).then(({ data }) => {
      dispatch({
        type: SET_RESPONDENT_TYPES,
        value: data.results,
      });
    });
  };
};
<|endoftext|>


<commit_before>define('main', [], function() {
    requirejs.config({
        paths: {<% if (includeModernizr) { %>
            'modernizr': '../bower_components/modernizr/modernizr',<% } %>
            'jquery': '../bower_components/jquery/dist/jquery',<% if (includeUnderscore) { %>
            'underscore': '../bower_components/underscore/underscore',<% } %><% if (cssFramework === 'SASSBootstrap') { %>
            'bootstrap': '../bower_components/sass-bootstrap/dist/js/bootstrap'<% } %>
        },
        shim: {
            'bootstrap': ['jquery']
        }
    });

    Window.name = 'NG_DEFER_BOOTSTRAP!';

    requirejs([
        'jquery',<% if (includeModernizr) { %>
        'modernizr',<% } %><% if (includeUnderscore) { %>
        'underscore',<% } %><% if (cssFramework === 'SASSBootstrap') { %>
        'bootstrap'<% } %>
    ], function($) {
        'use strict';
        /* App Module */
    });
});
<commit_msg>Remove bootstrap window from mainjs<commit_after>define('main', [], function() {
    requirejs.config({
        paths: {<% if (includeModernizr) { %>
            'modernizr': '../bower_components/modernizr/modernizr',<% } %>
            'jquery': '../bower_components/jquery/dist/jquery',<% if (includeUnderscore) { %>
            'underscore': '../bower_components/underscore/underscore',<% } %><% if (cssFramework === 'SASSBootstrap') { %>
            'bootstrap': '../bower_components/sass-bootstrap/dist/js/bootstrap'<% } %>
        },
        shim: {
            'bootstrap': ['jquery']
        }
    });

    requirejs([
        'jquery',<% if (includeModernizr) { %>
        'modernizr',<% } %><% if (includeUnderscore) { %>
        'underscore',<% } %><% if (cssFramework === 'SASSBootstrap') { %>
        'bootstrap'<% } %>
    ], function($) {
        'use strict';

        $(document).ready(function() {
            /* App Module */

        });
    });
});
<|endoftext|>