<commit_before>/**
 * Module dependencies
 * @type {Object}
 */
var util = require('util');
var _ = require('lodash');
var path = require('path');
var async = require('async');
var report = require('reportback')();

var generate = require('./generate');
var FolderHelper = require('./helpers/folder');
var TemplateHelper = require('./helpers/template');
var JSONFileHelper = require('./helpers/jsonfile');
var CopyHelper = require('./helpers/copy');
var NOOP_GENERATOR = require('./rootGenerator');

/**
 * generateTarget()
 *
 * @param  {Object}   options
 */

function generateTarget(options, cb) {

  var sb = report.extend(cb);

  // Options
  var target = options.target;
  var scope = options.scope;
  var parentGenerator = options.parent;
  var recursiveGenerate = options.recursiveGenerate;

  var MAX_RESOLVES = 5,
    _resolves = 0;

  async.until(
    function checkIfTargetIsValidYet() {
      return isValidTarget(target) || (++_resolves > MAX_RESOLVES);
    },
    function tryToParseTarget(async_cb) {
      parseTarget(target, scope, function(err, resolvedTarget) {
        if (err) return async_cb(err);
        target = resolvedTarget;
        return async_cb();
      });
    },
    function afterwards(err) {
      if (err) return sb(err);
      if (!isValidTarget(target)) {
        return sb(new Error('Generator Error: Could not resolve target "' + scope.rootPath + '" (probably a recursive loop)'));
      }

      // Pass down parent Generator's template directory abs path
      scope.templatesDirectory = parentGenerator.templatesDirectory;

      // Interpret generator definition
      if (target.exec) {
        return target.exec(scope, sb);
      }
      if (target.copy) {
        scope = mergeSubtargetScope(scope, typeof target.copy === 'string' ? {
          templatePath: target.copy
        } : target.copy);
        return CopyHelper(scope, sb);
      }
      if (target.folder) {
        scope = mergeSubtargetScope(scope, target.folder);
        return FolderHelper(scope, sb);
      }
      if (target.template) {
        scope = mergeSubtargetScope(scope, typeof target.template === 'string' ? {
          templatePath: target.template
        } : target.template);

        return TemplateHelper(scope, sb);
      }
      if (target.jsonfile) {
        if (typeof target.jsonfile === 'object') {
          scope = mergeSubtargetScope(scope, target.jsonfile);
        } else if (typeof target.jsonfile === 'function') {
          scope = _.merge(scope, {
            data: target.jsonfile(scope)
          });
        }
        return JSONFileHelper(scope, sb);
      }

      // If we made it here, this must be a recursive generator:

      // Now that the generator definition has been resolved,
      // call this method recursively on it, passing along our
      // callback:
      if (++scope._depth > scope.maxHops) {
        return sb(new Error('`maxHops` (' + scope.maxHops + ' exceeded!  There is probably a recursive loop in one of your generators.'));
      }
      return recursiveGenerate(target, scope, sb);

    }
  ); //</ async.until >//
}

module.exports = generateTarget;

/**
 * @param  {[type]} scope     [description]
 * @param  {[type]} subtarget [description]
 * @return {[type]}           [description]
 */
function mergeSubtargetScope(scope, subtarget) {
  return _.merge(scope, _.isObject(subtarget) ? subtarget : {});
}

/**
 * Known helpers
 * @type {Array}
 */
var KNOWN_HELPERS = ['exec', 'folder', 'template', 'jsonfile', 'file', 'copy'];

function targetIsHelper(target) {
  return _.some(target, function(subTarget, key) {
    return _.contains(KNOWN_HELPERS, key);
  });
}

/**
 *
 * @param  {String|Object}   target      [description]
 * @param  {Object}          scope [description]
 * @param  {Function} cb          [description]
 * @return {[type]}               [description]
 */
function parseTarget(target, scope, cb) {

  if (typeof target === 'string') {
    target = {
      generator: target
    };
  }

  // Interpret generator definition
  if (targetIsHelper(target)) {
    return cb(null, target);
  }

  if (target.generator) {

    // Normalize the subgenerator reference
    var subGeneratorRef;
    if (typeof target.generator === 'string') {
      subGeneratorRef = {
        module: target.generator
      };
    } else if (typeof target.generator === 'object') {
      subGeneratorRef = target.generator;
    }
    if (!subGeneratorRef) {
      return cb(new Error('Generator Error: Invalid subgenerator referenced for target "' + scope.rootPath + '"'));
    }

    // Now normalize the sub-generator
    var subGenerator;

    // No `module` means we'll treat this subgenerator as an inline generator definition.
    if (!subGeneratorRef.module) {
      subGenerator = subGeneratorRef;
      if (subGenerator) return cb(null, subGenerator);
    }

    //
    // Otherwise, we'll attempt to load this subgenerator.
    //

    if (typeof subGeneratorRef.module === 'string') {
      // Lookup the generator by name if a `module` was specified
      // (this allows the module for a given generator to be
      //  overridden.)
      var configuredReference = scope.modules && scope.modules[subGeneratorRef.module];

      // Refers to a configured module (i.e. sailsrc or comparable)
      // so keep going.
      if (configuredReference) {
        return cb(null, configuredReference);
      }

      // If this generator type is explicitly set to `false`,
      // disable the generator.
      else if (configuredReference === false) {
        return cb(null, NOOP_GENERATOR);
      }

      // If `configuredReference` is undefined, continue on
      // and try to require the module.
      //
      // ||
      // \/
    }

    // At this point, subGeneratorRef.module should be a string,
    // and the best guess at the generator module we're going
    // to get.
    var module = subGeneratorRef.module;
    var requireError;
    try {
      subGenerator = require(module);
    } catch (e0) {
      requireError = e0;
    }

    // Try the scope's rootPath
    if (!subGenerator) {
      try {
        var asDependencyInRootPath = path.resolve(scope.rootPath, 'node_modules', module);
        subGenerator = require(asDependencyInRootPath);
      } catch (e1) {
        requireError = e1;
      }
    }

    // Try the current working directory
    if (!subGenerator) {
      try {
        subGenerator = require(path.resolve(process.cwd(), 'node_modules', module));
      } catch (e1) {
        requireError = e1;
      }
    }

    // If we couldn't find a generator using the configured module,
    // try requiring "sails-generate-<module>" to get the core generator
    if (!subGenerator && !module.match(/^sails-generate-/)) {
      try {
        subGenerator = require('sails-generate-' + module);
      }

      // Ok, we give up.
      catch (e1) {
        requireError = e1;
      }
    }

    // If we were able to find it, send it back!
    if (subGenerator) return cb(null, subGenerator);

    // But if we still can't find it, give up.

    // TODO: look for subGeneratorRef on npm
    // TODO: emit a message to scope.output letting user know what's going on
    return cb(
      new Error('Generator Error: Failed to load "' +
        subGeneratorRef.module + '"...' +
        (requireError ? ' (' + requireError + ')' : '') +
        ''));

  } //fi// target.generator

  return cb(new Error(
    'Unrecognized generator syntax in `targets["' + scope.keyPath + '"]` ::\n' +
    util.inspect(target)));
}

/**
 *
 * @param  {[type]}  target [description]
 * @return {Boolean}        [description]
 */
function isValidTarget(target) {
  var ok = true;

  ok = ok && typeof target === 'object';

  // Is using a helper
  // Or is another generator def.
  ok = ok && (targetIsHelper(target) || _.has(target, 'targets'));

  return ok;
}
<commit_msg>Added notes<commit_after>/**
 * Module dependencies
 * @type {Object}
 */
var util = require('util');
var _ = require('lodash');
var path = require('path');
var async = require('async');
var report = require('reportback')();

var generate = require('./generate');
var FolderHelper = require('./helpers/folder');
var TemplateHelper = require('./helpers/template');
var JSONFileHelper = require('./helpers/jsonfile');
var CopyHelper = require('./helpers/copy');
var NOOP_GENERATOR = require('./rootGenerator');

/**
 * generateTarget()
 *
 * @param  {Object}   options
 */

function generateTarget(options, cb) {

  var sb = report.extend(cb);

  // Options
  var target = options.target;
  var scope = options.scope;
  var parentGenerator = options.parent;
  var recursiveGenerate = options.recursiveGenerate;

  var MAX_RESOLVES = 5,
    _resolves = 0;

  async.until(
    function checkIfTargetIsValidYet() {
      return isValidTarget(target) || (++_resolves > MAX_RESOLVES);
    },
    function tryToParseTarget(async_cb) {
      parseTarget(target, scope, function(err, resolvedTarget) {
        if (err) return async_cb(err);
        target = resolvedTarget;
        return async_cb();
      });
    },
    function afterwards(err) {
      if (err) return sb(err);
      if (!isValidTarget(target)) {
        return sb(new Error('Generator Error: Could not resolve target "' + scope.rootPath + '" (probably a recursive loop)'));
      }

      // Pass down parent Generator's template directory abs path
      scope.templatesDirectory = parentGenerator.templatesDirectory;

      // Interpret generator definition
      if (target.exec) {
        return target.exec(scope, sb);
      }
      if (target.copy) {
        scope = mergeSubtargetScope(scope, typeof target.copy === 'string' ? {
          templatePath: target.copy
        } : target.copy);
        return CopyHelper(scope, sb);
      }
      if (target.folder) {
        scope = mergeSubtargetScope(scope, target.folder);
        return FolderHelper(scope, sb);
      }
      if (target.template) {
        scope = mergeSubtargetScope(scope, typeof target.template === 'string' ? {
          templatePath: target.template
        } : target.template);

        return TemplateHelper(scope, sb);
      }
      if (target.jsonfile) {
        if (typeof target.jsonfile === 'object') {
          scope = mergeSubtargetScope(scope, target.jsonfile);
        } else if (typeof target.jsonfile === 'function') {
          scope = _.merge(scope, {
            data: target.jsonfile(scope)
          });
        }
        return JSONFileHelper(scope, sb);
      }

      // If we made it here, this must be a recursive generator:

      // Now that the generator definition has been resolved,
      // call this method recursively on it, passing along our
      // callback:
      if (++scope._depth > scope.maxHops) {
        return sb(new Error('`maxHops` (' + scope.maxHops + ' exceeded!  There is probably a recursive loop in one of your generators.'));
      }
      return recursiveGenerate(target, scope, sb);

    }
  ); //</ async.until >//
}

module.exports = generateTarget;

/**
 * @param  {[type]} scope     [description]
 * @param  {[type]} subtarget [description]
 * @return {[type]}           [description]
 */
function mergeSubtargetScope(scope, subtarget) {
  return _.merge(scope, _.isObject(subtarget) ? subtarget : {});
}

/**
 * Known helpers
 * @type {Array}
 */
var KNOWN_HELPERS = ['exec', 'folder', 'template', 'jsonfile', 'file', 'copy'];

function targetIsHelper(target) {
  return _.some(target, function(subTarget, key) {
    return _.contains(KNOWN_HELPERS, key);
  });
}

/**
 *
 * @param  {String|Object}   target      [description]
 * @param  {Object}          scope [description]
 * @param  {Function} cb          [description]
 * @return {[type]}               [description]
 */
function parseTarget(target, scope, cb) {

  if (typeof target === 'string') {
    target = {
      generator: target
    };
  }

  // Interpret generator definition
  if (targetIsHelper(target)) {
    return cb(null, target);
  }

  if (target.generator) {

    // Normalize the subgenerator reference
    var subGeneratorRef;
    if (typeof target.generator === 'string') {
      subGeneratorRef = {
        module: target.generator
      };
    } else if (typeof target.generator === 'object') {
      subGeneratorRef = target.generator;
    }
    if (!subGeneratorRef) {
      return cb(new Error('Generator Error: Invalid subgenerator referenced for target "' + scope.rootPath + '"'));
    }

    // Now normalize the sub-generator
    var subGenerator;

    // No `module` means we'll treat this subgenerator as an inline generator definition.
    if (!subGeneratorRef.module) {
      subGenerator = subGeneratorRef;
      if (subGenerator) return cb(null, subGenerator);
    }

    //
    // Otherwise, we'll attempt to load this subgenerator.
    //

    if (typeof subGeneratorRef.module === 'string') {
      // Lookup the generator by name if a `module` was specified
      // (this allows the module for a given generator to be
      //  overridden.)
      var configuredReference = scope.modules && scope.modules[subGeneratorRef.module];

      // Refers to a configured module (i.e. sailsrc or comparable)
      // so keep going.
      if (configuredReference) {
        return cb(null, configuredReference);
      }

      // If this generator type is explicitly set to `false`,
      // disable the generator.
      else if (configuredReference === false) {
        return cb(null, NOOP_GENERATOR);
      }

      // If `configuredReference` is undefined, continue on
      // and try to require the module.
      //
      // ||
      // \/
    }

    // At this point, subGeneratorRef.module should be a string,
    // and the best guess at the generator module we're going
    // to get.
    var module = subGeneratorRef.module;
    var requireError;

    // Try requiring it directly as a path
    try {
      subGenerator = require(module);
    } catch (e0) {
      requireError = e0;
    }

    // Try the scope's rootPath
    if (!subGenerator) {
      try {
        var asDependencyInRootPath = path.resolve(scope.rootPath, 'node_modules', module);
        subGenerator = require(asDependencyInRootPath);
      } catch (e1) {
        requireError = e1;
      }
    }

    // Try the current working directory
    if (!subGenerator) {
      try {
        subGenerator = require(path.resolve(process.cwd(), 'node_modules', module));
      } catch (e1) {
        requireError = e1;
      }
    }

    // If we couldn't find a generator using the configured module,
    // try requiring "sails-generate-<module>" to get the core generator
    if (!subGenerator && !module.match(/^sails-generate-/)) {
      try {
        subGenerator = require('sails-generate-' + module);
      }

      // Ok, we give up.
      catch (e1) {
        requireError = e1;
      }
    }

    // If we were able to find it, send it back!
    if (subGenerator) return cb(null, subGenerator);

    // But if we still can't find it, give up.

    // TODO: look for subGeneratorRef on npm
    // TODO: emit a message to scope.output letting user know what's going on
    return cb(
      new Error('Generator Error: Failed to load "' +
        subGeneratorRef.module + '"...' +
        (requireError ? ' (' + requireError + ')' : '') +
        ''));

  } //fi// target.generator

  return cb(new Error(
    'Unrecognized generator syntax in `targets["' + scope.keyPath + '"]` ::\n' +
    util.inspect(target)));
}

/**
 *
 * @param  {[type]}  target [description]
 * @return {Boolean}        [description]
 */
function isValidTarget(target) {
  var ok = true;

  ok = ok && typeof target === 'object';

  // Is using a helper
  // Or is another generator def.
  ok = ok && (targetIsHelper(target) || _.has(target, 'targets'));

  return ok;
}
<|endoftext|>


<commit_before>Object.subclass("PlayerControls", {
    initialize: function(player, world, input, viewport) {
        this.player = player;
        this.world = world;
        this.input = input;
        this.viewport = viewport;

        // constraint:
        // - the player tanks turret follows the mouse
		var turretConstraint = bbb.always({
            solver: new DBPlanner(),
            ctx: {
                player: player,
                input: input
            },
            methods: function() {
                player.turretDirection.formula([input.position, input.position.x, input.position.y, player.position, player.position.x, player.position.y], function(mousePosition, mousePositionX, mousePositionY, playerPosition, playerPositionX, playerPositionY) {
                    return mousePosition.sub(playerPosition);
                });
            } }, function() {
                return player.turretDirection.equals((input.mouse).sub(player.position));
		});
		player.constraints.push(turretConstraint);
    },
    update: function(dt) {
        // move player tank
        player.velocity.set(Vector2.Zero);
        if(this.input.state("up")) this.player.velocity.addSelf(new Vector2(0, -1));
        if(this.input.state("left")) this.player.velocity.addSelf(new Vector2(-1, 0));
        if(this.input.state("down")) this.player.velocity.addSelf(new Vector2(0, 1));
        if(this.input.state("right")) this.player.velocity.addSelf(new Vector2(1, 0));

        // player fires a bullet
        if(this.input.pressed("leftclick")) {
            player.fireBullet(this.world, dt);
        }
    }
});

Object.subclass("CPUControls", {
    initialize: function(tank, world, input, viewport) {
        this.tank = tank;
        this.world = world;

        this.turretRotationSpeed = 45 * Math.PI / 180;
    },
    update: function(dt) {
        this.turretUpdate(dt);
        this.movementUpdate(dt);
        this.fireUpdate(dt);
    }
});

/*
Object.subclass("Line", {
    initialize: function(a, b) {
        this.a = a;
        this.b = b;
    }
});

Object.extend(Line, {
    forRay: function(pos, dir) {
        var a = dir.y / dir.x;
        var b = pos.y - a * pos.x;
        return new Line(a, b);
    }
});

Object.subclass("Ray", {
    initialize: function(pos, dir, ricochet) {

    }
});
*/

CPUControls.raycast = function(world, tank, color) {
    var pos = tank.position.copy(),
        dir = tank.turretDirection.normalizedCopy(),
        ricochets = tank.bulletRicochets;

    function linecast(tank, pos, dir) {
        var tile = tank.getTile(pos);
        while(tile.canFlyThrough()) {
            tile.marked = color;
            pos.addSelf(dir);
            tile = tank.getTile(pos);
        }
        tile.marked = "red";
    };
    function reflect(world, pos, dir) {
        var reflectCoords = world.map.positionToCoordinates(pos);
        pos.subSelf(dir);
        var prevCoords = world.map.positionToCoordinates(pos);
        if(reflectCoords.x == prevCoords.x) {
            dir.y *= -1;
        }
        if(reflectCoords.y == prevCoords.y) {
            dir.x *= -1;
        }
    };

    linecast(tank, pos, dir);

    while(ricochets > 0) {
        ricochets--;
        reflect(world, pos, dir);
        linecast(tank, pos, dir);
    }
};

CPUControls.subclass("BrownTurret", { // Bobby
    initialize: function($super, tank, world, input, viewport) {
        $super(tank, world, input, viewport);
        this.rotationDirection = 1;
    },
    turretUpdate: function(dt) {
        if(Math.random() < 0.02) {
            this.rotationDirection *= -1;
        }
        this.tank.turretDirection.rotateSelf(this.rotationDirection * this.turretRotationSpeed * dt);
    },
    movementUpdate: function(dt) {
	    this.tank.velocity.set(Vector2.Zero);
    },
    // fire on line of sight
    fireUpdate: function(dt) {
        var world = this.world;
        var map = world.map;
        var tank = this.tank;
        var pos = tank.position.copy();
        var dir = tank.turretDirection.normalizedCopy();

        CPUControls.raycast(world, tank, "brown");

        if(tank.getTile(player.position).marked == "brown") {
            this.tank.fireBullet(this.world, dt);
        };
    }
});

CPUControls.subclass("GreySoldier", { // Fred
    turretUpdate: function(dt) {
        // adjust turret direction randomly
        this.tank.turretDirection.rotateSelf(Math.PI / 180 * (Math.random() - 0.5) * 50);
    },
    movementUpdate: function(dt) {
	    // adjust direction randomly
	    this.tank.velocity.rotateSelf(Math.PI / 180 * (Math.random() - 0.5) * 50);
        //this.velocity.set(player.position.sub(this.position));
    },
    fireUpdate: function(dt) {
        var world = this.world;
        var map = world.map;
        var tank = this.tank;

        CPUControls.raycast(world, tank, "grey");

        if(tank.getTile(player.position).marked == "grey") {
            this.tank.fireBullet(this.world, dt);
        };
    }
});

CPUControls.subclass("TealHunter", { // Luzy
    turretUpdate: function(dt) {
        // turret strongly seek the player
        this.tank.turretDirection.set(player.position.sub(this.tank.position));
    },
    movementUpdate: function(dt) {
	    // defensive movement
	    var tank = this.tank;
	    tank.velocity.set(this.world.getGameObjects()
            .filter(function(object) {
                // take only bullets
                return object.name === "bullet";
            })
            .filter(function(bullet) {
                // take only near bullets into account
                return bullet.position.distance(tank.position) < 7 * 2; // tileSize
            })
            .filter(function(bullet) {
                // take only bullets that fly towards my tank into account
                var angle = tank.position.sub(bullet.position).getDirectedAngle(bullet.velocity);
                return angle >= -90 && angle <= 90;
            })
            .map(function(bullet) {
                // use cross product of bullet direction and position difference
                var a = bullet.velocity.copy();
                var b = tank.position.sub(bullet.position);
                var cross = [a.y - b.y, b.x - a.x, a.x * b.y - a.y * b.x];
                var dir = new Vector2(cross[0], cross[1]);
                dir.divFloatSelf(cross[2]);
                return dir;
            })
            .reduce(function(prev, velocity) {
                return prev.add(velocity);
            }, Vector2.Zero.copy())
        );
    },
    fireUpdate: function(dt) {
        var world = this.world;
        var map = world.map;
        var tank = this.tank;
        var pos = tank.position.copy();
        var dir = tank.turretDirection.normalizedCopy();

        CPUControls.raycast(world, tank, "teal");

        if(tank.getTile(player.position).marked == "teal") {
            this.tank.fireBullet(this.world, dt);
        };
    }
});

<commit_msg>unify fireUpdate<commit_after>Object.subclass("PlayerControls", {
    initialize: function(player, world, input, viewport) {
        this.player = player;
        this.world = world;
        this.input = input;
        this.viewport = viewport;

        // constraint:
        // - the player tanks turret follows the mouse
		var turretConstraint = bbb.always({
            solver: new DBPlanner(),
            ctx: {
                player: player,
                input: input
            },
            methods: function() {
                player.turretDirection.formula([input.position, input.position.x, input.position.y, player.position, player.position.x, player.position.y], function(mousePosition, mousePositionX, mousePositionY, playerPosition, playerPositionX, playerPositionY) {
                    return mousePosition.sub(playerPosition);
                });
            } }, function() {
                return player.turretDirection.equals((input.mouse).sub(player.position));
		});
		player.constraints.push(turretConstraint);
    },
    update: function(dt) {
        // move player tank
        player.velocity.set(Vector2.Zero);
        if(this.input.state("up")) this.player.velocity.addSelf(new Vector2(0, -1));
        if(this.input.state("left")) this.player.velocity.addSelf(new Vector2(-1, 0));
        if(this.input.state("down")) this.player.velocity.addSelf(new Vector2(0, 1));
        if(this.input.state("right")) this.player.velocity.addSelf(new Vector2(1, 0));

        // player fires a bullet
        if(this.input.pressed("leftclick")) {
            player.fireBullet(this.world, dt);
        }
    }
});

Object.subclass("CPUControls", {
    initialize: function(tank, world, input, viewport) {
        this.tank = tank;
        this.world = world;

        this.turretRotationSpeed = 45 * Math.PI / 180;
    },
    update: function(dt) {
        this.turretUpdate(dt);
        this.movementUpdate(dt);
        this.fireUpdate(dt);
    }
});

/*
Object.subclass("Line", {
    initialize: function(a, b) {
        this.a = a;
        this.b = b;
    }
});

Object.extend(Line, {
    forRay: function(pos, dir) {
        var a = dir.y / dir.x;
        var b = pos.y - a * pos.x;
        return new Line(a, b);
    }
});

Object.subclass("Ray", {
    initialize: function(pos, dir, ricochet) {

    }
});
*/

CPUControls.raycast = function(world, tank, color) {
    var pos = tank.position.copy(),
        dir = tank.turretDirection.normalizedCopy(),
        ricochets = tank.bulletRicochets;

    function linecast(tank, pos, dir) {
        var tile = tank.getTile(pos);
        while(tile.canFlyThrough()) {
            tile.marked = color;
            pos.addSelf(dir);
            tile = tank.getTile(pos);
        }
        tile.marked = "red";
    };
    function reflect(world, pos, dir) {
        var reflectCoords = world.map.positionToCoordinates(pos);
        pos.subSelf(dir);
        var prevCoords = world.map.positionToCoordinates(pos);
        if(reflectCoords.x == prevCoords.x) {
            dir.y *= -1;
        }
        if(reflectCoords.y == prevCoords.y) {
            dir.x *= -1;
        }
    };

    linecast(tank, pos, dir);

    while(ricochets > 0) {
        ricochets--;
        reflect(world, pos, dir);
        linecast(tank, pos, dir);
    }
};

CPUControls.subclass("BrownTurret", { // Bobby
    initialize: function($super, tank, world, input, viewport) {
        $super(tank, world, input, viewport);
        this.rotationDirection = 1;
    },
    turretUpdate: function(dt) {
        if(Math.random() < 0.02) {
            this.rotationDirection *= -1;
        }
        this.tank.turretDirection.rotateSelf(this.rotationDirection * this.turretRotationSpeed * dt);
    },
    movementUpdate: function(dt) {
	    this.tank.velocity.set(Vector2.Zero);
    },
    // fire on line of sight
    fireUpdate: function(dt) {
        CPUControls.raycast(this.world, this.tank, "brown");

        if(this.tank.getTile(player.position).marked == "brown") {
            this.tank.fireBullet(this.world, dt);
        };
    }
});

CPUControls.subclass("GreySoldier", { // Fred
    turretUpdate: function(dt) {
        // adjust turret direction randomly
        this.tank.turretDirection.rotateSelf(Math.PI / 180 * (Math.random() - 0.5) * 50);
    },
    movementUpdate: function(dt) {
	    // adjust direction randomly
	    this.tank.velocity.rotateSelf(Math.PI / 180 * (Math.random() - 0.5) * 50);
        //this.velocity.set(player.position.sub(this.position));
    },
    fireUpdate: function(dt) {
        CPUControls.raycast(this.world, this.tank, "grey");

        if(this.tank.getTile(player.position).marked == "grey") {
            this.tank.fireBullet(this.world, dt);
        };
    }
});

CPUControls.subclass("TealHunter", { // Luzy
    turretUpdate: function(dt) {
        // turret strongly seek the player
        this.tank.turretDirection.set(player.position.sub(this.tank.position));
    },
    movementUpdate: function(dt) {
	    // defensive movement
	    var tank = this.tank;
	    tank.velocity.set(this.world.getGameObjects()
            .filter(function(object) {
                // take only bullets
                return object.name === "bullet";
            })
            .filter(function(bullet) {
                // take only near bullets into account
                return bullet.position.distance(tank.position) < 7 * 2; // tileSize
            })
            .filter(function(bullet) {
                // take only bullets that fly towards my tank into account
                var angle = tank.position.sub(bullet.position).getDirectedAngle(bullet.velocity);
                return angle >= -90 && angle <= 90;
            })
            .map(function(bullet) {
                // use cross product of bullet direction and position difference
                var a = bullet.velocity.copy();
                var b = tank.position.sub(bullet.position);
                var cross = [a.y - b.y, b.x - a.x, a.x * b.y - a.y * b.x];
                var dir = new Vector2(cross[0], cross[1]);
                dir.divFloatSelf(cross[2]);
                return dir;
            })
            .reduce(function(prev, velocity) {
                return prev.add(velocity);
            }, Vector2.Zero.copy())
        );
    },
    fireUpdate: function(dt) {
        CPUControls.raycast(this.world, this.tank, "teal");

        if(this.tank.getTile(player.position).marked == "teal") {
            this.tank.fireBullet(this.world, dt);
        };
    }
});

<|endoftext|>


<commit_before>import React from 'react';
import {connect} from 'react-redux';
import {validate_token} from '../utils/http_functions'
import * as actionCreators from '../actions/auth';
import { bindActionCreators } from 'redux';
import { browserHistory } from 'react-router'

function mapStateToProps(state) {
    return {
        token: state.auth.token,
        userName: state.auth.userName,
        isAuthenticated: state.auth.isAuthenticated
    }
};

function mapDispatchToProps(dispatch) {
    return bindActionCreators(actionCreators, dispatch)
};

export function requireAuthentication(Component) {

    class AuthenticatedComponent extends React.Component {

        componentWillMount() {
            this.checkAuth();
            this.state = {
                loaded_if_needed: false
            }
        }

        componentWillReceiveProps(nextProps) {
            this.checkAuth(nextProps);
        }

        checkAuth(props = this.props) {
            if (!props.isAuthenticated) {
                let token = localStorage.getItem('token')
                if (!token) {
                    browserHistory.push('/home')

                } else {
                    return fetch('api/is_token_valid', {
                        method: 'post',
                        credentials: 'include',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({token: token})
                    })
                        .then(res => {
                            if (res.status === 200) {
                                this.props.loginUserSuccess(token)
                                this.setState({
                                    loaded_if_needed: true
                                })

                            } else {
                                browserHistory.push('/home')

                            }
                        })

                }

            } else {
                this.setState({
                    loaded_if_needed: true
                })
            }
        }

        render() {
            return (

                    {this.props.isAuthenticated && this.state.loaded_if_needed
                        ? <Component {...this.props}/>
                        : null
                    }

            )

        }
    }

    return connect(mapStateToProps, mapDispatchToProps)(AuthenticatedComponent);

}
<commit_msg>eslint fix AuthenticatedComponent<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { browserHistory } from 'react-router';
import * as actionCreators from '../actions/auth';

function mapStateToProps(state) {
    return {
        token: state.auth.token,
        userName: state.auth.userName,
        isAuthenticated: state.auth.isAuthenticated,
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators(actionCreators, dispatch);
}

export function requireAuthentication(Component) {
    class AuthenticatedComponent extends React.Component {
        componentWillMount() {
            this.checkAuth();
            this.state = {
                loaded_if_needed: false,
            };
        }

        componentWillReceiveProps(nextProps) {
            this.checkAuth(nextProps);
        }

        checkAuth(props = this.props) {
            if (!props.isAuthenticated) {
                const token = localStorage.getItem('token');
                if (!token) {
                    browserHistory.push('/home');
                } else {
                    fetch('api/is_token_valid', {
                        method: 'post',
                        credentials: 'include',
                        headers: {
                            'Accept': 'application/json', // eslint-disable-line quote-props
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ token }),
                    })
                        .then(res => {
                            if (res.status === 200) {
                                this.props.loginUserSuccess(token);
                                this.setState({
                                    loaded_if_needed: true,
                                });

                            } else {
                                browserHistory.push('/home');

                            }
                        });

                }
            } else {
                this.setState({
                    loaded_if_needed: true,
                });
            }
        }

        render() {
            return (

                    {this.props.isAuthenticated && this.state.loaded_if_needed
                        ? <Component {...this.props} />
                        : null
                    }

            );

        }
    }

    AuthenticatedComponent.propTypes = {
        loginUserSuccess: React.PropTypes.func,
        isAuthenticated: React.PropTypes.bool,
    };

    return connect(mapStateToProps, mapDispatchToProps)(AuthenticatedComponent);
}
<|endoftext|>


<commit_before>FaultedEarth = Ext.extend(gxp.Viewer, {

    legendTabTitle: "Legend",
	summaryId: null,

    constructor: function(config) {

        Ext.Window.prototype.shadow = false;

        // property names for FeatureEditor and FeatureGrid
        var propertyNames = {
            // custom fied names for the fault summary table
            "fault_name": "Fault Name",
            "sec_name": "Fault Section Name",
            "episodi_is": "Episodic behaviour (yes/no)",
            "episodi_ac": "Episodic behaviour (active/inactive)",
            "length": "Length (km, pref, min, max)",
            "u_sm_d_min": "Upper seismogenic depth min (km)",
            "u_sm_d_max": "Upper seismogenic depth max (km)",
            "u_sm_d_pre": "Upper seismogenic depth pref (km)",
            "u_sm_d_com": "Upper seismogenic completeness (1, 2, 3, or 4)",
            "low_d_min": "Lower seismogenic depth min (km)",
            "low_d_max": "Lower seismogenic depth max (km)",
            "low_d_pref": "Lower seismogenic depth pref (km)",
            "low_d_com": "Lower seismogenic completeness (1, 2, 3, or 4)",
            "strike": "Strike (...\u00B0)",
            "dip_min": "Dip min (...\u00B0)",
            "dip_max": "Dip max (...\u00B0)",
            "dip_pref": "Dip pref (...\u00B0)",
            "dip_com": "Dip data completeness factor (1, 2, 3, or 4)",
            "dip_dir": "Dip direction (...\u00B0)",
            "down_thro": "Downthrown side (N, S, W, E or NW etc.)",
            "slip_typ": "Slip type (Reverse etc.)",
            "slip_com": "Slip type completeness (1, 2, 3, or 4)",
            "slip_r_min": "Slip rate min (mm/yr)",
            "slip_r_max": "Slip rate max (mm/yr)",
            "slip_r_pre": "Slip rate pref (mm/yr)",
            "slip_r_com": "Slip rate completeness (1, 2, 3, or 4)",
            "aseis_slip": "Aseismic-slip factor (0-1)",
            "aseis_com": "Aseismic-slip completeness (1, 2, 3, or 4)",
            "dis_min": "Displacement min (m)",
            "dis_max": "Displacement max (m)",
            "dis_pref": "Displacement pref (m)",
            "re_int_min": "Recurrence interval min (yr)",
            "re_int_max": "Recurrence interval max (yr)",
            "re_int_pre": "Recurrence interval pref (yr)",
            "re_int_com": "Recurrence interval common (yr)",
            "mov_min": "Age of last movement min (yr BP)",
            "mov_max": "Age of last movement max (yr BP)",
            "mov_pref": "Age of last movement pref (yr BP)",
            "all_com": "Overall data completeness (1, 2, 3, or 4)",
            "created": "Date created (date)",
            "compiler": "Compiled by (name)",
            "contrib": "Contributed by (name)",
            // custom fied names for the observations table
            "observationType": "Observation Type",
            "slipType": "Slip Type",
            "hv_ratio": "H:V Ratio",
            "rake": "Rake (deg)",
            "net_slip_rate_min": "Net Slip Rate Min (mm/yr)",
            "net_slip_rate_max": "Net Slip Rate Max (mm/yr)",
            "net_slip_rate_pref": "Net Slip Rate Pref (mm/yr)",
            "dip_slip_rate_min": "Dip Slip Rate Min (mm/yr)",
            "dip_slip_rate_max": "Dip Slip Rate Max (mm/yr)",
            "dip_slip_rate_pref": "Dip Slip Rate Pref (mm/yr)",
            "marker_age": "Marker Age (yrs BP)",
            "slip_rate_category": "Slip Rate Category",
            "strike_slip_rate_min": "Strike Slip Rate Min (mm/yr)",
            "strike_slip_rate_max": "Strike Slip Rate Max (mm/yr)",
            "strike_slip_rate_pref": "Strike Slip Rate Pref (mm/yr)",
            "vertical_slip_rate_min": "Vertical Slip Rate Min (mm/yr)",
            "vertical_slip_rate_max": "Vertical Slip Rate Max (mm/yr)",
            "vertical_slip_rate_pref": "Vertical Slip Rate Pref (mm/yr)",
            "site": "Site",
            "notes": "Notes",
            "summary_id": "Fault Section Summary ID",
            // custom fied names for fault trace form
            "section_name": "Fault Section Name",
            "loc_meth": "Location Method",
            "scale": "Scale",
            "accuracy": "Accuracy",
            "geomor_exp": "Geomorphic Expression",
            "notes": "Notes",
            "fault_section_id": "Fault Section Id",
            "t_feature": "Trace Feature",
	    "s_feature": "Site Feature",
	    // custom field names for fault source form
    	    "source_nm": "Fault Source Name",
    	    "width": "Width",
    	    "area": "Area",
    	    "rake_min": "Rake Min",
    	    "rake_max": "Rake Max",
    	    "rake_pref": "Rake Pref",
    	    "rake_com": "Rake Common",
    	    "magnitude": "Magnitude",
    	    "length_min": "Length Min",
    	    "length_max": "Length Max",
    	    "length_pre": "Length Pref"
        };

        Ext.applyIf(config, {
            proxy: "/proxy?url=",

            mapItems: [{
                xtype: "gx_zoomslider",
                vertical: true,
                height: 100
            }, {
                xtype: "gxp_scaleoverlay"
            }],
            portalItems: [{
                region: "center",
                layout: "border",
                tbar: {
                    id: "paneltbar",
                    items: ["-"]
                },
                items: [{
                    id: "west",
                    region: "west",
                    layout: "accordion",
                    width: 280,
                    split: true,
                    collapsible: true,
                    collapseMode: "mini",
                    header: false,
                    border: false,
                    defaults: {
                       hideBorders: true,
                       autoScroll: true

                    },
                    items: [{
                        id: "tree",
                        title: "Layers"
                    }, {
                        id: 'trace',
                        title: "Trace Form",
                        padding: 10
                    }, {
			id: 'summary',
			title: "Neotectonic Section Summary",
			padding: 10
		    }, {
                        id: 'site',
                        title: "Site Observation Form",
                        padding: 10
                    },/* {
                        id: 'observations',
                        title: "Observations",
                        layout: "fit",
                        autoScroll: false
                    },*/ {
			id: "fault",
			title: "Fault Summary"
                    }, {
			id: "source_trace",
			title: "Fault Source Trace"
                    }, {
        		id: "source",
        		title: "Fault Source"
                    }]
                },
		"map", {
                    id: "featuregrid",
                    layout: "fit",
                    region: "south",
                    border: false,
                    height: 200,
                    split: true,
                    collapseMode: "mini",
                }]
            }],

            tools: [{
                actionTarget: {target: "paneltbar", index: 0},
                outputAction: 0,
                outputConfig: {
                    title: "Faulted Earth",
                    width: 300,
                    height: 300,
                    modal: true,
                    bodyCfg: {
                        tag: "iframe",
                        src: "about.html",
                        style: {border: 0}
                    }
                },
                actions: [{
                    iconCls: "icon-geoexplorer",
                    text: "Faulted Earth",
                }]
            },{
                ptype: "gxp_layertree",
                outputTarget: "tree",
            }, {
                ptype: "gxp_featuremanager",
                id: "featuremanager",
                autoLoadFeatures: true,
                autoSetLayer: false,
                paging: false,
                maxFeatures: 100
            }, {
                ptype: "gxp_featuregrid",
                alwaysDisplayOnMap: true,
                selectOnMap: true,
                displayMode: "selected",
                featureManager: "featuremanager",
                outputTarget: "featuregrid",
                outputConfig: {
                    id: "grid",
                    propertyNames: propertyNames
                },
                controlOptions: {
                    multiple: true,
                }
            }, {
                ptype: "gxp_selectedfeatureactions",
                featureManager: "featuremanager",
                actions: [{
                    menuText: "Feature context demo",
                    text: "Feature context demo",
                    urlTemplate: "/geoserver/wms/reflect?layers={layer}&width=377&height=328&format=application/openlayers&featureid={fid}"
                }],
                actionTarget: ["grid.contextMenu", "grid.bbar"],
                outputConfig: {
                    width: 410,
                    height: 410
                }
            }, {
                ptype: "app_summaryform",
                id: "summaryform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "summary"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "summaryform_tooltarget",
                //createFeatureActionText: "Draw",
                //editFeatureActionText: "Modify",
				snappingAgent: "snapping-agent",
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_traceform",
                id: "traceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "trace"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "traceform_tooltarget",
                autoLoadFeatures: true,
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		snappingAgent: "snapping-agent",
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_siteform",
                id: "siteform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "site"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "siteform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
                snappingAgent: "snapping-agent",
                autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_faultform",
                id: "faultform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "fault"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "faultform_tooltarget",
                //createFeatureActionText: "Draw",
                //editFeatureActionText: "Modify",
		snappingAgent: "snapping-agent",
		autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_source_traceform",
                id: "source_traceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "source_trace"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "source_traceform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		snappingAgent: "snapping-agent",
		autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_sourceform",
                id: "sourceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "source"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "sourceform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		snappingAgent: "snapping-agent",
		autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            },{
                ptype: "app_sourceform",
                id: "sourceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "source"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "sourceform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		snappingAgent: "snapping-agent",
		autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            },{
		ptype: "gxp_wmsgetfeatureinfo",
		outputConfig: {
		        width: 400
		}
	    },/*{
		ptype: "app_observations",
		featureManager: "featuremanager",
		outputTarget: "observations"
	    },*/{
		ptype: "gxp_legend",
		outputTarget: "west",
		outputConfig: {
		    title: this.legendTabTitle,
		    autoScroll: true
		}
	     },  {
		ptype: "gxp_measure",
		actionTarget: {target: "map.tbar", index: 6},
		toggleGroup: "main"
	     }, {
		ptype: "gxp_zoomtoextent",
		actionTarget: "map.tbar"
	     }, {
		ptype: "gxp_zoom",
		actionTarget: "map.tbar"
	     }, {
		ptype: "gxp_navigationhistory",
		actionTarget: "map.tbar"
	     }, {
                ptype: "gxp_zoomtoselectedfeatures",
                featureManager: "featuremanager",
                actionTarget: "map.tbar",
                tooltip: "Zoom to selected closure"
             },                {
                ptype: "gxp_googlegeocoder",
                outputTarget: "paneltbar",
                outputConfig: {
                        emptyText: "Search for a location ..."
                }
             }, {
		ptype: "gxp_snappingagent",
		id: "snapping-agent",
		targets: [{
			source: "local",
			name: "geonode:trace"
		}]
	     }]
        });

        FaultedEarth.superclass.constructor.apply(this, arguments);
    }

});
<commit_msg>login button<commit_after>FaultedEarth = Ext.extend(gxp.Viewer, {

    legendTabTitle: "Legend",
	summaryId: null,

    constructor: function(config) {

        Ext.Window.prototype.shadow = false;

        // property names for FeatureEditor and FeatureGrid
        var propertyNames = {
            // custom fied names for the fault summary table
            "fault_name": "Fault Name",
            "sec_name": "Fault Section Name",
            "episodi_is": "Episodic behaviour (yes/no)",
            "episodi_ac": "Episodic behaviour (active/inactive)",
            "length": "Length (km, pref, min, max)",
            "u_sm_d_min": "Upper seismogenic depth min (km)",
            "u_sm_d_max": "Upper seismogenic depth max (km)",
            "u_sm_d_pre": "Upper seismogenic depth pref (km)",
            "u_sm_d_com": "Upper seismogenic completeness (1, 2, 3, or 4)",
            "low_d_min": "Lower seismogenic depth min (km)",
            "low_d_max": "Lower seismogenic depth max (km)",
            "low_d_pref": "Lower seismogenic depth pref (km)",
            "low_d_com": "Lower seismogenic completeness (1, 2, 3, or 4)",
            "strike": "Strike (...\u00B0)",
            "dip_min": "Dip min (...\u00B0)",
            "dip_max": "Dip max (...\u00B0)",
            "dip_pref": "Dip pref (...\u00B0)",
            "dip_com": "Dip data completeness factor (1, 2, 3, or 4)",
            "dip_dir": "Dip direction (...\u00B0)",
            "down_thro": "Downthrown side (N, S, W, E or NW etc.)",
            "slip_typ": "Slip type (Reverse etc.)",
            "slip_com": "Slip type completeness (1, 2, 3, or 4)",
            "slip_r_min": "Slip rate min (mm/yr)",
            "slip_r_max": "Slip rate max (mm/yr)",
            "slip_r_pre": "Slip rate pref (mm/yr)",
            "slip_r_com": "Slip rate completeness (1, 2, 3, or 4)",
            "aseis_slip": "Aseismic-slip factor (0-1)",
            "aseis_com": "Aseismic-slip completeness (1, 2, 3, or 4)",
            "dis_min": "Displacement min (m)",
            "dis_max": "Displacement max (m)",
            "dis_pref": "Displacement pref (m)",
            "re_int_min": "Recurrence interval min (yr)",
            "re_int_max": "Recurrence interval max (yr)",
            "re_int_pre": "Recurrence interval pref (yr)",
            "re_int_com": "Recurrence interval common (yr)",
            "mov_min": "Age of last movement min (yr BP)",
            "mov_max": "Age of last movement max (yr BP)",
            "mov_pref": "Age of last movement pref (yr BP)",
            "all_com": "Overall data completeness (1, 2, 3, or 4)",
            "created": "Date created (date)",
            "compiler": "Compiled by (name)",
            "contrib": "Contributed by (name)",
            // custom fied names for the observations table
            "observationType": "Observation Type",
            "slipType": "Slip Type",
            "hv_ratio": "H:V Ratio",
            "rake": "Rake (deg)",
            "net_slip_rate_min": "Net Slip Rate Min (mm/yr)",
            "net_slip_rate_max": "Net Slip Rate Max (mm/yr)",
            "net_slip_rate_pref": "Net Slip Rate Pref (mm/yr)",
            "dip_slip_rate_min": "Dip Slip Rate Min (mm/yr)",
            "dip_slip_rate_max": "Dip Slip Rate Max (mm/yr)",
            "dip_slip_rate_pref": "Dip Slip Rate Pref (mm/yr)",
            "marker_age": "Marker Age (yrs BP)",
            "slip_rate_category": "Slip Rate Category",
            "strike_slip_rate_min": "Strike Slip Rate Min (mm/yr)",
            "strike_slip_rate_max": "Strike Slip Rate Max (mm/yr)",
            "strike_slip_rate_pref": "Strike Slip Rate Pref (mm/yr)",
            "vertical_slip_rate_min": "Vertical Slip Rate Min (mm/yr)",
            "vertical_slip_rate_max": "Vertical Slip Rate Max (mm/yr)",
            "vertical_slip_rate_pref": "Vertical Slip Rate Pref (mm/yr)",
            "site": "Site",
            "notes": "Notes",
            "summary_id": "Fault Section Summary ID",
            // custom fied names for fault trace form
            "section_name": "Fault Section Name",
            "loc_meth": "Location Method",
            "scale": "Scale",
            "accuracy": "Accuracy",
            "geomor_exp": "Geomorphic Expression",
            "notes": "Notes",
            "fault_section_id": "Fault Section Id",
            "t_feature": "Trace Feature",
	        "s_feature": "Site Feature",
	        // custom field names for fault source form
    	    "source_nm": "Fault Source Name",
    	    "width": "Width",
    	    "area": "Area",
    	    "rake_min": "Rake Min",
    	    "rake_max": "Rake Max",
    	    "rake_pref": "Rake Pref",
    	    "rake_com": "Rake Common",
    	    "magnitude": "Magnitude",
    	    "length_min": "Length Min",
    	    "length_max": "Length Max",
    	    "length_pre": "Length Pref"
        };

        Ext.applyIf(config, {
            proxy: "/proxy?url=",

            mapItems: [{
                xtype: "gx_zoomslider",
                vertical: true,
                height: 100
            }, {
                xtype: "gxp_scaleoverlay"
            }],
            portalItems: [{
                region: "center",
                layout: "border",
                tbar: {
                    id: "paneltbar",
                    items: ["-"]
                },
                items: [{
                    id: "west",
                    region: "west",
                    layout: "accordion",
                    width: 280,
                    split: true,
                    collapsible: true,
                    collapseMode: "mini",
                    header: false,
                    border: false,
                    defaults: {
                       hideBorders: true,
                       autoScroll: true

                    },
                    items: [{
                        id: "tree",
                        title: "Layers"
                    }, {
                        id: 'trace',
                        title: "Trace Form",
                        padding: 10
                    }, {
                		id: 'summary',
                		title: "Neotectonic Section Summary",
                		padding: 10
                	}, {
                        id: 'site',
                        title: "Site Observation Form",
                        padding: 10
                    },/* {
                        id: 'observations',
                        title: "Observations",
                        layout: "fit",
                        autoScroll: false
                    },*/ {
                		id: "fault",
                		title: "Fault Summary"
                    }, {
                		id: "source_trace",
                		title: "Fault Source Trace"
                    }, {
                    	id: "source",
                    	title: "Fault Source"
                    }]
                },
		"map", {
                    id: "featuregrid",
                    layout: "fit",
                    region: "south",
                    border: false,
                    height: 200,
                    split: true,
                    collapseMode: "mini",
                }]
            }],

            tools: [{
                actionTarget: {target: "paneltbar", index: 0},
                outputAction: 0,
                outputConfig: {
                    title: "Login",
                    width: 900,
                    height: 500,
                    modal: true,
                    bodyCfg: {
                        tag: "iframe",
                        src: "http://178.79.185.190/",
                        style: {border: 0}
                    }
                },
                actions: [{
                    iconCls: "icon-geoexplorer",
                    text: "Login",
                }]
            },{
                ptype: "gxp_layertree",
                outputTarget: "tree",
            }, {
                ptype: "gxp_featuremanager",
                id: "featuremanager",
                autoLoadFeatures: true,
                autoSetLayer: false,
                paging: false,
                maxFeatures: 100
            }, {
                ptype: "gxp_featuregrid",
                alwaysDisplayOnMap: true,
                selectOnMap: true,
                displayMode: "selected",
                featureManager: "featuremanager",
                outputTarget: "featuregrid",
                outputConfig: {
                    id: "grid",
                    propertyNames: propertyNames
                },
                controlOptions: {
                    multiple: true,
                }
            }, {
                ptype: "app_summaryform",
                id: "summaryform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "summary"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "summaryform_tooltarget",
                //createFeatureActionText: "Draw",
                //editFeatureActionText: "Modify",
				snappingAgent: "snapping-agent",
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_traceform",
                id: "traceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "trace"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "traceform_tooltarget",
                autoLoadFeatures: true,
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		        snappingAgent: "snapping-agent",
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_siteform",
                id: "siteform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "site"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "siteform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
                snappingAgent: "snapping-agent",
                autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_faultform",
                id: "faultform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "fault"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "faultform_tooltarget",
                //createFeatureActionText: "Draw",
                //editFeatureActionText: "Modify",
		        snappingAgent: "snapping-agent",
		        autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_source_traceform",
                id: "source_traceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "source_trace"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "source_traceform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		        snappingAgent: "snapping-agent",
		        autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            }, {
                ptype: "app_sourceform",
                id: "sourceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "source"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "sourceform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		        snappingAgent: "snapping-agent",
		        autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                }
            },{
                ptype: "app_sourceform",
                id: "sourceform",
                featureManager: "featuremanager",
                featureEditor: "featureeditor",
                outputTarget: "source"
            }, {
                ptype: "gxp_featureeditor",
                id: "featureeditor",
                featureManager: "featuremanager",
                actionTarget: "sourceform_tooltarget",
                createFeatureActionText: "Draw",
                editFeatureActionText: "Modify",
		        snappingAgent: "snapping-agent",
		        autoLoadFeatures: true,
                outputConfig: {
                    propertyNames: propertyNames
                    }
             }, {
		         ptype: "gxp_wmsgetfeatureinfo",
	             outputConfig: {
	                 width: 400
	                 }
	         },/*{
        		ptype: "app_observations",
        		featureManager: "featuremanager",
        		outputTarget: "observations"
        	    },*/{
        		ptype: "gxp_legend",
        		outputTarget: "west",
        		outputConfig: {
        		    title: this.legendTabTitle,
        		    autoScroll: true
        		}
        	}, {
            	ptype: "gxp_measure",
            	actionTarget: {target: "map.tbar", index: 6},
            	toggleGroup: "main"
            }, {
            	ptype: "gxp_zoomtoextent",
            	actionTarget: "map.tbar"
            }, {
            	ptype: "gxp_zoom",
            	actionTarget: "map.tbar"
            }, {
            	ptype: "gxp_navigationhistory",
            	actionTarget: "map.tbar"
            }, {
                ptype: "gxp_zoomtoselectedfeatures",
                featureManager: "featuremanager",
                actionTarget: "map.tbar",
                tooltip: "Zoom to selected closure"
            }, {
                ptype: "gxp_selectedfeatureactions",
                featureManager: "featuremanager",
                actions: [{
                    menuText: "Feature context demo",
                    text: "Feature context demo",
                    urlTemplate: "/geoserver/wms/reflect?layers={layer}&width=377&height=328&format=application/openlayers&featureid={fid}"
                }],
                actionTarget: ["grid.contextMenu", "grid.bbar"],
                outputConfig: {
                    width: 410,
                    height: 410
                }
            },{
                ptype: "gxp_googlegeocoder",
                outputTarget: "paneltbar",
                outputConfig: {
                    emptyText: "Search for a location ..."
                }
            }, {
            	ptype: "gxp_snappingagent",
            	id: "snapping-agent",
            	targets: [{
            		source: "local",
            		name: "geonode:trace"
            	}]
    	     }]
        });

        FaultedEarth.superclass.constructor.apply(this, arguments);
    }

});
<|endoftext|>


<commit_before>var exec = require('child_process').execSync;
var version = JSON.stringify(require("./package.json").version);

// Move build js and css files out to top level
exec("mv build/static/js/*.js build/js");
exec("mv build/static/css/*.css build/css");

// Remove source maps by deleting lines matching the source map pattern
exec("sed -i '' -e '/\\/\\/# sourceMappingURL.*/d' build/js");
exec("sed -i '' -e '/\\/\\*# sourceMappingURL.*/d' build/css");

// Delete unneeded files
exec("rm -r build/static");
exec("rm build/*.json");
exec("rm build/*.html");
exec("rm build/*.ico");
exec("rm build/service-worker.js");

// Put version in file name
exec("mv build/js build/website-search." + version + ".js");
exec("mv build/css build/website-search." + version + ".css");
<commit_msg>site-search-overlay: correct dist name to be same as sajaricom<commit_after>var exec = require('child_process').execSync;
var version = JSON.stringify(require("./package.json").version);

// Move build js and css files out to top level
exec("mv build/static/js/*.js build/js");
exec("mv build/static/css/*.css build/css");

// Remove source maps by deleting lines matching the source map pattern
exec("sed -i '' -e '/\\/\\/# sourceMappingURL.*/d' build/js");
exec("sed -i '' -e '/\\/\\*# sourceMappingURL.*/d' build/css");

// Delete unneeded files
exec("rm -r build/static");
exec("rm build/*.json");
exec("rm build/*.html");
exec("rm build/*.ico");
exec("rm build/service-worker.js");

// Put version in file name
exec("mv build/js build/website-search-" + version + ".js");
exec("mv build/css build/website-search-" + version + ".css");
<|endoftext|>


<commit_before>anyware_config = {
  DEBUG: {
    status: false,     // Persistent status icons
    debugView: false,  // Show game debug view
    console: false,    // Javascript console debug output
  },

    // The sequence of the games to be run. The first game is run on startup
  GAMES_SEQUENCE: [ "mole", "disk", "simon" ],

  // These settings effect the default behaviour of panels outside of
  // any custom logic in any of the games
  PANEL_DEFAULTS: {
    ACTIVE_INTENSITY: 100,
    INACTIVE_INTENSITY: 0
  },

  /******* GAMES CONFIGURATION *******/

  HANDSHAKE: {
    TRANSITION_OUT_TIME: 4000 // Time (ms) from handshake is touched until we start the next game
  },

  MOLE_GAME: {
    GAME_END: 30, // Game ends after this number of panels have been touched
    INITIAL_PANELS: [
      {stripId: '2', panelId: '3'},
      {stripId: '2', panelId: '7'},
      {stripId: '1', panelId: '6'},
      {stripId: '0', panelId: '5'}
    ],
    NUM_ACTIVE_PANELS: {
//        10: 1, // At panelCount of 10, increase # of simultaneusly active panels
//        20: 1,
//        25: -1, // At panelCount of 25, decrease # of simultaneusly active panels
//        27: -1
    },
    PANEL_LIFETIME: [
      {count: 0, range: [10, 10]}, // Initial timeout
      {count: 4, range: [4, 6]}, // At panelCount of 4, set panel lifetime to 4-6 seconds. Gradually interpolate to next timeout level
      {count: 20, range: [2, 3]},
      {count: 30, range: [1.5, 2]}
    ],
    // How long to wait before enabling the next panel, on success
    PANEL_SUCCESS_DELAY: 1000,
    // How long to wait before enabling the next panel, on automatic panel move
    PANEL_MOVE_DELAY: 500,
    // The intensity to use on active panels
    ACTIVE_PANEL_INTENSITY: 100,
    // The intensity to use on inactive panels
    INACTIVE_PANEL_INTENSITY: 0,
    // The intensity to use on ignored panels (panels turned to location color)
    COLORED_PANEL_INTENSITY: 75,
    // We don't use failure sounds in the default setup due to too many accidental touches
    ENABLE_FAILURE_SOUND: false
  },

  DISK_GAME: {
    SPEEDS: [6, 15, 21, 30, 72], // degrees/sec
    // The intensity of the panels that the user can use to play the sequence
    CONTROL_PANEL_COLOR: 'white',
    CONTROL_PANEL_INTENSITIES: [10, 20, 30, 40, 50],
    CONFLICT_INTENSITY: 20,
    ACTIVE_CONTROL_PANEL_INTENSITY: 100,
    SHADOW_LIGHTS: {
      // stripId: [panelId..]
      '6': ['0', '1', '2', '3']
    },
    SHADOW_LIGHT_INTENSITY: 100,
    LEVELS: [
      // rule: 'absolute' or 'relative'
      // disks: { diskId: initial position }

      // level 0
      { rule: 'absolute', disks: { disk0: -90, disk1: 90, disk2: 120 } },

      // level 1
      { rule: 'relative', disks: { disk0: 90, disk1: -90, disk2: -120 } },

      // level 2
      { rule: 'absolute', disks: { disk0: 180, disk1: 45, disk2: -90 } },

    ],
    CONTROL_MAPPINGS: {
      STRIP_TO_DISK: {
        '0': 'disk0',
        '1': 'disk1',
        '2': 'disk2',
      },
    }
  },

  SIMON_GAME: {
    PATTERN_LEVELS: [
      // level 0 sequence
      {
        stripId: '0',
        // Each array of panel IDs is lit up one at a time
        // Each array within this array is called a "frame" in the "sequence"
        panelSequences: [
          ['1', '2', '3'],
          ['4', '5', '6'],
          ['7', '8', '9'],
        ],
        frameDelay: 750 // Overriding default frame delay to make first level slower
      },
      // level 1 sequence
      {
        stripId: '1',
        panelSequences: [
          ['1', '8', '6'],
          ['2', '7', '0'],
          ['4', '9', '5'],
        ],
      },
      // level 2 sequence
      {
        stripId: '2',
        panelSequences: [
          ['3', '6', '2', '9'],
          ['5', '1', '8', '7'],
          ['0', '4', '7', '6'],
        ],
      }
    ],
    // The intensity of the panels when they are pressed or when the sequence is playing
    TARGET_PANEL_INTENSITY: 100,
    // The intensity of the panels that the user can use to play the sequence
    AVAILABLE_PANEL_INTENSITY: 1,
    // The delay in ms between sequence frames
    SEQUENCE_ANIMATION_FRAME_DELAY: 500,
    // The delay in ms to wait before replaying the sequence
    // Only replayed if no input is received from the user
    DELAY_BETWEEN_PLAYS: 5000,
    // The time after input to wait for the user to finish the sequence
    INPUT_TIMEOUT: 10000,
    // The default color to set the panels to when
    DEFAULT_SIMON_PANEL_COLOR: 'white',
    // Wait while playing final sound
    TRANSITION_OUT_TIME: 10000
  }
};
<commit_msg>bugfix: relative rule was left behind<commit_after>anyware_config = {
  DEBUG: {
    status: false,     // Persistent status icons
    debugView: false,  // Show game debug view
    console: false,    // Javascript console debug output
  },

    // The sequence of the games to be run. The first game is run on startup
  GAMES_SEQUENCE: [ "mole", "disk", "simon" ],

  // These settings effect the default behaviour of panels outside of
  // any custom logic in any of the games
  PANEL_DEFAULTS: {
    ACTIVE_INTENSITY: 100,
    INACTIVE_INTENSITY: 0
  },

  /******* GAMES CONFIGURATION *******/

  HANDSHAKE: {
    TRANSITION_OUT_TIME: 4000 // Time (ms) from handshake is touched until we start the next game
  },

  MOLE_GAME: {
    GAME_END: 30, // Game ends after this number of panels have been touched
    INITIAL_PANELS: [
      {stripId: '2', panelId: '3'},
      {stripId: '2', panelId: '7'},
      {stripId: '1', panelId: '6'},
      {stripId: '0', panelId: '5'}
    ],
    NUM_ACTIVE_PANELS: {
//        10: 1, // At panelCount of 10, increase # of simultaneusly active panels
//        20: 1,
//        25: -1, // At panelCount of 25, decrease # of simultaneusly active panels
//        27: -1
    },
    PANEL_LIFETIME: [
      {count: 0, range: [10, 10]}, // Initial timeout
      {count: 4, range: [4, 6]}, // At panelCount of 4, set panel lifetime to 4-6 seconds. Gradually interpolate to next timeout level
      {count: 20, range: [2, 3]},
      {count: 30, range: [1.5, 2]}
    ],
    // How long to wait before enabling the next panel, on success
    PANEL_SUCCESS_DELAY: 1000,
    // How long to wait before enabling the next panel, on automatic panel move
    PANEL_MOVE_DELAY: 500,
    // The intensity to use on active panels
    ACTIVE_PANEL_INTENSITY: 100,
    // The intensity to use on inactive panels
    INACTIVE_PANEL_INTENSITY: 0,
    // The intensity to use on ignored panels (panels turned to location color)
    COLORED_PANEL_INTENSITY: 75,
    // We don't use failure sounds in the default setup due to too many accidental touches
    ENABLE_FAILURE_SOUND: false
  },

  DISK_GAME: {
    SPEEDS: [6, 15, 21, 30, 72], // degrees/sec
    // The intensity of the panels that the user can use to play the sequence
    CONTROL_PANEL_COLOR: 'white',
    CONTROL_PANEL_INTENSITIES: [10, 20, 30, 40, 50],
    CONFLICT_INTENSITY: 20,
    ACTIVE_CONTROL_PANEL_INTENSITY: 100,
    SHADOW_LIGHTS: {
      // stripId: [panelId..]
      '6': ['0', '1', '2', '3']
    },
    SHADOW_LIGHT_INTENSITY: 100,
    LEVELS: [
      // rule: 'absolute' or 'relative'
      // disks: { diskId: initial position }

      // level 0
      { rule: 'absolute', disks: { disk0: -90, disk1: 90, disk2: 120 } },

      // level 1
      { rule: 'absolute', disks: { disk0: 90, disk1: -90, disk2: -120 } },

      // level 2
      { rule: 'absolute', disks: { disk0: 180, disk1: 45, disk2: -90 } },

    ],
    CONTROL_MAPPINGS: {
      STRIP_TO_DISK: {
        '0': 'disk0',
        '1': 'disk1',
        '2': 'disk2',
      },
    }
  },

  SIMON_GAME: {
    PATTERN_LEVELS: [
      // level 0 sequence
      {
        stripId: '0',
        // Each array of panel IDs is lit up one at a time
        // Each array within this array is called a "frame" in the "sequence"
        panelSequences: [
          ['1', '2', '3'],
          ['4', '5', '6'],
          ['7', '8', '9'],
        ],
        frameDelay: 750 // Overriding default frame delay to make first level slower
      },
      // level 1 sequence
      {
        stripId: '1',
        panelSequences: [
          ['1', '8', '6'],
          ['2', '7', '0'],
          ['4', '9', '5'],
        ],
      },
      // level 2 sequence
      {
        stripId: '2',
        panelSequences: [
          ['3', '6', '2', '9'],
          ['5', '1', '8', '7'],
          ['0', '4', '7', '6'],
        ],
      }
    ],
    // The intensity of the panels when they are pressed or when the sequence is playing
    TARGET_PANEL_INTENSITY: 100,
    // The intensity of the panels that the user can use to play the sequence
    AVAILABLE_PANEL_INTENSITY: 1,
    // The delay in ms between sequence frames
    SEQUENCE_ANIMATION_FRAME_DELAY: 500,
    // The delay in ms to wait before replaying the sequence
    // Only replayed if no input is received from the user
    DELAY_BETWEEN_PLAYS: 5000,
    // The time after input to wait for the user to finish the sequence
    INPUT_TIMEOUT: 10000,
    // The default color to set the panels to when
    DEFAULT_SIMON_PANEL_COLOR: 'white',
    // Wait while playing final sound
    TRANSITION_OUT_TIME: 10000
  }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import {
  Container, Content, Grid, Input,
  Item, Button, Label, Text as NBText } from 'native-base';
import styles from './style';
import I18n from '../../../i18n';

const WHITE = 'white';

export default class ForgotPassword extends Component {

  pressLoginButton = () => {
    const { navigate, state } = this.props.navigation;
    if (state.params !== undefined && state.params.nextScreen !== undefined) {
      navigate(state.params.nextScreen);
    } else {
      navigate('LoginScreen');
    }
  }

  render() {
    return (
      <Container style={{ backgroundColor: WHITE }}>
        <Content contentContainerStyle={styles.padder}>
          <View>
            <Text style={StyleSheet.flatten(styles.text1)}>
              <Text>{I18n.t('login.forgot_your_password')}</Text>
            </Text>
          </View>
          <View>
            <Text style={StyleSheet.flatten(styles.text2)}>
              <Text>{I18n.t('login.forgot_your_password_info')}</Text>
            </Text>
          </View>
          <Item floatingLabel>
            {I18n.t('account.email')}
            <Input />
          </Item>
          <Grid />
          <View style={styles.buttonContainer}>
            <Button
              style={StyleSheet.flatten(styles.button)}
              rounded primary onPress={() => this.pressLoginButton()}
            >
              <NBText>{I18n.t('button_actions.send')}</NBText>
            </Button>
          </View>
        </Content>
      </Container>
    );
  }
}
<commit_msg>Removed duplicate text input<commit_after>import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import {
  Container, Content, Grid, Input,
  Item, Button, Label, Text as NBText } from 'native-base';
import styles from './style';
import I18n from '../../../i18n';

const WHITE = 'white';

export default class ForgotPassword extends Component {

  pressLoginButton = () => {
    const { navigate, state } = this.props.navigation;
    if (state.params !== undefined && state.params.nextScreen !== undefined) {
      navigate(state.params.nextScreen);
    } else {
      navigate('LoginScreen');
    }
  }

  render() {
    return (
      <Container style={{ backgroundColor: WHITE }}>
        <Content contentContainerStyle={styles.padder}>
          <View>
            <Text style={StyleSheet.flatten(styles.text1)}>
              {I18n.t('login.forgot_your_password')}
            </Text>
          </View>
          <View>
            <Text style={StyleSheet.flatten(styles.text2)}>
              {I18n.t('login.forgot_your_password_info')}
            </Text>
          </View>
          <Item floatingLabel>
            {I18n.t('account.email')}
            <Input />
          </Item>
          <Grid />
          <View style={styles.buttonContainer}>
            <Button
              style={StyleSheet.flatten(styles.button)}
              rounded primary onPress={() => this.pressLoginButton()}
            >
              <NBText>{I18n.t('button_actions.send')}</NBText>
            </Button>
          </View>
        </Content>
      </Container>
    );
  }
}
<|endoftext|>


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

    require.config({
        baseUrl: 'app',
        paths: {
            // vendor
            '$': '../node_modules/jquery/dist/jquery.min',
            // app
            'utils': 'utils',
            'consts': 'consts',
            'buttons': 'buttons',
            'components': 'components',
            'events': 'events',
            'app': 'app',
            // Worker
            'enemyWorker': 'workers/enemyWorker'
        },
        shim: {
            '$': {
                exports: '$'
            },
            'enemyWorker': {
                deps: ['utils']
            }
        },
        callback: function() {
            require([
                'app',
                '$',
                'utils',
                'consts',
                'buttons',
                'events',
                'components'
            ], function(app) {
                app.init();
            });
        }
    });
    /*eslint-disable */
    requirejs.onError = function(err) {
        console.log(err.requireType);
        /*eslint-enable */
        if (err.requireType === 'timeout') {
            /*eslint-disable */
            console.log('modules: ' + err.requireModules);
            /*eslint-enable */
        }

        throw err;
    };
}());
<commit_msg>Removed enemyWorker shim<commit_after>(function() {
    'use strict';

    require.config({
        baseUrl: 'app',
        paths: {
            // vendor
            '$': '../node_modules/jquery/dist/jquery.min',
            // app
            'utils': 'utils',
            'consts': 'consts',
            'buttons': 'buttons',
            'components': 'components',
            'events': 'events',
            'app': 'app',
            // Worker
            'enemyWorker': 'workers/enemyWorker'
        },
        shim: {
            '$': {
                exports: '$'
            }
        },
        callback: function() {
            require([
                'app',
                '$',
                'utils',
                'consts',
                'buttons',
                'events',
                'components'
            ], function(app) {
                app.init();
            });
        }
    });
    /*eslint-disable */
    requirejs.onError = function(err) {
        console.log(err.requireType);
        /*eslint-enable */
        if (err.requireType === 'timeout') {
            /*eslint-disable */
            console.log('modules: ' + err.requireModules);
            /*eslint-enable */
        }

        throw err;
    };
}());
<|endoftext|>


<commit_before>var config = require('./config');
var manageUsers = require('./manageUsers.js');
var request = require('request');
//var mongo = require('./mongoFunctions.js');

function sendSubstitutions(senderID){
	var body = {
		'mode': 'getChanges',
		'param': 'today'
	};
	var messageText = '';
	manageUsers.postCall('0000', body, function(substitutions){
		var json = substitutions;
		if(json['substitution']=='no substitutions'){
			messageText = 'brak zastępstw';
		} else {
			console.log("zastępstwa: " + json['substitution']);
			messageText = 'zastępstwa';
		}
		var messageData = {
			recipient: {
			  id: senderID
			},
			message: {
			  text: messageText
			}
		};
		callSendAPI(messageData);
	});
}

function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  // The 'payload' param is a developer-defined field which is set in a postback
  // button for Structured Messages.
  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  //sendTextMessage(senderID, "Postback called");
}

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;

  /*if (messageText) {

    // If we receive a text message, check to see if it matches a keyword
    // and send back the example. Otherwise, just echo the text we received.
    switch (messageText) {
      case 'generic':
        sendGenericMessage(senderID);
        break;

      default:
        sendTextMessage(senderID, messageText);
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment received");
  }*/
  sendSubstitutions(senderID);
  //sendTextMessage(senderID, messageText);
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<commit_msg>added tommorow<commit_after>var config = require('./config');
var manageUsers = require('./manageUsers.js');
var request = require('request');
//var mongo = require('./mongoFunctions.js');

function sendSubstitutions(senderID, messageText){
	var body = {
		'mode': 'getChanges',
		'param': 'today'
	};
	switch(messageText){
		case 'jutro':
			//przechodzimy dalej (do tommorow)
		case 'tommorow':
			body['param'] = 'tommorow';
			break;
		default:
			break;
	}
	var messageText = '';
	manageUsers.postCall('0000', body, function(substitutions){
		var json = substitutions;
		if(json['substitution']=='no substitutions'){
			messageText = 'brak zastępstw';
		} else {
			console.log("zastępstwa: " + json['substitution']);
			messageText = 'zastępstwa';
		}
		var messageData = {
			recipient: {
			  id: senderID
			},
			message: {
			  text: messageText
			}
		};
		callSendAPI(messageData);
	});
}

function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  // The 'payload' param is a developer-defined field which is set in a postback
  // button for Structured Messages.
  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  //sendTextMessage(senderID, "Postback called");
}

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;

  /*if (messageText) {

    // If we receive a text message, check to see if it matches a keyword
    // and send back the example. Otherwise, just echo the text we received.
    switch (messageText) {
      case 'generic':
        sendGenericMessage(senderID);
        break;

      default:
        sendTextMessage(senderID, messageText);
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment received");
  }*/
  sendSubstitutions(senderID, messageText);
  //sendTextMessage(senderID, messageText);
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<|endoftext|>


<commit_before>/**
 * Node app that calls phantomJs to render the page and then outputs the page content.
 * App takes 3 arguments in the following order:
 *  1. which url to render
 *  2. path to phantomjs executable
 *  3. amount of miliseconds to wait before fetching the content
 *  4. (optional) debug mode - to enable pass "debug" as 4th parameter
 *
 *  Note: this js file needs to be inside the PHP folder, otherwise webpack will strip it out when deploying the app to production.
 */
const phantom = require("phantom");

const args = process.argv.slice(2);
const url = args[0];

const debug = args[3] || false;

phantom.create([
    '--ignore-ssl-errors=yes',
    '--load-images=false',
    '--local-storage-path=/tmp',
    '--local-storage-quota=5000',
    '--offline-storage-path=/tmp',
    '--offline-storage-quota=5000'], {
    phantomPath: args[1],
    logLevel: (debug) ? 'info' : 'error'
}).then(function (ph) {
    ph.createPage().then(function (page) {

        if (debug) {
            page.on("onConsoleMessage", function (msg, lineNum, sourceId) {
                console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
            });

            page.on("onResourceRequested", (requestData) => {
                console.info('Requesting', requestData.url);
            });

            page.on("onResourceError", function (resourceError) {
                console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
                console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
            });
        }

        page.property('viewportSize', {width: 1440, height: 768});
        page.property('customHeaders', {"XWebinyStaticRender": "true"});

        page.open(url).then(function (status) {
            setTimeout(() => {
                page.property('content').then(function (content) {
                    console.log(content);
                    page.close();
                    ph.exit();
                });
            }, args[2])
        });
    });
});<commit_msg>phantom exit is called in a callback to prevent console error message.<commit_after>/**
 * Node app that calls phantomJs to render the page and then outputs the page content.
 * App takes 3 arguments in the following order:
 *  1. which url to render
 *  2. path to phantomjs executable
 *  3. amount of miliseconds to wait before fetching the content
 *  4. (optional) debug mode - to enable pass "debug" as 4th parameter
 *
 *  Note: this js file needs to be inside the PHP folder, otherwise webpack will strip it out when deploying the app to production.
 */
const phantom = require("phantom");

const args = process.argv.slice(2);
const url = args[0];

const debug = args[3] || false;

phantom.create([
    '--ignore-ssl-errors=yes',
    '--load-images=false',
    '--local-storage-path=/tmp',
    '--local-storage-quota=5000',
    '--offline-storage-path=/tmp',
    '--offline-storage-quota=5000'], {
    phantomPath: args[1],
    logLevel: (debug) ? 'info' : 'error'
}).then(function (ph) {
    ph.createPage().then(function (page) {

        if (debug) {
            page.on("onConsoleMessage", function (msg, lineNum, sourceId) {
                console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
            });

            page.on("onResourceRequested", (requestData) => {
                console.info('Requesting', requestData.url);
            });

            page.on("onResourceError", function (resourceError) {
                console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
                console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
            });
        }

        page.property('viewportSize', {width: 1440, height: 768});
        page.property('customHeaders', {"XWebinyStaticRender": "true"});

        page.open(url).then(function (status) {
            setTimeout(() => {
                page.property('content').then(function (content) {
                    console.log(content);
                    page.close().then(() => {
                        ph.exit();
                    });
                });
            }, args[2])
        });
    });
});<|endoftext|>