<commit_before>/*
 * grunt-shared-config
 *
 * Use this task to create multiple config files for JS/JS-AMD, SCSS/SASS/LESS/stylus from one JSON/YAML.
 *
 * Copyright (c) 2013 Mathias Paumgarten
 * Licensed under the MIT license.
 */

var mout = require("mout");

module.exports = function (grunt) {
  "use strict";

  grunt.registerMultiTask("sharedConfig", "Your task description goes here.", function () {

    // ===========
    // -- UTILS --
    // ===========

    function normalizeOutArray(value) {
      return typeof value === "string" ? [value] : value;
    }

    function normalizeFormat(value) {
      return mout.array.contains(varFormats, value) ? value : varFormats[0];
    }

    function normalizeMask(mask) {
      if (mask === null) return null;

      if (mout.lang.isString(mask) && fileExists(mask)) return readFile(mask);
      else if (mout.lang.isObject(mask)) return mask;
      else if (mout.lang.isArray(mask)) {

        return mask.reduce(function (previous, current) {
          return mout.object.deepMixIn(previous, normalizeMask(current));
        }, {});

      }

      return {};
    }

    function format(value, type) {
      value = value.replace(/-/g, " ");

      switch (type) {
        case "underscore":
          return mout.string.underscore(value);
        case "uppercase":
          return value.toUpperCase().replace(/ /g, "_");
        case "dash":
          return mout.string.hyphenate(value);
        default:
          return mout.string.camelCase(value);
      }
    }

    function fileExists(filePath) {
      if (!grunt.file.exists(filePath)) {
        grunt.log.warn("Source file (" + filePath + ") not found.");
        return false;
      }
      return true;
    }

    function readFile(filePath) {
      var fileType = filePath.split(".").pop().toLowerCase();

      return ( ( fileType === "yml" || fileType === "yaml" ) ? grunt.file.readYAML : grunt.file.readJSON )(filePath);
    }

    function isStringNumber(value) {
      var units = ["em", "px", "s", "in", "mm", "cm", "pt", "pc", "%"];

      return units.reduce(function (previous, current) {
        return previous || mout.string.endsWith(value, current);
      }, false);
    }

    function isPathExpression(value) {
      return new RegExp(
        "^(" +
          // full URL
          /// protocol identifier
        "(?:(?:https?|ftp)://)" +
          /// user:pass authentication
        "(?:\\S+(?::\\S*)?@)?" +
        "(?:" +
          /// IP address exclusion
          /// private & local networks
        "(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
        "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
        "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
          /// IP address dotted notation octets
          /// excludes loopback network 0.0.0.0
          /// excludes reserved space >= 224.0.0.0
          /// excludes network & broacast addresses
          /// (first & last IP address of each class)
        "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
        "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
        "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
        "|" +
          /// host name
        "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
          /// domain name
        "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
          /// TLD identifier
        "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
        ")" +
          /// port number
        "(?::\\d{2,5})?" +
          /// resource path
        "(?:/\\S*)?" +
        "|" +
          /// or PATH
        "([\\w\\/]?(?:\\/[\\w\\.\\-]+)+)" +
        ")$", "i"
      ).test(value);
    }

    function isBooleanExpression(value) {
      return (/^true$/i).test(value);
    }

    function isStringExpression(value) {
      return (/^[\'\"].*[\'\"]$/i).test(value);
    }

    function getStyleSafeValue(value) {
      if (isStringExpression(value)) {
        value = "\"" + value.substr(1, value.length - 2) + "\"";
      } else if (isPathExpression(value)) {
        value = "\"" + value + "\"";
      } else if (isBooleanExpression(value) && typeof value === "string") {
        value = "\"" + value + "\"";
      }

      return value;
    }

    // ==============
    // -- SETTINGS --
    // ==============

    // default options
    var options = this.options({
      ngconstant: false,
      amd: false,
      jsFormat: "uppercase",
      cssFormat: "dash",
      singlequote: false,
      name: "config",
      module: "config",
      useSassMaps: false,
      indention: "\t",
      mask: undefined,
      maskAllowUnknownLevels: 0
    });

    // possible variable formats
    var varFormats = ["underscore", "uppercase", "dash", "camelcase"];

    // available file extensions
    var fileExtensions = {
      js: ["js"],
      css: ["scss", "sass", "less", "styl"]
    };

    // variable patterns
    var outputPattern = {
      scss: "${{key}}: {{value}};\n",
      sass: "${{key}}: {{value}}\n",
      less: "@{{key}}: {{value}};\n",
      sassmaps: "{{key}}: {{value}},",
      styl: "{{key}} = {{value}}\n",
      amd: "define( function() {\n\n" + options.indention + "return {{{vars}}" + options.indention + "}\n\n} );\n",
      ngconstant: "angular.module(\"{{module}}\", [])\n" + options.indention + ".constant(\"{{name}}\", {{{vars}}" + options.indention + "});",
      js: "var {{name}} = {{vars}};\n"
    };

    // Normalize user input
    options.dest = normalizeOutArray(options.dest);
    options.jsFormat = normalizeFormat(options.jsFormat);
    options.cssFormat = normalizeFormat(options.cssFormat);

    // ================
    // -- GENERATORS --
    // ================

    // Generate Style files
    function generateStyle(data, type) {
      var content = "";
      var pattern = outputPattern[type];

      function resolveNested(data, parentKey) {
        var name, key;
        for (key in data) {
          if (data.hasOwnProperty(key)) {
            name = parentKey ? format(parentKey + "-" + key, options.cssFormat) : format(key, options.cssFormat);

            if (mout.lang.isObject(data[key])) {

              resolveNested(data[key], name);

            } else {

              var value = getStyleSafeValue(data[key]);

              content += pattern.replace("{{key}}", name).replace("{{value}}", value);
            }
          }
        }
      }

      resolveNested(data);

      return content;
    }

    // Generate JavaScript files
    function generateJS(data) {
      var preparedData = prepareValues(data);
      var content = JSON.stringify(preparedData, null, options.indention);

      var output = outputPattern.js.replace("{{name}}", options.name).replace("{{vars}}", content);
      return options.singlequote ? output.replace(/"/g, '\'') : output;
    }

    function generateAMD(data) {
      var preparedData = prepareValues(data);
      var content = JSON.stringify(preparedData, null, options.indention);
      var pattern = mout.lang.deepClone(outputPattern.amd);

      content = content.substr(1, content.length - 2);
      content = indent(content, options.indention);

      return pattern.replace("{{vars}}", content);
    }

    function generateNGConstant(data) {
      var preparedData = prepareValues(data);
      var content = JSON.stringify(preparedData, null, options.indention);
      var pattern = mout.lang.deepClone(outputPattern.ngconstant);

      content = content.substr(1, content.length - 2);
      content = indent(content, options.indention);

      var output = pattern.replace("{{module}}", options.module)
        .replace(/\{\{name\}\}/g, options.name).replace("{{vars}}", content);

      return options.singlequote ? output.replace(/"/g, '\'') : output;
    }

    function generateSassMaps(data) {
      var pattern = outputPattern.sassmaps;

      function generateSassMapsRecursive(data) {
        var key;
        var currentItem = "";
        var first = true;
        var sassMapStr = "";
        var currentValue;

        for (key in data) {
          if (data.hasOwnProperty(key)) {
            if (mout.lang.isObject(data[key])) {
              currentValue = generateSassMapsRecursive(data[key]);
            } else {
              currentValue = getStyleSafeValue(data[key]);
            }

            currentItem = pattern.replace("{{key}}", key).replace("{{value}}", currentValue);

            if (first) {
              sassMapStr = indent("\n" + currentItem, options.indention);
              first = false;
            } else {
              sassMapStr = sassMapStr + indent("\n" + currentItem, options.indention);
            }

            sassMapStr = sassMapStr.replace(",\n" + options.indention + ")", "\n" + options.indention + ")");
          }
        }

        // the slice removes the last comma
        return "(" + sassMapStr.slice(0, -1) + "\n)";
      }

      return "$" + options.name + ": " + generateSassMapsRecursive(data).replace(/,\)/g, ")") + ";";

    }

    function prepareValues(data) {
      var newData = {};

      function updateValues(object, newData) {
        for (var key in object) {
          if (object.hasOwnProperty(key)) {
            var value = object[key];

            if (mout.lang.isObject(value)) {
              var newKey = format(key, options.jsFormat);

              newData[newKey] = {};
              updateValues(value, newData[newKey]);

              continue;

            } else if (mout.string.endsWith(value, "%")) {
              value = parseInt(value, 10) / 100;

            } else if (isStringNumber(value)) {
              value = parseInt(value, 10);

            } else if (isStringExpression(value)) {
              value = value.substr(1, value.length - 2);

            }

            newData[format(key, options.jsFormat)] = value;

          }
        }
      }

      updateValues(data, newData);

      return newData;
    }

    function indent(content, indention) {
      content = content.replace(/\n/g, "\n" + indention);

      while (mout.string.endsWith(content, options.indention)) {
        content = content.substr(0, content.length - 1);
      }

      return content;
    }

    function getLevelsFromObject(src, numberOfLevels) {
      var result = {};

      if (numberOfLevels === 0) return result;

      if (typeof src !== "object") return src;

      for (var key in src) {

        if (numberOfLevels === 1) {

          // only add it to result if it's not an object
          // we don't want empty objects in the result
          if (typeof src[key] !== "object") {

            result[key] = src[key];

          }

        } else {

          result[key] = getLevelsFromObject(src[key], numberOfLevels - 1);

        }
      }

      return result;
    }

    function maskObject(src, mask, allowLevel, round) {
      var result = {};

      // check for every key in src, if it should end up in the result
      for (var key in src) {

        // if this property is in the mask too, check that
        if (mask.hasOwnProperty(key)) {

          // if this mask is an object, send it through maskObject again
          if (typeof mask[key] === "object") {

            // we allow to include unknown objects only on the root level
            // on every other level, you can just use "true"
            result[key] = maskObject(src[key], mask[key], allowLevel, round + 1);

          } else {

            // true, include everything in result
            if (mask[key] === true) {

              result[key] = src[key];

            } else {

              // if the mask value starts with 'allowLevel-' we get the number after '-' and allow as many levels
              if (typeof mask[key] === "string" && mask[key].split("-")[0] === "allowLevel") {

                var numberOfLevels = parseInt(mask[key].split("-")[1], 10);

                if (isNaN(numberOfLevels)) {

                  grunt.log.error("invalid mask value: " + mask[key]);

                } else {

                  result[key] = getLevelsFromObject(src[key], numberOfLevels);

                }

              } else if (mask[key] !== false) {

                grunt.log.error("invalid mask value: " + mask[key]);

              }
            }
          }
          // otherwise we only include it, if other first level object should end up in the result
        } else if (allowLevel > round) {

          result[key] = src[key];

        }
      }

      return result;
    }

    // ===================
    // -- SHARED CONFIG --
    // ===================

    this.files.forEach(function (file) {

      var srcConfig = {};
      var destinationFiles = normalizeOutArray(file.dest);
      var mask = normalizeMask(options.mask);

      file.src.filter(fileExists).forEach(function (filePath) {

        mout.object.deepMixIn(srcConfig, readFile(filePath));

      });

      if (mask !== null) {

        srcConfig = maskObject(srcConfig, mask, options.maskAllowUnknownLevels, 0);

      }

      if (Object.keys(srcConfig).length === 0) {
        grunt.log.warn("Empty src results in no output");
        return false;
      }

      destinationFiles.map(function (filePath) {

        var fileType = filePath.split(".").pop().toLowerCase();
        var output, generator;

        if (fileType === "scss" && options.useSassMaps) {

          generator = generateSassMaps;

        } else if (mout.array.contains(fileExtensions.css, fileType)) {

          generator = generateStyle;

        } else if (mout.array.contains(fileExtensions.js, fileType)) {

          if (options.amd) {

            generator = generateAMD;

          } else if (options.ngconstant) {

            generator = generateNGConstant;

          } else {

            generator = generateJS;
          }

        } else {
          grunt.log.warn("Unknown filetype (" + fileType + ").");
          return false;
        }

        output = generator.apply(null, [srcConfig, fileType]);
        grunt.file.write(filePath, output);

        grunt.log.ok("File: " + filePath + " created.");
      });

    });

  });

};
<commit_msg>Deprecation warning for the "shared_config" task<commit_after>/*
 * grunt-shared-config
 *
 * Use this task to create multiple config files for JS/JS-AMD, SCSS/SASS/LESS/stylus from one JSON/YAML.
 *
 * Copyright (c) 2013 Mathias Paumgarten
 * Licensed under the MIT license.
 */

var mout = require("mout");

module.exports = function (grunt) {
  "use strict";

  grunt.registerMultiTask("sharedConfig", "Your task description goes here.", function createSharedConfigCTask() {

    // ===========
    // -- UTILS --
    // ===========

    function normalizeOutArray(value) {
      return typeof value === "string" ? [value] : value;
    }

    function normalizeFormat(value) {
      return mout.array.contains(varFormats, value) ? value : varFormats[0];
    }

    function normalizeMask(mask) {
      if (mask === null) return null;

      if (mout.lang.isString(mask) && fileExists(mask)) return readFile(mask);
      else if (mout.lang.isObject(mask)) return mask;
      else if (mout.lang.isArray(mask)) {

        return mask.reduce(function (previous, current) {
          return mout.object.deepMixIn(previous, normalizeMask(current));
        }, {});

      }

      return {};
    }

    function format(value, type) {
      value = value.replace(/-/g, " ");

      switch (type) {
        case "underscore":
          return mout.string.underscore(value);
        case "uppercase":
          return value.toUpperCase().replace(/ /g, "_");
        case "dash":
          return mout.string.hyphenate(value);
        default:
          return mout.string.camelCase(value);
      }
    }

    function fileExists(filePath) {
      if (!grunt.file.exists(filePath)) {
        grunt.log.warn("Source file (" + filePath + ") not found.");
        return false;
      }
      return true;
    }

    function readFile(filePath) {
      var fileType = filePath.split(".").pop().toLowerCase();

      return ( ( fileType === "yml" || fileType === "yaml" ) ? grunt.file.readYAML : grunt.file.readJSON )(filePath);
    }

    function isStringNumber(value) {
      var units = ["em", "px", "s", "in", "mm", "cm", "pt", "pc", "%"];

      return units.reduce(function (previous, current) {
        return previous || mout.string.endsWith(value, current);
      }, false);
    }

    function isPathExpression(value) {
      return new RegExp(
        "^(" +
          // full URL
          /// protocol identifier
        "(?:(?:https?|ftp)://)" +
          /// user:pass authentication
        "(?:\\S+(?::\\S*)?@)?" +
        "(?:" +
          /// IP address exclusion
          /// private & local networks
        "(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
        "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
        "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
          /// IP address dotted notation octets
          /// excludes loopback network 0.0.0.0
          /// excludes reserved space >= 224.0.0.0
          /// excludes network & broacast addresses
          /// (first & last IP address of each class)
        "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
        "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
        "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
        "|" +
          /// host name
        "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
          /// domain name
        "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
          /// TLD identifier
        "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
        ")" +
          /// port number
        "(?::\\d{2,5})?" +
          /// resource path
        "(?:/\\S*)?" +
        "|" +
          /// or PATH
        "([\\w\\/]?(?:\\/[\\w\\.\\-]+)+)" +
        ")$", "i"
      ).test(value);
    }

    function isBooleanExpression(value) {
      return (/^true$/i).test(value);
    }

    function isStringExpression(value) {
      return (/^[\'\"].*[\'\"]$/i).test(value);
    }

    function getStyleSafeValue(value) {
      if (isStringExpression(value)) {
        value = "\"" + value.substr(1, value.length - 2) + "\"";
      } else if (isPathExpression(value)) {
        value = "\"" + value + "\"";
      } else if (isBooleanExpression(value) && typeof value === "string") {
        value = "\"" + value + "\"";
      }

      return value;
    }

    // ==============
    // -- SETTINGS --
    // ==============

    // default options
    var options = this.options({
      ngconstant: false,
      amd: false,
      jsFormat: "uppercase",
      cssFormat: "dash",
      singlequote: false,
      name: "config",
      module: "config",
      useSassMaps: false,
      indention: "\t",
      mask: undefined,
      maskAllowUnknownLevels: 0
    });

    // possible variable formats
    var varFormats = ["underscore", "uppercase", "dash", "camelcase"];

    // available file extensions
    var fileExtensions = {
      js: ["js"],
      css: ["scss", "sass", "less", "styl"]
    };

    // variable patterns
    var outputPattern = {
      scss: "${{key}}: {{value}};\n",
      sass: "${{key}}: {{value}}\n",
      less: "@{{key}}: {{value}};\n",
      sassmaps: "{{key}}: {{value}},",
      styl: "{{key}} = {{value}}\n",
      amd: "define( function() {\n\n" + options.indention + "return {{{vars}}" + options.indention + "}\n\n} );\n",
      ngconstant: "angular.module(\"{{module}}\", [])\n" + options.indention + ".constant(\"{{name}}\", {{{vars}}" + options.indention + "});",
      js: "var {{name}} = {{vars}};\n"
    };

    // Normalize user input
    options.dest = normalizeOutArray(options.dest);
    options.jsFormat = normalizeFormat(options.jsFormat);
    options.cssFormat = normalizeFormat(options.cssFormat);

    // ================
    // -- GENERATORS --
    // ================

    // Generate Style files
    function generateStyle(data, type) {
      var content = "";
      var pattern = outputPattern[type];

      function resolveNested(data, parentKey) {
        var name, key;
        for (key in data) {
          if (data.hasOwnProperty(key)) {
            name = parentKey ? format(parentKey + "-" + key, options.cssFormat) : format(key, options.cssFormat);

            if (mout.lang.isObject(data[key])) {

              resolveNested(data[key], name);

            } else {

              var value = getStyleSafeValue(data[key]);

              content += pattern.replace("{{key}}", name).replace("{{value}}", value);
            }
          }
        }
      }

      resolveNested(data);

      return content;
    }

    // Generate JavaScript files
    function generateJS(data) {
      var preparedData = prepareValues(data);
      var content = JSON.stringify(preparedData, null, options.indention);

      var output = outputPattern.js.replace("{{name}}", options.name).replace("{{vars}}", content);
      return options.singlequote ? output.replace(/"/g, '\'') : output;
    }

    function generateAMD(data) {
      var preparedData = prepareValues(data);
      var content = JSON.stringify(preparedData, null, options.indention);
      var pattern = mout.lang.deepClone(outputPattern.amd);

      content = content.substr(1, content.length - 2);
      content = indent(content, options.indention);

      return pattern.replace("{{vars}}", content);
    }

    function generateNGConstant(data) {
      var preparedData = prepareValues(data);
      var content = JSON.stringify(preparedData, null, options.indention);
      var pattern = mout.lang.deepClone(outputPattern.ngconstant);

      content = content.substr(1, content.length - 2);
      content = indent(content, options.indention);

      var output = pattern.replace("{{module}}", options.module)
        .replace(/\{\{name\}\}/g, options.name).replace("{{vars}}", content);

      return options.singlequote ? output.replace(/"/g, '\'') : output;
    }

    function generateSassMaps(data) {
      var pattern = outputPattern.sassmaps;

      function generateSassMapsRecursive(data) {
        var key;
        var currentItem = "";
        var first = true;
        var sassMapStr = "";
        var currentValue;

        for (key in data) {
          if (data.hasOwnProperty(key)) {
            if (mout.lang.isObject(data[key])) {
              currentValue = generateSassMapsRecursive(data[key]);
            } else {
              currentValue = getStyleSafeValue(data[key]);
            }

            currentItem = pattern.replace("{{key}}", key).replace("{{value}}", currentValue);

            if (first) {
              sassMapStr = indent("\n" + currentItem, options.indention);
              first = false;
            } else {
              sassMapStr = sassMapStr + indent("\n" + currentItem, options.indention);
            }

            sassMapStr = sassMapStr.replace(",\n" + options.indention + ")", "\n" + options.indention + ")");
          }
        }

        // the slice removes the last comma
        return "(" + sassMapStr.slice(0, -1) + "\n)";
      }

      return "$" + options.name + ": " + generateSassMapsRecursive(data).replace(/,\)/g, ")") + ";";

    }

    function prepareValues(data) {
      var newData = {};

      function updateValues(object, newData) {
        for (var key in object) {
          if (object.hasOwnProperty(key)) {
            var value = object[key];

            if (mout.lang.isObject(value)) {
              var newKey = format(key, options.jsFormat);

              newData[newKey] = {};
              updateValues(value, newData[newKey]);

              continue;

            } else if (mout.string.endsWith(value, "%")) {
              value = parseInt(value, 10) / 100;

            } else if (isStringNumber(value)) {
              value = parseInt(value, 10);

            } else if (isStringExpression(value)) {
              value = value.substr(1, value.length - 2);

            }

            newData[format(key, options.jsFormat)] = value;

          }
        }
      }

      updateValues(data, newData);

      return newData;
    }

    function indent(content, indention) {
      content = content.replace(/\n/g, "\n" + indention);

      while (mout.string.endsWith(content, options.indention)) {
        content = content.substr(0, content.length - 1);
      }

      return content;
    }

    function getLevelsFromObject(src, numberOfLevels) {
      var result = {};

      if (numberOfLevels === 0) return result;

      if (typeof src !== "object") return src;

      for (var key in src) {

        if (numberOfLevels === 1) {

          // only add it to result if it's not an object
          // we don't want empty objects in the result
          if (typeof src[key] !== "object") {

            result[key] = src[key];

          }

        } else {

          result[key] = getLevelsFromObject(src[key], numberOfLevels - 1);

        }
      }

      return result;
    }

    function maskObject(src, mask, allowLevel, round) {
      var result = {};

      // check for every key in src, if it should end up in the result
      for (var key in src) {

        // if this property is in the mask too, check that
        if (mask.hasOwnProperty(key)) {

          // if this mask is an object, send it through maskObject again
          if (typeof mask[key] === "object") {

            // we allow to include unknown objects only on the root level
            // on every other level, you can just use "true"
            result[key] = maskObject(src[key], mask[key], allowLevel, round + 1);

          } else {

            // true, include everything in result
            if (mask[key] === true) {

              result[key] = src[key];

            } else {

              // if the mask value starts with 'allowLevel-' we get the number after '-' and allow as many levels
              if (typeof mask[key] === "string" && mask[key].split("-")[0] === "allowLevel") {

                var numberOfLevels = parseInt(mask[key].split("-")[1], 10);

                if (isNaN(numberOfLevels)) {

                  grunt.log.error("invalid mask value: " + mask[key]);

                } else {

                  result[key] = getLevelsFromObject(src[key], numberOfLevels);

                }

              } else if (mask[key] !== false) {

                grunt.log.error("invalid mask value: " + mask[key]);

              }
            }
          }
          // otherwise we only include it, if other first level object should end up in the result
        } else if (allowLevel > round) {

          result[key] = src[key];

        }
      }

      return result;
    }

    // ===================
    // -- SHARED CONFIG --
    // ===================

    this.files.forEach(function (file) {

      var srcConfig = {};
      var destinationFiles = normalizeOutArray(file.dest);
      var mask = normalizeMask(options.mask);

      file.src.filter(fileExists).forEach(function (filePath) {

        mout.object.deepMixIn(srcConfig, readFile(filePath));

      });

      if (mask !== null) {

        srcConfig = maskObject(srcConfig, mask, options.maskAllowUnknownLevels, 0);

      }

      if (Object.keys(srcConfig).length === 0) {
        grunt.log.warn("Empty src results in no output");
        return false;
      }

      destinationFiles.map(function (filePath) {

        var fileType = filePath.split(".").pop().toLowerCase();
        var output, generator;

        if (fileType === "scss" && options.useSassMaps) {

          generator = generateSassMaps;

        } else if (mout.array.contains(fileExtensions.css, fileType)) {

          generator = generateStyle;

        } else if (mout.array.contains(fileExtensions.js, fileType)) {

          if (options.amd) {

            generator = generateAMD;

          } else if (options.ngconstant) {

            generator = generateNGConstant;

          } else {

            generator = generateJS;
          }

        } else {
          grunt.log.warn("Unknown filetype (" + fileType + ").");
          return false;
        }

        output = generator.apply(null, [srcConfig, fileType]);
        grunt.file.write(filePath, output);

        grunt.log.ok("File: " + filePath + " created.");
      });

    });

  });

  grunt.registerMultiTask('shared_config', 'DEPRECATED TASK. Use "sharedConfig" instead', function () {
    grunt.log.warn('DEPRECATED TASK. Use "sharedConfig" instead.');
  });

};
<|endoftext|>


<commit_before>/*
 * grunt-traceur-build
 * https://github.com/tarruda/grunt-traceur-build
 *
 * Copyright (c) 2013 Thiago de Arruda
 * Licensed under the MIT license.
 */

'use strict';
var spawn = require('child_process').spawn;
var path = require('path');

var traceur = require('traceur');

// this hack is needed because the traceur developers have made the
// command line compiler modules private. without this we won't get
// the automatic dependency resolution done by parsing the modules
// 'import' statements.
var modPath = path.resolve('node_modules/traceur/src/node/inline-module');
var inlineAndCompileSync = require(modPath).inlineAndCompileSync;

var TreeWriter = traceur.outputgeneration.TreeWriter;
var SourceMapGenerator = traceur.outputgeneration.SourceMapGenerator;
var TestErrorReporter = traceur.util.TestErrorReporter;
var Project = traceur.semantics.symbols.Project;
var SourceFile = traceur.syntax.SourceFile;

var NAME = 'traceur_build';
var DESC =
  'Compiles ECMAScript 6 (harmony) files, optionally merging and ' +
  'generating source maps.';

function generateIncludeFile(files) {
  var rv = [];
  files.forEach(function(f) {
    rv.push('module ' + traceur.generateNameForUrl(f) + ' from "' + f + '"');
  });
  return rv.join('\n');
}

function wrapClosure(code, param, expression, sourceMapGenerator) {
    code = '(function(' + (param || 'global') + ') {\n' + code;
    code = code + '}(' + (expression || 'this') + ')();\n';
    if (sourceMapGenerator) {
      // adjust the mappings
      sourceMapGenerator._mappings.forEach(function(mapping) {
        mapping.generated.line++;
      });
    }
    return code;
}

function buildToDirectory(grunt, options, f) {
  // Iterate over all specified file groups.
  var asts, currentDir;
  var reporter = new TestErrorReporter();
  var project = new traceur.semantics.symbols.Project(f.dest);
  var cwd = f.orig.cwd || '.';

  f.src.filter(function(filepath) {
    if (!grunt.file.exists(filepath)) {
      grunt.log.warn('Source file "' + filepath + '" not found.');
      return false;
    } else {
      return true;
    }
  }).map(function(filepath) {
    var sourceFile = new traceur.syntax.SourceFile(path.relative(cwd, filepath),
      grunt.file.read(filepath));
    project.addFile(sourceFile);
  });

  currentDir = process.cwd();
  process.chdir(cwd);
  asts = traceur.codegeneration.Compiler.compile(reporter, project);
  process.chdir(currentDir);

  if (reporter.hadError()) {
    grunt.log.error('Compilation error!');
    reporter.errors.forEach(function(e) {
      grunt.log.error(e);
    });
    return false;
  }

  asts.keys().forEach(function(file) {
    var ast, code, treeWriteOpts, sourceMapGenerator;
    var sourceMapDest, sourceMapRoot, sourceMapConfig;
    var outFile = f.dest;
    var outDir = path.dirname(outFile);

    ast = asts.get(file);

    if (options.sourceMaps) {
      sourceMapDest = outFile + '.map';
      sourceMapRoot = path.relative(outDir, cwd);
      sourceMapConfig = {
        file: path.relative(outDir, outFile),
        sourceRoot: sourceMapRoot
      };
      sourceMapGenerator = new SourceMapGenerator(sourceMapConfig);
      treeWriteOpts = {sourceMapGenerator: sourceMapGenerator};
    }

    code = TreeWriter.write(ast, treeWriteOpts);

    if (options.wrap) {
      code = wrapClosure(code, options.wrap.param, options.wrap.expression,
        sourceMapGenerator);
    }

    if (options.sourceMaps) {
      code += '\n//@ sourceMappingURL=' + path.relative(outDir, sourceMapDest);
      grunt.file.write(sourceMapDest, treeWriteOpts.sourceMap);
    }

    grunt.file.write(outFile, code);
    grunt.log.writeln('File "' + outFile + '" created.');
  });
}

function buildToFile(grunt, options, f) {
  var reporter, ast, files, currentDir, includeData;
  var code, writeOpts, sourceMapGenerator;
  var sourceMapDest, sourceMapRoot, sourceMapConfig;
  var outFile = f.dest;
  var outDir = path.dirname(outFile);
  var cwd = f.cwd || '.';
  // use a temporary helper file that imports all other files to use the
  // default traceur compilation routine
  var include = path.join(cwd, '.includejs.tmp~');
  files = f.src;
  includeData = generateIncludeFile(files);
  grunt.file.write(include, includeData);
  reporter = new TestErrorReporter();
  currentDir = process.cwd();
  process.chdir(cwd);
  ast = inlineAndCompileSync([path.basename(include)], null, reporter);
  process.chdir(currentDir);
  grunt.file.delete(include);

  if (reporter.hadError()) {
    grunt.log.error('Compilation error!');
    reporter.errors.forEach(function(e) {
      grunt.log.error(e);
    });
    return false;
  }

  if (options.sourceMaps) {
    sourceMapDest = outFile + '.map';
    sourceMapRoot = path.relative(outDir, cwd);
    sourceMapConfig = {
      file: path.relative(outDir, outFile),
      sourceRoot: sourceMapRoot
    };
    sourceMapGenerator = new SourceMapGenerator(sourceMapConfig);
    writeOpts = {sourceMapGenerator: sourceMapGenerator};
  }

  code = TreeWriter.write(ast, writeOpts).split('\n');
  // remove the lines added by the include helper
  code = code.slice(0, code.length - includeData.split('\n').length - 1);
  code = code.join('\n');
  code += '\n';

  if (options.wrap) {
    code = wrapClosure(code, options.wrap.param, options.wrap.expression,
      sourceMapGenerator);
  }

  if (options.sourceMaps) {
    code += '\n//@ sourceMappingURL=' + path.relative(outDir, sourceMapDest);
    grunt.file.write(sourceMapDest, writeOpts.sourceMap);
  }

  grunt.file.write(outFile, code);
  grunt.log.writeln('File "' + outFile + '" created.');
}

module.exports = function(grunt) {
  grunt.registerMultiTask(NAME, DESC, function() {
    var options = this.options({
      debug: false,
      sourceMaps: true,
      freeVariableChecker: true,
      validate: false,
      strictSemicolons: false,
      unstarredGenerators: false,
      ignoreNolint: false,
      //
      arrayComprehension: true,
      arrowFunctions: true,
      classes: true,
      defaultParameters: true,
      destructuring: true,
      forOf: true,
      propertyMethods: true,
      propertyNameShorthand: true,
      templateLiterals: true,
      restParameters: true,
      spread: true,
      generatorComprehension: true,
      generators: true,
      modules: true,
      blockBinding: false,
      privateNameSyntax: false,
      privateNames: false,
      cascadeExpression: false,
      trapMemberLookup: false,
      deferredFunctions: false,
      propertyOptionalComma: false,
      types: false
    });

    traceur.options.reset();

    for (var k in options) {
      if (k in traceur.options) traceur.options[k] = options[k];
    }

    this.files.forEach(function(f) {
      if (/\.js$/.test(f.orig.dest)) {
        buildToFile(grunt, options, f);
      } else {
        buildToDirectory(grunt, options, f);
      }
    });
  });
};
<commit_msg>Fix traceur private module hack<commit_after>/*
 * grunt-traceur-build
 * https://github.com/tarruda/grunt-traceur-build
 *
 * Copyright (c) 2013 Thiago de Arruda
 * Licensed under the MIT license.
 */

'use strict';
var spawn = require('child_process').spawn;
var path = require('path');

var traceur = require('traceur');

// this hack is needed because the traceur developers have made the
// command line compiler modules private. without this we won't get
// the automatic dependency resolution done by parsing the modules
// 'import' statements.
try {
  var modPath = path.resolve('node_modules/grunt-traceur-build/node_modules/traceur/src/node/inline-module');
} catch (e) {
  var modPath = path.resolve('node_modules/traceur/src/node/inline-module');
}
var inlineAndCompileSync = require(modPath).inlineAndCompileSync;

var TreeWriter = traceur.outputgeneration.TreeWriter;
var SourceMapGenerator = traceur.outputgeneration.SourceMapGenerator;
var TestErrorReporter = traceur.util.TestErrorReporter;
var Project = traceur.semantics.symbols.Project;
var SourceFile = traceur.syntax.SourceFile;

var NAME = 'traceur_build';
var DESC =
  'Compiles ECMAScript 6 (harmony) files, optionally merging and ' +
  'generating source maps.';

function generateIncludeFile(files) {
  var rv = [];
  files.forEach(function(f) {
    rv.push('module ' + traceur.generateNameForUrl(f) + ' from "' + f + '"');
  });
  return rv.join('\n');
}

function wrapClosure(code, param, expression, sourceMapGenerator) {
    code = '(function(' + (param || 'global') + ') {\n' + code;
    code = code + '}(' + (expression || 'this') + ')();\n';
    if (sourceMapGenerator) {
      // adjust the mappings
      sourceMapGenerator._mappings.forEach(function(mapping) {
        mapping.generated.line++;
      });
    }
    return code;
}

function buildToDirectory(grunt, options, f) {
  // Iterate over all specified file groups.
  var asts, currentDir;
  var reporter = new TestErrorReporter();
  var project = new traceur.semantics.symbols.Project(f.dest);
  var cwd = f.orig.cwd || '.';

  f.src.filter(function(filepath) {
    if (!grunt.file.exists(filepath)) {
      grunt.log.warn('Source file "' + filepath + '" not found.');
      return false;
    } else {
      return true;
    }
  }).map(function(filepath) {
    var sourceFile = new traceur.syntax.SourceFile(path.relative(cwd, filepath),
      grunt.file.read(filepath));
    project.addFile(sourceFile);
  });

  currentDir = process.cwd();
  process.chdir(cwd);
  asts = traceur.codegeneration.Compiler.compile(reporter, project);
  process.chdir(currentDir);

  if (reporter.hadError()) {
    grunt.log.error('Compilation error!');
    reporter.errors.forEach(function(e) {
      grunt.log.error(e);
    });
    return false;
  }

  asts.keys().forEach(function(file) {
    var ast, code, treeWriteOpts, sourceMapGenerator;
    var sourceMapDest, sourceMapRoot, sourceMapConfig;
    var outFile = f.dest;
    var outDir = path.dirname(outFile);

    ast = asts.get(file);

    if (options.sourceMaps) {
      sourceMapDest = outFile + '.map';
      sourceMapRoot = path.relative(outDir, cwd);
      sourceMapConfig = {
        file: path.relative(outDir, outFile),
        sourceRoot: sourceMapRoot
      };
      sourceMapGenerator = new SourceMapGenerator(sourceMapConfig);
      treeWriteOpts = {sourceMapGenerator: sourceMapGenerator};
    }

    code = TreeWriter.write(ast, treeWriteOpts);

    if (options.wrap) {
      code = wrapClosure(code, options.wrap.param, options.wrap.expression,
        sourceMapGenerator);
    }

    if (options.sourceMaps) {
      code += '\n//@ sourceMappingURL=' + path.relative(outDir, sourceMapDest);
      grunt.file.write(sourceMapDest, treeWriteOpts.sourceMap);
    }

    grunt.file.write(outFile, code);
    grunt.log.writeln('File "' + outFile + '" created.');
  });
}

function buildToFile(grunt, options, f) {
  var reporter, ast, files, currentDir, includeData;
  var code, writeOpts, sourceMapGenerator;
  var sourceMapDest, sourceMapRoot, sourceMapConfig;
  var outFile = f.dest;
  var outDir = path.dirname(outFile);
  var cwd = f.cwd || '.';
  // use a temporary helper file that imports all other files to use the
  // default traceur compilation routine
  var include = path.join(cwd, '.includejs.tmp~');
  files = f.src;
  includeData = generateIncludeFile(files);
  grunt.file.write(include, includeData);
  reporter = new TestErrorReporter();
  currentDir = process.cwd();
  process.chdir(cwd);
  ast = inlineAndCompileSync([path.basename(include)], null, reporter);
  process.chdir(currentDir);
  grunt.file.delete(include);

  if (reporter.hadError()) {
    grunt.log.error('Compilation error!');
    reporter.errors.forEach(function(e) {
      grunt.log.error(e);
    });
    return false;
  }

  if (options.sourceMaps) {
    sourceMapDest = outFile + '.map';
    sourceMapRoot = path.relative(outDir, cwd);
    sourceMapConfig = {
      file: path.relative(outDir, outFile),
      sourceRoot: sourceMapRoot
    };
    sourceMapGenerator = new SourceMapGenerator(sourceMapConfig);
    writeOpts = {sourceMapGenerator: sourceMapGenerator};
  }

  code = TreeWriter.write(ast, writeOpts).split('\n');
  // remove the lines added by the include helper
  code = code.slice(0, code.length - includeData.split('\n').length - 1);
  code = code.join('\n');
  code += '\n';

  if (options.wrap) {
    code = wrapClosure(code, options.wrap.param, options.wrap.expression,
      sourceMapGenerator);
  }

  if (options.sourceMaps) {
    code += '\n//@ sourceMappingURL=' + path.relative(outDir, sourceMapDest);
    grunt.file.write(sourceMapDest, writeOpts.sourceMap);
  }

  grunt.file.write(outFile, code);
  grunt.log.writeln('File "' + outFile + '" created.');
}

module.exports = function(grunt) {
  grunt.registerMultiTask(NAME, DESC, function() {
    var options = this.options({
      debug: false,
      sourceMaps: true,
      freeVariableChecker: true,
      validate: false,
      strictSemicolons: false,
      unstarredGenerators: false,
      ignoreNolint: false,
      //
      arrayComprehension: true,
      arrowFunctions: true,
      classes: true,
      defaultParameters: true,
      destructuring: true,
      forOf: true,
      propertyMethods: true,
      propertyNameShorthand: true,
      templateLiterals: true,
      restParameters: true,
      spread: true,
      generatorComprehension: true,
      generators: true,
      modules: true,
      blockBinding: false,
      privateNameSyntax: false,
      privateNames: false,
      cascadeExpression: false,
      trapMemberLookup: false,
      deferredFunctions: false,
      propertyOptionalComma: false,
      types: false
    });

    traceur.options.reset();

    for (var k in options) {
      if (k in traceur.options) traceur.options[k] = options[k];
    }

    this.files.forEach(function(f) {
      if (/\.js$/.test(f.orig.dest)) {
        buildToFile(grunt, options, f);
      } else {
        buildToDirectory(grunt, options, f);
      }
    });
  });
};
<|endoftext|>


<commit_before>define(['app', 'underscore',
 '/app/services/role-service.js',
 '/app/views/register/directives/register-top-menu.js'],
function(app, _) {
    "use strict";
    app.controller("DashboardController", ["$rootScope", "$scope", "IStorage", "roleService", "$compile", "realm", "$q",
                    "$routeParams", '$location', "$filter", "$http", "$element","$timeout",
        function($rootScope, $scope, storage, roleService, $compile, realm, $q, $routeParams, $location, $filter, $http, $element, $timeout) {

            var schemaFacets = {};

            $timeout(function(){
                $element.find('[data-toggle="tooltip"]').tooltip();
            },50);

            //====================================================================================
            $scope.isFilter = function(filter) {
                return $scope.dashboardFilter == filter || $scope.dashboardFilter == "All";
            }

            $scope.user = $rootScope.user;

            if ($scope.user.isAuthenticated) {
                $scope.roles = {
                    isAbsPublishingAuthority : roleService.isAbsPublishingAuthority(),
                    isAbsNationalFocalPoint  : roleService.isAbsNationalFocalPoint(),
                    isAbsAdministrator       : roleService.isAbsAdministrator(),
                    isAdministrator          : roleService.isAdministrator(),
                    isAbsNationalAuthorizedUser : roleService.isAbsNationalAuthorizedUser(),
                    isUser                      : roleService.isUser()
                };

                if($scope.user.government)
                    $scope.userCountry = {identifier:$scope.user.government };

            }

            $scope.gotoNew = function($event, cftype) {
                $event.stopPropagation();
                $location.path("/register/" + $filter("mapSchema")(cftype) + "/new");
            }

            $scope.gotoList = function($event, cftype) {
                $location.path("/register/" + $filter("mapSchema")(cftype));
            }

            //===================================================================
            $scope.facets = function(schema, type){

                if (schemaFacets[schema]) {
                    return schemaFacets[schema][type+'Count']||0;
                }
                else return 0;
            };

            function init(){
                $scope.isNationalUser = roleService.hasAbsRoles();
                loadFacets();
            }

            function loadFacets() {
                //  var fromStorage = localStorageService.get('documentRegisterFacets');
                // if(fromStorage)
                //     return fromStorage;

                var published = storage.documentQuery.facets("", {collection: "my"});
                var drafts = storage.documentQuery.facets("", {collection: "mydraft"});
                var requests = storage.documentQuery.facets("", {collection: "request"});

                $q.all([published, drafts, requests]).then(function(results) {

                    var index = 0;
                    _.each(results, function(facets) {
                        _.each(facets.data, function(count, format) {

                            if (!schemaFacets[format])
                                schemaFacets[format] = {};

                            if (index == 0)
                                schemaFacets[format].publishCount = count;
                            else if (index == 1)
                                schemaFacets[format].draftCount = count;
                            else if (index == 2)
                                schemaFacets[format].requestCount = count;
                        })
                        index++;
                    });

                }).then(null, function(error) {
                    toastr.error("error loading facets.");
                    console.log(error);
                })
            }

            init();
        }
    ]);
});
<commit_msg>add dependency to  controler<commit_after>define(['app', 'underscore',
 '/app/services/role-service.js',
 '/app/views/register/directives/register-top-menu.js', 'toastr'],
function(app, _) {
    "use strict";
    app.controller("DashboardController", ["$rootScope", "$scope", "IStorage", "roleService", "$compile", "realm", "$q",
                    "$routeParams", '$location', "$filter", "$http", "$element","$timeout", 'toastr',
        function($rootScope, $scope, storage, roleService, $compile, realm, $q, $routeParams, $location, $filter, $http, $element, $timeout, toastr) {

            var schemaFacets = {};

            $timeout(function(){
                $element.find('[data-toggle="tooltip"]').tooltip();
            },50);

            //====================================================================================
            $scope.isFilter = function(filter) {
                return $scope.dashboardFilter == filter || $scope.dashboardFilter == "All";
            }

            $scope.user = $rootScope.user;

            if ($scope.user.isAuthenticated) {
                $scope.roles = {
                    isAbsPublishingAuthority : roleService.isAbsPublishingAuthority(),
                    isAbsNationalFocalPoint  : roleService.isAbsNationalFocalPoint(),
                    isAbsAdministrator       : roleService.isAbsAdministrator(),
                    isAdministrator          : roleService.isAdministrator(),
                    isAbsNationalAuthorizedUser : roleService.isAbsNationalAuthorizedUser(),
                    isUser                      : roleService.isUser()
                };

                if($scope.user.government)
                    $scope.userCountry = {identifier:$scope.user.government };

            }

            $scope.gotoNew = function($event, cftype) {
                $event.stopPropagation();
                $location.path("/register/" + $filter("mapSchema")(cftype) + "/new");
            }

            $scope.gotoList = function($event, cftype) {
                $location.path("/register/" + $filter("mapSchema")(cftype));
            }

            //===================================================================
            $scope.facets = function(schema, type){

                if (schemaFacets[schema]) {
                    return schemaFacets[schema][type+'Count']||0;
                }
                else return 0;
            };

            function init(){
                $scope.isNationalUser = roleService.hasAbsRoles();
                loadFacets();
            }

            function loadFacets() {
                //  var fromStorage = localStorageService.get('documentRegisterFacets');
                // if(fromStorage)
                //     return fromStorage;

                var published = storage.documentQuery.facets("", {collection: "my"});
                var drafts = storage.documentQuery.facets("", {collection: "mydraft"});
                var requests = storage.documentQuery.facets("", {collection: "request"});

                $q.all([published, drafts, requests]).then(function(results) {

                    var index = 0;
                    _.each(results, function(facets) {
                        _.each(facets.data, function(count, format) {

                            if (!schemaFacets[format])
                                schemaFacets[format] = {};

                            if (index == 0)
                                schemaFacets[format].publishCount = count;
                            else if (index == 1)
                                schemaFacets[format].draftCount = count;
                            else if (index == 2)
                                schemaFacets[format].requestCount = count;
                        })
                        index++;
                    });

                }).then(null, function(error) {
                    toastr.error("error loading facets.");
                    console.log(error);
                })
            }

            init();
        }
    ]);
});
<|endoftext|>


<commit_before>define(['app', '/app/views/directives/xuser-notifications.js',
'/app/views/directives/switch-realm-directive.html.js'
], function (app) {
"use strict";
app.controller("DashboardController",
	["$rootScope", "$scope", "underscore", "lstringFilter","IWorkflows","realm","$q","$routeParams",'$location',"$filter","$http",
	function ($rootScope, $scope, _, lstringFilter,workflows,realm,$q,$routeParams, $location, $filter,$http) {

    //intro.js configurations
	$scope.startTour=false;

    if($routeParams.tour)
    {
        $scope.startTour=true;
        $location.search("tour", null);
    }
    $scope.introOptions = {
      steps: [
        {
          intro: "Welcome to the introduction the ABSCH Dashboard. When the page is fully loaded click 'Next ->' to start the tour.",
        },
		{
          element: '#dashboard_panels',
          intro: 'Use these panels to get an overview of your documents and requests, as well as view the detail lists of requests.',
        },
        {
          element: '#myTabContent',
          intro: 'This feed give an overview of the activities of all members.',
        },
        {
          element: '#document_type_links',
          intro: 'To create a new document or view and edit current documents, select the type of document you want work with here.',
          position: 'right',
        },
        {
          element: '.label',
          intro: 'These labels describe the number of documents in each phase.
Green is published
Gray is draft
Red is Requests',
          position: 'right',
        },
      ],
    };

//============================================================
	$scope.PAroles= [$scope.$root.getRoleName('AbsPublishingAuthorities'), $scope.$root.getRoleName('AbsNationalFocalPoint'),
					$scope.$root.getRoleName('AbsAdministrator'),$scope.$root.getRoleName('Administrator')];
	//console.log($scope.PAroles);
	 $scope.compareRoles = function(array1, array2) {

		if(!array1) return false;
		if(!array2) return false;

		for(var i=0; i < array1.length; i++){
			for(var j=0; j < array2.length; j++){
				if(array1[i] == array2[j])
					return true;
			}
		}
    };

//============================================================

  //TODO: this is almost identical to type_document_list.html.js... inherit them

	$scope.dashboardFilter = "All";

 	$scope.setDashFilter = function(filter){
 			$scope.dashboardFilter = filter;
 	}

 	$scope.isFilter = function(filter){
 			return	$scope.dashboardFilter == filter || $scope.dashboardFilter == "All";
 	}

	if($rootScope.user.isAuthenticated){
	    // var myUserID = $scope.$root.user.userID;
	    // var query    = {
	    //             $and : [
	    //                 { "createdBy" : myUserID },
	    //                 { closedOn : { $exists : true } },
	    //                 { "data.realm" : realm.value }
	    //             ]
	    //         };
	    // $q.when(workflows.query(query), function(data){
		//
		// 	$scope.completedRequests = data;
		//
		// 	for(var i=0; i < data.length; i++){
		// 		for(var j=0; j < data[i].activities.length; j++){
		//
		// 			if(data[i].activities[j].result && data[i].activities[j].result.action == 'reject')
		// 				$scope.rejectedRequests++;
		//
		// 			if(data[i].activities[j].result && data[i].activities[j].result.action == 'approve')
		// 					$scope.approvedRequests++;
		// 		}
		// 	}
		//
		//
	    // });
		//
		// query    = {
		// 			$and : [
		// 				{ "createdBy" : myUserID } ,
		// 				{ closedOn : { $exists : false } },
		// 				{ "data.realm" : realm.value }
		// 			]
		// 		};
	    // $q.when(workflows.query(query), function(data){
		//     $scope.pendingCount  = data.length;
	    // });
		//
		// query    = {
		// 		$and : [
		// 			{ "activities.assignedTo" : myUserID },
		// 			{ closedOn : { $exists : false } },
		// 			{ "data.realm" : realm.value }
		// 		]
		// 	};
	    // $q.when(workflows.query(query), function(data){
		// 	$scope.urgentAttentionCount = data.length;
	    // });

		$scope.$emit('loadActivities','dashboard');
		$http.get("/api/v2013/thesaurus/terms?termCode=" + $scope.user.government, {
                cache: true
        }).then(function(result) {
            $scope.userCountry = $filter("lstring")(result.data.title);
        });
	}

	$scope.approvedRequests = 0;
	$scope.rejectedRequests = 0;
	$scope.completedRequestCount = 0;
	$scope.pendingCount = 0;
	$scope.urgentAttentionCount = 0;

}]);
});
<commit_msg>remove tour option from dashboard page<commit_after>define(['app', '/app/views/directives/xuser-notifications.js',
'/app/views/directives/switch-realm-directive.html.js'
], function (app) {
"use strict";
app.controller("DashboardController",
	["$rootScope", "$scope", "underscore", "lstringFilter","IWorkflows","realm","$q","$routeParams",'$location',"$filter","$http",
	function ($rootScope, $scope, _, lstringFilter,workflows,realm,$q,$routeParams, $location, $filter,$http) {

//============================================================
	$scope.PAroles= [$scope.$root.getRoleName('AbsPublishingAuthorities'), $scope.$root.getRoleName('AbsNationalFocalPoint'),
					$scope.$root.getRoleName('AbsAdministrator'),$scope.$root.getRoleName('Administrator')];
	//console.log($scope.PAroles);
	 $scope.compareRoles = function(array1, array2) {

		if(!array1) return false;
		if(!array2) return false;

		for(var i=0; i < array1.length; i++){
			for(var j=0; j < array2.length; j++){
				if(array1[i] == array2[j])
					return true;
			}
		}
    };

//============================================================

  //TODO: this is almost identical to type_document_list.html.js... inherit them

	$scope.dashboardFilter = "All";

 	$scope.setDashFilter = function(filter){
 			$scope.dashboardFilter = filter;
 	}

 	$scope.isFilter = function(filter){
 			return	$scope.dashboardFilter == filter || $scope.dashboardFilter == "All";
 	}

	if($rootScope.user.isAuthenticated){
	    // var myUserID = $scope.$root.user.userID;
	    // var query    = {
	    //             $and : [
	    //                 { "createdBy" : myUserID },
	    //                 { closedOn : { $exists : true } },
	    //                 { "data.realm" : realm.value }
	    //             ]
	    //         };
	    // $q.when(workflows.query(query), function(data){
		//
		// 	$scope.completedRequests = data;
		//
		// 	for(var i=0; i < data.length; i++){
		// 		for(var j=0; j < data[i].activities.length; j++){
		//
		// 			if(data[i].activities[j].result && data[i].activities[j].result.action == 'reject')
		// 				$scope.rejectedRequests++;
		//
		// 			if(data[i].activities[j].result && data[i].activities[j].result.action == 'approve')
		// 					$scope.approvedRequests++;
		// 		}
		// 	}
		//
		//
	    // });
		//
		// query    = {
		// 			$and : [
		// 				{ "createdBy" : myUserID } ,
		// 				{ closedOn : { $exists : false } },
		// 				{ "data.realm" : realm.value }
		// 			]
		// 		};
	    // $q.when(workflows.query(query), function(data){
		//     $scope.pendingCount  = data.length;
	    // });
		//
		// query    = {
		// 		$and : [
		// 			{ "activities.assignedTo" : myUserID },
		// 			{ closedOn : { $exists : false } },
		// 			{ "data.realm" : realm.value }
		// 		]
		// 	};
	    // $q.when(workflows.query(query), function(data){
		// 	$scope.urgentAttentionCount = data.length;
	    // });

		$scope.$emit('loadActivities','dashboard');
		$http.get("/api/v2013/thesaurus/terms?termCode=" + $scope.user.government, {
                cache: true
        }).then(function(result) {
            $scope.userCountry = $filter("lstring")(result.data.title);
        });
	}

	$scope.approvedRequests = 0;
	$scope.rejectedRequests = 0;
	$scope.completedRequestCount = 0;
	$scope.pendingCount = 0;
	$scope.urgentAttentionCount = 0;

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


<commit_before>'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const fireworm = require('fireworm');
const Bluebird = require('bluebird');

const Config = require('../lib/config');
const App = require('../lib/app');
const RunTimeout = require('../lib/utils/run-timeout');

const FakeReporter = require('./support/fake_reporter');

describe('App', function() {
  let app, config, sandbox;

  beforeEach(function() {
    sandbox = sinon.createSandbox();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('triggerRun', function() {
    let finish;
    beforeEach(function(done) {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        if (finish) { finish(); }
        else { done(); }
      });
      sandbox.spy(app, 'triggerRun');
      sandbox.spy(app, 'stopRunners');
      sandbox.stub(app, 'singleRun').callsFake(function() {
        return Bluebird.resolve().delay(50);
      });
      app.once('testRun', done);
      app.start();
    });

    afterEach(function(done) {
      finish = done;
      app.exit();
    });

    it('triggers a run on start', function() {
      expect(app.triggerRun.calledWith('Start')).to.be.true();
    });

    it('can only be executed once at the same time', function() {
      app.currentRun = Bluebird.resolve();

      app.triggerRun('one');
      app.triggerRun('two');
      expect(app.stopRunners).to.have.been.calledOnce();
    });
  });

  describe('singleRun', function() {
    let runner;
    beforeEach(function() {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config);
      runner = {
        start: function() {
          return Bluebird.resolve().delay(100).then(function() {
            if (this.killed) {
              throw new Error('Killed');
            }

            return;
          }.bind(this));
        },
        exit: function() {
          this.killed = true;

          return Bluebird.resolve();
        }
      };
      app.runners = [runner];

      sandbox.spy(runner, 'start');
      sandbox.spy(runner, 'exit');
    });

    it('times out slow runners', function() {
      return Bluebird.using(RunTimeout.with(0.005), function(timeout) {
        timeout.on('timeout', function() {
          app.killRunners();
        });

        return app.singleRun(timeout);
      }).then(function() {
        expect('Should never be called').to.be.true();
      }, function(err) {
        expect(err.message).to.eq('Killed');
        expect(err.hideFromReporter).not.to.exist();
        expect(runner.start).to.have.been.called();
        expect(runner.exit).to.have.been.called();
      });
    });

    it('doesn\'t start additional runners when timed out', function() {
      return Bluebird.using(RunTimeout.with(0), function(timeout) {
        timeout.on('timeout', function() {
          app.killRunners();
        });
        timeout.setTimedOut();

        return app.singleRun(timeout);
      }).then(function() {
        expect('Should never be called').to.be.true();
      }, function(err) {
        expect(err.message).to.eq('Run timed out.');
        expect(err.hideFromReporter).not.to.exist();
        expect(runner.start).to.not.have.been.called();
        expect(runner.exit).to.have.been.called();
      });
    });

    it('resolves when restarting', function() {
      app.restarting = true;

      return Bluebird.using(RunTimeout.with(app.config.get('timeout')), function(timeout) {
        timeout.on('timeout', function() {
          app.killRunners();
        });
        return app.singleRun(timeout);
      }).then(function() {
        expect(runner.start).to.not.have.been.called();
        expect(runner.exit).to.not.have.been.called();
      });
    });

    it('rejects when exiting', function() {
      app.exited = true;

      return Bluebird.using(RunTimeout.with(app.config.get('timeout')), function(timeout) {
        timeout.timedOut = true;
        timeout.on('timeout', function() {
          app.killRunners();
        });
        return app.singleRun(timeout);
      }).then(function() {
        expect('Should never be called').to.be.true();
      }, function(err) {
        expect(err.message).to.eq('Run canceled.');
        expect(err.hideFromReporter).to.be.true();
        expect(runner.start).to.not.have.been.called();
        expect(runner.exit).to.not.have.been.called();
      });
    });
  });

  describe('pause running', function() {
    beforeEach(function(done) {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config, function() {});
      app.start(done);
    });

    afterEach(function(done) {
      app.exit(null, done);
    });

    it('starts off not paused', function() {
      expect(app.paused).to.be.false();
    });

    it('doesn\'t run tests when reset and paused', function() {
      app.paused = true;
      let runHook = sandbox.spy(app, 'runHook');

      return app.runTests().then(function() {
        expect(runHook.called).to.be.false();
      });
    });

    it('runs tests when reset and not paused', function() {
      let runHook = sandbox.spy(app, 'runHook');

      return app.runTests().then(function() {
        expect(runHook.called).to.be.true();
      });
    });
  });

  describe('file watching', function() {
    beforeEach(function() {
      sandbox.stub(Config.prototype, 'readConfigFile').callsFake(function(file, cb) {
        cb();
      });
    });

    it('adds a watch', function(done) {
      let add = sandbox.spy(fireworm.prototype, 'add');
      let srcFiles = ['test.js'];
      config = new Config('dev', {}, {
        src_files: srcFiles,
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        done();
      });
      app.start(function() {
        expect(add.getCall(0).args[0]).to.eq(srcFiles);
        app.exit();
      });
    });

    it('triggers a test run on change', function(done) {
      let srcFiles = ['test.js'];
      config = new Config('dev', {}, {
        src_files: srcFiles,
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        done();
      });
      app.start(function() {
        sandbox.spy(app, 'triggerRun');
        app.fileWatcher.onFileChanged.call(app.fileWatcher, 'test.js');
        expect(app.triggerRun.calledWith('File changed: test.js')).to.be.true();
        app.exit();
      });
    });

    it('creates no watcher', function(done) {
      config = new Config('dev', {}, {
        src_files: ['test.js'],
        disable_watching: true,
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        done();
      });
      app.start(function() {
        expect(app.fileWatcher).to.eq(undefined);
        app.exit();
      });
    });
  });

  describe('start', function() {
    let finish;
    let onExitCb;
    let onExitFinished;

    beforeEach(function() {
      onExitFinished = false;
      onExitCb = sinon.stub().callsFake(function(config, data, callback) {
        setTimeout(function() {
          callback(null);
          onExitFinished = true;
        }, 10);
      });
      config = new Config('dev', {}, {
        reporter: new FakeReporter(),
        on_exit: onExitCb
      });
      app = new App(config, function() {
        expect(onExitCb.called).to.be.true();
        expect(onExitFinished).to.be.true();
        finish();
      });
      app.once('testRun', app.exit);
    });

    it('calls on_exit hook on success', function(done) {
      finish = done;
      sandbox.stub(app, 'waitForTests').usingPromise(Bluebird.Promise).resolves();
      app.start();
    });

    it('calls on_exit hook on failure and waits for it to finish', function(done) {
      finish = done;
      sandbox.stub(app, 'waitForTests').usingPromise(Bluebird.Promise).rejects();
      app.start();
    });
  });

  describe('onBrowserRelogin', function() {
    let tryAttachCalled;

    beforeEach(function() {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config);
      tryAttachCalled = false;
      app.runners = [
        {
          launcherId: 1,
          socket: {},
          tryAttach: () => {
            tryAttachCalled = true;
          }
        },
        {
          launcherId: 2,
          socket: null,
          tryAttach: () => {
            tryAttachCalled = true;
          }
        },
        {
          launcherId: 3,
          tryAttach: () => {
            tryAttachCalled = true;
          }
        }
      ];
    });

    it('does not call tryAttach for an existing browser with existing socket', function() {
      app.onBrowserRelogin('fakeBrowser', 2, {});
      expect(tryAttachCalled).to.be.false();
    });

    it('calls tryAttach for an existing browser with null socket', function() {
      app.onBrowserRelogin('fakeBrowser', 1, {});
      expect(tryAttachCalled).to.be.true();
    });
  });
});
<commit_msg>Fix bad tests<commit_after>'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const fireworm = require('fireworm');
const Bluebird = require('bluebird');

const Config = require('../lib/config');
const App = require('../lib/app');
const RunTimeout = require('../lib/utils/run-timeout');

const FakeReporter = require('./support/fake_reporter');

describe('App', function() {
  let app, config, sandbox;

  beforeEach(function() {
    sandbox = sinon.createSandbox();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('triggerRun', function() {
    let finish;
    beforeEach(function(done) {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        if (finish) { finish(); }
        else { done(); }
      });
      sandbox.spy(app, 'triggerRun');
      sandbox.spy(app, 'stopRunners');
      sandbox.stub(app, 'singleRun').callsFake(function() {
        return Bluebird.resolve().delay(50);
      });
      app.once('testRun', done);
      app.start();
    });

    afterEach(function(done) {
      finish = done;
      app.exit();
    });

    it('triggers a run on start', function() {
      expect(app.triggerRun.calledWith('Start')).to.be.true();
    });

    it('can only be executed once at the same time', function() {
      app.currentRun = Bluebird.resolve();

      app.triggerRun('one');
      app.triggerRun('two');
      expect(app.stopRunners).to.have.been.calledOnce();
    });
  });

  describe('singleRun', function() {
    let runner;
    beforeEach(function() {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config);
      runner = {
        start: function() {
          return Bluebird.resolve().delay(100).then(function() {
            if (this.killed) {
              throw new Error('Killed');
            }

            return;
          }.bind(this));
        },
        exit: function() {
          this.killed = true;

          return Bluebird.resolve();
        }
      };
      app.runners = [runner];

      sandbox.spy(runner, 'start');
      sandbox.spy(runner, 'exit');
    });

    it('times out slow runners', function() {
      return Bluebird.using(RunTimeout.with(0.005), function(timeout) {
        timeout.on('timeout', function() {
          app.killRunners();
        });

        return app.singleRun(timeout);
      }).then(function() {
        expect('Should never be called').to.be.true();
      }, function(err) {
        expect(err.message).to.eq('Killed');
        expect(err.hideFromReporter).not.to.exist();
        expect(runner.start).to.have.been.called();
        expect(runner.exit).to.have.been.called();
      });
    });

    it('doesn\'t start additional runners when timed out', function() {
      return Bluebird.using(RunTimeout.with(0), function(timeout) {
        timeout.on('timeout', function() {
          app.killRunners();
        });
        timeout.setTimedOut();

        return app.singleRun(timeout);
      }).then(function() {
        expect('Should never be called').to.be.true();
      }, function(err) {
        expect(err.message).to.eq('Run timed out.');
        expect(err.hideFromReporter).not.to.exist();
        expect(runner.start).to.not.have.been.called();
        expect(runner.exit).to.have.been.called();
      });
    });

    it('resolves when restarting', function() {
      app.restarting = true;

      return Bluebird.using(RunTimeout.with(app.config.get('timeout')), function(timeout) {
        timeout.on('timeout', function() {
          app.killRunners();
        });
        return app.singleRun(timeout);
      }).then(function() {
        expect(runner.start).to.not.have.been.called();
        expect(runner.exit).to.not.have.been.called();
      });
    });

    it('rejects when exiting', function() {
      app.exited = true;

      return Bluebird.using(RunTimeout.with(app.config.get('timeout')), function(timeout) {
        timeout.timedOut = true;
        timeout.on('timeout', function() {
          app.killRunners();
        });
        return app.singleRun(timeout);
      }).then(function() {
        expect('Should never be called').to.be.true();
      }, function(err) {
        expect(err.message).to.eq('Run canceled.');
        expect(err.hideFromReporter).to.be.true();
        expect(runner.start).to.not.have.been.called();
        expect(runner.exit).to.not.have.been.called();
      });
    });
  });

  describe('pause running', function() {
    beforeEach(function(done) {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config, function() {});
      app.start(done);
    });

    afterEach(function(done) {
      app.exit(null, done);
    });

    it('starts off not paused', function() {
      expect(app.paused).to.be.false();
    });

    it('doesn\'t run tests when reset and paused', function() {
      app.paused = true;
      let runHook = sandbox.spy(app, 'runHook');

      return app.runTests().then(function() {
        expect(runHook.called).to.be.false();
      });
    });

    it('runs tests when reset and not paused', function() {
      let runHook = sandbox.spy(app, 'runHook');

      return app.runTests().then(function() {
        expect(runHook.called).to.be.true();
      });
    });
  });

  describe('file watching', function() {
    beforeEach(function() {
      sandbox.stub(Config.prototype, 'readConfigFile').callsFake(function(file, cb) {
        cb();
      });
    });

    it('adds a watch', function(done) {
      let add = sandbox.spy(fireworm.prototype, 'add');
      let srcFiles = ['test.js'];
      config = new Config('dev', {}, {
        src_files: srcFiles,
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        done();
      });
      app.start(function() {
        expect(add.getCall(0).args[0]).to.eq(srcFiles);
        app.exit();
      });
    });

    it('triggers a test run on change', function(done) {
      let srcFiles = ['test.js'];
      config = new Config('dev', {}, {
        src_files: srcFiles,
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        done();
      });
      app.start(function() {
        sandbox.spy(app, 'triggerRun');
        app.fileWatcher.onFileChanged.call(app.fileWatcher, 'test.js');
        expect(app.triggerRun.calledWith('File changed: test.js')).to.be.true();
        app.exit();
      });
    });

    it('creates no watcher', function(done) {
      config = new Config('dev', {}, {
        src_files: ['test.js'],
        disable_watching: true,
        reporter: new FakeReporter()
      });
      app = new App(config, function() {
        done();
      });
      app.start(function() {
        expect(app.fileWatcher).to.eq(undefined);
        app.exit();
      });
    });
  });

  describe('start', function() {
    let finish;
    let onExitCb;
    let onExitFinished;

    beforeEach(function() {
      onExitFinished = false;
      onExitCb = sinon.stub().callsFake(function(config, data, callback) {
        setTimeout(function() {
          callback(null);
          onExitFinished = true;
        }, 10);
      });
      config = new Config('dev', {}, {
        reporter: new FakeReporter(),
        on_exit: onExitCb
      });
      app = new App(config, function() {
        expect(onExitCb.called).to.be.true();
        expect(onExitFinished).to.be.true();
        finish();
      });
      app.once('testRun', app.exit);
    });

    it('calls on_exit hook on success', function(done) {
      finish = done;
      sandbox.stub(app, 'waitForTests').usingPromise(Bluebird.Promise).resolves();
      app.start();
    });

    it('calls on_exit hook on failure and waits for it to finish', function(done) {
      finish = done;
      sandbox.stub(app, 'waitForTests').usingPromise(Bluebird.Promise).rejects();
      app.start();
    });
  });

  describe('onBrowserRelogin', function() {
    let tryAttachCalled;

    beforeEach(function() {
      config = new Config('dev', {}, {
        reporter: new FakeReporter()
      });
      app = new App(config);
      tryAttachCalled = false;
      app.runners = [
        {
          launcherId: 1,
          socket: {},
          tryAttach: () => {
            tryAttachCalled = true;
          },
          clearTimeouts: () => { }
        },
        {
          launcherId: 2,
          socket: null,
          tryAttach: () => {
            tryAttachCalled = true;
          },
          clearTimeouts: () => { }
        },
        {
          launcherId: 3,
          tryAttach: () => {
            tryAttachCalled = true;
          },
          clearTimeouts: () => { }
        }
      ];
    });

    it('does not call tryAttach for an existing browser with existing socket', function() {
      app.onBrowserRelogin('fakeBrowser', 1, {});
      expect(tryAttachCalled).to.be.false();
    });

    it('calls tryAttach for an existing browser with null socket', function() {
      app.onBrowserRelogin('fakeBrowser', 2, {});
      expect(tryAttachCalled).to.be.true();
    });
  });
});
<|endoftext|>


<commit_before>require('babel/register');

var test = require('tape'),
    futureValue = require('../src/futureValue');

test('calculate futureValue', function(t) {
  t.plan(3);

// $1000 invested for 5 years with simple annual interest of 10% would have a future value of $1,500.00.

  var calc1 = futureValue({
    compounding: false,
    rate: 0.10,
    principal: 1000,
    years: 5
  });

  t.equal(calc1, 1500, 'correctly calculates future Value with simple interest');

  var calc2 = futureValue({
    compounding: false,
    rate: 0.10,
    principal: 1000,
    years: 6
  });

  t.equal(calc2, 1600, 'correctly calculates future Value with simple interest');

  var calc3 = futureValue({
    compounding: true,
    rate: 0.10,
    principal: 1000,
    years: 5
  });

  // Original Investment x ((1+interest rate)^number of years);
  // 1000 * ((1+0.10)^5)
  t.equal(calc3, 1610.51, 'correctly calculates future value with compound interest');

});
<commit_msg>add test for compound interest<commit_after>require('babel/register');

var test = require('tape'),
    futureValue = require('../src/futureValue');

test('calculate futureValue', function(t) {

  t.plan(4);
// $1000 invested for 5 years with simple annual interest of 10% would have a future value of $1,500.00.

  var calc1 = futureValue({
    compounding: false,
    rate: 0.10,
    principal: 1000,
    years: 5
  });

  t.equal(calc1, 1500, 'correctly calculates future Value with simple interest');

  var calc2 = futureValue({
    compounding: false,
    rate: 0.10,
    principal: 1000,
    years: 6
  });

  t.equal(calc2, 1600, 'correctly calculates future Value with simple interest');

  var calc3 = futureValue({
    compounding: true,
    rate: 0.10,
    numberOfCompounds: 1,
    principal: 1000,
    years: 5
  });

  // Original Investment x ((1+interest rate)^number of years);
  // 1000 * ((1+0.10)^5)
  t.equal(calc3, 1610.51, 'correctly calculates future value with compound interest');

  var calc4 = futureValue({
    compounding: true,
    rate: 0.10,
    numberOfCompounds: 4,
    principal: 1000,
    years: 5
  });

  t.equal(calc4, 1638.62, 'correctly calculates future value with compound interest' );

});
<|endoftext|>


<commit_before>var assert = require('assert'),
  SandboxedModule = require('sandboxed-module'),
  SandboxedModuleBlanket = require('../'),
  moduleUnderTest = 'fixture',
  blanket = require('blanket')({
    pattern: moduleUnderTest
  });

var fixture = SandboxedModule.load('./' + moduleUnderTest, {
  sourceTransformers: SandboxedModuleBlanket
}).exports;

var instrumentedSource = fixture.answer.toString();

assert(instrumentedSource.indexOf(global._blanket.getCovVar()) !== -1);
assert(instrumentedSource.indexOf(moduleUnderTest) !== -1);

<commit_msg>Add test to verify blanket.js instrumentation is missing without this module<commit_after>var assert = require('assert'),
  SandboxedModule = require('sandboxed-module'),
  SandboxedModuleBlanket = require('../'),
  moduleUnderTest = 'fixture',
  blanket = require('blanket')({
    pattern: moduleUnderTest
  });

// Verify sandboxed-module does not provide blanket code coverage instrumentation on its own
var fixtureWithoutBlanket = SandboxedModule.load('./' + moduleUnderTest).exports;
var instrumentedSourceWithoutBlanket = fixtureWithoutBlanket.answer.toString();

assert(instrumentedSourceWithoutBlanket.indexOf(global._blanket.getCovVar()) === -1);
assert(instrumentedSourceWithoutBlanket.indexOf(moduleUnderTest) === -1);

// Verify sandboxed-module + sandboxed-module-blanket provides blanket code coverage instrumentation
var fixtureWithBlanket = SandboxedModule.load('./' + moduleUnderTest, {
  sourceTransformers: SandboxedModuleBlanket
}).exports;
var instrumentedSourceWithBlanket = fixtureWithBlanket.answer.toString();

assert(instrumentedSourceWithBlanket.indexOf(global._blanket.getCovVar()) !== -1);
assert(instrumentedSourceWithBlanket.indexOf(moduleUnderTest) !== -1);

<|endoftext|>


<commit_before>import 'should';
import fs from 'fs';
import nock from 'nock';
import wiki from '../src/wiki';

describe('Dublin page integration', () => {

  let dublin;
  before(done => {
    nock('http://en.wikipedia.org')
      .get('/w/api.php?prop=info%7Cpageprops&inprop=url&ppprop=disambiguation'
         + '&titles=Dublin&format=json&action=query&redirects=&origin=*')
      .once()
      .reply(200, JSON.parse(fs.readFileSync('./test/data/dublin-page.json')));

    const opts = {
      parser: {
        simplifyDataValues: false
      }
    }

    wiki(opts).page('Dublin')
    .then((page) => {
      dublin = page
      done()
    })
    .catch(done)
  });

  after(() => {
    nock.cleanAll();
    nock.enableNetConnect();
  });

  it('should get Dublins info', () => {
    nock('http://en.wikipedia.org')
      .get('/w/api.php?prop=revisions&rvprop=content&rvsection=0'
         + '&titles=Dublin&format=json&action=query&redirects=&origin=*')
      .once()
      .reply(200, JSON.parse(fs.readFileSync('./test/data/dublin-info.json')));

    return dublin.info().then((info) => {
      info.name.should.equal('Dublin');
      info.gdp.should.equal('American dollar 90.1 billion');
      info.populationTotal.should.equal(553165)
    });
  });

});

<commit_msg>Fixed other test<commit_after>import 'should';
import fs from 'fs';
import nock from 'nock';
import wiki from '../src/wiki';

describe('Dublin page integration', () => {

  let dublin;
  before(done => {
    nock('http://en.wikipedia.org')
      .get('/w/api.php')
      .query({
        prop: 'info|pageprops',
        inprop: 'url',
        ppprop: 'disambiguation',
        titles: 'Dublin',
        format: 'json',
        action: 'query',
        redirects: '',
        origin: '*'
      })
      .once()
      .reply(200, JSON.parse(fs.readFileSync('./test/data/dublin-page.json')));

    const opts = {
      parser: {
        simplifyDataValues: false
      }
    }

    wiki(opts).page('Dublin')
    .then((page) => {
      dublin = page
      done()
    })
    .catch(done)
  });

  after(() => {
    nock.cleanAll();
    nock.enableNetConnect();
  });

  it('should get Dublins info', () => {
    nock('http://en.wikipedia.org')
      .get('/w/api.php')
      .query({
        prop: 'revisions',
        rvprop: 'content',
        rvsection: '0',
        titles: 'Dublin',
        format: 'json',
        action: 'query',
        redirects: '',
        origin: '*'
      })
      .once()
      .reply(200, JSON.parse(fs.readFileSync('./test/data/dublin-info.json')));

    return dublin.info().then((info) => {
      info.name.should.equal('Dublin');
      info.gdp.should.equal('American dollar 90.1 billion');
      info.populationTotal.should.equal(553165)
    });
  });

});

<|endoftext|>


<commit_before>/*
 Might be able to replace this and parent_pipe.py with npm package python-shell
   or python-runner

*/

var _ = require('underscore');
var child_process = require('child_process');
var logio = require('../web/logio');
var WebSocketHelper = require('../web/WebSocketHelper');

exports.ChildJsonPipe = ChildJsonPipe;
exports.setupJsonIn = setupJsonIn;
exports.sendJsonOut = sendJsonOut;
exports.mkChildProcessRpc = mkChildProcessRpc;

var verbose = 1;

function ChildJsonPipe(execName, execArgs, execOptions) {
  var m = this;

  var child = child_process.spawn(execName, execArgs, _.extend({stdio: ['pipe', 'pipe', 'inherit']}, execOptions));

  m.child = child;
  m.queue = [];
  var datas=[];
  m.child.stdout.on('data', function(buf) {
    while (buf.length) {
      var eol = buf.indexOf(10); // newline
      if (eol < 0) {
        datas.push(buf);
        return;
      } else {
        datas.push(buf.slice(0, eol));
        var rep = JSON.parse(datas.join(''));
        datas = [];
        var repCb = m.queue.shift();
        repCb.apply(null, rep);
        buf = buf.slice(eol+1);
      }
    }
  });
  m.child.on('close', function(code, signal) {
    logio.I('child', 'close, code=', code, 'signal=', signal);
    m.child = null;
  });
}

ChildJsonPipe.prototype.rpc = function(req, repCb) {
  var m = this;
  m.queue.push(repCb);
  m.child.stdin.write(JSON.stringify(req));
  m.child.stdin.write('\n');
}

function setupJsonIn(stream, cb) {
  var datas=[];
  stream.on('data', function(buf) {
    while (buf.length) {
      var eol = buf.indexOf(10); // newline
      if (eol < 0) {
        datas.push(buf);
        return;
      } else {
        datas.push(buf.slice(0, eol));
        var rep = JSON.parse(datas.join(''));
        datas = [];
        cb(null, rep);
        buf = buf.slice(eol+1);
      }
    }
  });
}

function sendJsonOut(stream, obj) {
  stream.write(JSON.stringify(obj));
  stream.write('\n');
}

function mkChildProcessRpc(execCmd, execArgs, handlers) {
  var pending = new WebSocketHelper.RpcPendingQueue();
  var callbacks = {};

  var child = child_process.spawn(execCmd, execArgs, {stdio: ['pipe', 'pipe', 'inherit']});
  var label = execCmd + ' ' + execArgs.join(' ');
  setupPipe();
  setupHandlers();
  return handlers;

  function setupPipe() {

    setupJsonIn(child.stdout, function(err, msg) {
      if (err) {
        logio.E(label, err);
        if (handlers.close) handlers.close();
      }
      if (msg.cmdReq) {
        var cmdFunc = handlers['cmd_' + msg.cmdReq];
        if (!cmdFunc) {
          logio.E(label, 'Unknown cmd', msg.cmdReq);
          return;
        }
        cmdFunc.apply(handlers, msg.cmdArgs);
      }
      else if (msg.rpcReq) {
        var reqFunc = handlers['req_' + msg.rpcReq];
        if (!reqFunc) {
          logio.E(label, 'Unknown rpcReq', msg.rpcReq);
          return;
        }
        var done = false;
        try {
          reqFunc.apply(handlers, msg.rpcArgs.concat([function(/* ... */) {
            var rpcRet = Array.prototype.slice.call(arguments, 0);
            done = true;
            handlers.tx({ rpcId: msg.rpcId, rpcRet: rpcRet });
          }]));
        } catch(ex) {
          if (!done) {
            done = true;
            handlers.tx({ rpcId: msg.rpcId, rpcRet: [ex.toString()] });
          }
        }
      }
      else if (msg.rpcId) {
        var rpcCb = callbacks[msg.rpcId];
        if (!rpcCb) rpcCb = pending.get(msg.rpcId);
        if (!rpcCb) {
          logio.E(label, 'Unknown response', msg.rpcId);
          return;
        }
        if (verbose >= 2) logio.I(label, 'rpcId=', msg.rpcId, 'rpcRet=', msg.rpcRet)
        rpcCb.apply(handlers, msg.rpcRet);
      }

      else if (msg.hello) {
        handlers.hello = msg.hello;
        if (handlers.onHello) handlers.onHello();
      }
      else {
        if (verbose >= 1) logio.E(label, 'Unknown message', msg);
      }
    });

    child.on('close', function(code, signal) {
      logio.I(label, 'close, code=', code, 'signal=', signal);
      child = null;
    });
  }

  function setupHandlers() {
    handlers.cmd = function(cmdReq /* ... */) {
      var cmdArgs = Array.prototype.slice.call(arguments, 1);
      handlers.tx({cmdReq: cmdReq, cmdArgs: cmdArgs});
    };
    handlers.rpc = function(rpcReq /* ... */) {
      var rpcId = pending.getNewId();
      var rpcArgs = Array.prototype.slice.call(arguments, 1, arguments.length - 1);
      var rpcCb = arguments[arguments.length - 1];
      if (verbose >= 2) logio.O(label, 'rpcReq=', rpcReq, 'rpcArgs=', rpcArgs)

      pending.add(rpcId, rpcCb);
      handlers.tx({rpcReq: rpcReq, rpcId: rpcId, rpcArgs: rpcArgs});
    };
    handlers.callback = function(rpcReq /* ... */) {
      var rpcId = pending.getNewId();
      var rpcCb = arguments[arguments.length - 1];
      var rpcArgs = Array.prototype.slice.call(arguments, 1, arguments.length - 1);
      callbacks[rpcId] = rpcCb;
      handlers.tx({rpcReq: rpcReq, rpcId: rpcId, rpcArgs: rpcArgs});
    };
    handlers.tx = function(msg) {
      sendJsonOut(child.stdin, msg);
    };
    handlers.shutdown = function() {
      shutdownRequested = true;
      logio.O(label, 'Closing pipe');
      if (child && child.stdin) {
        child.stdin.end();
      }
    };
    handlers.pending = pending;
    handlers.getPendingCount = function() {
      return pending.pendingCount;
    };
  }
}
<commit_msg>Delete child_pipe.js<commit_after><|endoftext|>


<commit_before>Tester.checkLeaks(false);

describe('<editor-console>', function() {
    var consoleEL;
    beforeEach(function ( done ) {
        Editor.sendToCore('console:clear');
        fixture('panel', function (el) {
            consoleEL = el;
            done();
        });
    });
    after(function () {
        Editor.sendToCore('console:clear');
    });

    var delay = 50;

    it('should recv clear log when press command+k', function( done ) {
        Tester.send( 'console:log', 'foo bar' );
        Tester.send( 'console:log', 'foo bar 02' );
        Tester.send( 'console:log', 'foo bar 03' );
        Tester.send( 'console:log', 'foo bar 04' );
        setTimeout( function () {
            Tester.keyDownOn( consoleEL, 'k', 'command' );
            expect( consoleEL.logs.length ).to.equal(0);

            done();
        }, delay);
    });
});
<commit_msg>update tests<commit_after>Tester.checkLeaks(false);

describe('<editor-console>', function() {
    var consoleEL;
    beforeEach(function ( done ) {
        Editor.sendToCore('console:clear');
        fixture('panel', function (el) {
            consoleEL = el;
            done();
        });
    });
    after(function () {
        Editor.sendToCore('console:clear');
    });

    var delay = 50;

    it('should recv clear log when press command+k', function( done ) {
        Tester.send( 'console:log', 'foo bar' );
        Tester.send( 'console:log', 'foo bar 02' );
        Tester.send( 'console:log', 'foo bar 03' );
        Tester.send( 'console:log', 'foo bar 04' );
        setTimeout( function () {
            Tester.keydown( consoleEL, 'k', 'command' );
            expect( consoleEL.logs.length ).to.equal(0);

            done();
        }, delay);
    });
});
<|endoftext|>


<commit_before>describe("The constructor is supposed a proper Biom object", function() {
    it('Constructor Biom exists', function(){
        var biomObject = {
            "id": "No Table ID",
            "format": "Biological Observation Matrix 2.1.0",
            "format_url": "http://biom-format.org",
            "matrix_type": "sparse",
            "generated_by": "BIOM-Format 2.1",
            "date": "2016-05-03T08:13:41.848780",
            "type": "OTU table",
            "matrix_element_type": "float",
            "shape": [10, 5],
            "data": [[0,0,120.0],[3,1,12.0],[5,2,20.0],[7,3,12.7],[8,4,16.0]],
            "rows": [
                {"id": "OTU_1", "metadata": {}},
                {"id": "OTU_2", "metadata": {}},
                {"id": "OTU_3", "metadata": {}},
                {"id": "OTU_4", "metadata": {}},
                {"id": "OTU_5", "metadata": {}},
                {"id": "OTU_6", "metadata": {}},
                {"id": "OTU_7", "metadata": {}},
                {"id": "OTU_8", "metadata": {}},
                {"id": "OTU_9", "metadata": {}},
                {"id": "OTU_10", "metadata": {}}
            ],
            "columns": [
                {"id": "Sample_1", "metadata": {}},
                {"id": "Sample_2", "metadata": {}},
                {"id": "Sample_3", "metadata": {}},
                {"id": "Sample_4", "metadata": {}},
                {"id": "Sample_5", "metadata": {}}
            ]
        };
        var biom = new Biom(biomObject);
        expect(biom).toBeDefined();
    });
});

<commit_msg>Add test for checking if biom object contains an id. The test fails<commit_after>describe("The constructor is supposed a proper Biom object", function() {
    it('Constructor Biom exists', function(){
        var biomObject = {
            "id": "No Table ID",
            "format": "Biological Observation Matrix 2.1.0",
            "format_url": "http://biom-format.org",
            "matrix_type": "sparse",
            "generated_by": "BIOM-Format 2.1",
            "date": "2016-05-03T08:13:41.848780",
            "type": "OTU table",
            "matrix_element_type": "float",
            "shape": [10, 5],
            "data": [[0,0,120.0],[3,1,12.0],[5,2,20.0],[7,3,12.7],[8,4,16.0]],
            "rows": [
                {"id": "OTU_1", "metadata": {}},
                {"id": "OTU_2", "metadata": {}},
                {"id": "OTU_3", "metadata": {}},
                {"id": "OTU_4", "metadata": {}},
                {"id": "OTU_5", "metadata": {}},
                {"id": "OTU_6", "metadata": {}},
                {"id": "OTU_7", "metadata": {}},
                {"id": "OTU_8", "metadata": {}},
                {"id": "OTU_9", "metadata": {}},
                {"id": "OTU_10", "metadata": {}}
            ],
            "columns": [
                {"id": "Sample_1", "metadata": {}},
                {"id": "Sample_2", "metadata": {}},
                {"id": "Sample_3", "metadata": {}},
                {"id": "Sample_4", "metadata": {}},
                {"id": "Sample_5", "metadata": {}}
            ]
        };
        var biom = new Biom(biomObject);
        expect(biom).toBeDefined();
    });
    it('Throws error message if biom object does not contain an id', function(){
        var biomObject = {
            "format": "Biological Observation Matrix 2.1.0",
            "format_url": "http://biom-format.org",
            "matrix_type": "sparse",
            "generated_by": "BIOM-Format 2.1",
            "date": "2016-05-03T08:13:41.848780",
            "type": "OTU table",
            "matrix_element_type": "float",
            "shape": [10, 5],
            "data": [[0,0,120.0],[3,1,12.0],[5,2,20.0],[7,3,12.7],[8,4,16.0]],
            "rows": [
                {"id": "OTU_1", "metadata": {}},
                {"id": "OTU_2", "metadata": {}},
                {"id": "OTU_3", "metadata": {}},
                {"id": "OTU_4", "metadata": {}},
                {"id": "OTU_5", "metadata": {}},
                {"id": "OTU_6", "metadata": {}},
                {"id": "OTU_7", "metadata": {}},
                {"id": "OTU_8", "metadata": {}},
                {"id": "OTU_9", "metadata": {}},
                {"id": "OTU_10", "metadata": {}}
            ],
            "columns": [
                {"id": "Sample_1", "metadata": {}},
                {"id": "Sample_2", "metadata": {}},
                {"id": "Sample_3", "metadata": {}},
                {"id": "Sample_4", "metadata": {}},
                {"id": "Sample_5", "metadata": {}}
            ]
        };
        expect(function(){Biom(biomObject);}).toThrow('Not a function');
    });
});

<|endoftext|>