<commit_before>/* See license.txt for terms of usage */

var Firebug = Firebug || {};

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

/**
 * Returns default configuration object for Firebug module loader (RequireJS). Custom
 * value can be passed through the argument.
 *
 * @param {Object} baseConfig Custom configuration values.
 */
Firebug.getModuleLoaderConfig = function(baseConfig)
{
    baseConfig = baseConfig || {};

    // Set configuration defaults.
    baseConfig.baseLoaderUrl = baseConfig.baseLoaderUrl || "resource://moduleLoader/";
    baseConfig.prefDomain = baseConfig.prefDomain || "extensions.firebug";
    baseConfig.baseUrl = baseConfig.baseUrl || "resource://";
    baseConfig.xhtml = true;  // createElementNS used
    baseConfig.arch = baseConfig.arch || "chrome://firebug/content/bti/inProcess";

    baseConfig.paths = baseConfig.paths || {
        "arch": baseConfig.arch,
        "firebug": "chrome://firebug/content"
    };

    var config = {};
    var keys = Object.keys(baseConfig);
    keys.forEach(function copy(key)
    {
        config[key] = baseConfig[key];
    });

    // This is the basic list of necessary modules. All the other modules will be
    // automatically loaded as dependencies.
    config.modules = [
        "firebug/trace/traceModule",
        "firebug/chrome/navigationHistory",
        "firebug/chrome/knownIssues",
        "firebug/js/sourceFile",
        "firebug/chrome/shortcuts",
        "firebug/firefox/start-button/startButtonOverlay",
        "firebug/firefox/external-editors/externalEditors",
        "firebug/chrome/panelActivation",
        //"firebug/console/memoryProfiler", xxxHonza: removed from 1.10 (issue 5599)
        "firebug/chrome/tableRep",
        "firebug/html/htmlPanel",
        "firebug/console/commandLinePopup",
        "firebug/accessible/a11y",
        "firebug/js/scriptPanel",
        "firebug/js/callstack",
        "firebug/console/consoleInjector",
        "firebug/net/spy",
        "firebug/js/tabCache",
        "firebug/chrome/activation",
        "firebug/css/stylePanel",
        "firebug/css/computedPanel",
        "firebug/cookies/cookieModule",
        "firebug/cookies/cookiePanel",
        "firebug/css/selectorPanel",
    ];

    return config;
}

// ********************************************************************************************* //
// Firebug Extension Registration

Firebug.extensions = {};

/**
 * Registers a Firebug extension. The framework automatically loads 'main' extension
 * module (AMD).
 *
 * @param {String} extName        Unique name of the extension. This name is used to
 *      build chrome paths for extension resource: chrome://<ext-id>/content/main.js
 * @param {Object} extConfig    Configuration file
 */
Firebug.registerExtension = function(extName, extConfig)
{
    extConfig = extConfig || {};

    var tempConfig = this.getExtensionConfig(extName);
    if (tempConfig)
    {
        FBTrace.sysout("firebug.registerExtension; ERROR An extension with the same ID " +
            "already exists! - " + extName, tempConfig);
        return;
    }

    if (FBTrace.DBG_REGISTRATION)
        FBTrace.sysout("Extension registered: " + extName);

    this.extensions[extName] = extConfig;

    var config = Firebug.getModuleLoaderConfig();

    // Do not use resource: protocol for extensions (it's not allowed for bootstrapped
    // extensions to specify the protocol in chrome.manifest and it would require
    // additional code in every extension (in bootstrap.js), use standard chrome: instead.
    //config.paths[extName] = extName + "/content";
    config.paths[extName] = "chrome://" + extName + "/content";

    // Load main.js module (the entry point of the extension) and support for tracing.
    // All other extension modules should be loaded within "main" module.
    Firebug.require(config, [
        extName + "/main",
        "firebug/lib/trace"
    ],
    function(Extension, FBTrace)
    {
        try
        {
            extConfig.app = Extension;

            // Extension intialization procedure should be within this method (in main.js).
            if (Extension.initialize)
                Extension.initialize();

            // Refresh Firebug tab-bar to make sure that any new registered panels
            // are displayed.
            if (Firebug.chrome)
                Firebug.chrome.syncMainPanels();

            if (FBTrace.DBG_INITIALIZE)
                FBTrace.sysout("firebug.main; Extension '" + extName + " - modules loaded!");
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS || FBTrace.DBG_REGISTRATION)
                FBTrace.sysout("firebug.main; Extension: " + extName + " EXCEPTION " + err, err);
        }
    });
}

/**
 * Unregisters and shutdowns specific extension. Registered extensions are unregistered
 * automatically when Firebug shutdowns. Bootstrapped extensions should use this method
 * to dynamically uninstall an extension.
 *
 * @param {Object} extName    ID of the extensions that should be unregistered.
 */
Firebug.unregisterExtension = function(extName)
{
    var extConfig = this.getExtensionConfig(extName);
    if (!extConfig)
        return;

    try
    {
        if (extConfig.app && extConfig.app.shutdown)
            extConfig.app.shutdown();

        delete this.extensions[extName];

        if (FBTrace.DBG_REGISTRATION)
            FBTrace.sysout("Extension unregistered: " + extName);
    }
    catch (err)
    {
        if (FBTrace.DBG_ERRORS || FBTrace.DBG_REGISTRATION)
            FBTrace.sysout("unregisterExtension: " + extName + " EXCEPTION " + err, err);
    }
}

Firebug.getExtensionConfig = function(extName)
{
    return this.extensions[extName];
}

Firebug.iterateExtensions = function(callback)
{
    for (var ext in this.extensions)
        callback(ext, this.extensions[ext]);
}

/**
 * Unregisters and shutdowns all registered extensions. Called by the framework when
 * Firebug shutdowns.
 */
Firebug.unregisterExtensions = function()
{
    var extensions = {};
    for (var p in this.extensions)
        extensions[p] = this.extensions[p];

    for (var extName in extensions)
        this.unregisterExtension(extName);

    this.extensions = {};
}

// ********************************************************************************************* //
<commit_msg>Issue 6078: 	Firebug & FirePhp compatibility<commit_after>/* See license.txt for terms of usage */

var Firebug = Firebug || {};

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

/**
 * Returns default configuration object for Firebug module loader (RequireJS). Custom
 * value can be passed through the argument.
 *
 * @param {Object} baseConfig Custom configuration values.
 */
Firebug.getModuleLoaderConfig = function(baseConfig)
{
    baseConfig = baseConfig || {};

    // Set configuration defaults.
    baseConfig.baseLoaderUrl = baseConfig.baseLoaderUrl || "resource://moduleLoader/";
    baseConfig.prefDomain = baseConfig.prefDomain || "extensions.firebug";
    baseConfig.baseUrl = baseConfig.baseUrl || "resource://";
    baseConfig.xhtml = true;  // createElementNS used
    baseConfig.arch = baseConfig.arch || "chrome://firebug/content/bti/inProcess";

    baseConfig.paths = baseConfig.paths || {
        "arch": baseConfig.arch,
        "firebug": "chrome://firebug/content"
    };

    var config = {};
    var keys = Object.keys(baseConfig);
    keys.forEach(function copy(key)
    {
        config[key] = baseConfig[key];
    });

    // This is the basic list of necessary modules. All the other modules will be
    // automatically loaded as dependencies.
    config.modules = [
        "firebug/trace/traceModule",
        "firebug/chrome/navigationHistory",
        "firebug/chrome/knownIssues",
        "firebug/js/sourceFile",
        "firebug/chrome/shortcuts",
        "firebug/firefox/start-button/startButtonOverlay",
        "firebug/firefox/external-editors/externalEditors",
        "firebug/chrome/panelActivation",
        //"firebug/console/memoryProfiler", xxxHonza: removed from 1.10 (issue 5599)
        "firebug/chrome/tableRep",
        "firebug/html/htmlPanel",
        "firebug/console/commandLinePopup",
        "firebug/accessible/a11y",
        "firebug/js/scriptPanel",
        "firebug/js/callstack",
        "firebug/console/consoleInjector",
        "firebug/net/spy",
        "firebug/js/tabCache",
        "firebug/chrome/activation",
        "firebug/css/stylePanel",
        "firebug/css/computedPanel",
        "firebug/cookies/cookieModule",
        "firebug/cookies/cookiePanel",
        "firebug/css/selectorPanel",
    ];

    return config;
}

// ********************************************************************************************* //
// Firebug Extension Registration

Firebug.extensions = {};

/**
 * Registers a Firebug extension. The framework automatically loads 'main' extension
 * module (AMD).
 *
 * @param {String} extName        Unique name of the extension. This name is used to
 *      build chrome paths for extension resource: chrome://<ext-id>/content/main.js
 * @param {Object} extConfig    Configuration file
 */
Firebug.registerExtension = function(extName, extConfig)
{
    extConfig = extConfig || {};

    var tempConfig = this.getExtensionConfig(extName);
    if (tempConfig)
    {
        Components.utils.reportError("firebug.registerExtension; ERROR An extension " +
            "with the same ID already exists! - " + extName, tempConfig);
        return;
    }

    this.extensions[extName] = extConfig;

    var config = Firebug.getModuleLoaderConfig();

    // Do not use resource: protocol for extensions (it's not allowed for bootstrapped
    // extensions to specify the protocol in chrome.manifest and it would require
    // additional code in every extension (in bootstrap.js), use standard chrome: instead.
    //config.paths[extName] = extName + "/content";
    config.paths[extName] = "chrome://" + extName + "/content";

    // Load main.js module (the entry point of the extension) and support for tracing.
    // All other extension modules should be loaded within "main" module.
    Firebug.require(config, [
        extName + "/main",
        "firebug/lib/trace"
    ],
    function(Extension, FBTrace)
    {
        try
        {
            extConfig.app = Extension;

            // Extension intialization procedure should be within this method (in main.js).
            if (Extension.initialize)
                Extension.initialize();

            // Refresh Firebug tab-bar to make sure that any new registered panels
            // are displayed.
            if (Firebug.chrome)
                Firebug.chrome.syncMainPanels();

            if (FBTrace.DBG_INITIALIZE)
                FBTrace.sysout("firebug.main; Extension '" + extName + " - modules loaded!");
        }
        catch (err)
        {
            Components.utils.reportError("firebug.main; Extension: " + extName +
                " EXCEPTION " + err, err);
        }
    });
}

/**
 * Unregisters and shutdowns specific extension. Registered extensions are unregistered
 * automatically when Firebug shutdowns. Bootstrapped extensions should use this method
 * to dynamically uninstall an extension.
 *
 * @param {Object} extName    ID of the extensions that should be unregistered.
 */
Firebug.unregisterExtension = function(extName)
{
    var extConfig = this.getExtensionConfig(extName);
    if (!extConfig)
        return;

    try
    {
        if (extConfig.app && extConfig.app.shutdown)
            extConfig.app.shutdown();

        delete this.extensions[extName];
    }
    catch (err)
    {
        Components.utils.reportError("unregisterExtension: " + extName +
            " EXCEPTION " + err, err);
    }
}

Firebug.getExtensionConfig = function(extName)
{
    return this.extensions[extName];
}

Firebug.iterateExtensions = function(callback)
{
    for (var ext in this.extensions)
        callback(ext, this.extensions[ext]);
}

/**
 * Unregisters and shutdowns all registered extensions. Called by the framework when
 * Firebug shutdowns.
 */
Firebug.unregisterExtensions = function()
{
    var extensions = {};
    for (var p in this.extensions)
        extensions[p] = this.extensions[p];

    for (var extName in extensions)
        this.unregisterExtension(extName);

    this.extensions = {};
}

// ********************************************************************************************* //
<|endoftext|>


<commit_before>var through = require('through2'),
    gutil = require('gulp-util'),
    _ = require('lodash'),
    fs = require('fs'),
    jsYaml = require('js-yaml'),
    templateFilePath = __dirname + '/template.html',
    PluginError = gutil.PluginError;

const PLUGIN_NAME = 'gulp-ng-config',
      WRAP_TEMPLATE = '(function () { \n return <%= module %>\n})();\n';

function gulpNgConfig (moduleName, configuration) {
  var templateFile, stream, defaults;
  defaults = {
    createModule: true,
    wrap: false,
    environment: null,
    parser: null,
    pretty: false
  };

  if (!moduleName) {
    throw new PluginError(PLUGIN_NAME, 'Missing required moduleName option for gulp-ng-config');
  }

  templateFile = fs.readFileSync(templateFilePath, 'utf8');
  configuration = configuration || {};
  configuration = _.merge({}, defaults, configuration);

  stream = through.obj(function (file, encoding, callback) {
    var constants = [],
        templateOutput,
        jsonObj,
        wrapTemplate;

    if (!configuration.parser && (_.endsWith(file.path, 'yml') || _.endsWith(file.path, 'yaml'))) {
      configuration.parser = 'yml';
    }

    if (!configuration.parser) {
      configuration.parser = 'json';
    }

    if (configuration.parser === 'json') {
      try {
        jsonObj = file.isNull() ? {} : JSON.parse(file.contents.toString('utf8'));
      } catch (e) {
        this.emit('error', new PluginError(PLUGIN_NAME, 'invaild JSON file provided'));
      }
    } else if (configuration.parser === 'yml' || configuration.parser === 'yaml') {
      try {
        jsonObj = jsYaml.safeLoad(file.contents);
      } catch (e) {
        this.emit('error', new PluginError(PLUGIN_NAME, 'invaild YML file provided'));
      }
    } else {
      this.emit('error', new PluginError(PLUGIN_NAME, configuration.parser + ' is not supported as a valid parser'));
    }

    if (!_.isPlainObject(jsonObj)) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'invalid JSON object provided'));
    }

    // select the environment in the configuration
    if (configuration.environment && jsonObj.hasOwnProperty(configuration.environment)) {
      jsonObj = jsonObj[configuration.environment];
    }

    jsonObj = _.merge({}, jsonObj, configuration.constants || {});

    var spaces = (configuration.pretty) ?  2 : 0;

    _.each(jsonObj, function (value, key) {
      constants.push({
        name: key,
        value: JSON.stringify(value, null, spaces)
      });
    });

    templateOutput = _.template(templateFile)({
      createModule: configuration.createModule,
      moduleName: moduleName,
      constants: constants
    });

    if (configuration.wrap) {
      if (typeof configuration.wrap === 'string') {
        wrapTemplate = configuration.wrap;
      } else {
        wrapTemplate = WRAP_TEMPLATE;
      }
      templateOutput = _.template(wrapTemplate)({
        module: templateOutput
      });
    }

    file.path = gutil.replaceExtension(file.path, '.js');
    file.contents = new Buffer(templateOutput);
    this.push(file);
    callback();
  });

  return stream;
}

module.exports = gulpNgConfig;
<commit_msg>Added ability to pass numeric value as 'pretty' param (spaces count)<commit_after>var through = require('through2'),
    gutil = require('gulp-util'),
    _ = require('lodash'),
    fs = require('fs'),
    jsYaml = require('js-yaml'),
    templateFilePath = __dirname + '/template.html',
    PluginError = gutil.PluginError;

const PLUGIN_NAME = 'gulp-ng-config',
      WRAP_TEMPLATE = '(function () { \n return <%= module %>\n})();\n';

function gulpNgConfig (moduleName, configuration) {
  var templateFile, stream, defaults;
  defaults = {
    createModule: true,
    wrap: false,
    environment: null,
    parser: null,
    pretty: false
  };

  if (!moduleName) {
    throw new PluginError(PLUGIN_NAME, 'Missing required moduleName option for gulp-ng-config');
  }

  templateFile = fs.readFileSync(templateFilePath, 'utf8');
  configuration = configuration || {};
  configuration = _.merge({}, defaults, configuration);

  stream = through.obj(function (file, encoding, callback) {
    var constants = [],
        templateOutput,
        jsonObj,
        wrapTemplate;

    if (!configuration.parser && (_.endsWith(file.path, 'yml') || _.endsWith(file.path, 'yaml'))) {
      configuration.parser = 'yml';
    }

    if (!configuration.parser) {
      configuration.parser = 'json';
    }

    if (configuration.parser === 'json') {
      try {
        jsonObj = file.isNull() ? {} : JSON.parse(file.contents.toString('utf8'));
      } catch (e) {
        this.emit('error', new PluginError(PLUGIN_NAME, 'invaild JSON file provided'));
      }
    } else if (configuration.parser === 'yml' || configuration.parser === 'yaml') {
      try {
        jsonObj = jsYaml.safeLoad(file.contents);
      } catch (e) {
        this.emit('error', new PluginError(PLUGIN_NAME, 'invaild YML file provided'));
      }
    } else {
      this.emit('error', new PluginError(PLUGIN_NAME, configuration.parser + ' is not supported as a valid parser'));
    }

    if (!_.isPlainObject(jsonObj)) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'invalid JSON object provided'));
    }

    // select the environment in the configuration
    if (configuration.environment && jsonObj.hasOwnProperty(configuration.environment)) {
      jsonObj = jsonObj[configuration.environment];
    }

    jsonObj = _.merge({}, jsonObj, configuration.constants || {});

    var spaces = 0;
    if (configuration.pretty) {
      if (configuration.pretty === true) {
        spaces = 2;
      } else if (configuration.pretty === +configuration.pretty) {
        //if number passed
        spaces = configuration.pretty;
      }
    }

    _.each(jsonObj, function (value, key) {
      constants.push({
        name: key,
        value: JSON.stringify(value, null, spaces)
      });
    });

    templateOutput = _.template(templateFile)({
      createModule: configuration.createModule,
      moduleName: moduleName,
      constants: constants
    });

    if (configuration.wrap) {
      if (typeof configuration.wrap === 'string') {
        wrapTemplate = configuration.wrap;
      } else {
        wrapTemplate = WRAP_TEMPLATE;
      }
      templateOutput = _.template(wrapTemplate)({
        module: templateOutput
      });
    }

    file.path = gutil.replaceExtension(file.path, '.js');
    file.contents = new Buffer(templateOutput);
    this.push(file);
    callback();
  });

  return stream;
}

module.exports = gulpNgConfig;
<|endoftext|>


<commit_before>/**
 * @constructor
 * @param {number} x
 * @param {number} y
 * @param {number} z
 */
function Vector(x, y, z){
    if (typeof x === 'undefined' ||
        typeof y === 'undefined' ||
        typeof z === 'undefined'){
        throw new Error('Insufficient arguments.');
    } else {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}
/**
 * Add vector to self.
 * @method
 * @param {Vector} vector
 * @return {Vector}
 */
Vector.prototype.add = function(vector){
    return new Vector(this.x + vector.x, this.y + vector.y, this.z + vector.z);
};
/**
 * Subtract vector from self.
 * @method
 * @param {Vector} vector
 * @return {Vector}
 */
Vector.prototype.subtract = function(vector){
    return new Vector(this.x - vector.x, this.y - vector.y, this.z - vector.z);
};
/**
 * Compare vector with self for equality
 * @method
 * @param {Vector} vector
 * @return {boolean}
 */
Vector.prototype.equal = function(vector){
    return this.x === vector.x && this.y === vector.y && this.z === vector.z;
};
/**
 * Find angle between two vectors.
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.angle = function(vector){
    var a = this.normalize();
    var b = vector.normalize();
    var amag = a.magnitude();
    var bmag = b.magnitude();
    if (amag === 0 || bmag === 0){
        return 0;
    }
    var theta = a.dot(b) / (amag * bmag );
    if (theta < -1) {theta = -1;}
    if (theta > 1) {theta = 1;}
    return Math.acos(theta);
};
/**
 * Find the cos of the angle between two vectors.
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.cosAngle = function(vector){
    var a = this.normalize();
    var b = vector.normalize();
    var amag = a.magnitude();
    var bmag = b.magnitude();
    if (amag === 0 || bmag === 0){
        return 0;
    }
    var theta = a.dot(b) / (amag * bmag )
        if (theta < -1) {theta = -1;}
    if (theta > 1) {theta = 1;}
    return theta;
};
/**
 * Find magnitude of a vector.
 * @method
 * @return {number}
 */
Vector.prototype.magnitude = function(){
    return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z));
};
/**
 * Find magnitude squared of a vector.
 * @method
 * @return {number}
 */
Vector.prototype.magnitudeSquared = function(){
    return (this.x * this.x) + (this.y * this.y) + (this.z * this.z);
};
/**
 * Find dot product of self and vector.
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.dot = function(vector){
    return (this.x * vector.x) + (this.y * vector.y) + (this.z * vector.z);
};
/**
 * Find cross product of self and vector.
 * @method
 * @param {Vector} vector
 * @return {Vector}
 */
Vector.prototype.cross = function(vector){
    return new Vector(
        (this.y * vector.z) - (this.z * vector.y),
        (this.z * vector.x) - (this.x * vector.z),
        (this.x * vector.y) - (this.y * vector.x)
    );
};
/**
 * Normalize self.
 * @method
 * @return {Vector}
 * @throws {ZeroDivisionError}
 */
Vector.prototype.normalize = function(){
    var magnitude = this.magnitude();
    if (magnitude === 0) {
        return this;
    }
    return new Vector(this.x / magnitude, this.y / magnitude, this.z / magnitude);
};
/**
 * Scale self by scale.
 * @method
 * @param {number} scale
 * @return {Vector}
 */
Vector.prototype.scale = function(scale){
    return new Vector(this.x * scale, this.y * scale, this.z * scale);
};
/** @method */
Vector.prototype.negate = function(){
    return new Vector(-this.x, -this.y, -this.z);
};
/**
 * Project self onto vector
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.vectorProjection = function(vector){
    return this.magnitude() * Math.cos(this.angle(vector));
};
/**
 * Project self onto vector
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.scalarProjection = function(vector){
    return this.dot(vector.normalize()) * vector.normalize;
};
/**
 * Comp self and vector
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.component = function(vector){
    //A.comp(B) = dot(A,norm(B))
    return this.dot(vector) / this.magnitude();
};
/**
 * Rotate self by theta around axis
 * @method
 * @param {Vector} axis
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotate = function(axis, theta){
    var u = axis.normalize();
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var cos1 = 1-cos;
    var ux = u.x;
    var uy = u.y;
    var uz = u.z;
    var xy = u.x * u.y;
    var xz = u.x * u.z;
    var yz = u.y * u.z;
    var x = ((cos + ((ux*ux)*cos1)) * this.x) + (((xy*cos1) - (uz*sin)) * this.y) + (((xz*cos1)+(uy*sin)) * this.z);
    var y = (((xy*cos1)+(uz*sin)) * this.x) + ((cos+((uy*uy)*cos1)) * this.y) + (((yz*cos1)-(ux*sin)) * this.z);
    var z = (((xz*cos1)-(uy*sin)) * this.x) + (((yz*cos1)+(ux*sin)) * this.y) + ((cos + ((ux*ux)*cos1)) * this.z);
    return new Vector(x, y, z);
};
/**
 * Perform linear tranformation on self.
 * @method
 * @param {Matrix} transform_matrix
 * @return {Vector}
 */
Vector.prototype.transform = function(transform_matrix){
     var x = (this.x * transform_matrix[0]) + (this.y * transform_matrix[4]) + (this.z * transform_matrix[8]) + transform_matrix[12];
    var y = (this.x * transform_matrix[1]) + (this.y * transform_matrix[5]) + (this.z * transform_matrix[9]) + transform_matrix[13];
    var z = (this.x * transform_matrix[2]) + (this.y * transform_matrix[6]) + (this.z * transform_matrix[10]) + transform_matrix[14];
    var w = (this.x * transform_matrix[3]) + (this.y * transform_matrix[7]) + (this.z * transform_matrix[11]) + transform_matrix[15];
    return new Vector(x / w, y / w, z / w);
};
/**
 * Rotate self by theta around x-axis
 * @method
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotateX = function(theta){
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var x = this.x;
    var y = (cos * this.y) - (sin * this.z);
    var z = (sin * this.y) + (cos * this.z);
    return new Vector(x, y, z);
};
/**
 * Rotate self by theta around y-axis
 * @method
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotateY = function(theta){
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var x = (cos *this.x) + (sin * this.z);
    var y = this.y;
    var z = -(sin * this.x) + (cos * this.z);
    return new Vector(x, y, z);
};
/**
 * Rotate self by theta around z-axis
 * @method
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotateZ = function(theta){
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var x = (cos * this.x) - (sin * this.y);
    var y = (sin * this.x) + (cos * this.y);
    var z = this.z;
    return new Vector(x, y, z);
};
/**
 * Rotate self by pitch, yaw, roll
 * @method
 * @param {number} pitch
 * @param {number} yaw
 * @param {number} roll
 * @return {Vector}
 */
Vector.prototype.rotatePitchYawRoll = function(pitch_amnt, yaw_amnt, roll_amnt) {
    return this.rotateX(roll_amnt).rotateY(pitch_amnt).rotateZ(yaw_amnt);
};

module.exports = Vector;<commit_msg>Fix vectorProjection and scalarProjection. Remove comp (redundant)<commit_after>/**
 * @constructor
 * @param {number} x
 * @param {number} y
 * @param {number} z
 */
function Vector(x, y, z){
    if (typeof x === 'undefined' ||
        typeof y === 'undefined' ||
        typeof z === 'undefined'){
        throw new Error('Insufficient arguments.');
    } else {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}
/**
 * Add vector to self.
 * @method
 * @param {Vector} vector
 * @return {Vector}
 */
Vector.prototype.add = function(vector){
    return new Vector(this.x + vector.x, this.y + vector.y, this.z + vector.z);
};
/**
 * Subtract vector from self.
 * @method
 * @param {Vector} vector
 * @return {Vector}
 */
Vector.prototype.subtract = function(vector){
    return new Vector(this.x - vector.x, this.y - vector.y, this.z - vector.z);
};
/**
 * Compare vector with self for equality
 * @method
 * @param {Vector} vector
 * @return {boolean}
 */
Vector.prototype.equal = function(vector){
    return this.x === vector.x && this.y === vector.y && this.z === vector.z;
};
/**
 * Find angle between two vectors.
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.angle = function(vector){
    var a = this.normalize();
    var b = vector.normalize();
    var amag = a.magnitude();
    var bmag = b.magnitude();
    if (amag === 0 || bmag === 0){
        return 0;
    }
    var theta = a.dot(b) / (amag * bmag );
    if (theta < -1) {theta = -1;}
    if (theta > 1) {theta = 1;}
    return Math.acos(theta);
};
/**
 * Find the cos of the angle between two vectors.
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.cosAngle = function(vector){
    var a = this.normalize();
    var b = vector.normalize();
    var amag = a.magnitude();
    var bmag = b.magnitude();
    if (amag === 0 || bmag === 0){
        return 0;
    }
    var theta = a.dot(b) / (amag * bmag )
        if (theta < -1) {theta = -1;}
    if (theta > 1) {theta = 1;}
    return theta;
};
/**
 * Find magnitude of a vector.
 * @method
 * @return {number}
 */
Vector.prototype.magnitude = function(){
    return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z));
};
/**
 * Find magnitude squared of a vector.
 * @method
 * @return {number}
 */
Vector.prototype.magnitudeSquared = function(){
    return (this.x * this.x) + (this.y * this.y) + (this.z * this.z);
};
/**
 * Find dot product of self and vector.
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.dot = function(vector){
    return (this.x * vector.x) + (this.y * vector.y) + (this.z * vector.z);
};
/**
 * Find cross product of self and vector.
 * @method
 * @param {Vector} vector
 * @return {Vector}
 */
Vector.prototype.cross = function(vector){
    return new Vector(
        (this.y * vector.z) - (this.z * vector.y),
        (this.z * vector.x) - (this.x * vector.z),
        (this.x * vector.y) - (this.y * vector.x)
    );
};
/**
 * Normalize self.
 * @method
 * @return {Vector}
 * @throws {ZeroDivisionError}
 */
Vector.prototype.normalize = function(){
    var magnitude = this.magnitude();
    if (magnitude === 0) {
        return this;
    }
    return new Vector(this.x / magnitude, this.y / magnitude, this.z / magnitude);
};
/**
 * Scale self by scale.
 * @method
 * @param {number} scale
 * @return {Vector}
 */
Vector.prototype.scale = function(scale){
    return new Vector(this.x * scale, this.y * scale, this.z * scale);
};
/** @method */
Vector.prototype.negate = function(){
    return new Vector(-this.x, -this.y, -this.z);
};
/**
 * Project self onto vector
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.vectorProjection = function(vector){
    var mag = vector.magnitude();
    return vector.scale(this.dot(vector) / (mag * mag));
};
/**
 * Project self onto vector
 * @method
 * @param {Vector} vector
 * @return {number}
 */
Vector.prototype.scalarProjection = function(vector){
    return this.dot(vector) / vector.magnitude();
};
/**
 * Rotate self by theta around axis
 * @method
 * @param {Vector} axis
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotate = function(axis, theta){
    var u = axis.normalize();
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var cos1 = 1-cos;
    var ux = u.x;
    var uy = u.y;
    var uz = u.z;
    var xy = u.x * u.y;
    var xz = u.x * u.z;
    var yz = u.y * u.z;
    var x = ((cos + ((ux*ux)*cos1)) * this.x) + (((xy*cos1) - (uz*sin)) * this.y) + (((xz*cos1)+(uy*sin)) * this.z);
    var y = (((xy*cos1)+(uz*sin)) * this.x) + ((cos+((uy*uy)*cos1)) * this.y) + (((yz*cos1)-(ux*sin)) * this.z);
    var z = (((xz*cos1)-(uy*sin)) * this.x) + (((yz*cos1)+(ux*sin)) * this.y) + ((cos + ((ux*ux)*cos1)) * this.z);
    return new Vector(x, y, z);
};
/**
 * Perform linear tranformation on self.
 * @method
 * @param {Matrix} transform_matrix
 * @return {Vector}
 */
Vector.prototype.transform = function(transform_matrix){
     var x = (this.x * transform_matrix[0]) + (this.y * transform_matrix[4]) + (this.z * transform_matrix[8]) + transform_matrix[12];
    var y = (this.x * transform_matrix[1]) + (this.y * transform_matrix[5]) + (this.z * transform_matrix[9]) + transform_matrix[13];
    var z = (this.x * transform_matrix[2]) + (this.y * transform_matrix[6]) + (this.z * transform_matrix[10]) + transform_matrix[14];
    var w = (this.x * transform_matrix[3]) + (this.y * transform_matrix[7]) + (this.z * transform_matrix[11]) + transform_matrix[15];
    return new Vector(x / w, y / w, z / w);
};
/**
 * Rotate self by theta around x-axis
 * @method
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotateX = function(theta){
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var x = this.x;
    var y = (cos * this.y) - (sin * this.z);
    var z = (sin * this.y) + (cos * this.z);
    return new Vector(x, y, z);
};
/**
 * Rotate self by theta around y-axis
 * @method
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotateY = function(theta){
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var x = (cos *this.x) + (sin * this.z);
    var y = this.y;
    var z = -(sin * this.x) + (cos * this.z);
    return new Vector(x, y, z);
};
/**
 * Rotate self by theta around z-axis
 * @method
 * @param {number} theta
 * @return {Vector}
 */
Vector.prototype.rotateZ = function(theta){
    var sin = Math.sin(theta);
    var cos = Math.cos(theta);
    var x = (cos * this.x) - (sin * this.y);
    var y = (sin * this.x) + (cos * this.y);
    var z = this.z;
    return new Vector(x, y, z);
};
/**
 * Rotate self by pitch, yaw, roll
 * @method
 * @param {number} pitch
 * @param {number} yaw
 * @param {number} roll
 * @return {Vector}
 */
Vector.prototype.rotatePitchYawRoll = function(pitch_amnt, yaw_amnt, roll_amnt) {
    return this.rotateX(roll_amnt).rotateY(pitch_amnt).rotateZ(yaw_amnt);
};

module.exports = Vector;<|endoftext|>


<commit_before>// @flow

import React from 'react';
import PropTypes from 'prop-types';

import {
    Step,
    Stepper,
    StepLabel,
    StepContent,
} from 'material-ui/Stepper';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import DatePicker from 'material-ui/DatePicker';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';

class ShowPicker extends React.Component {

    static propTypes = {
        /**
         * Called when a show has been selected, called with the ID of the selected show.
         * Signature: (id) => ().
         */
        onFinish: PropTypes.func.isRequired,
    };

    state = {
        /** The current step of the stepper. */
        stepIndex: 0,

        /** The selected date. */
        date: new Date(),

        /** The shows which are possible after having selected a date. */
        shows: [],

        /** The ID of the selected show. */
        show: undefined,
    };

    handleNext = () => {
        const {stepIndex, date, show} = this.state;

        this.setState({
            stepIndex: stepIndex + 1,
        });

        if (stepIndex === 0) {
            // TODO Skip next step if there is only one show.
        }

        if (stepIndex === 1) {
            this.props.onFinish(show);

            // TODO Refactor to avoid duplicating the defaults.
            this.setState({
                stepIndex: 0,
                date: new Date(),
                shows: [],
                show: undefined,
            });
        }
    };

    handlePrev = () => {
        const {stepIndex} = this.state;
        if (stepIndex > 0) {
            this.setState({stepIndex: stepIndex - 1});
        }
    };

    handleDateChange = (_, date) => {
        this.setState({
            date: date
        });

        /* We already query the available shows here to make it a bit snappier. */
        // TODO Correct date
        fetch("api/shows?date=23051990", {
            accept: "application/json"
        }).then((response) => {
            return response.json();
        }).then((shows) => {
            var selected = (shows.length > 0) ? shows[0].id : "";

            this.setState({
                shows: shows,
                show: selected,
            });
        });
    };

    handleShowChange = (_, value) => {
        this.setState({
            show: value
        });
    };

    renderStepActions(step) {
        const {stepIndex} = this.state;

        return (

                <RaisedButton
                    label={stepIndex === 1 ? 'Besetzung suchen' : 'Weiter'}
                    disableTouchRipple={true}
                    disableFocusRipple={true}
                    primary={true}
                    onTouchTap={this.handleNext}
                    style={{marginRight: 12}}
                />
                {step > 0 && (
                    <FlatButton
                        label="Zurück"
                        disabled={stepIndex === 0}
                        disableTouchRipple={true}
                        disableFocusRipple={true}
                        onTouchTap={this.handlePrev}
                    />
                )}

        );
    }

    render() {
        const {stepIndex, shows, show} = this.state;

        const minDate = new Date("10-04-1997");
        const maxDate = new Date();

        const styles = {
            radioButton: {
                textAlign: "left",
                marginBottom: 16,
            },
        };

        var items = shows.map((current) => {
            // TODO include time AND place in label
            return (
                <RadioButton
                    key={current.id}
                    value={current.id}
                    label={current.time}
                    style={styles.radioButton}
                />
            );
        });

        let DateTimeFormat = global.Intl.DateTimeFormat;

        // TODO Disable days without any show (shouldDisableDate)
        return (

                <Stepper activeStep={stepIndex} orientation="vertical">
                    <Step>
                        <StepLabel>Wähle das Datum der Vorstellung aus</StepLabel>
                        <StepContent>
                            <DatePicker
                                hintText="Datum wählen"
                                cancelLabel="Abbrechen"
                                autoOk={true}
                                defaultDate={this.state.date}
                                DateTimeFormat={DateTimeFormat}
                                minDate={minDate}
                                maxDate={maxDate}
                                onChange={this.handleDateChange}
                                formatDate={new DateTimeFormat("de-DE", {
                                    weekday: "long",
                                    day: "numeric",
                                    month: "long",
                                    year: "numeric",
                                }).format}
                            />

                            {this.renderStepActions(0)}
                        </StepContent>
                    </Step>
                    <Step>
                        <StepLabel>Wähle zwischen Matinee und Soiree</StepLabel>
                        <StepContent>
                            <RadioButtonGroup
                                name="show"
                                onChange={this.handleShowChange}
                                defaultSelected={show}
                            >
                                {items}
                            </RadioButtonGroup>

                            {this.renderStepActions(1)}
                        </StepContent>
                    </Step>
                </Stepper>

        );
    }

}

export default ShowPicker;<commit_msg>Move API call<commit_after>// @flow

import React from 'react';
import PropTypes from 'prop-types';

import {
    Step,
    Stepper,
    StepLabel,
    StepContent,
} from 'material-ui/Stepper';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import DatePicker from 'material-ui/DatePicker';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';

class ShowPicker extends React.Component {

    static propTypes = {
        /**
         * Called when a show has been selected, called with the ID of the selected show.
         * Signature: (id) => ().
         */
        onFinish: PropTypes.func.isRequired,
    };

    state = {
        /** The current step of the stepper. */
        stepIndex: 0,

        /** The selected date. */
        date: new Date(),

        /** The shows which are possible after having selected a date. */
        shows: [],

        /** The ID of the selected show. */
        show: undefined,
    };

    handleNext = () => {
        const {stepIndex, date, show} = this.state;

        this.setState({
            stepIndex: stepIndex + 1,
        });

        if (stepIndex === 0) {
            // TODO Correct date
            fetch("api/shows?date=23051990", {
                accept: "application/json"
            }).then((response) => {
                return response.json();
            }).then((shows) => {
                var selected = (shows.length > 0) ? shows[0].id : "";

                this.setState({
                    shows: shows,
                    show: selected,
                });
            });

            // TODO Skip next step if there is only one show.
        }

        if (stepIndex === 1) {
            this.props.onFinish(show);

            // TODO Refactor to avoid duplicating the defaults.
            this.setState({
                stepIndex: 0,
                date: new Date(),
                shows: [],
                show: undefined,
            });
        }
    };

    handlePrev = () => {
        const {stepIndex} = this.state;
        if (stepIndex > 0) {
            this.setState({stepIndex: stepIndex - 1});
        }
    };

    handleDateChange = (_, date) => {
        this.setState({
            date: date
        });
    };

    handleShowChange = (_, value) => {
        this.setState({
            show: value
        });
    };

    renderStepActions(step) {
        const {stepIndex} = this.state;

        return (

                <RaisedButton
                    label={stepIndex === 1 ? 'Besetzung suchen' : 'Weiter'}
                    disableTouchRipple={true}
                    disableFocusRipple={true}
                    primary={true}
                    onTouchTap={this.handleNext}
                    style={{marginRight: 12}}
                />
                {step > 0 && (
                    <FlatButton
                        label="Zurück"
                        disabled={stepIndex === 0}
                        disableTouchRipple={true}
                        disableFocusRipple={true}
                        onTouchTap={this.handlePrev}
                    />
                )}

        );
    }

    render() {
        const {stepIndex, shows, show} = this.state;

        const minDate = new Date("10-04-1997");
        const maxDate = new Date();

        const styles = {
            radioButton: {
                textAlign: "left",
                marginBottom: 16,
            },
        };

        var items = shows.map((current) => {
            // TODO include time AND place in label
            return (
                <RadioButton
                    key={current.id}
                    value={current.id}
                    label={current.time}
                    style={styles.radioButton}
                />
            );
        });

        let DateTimeFormat = global.Intl.DateTimeFormat;

        // TODO Disable days without any show (shouldDisableDate)
        return (

                <Stepper activeStep={stepIndex} orientation="vertical">
                    <Step>
                        <StepLabel>Wähle das Datum der Vorstellung aus</StepLabel>
                        <StepContent>
                            <DatePicker
                                hintText="Datum wählen"
                                cancelLabel="Abbrechen"
                                autoOk={true}
                                defaultDate={this.state.date}
                                DateTimeFormat={DateTimeFormat}
                                minDate={minDate}
                                maxDate={maxDate}
                                onChange={this.handleDateChange}
                                formatDate={new DateTimeFormat("de-DE", {
                                    weekday: "long",
                                    day: "numeric",
                                    month: "long",
                                    year: "numeric",
                                }).format}
                            />

                            {this.renderStepActions(0)}
                        </StepContent>
                    </Step>
                    <Step>
                        <StepLabel>Wähle zwischen Matinee und Soiree</StepLabel>
                        <StepContent>
                            <RadioButtonGroup
                                name="show"
                                onChange={this.handleShowChange}
                                defaultSelected={show}
                            >
                                {items}
                            </RadioButtonGroup>

                            {this.renderStepActions(1)}
                        </StepContent>
                    </Step>
                </Stepper>

        );
    }

}

export default ShowPicker;<|endoftext|>


<commit_before>const navHamburger = getElementByClassName('menu-link hamburger')
const navClose = getElementByClassName('nav-close')
const navContainer = getElementByClassName('nav-container')
// If nav menu is opened
onClick(navHamburger, () => {
	//	If nav menu is opened
	if (!isVisible(navClose)) {
		navContainer.classList.add('display')
		setTimeout(() => navContainer.classList.add('fade'), 100)
	}
	else {
		navContainer.classList.remove('fade')
	}
})
// If nav menu is closed
onClick(navClose, () => navHamburger.click())<commit_msg>Nav menu integration for mobile.<commit_after>const navHamburger = getElementByClassName('menu-link hamburger')
const navClose = getElementByClassName('nav-close')
const navContainer = getElementByClassName('nav-container')
// If nav menu is opened
onClick(navHamburger, () => {
	//	If nav menu is opened
	if (!isVisible(navContainer)) {
		navContainer.classList.add('display')
		setTimeout(() => navContainer.classList.add('fade'), 100)
	}
	else {
		navContainer.classList.remove('fade')
	}
})
// If nav menu is closed
onClick(navClose, () => navHamburger.click())<|endoftext|>


<commit_before>/* Dispatch area - Should be eliminate after dispatching */

var markersGroup = new L.LayerGroup();
var isDispatching = false;
var placeIcon = L.icon({
    iconUrl: '/static/icons/place_marker.png',
    iconSize: [50, 50], // size of the icon
});
var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var beginDispatching = function () {

    isDispatching = true;
    console.log('Begin dispatching.');

    document.getElementById('dispatch_work').innerHTML
        = '<button type="button" class="btn btn-link" onclick="endDispatching()">'
        + ''
        + 'Abort dispatching'
        + '</button>';
    $('#dispatchForm').collapse('show');
    $('#ambulance_info_collapse').collapse('hide');

    mymap.on('click', function (e) {

        markersGroup.clearLayers();
        document.getElementById('curr-lat').innerHTML = e.latlng.lat;
        document.getElementById('curr-lng').innerHTML = e.latlng.lng;
        if (isDispatching) {
            L.marker([e.latlng.lat, e.latlng.lng], {icon: placeIcon}).addTo(markersGroup);
            markersGroup.addTo(mymap);
        }

    });

}

var endDispatching = function () {

    isDispatching = false;
    dispatchingAmbulances = {};
    console.log('End dispatching.');

    markersGroup.clearLayers();
    document.getElementById('dispatch_work').innerHTML
        = '<button class="btn btn-primary" style="display: block; width: 100%;"'
        + 'data-toggle="collapse" href="#dispatchForm" onclick="beginDispatching()">'
        + 'Dispatch'
        + '</button>';
    $('#dispatchForm').collapse('hide');
    $('#ambulance_info_collapse').collapse('show');

}

var removeFromDispatchingList = function(ambulance) {

    // delete from dispatching list
    delete dispatchingAmbulances[ambulance.id];
    numberOfDispatchingAmbulances--;

    // show message if last button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').show();

}

var addToDispatchingList = function(ambulance) {

    // quick return if null or not dispatching
    if (ambulance == null || !isDispatching)
        return;

    // add ambulance to dispatching list
    console.log('Adding ambulance ' + ambulance.identifier + ' to dispatching list');

    // already in?
    if (ambulance.id in dispatchingAmbulances) {
        console.log('Already in dispatching list, skip');
        return;
    }

    // not available?
    if (ambulance.status != STATUS_AVAILABLE) {
        console.log('Ambulance is not available');
        alert('Can only dispatch available ambulances!');
        return;
    }

    // hide message if first button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').hide();

    // add ambulance to list of dispatching ambulances
    dispatchingAmbulances[ambulance.id] = true;
    numberOfDispatchingAmbulances++;

    // add button to ambulance dispatch grid
    $('#ambulance-selection').append(
        '<button id="dispatch-button-' + ambulance.id + '"'
        + ' value="' + ambulance.id + '"'
        + ' type="button" class="btn btn-sm btn-success"'
        + ' style="margin: 2px 2px;"'
        + ' draggable="true">'
        + ambulance.identifier
        + '</button>'
    );
    $('#dispatch-button-' + ambulance.id)
        .on('dragstart', function (e) {
            // on start of drag, copy information and fade button
            console.log('dragstart');
            this.style.opacity = '0.4';
            e.originalEvent.dataTransfer.setData("text/plain", ambulance.id);
        })
        .on('dragend', function (e) {
            console.log('dragend');
            if (e.originalEvent.dataTransfer.dropEffect == 'none') {
                // Remove button if not dropped back
                removeFromDispatchingList(ambulance);
                // Remove button
                $(this).remove();
            } else {
                // Restore opacity if dropped back in
                this.style.opacity = '1.0';
            }
        });
}

function geocode(query, options, callback) {

    var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/";

    // add query
    url += encodeURIComponent(query) + ".json";

    // add parameters
    var prefix = '?';

    for (var option in options) {
        if (options.hasOwnProperty(option)) {

            // add options
            url += prefix + encodeURIComponent(option) + "=" + encodeURIComponent(options[option]);
            prefix = '&';

        }
    }

    // add token
    if (!options.hasOwnProperty("access_token"))
        url += prefix + "access_token=" + accessToken;

    // query mapbox
    $.getJSON(url, function (response) {

        // callback
        if (callback)
            callback(response.features);

    })
        .fail(function (jqxhr, testStatus, error) {

            alert("Could not geocode:" +
                testStatus + "," + error + "\n");

        });

}

$("#street").change(function (data) {

    var address = document.getElementById('street').value;
    console.log('Received address: ' + address);

    var options = {
        types: 'address',
        limit: 1,
        autocomplete: 'true'
    };
    geocode(address, options, function (features) {

        var feature = features[0];
        alert('Got geocode ' + feature['place_name']);

    });

/*
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({address: addressInput}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coordinate = results[0].geometry.location;

            document.getElementById('curr-lat').innerHTML = coordinate.lat();
            document.getElementById('curr-lng').innerHTML = coordinate.lng();

            L.marker([coordinate.lat(), coordinate.lng()], {icon: placeIcon}).addTo(markersGroup);
            markersGroup.addTo(mymap);
            mymap.setView(new L.LatLng(coordinate.lat(), coordinate.lng()), 17);
        }
        else {
            alert("There is error from Google map server");
        }
    });
*/

});

/*
 * postDispatchCall makes an ajax post request to post dispatched ambulance.
 * @param void.
 * @return void.
 */
function postDispatchCall() {
    var formData = {};
    var assigned_ambulances = [];

    // Extract form value to JSON
    formData["stmain_number"] = $('#street').val();
    formData["residential_unit"] = $('#address').val();
    formData["latitude"] = document.getElementById('curr-lat').innerHTML;
    formData["longitude"] = document.getElementById('curr-lng').innerHTML;
    formData["active"] = true
    formData["name"] = "Make Dynamic for Future"
    console.log(formData["active"])

    console.log(formData["latitude"]);
    formData["description"] = $('#comment').val();
    formData["priority"] = $('input:radio[name=priority]:checked').val();
    $('input:checkbox[name="ambulance_assignment"]:checked').each(function (i) {
        assigned_ambulances[i] = $(this).val();
    });

    if (formData["priority"] == undefined) {
        alert("Please click one of priorities");
        return;
    }

    if (assigned_ambulances.length == 0) {
        alert("Please dispatch at least one ambulance");
        return;
    }

    formData["ambulance"] = assigned_ambulances.toString();

    let postJsonUrl = 'api/calls/';
    alert(JSON.stringify(formData) + '\n' + postJsonUrl);

    var csrftoken = getCookie('csrftoken');

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    })

    $.ajax({
        url: postJsonUrl,
        type: 'POST',
        dataType: 'json',
        data: formData,
        success: function (data) {
            // alert(JSON.stringify(data));
            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];
            $('.modal-body').html(successMsg).addClass('alert-success');
            $('.modal-title').append('Successfully Dispached');
            $("#dispatchModal").modal('show');
            endDispatching();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(JSON.stringify(jqXHR) + ' ' + textStatus);
            $('.modal-title').append('Dispatch failed');
            $("#dispatchModal").modal('show');
            endDispatching();
        }
    });
}

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

/*
 * getCookie extracts the csrf token for form submit
 */
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

/* Functions to fill autocomplete AND to click specific locations */
function dispatchInitAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    autocomplete = new google.maps.places.Autocomplete((document.getElementById('street')),
        {types: ['geocode']});
    //autocomplete.addListener('place_changed', fillInAddress);
}<commit_msg>Separating dispatch from map.js<commit_after>/* Dispatch area - Should be eliminate after dispatching */

var markersGroup = new L.LayerGroup();
var isDispatching = false;
var placeIcon = L.icon({
    iconUrl: '/static/icons/place_marker.png',
    iconSize: [50, 50], // size of the icon
});
var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var beginDispatching = function () {

    isDispatching = true;
    console.log('Begin dispatching.');

    document.getElementById('dispatch_work').innerHTML
        = '<button type="button" class="btn btn-link" onclick="endDispatching()">'
        + ''
        + 'Abort dispatching'
        + '</button>';
    $('#dispatchForm').collapse('show');
    $('#ambulance_info_collapse').collapse('hide');

    mymap.on('click', function (e) {

        markersGroup.clearLayers();
        document.getElementById('curr-lat').innerHTML = e.latlng.lat;
        document.getElementById('curr-lng').innerHTML = e.latlng.lng;
        if (isDispatching) {
            L.marker([e.latlng.lat, e.latlng.lng], {icon: placeIcon}).addTo(markersGroup);
            markersGroup.addTo(mymap);
        }

    });

}

var endDispatching = function () {

    isDispatching = false;
    dispatchingAmbulances = {};
    console.log('End dispatching.');

    markersGroup.clearLayers();
    document.getElementById('dispatch_work').innerHTML
        = '<button class="btn btn-primary" style="display: block; width: 100%;"'
        + 'data-toggle="collapse" href="#dispatchForm" onclick="beginDispatching()">'
        + 'Dispatch'
        + '</button>';
    $('#dispatchForm').collapse('hide');
    $('#ambulance_info_collapse').collapse('show');

}

var removeFromDispatchingList = function(ambulance) {

    // delete from dispatching list
    delete dispatchingAmbulances[ambulance.id];
    numberOfDispatchingAmbulances--;

    // show message if last button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').show();

}

var addToDispatchingList = function(ambulance) {

    // quick return if null or not dispatching
    if (ambulance == null || !isDispatching)
        return;

    // add ambulance to dispatching list
    console.log('Adding ambulance ' + ambulance.identifier + ' to dispatching list');

    // already in?
    if (ambulance.id in dispatchingAmbulances) {
        console.log('Already in dispatching list, skip');
        return;
    }

    // not available?
    if (ambulance.status != STATUS_AVAILABLE) {
        console.log('Ambulance is not available');
        alert('Can only dispatch available ambulances!');
        return;
    }

    // hide message if first button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').hide();

    // add ambulance to list of dispatching ambulances
    dispatchingAmbulances[ambulance.id] = true;
    numberOfDispatchingAmbulances++;

    // add button to ambulance dispatch grid
    $('#ambulance-selection').append(
        '<button id="dispatch-button-' + ambulance.id + '"'
        + ' value="' + ambulance.id + '"'
        + ' type="button" class="btn btn-sm btn-success"'
        + ' style="margin: 2px 2px;"'
        + ' draggable="true">'
        + ambulance.identifier
        + '</button>'
    );
    $('#dispatch-button-' + ambulance.id)
        .on('dragstart', function (e) {
            // on start of drag, copy information and fade button
            console.log('dragstart');
            this.style.opacity = '0.4';
            e.originalEvent.dataTransfer.setData("text/plain", ambulance.id);
        })
        .on('dragend', function (e) {
            console.log('dragend');
            if (e.originalEvent.dataTransfer.dropEffect == 'none') {
                // Remove button if not dropped back
                removeFromDispatchingList(ambulance);
                // Remove button
                $(this).remove();
            } else {
                // Restore opacity if dropped back in
                this.style.opacity = '1.0';
            }
        });
}

function geocode(query, options, callback) {

    var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/";

    // add query
    url += encodeURIComponent(query) + ".json";

    // add parameters
    var prefix = '?';

    for (var option in options) {
        if (options.hasOwnProperty(option)) {

            // add options
            url += prefix + encodeURIComponent(option) + "=" + encodeURIComponent(options[option]);
            prefix = '&';

        }
    }

    // add token
    if (!options.hasOwnProperty("access_token"))
        url += prefix + "access_token=" + accessToken;

    // query mapbox
    $.getJSON(url, function (response) {

        // callback
        if (callback)
            callback(response.features);

    })
        .fail(function (jqxhr, testStatus, error) {

            alert("Could not geocode:" +
                testStatus + "," + error + "\n");

        });

}

$("#street").change(function (data) {

    var address = document.getElementById('street').value;
    console.log('Received address: ' + address);

    var options = {
        types: 'address',
        limit: 1,
        autocomplete: 'true'
    };
    geocode(address, options, function (features) {

        // quick return if found nothing
        if (features.length == 0) {
            console.log('Got nothing from geocode');
            return;
        }

        // parse features into address
        var feature = features[0];
        var street = feature['place_name'];
        var latlng= feature['center'];

        alert('street = ' + street + '\nlatlng = ' + latlng);

    });

/*
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({address: addressInput}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coordinate = results[0].geometry.location;

            document.getElementById('curr-lat').innerHTML = coordinate.lat();
            document.getElementById('curr-lng').innerHTML = coordinate.lng();

            L.marker([coordinate.lat(), coordinate.lng()], {icon: placeIcon}).addTo(markersGroup);
            markersGroup.addTo(mymap);
            mymap.setView(new L.LatLng(coordinate.lat(), coordinate.lng()), 17);
        }
        else {
            alert("There is error from Google map server");
        }
    });
*/

});

/*
 * postDispatchCall makes an ajax post request to post dispatched ambulance.
 * @param void.
 * @return void.
 */
function postDispatchCall() {
    var formData = {};
    var assigned_ambulances = [];

    // Extract form value to JSON
    formData["stmain_number"] = $('#street').val();
    formData["residential_unit"] = $('#address').val();
    formData["latitude"] = document.getElementById('curr-lat').innerHTML;
    formData["longitude"] = document.getElementById('curr-lng').innerHTML;
    formData["active"] = true
    formData["name"] = "Make Dynamic for Future"
    console.log(formData["active"])

    console.log(formData["latitude"]);
    formData["description"] = $('#comment').val();
    formData["priority"] = $('input:radio[name=priority]:checked').val();
    $('input:checkbox[name="ambulance_assignment"]:checked').each(function (i) {
        assigned_ambulances[i] = $(this).val();
    });

    if (formData["priority"] == undefined) {
        alert("Please click one of priorities");
        return;
    }

    if (assigned_ambulances.length == 0) {
        alert("Please dispatch at least one ambulance");
        return;
    }

    formData["ambulance"] = assigned_ambulances.toString();

    let postJsonUrl = 'api/calls/';
    alert(JSON.stringify(formData) + '\n' + postJsonUrl);

    var csrftoken = getCookie('csrftoken');

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    })

    $.ajax({
        url: postJsonUrl,
        type: 'POST',
        dataType: 'json',
        data: formData,
        success: function (data) {
            // alert(JSON.stringify(data));
            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];
            $('.modal-body').html(successMsg).addClass('alert-success');
            $('.modal-title').append('Successfully Dispached');
            $("#dispatchModal").modal('show');
            endDispatching();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(JSON.stringify(jqXHR) + ' ' + textStatus);
            $('.modal-title').append('Dispatch failed');
            $("#dispatchModal").modal('show');
            endDispatching();
        }
    });
}

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

/*
 * getCookie extracts the csrf token for form submit
 */
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

/* Functions to fill autocomplete AND to click specific locations */
function dispatchInitAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    autocomplete = new google.maps.places.Autocomplete((document.getElementById('street')),
        {types: ['geocode']});
    //autocomplete.addListener('place_changed', fillInAddress);
}<|endoftext|>


<commit_before>// Main
import postcss          from 'gulp-postcss';
import gulp             from 'gulp';

// Gulp-plugins
import rmvHtmlComnts    from 'gulp-remove-html-comments';
import prefix           from 'gulp-autoprefixer';
import sourcemaps       from 'gulp-sourcemaps';
import jsonlint         from 'gulp-jsonlint';
import htmlmin          from 'gulp-htmlmin';
import plumber          from 'gulp-plumber';
import changed          from 'gulp-changed';
import rename           from 'gulp-rename';
import concat           from 'gulp-concat';
import jshint           from 'gulp-jshint';
import notify           from 'gulp-notify';
import babel            from 'gulp-babel';
import jscpd            from 'gulp-jscpd';
import debug            from 'gulp-debug';
import uglify           from 'gulp-uglify';
import sass             from 'gulp-sass';
import csso             from 'gulp-csso';
import gulpIf           from 'gulp-if';

// Postcss-plugins
import colorShort       from 'postcss-color-short';
import pxtorem          from 'postcss-pxtorem';
import focus            from 'postcss-focus';
import size             from 'postcss-size';

// Other
import imageminPngquant from 'imagemin-pngquant';
import combiner         from 'stream-combiner2';
import imagemin         from 'gulp-imagemin';
import cp               from 'child_process';
import cssMqpacker      from 'css-mqpacker';
import browserSync      from 'browser-sync';
import del              from 'del';

const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV === 'devlopment'; // NODE_ENV=production gulp

const paths = {
  // css
  css: {
    sassAll:  'assets/css/*/*/*.*',
    sassMain: 'assets/css/main.sass',
    cssMin:   'assets/css/min/'
  },

  // js
  js: {
    jsMain: 'assets/js/*.js',
    jsMin:  'assets/js/min/'
  },

  //images
  img: {
    imagesAll: 'assets/img/*.*',
    imagesMin: 'assets/img/min/'
  },

  // html
  html: {
    includes: '_includes/*.html',
    site:     '_site',
    main:     '*.html',
    posts:    '_includes/posts/*.html'
  },

  // markdowm
  markdown: {
    posts: '_posts/*.markdown'
  }
}

const jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll',
  messages = {
    build: 'Running: jekyll build'
};

// Assets
// ========================
gulp.task('assets:css', () => {
  let processors = [
      cssMqpacker,
      colorShort,
      pxtorem,
      focus,
      size
    ]
  let combined = combiner.obj([
    gulp.src(paths.css.sassMain),
      plumber(),
      changed(paths.css.cssMin),
      gulpIf(isDevelopment, sourcemaps.init()),
      sass({
        includePaths: ['assets/css/'],
        onError: browserSync.notify
      }),
      postcss(processors),
      prefix({ browsers: ['> 1%', 'ie 8', 'ie 7', 'ie 6'], cascade: false }),
      csso(),
      rename({suffix: '.min'}),
      debug({title: 'Checking CSS:'}),
      gulpIf(isDevelopment, sourcemaps.write('.')),
      gulp.dest(paths.css.cssMin)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});
gulp.task('assets:js', () => {
  let combined = combiner.obj([
    gulp.src(paths.js.jsMain),
      plumber(),
      changed(paths.js.jsMain),
      jshint({esversion: 6}),
      jshint.reporter('jshint-stylish'),
      babel({
        presets: ['es2015']
      }),
      jscpd(),
      concat(paths.js.jsMain),
      //uglify(),
      rename({
        dirname: paths.js.jsMin,
        basename: "common",
        suffix: ".min",
        extname: ".js"
      }),
      debug({title: 'Checking JavaScript:'}),
    gulp.dest('./')
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});
// gulp.task('assets:json', () => {
//   let combined = combiner.obj([
//     gulp.src('*.json'),
//       plumber(),
//       jsonlint(),
//       jsonlint.reporter(),
//       jsonlint.failOnError(),
//       debug({title: 'Checking JSON:'}),
//     gulp.dest('.')
//   ])
//   combined.on('error', console.error.bind(console))
//   return combined;
// });
gulp.task('assets:image', () => {
  let combined = combiner.obj([
    gulp.src(paths.img.imagesAll),
      changed(paths.img.imagesMin),
      imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [imageminPngquant()]
      }),
      debug({title: 'Checking Images:'}),
    gulp.dest(paths.img.imagesMin)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});

// Browser
// ========================
gulp.task('browser:build', done => {
  browserSync.notify(messages.build);
  return cp.spawn( jekyll , ['build'], {stdio: 'inherit'})
    .on('close', done)
});
gulp.task('browser:rebuild', () => browserSync.reload());
gulp.task('browser:sync', () => {
  browserSync.init({
    server: {
      baseDir: paths.html.site
    },
    host: "localhost",
    notify: false
  })
  gulp.watch(paths.css.sassMain, gulp.series('assets:css', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.css.sassAll, gulp.series('assets:css', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.js.jsMain, gulp.series('assets:js', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.includes, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.main, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.posts, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.markdown.posts, gulp.series('browser:build', 'browser:rebuild'));
});

// Cleen
// ========================
gulp.task('clean:del', done => {
  return del(paths.html.site)
  done();
});

// DEPLOY
// html
gulp.task('deploy:html', () => {
  let combined = combiner.obj([
    gulp.src(paths.html.includes),
      rmvHtmlComnts(),
      htmlmin({collapseWhitespace: true}),
      debug({title: 'Checking HTML:'}),
    gulp.dest(paths.html.includes)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});

// image
gulp.task('deploy:image', () => {
  let combined = combiner.obj([
    gulp.src(paths.img.imagesAll),
      imageminPngquant({quality: '100', speed: 1})(),
      debug({title: 'Checking Images:'}),
    gulp.dest(paths.img.imagesMin)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});

const browser = gulp.parallel('browser:build', 'browser:rebuild', 'browser:sync');
const assets = gulp.parallel('assets:js', 'assets:css', /*'assets:json',*/ 'assets:image');
const clean = gulp.parallel('clean:del');
const build = gulp.series(clean, gulp.parallel(assets, browser));
const deploy = gulp.parallel('deploy:image', 'deploy:html');
export { build, clean, assets, browser, deploy };
export default build;
<commit_msg>add webpack module system<commit_after>// Main
import postcss          from 'gulp-postcss';
import gulp             from 'gulp';

// Gulp-plugins
import strip            from 'gulp-strip-comments';
import prefix           from 'gulp-autoprefixer';
import sourcemaps       from 'gulp-sourcemaps';
import jsonlint         from 'gulp-jsonlint';
import htmlmin          from 'gulp-htmlmin';
import plumber          from 'gulp-plumber';
import changed          from 'gulp-changed';
import rename           from 'gulp-rename';
import concat           from 'gulp-concat';
import jshint           from 'gulp-jshint';
import notify           from 'gulp-notify';
import babel            from 'gulp-babel';
import jscpd            from 'gulp-jscpd';
import debug            from 'gulp-debug';
import uglify           from 'gulp-uglify';
import sass             from 'gulp-sass';
import csso             from 'gulp-csso';
import gulpIf           from 'gulp-if';

// Postcss-plugins
import colorShort       from 'postcss-color-short';
import pxtorem          from 'postcss-pxtorem';
import focus            from 'postcss-focus';
import size             from 'postcss-size';

// Other
import imageminPngquant from 'imagemin-pngquant';
import combiner         from 'stream-combiner2';
import webpack          from 'webpack-stream';
import imagemin         from 'gulp-imagemin';
import cp               from 'child_process';
import cssMqpacker      from 'css-mqpacker';
import browserSync      from 'browser-sync';
import del              from 'del';

const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV === 'devlopment'; // NODE_ENV=production gulp

const paths = {
  // css
  css: {
    sassAll:  'assets/css/*/*/*.*',
    sassMain: 'assets/css/main.sass',
    cssMin:   'assets/css/min/'
  },

  // js
  js: {
    jsMain:    'assets/js/common.js',
    jsMin:     'assets/js/min/',
    jsModules: 'assets/js/modules/*.js'
  },

  //images
  img: {
    imagesAll: 'assets/img/*.*',
    imagesMin: 'assets/img/min/'
  },

  // html
  html: {
    includes: '_includes/*.html',
    layouts:  '_layouts/*.html',
    site:     '_site',
    main:     '*.html',
    posts:    '_includes/posts/*.html'
  },

  // markdowm
  markdown: {
    posts: '_posts/*.markdown'
  },

  json: {
    jsonSearch: '_site/data/*.json'
  }
}

const jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll',
  messages = {
    build: 'Running: jekyll build'
};

// Assets
// ========================
// CSS
gulp.task('assets:css', () => {
  let processors = [
      cssMqpacker,
      colorShort,
      pxtorem,
      focus,
      size
    ]
  let combined = combiner.obj([
    gulp.src(paths.css.sassMain),
      plumber(),
      changed(paths.css.cssMin),
      gulpIf(isDevelopment, sourcemaps.init()),
      sass({
        includePaths: ['assets/css/'],
        onError: browserSync.notify
      }),
      postcss(processors),
      prefix({ browsers: ['> 1%', 'ie 8', 'ie 7', 'ie 6'], cascade: false }),
      // csso(),
      rename({
        dirname: paths.css.cssMin,
        basename: "main",
        suffix: ".min",
        extname: ".css"
      }),
      debug({title: 'Checking CSS:'}),
      gulpIf(isDevelopment, sourcemaps.write('.')),
      gulp.dest(paths.css.cssMin)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});
// JS
gulp.task('assets:js', () => {
  let combined = combiner.obj([
    gulp.src(paths.js.jsMain),
      plumber(),
      changed('.'),
      webpack(),
      jshint({
        esversion: 6
      }),
      jshint.reporter('jshint-stylish'),
      babel({
        presets: ['es2015']
      }),
      jscpd(),
      // uglify(),
      strip(),
      rename({
        dirname: paths.js.jsMin,
        basename: "common",
        suffix: ".min",
        extname: ".js"
      }),
      debug({title: 'Checking JavaScript:'}),
    gulp.dest('./')
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});
// IMG
gulp.task('assets:image', () => {
  let combined = combiner.obj([
    gulp.src(paths.img.imagesAll),
      changed(paths.img.imagesMin),
      imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [imageminPngquant()]
      }),
      debug({title: 'Checking Images:'}),
    gulp.dest(paths.img.imagesMin)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});

// Browser
// ========================
gulp.task('browser:build', done => {
  browserSync.notify(messages.build);
  return cp.spawn( jekyll , ['build'], {stdio: 'inherit'})
    .on('close', done)
});
gulp.task('browser:rebuild', () => browserSync.reload());
gulp.task('browser:sync', () => {
  browserSync.init({
    server: {
      baseDir: paths.html.site
    },
    host: "localhost",
    notify: false
  })
  gulp.watch(paths.css.sassMain, gulp.series('assets:css', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.css.sassAll, gulp.series('assets:css', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.js.jsMain, gulp.series('assets:js', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.js.jsModules, gulp.series('assets:js', 'browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.includes, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.layouts, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.main, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.html.posts, gulp.series('browser:build', 'browser:rebuild'));
  gulp.watch(paths.markdown.posts, gulp.series('browser:build', 'browser:rebuild'));
});

// Cleen
// ========================
gulp.task('clean:del', done => {
  return del(paths.html.site)
  done();
});

// DEPLOY
// ========================
// HTML
gulp.task('deploy:html', () => {
  let combined = combiner.obj([
    gulp.src(paths.html.includes),
      htmlmin({collapseWhitespace: true}),
      srip(),
      debug({title: 'Checking HTML:'}),
    gulp.dest(paths.html.includes)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});
// IMG
gulp.task('deploy:image', () => {
  let combined = combiner.obj([
    gulp.src(paths.img.imagesAll),
      imageminPngquant({quality: '100', speed: 1})(),
      debug({title: 'Checking Images:'}),
    gulp.dest(paths.img.imagesMin)
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});
// JSON
gulp.task('deploy:json', () => {
  let combined = combiner.obj([
    gulp.src(paths.json.jsonSearch),
      plumber(),
      jsonlint(),
      jsonlint.reporter(),
      jsonlint.failOnError(),
      debug({title: 'Checking JSON:'}),
    gulp.dest('.')
  ])
  combined.on('error', console.error.bind(console))
  return combined;
});

const browser = gulp.parallel('browser:build', 'browser:rebuild', 'browser:sync');
const assets = gulp.parallel('assets:js', 'assets:css', 'assets:image');
const clean = gulp.parallel('clean:del');
const build = gulp.series(clean, gulp.parallel(browser, assets));
const deploy = gulp.parallel('deploy:image', 'deploy:html', 'deploy:json');
export { build, clean, assets, browser, deploy };
export default build;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  function Vector() {
    var self = this;
    self.values = [];
    self.length = 0;

    // Opt 1
    //  1 Stopping making new array and slicing arguments into it
    //  2 Using for loop rather than .forEach(fn)

    /*

    [].slice.call(arguments, 0)
      .forEach(function(argument) {
        if(argument instanceof Vector)
          self = argument;
        else {
          self.push(argument);
          self.length = self.values.length;
        }
      });

    */
    var argument;

    for (var c = 0, l = arguments.length; c < l; c++) {
      argument = arguments[c];
      if(argument instanceof Vector)
        self = argument;
      else {
        self.push(argument);
        self.length = self.values.length;
      }
    }

    return self;
  }

  // array of arguments to function arguments (e.g. f.construct([a, b, c]) => f(a, b, c))
  Function.prototype.construct = function(args) {
    var object = Object.create(this.prototype);
    this.apply(object, args);
    return object;
  };

  Vector.prototype.add = function(vector) {
    if(this.length !== vector.length)
      throw 'Error: sizes do not match!';

    // Opt 2
    //  Using for loop instead of map. Caching values arrays.

    var res = new Vector();
    var my_vals = this.values, its_vals = vector.values;

    for (var c = 0, l = this.length; c < l; c++) {
      res.push(my_vals[c] + its_vals[c]);
    };
    return res;
  };

  Vector.prototype.subtract = function(vector) {
    if(this.length !== vector.length)
      throw 'Error: sizes do not match!';

    // Opt 3
    //  Using for loop instead of map. Caching values arrays.

    var res = new Vector();
    var my_vals = this.values, its_vals = vector.values;

    for (var c = 0, l = this.length; c < l; c++) {
      res.push(my_vals[c] - its_vals[c]);
    };
    return res;
  };

  Vector.prototype.scale = function(scalar) {
    var res = new Vector();
    var my_vals = this.values;

    // Opt 4
    //  Using for loop instead of map. Caching values array.

    for (var c = 0, l = this.length; c < l; c++) {
      res.push(my_vals[c] * scalar);
    };
    return res;
  };

  Vector.prototype.normalize = function() {
    return this.scale(1 / this.length);
  };

  Vector.prototype.project = function(vector) {
    return Vector.construct(
      vector
        .normalize()
        .scale(this.magnitude() * Math.cos(this.dot(vector) / (this.magnitude() * vector.magnitude())))
    );
  };

  Vector.prototype.zeros = function(count) {
    // Opt 5
    //  Use for loop instead of Array.apply and .map

    var values = this.values = new Array(count);
    for (var c = 0; c < count; c++) {
      values[c] = 0;
    };
    this.length = count;
    return this;
  };

  Vector.prototype.ones = function(count) {
    // Opt 6
    //  Use for loop instead of Array.apply and .map

    var values = this.values = new Array(count);
    for (var c = 0; c < count; c++) {
      values[c] = 1;
    };
    this.length = count;
    return this;
  };

  Vector.prototype.range = function() {
    var args = [].slice.call(arguments, 0),
        start, step, end;

    switch(args.length) {
      case 2:
        end = args.pop();
        step = 1;
        start = args.pop();
        break;
      case 3:
        end = args.pop();
        step = args.pop();
        start = args.pop();
        break;
      default:
        throw 'Error: invalid range!';
    }

    if(end - start < 0) {
      var copy = end;
      end = start;
      start = copy;
    }

    if(step > end - start)
      throw 'Error: invalid range!';

    var i;
    for(i = start; i < end - step; i += step)
      this.push(i);

    return Vector.construct(this.values);
  };

  Vector.prototype.dot = function(vector) {
    if(this.length !== vector.length)
      throw 'Error: sizes do not match!';

    return this.values
      .map(function(value, index) {
        return value * vector.values[index];
      })
      .reduce(function(previous, current) {
        return previous + current;
      });
  };

  Vector.prototype.magnitude = function() {
    return Math.sqrt(this.values
      .map(function(value) {
        return value * value;
      })
      .reduce(function(previous, current) {
        return previous + current;
      })
    );
  };

  Vector.prototype.angle = function(vector) {
    return Math.acos(this.dot(vector) / this.magnitude() * vector.magnitude());
  };

  Vector.prototype.equals = function(vector) {
    if(this.length !== vector.length)
      return false;

    var my_values = this.values, its_values = vector.values;

    var c = 0, l = this.length;
    while(c < l && my_values[c] === its_values[c++]) {};

    return (c === l);

    // Fix 1
    //  Bug: Returning true when they are not equal
    // Opt 7
    //  Use fast loop to check equality
    //   Douglas Crockford would not approve: https://www.youtube.com/watch?v=taaEzHI9xyY&t=50m42s

  };

  Vector.prototype.get = function(index) {
    return this.values[index];
  };

  Vector.prototype.min = function() {
    // Opt 8
    //  For loop rather than .each(fn)
    //  values caching

    var min = Number.POSITIVE_INFINITY;
    var val, my_values = this.values;

    for (var c = 0, l = this.length; c < l; c++) {
      val = my_values[c];
      if (val < min) min = val;
    }

    return min;
  };

  Vector.prototype.max = function() {
    // Opt 9
    //  For loop rather than .each(fn)
    //  values caching

    var max = Number.NEGATIVE_INFINITY;
    var val, my_values = this.values;

    for (var c = 0, l = this.length; c < l; c++) {
      val = my_values[c];
      if (val > max) max = val;
    }

    return max;
  };

  Vector.prototype.set = function(index, value) {
    this.values[index] = value;
    return this;
  };

  Vector.prototype.combine = function(vector) {
    var self = this;
    vector.values.forEach(function(value) {
      self.push(value);
    });

    return this;
  };

  Vector.prototype.push = function(value) {
    this.values.push(value);
    this.length++;
    return this;
  };

  Vector.prototype.map = function(callback) {
    return Vector.construct(this.values.map(function(value) {
      return callback(value);
    }));
  };

  Vector.prototype.each = function(callback) {
    this.values.forEach(function(value, index) {
      callback(value, index);
    });

    return this;
  };

  Vector.prototype.toString = function() {
    return '[' + this.values.join(', ') + ']';
  };

  Vector.prototype.toArray = function() {
    return this.values;
  };

  module.exports = Vector;
})();<commit_msg>Opt 10 - Vector combine Opt 11 - Vector each<commit_after>(function() {
  'use strict';

  function Vector() {
    var self = this;
    self.values = [];
    self.length = 0;

    // Opt 1
    //  1 Stopping making new array and slicing arguments into it
    //  2 Using for loop rather than .forEach(fn)

    /*

    [].slice.call(arguments, 0)
      .forEach(function(argument) {
        if(argument instanceof Vector)
          self = argument;
        else {
          self.push(argument);
          self.length = self.values.length;
        }
      });

    */
    var argument;

    for (var c = 0, l = arguments.length; c < l; c++) {
      argument = arguments[c];
      if(argument instanceof Vector)
        self = argument;
      else {
        self.push(argument);
        self.length = self.values.length;
      }
    }

    return self;
  }

  // array of arguments to function arguments (e.g. f.construct([a, b, c]) => f(a, b, c))
  Function.prototype.construct = function(args) {
    var object = Object.create(this.prototype);
    this.apply(object, args);
    return object;
  };

  Vector.prototype.add = function(vector) {
    if(this.length !== vector.length)
      throw 'Error: sizes do not match!';

    // Opt 2
    //  Using for loop instead of map. Caching values arrays.

    var res = new Vector();
    var my_vals = this.values, its_vals = vector.values;

    for (var c = 0, l = this.length; c < l; c++) {
      res.push(my_vals[c] + its_vals[c]);
    };
    return res;
  };

  Vector.prototype.subtract = function(vector) {
    if(this.length !== vector.length)
      throw 'Error: sizes do not match!';

    // Opt 3
    //  Using for loop instead of map. Caching values arrays.

    var res = new Vector();
    var my_vals = this.values, its_vals = vector.values;

    for (var c = 0, l = this.length; c < l; c++) {
      res.push(my_vals[c] - its_vals[c]);
    };
    return res;
  };

  Vector.prototype.scale = function(scalar) {
    var res = new Vector();
    var my_vals = this.values;

    // Opt 4
    //  Using for loop instead of map. Caching values array.

    for (var c = 0, l = this.length; c < l; c++) {
      res.push(my_vals[c] * scalar);
    };
    return res;
  };

  Vector.prototype.normalize = function() {
    return this.scale(1 / this.length);
  };

  Vector.prototype.project = function(vector) {
    return Vector.construct(
      vector
        .normalize()
        .scale(this.magnitude() * Math.cos(this.dot(vector) / (this.magnitude() * vector.magnitude())))
    );
  };

  Vector.prototype.zeros = function(count) {
    // Opt 5
    //  Use for loop instead of Array.apply and .map

    var values = this.values = new Array(count);
    for (var c = 0; c < count; c++) {
      values[c] = 0;
    };
    this.length = count;
    return this;
  };

  Vector.prototype.ones = function(count) {
    // Opt 6
    //  Use for loop instead of Array.apply and .map

    var values = this.values = new Array(count);
    for (var c = 0; c < count; c++) {
      values[c] = 1;
    };
    this.length = count;
    return this;
  };

  Vector.prototype.range = function() {
    var args = [].slice.call(arguments, 0),
        start, step, end;

    switch(args.length) {
      case 2:
        end = args.pop();
        step = 1;
        start = args.pop();
        break;
      case 3:
        end = args.pop();
        step = args.pop();
        start = args.pop();
        break;
      default:
        throw 'Error: invalid range!';
    }

    if(end - start < 0) {
      var copy = end;
      end = start;
      start = copy;
    }

    if(step > end - start)
      throw 'Error: invalid range!';

    var i;
    for(i = start; i < end - step; i += step)
      this.push(i);

    return Vector.construct(this.values);
  };

  Vector.prototype.dot = function(vector) {
    if(this.length !== vector.length)
      throw 'Error: sizes do not match!';

    return this.values
      .map(function(value, index) {
        return value * vector.values[index];
      })
      .reduce(function(previous, current) {
        return previous + current;
      });
  };

  Vector.prototype.magnitude = function() {
    return Math.sqrt(this.values
      .map(function(value) {
        return value * value;
      })
      .reduce(function(previous, current) {
        return previous + current;
      })
    );
  };

  Vector.prototype.angle = function(vector) {
    return Math.acos(this.dot(vector) / this.magnitude() * vector.magnitude());
  };

  Vector.prototype.equals = function(vector) {
    if(this.length !== vector.length)
      return false;

    var my_values = this.values, its_values = vector.values;

    var c = 0, l = this.length;
    while(c < l && my_values[c] === its_values[c++]) {};

    return (c === l);

    // Fix 1
    //  Bug: Returning true when they are not equal
    // Opt 7
    //  Use fast loop to check equality
    //   Douglas Crockford would not approve: https://www.youtube.com/watch?v=taaEzHI9xyY&t=50m42s

  };

  Vector.prototype.get = function(index) {
    return this.values[index];
  };

  Vector.prototype.min = function() {
    // Opt 8
    //  For loop rather than .each(fn)
    //  values caching

    var min = Number.POSITIVE_INFINITY;
    var val, my_values = this.values;

    for (var c = 0, l = this.length; c < l; c++) {
      val = my_values[c];
      if (val < min) min = val;
    }

    return min;
  };

  Vector.prototype.max = function() {
    // Opt 9
    //  For loop rather than .each(fn)
    //  values caching

    var max = Number.NEGATIVE_INFINITY;
    var val, my_values = this.values;

    for (var c = 0, l = this.length; c < l; c++) {
      val = my_values[c];
      if (val > max) max = val;
    }

    return max;
  };

  Vector.prototype.set = function(index, value) {
    this.values[index] = value;
    return this;
  };

  Vector.prototype.combine = function(vector) {
    // Opt 10
    //  Use for loop
    //  Use cached its_values

    //var self = this;
    var its_values = vector.values;
    for (var c = 0, l = vector.length; c < l; c++) {
      this.push(its_values[c]);
    }

    //vector.values.forEach(function(value) {
    //  self.push(value);
    //});

    return this;
  };

  Vector.prototype.push = function(value) {
    this.values.push(value);
    this.length++;
    return this;
  };

  Vector.prototype.map = function(callback) {
    return Vector.construct(this.values.map(function(value) {
      return callback(value);
    }));
  };

  Vector.prototype.each = function(callback) {
    // Opt 11
    //  Remove inner function call

    this.values.forEach(callback);

    //this.values.forEach(function(value, index) {
    //  callback(value, index);
    //});

    return this;
  };

  Vector.prototype.toString = function() {
    return '[' + this.values.join(', ') + ']';
  };

  Vector.prototype.toArray = function() {
    return this.values;
  };

  module.exports = Vector;
})();<|endoftext|>