<commit_before>(function(run) {
	var s = document.createElement('script');
	s.type= 'text/javascript';
	s.textContent = '('+ run.toString() +')()';
	(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(s);
}(function() {

	var NightsWatch = function() {
		var thresholds = {
			too_many_watches: 50,
			warned: []
		};
		var stats = {
			total_watches: 0,
			watches_by_element: {},
		};

		$('.ng-scope').each(function(n, elem) {
			var $elem = $(elem);
			var $scope = $elem.scope();
			var $watchers = $scope.$$watchers;

			if ($watchers) {
				var watchers_len = $watchers.length;
				stats.watches_by_element[elem.nodeName] = stats.watches_by_element[elem.nodeName] || 0;
				stats.total_watches += watchers_len;
				stats.watches_by_element[elem.nodeName] += watchers_len;

				//console.log(stats.watches_by_element[elem.nodeName]);

				if (thresholds.warned.indexOf(elem.nodeName) === -1 && stats.watches_by_element[elem.nodeName] >= thresholds.too_many_watches)  {
					thresholds.warned.push(elem.nodeName);
					var expressions = [];
					angular.forEach($watchers, function(w) {
						if (typeof w.exp === 'function')
							expressions.push([w.exp.toString(), 'see:', w.last]);
						else
							expressions.push(w.exp);
					});
					console.log('Threshold Exceeded:', elem.nodeName, $scope, stats.watches_by_element[elem.nodeName]);
					console.log('In this scope:', watchers_len, $watchers);
					console.log('Expressions:', expressions);
					console.log('This Sample $scope', $elem);
				}
			}
		});

		console.log('Total Watches:', stats.total_watches);
		console.log('Breakdown by nodeName:');

		for (var name in stats.watches_by_element)
			console.log(name, stats.watches_by_element[name]);

	};

	new NightsWatch();

	setTimeout(function() {
		new NightsWatch();
	}, 10000);

}));
<commit_msg>write it properly<commit_after>(function(run) {
	var s = document.createElement('script');
	s.type= 'text/javascript';
	s.textContent = '('+ run.toString() +')()';
	(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(s);
}(function() {

	var NightsWatch = function() {
		this.thresholds = {
			too_many_watches: 50,
			warned: []
		};
		this.stats = {
			total_watches: 0,
			watches_by_element: {},
		};
	};

	NightsWatch.prototype.getDom = function() {
		return $('.ng-scope');
	};

	NightsWatch.prototype.exceedsThreshold = function(key) {
		var exceeds = this.thresholds.warned.indexOf(key) === -1
			&& this.stats.watches_by_element[key] >= this.thresholds.too_many_watches;
		if (exceeds)
			this.thresholds.warned.push(key);
		return exceeds;
	};

	NightsWatch.prototype.analyzeExpressions = function($watchers) {
		var expressions = [];
		angular.forEach($watchers, function(w) {
			if (typeof w.exp === 'function')
				return expressions.push([w.exp.toString(), 'see:', w.last]); // this could be minified :/
			return expressions.push(w.exp);
		});
		return expressions;
	};

	NightsWatch.prototype.scanEach = function() {
		var self = this;
		this.getDom().each(function(n, elem) {
			var $elem = $(elem);
			var $scope = $elem.scope();
			var $watchers = $scope.$$watchers;

			if (!$watchers)
				return true;

			var watchers_len = $watchers.length;
			self.stats.watches_by_element[elem.nodeName] = self.stats.watches_by_element[elem.nodeName] || 0;
			self.stats.total_watches += watchers_len;
			self.stats.watches_by_element[elem.nodeName] += watchers_len;

			if (!self.exceedsThreshold(elem.nodeName))
				return true;

			console.log("Threshold Exceeded:", elem.nodeName, $scope, self.stats.watches_by_element[elem.nodeName]);
			console.log("Sample for this scope:", watchers_len, $watchers, $elem);
			console.log("Expressions for this scope's $watchers:", self.analyzeExpressions($watchers));
		});

		console.log('Total Watches:', this.stats.total_watches);
		console.log('Breakdown by nodeName:');
		for (var name in this.stats.watches_by_element)
			console.log(name, this.stats.watches_by_element[name]);
	};

	window.nwScan = function() {
		new NightsWatch().scanEach();
	};

	// initial check, call it from console whenever you want!
	window.nwScan();

}));
<|endoftext|>


<commit_before>
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    let res = "";
    for (let i = 0; i < params.length; i++) {
        let emoji = bot.emojis.find('name', params[i]);
        if (emoji)
            res = res + " " + emoji.toString();
        else
            res = params[i];
    }
    message.channel.sendMessage(res);
}
/**
 * description of the command
 */
const description = "Converts text to emoji";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<commit_msg>fix bot reference<commit_after>
const bot = require('./../bot');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    let res = "";
    for (let i = 0; i < params.length; i++) {
        let emoji = bot.emojis.find('name', params[i]);
        if (emoji)
            res = res + " " + emoji.toString();
        else
            res = params[i];
    }
    message.channel.sendMessage(res);
}
/**
 * description of the command
 */
const description = "Converts text to emoji";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<|endoftext|>


<commit_before>var listing = require('./lib/listing.js'),
    mapping = require('./lib/mapping.js');

/*----------------------------------------------------------------------------*/

/**
 * Converts `func` of `name` to an auto-curried iteratee-first version. If `name`
 * is an object the methods on it will be converted and the object returned.
 *
 * @param {string} name The name of the function to wrap.
 * @param {Function} func The function to wrap.
 * @returns {Function|Object} Returns the new converted function or object of
 *  converted functions.
 */
function convert(name, func) {
  if (!func) {
    func = name;
    name = null;
  }
  if (func == null) {
    throw new TypeError;
  }
  var isLib = typeof func.VERSION == 'string';

  var _ = isLib ? func : {
    'ary': require('lodash-compat/function/ary'),
    'callback': require('lodash-compat/utility/callback'),
    'curry': require('lodash-compat/function/curry'),
    'each': require('lodash-compat/internal/arrayEach'),
    'rearg': require('lodash-compat/function/rearg')
  };

  var ary = _.ary,
      curry = _.curry,
      each = _.each,
      rearg = _.rearg;

  var wrappers = {
    'callback': function(callback) {
      return function(func, thisArg, argCount) {
        argCount = argCount > 2 ? (argCount - 2) : 1;
        return ary(callback(func, thisArg), argCount);
      };
    },
    'runInContext': function(runInContext) {
      return function(context) {
        return convert(runInContext(context));
      };
    }
  };

  var wrap = function(name, func) {
    var wrapper = wrappers[name];
    if (wrapper) {
      return wrapper(func);
    }
    var result;
    each(listing.caps, function(cap) {
      each(mapping.aryMethodMap[cap], function(otherName) {
        if (name == otherName) {
          result = (cap > 1 && !mapping.skipReargMap[name])
            ? rearg(func, mapping.aryReargMap[cap])
            : func;

          return !(result = curry(ary(result, cap), cap));
        }
      });
      return !result;
    });
    return result || func;
  };

  if (!isLib) {
    return wrap(name, func);
  }
  // Disable custom `_.indexOf` use by these methods.
  _.mixin({
    'difference': require('lodash-compat/array/difference'),
    'includes': require('lodash-compat/collection/includes'),
    'intersection': require('lodash-compat/array/intersection'),
    'omit': require('lodash-compat/object/omit'),
    'pull': require('lodash-compat/array/pull'),
    'union': require('lodash-compat/array/union'),
    'uniq': require('lodash-compat/array/uniq'),
    'without': require('lodash-compat/array/without'),
    'xor': require('lodash-compat/array/xor')
  });

  var pairs = [];
  each(listing.caps, function(cap) {
    // Iterate over methods for the current ary cap.
    each(mapping.aryMethodMap[cap], function(name) {
      var func = _[mapping.keyMap[name] || name];
      if (func) {
        // Wrap the lodash method and its aliases.
        var wrapped = wrap(name, func);
        pairs.push([name, wrapped]);
        each(mapping.aliasMap[name], function(alias) { pairs.push([alias, wrapped]); });
      }
    });
  });

  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  _.callback = wrappers.callback(_.callback);
  _.iteratee = _.callback;
  _.runInContext = wrappers.runInContext(_.runInContext);

  each(pairs, function(pair) { _[pair[0]] = pair[1]; });
  return _;
}

module.exports = convert;
<commit_msg>Fix compose order to catch metadata fast path.<commit_after>var listing = require('./lib/listing.js'),
    mapping = require('./lib/mapping.js');

/*----------------------------------------------------------------------------*/

/**
 * Converts `func` of `name` to an auto-curried iteratee-first version. If `name`
 * is an object the methods on it will be converted and the object returned.
 *
 * @param {string} name The name of the function to wrap.
 * @param {Function} func The function to wrap.
 * @returns {Function|Object} Returns the new converted function or object of
 *  converted functions.
 */
function convert(name, func) {
  if (!func) {
    func = name;
    name = null;
  }
  if (func == null) {
    throw new TypeError;
  }
  var isLib = typeof func.VERSION == 'string';

  var _ = isLib ? func : {
    'ary': require('lodash-compat/function/ary'),
    'callback': require('lodash-compat/utility/callback'),
    'curry': require('lodash-compat/function/curry'),
    'each': require('lodash-compat/internal/arrayEach'),
    'rearg': require('lodash-compat/function/rearg')
  };

  var ary = _.ary,
      curry = _.curry,
      each = _.each,
      rearg = _.rearg;

  var wrappers = {
    'callback': function(callback) {
      return function(func, thisArg, argCount) {
        argCount = argCount > 2 ? (argCount - 2) : 1;
        return ary(callback(func, thisArg), argCount);
      };
    },
    'runInContext': function(runInContext) {
      return function(context) {
        return convert(runInContext(context));
      };
    }
  };

  var wrap = function(name, func) {
    var wrapper = wrappers[name];
    if (wrapper) {
      return wrapper(func);
    }
    var result;
    each(listing.caps, function(cap) {
      each(mapping.aryMethodMap[cap], function(otherName) {
        if (name == otherName) {
          result = ary(func, cap);
          if (cap > 1 && !mapping.skipReargMap[name]) {
            result = rearg(result, mapping.aryReargMap[cap]);
          }
          return !(result = curry(result, cap));
        }
      });
      return !result;
    });
    return result || func;
  };

  if (!isLib) {
    return wrap(name, func);
  }
  // Disable custom `_.indexOf` use by these methods.
  _.mixin({
    'difference': require('lodash-compat/array/difference'),
    'includes': require('lodash-compat/collection/includes'),
    'intersection': require('lodash-compat/array/intersection'),
    'omit': require('lodash-compat/object/omit'),
    'pull': require('lodash-compat/array/pull'),
    'union': require('lodash-compat/array/union'),
    'uniq': require('lodash-compat/array/uniq'),
    'without': require('lodash-compat/array/without'),
    'xor': require('lodash-compat/array/xor')
  });

  var pairs = [];
  each(listing.caps, function(cap) {
    // Iterate over methods for the current ary cap.
    each(mapping.aryMethodMap[cap], function(name) {
      var func = _[mapping.keyMap[name] || name];
      if (func) {
        // Wrap the lodash method and its aliases.
        var wrapped = wrap(name, func);
        pairs.push([name, wrapped]);
        each(mapping.aliasMap[name], function(alias) { pairs.push([alias, wrapped]); });
      }
    });
  });

  // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  _.callback = wrappers.callback(_.callback);
  _.iteratee = _.callback;
  _.runInContext = wrappers.runInContext(_.runInContext);

  each(pairs, function(pair) { _[pair[0]] = pair[1]; });
  return _;
}

module.exports = convert;
<|endoftext|>


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

function validateQueries() {
    var executionPlan = window.queryEditor.getValue();

    if (executionPlan == "") {
        CARBON.showErrorDialog("Query expressions cannot be empty.");
        return;
    }

    new Ajax.Request('../eventprocessor/validate_siddhi_queries_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{executionPlan:executionPlan },
        onSuccess:function (callbackMessage) {
            var resultText = callbackMessage.responseText.trim();
            if (resultText == "success") {
                CARBON.showInfoDialog("Queries are valid!");
                return;
            } else {
                CARBON.showErrorDialog(resultText);
                return;
            }
        }
    });
}

function createImportedStreamDefinition(element) {
    var selectedVal = element.options[element.selectedIndex].value;
    if (selectedVal == 'createStreamDef') {
        new Ajax.Request('../eventstream/popup_create_event_stream_ajaxprocessor.jsp', {
            method:'POST',
            asynchronous:false,
            parameters:{callback:"inflow"},
            onSuccess:function (data) {
                showCustomPopupDialog(data.responseText, "Create Stream Definition", "80%", "", onSuccessCreateInflowStreamDefinition, "90%");
            }
        });
    }
}

function importedStreamDefSelectClick(element) {
    if (element.length <= 1) {
        createImportedStreamDefinition(element);
    }
}

function exportedStreamDefSelectClick(element) {
    if (element.length <= 1) {
        createExportedStreamDefinition(element);
    }
}

function createExportedStreamDefinition(element) {

    var selectedVal = element.options[element.selectedIndex].value;
    if (selectedVal == 'createStreamDef') {

        var executionPlan = window.queryEditor.getValue();

        if (executionPlan == "") {
            CARBON.showErrorDialog("Execution plan cannot be empty.");
            return;
        }

        var valueOf = document.getElementById("exportedStreamValueOf").value;

        if (valueOf == "") {
            CARBON.showErrorDialog("Please fill the 'Value of' field with a valid stream name. It cannot be empty.");
            return;
        }

        var jsonStreamDefinition = "";

        new Ajax.Request('../eventprocessor/export_siddhi_stream_ajaxprocessor.jsp', {
            method:'POST',
            asynchronous:false,
            parameters:{executionPlan:executionPlan, targetStream:valueOf },
            onSuccess:function (data) {
                jsonStreamDefinition = data.responseText;
            }
        });

        if (jsonStreamDefinition) {
            jsonStreamDefinition = jsonStreamDefinition.replace(/^\s+|\s+$/g, '');
            if (jsonStreamDefinition == "") {
                CARBON.showErrorDialog("No matching stream definition can be found for: " + valueOf + ". " +
                                       "Please fill the 'Value of' field with a valid stream name.");
                return;
            }else if(jsonStreamDefinition.trim().startsWith("exception")){
                CARBON.showErrorDialog("Exception when validating the stream, "+jsonStreamDefinition);
                return;
            }
        } else {
            CARBON.showErrorDialog("No matching stream definition can be found for: " + valueOf + ". " +
                                   "Please fill the 'Value of' field with a valid stream name.");
            return;
        }

        new Ajax.Request('../eventstream/popup_create_event_stream_ajaxprocessor.jsp', {
            method:'POST',
            asynchronous:false,
            parameters:{streamDef:jsonStreamDefinition, callback:"outflow"},
            onSuccess:function (data) {
                showCustomPopupDialog(data.responseText, "Create Stream Definition", "80%", "", onSuccessCreateOutflowStreamDefinition, "90%");
            }
        });
    }
}

function addImportedStreamDefinition() {
    var propStreamId = document.getElementById("importedStreamId");
    var propAs = document.getElementById("importedStreamAs");

    var error = "";
    if (propStreamId.value == "" || propStreamId.value == "createStreamDef") {
        error = "Invalid Stream ID selected.\n";
    }

    if (error != "") {
        CARBON.showErrorDialog(error);
        return;
    }

    if (propAs.value.trim() == "") {
        propAs.value = propStreamId.value.trim().split(':')[0];
        propAs.value = propAs.value.replace(/\./g, '_');
    }

    new Ajax.Request('../eventprocessor/get_stream_definition_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{streamId:propStreamId.value, streamAs:propAs.value },
        onSuccess:function (eventStreamDefinition) {
            var definitions = eventStreamDefinition.responseText.trim().split("|=");
            var streamId = definitions[0].trim();
            var streamAs = definitions[1].trim();
            var streamDefinition = definitions[3].trim();

            var currentExecutionPlan = window.queryEditor.getValue();
            var executionPlanHeader = "";
            var executionPlanBody = "";
            if(currentExecutionPlan != "") {
                var linesArray = currentExecutionPlan.split(SIDDHI_LINE_BREAK_CHARACTER);
                var bodyBeginIndex = -1;
                for (var i = 0; i < linesArray.length ; i++){
                    var line = linesArray[i];
                    if(line.match(REGEX_LINE_STARTING_WITH_PLAN) != null
                        || line.match(REGEX_LINE_STARTING_WITH_SINGLE_LINE_COMMENT) != null
                        || line.match(REGEX_LINE_STARTING_WITH_MULTI_LINE_COMMENT) != null
                        || line == ""){
                        executionPlanHeader += line + SIDDHI_LINE_BREAK;
                    } else {
                        bodyBeginIndex = i;
                        break;
                    }
                }
                if(bodyBeginIndex != -1){
                    for (var i = bodyBeginIndex; i < linesArray.length ; i++){
                        var line = linesArray[i];
                        executionPlanBody += SIDDHI_LINE_BREAK + line;
                    }
                }
            }
            var importStatement = ANNOTATION_TOKEN_AT +
                ANNOTATION_IMPORT +
                ANNOTATION_TOKEN_OPENING_BRACKET +
                SIDDHI_SINGLE_QUOTE + streamId + SIDDHI_SINGLE_QUOTE +
                ANNOTATION_TOKEN_CLOSING_BRACKET +
                SIDDHI_LINE_BREAK +
                SIDDHI_LITERAL_DEFINE_STREAM + SIDDHI_SPACE_LITERAL + streamAs + SIDDHI_SPACE_LITERAL +
                ANNOTATION_TOKEN_OPENING_BRACKET +
                streamDefinition +
                ANNOTATION_TOKEN_CLOSING_BRACKET +
                SIDDHI_STATEMENT_DELIMETER;
            window.queryEditor.setValue(executionPlanHeader + importStatement + SIDDHI_LINE_BREAK + executionPlanBody);
            window.queryEditor.save();
        }
    });
    propAs.value = "";
}

function addExportedStreamDefinition() {
    var propStreamId = document.getElementById("exportedStreamId");
    var propValueOf = document.getElementById("exportedStreamValueOf");
    var streamDefinitionsTable = document.getElementById("streamDefinitionsTable");

    var error = "";

    if (propStreamId.value == "" || propStreamId.value == "createStreamDef") {
        error = "Invalid Stream ID selected.\n";
    }

    if (propValueOf.value == "") {
        error = "Value Of field is empty.\n";
    }

    if (error != "") {
        CARBON.showErrorDialog(error);
        return;
    }

    new Ajax.Request('../eventprocessor/get_stream_definition_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{streamId:propStreamId.value, streamAs:propValueOf.value },
        onSuccess:function (eventStreamDefinition) {
            var definitions = eventStreamDefinition.responseText.trim().split("|=");
            var streamId = definitions[0].trim();
            var streamAs = definitions[1].trim();
            var streamDefinition = definitions[3].trim();

            var currentExecutionPlan = window.queryEditor.getValue();
            var executionPlanHeader = "";
            var executionPlanBody = "";

            if(currentExecutionPlan != "") {
                var linesArray = currentExecutionPlan.split(SIDDHI_LINE_BREAK_CHARACTER);
                var bodyBeginIndex = -1;
                for (var i = 0; i < linesArray.length ; i++){
                    var line = linesArray[i];
                    if(line.match(REGEX_LINE_STARTING_WITH_PLAN) != null
                        || line.match(REGEX_LINE_STARTING_WITH_SINGLE_LINE_COMMENT) != null
                        || line.match(REGEX_LINE_STARTING_WITH_MULTI_LINE_COMMENT) != null
                        || line == ""
                        || line.match(REGEX_LINE_STARTING_WITH_IMPORT_STATEMENT) != null){
                        if(line.match(REGEX_LINE_STARTING_WITH_IMPORT_STATEMENT) != null){
                            executionPlanHeader += line + SIDDHI_LINE_BREAK;
                            executionPlanHeader += linesArray[++i] + SIDDHI_LINE_BREAK;
                        } else {
                            executionPlanHeader += line + SIDDHI_LINE_BREAK;
                        }
                    } else {
                        bodyBeginIndex = i;
                        break;
                    }
                }
                if(bodyBeginIndex != -1){
                    for (var i = bodyBeginIndex; i < linesArray.length ; i++){
                        var line = linesArray[i];
                        executionPlanBody += SIDDHI_LINE_BREAK + line;
                    }
                }
            }
            var exportStatement = ANNOTATION_TOKEN_AT + ANNOTATION_EXPORT + ANNOTATION_TOKEN_OPENING_BRACKET +
                SIDDHI_SINGLE_QUOTE + streamId + SIDDHI_SINGLE_QUOTE + ANNOTATION_TOKEN_CLOSING_BRACKET +
                SIDDHI_LINE_BREAK + SIDDHI_LITERAL_DEFINE_STREAM + SIDDHI_SPACE_LITERAL + streamAs + SIDDHI_SPACE_LITERAL +
                ANNOTATION_TOKEN_OPENING_BRACKET + streamDefinition + ANNOTATION_TOKEN_CLOSING_BRACKET + SIDDHI_STATEMENT_DELIMETER;
            window.queryEditor.setValue(executionPlanHeader + exportStatement + SIDDHI_LINE_BREAK + executionPlanBody);
            window.queryEditor.save();
        }
    });
    propValueOf.value = "";
}

function addExecutionPlan(form) {
    // query expressions can be empty for pass thru execution plans...?
    var executionPlan = window.queryEditor.getValue();
    if (executionPlan == "") {
        CARBON.showErrorDialog("Query expressions cannot be empty.");
        return;
    }

    new Ajax.Request('../eventprocessor/validate_siddhi_queries_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{executionPlan:executionPlan },
        onSuccess:function (callbackMessage) {
            var resultText = callbackMessage.responseText.trim();
            if (resultText == "success") {
                makeAsyncCallToCreateExecutionPlan(form, executionPlan);
            } else {
                CARBON.showErrorDialog(resultText);
                return;
            }
        }
    });
}

function getDuplicatedStreams() {
    var exportedStreamsTable = document.getElementById("exportedStreamsTable");
    var StreamTable = document.getElementById("streamDefinitionsTable");

    var importedStreamCount = 0;
    var exportedStreamCount = 0;
    var importedStreamArray = new Array();
    var exportedStreamArray = new Array();

    for (var i = 0; i < StreamTable.rows.length; i++) {
        var row = StreamTable.rows[i];
        if (row.getAttribute("streamType") == "imported") {
            importedStreamArray[importedStreamCount] = row.getAttribute("streamId");
            importedStreamCount++;
        } else if (row.getAttribute("streamType") == "exported") {
            exportedStreamArray[exportedStreamCount] = row.getAttribute("streamId");
            exportedStreamCount++;
        }
    }

    var reusedStreams = "";

    if (exportedStreamCount == 0) {
        return "no-export-streams";
    }
    else if (importedStreamCount > 0 && exportedStreamCount > 0) {
        for (var i = 0; i < exportedStreamCount; i++) {
            var exportedStreamId = exportedStreamArray[i];
            for (var j = 0; j < importedStreamCount; j++) {
                var importedStreamId = importedStreamArray[j];
                if (importedStreamId == exportedStreamId) {
                    if (reusedStreams != "") {
                        reusedStreams = reusedStreams + "\n"
                    }
                    reusedStreams = reusedStreams + importedStreamId;
                }
            }
        }
    }
    return reusedStreams;

}

function makeAsyncCallToCreateExecutionPlan(form, queryExpressions) {
    new Ajax.Request('../eventprocessor/add_execution_plan_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{queryExpressions:queryExpressions },
        onSuccess:function (transport) {
            if ("true" == transport.responseText.trim()) {
                form.submit();
            } else {
                CARBON.showErrorDialog("Failed to add execution plan, Exception: " + transport.responseText.trim());
            }
        }
    });
}

function loadUIElements(uiId) {
    var uiElementTd = document.getElementById("uiElement");
    uiElementTd.innerHTML = "";

    jQuery.ajax({
        type:"POST",
        url:"../eventexecutionplanwizard/get_ui_ajaxprocessor.jsp?uiId=" + uiId + "",
        data:{},
        contentType:"text/html; charset=utf-8",
        dataType:"text",
        async:false,
        success:function (ui_content) {
            if (ui_content != null) {
                jQuery(uiElementTd).html(ui_content);

                if (uiId == 'builder') {
                    var innertTD = document.getElementById('addEventAdaptorTD');
                    jQuery(innertTD).html(' Add New Input Event Adaptor ')
                }

                else if (uiId == 'formatter') {
                    var innertTD = document.getElementById('addOutputEventAdaptorTD');
                    jQuery(innertTD).html(' Add New Out Event Adaptor ')
                }

                else if (uiId == 'processor') {
                    var innertTD = document.getElementById('addEventStreamTD');
                    jQuery(innertTD).html(' Add New Event Stream ')
                }

            }
        }
    });
}

<commit_msg>Removing creation of event builder pop-up<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function validateQueries() {
    var executionPlan = window.queryEditor.getValue();

    if (executionPlan == "") {
        CARBON.showErrorDialog("Query expressions cannot be empty.");
        return;
    }

    new Ajax.Request('../eventprocessor/validate_siddhi_queries_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{executionPlan:executionPlan },
        onSuccess:function (callbackMessage) {
            var resultText = callbackMessage.responseText.trim();
            if (resultText == "success") {
                CARBON.showInfoDialog("Queries are valid!");
                return;
            } else {
                CARBON.showErrorDialog(resultText);
                return;
            }
        }
    });
}

function createImportedStreamDefinition(element) {
    var selectedVal = element.options[element.selectedIndex].value;
    if (selectedVal == 'createStreamDef') {
        new Ajax.Request('../eventstream/popup_create_event_stream_ajaxprocessor.jsp', {
            method:'POST',
            asynchronous:false,
            parameters:{callback:"inflow"},
            onSuccess:function (data) {
                //showCustomPopupDialog(data.responseText, "Create Stream Definition", "80%", "", onSuccessCreateInflowStreamDefinition, "90%");
                showCustomPopupDialog(data.responseText, "Create Stream Definition", "80%", "", "", "90%");
            }
        });
    }
}

function importedStreamDefSelectClick(element) {
    if (element.length <= 1) {
        createImportedStreamDefinition(element);
    }
}

function exportedStreamDefSelectClick(element) {
    if (element.length <= 1) {
        createExportedStreamDefinition(element);
    }
}

function createExportedStreamDefinition(element) {

    var selectedVal = element.options[element.selectedIndex].value;
    if (selectedVal == 'createStreamDef') {

        var executionPlan = window.queryEditor.getValue();

        if (executionPlan == "") {
            CARBON.showErrorDialog("Execution plan cannot be empty.");
            return;
        }

        var valueOf = document.getElementById("exportedStreamValueOf").value;

        if (valueOf == "") {
            CARBON.showErrorDialog("Please fill the 'Value of' field with a valid stream name. It cannot be empty.");
            return;
        }

        var jsonStreamDefinition = "";

        new Ajax.Request('../eventprocessor/export_siddhi_stream_ajaxprocessor.jsp', {
            method:'POST',
            asynchronous:false,
            parameters:{executionPlan:executionPlan, targetStream:valueOf },
            onSuccess:function (data) {
                jsonStreamDefinition = data.responseText;
            }
        });

        if (jsonStreamDefinition) {
            jsonStreamDefinition = jsonStreamDefinition.replace(/^\s+|\s+$/g, '');
            if (jsonStreamDefinition == "") {
                CARBON.showErrorDialog("No matching stream definition can be found for: " + valueOf + ". " +
                                       "Please fill the 'Value of' field with a valid stream name.");
                return;
            }else if(jsonStreamDefinition.trim().startsWith("exception")){
                CARBON.showErrorDialog("Exception when validating the stream, "+jsonStreamDefinition);
                return;
            }
        } else {
            CARBON.showErrorDialog("No matching stream definition can be found for: " + valueOf + ". " +
                                   "Please fill the 'Value of' field with a valid stream name.");
            return;
        }

        new Ajax.Request('../eventstream/popup_create_event_stream_ajaxprocessor.jsp', {
            method:'POST',
            asynchronous:false,
            parameters:{streamDef:jsonStreamDefinition, callback:"outflow"},
            onSuccess:function (data) {
                //showCustomPopupDialog(data.responseText, "Create Stream Definition", "80%", "", onSuccessCreateOutflowStreamDefinition, "90%");
                showCustomPopupDialog(data.responseText, "Create Stream Definition", "80%", "", "", "90%");
            }
        });
    }
}

function addImportedStreamDefinition() {
    var propStreamId = document.getElementById("importedStreamId");
    var propAs = document.getElementById("importedStreamAs");

    var error = "";
    if (propStreamId.value == "" || propStreamId.value == "createStreamDef") {
        error = "Invalid Stream ID selected.\n";
    }

    if (error != "") {
        CARBON.showErrorDialog(error);
        return;
    }

    if (propAs.value.trim() == "") {
        propAs.value = propStreamId.value.trim().split(':')[0];
        propAs.value = propAs.value.replace(/\./g, '_');
    }

    new Ajax.Request('../eventprocessor/get_stream_definition_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{streamId:propStreamId.value, streamAs:propAs.value },
        onSuccess:function (eventStreamDefinition) {
            var definitions = eventStreamDefinition.responseText.trim().split("|=");
            var streamId = definitions[0].trim();
            var streamAs = definitions[1].trim();
            var streamDefinition = definitions[3].trim();

            var currentExecutionPlan = window.queryEditor.getValue();
            var executionPlanHeader = "";
            var executionPlanBody = "";
            if(currentExecutionPlan != "") {
                var linesArray = currentExecutionPlan.split(SIDDHI_LINE_BREAK_CHARACTER);
                var bodyBeginIndex = -1;
                for (var i = 0; i < linesArray.length ; i++){
                    var line = linesArray[i];
                    if(line.match(REGEX_LINE_STARTING_WITH_PLAN) != null
                        || line.match(REGEX_LINE_STARTING_WITH_SINGLE_LINE_COMMENT) != null
                        || line.match(REGEX_LINE_STARTING_WITH_MULTI_LINE_COMMENT) != null
                        || line == ""){
                        executionPlanHeader += line + SIDDHI_LINE_BREAK;
                    } else {
                        bodyBeginIndex = i;
                        break;
                    }
                }
                if(bodyBeginIndex != -1){
                    for (var i = bodyBeginIndex; i < linesArray.length ; i++){
                        var line = linesArray[i];
                        executionPlanBody += SIDDHI_LINE_BREAK + line;
                    }
                }
            }
            var importStatement = ANNOTATION_TOKEN_AT +
                ANNOTATION_IMPORT +
                ANNOTATION_TOKEN_OPENING_BRACKET +
                SIDDHI_SINGLE_QUOTE + streamId + SIDDHI_SINGLE_QUOTE +
                ANNOTATION_TOKEN_CLOSING_BRACKET +
                SIDDHI_LINE_BREAK +
                SIDDHI_LITERAL_DEFINE_STREAM + SIDDHI_SPACE_LITERAL + streamAs + SIDDHI_SPACE_LITERAL +
                ANNOTATION_TOKEN_OPENING_BRACKET +
                streamDefinition +
                ANNOTATION_TOKEN_CLOSING_BRACKET +
                SIDDHI_STATEMENT_DELIMETER;
            window.queryEditor.setValue(executionPlanHeader + importStatement + SIDDHI_LINE_BREAK + executionPlanBody);
            window.queryEditor.save();
        }
    });
    propAs.value = "";
}

function addExportedStreamDefinition() {
    var propStreamId = document.getElementById("exportedStreamId");
    var propValueOf = document.getElementById("exportedStreamValueOf");
    var streamDefinitionsTable = document.getElementById("streamDefinitionsTable");

    var error = "";

    if (propStreamId.value == "" || propStreamId.value == "createStreamDef") {
        error = "Invalid Stream ID selected.\n";
    }

    if (propValueOf.value == "") {
        error = "Value Of field is empty.\n";
    }

    if (error != "") {
        CARBON.showErrorDialog(error);
        return;
    }

    new Ajax.Request('../eventprocessor/get_stream_definition_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{streamId:propStreamId.value, streamAs:propValueOf.value },
        onSuccess:function (eventStreamDefinition) {
            var definitions = eventStreamDefinition.responseText.trim().split("|=");
            var streamId = definitions[0].trim();
            var streamAs = definitions[1].trim();
            var streamDefinition = definitions[3].trim();

            var currentExecutionPlan = window.queryEditor.getValue();
            var executionPlanHeader = "";
            var executionPlanBody = "";

            if(currentExecutionPlan != "") {
                var linesArray = currentExecutionPlan.split(SIDDHI_LINE_BREAK_CHARACTER);
                var bodyBeginIndex = -1;
                for (var i = 0; i < linesArray.length ; i++){
                    var line = linesArray[i];
                    if(line.match(REGEX_LINE_STARTING_WITH_PLAN) != null
                        || line.match(REGEX_LINE_STARTING_WITH_SINGLE_LINE_COMMENT) != null
                        || line.match(REGEX_LINE_STARTING_WITH_MULTI_LINE_COMMENT) != null
                        || line == ""
                        || line.match(REGEX_LINE_STARTING_WITH_IMPORT_STATEMENT) != null){
                        if(line.match(REGEX_LINE_STARTING_WITH_IMPORT_STATEMENT) != null){
                            executionPlanHeader += line + SIDDHI_LINE_BREAK;
                            executionPlanHeader += linesArray[++i] + SIDDHI_LINE_BREAK;
                        } else {
                            executionPlanHeader += line + SIDDHI_LINE_BREAK;
                        }
                    } else {
                        bodyBeginIndex = i;
                        break;
                    }
                }
                if(bodyBeginIndex != -1){
                    for (var i = bodyBeginIndex; i < linesArray.length ; i++){
                        var line = linesArray[i];
                        executionPlanBody += SIDDHI_LINE_BREAK + line;
                    }
                }
            }
            var exportStatement = ANNOTATION_TOKEN_AT + ANNOTATION_EXPORT + ANNOTATION_TOKEN_OPENING_BRACKET +
                SIDDHI_SINGLE_QUOTE + streamId + SIDDHI_SINGLE_QUOTE + ANNOTATION_TOKEN_CLOSING_BRACKET +
                SIDDHI_LINE_BREAK + SIDDHI_LITERAL_DEFINE_STREAM + SIDDHI_SPACE_LITERAL + streamAs + SIDDHI_SPACE_LITERAL +
                ANNOTATION_TOKEN_OPENING_BRACKET + streamDefinition + ANNOTATION_TOKEN_CLOSING_BRACKET + SIDDHI_STATEMENT_DELIMETER;
            window.queryEditor.setValue(executionPlanHeader + exportStatement + SIDDHI_LINE_BREAK + executionPlanBody);
            window.queryEditor.save();
        }
    });
    propValueOf.value = "";
}

function addExecutionPlan(form) {
    // query expressions can be empty for pass thru execution plans...?
    var executionPlan = window.queryEditor.getValue();
    if (executionPlan == "") {
        CARBON.showErrorDialog("Query expressions cannot be empty.");
        return;
    }

    new Ajax.Request('../eventprocessor/validate_siddhi_queries_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{executionPlan:executionPlan },
        onSuccess:function (callbackMessage) {
            var resultText = callbackMessage.responseText.trim();
            if (resultText == "success") {
                makeAsyncCallToCreateExecutionPlan(form, executionPlan);
            } else {
                CARBON.showErrorDialog(resultText);
                return;
            }
        }
    });
}

function getDuplicatedStreams() {
    var exportedStreamsTable = document.getElementById("exportedStreamsTable");
    var StreamTable = document.getElementById("streamDefinitionsTable");

    var importedStreamCount = 0;
    var exportedStreamCount = 0;
    var importedStreamArray = new Array();
    var exportedStreamArray = new Array();

    for (var i = 0; i < StreamTable.rows.length; i++) {
        var row = StreamTable.rows[i];
        if (row.getAttribute("streamType") == "imported") {
            importedStreamArray[importedStreamCount] = row.getAttribute("streamId");
            importedStreamCount++;
        } else if (row.getAttribute("streamType") == "exported") {
            exportedStreamArray[exportedStreamCount] = row.getAttribute("streamId");
            exportedStreamCount++;
        }
    }

    var reusedStreams = "";

    if (exportedStreamCount == 0) {
        return "no-export-streams";
    }
    else if (importedStreamCount > 0 && exportedStreamCount > 0) {
        for (var i = 0; i < exportedStreamCount; i++) {
            var exportedStreamId = exportedStreamArray[i];
            for (var j = 0; j < importedStreamCount; j++) {
                var importedStreamId = importedStreamArray[j];
                if (importedStreamId == exportedStreamId) {
                    if (reusedStreams != "") {
                        reusedStreams = reusedStreams + "\n"
                    }
                    reusedStreams = reusedStreams + importedStreamId;
                }
            }
        }
    }
    return reusedStreams;

}

function makeAsyncCallToCreateExecutionPlan(form, queryExpressions) {
    new Ajax.Request('../eventprocessor/add_execution_plan_ajaxprocessor.jsp', {
        method:'POST',
        asynchronous:false,
        parameters:{queryExpressions:queryExpressions },
        onSuccess:function (transport) {
            if ("true" == transport.responseText.trim()) {
                form.submit();
            } else {
                CARBON.showErrorDialog("Failed to add execution plan, Exception: " + transport.responseText.trim());
            }
        }
    });
}

function loadUIElements(uiId) {
    var uiElementTd = document.getElementById("uiElement");
    uiElementTd.innerHTML = "";

    jQuery.ajax({
        type:"POST",
        url:"../eventexecutionplanwizard/get_ui_ajaxprocessor.jsp?uiId=" + uiId + "",
        data:{},
        contentType:"text/html; charset=utf-8",
        dataType:"text",
        async:false,
        success:function (ui_content) {
            if (ui_content != null) {
                jQuery(uiElementTd).html(ui_content);

                if (uiId == 'builder') {
                    var innertTD = document.getElementById('addEventAdaptorTD');
                    jQuery(innertTD).html(' Add New Input Event Adaptor ')
                }

                else if (uiId == 'formatter') {
                    var innertTD = document.getElementById('addOutputEventAdaptorTD');
                    jQuery(innertTD).html(' Add New Out Event Adaptor ')
                }

                else if (uiId == 'processor') {
                    var innertTD = document.getElementById('addEventStreamTD');
                    jQuery(innertTD).html(' Add New Event Stream ')
                }

            }
        }
    });
}

<|endoftext|>


<commit_before>sb.include('String.prototype.stripHTML');
/**
@Name: sb.browser.pulsingTitle
@Description: pulses document title between default and custom to grab user attention
@Param string title The custom title to pulse
@Param integer interval The frequency to pulse at in ms
@Example:
var p = new sb.browser.pulsingTitle('dancing');
//stop pulsing
p.stop();
*/
sb.browser.pulsingTitle = function(title, interval){
	this.title = title || 'pulsing';
	this.interval = interval || 2000;

	if(sb.browser.pulsingTitle.instances > 0){
		return sb.browser.pulseTitle.instance;
	}

	this.origTitle = document.title;

	sb.browser.pulsingTitle.instance = this;
	if(this.title){
		this.pulse(this.title);
	}

};

sb.browser.pulsingTitle.prototype = {
	/**
	@Name: sb.browser.pulsingTitle.prototype.stop()
	@Description: stops pulsing
	@Example:
	var p = new sb.browser.pulsingTitle('dancing');
	//stop pulsing
	p.stop();
	*/
	stop : function(){
		document.title = this.origTitle;
		if(this.isPulsing){
			window.clearInterval(this.isPulsing);
		}
		return this;
	},

	/**
	@Name: sb.browser.pulsingTitle.prototype.stop()
	@Description: starts pulsing, does this by default when constructor is used, can be used to restart
	@Example:
	var p = new sb.browser.pulsingTitle('dancing');
	//stop pulsing
	p.stop();
	//start pulsing again
	p.pulse();
	*/
	pulse : function(title){
		var self = this;
		this.stop();
		if(title == false){
			intra.resetTitle();
			return;
		}
		var x =0;

		this.isPulsing = window.setInterval(function(){
			if(x % 2 == 0){
				document.title = title;
			} else {
				document.title = self.origTitle;
			}
			x++;

		}, this.interval);
		return this;
	}
};<commit_msg>pulsing title actually returns the single instance now instead of creating a pulsing nightmare<commit_after>sb.include('String.prototype.stripHTML');
/**
@Name: sb.browser.pulsingTitle
@Description: pulses document title between default and custom to grab user attention
@Param string title The custom title to pulse
@Param integer interval The frequency to pulse at in ms
@Example:
var p = new sb.browser.pulsingTitle('dancing');
//stop pulsing
p.stop();
*/
sb.browser.pulsingTitle = function(title, interval){

	if(!sb.browser.pulsingTitle.instance){
		this.origTitle = document.title;
		this.interval = interval || 2000;
		sb.browser.pulsingTitle.instance = this;
	}

	sb.browser.pulsingTitle.instance.title = title || 'pulsing';
	sb.browser.pulsingTitle.instance.interval = interval || 2000;

	sb.browser.pulsingTitle.instance.pulse(sb.browser.pulsingTitle.instance.title);
	return sb.browser.pulsingTitle.instance;

};

sb.browser.pulsingTitle.prototype = {
	/**
	@Name: sb.browser.pulsingTitle.prototype.stop()
	@Description: stops pulsing
	@Example:
	var p = new sb.browser.pulsingTitle('dancing');
	//stop pulsing
	p.stop();
	*/
	stop : function(){
		document.title = this.origTitle;
		if(this.isPulsing){
			window.clearInterval(this.isPulsing);
		}
		return this;
	},

	/**
	@Name: sb.browser.pulsingTitle.prototype.stop()
	@Description: starts pulsing, does this by default when constructor is used, can be used to restart
	@Example:
	var p = new sb.browser.pulsingTitle('dancing');
	//stop pulsing
	p.stop();
	//start pulsing again
	p.pulse();
	*/
	pulse : function(title){
		var self = this;
		this.stop();
		if(title == false){
			intra.resetTitle();
			return;
		}
		var x =0;

		this.isPulsing = window.setInterval(function(){
			if(x % 2 == 0){
				document.title = title;
			} else {
				document.title = self.origTitle;
			}
			x++;

		}, this.interval);
		return this;
	}
};<|endoftext|>


<commit_before>module.exports = "BOTTOKEN_HERE";
<commit_msg>Delete bottoken.js<commit_after><|endoftext|>


<commit_before>(jQuery)(function($){

    var currentMenu = $("#mainMenu .active").text();

    $("#currenttMenu").text(currentMenu);

    // Gestion des sous-menus
    $("#mainMenu .menu > a").on("click", function(e){
        if($(this).siblings(".submenu").length !== 0) {
            e.preventDefault();
        }

        var $parent = $(this).parent();

        if($parent.hasClass("open")) {
            $parent.removeClass("open");
        }
        else {
            $("#mainMenu .open").removeClass("open");
            $parent.addClass("open");
        }
    });

    // Mise en place des tooltips custom
    $(document).tooltip();

    // Fermeture de la liste des erreurs
    $("#closeError").on("click", function(){
        $(this).parent().fadeOut(350, function(){
            $(this).remove();
        });
    });
});<commit_msg>Ouverture auto du menu sélectionné<commit_after>(jQuery)(function($){

    // Gestion des sous-menus
    $("#mainMenu .menu > a").on("click", function(e){
        if($(this).siblings(".submenu").length !== 0) {
            e.preventDefault();
        }

        var $parent = $(this).parent();

        if($parent.hasClass("open")) {
            $parent.removeClass("open");
        }
        else {
            $("#mainMenu .open").removeClass("open");
            $parent.addClass("open");
        }
    });

    // Mise en place des tooltips custom
    $(document).tooltip();

    // Fermeture de la liste des erreurs
    $("#closeError").on("click", function(){
        $(this).parent().fadeOut(350, function(){
            $(this).remove();
        });
    });

    var $currentMenu = $("#mainMenu .active");
    if($currentMenu.parent().hasClass("submenu")) {
        $currentMenu.parents(".menu").find("a").click();
    }
});<|endoftext|>


<commit_before>const compileSass = require('broccoli-sass');
const mergeTrees = require('broccoli-merge-trees');
const esTranspiler = require('broccoli-babel-transpiler');
const pickFiles = require('broccoli-static-compiler');

const sourceDir = 'src';

const scripts = esTranspiler(sourceDir, {
  compact: true
});

const statics = pickFiles(sourceDir, {
  srcDir: '/',
  files: ['*.html'],
  destDir: '/'
});

const styles = compileSass([sourceDir], 'styles.scss', 'assets/styles.css', {
  outputStyle: 'compressed'
});

module.exports = mergeTrees([styles, scripts, statics], {
  overwrite: true
});
<commit_msg>Don't move styles into subfolder<commit_after>const compileSass = require('broccoli-sass');
const mergeTrees = require('broccoli-merge-trees');
const esTranspiler = require('broccoli-babel-transpiler');
const pickFiles = require('broccoli-static-compiler');

const sourceDir = 'src';

const scripts = esTranspiler(sourceDir, {
  compact: true
});

const statics = pickFiles(sourceDir, {
  srcDir: '/',
  files: ['*.html'],
  destDir: '/'
});

const styles = compileSass([sourceDir], 'styles.scss', 'styles.css', {
  outputStyle: 'compressed'
});

module.exports = mergeTrees([styles, scripts, statics], {
  overwrite: true
});
<|endoftext|>


<commit_before>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	$C = require('collection.js'),
	config = require('config'),
	MiniCssExtractPlugin = require('mini-css-extract-plugin');

const
	{resolve} = require('@pzlr/build-core'),
	{output, assetsOutput, assetsJSON, hash, inherit, depsRgxpStr} = include('build/build.webpack');

const
	path = require('upath'),
	build = include('build/entities.webpack'),
	depsRgxp = new RegExp(`(?:^|/)node_modules/(?:(?!${depsRgxpStr}).)*?(?:/|$)`);

const
	snakeskin = config.snakeskin(),
	typescript = config.typescript(),
	monic = config.monic(),
	imageOpts = config.imageOpts();

const fileLoaderOpts = {
	name: path.basename(assetsOutput),
	outputPath: path.dirname(assetsOutput),
	limit: config.webpack.dataURILimit()
};

/**
 * Returns parameters for webpack.module
 *
 * @param {(number|string)} buildId - build id
 * @param {!Map} plugins - list of plugins
 * @returns {!Promise<Object>}
 */
module.exports = async function ({buildId, plugins}) {
	const
		graph = await build,
		loaders = {rules: new Map()};

	if (buildId === build.RUNTIME) {
		loaders.rules.set('ts', {
			test: /^(?:(?!\/workers\/).)*(?:\.d)?\.ts$/,
			exclude: depsRgxp,
			use: [
				{
					loader: 'ts',
					options: typescript.client
				},

				{
					loader: 'proxy',
					options: {
						modules: [resolve.blockSync(), resolve.sourceDir, ...resolve.rootDependencies]
					}
				},

				{
					loader: 'monic',
					options: inherit(monic.typescript, {
						replacers: [
							include('build/context.replacer'),
							include('build/super.replacer'),
							include('build/ts-import.replacer'),
							include('build/typograf.replacer'),
							include('build/prelude.replacer')
						]
					})
				}
			]
		});

		loaders.rules.set('ts.workers', {
			test: /\/workers\/.*?(?:\.d)?\.ts$/,
			exclude: depsRgxp,
			use: [
				{
					loader: 'ts',
					options: typescript.worker
				},

				{
					loader: 'monic',
					options: inherit(monic.typescript, {
						replacers: [
							include('build/context.replacer'),
							include('build/super.replacer'),
							include('build/ts-import.replacer'),
							include('build/typograf.replacer'),
							include('build/prelude.replacer')
						]
					})
				}
			]
		});

		loaders.rules.set('js', {
			test: /\.js$/,
			exclude: depsRgxp,
			use: [{
				loader: 'monic',
				options: inherit(monic.javascript, {
					replacers: [
						include('build/context.replacer'),
						include('build/super.replacer'),
						include('build/typograf.replacer'),
						include('build/prelude.replacer')
					]
				})
			}]
		});

	} else {
		plugins.set('extractCSS', new MiniCssExtractPlugin({
			filename: `${hash(output, true)}.css`,
			chunkFilename: '[id].css'
		}));

		const
			autoprefixer = config.autoprefixer(),
			postcss = config.postcss();

		loaders.rules.set('styl', {
			test: /\.styl$/,
			use: [].concat(
				MiniCssExtractPlugin.loader,

				{
					loader: 'fast-css',
					options: Object.reject(config.css(), ['minimize'])
				},

				isProd || $C(postcss).length() || $C(autoprefixer).length() ? {
					loader: 'postcss',
					options: inherit(postcss, {
						plugins: [require('autoprefixer')(autoprefixer)]
					})
				} : [],

				{
					loader: 'stylus',
					options: inherit(config.stylus(), {
						use: include('build/stylus')
					})
				},

				{
					loader: 'monic',
					options: inherit(monic.stylus, {
						replacers: [
							require('@pzlr/stylus-inheritance')({resolveImports: true})
						]
					})
				}
			)
		});

		loaders.rules.set('ess', {
			test: /\.ess$/,
			use: [
				{
					loader: 'file',
					options: {
						name: `${output.replace(/\[hash:\d+]_/, '')}.html`
					}
				},

				'extract',

				{
					loader: 'html',
					options: config.html()
				},

				{
					loader: 'monic',
					options: inherit(monic.html, {
						replacers: [
							include('build/html-import.replacer')
						]
					})
				},

				{
					loader: 'snakeskin',
					options: inherit(snakeskin.server, {
						exec: true,
						vars: {
							dependencies: graph.dependencies,
							assetsJSON
						}
					})
				}
			]
		});
	}

	loaders.rules.set('ss', {
		test: /\.ss$/,
		use: [
			{
				loader: 'snakeskin',
				options: snakeskin.client
			}
		]
	});

	loaders.rules.set('assets', {
		test: /\.(?:ttf|eot|woff|woff2|mp3|ogg|aac)$/,
		use: [
			{
				loader: 'url',
				options: fileLoaderOpts
			}
		]
	});

	loaders.rules.set('img', {
		test: /\.(?:png|gif|jpe?g)$/,
		use: [
			{
				loader: 'url',
				options: fileLoaderOpts
			}
		].concat(
			isProd ? {
				loader: 'image-webpack',
				options: imageOpts
			} : []
		)
	});

	loaders.rules.set('img.svg', {
		test: /\.svg$/,
		use: [
			{
				loader: 'svg-url',
				options: fileLoaderOpts
			}
		].concat(
			isProd ? {
				loader: 'svgo',
				options: imageOpts.svgo
			} : []
		)
	});

	return loaders;
};
<commit_msg>Removed some replacers from js loaders<commit_after>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	$C = require('collection.js'),
	config = require('config'),
	MiniCssExtractPlugin = require('mini-css-extract-plugin');

const
	{resolve} = require('@pzlr/build-core'),
	{output, assetsOutput, assetsJSON, hash, inherit, depsRgxpStr} = include('build/build.webpack');

const
	path = require('upath'),
	build = include('build/entities.webpack'),
	depsRgxp = new RegExp(`(?:^|/)node_modules/(?:(?!${depsRgxpStr}).)*?(?:/|$)`);

const
	snakeskin = config.snakeskin(),
	typescript = config.typescript(),
	monic = config.monic(),
	imageOpts = config.imageOpts();

const fileLoaderOpts = {
	name: path.basename(assetsOutput),
	outputPath: path.dirname(assetsOutput),
	limit: config.webpack.dataURILimit()
};

/**
 * Returns parameters for webpack.module
 *
 * @param {(number|string)} buildId - build id
 * @param {!Map} plugins - list of plugins
 * @returns {!Promise<Object>}
 */
module.exports = async function ({buildId, plugins}) {
	const
		graph = await build,
		loaders = {rules: new Map()};

	if (buildId === build.RUNTIME) {
		loaders.rules.set('ts', {
			test: /^(?:(?!\/workers\/).)*(?:\.d)?\.ts$/,
			exclude: depsRgxp,
			use: [
				{
					loader: 'ts',
					options: typescript.client
				},

				{
					loader: 'proxy',
					options: {
						modules: [resolve.blockSync(), resolve.sourceDir, ...resolve.rootDependencies]
					}
				},

				{
					loader: 'monic',
					options: inherit(monic.typescript, {
						replacers: [
							include('build/context.replacer'),
							include('build/super.replacer'),
							include('build/ts-import.replacer'),
							include('build/typograf.replacer'),
							include('build/prelude.replacer')
						]
					})
				}
			]
		});

		loaders.rules.set('ts.workers', {
			test: /\/workers\/.*?(?:\.d)?\.ts$/,
			exclude: depsRgxp,
			use: [
				{
					loader: 'ts',
					options: typescript.worker
				},

				{
					loader: 'monic',
					options: inherit(monic.typescript, {
						replacers: [
							include('build/context.replacer'),
							include('build/super.replacer'),
							include('build/ts-import.replacer'),
							include('build/typograf.replacer'),
							include('build/prelude.replacer')
						]
					})
				}
			]
		});

		loaders.rules.set('js', {
			test: /\.js$/,
			exclude: depsRgxp,
			use: [{
				loader: 'monic',
				options: inherit(monic.javascript, {
					replacers: [
						include('build/context.replacer'),
						include('build/super.replacer')
					]
				})
			}]
		});

	} else {
		plugins.set('extractCSS', new MiniCssExtractPlugin({
			filename: `${hash(output, true)}.css`,
			chunkFilename: '[id].css'
		}));

		const
			autoprefixer = config.autoprefixer(),
			postcss = config.postcss();

		loaders.rules.set('styl', {
			test: /\.styl$/,
			use: [].concat(
				MiniCssExtractPlugin.loader,

				{
					loader: 'fast-css',
					options: Object.reject(config.css(), ['minimize'])
				},

				isProd || $C(postcss).length() || $C(autoprefixer).length() ? {
					loader: 'postcss',
					options: inherit(postcss, {
						plugins: [require('autoprefixer')(autoprefixer)]
					})
				} : [],

				{
					loader: 'stylus',
					options: inherit(config.stylus(), {
						use: include('build/stylus')
					})
				},

				{
					loader: 'monic',
					options: inherit(monic.stylus, {
						replacers: [
							require('@pzlr/stylus-inheritance')({resolveImports: true})
						]
					})
				}
			)
		});

		loaders.rules.set('ess', {
			test: /\.ess$/,
			use: [
				{
					loader: 'file',
					options: {
						name: `${output.replace(/\[hash:\d+]_/, '')}.html`
					}
				},

				'extract',

				{
					loader: 'html',
					options: config.html()
				},

				{
					loader: 'monic',
					options: inherit(monic.html, {
						replacers: [
							include('build/html-import.replacer')
						]
					})
				},

				{
					loader: 'snakeskin',
					options: inherit(snakeskin.server, {
						exec: true,
						vars: {
							dependencies: graph.dependencies,
							assetsJSON
						}
					})
				}
			]
		});
	}

	loaders.rules.set('ss', {
		test: /\.ss$/,
		use: [
			{
				loader: 'snakeskin',
				options: snakeskin.client
			}
		]
	});

	loaders.rules.set('assets', {
		test: /\.(?:ttf|eot|woff|woff2|mp3|ogg|aac)$/,
		use: [
			{
				loader: 'url',
				options: fileLoaderOpts
			}
		]
	});

	loaders.rules.set('img', {
		test: /\.(?:png|gif|jpe?g)$/,
		use: [
			{
				loader: 'url',
				options: fileLoaderOpts
			}
		].concat(
			isProd ? {
				loader: 'image-webpack',
				options: imageOpts
			} : []
		)
	});

	loaders.rules.set('img.svg', {
		test: /\.svg$/,
		use: [
			{
				loader: 'svg-url',
				options: fileLoaderOpts
			}
		].concat(
			isProd ? {
				loader: 'svgo',
				options: imageOpts.svgo
			} : []
		)
	});

	return loaders;
};
<|endoftext|>


<commit_before>NRDB.data = {};
(function(data, $) {

	var force_update = false;
	var dbNames = ['cycles', 'packs', 'cards', 'prebuilts', 'factions', 'types', 'sides', 'mwl'];

	data.fdb_load = function (db) {
		return new Promise(function (resolve, reject) {
			db.load(function (err) {
				if(err) reject(err);
				else resolve(db);
			});
		});
	}

	/**
	 * loads the database from local
	 * sets up a Promise on all data loading/updating
	 * @memberOf data
	 */
	data.load = function load() {

		var fdb = new ForerunnerDB();
		data.db = fdb.db('netrunnerdb');
		data.masters = {};

		Promise.resolve(dbNames)
		.then(function (dbNames) {
			return Promise.all(_.map(dbNames, function (dbName) {
				data.masters[dbName] = data.db.collection('master_'+dbName, {primaryKey:'code', changeTimestamp: true});
				return data.fdb_load(data.masters[dbName]);
			}))
		})
		.then(function (collections) {
			return Promise.all(_.map(collections, function (collection) {
				// doing various on the collection to make sure we can run with it
				var age_of_database = new Date() - new Date(collection.metaData().lastChange);
				if(age_of_database > 864000000) {
					console.log('database is older than 10 days => refresh it');
					collection.setData([]);
					return false;
				}
				if(collection.count() === 0) {
					console.log('database is empty => load it');
					return false;
				}
				return true;
			}));
		})
		.then(function (collectionsInOrder) {
			console.log('all db successfully reloaded from storage');
			if(!_.every(collectionsInOrder)) {
				return false;
			};
			return true;
		}, function (message) {
			console.log('error when reloading db', message);
			return false;
		})
		.then(function (allCollectionsInOrder) {
			/*
			 * data has been fetched from local store
			 */
			force_update = !allCollectionsInOrder;

			/*
			 * triggering event that data is loaded
			 */
			if(!force_update) {
				data.release();
			}
		})
		.then(function () {
			return Promise.all(_.map(dbNames, function (dbName) {
				return new Promise(function (resolve, reject) {

					$.ajax(Routing.generate('api_public_'+dbName))
					.then(function (response, textStatus, jqXHR) {
						var lastModifiedData = new Date(jqXHR.getResponseHeader('Last-Modified'));
						var locale = jqXHR.getResponseHeader('Content-Language');
						var master = data.masters[dbName];
						var lastChangeDatabase = new Date(master.metaData().lastChange);
						var lastLocale = master.metaData().locale;
						var isCollectionUpdated = false;

						if(dbName === 'cards') {
							response.data.forEach(function (card) {
								card.imageUrl = response.imageUrlTemplate.replace(/{code}/, card.code);
							});
						}

						/*
						 * if we decided to force the update,
						 * or if the database is fresh,
						 * or if the database is older than the data,
						 * or if the locale has changed
						 * then we update the database
						 */
						if(force_update || !lastChangeDatabase || lastChangeDatabase < lastModifiedData || locale != lastLocale) {
							console.log(dbName+' data is newer than database or update forced or locale has changed => update the database')
							master.setData(response.data);
							master.metaData().locale = locale;
							isCollectionUpdated = (locale === lastLocale);
						}

						master.save(function (err) {
							if(err) {
								console.log('error when saving '+dbName, err);
								reject(true);
							} else {
								resolve(isCollectionUpdated);
							}
						});
					})
					.catch(function (jqXHR, textStatus, errorThrown) {
						console.log('error when requesting packs', errorThrown);
						reject(false);
					});
				})
			}));
		})
		.then(function (collectionsUpdated) {
			if(force_update) {
				data.release();
				return;
			}

			if(_.find(collectionsUpdated)) {
				/*
				 * we display a message informing the user that they can reload their page to use the updated data
				 * except if we are on the front page, because data is not essential on the front page
				 */
				if($('.site-title').length === 0) {
					var message = "A new version of the data is available. Click here to reload your page.";
					alert(message);
				}
			}

		}, function (dataLoaded) {
			/*
			 * if not all data has been loaded, we can't run the site properly
			 */
			if(!_.every(dataLoaded)) {
				var message = "Unable to load the data. Click here to reload your page.";
				alert(message);
				return;
			} else {
				data.release();
			}
		});
	}

	/**
	 * release the data for consumption by other modules
	 * @memberOf data
	 */
	data.release = function release() {
		_.each(dbNames, function (dbName) {
			data[dbName] = data.db.collection(dbName, {primaryKey:'code', changeTimestamp: false});
			data[dbName].setData(data.masters[dbName].find());
		})

		_.each(data.types.find(), function (type) {
			data.types.updateById(type.code, {
				side: data.sides.findById(type.side_code)
			});
		});

		_.each(data.packs.find(), function (pack) {
			data.packs.updateById(pack.code, {
				cycle: data.cycles.findById(pack.cycle_code)
			});
		});

		_.each(data.factions.find(), function (faction) {
			data.factions.updateById(faction.code, {
				side: data.sides.findById(faction.side_code)
			});
		});

		_.each(data.cards.find(), function (card) {
			data.cards.updateById(card.code, {
				faction: data.masters.factions.findById(card.faction_code),
				side: data.sides.findById(card.side_code),
				type: data.types.findById(card.type_code),
				pack: data.packs.findById(card.pack_code)
			});
		});

		data.isLoaded = true;

		$(document).trigger('data.app');
	}

	/**
	 * triggers a forced update of the database
	 * @memberOf data
	 */
	data.update = function update() {
		_.each(data.masters, function (collection) {
			collection.drop();
		});
		data.load();
	}

	$(function() {
		data.load();
	});

})(NRDB.data, jQuery);

<commit_msg>fix alert display<commit_after>NRDB.data = {};
(function(data, $) {

	var force_update = false;
	var dbNames = ['cycles', 'packs', 'cards', 'prebuilts', 'factions', 'types', 'sides', 'mwl'];

	data.fdb_load = function (db) {
		return new Promise(function (resolve, reject) {
			db.load(function (err) {
				if(err) reject(err);
				else resolve(db);
			});
		});
	}

	/**
	 * loads the database from local
	 * sets up a Promise on all data loading/updating
	 * @memberOf data
	 */
	data.load = function load() {

		var fdb = new ForerunnerDB();
		data.db = fdb.db('netrunnerdb');
		data.masters = {};

		Promise.resolve(dbNames)
		.then(function (dbNames) {
			return Promise.all(_.map(dbNames, function (dbName) {
				data.masters[dbName] = data.db.collection('master_'+dbName, {primaryKey:'code', changeTimestamp: true});
				return data.fdb_load(data.masters[dbName]);
			}))
		})
		.then(function (collections) {
			return Promise.all(_.map(collections, function (collection) {
				// doing various on the collection to make sure we can run with it
				var age_of_database = new Date() - new Date(collection.metaData().lastChange);
				if(age_of_database > 864000000) {
					console.log('database is older than 10 days => refresh it');
					collection.setData([]);
					return false;
				}
				if(collection.count() === 0) {
					console.log('database is empty => load it');
					return false;
				}
				return true;
			}));
		})
		.then(function (collectionsInOrder) {
			console.log('all db successfully reloaded from storage');
			if(!_.every(collectionsInOrder)) {
				return false;
			};
			return true;
		}, function (message) {
			console.log('error when reloading db', message);
			return false;
		})
		.then(function (allCollectionsInOrder) {
			/*
			 * data has been fetched from local store
			 */
			force_update = !allCollectionsInOrder;

			/*
			 * triggering event that data is loaded
			 */
			if(!force_update) {
				data.release();
			}
		})
		.then(function () {
			return Promise.all(_.map(dbNames, function (dbName) {
				return new Promise(function (resolve, reject) {

					$.ajax(Routing.generate('api_public_'+dbName))
					.then(function (response, textStatus, jqXHR) {
						var lastModifiedData = new Date(jqXHR.getResponseHeader('Last-Modified'));
						var locale = jqXHR.getResponseHeader('Content-Language');
						var master = data.masters[dbName];
						var lastChangeDatabase = new Date(master.metaData().lastChange);
						var lastLocale = master.metaData().locale;
						var isCollectionUpdated = false;

						if(dbName === 'cards') {
							response.data.forEach(function (card) {
								card.imageUrl = response.imageUrlTemplate.replace(/{code}/, card.code);
							});
						}

						/*
						 * if we decided to force the update,
						 * or if the database is fresh,
						 * or if the database is older than the data,
						 * or if the locale has changed
						 * then we update the database
						 */
						if(force_update || !lastChangeDatabase || lastChangeDatabase < lastModifiedData || locale != lastLocale) {
							console.log(dbName+' data is newer than database or update forced or locale has changed => update the database')
							master.setData(response.data);
							master.metaData().locale = locale;
							isCollectionUpdated = (locale === lastLocale);
						}

						master.save(function (err) {
							if(err) {
								console.log('error when saving '+dbName, err);
								reject(true);
							} else {
								resolve(isCollectionUpdated);
							}
						});
					})
					.catch(function (jqXHR, textStatus, errorThrown) {
						console.log('error when requesting packs', errorThrown);
						reject(false);
					});
				})
			}));
		})
		.then(function (collectionsUpdated) {
			if(force_update) {
				data.release();
				return;
			}

			if(_.find(collectionsUpdated)) {
				/*
				 * we display a message informing the user that they can reload their page to use the updated data
				 * except if we are on the front page, because data is not essential on the front page
				 */
				if($('.site-title').length === 0) {
					var message = "A new version of the data is available. Click here to reload your page.";
					$('
').html(message).insertAfter($('nav'));
				}
			}

		}, function (dataLoaded) {
			/*
			 * if not all data has been loaded, we can't run the site properly
			 */
			if(!_.every(dataLoaded)) {
				var message = "Unable to load the data. Click here to reload your page.";
				$('
').html(message).insertAfter($('nav'));
				return;
			} else {
				data.release();
			}
		});
	}

	/**
	 * release the data for consumption by other modules
	 * @memberOf data
	 */
	data.release = function release() {
		_.each(dbNames, function (dbName) {
			data[dbName] = data.db.collection(dbName, {primaryKey:'code', changeTimestamp: false});
			data[dbName].setData(data.masters[dbName].find());
		})

		_.each(data.types.find(), function (type) {
			data.types.updateById(type.code, {
				side: data.sides.findById(type.side_code)
			});
		});

		_.each(data.packs.find(), function (pack) {
			data.packs.updateById(pack.code, {
				cycle: data.cycles.findById(pack.cycle_code)
			});
		});

		_.each(data.factions.find(), function (faction) {
			data.factions.updateById(faction.code, {
				side: data.sides.findById(faction.side_code)
			});
		});

		_.each(data.cards.find(), function (card) {
			data.cards.updateById(card.code, {
				faction: data.masters.factions.findById(card.faction_code),
				side: data.sides.findById(card.side_code),
				type: data.types.findById(card.type_code),
				pack: data.packs.findById(card.pack_code)
			});
		});

		data.isLoaded = true;

		$(document).trigger('data.app');
	}

	/**
	 * triggers a forced update of the database
	 * @memberOf data
	 */
	data.update = function update() {
		_.each(data.masters, function (collection) {
			collection.drop();
		});
		data.load();
	}

	$(function() {
		data.load();
	});

})(NRDB.data, jQuery);

<|endoftext|>


<commit_before>var jsonfile = './browscap.preprocessed.json';

exports.setJson = function (filename) {
  jsonfile = filename;
};

exports.getBrowser = function (userAgent) {
  var browsers, patterns, re, key, found, matches, browsersindex;

  patterns = require(jsonfile).patterns;
  browsers = require(jsonfile).browsers;

  // Test user agent against each browser regex
  for (var pattern in patterns) {
    pattern = pattern.replace(/@/g, '');
    re = new RegExp(pattern, 'i');

    console.log(pattern);

    if (re.test(userAgent)) {
      key = patterns[pattern];
      found = false;
      matches = userAgent.match(re);

      if (matches.length === 1) {
        browsersindex = key;
        found = true;
      } else {
        var matchString = '@' + matches.join('|');

        if (key[matchString]) {
          browsersindex = key[matchString];
          found = true;
        }
      }

      console.log(found);

      if (found && browsers[browsersindex]) {
        var browser = [userAgent, pattern.toLowerCase().trim()];
        var browserData = JSON.parse(browsers[browsersindex]);

        for (var property in browserData) {
          browser[property] = browserData[property];
        }

        while (browserData['Parent']) {
          browserData = JSON.parse(browsers[browserData['Parent']]);

          for (var property in browserData) {
            if (!browser[property]) {
              browser[property] = browserData[property];
            }
          }
        }

        if (browser['Parent']) {
          var userAgents = require(jsonfile).userAgents;
          browser['Parent'] = userAgents[browser['Parent']];
        }

        return browser;
      }
    }
  }

  return null;
};
<commit_msg>change replacing @ char<commit_after>var jsonfile = './browscap.preprocessed.json';

exports.setJson = function (filename) {
  jsonfile = filename;
};

exports.getBrowser = function (userAgent) {
  var browsers, patterns, re, key, found, matches, browsersindex;

  patterns = require(jsonfile).patterns;
  browsers = require(jsonfile).browsers;

  // Test user agent against each browser regex
  for (var pattern in patterns) {
    re = new RegExp(pattern.replace(/@/g, ''), 'i');

    if (re.test(userAgent)) {
      if (!patterns.hasOwnProperty(pattern)) {
        continue;
      }

      key = patterns[pattern];
      found = false;
      matches = userAgent.match(re);

      if (matches.length === 1) {
        browsersindex = key;
        found = true;
      } else {
        var matchString = '@' + matches.join('|');

        if (key[matchString]) {
          browsersindex = key[matchString];
          found = true;
        }
      }

      console.log(found);

      if (found && browsers[browsersindex]) {
        var browser = [userAgent, pattern.toLowerCase().trim()];
        var browserData = JSON.parse(browsers[browsersindex]);

        for (var property in browserData) {
          browser[property] = browserData[property];
        }

        while (browserData['Parent']) {
          browserData = JSON.parse(browsers[browserData['Parent']]);

          for (var property in browserData) {
            if (!browser[property]) {
              browser[property] = browserData[property];
            }
          }
        }

        if (browser['Parent']) {
          var userAgents = require(jsonfile).userAgents;
          browser['Parent'] = userAgents[browser['Parent']];
        }

        return browser;
      }
    }
  }

  return null;
};
<|endoftext|>


<commit_before>NRDB.data = {};
(function(data, $) {

	var force_update = false;
	var dbNames = ['cycles', 'packs', 'cards', 'prebuilts', 'factions', 'types', 'sides', 'mwl'];

	data.fdb_load = function (db) {
		return new Promise(function (resolve, reject) {
			db.load(function (err) {
				if(err) reject(err);
				else resolve(db);
			});
		});
	}

	/**
	 * loads the database from local
	 * sets up a Promise on all data loading/updating
	 * @memberOf data
	 */
	data.load = function load() {

		var fdb = new ForerunnerDB();
		data.db = fdb.db('netrunnerdb');
		data.masters = {};

		Promise.resolve(dbNames)
		.then(function (dbNames) {
			return Promise.all(_.map(dbNames, function (dbName) {
				data.masters[dbName] = data.db.collection('master_'+dbName, {primaryKey:'code', changeTimestamp: true});
				return data.fdb_load(data.masters[dbName]);
			}))
		})
		.then(function (collections) {
			return Promise.all(_.map(collections, function (collection) {
				// doing various on the collection to make sure we can run with it
				var age_of_database = new Date() - new Date(collection.metaData().lastChange);
				if(age_of_database > 864000000) {
					console.log('database is older than 10 days => refresh it');
					collection.setData([]);
					return false;
				}
				if(collection.count() === 0) {
					console.log('database is empty => load it');
					return false;
				}
				return true;
			}));
		})
		.then(function (collectionsInOrder) {
			console.log('all db successfully reloaded from storage');
			if(!_.every(collectionsInOrder)) {
				return false;
			};
			return true;
		}, function (message) {
			console.log('error when reloading db', message);
			return false;
		})
		.then(function (allCollectionsInOrder) {
			/*
			 * data has been fetched from local store
			 */
			force_update = !allCollectionsInOrder;

			/*
			 * triggering event that data is loaded
			 */
			if(!force_update) {
				data.release();
			}
		})
		.then(function () {
			return Promise.all(_.map(dbNames, function (dbName) {
				return new Promise(function (resolve, reject) {

					$.ajax(Routing.generate('api_public_'+dbName))
					.then(function (response, textStatus, jqXHR) {
						var lastModifiedData = new Date(jqXHR.getResponseHeader('Last-Modified'));
						var locale = jqXHR.getResponseHeader('Content-Language');
						var master = data.masters[dbName];
						var lastChangeDatabase = new Date(master.metaData().lastChange);
						var lastLocale = master.metaData().locale;
						var isCollectionUpdated = false;

						if(dbName === 'cards') {
							response.data.forEach(function (card) {
								card.imageUrl = response.imageUrlTemplate.replace(/{code}/, card.code);
							});
						}

						/*
						 * if we decided to force the update,
						 * or if the database is fresh,
						 * or if the database is older than the data,
						 * or if the locale has changed
						 * then we update the database
						 */
						if(force_update || !lastChangeDatabase || lastChangeDatabase < lastModifiedData || locale != lastLocale) {
							console.log(dbName+' data is newer than database or update forced or locale has changed => update the database')
							master.setData(response.data);
							master.metaData().locale = locale;
							isCollectionUpdated = (locale === lastLocale);
						}

						master.save(function (err) {
							if(err) {
								console.log('error when saving '+dbName, err);
								reject(true);
							} else {
								resolve(isCollectionUpdated);
							}
						});
					})
					.catch(function (jqXHR, textStatus, errorThrown) {
						console.log('error when requesting packs', errorThrown);
						reject(false);
					});
				})
			}));
		})
		.then(function (collectionsUpdated) {
			if(force_update) {
				data.release();
				return;
			}

			if(_.find(collectionsUpdated)) {
				/*
				 * we display a message informing the user that they can reload their page to use the updated data
				 * except if we are on the front page, because data is not essential on the front page
				 */
				if($('.site-title').length === 0) {
					var message = "A new version of the data is available. Click here to reload your page.";
					$('
').html(message).insertAfter($('nav'));
				}
			}

		}, function (dataLoaded) {
			/*
			 * if not all data has been loaded, we can't run the site properly
			 */
			if(!_.every(dataLoaded)) {
				var message = "Unable to load the data. Click here to reload your page.";
				$('
').html(message).insertAfter($('nav'));
				return;
			} else {
				data.release();
			}
		});
	}

	/**
	 * release the data for consumption by other modules
	 * @memberOf data
	 */
	data.release = function release() {
		_.each(dbNames, function (dbName) {
			data[dbName] = data.db.collection(dbName, {primaryKey:'code', changeTimestamp: false});
			data[dbName].setData(data.masters[dbName].find());
		})

		_.each(data.types.find(), function (type) {
			data.types.updateById(type.code, {
				side: data.sides.findById(type.side_code)
			});
		});

		_.each(data.packs.find(), function (pack) {
			data.packs.updateById(pack.code, {
				cycle: data.cycles.findById(pack.cycle_code)
			});
		});

		_.each(data.factions.find(), function (faction) {
			data.factions.updateById(faction.code, {
				side: data.sides.findById(faction.side_code)
			});
		});

		_.each(data.cards.find(), function (card) {
			data.cards.updateById(card.code, {
				faction: data.masters.factions.findById(card.faction_code),
				side: data.sides.findById(card.side_code),
				type: data.types.findById(card.type_code),
				pack: data.packs.findById(card.pack_code)
			});
		});

		data.isLoaded = true;

		$(document).trigger('data.app');
	}

	/**
	 * triggers a forced update of the database
	 * @memberOf data
	 */
	data.update = function update() {
		_.each(data.masters, function (collection) {
			collection.drop();
		});
		data.load();
	}

	$(function() {
		data.load();
	});

})(NRDB.data, jQuery);

<commit_msg>use proper alert<commit_after>NRDB.data = {};
(function(data, $) {

	var force_update = false;
	var dbNames = ['cycles', 'packs', 'cards', 'prebuilts', 'factions', 'types', 'sides', 'mwl'];

	data.fdb_load = function (db) {
		return new Promise(function (resolve, reject) {
			db.load(function (err) {
				if(err) reject(err);
				else resolve(db);
			});
		});
	}

	/**
	 * loads the database from local
	 * sets up a Promise on all data loading/updating
	 * @memberOf data
	 */
	data.load = function load() {

		var fdb = new ForerunnerDB();
		data.db = fdb.db('netrunnerdb');
		data.masters = {};

		Promise.resolve(dbNames)
		.then(function (dbNames) {
			return Promise.all(_.map(dbNames, function (dbName) {
				data.masters[dbName] = data.db.collection('master_'+dbName, {primaryKey:'code', changeTimestamp: true});
				return data.fdb_load(data.masters[dbName]);
			}))
		})
		.then(function (collections) {
			return Promise.all(_.map(collections, function (collection) {
				// doing various on the collection to make sure we can run with it
				var age_of_database = new Date() - new Date(collection.metaData().lastChange);
				if(age_of_database > 864000000) {
					console.log('database is older than 10 days => refresh it');
					collection.setData([]);
					return false;
				}
				if(collection.count() === 0) {
					console.log('database is empty => load it');
					return false;
				}
				return true;
			}));
		})
		.then(function (collectionsInOrder) {
			console.log('all db successfully reloaded from storage');
			if(!_.every(collectionsInOrder)) {
				return false;
			};
			return true;
		}, function (message) {
			console.log('error when reloading db', message);
			return false;
		})
		.then(function (allCollectionsInOrder) {
			/*
			 * data has been fetched from local store
			 */
			force_update = !allCollectionsInOrder;

			/*
			 * triggering event that data is loaded
			 */
			if(!force_update) {
				data.release();
			}
		})
		.then(function () {
			return Promise.all(_.map(dbNames, function (dbName) {
				return new Promise(function (resolve, reject) {

					$.ajax(Routing.generate('api_public_'+dbName))
					.then(function (response, textStatus, jqXHR) {
						var lastModifiedData = new Date(jqXHR.getResponseHeader('Last-Modified'));
						var locale = jqXHR.getResponseHeader('Content-Language');
						var master = data.masters[dbName];
						var lastChangeDatabase = new Date(master.metaData().lastChange);
						var lastLocale = master.metaData().locale;
						var isCollectionUpdated = false;

						if(dbName === 'cards') {
							response.data.forEach(function (card) {
								card.imageUrl = response.imageUrlTemplate.replace(/{code}/, card.code);
							});
						}

						/*
						 * if we decided to force the update,
						 * or if the database is fresh,
						 * or if the database is older than the data,
						 * or if the locale has changed
						 * then we update the database
						 */
						if(force_update || !lastChangeDatabase || lastChangeDatabase < lastModifiedData || locale != lastLocale) {
							console.log(dbName+' data is newer than database or update forced or locale has changed => update the database')
							master.setData(response.data);
							master.metaData().locale = locale;
							isCollectionUpdated = (locale === lastLocale);
						}

						master.save(function (err) {
							if(err) {
								console.log('error when saving '+dbName, err);
								reject(true);
							} else {
								resolve(isCollectionUpdated);
							}
						});
					})
					.catch(function (jqXHR, textStatus, errorThrown) {
						console.log('error when requesting packs', errorThrown);
						reject(false);
					});
				})
			}));
		})
		.then(function (collectionsUpdated) {
			if(force_update) {
				data.release();
				return;
			}

			if(_.find(collectionsUpdated)) {
				/*
				 * we display a message informing the user that they can reload their page to use the updated data
				 * except if we are on the front page, because data is not essential on the front page
				 */
				if($('.site-title').length === 0) {
					var message = "A new version of the data is available. Click here to reload your page.";
					$('
').html(message).insertAfter($('nav'));
				}
			}

		}, function (dataLoaded) {
			/*
			 * if not all data has been loaded, we can't run the site properly
			 */
			if(!_.every(dataLoaded)) {
				var message = "Unable to load the data. Click here to reload your page.";
				$('
').html(message).insertAfter($('nav'));
				return;
			} else {
				data.release();
			}
		});
	}

	/**
	 * release the data for consumption by other modules
	 * @memberOf data
	 */
	data.release = function release() {
		_.each(dbNames, function (dbName) {
			data[dbName] = data.db.collection(dbName, {primaryKey:'code', changeTimestamp: false});
			data[dbName].setData(data.masters[dbName].find());
		})

		_.each(data.types.find(), function (type) {
			data.types.updateById(type.code, {
				side: data.sides.findById(type.side_code)
			});
		});

		_.each(data.packs.find(), function (pack) {
			data.packs.updateById(pack.code, {
				cycle: data.cycles.findById(pack.cycle_code)
			});
		});

		_.each(data.factions.find(), function (faction) {
			data.factions.updateById(faction.code, {
				side: data.sides.findById(faction.side_code)
			});
		});

		_.each(data.cards.find(), function (card) {
			data.cards.updateById(card.code, {
				faction: data.masters.factions.findById(card.faction_code),
				side: data.sides.findById(card.side_code),
				type: data.types.findById(card.type_code),
				pack: data.packs.findById(card.pack_code)
			});
		});

		data.isLoaded = true;

		$(document).trigger('data.app');
	}

	/**
	 * triggers a forced update of the database
	 * @memberOf data
	 */
	data.update = function update() {
		_.each(data.masters, function (collection) {
			collection.drop();
		});
		data.load();
	}

	$(function() {
		data.load();
	});

})(NRDB.data, jQuery);

<|endoftext|>


<commit_before>Ember.LinkView.reopen({
    active: Ember.computed('resolvedParams', 'routeArgs', function () {
        var isActive = this._super();

        Ember.set(this, 'alternateActive', isActive);

        return isActive;
    })
});
<commit_msg>Remove active class from buttons.<commit_after>Ember.LinkView.reopen({
    active: Ember.computed('resolvedParams', 'routeArgs', function () {
        var isActive = this._super();

        Ember.set(this, 'alternateActive', isActive);

        return isActive;
    }),

    activeClass: Ember.computed('tagName', function () {
        return this.get('tagName') === 'button' ? '' : 'active';
    })
});
<|endoftext|>


<commit_before>/*

    countUp.js
    by @inorganik
    v 1.0.1

*/

// target = id of Html element where counting occurs
// startVal = the value you want to begin at
// endVal = the value you want to arrive at
// decimals = number of decimal places in number, default 0
// duration = duration in seconds, default 2

function countUp(target, startVal, endVal, decimals, duration) {

    // make sure requestAnimationFrame and cancelAnimationFrame are defined
    // polyfill for browsers without native support
    // by Opera engineer Erik Möller
    var lastTime = 0;
    var vendors = ['webkit', 'moz', 'ms'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        }
    }
    if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        }
    }

    var self = this;

    // toggle easing
    this.useEasing = true;

    this.d = document.getElementById(target);
    self.startVal = Number(startVal);
    endVal = Number(endVal);
    this.countDown = (startVal > endVal) ? true : false;
    decimals = Math.max(0, decimals || 0);
    this.dec = Math.pow(10, decimals);
    this.duration = duration * 1000 || 2000;
    this.startTime = null;
    this.timestamp = null;
    this.remaining = null;
    this.frameVal = self.startVal;
    this.rAF = null;

    // Robert Penner's easeOutExpo
    this.easeOutExpo = function(t, b, c, d) {
        return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
    }
    this.count = function(timestamp) {

        if (self.startTime === null) self.startTime = timestamp;

        self.timestamp = timestamp;

        var progress = timestamp - self.startTime;
        self.remaining = self.duration - progress;

        // to ease or not to ease
        if (self.useEasing) {
            if (self.countDown) {
                var i = self.easeOutExpo(progress, 0, self.startVal - endVal, self.duration);
                self.frameVal = self.startVal - i;
            } else {
                self.frameVal = self.easeOutExpo(progress, self.startVal, endVal - self.startVal, self.duration);
            }
        } else {
            if (self.countDown) {
                var i = (self.startVal - endVal) * (progress / self.duration);
                self.frameVal = self.startVal - i;
            } else {
                self.frameVal = self.startVal + (endVal - self.startVal) * (progress / self.duration);
            }
        }

        // decimal
        self.frameVal = Math.round(self.frameVal*self.dec)/self.dec;

        // don't go past endVal since progress can exceed duration in the last frame
        if (self.countDown) {
            self.frameVal = (self.frameVal < endVal) ? endVal : self.frameVal;
        } else {
            self.frameVal = (self.frameVal > endVal) ? endVal : self.frameVal;
        }

        // format and print value
        self.d.innerHTML = self.addCommas(self.frameVal.toFixed(decimals));

        // whether to continue
        if (progress < self.duration) {
            self.rAF = requestAnimationFrame(self.count);
        } else {
            if (self.callback != null) self.callback();
        }
    }
    this.start = function(callback) {
        self.callback = callback;
        // make sure values are valid
        if (!isNaN(endVal) && !isNaN(startVal)) {
            self.rAF = requestAnimationFrame(self.count);
        } else {
            console.log('countUp error: startVal or endVal is not a number');
            self.d.innerHTML = '--';
        }
        return false;
    }
    this.stop = function() {
        cancelAnimationFrame(self.rAF);
    }
    this.reset = function() {
        cancelAnimationFrame(self.rAF);
        self.d.innerHTML = self.addCommas(startVal.toFixed(decimals));
    }
    this.resume = function() {
        self.startTime = null;
        self.duration = self.remaining;
        self.startVal = self.frameVal;
        requestAnimationFrame(self.count);
    }
    this.addCommas = function(nStr) {
        nStr += '';
        var x, x1, x2, rgx;
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

    // format startVal on initialization
    self.d.innerHTML = self.addCommas(startVal.toFixed(decimals));
}

// Example:
// var numAnim = new countUp("SomeElementYouWantToAnimate", 0, 99.99, 2, 1.5);
// numAnim.start();
// with optional callback:
// numAnim.start(someMethodToCallOnComplete);<commit_msg>allow target to accept something other than an ID<commit_after>/*

    countUp.js
    by @inorganik
    v 1.0.1

*/

// target = id of Html element where counting occurs
// startVal = the value you want to begin at
// endVal = the value you want to arrive at
// decimals = number of decimal places in number, default 0
// duration = duration in seconds, default 2

function countUp(target, startVal, endVal, decimals, duration) {

    // make sure requestAnimationFrame and cancelAnimationFrame are defined
    // polyfill for browsers without native support
    // by Opera engineer Erik Möller
    var lastTime = 0;
    var vendors = ['webkit', 'moz', 'ms'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        }
    }
    if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        }
    }

    var self = this;

    // toggle easing
    this.useEasing = true;

    this.d = (typeof target === 'string') ? document.getElementById(target) : target;
    self.startVal = Number(startVal);
    endVal = Number(endVal);
    this.countDown = (startVal > endVal) ? true : false;
    decimals = Math.max(0, decimals || 0);
    this.dec = Math.pow(10, decimals);
    this.duration = duration * 1000 || 2000;
    this.startTime = null;
    this.timestamp = null;
    this.remaining = null;
    this.frameVal = self.startVal;
    this.rAF = null;

    // Robert Penner's easeOutExpo
    this.easeOutExpo = function(t, b, c, d) {
        return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
    }
    this.count = function(timestamp) {

        if (self.startTime === null) self.startTime = timestamp;

        self.timestamp = timestamp;

        var progress = timestamp - self.startTime;
        self.remaining = self.duration - progress;

        // to ease or not to ease
        if (self.useEasing) {
            if (self.countDown) {
                var i = self.easeOutExpo(progress, 0, self.startVal - endVal, self.duration);
                self.frameVal = self.startVal - i;
            } else {
                self.frameVal = self.easeOutExpo(progress, self.startVal, endVal - self.startVal, self.duration);
            }
        } else {
            if (self.countDown) {
                var i = (self.startVal - endVal) * (progress / self.duration);
                self.frameVal = self.startVal - i;
            } else {
                self.frameVal = self.startVal + (endVal - self.startVal) * (progress / self.duration);
            }
        }

        // decimal
        self.frameVal = Math.round(self.frameVal*self.dec)/self.dec;

        // don't go past endVal since progress can exceed duration in the last frame
        if (self.countDown) {
            self.frameVal = (self.frameVal < endVal) ? endVal : self.frameVal;
        } else {
            self.frameVal = (self.frameVal > endVal) ? endVal : self.frameVal;
        }

        // format and print value
        self.d.innerHTML = self.addCommas(self.frameVal.toFixed(decimals));

        // whether to continue
        if (progress < self.duration) {
            self.rAF = requestAnimationFrame(self.count);
        } else {
            if (self.callback != null) self.callback();
        }
    }
    this.start = function(callback) {
        self.callback = callback;
        // make sure values are valid
        if (!isNaN(endVal) && !isNaN(startVal)) {
            self.rAF = requestAnimationFrame(self.count);
        } else {
            console.log('countUp error: startVal or endVal is not a number');
            self.d.innerHTML = '--';
        }
        return false;
    }
    this.stop = function() {
        cancelAnimationFrame(self.rAF);
    }
    this.reset = function() {
        cancelAnimationFrame(self.rAF);
        self.d.innerHTML = self.addCommas(startVal.toFixed(decimals));
    }
    this.resume = function() {
        self.startTime = null;
        self.duration = self.remaining;
        self.startVal = self.frameVal;
        requestAnimationFrame(self.count);
    }
    this.addCommas = function(nStr) {
        nStr += '';
        var x, x1, x2, rgx;
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

    // format startVal on initialization
    self.d.innerHTML = self.addCommas(startVal.toFixed(decimals));
}

// Example:
// var numAnim = new countUp("SomeElementYouWantToAnimate", 0, 99.99, 2, 1.5);
// numAnim.start();
// with optional callback:
// numAnim.start(someMethodToCallOnComplete);<|endoftext|>