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

    var buffer = [];

    var measure = function (name, input, fn) {
        var i,
            t0,
            time,
            repeat = 5,
            runs = [],
            min = null,
            max = null,
            sum = 0;

        for (i = 0; i < repeat; i++) {
            t0 = Date.now();
            var val = fn.call({}, input);
            buffer.push(val);
            time = Date.now() - t0;
            runs.push({
                name: name,
                time: time
            });
        }

        for (i = 0; i < runs.length; i++) {
            var run = runs[i];
            sum += run.time;
            if (min === null || min > run.time) {
                min = run.time;
            }
            if (max === null || max < run.time) {
                max = run.time;
            }
        }

        return {
            name: name,
            min: min,
            max: max,
            avg: sum / repeat
        };
    };

    var createInput = function (size) {
        return Stream.range(0, size)
            .map(function () {
                return Math.floor(Math.random() * size) + 1;
            })
            .toArray();
    };

    var input = createInput(100000);
    console.log("input.length: %o", input.length);

    var result;

    result = measure("Stream.js [filter - map - toArray]", input, function () {
        return Stream(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .toArray();
    });

    console.log(result);

    result = measure("Underscore.js [filter - map - value]", input, function () {
        return _.chain(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .value();
    });

    console.log(result);

    result = measure("Stream.js [filter - map - findFirst]", input, function () {
        return Stream(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .findFirst();
    });

    console.log(result);

    result = measure("Underscore.js [filter - map - first - value]", input, function () {
        return _.chain(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .first()
            .value();
    });

    console.log(result);

}());<commit_msg>Add iterative examples<commit_after>(function () {
    "use strict";

    var buffer = [];

    var measure = function (name, input, fn) {
        var i,
            t0,
            time,
            repeat = 5,
            runs = [],
            min = null,
            max = null,
            sum = 0;

        for (i = 0; i < repeat; i++) {
            t0 = Date.now();
            var val = fn.call({}, input);
            buffer.push(val);
            time = Date.now() - t0;
            runs.push({
                name: name,
                time: time
            });
        }

        for (i = 0; i < runs.length; i++) {
            var run = runs[i];
            sum += run.time;
            if (min === null || min > run.time) {
                min = run.time;
            }
            if (max === null || max < run.time) {
                max = run.time;
            }
        }

        return {
            name: name,
            min: min,
            max: max,
            avg: sum / repeat
        };
    };

    var createInput = function (size) {
        return Stream.range(0, size)
            .map(function () {
                return Math.floor(Math.random() * size) + 1;
            })
            .toArray();
    };

    var input = createInput(100000);
    console.log("input.length: %o", input.length);

    var result;

    result = measure("Stream.js [filter - map - toArray]", input, function () {
        return Stream(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .toArray();
    });

    console.log(result);

    result = measure("Underscore.js [filter - map - value]", input, function () {
        return _.chain(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .value();
    });

    console.log(result);

    result = measure("Iterative [filter - map - array]", input, function () {
        var result = [];
        for (var i = 0; i < input.length; i++) {
            if (i % 2 === 1) {
                result.push({num: i});
            }
        }
        return result;
    });

    console.log(result);

    result = measure("Stream.js [filter - map - findFirst]", input, function () {
        return Stream(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .findFirst();
    });

    console.log(result);

    result = measure("Underscore.js [filter - map - first - value]", input, function () {
        return _.chain(input)
            .filter(function (num) {
                return num % 2 === 1;
            })
            .map(function (num) {
                return {num: num};
            })
            .first()
            .value();
    });

    console.log(result);

    result = measure("Iterative [filter - map - return first]", input, function () {
        for (var i = 0; i < input.length; i++) {
            if (i % 2 === 1) {
                return {num: i};
            }
        }
        return null;
    });

    console.log(result);

}());<|endoftext|>


<commit_before>var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

/**
 * Destroy One Record
 * DELETE /:model/:id
 *
 * Destroys the single model instance with the specified `id` from the data adapter for the given model if it exists.
 */
module.exports = function (req, res) {
  var Model = actionUtil.parseModel(req);
  var pk = actionUtil.requirePk(req);
  var query = Model.findOne(pk);

  query = actionUtil.populateEach(query, req);
  query.exec(function (error, record) {
    if (error) return res.serverError(error);
    if (!record) return res.notFound();

    Model
      .destroy(pk)
      .exec(function (error) {
        if (error) return res.serverError(error);

        return res.ok(record);
      });
  });
};
<commit_msg>Move destroy blueprint to private fn<commit_after>var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

/**
 * Triggers when Model.destroy
 * @param {Object} req
 * @param {Object} res
 * @param {Object} record
 * @param {Object} error
 * @returns {*}
 * @private
 */
function _onModelDestroy(req, res, record, error) {
  if (error) return res.serverError(error);

  return res.ok(record);
}

/**
 * Triggers when Model.findOne
 * @param {Object} req
 * @param {Object} res
 * @param {Object} pk
 * @param {Object} error
 * @param {Object} record
 * @returns {*}
 * @private
 */
function _onModelFindOne(req, res, pk, error, record) {
  if (error) return res.serverError(error);
  if (!record) return res.notFound();

  Model.destroy(pk).exec(_onModelDestroy.bind(req, res, record));
}

/**
 * Destroy One Record
 * DELETE /:model/:id
 *
 * Destroys the single model instance with the specified `id` from the data adapter for the given model if it exists.
 */
module.exports = function (req, res) {
  var Model = actionUtil.parseModel(req);
  var pk = actionUtil.requirePk(req);
  var query = actionUtil.populateEach(Model.findOne(pk), req);

  query.exec(_onModelFindOne.bind(req, res, pk));
};
<|endoftext|>


<commit_before>'use strict';

var Leverage = require('leverage')
  , https = require('https')
  , fuse = require('fusing')
  , ip = require('ip');

//
// Ensure that the directory for our custom lua scripts is set correctly.
//
Leverage.scripts = Leverage.scripts.concat(
  Leverage.introduce(require('path').join(__dirname, 'redis'), Leverage.prototype)
);

/**
 * Add defaults to the supplied options. The following options are available:
 *
 * - redis: The Redis instance we should use to store data
 * - namespace: The namespace prefix to prevent collision's.
 * - interval: Expire interval to keep the server alive in Redis
 * - timeout: Timeout for sparks who are alive.
 * - latency: Time it takes for our Redis commands to execute.
 *
 * @param {Primus} primus The Primus instance that received the plugin.
 * @param {Object} options Configuration.
 * @returns {Object} Options.
 * @api public
 */
function Metroplex(primus, options) {
  if (!(this instanceof Metroplex)) return new Metroplex(primus, options);

  options = options || {};
  primus = primus || {};

  var parsed = this.parse(primus.server);

  this.fuse();

  this.redis = options.redis || require('redis').createClient();
  this.namespace = (options.namespace || 'metroplex') +':';
  this.interval = options.interval || 5 * 60 * 1000;
  this.timeout = options.timeout || 30 * 60;
  this.latency = options.latency || 2000;
  this.leverage = new Leverage(this.redis, {
    namespace: this.namespace
  });

  if (parsed || options.address) {
    this.register(options.address || parsed);
  }
}

fuse(Metroplex, require('eventemitter3'));

/**
 * Parse our the connection URL from a given HTTP server instance or string.
 *
 * @param {Server} server HTTP or HTTPS server instance we should read address from
 * @returns {String} The address
 * @api public
 */
Metroplex.readable('parse', function parse(server) {
  if ('string' === typeof server || !server) return server || '';

  var secure = server instanceof https.Server || 'function' === typeof server.addContext
    , address = server.address ? server.address() : undefined;

  //
  // If the HTTP server isn't listening yet to a port number the result of
  // .address will be undefined. We can only get the location
  //
  if (!address) return '';

  //
  // Seriously, 0.0.0.0 is basically localhost. Get the correct address for it.
  //
  if (address.address === '0.0.0.0') {
    address.address = ip.address();
  }

  return 'http'+ (secure ? 's' : '') +'://'+ address.address +':'+ address.port;
});

/**
 * Register a new server/address in the Metroplex registry.
 *
 * @param {String|Server} address The server to add.
 * @param {Function} fn Optional callback;
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('register', function register(address, fn) {
  var metroplex = this;

  metroplex.address = this.parse(address || metroplex.address);
  if (!metroplex.address) {
    if (fn) fn();
    return this;
  }

  metroplex.leverage.annihilate(metroplex.address, function annihilate(err) {
    if (err) {
      if (fn) return fn(err);
      return metroplex.emit('error', err);
    }

    metroplex.redis.multi()
      .setex(metroplex.namespace + metroplex.address, metroplex.interval, Date.now())
      .sadd(metroplex.namespace +'servers', metroplex.address)
    .exec(function register(err) {
      if (err) {
        if (fn) return fn(err);
        return metroplex.emit('error', err);
      }

      metroplex.emit('register', metroplex.address);
      metroplex.setInterval();

      if (fn) fn(err, metroplex.address);
    });
  });
});

/**
 * Remove a server/address from the Metroplex registry.
 *
 * @param {String|Server} address The server to remove.
 * @param {Function} fn Optional callback.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('unregister', function unregister(address, fn) {
  var metroplex = this;

  address = this.parse(address || metroplex.address);
  if (!metroplex.address) {
    if (fn) fn();
    return this;
  }

  metroplex.leverage.annihilate(address, function annihilate(err) {
    if (err) {
      if (fn) return fn(err);
      return metroplex.emit('error', err);
    }

    metroplex.emit('unregister', address);

    if (metroplex.timer) clearInterval(metroplex.timer);
    if (fn) fn(err, address);
  });

  return this;
});

/**
 * Add a new connection for our registered address.
 *
 * @param {Spark} spark The connection/spark from Primus.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('connect', function connect(spark) {
  this.redis.multi()
    .hset(this.namespace +'sparks', spark.id, this.address)
    .sadd(this.namespace + this.address +':sparks', spark.id)
  .exec();

  return this;
});

/**
 * Remove a connection for our registered address.
 *
 * @param {Spark} spark The connection/spark from Primus.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('disconnect', function disconnect(spark) {
  this.redis.multi()
    .hdel(this.namespace +'sparks', spark.id)
    .srem(this.namespace + this.address +':sparks', spark.id)
  .exec();

  return this;
});

/**
 * Get all current registered servers except our selfs.
 *
 * @param {Function} fn Callback
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('servers', function servers(self, fn) {
  var metroplex = this;

  if ('boolean' !== typeof self) {
    fn = self;
    self = 0;
  }

  this.redis.smembers(this.namespace +'servers', function smembers(err, members) {
    if (self) return fn(err, members);

    fn(err, (members || []).filter(function filter(address) {
      return address !== metroplex.address;
    }));
  });

  return this;
});

/**
 * Get the server address for a given spark id.
 *
 * @param {String} id The spark id who's server address we want to retrieve.
 * @param {Function} fn Callback
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('spark', function spark(id, fn) {
  this.redis.hget(this.namespace +'sparks', id, fn);
  return this;
});

/**
 * Get all server addresses for the given spark ids.
 *
 * @param {Array} args The spark id's we need to look up
 * @param {Function} fn Callback.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('sparks', function sparks(args, fn) {
  args.push(fn);
  args.shift(this.namespace +'sparks');
  this.redis.hmget.apply(this.redis, args);

  return this;
});

/**
 * We need to make sure that this server is alive, the most easy and dirty way
 * of doing this is setting an interval which bumps the expire of our
 * dedicated server key. If we go off line, the key will expire and we will be
 * K.O. The value indicates the last "ping" that we got from the node server
 * so you can see when the last update was.
 *
 * @api private
 */
Metroplex.readable('setInterval', function setIntervals() {
  if (this.timer) clearInterval(this.timer);

  var alive = this.namespace + this.address +':alive'
    , redis = this.redis
    , metroplex = this;

  this.timer = setInterval(function interval() {
    //
    // Redis expects the expire value in seconds instead of milliseconds so we
    // need to correct our interval.
    //
    redis.setex(alive, metroplex.interval / 1000, Date.now());

    metroplex.servers(function servers(err, list) {
      if (err) return metroplex.emit('error', err);

      list.forEach(function expired(address) {
        redis.get(metroplex.namespace + address, function get(err, stamp) {
          if (err || Date.now() - +stamp < metroplex.interval) return;

          metroplex.leverage.annihilate(address, function murdered(err) {
            if (err) return metroplex.emit('error', err);
          });
        });
      });
    });
  }, this.interval - this.latency);
});

//
// Expose the Metroplex library/registry/api
//
module.exports = Metroplex;
<commit_msg>Fixed redis key mismatch that was causing registered servers to be improperly annihilated<commit_after>'use strict';

var Leverage = require('leverage')
  , https = require('https')
  , fuse = require('fusing')
  , ip = require('ip');

//
// Ensure that the directory for our custom lua scripts is set correctly.
//
Leverage.scripts = Leverage.scripts.concat(
  Leverage.introduce(require('path').join(__dirname, 'redis'), Leverage.prototype)
);

/**
 * Add defaults to the supplied options. The following options are available:
 *
 * - redis: The Redis instance we should use to store data
 * - namespace: The namespace prefix to prevent collision's.
 * - interval: Expire interval to keep the server alive in Redis
 * - timeout: Timeout for sparks who are alive.
 * - latency: Time it takes for our Redis commands to execute.
 *
 * @param {Primus} primus The Primus instance that received the plugin.
 * @param {Object} options Configuration.
 * @returns {Object} Options.
 * @api public
 */
function Metroplex(primus, options) {
  if (!(this instanceof Metroplex)) return new Metroplex(primus, options);

  options = options || {};
  primus = primus || {};

  var parsed = this.parse(primus.server);

  this.fuse();

  this.redis = options.redis || require('redis').createClient();
  this.namespace = (options.namespace || 'metroplex') +':';
  this.interval = options.interval || 5 * 60 * 1000;
  this.timeout = options.timeout || 30 * 60;
  this.latency = options.latency || 2000;
  this.leverage = new Leverage(this.redis, {
    namespace: this.namespace
  });

  if (parsed || options.address) {
    this.register(options.address || parsed);
  }
}

fuse(Metroplex, require('eventemitter3'));

/**
 * Parse our the connection URL from a given HTTP server instance or string.
 *
 * @param {Server} server HTTP or HTTPS server instance we should read address from
 * @returns {String} The address
 * @api public
 */
Metroplex.readable('parse', function parse(server) {
  if ('string' === typeof server || !server) return server || '';

  var secure = server instanceof https.Server || 'function' === typeof server.addContext
    , address = server.address ? server.address() : undefined;

  //
  // If the HTTP server isn't listening yet to a port number the result of
  // .address will be undefined. We can only get the location
  //
  if (!address) return '';

  //
  // Seriously, 0.0.0.0 is basically localhost. Get the correct address for it.
  //
  if (address.address === '0.0.0.0') {
    address.address = ip.address();
  }

  return 'http'+ (secure ? 's' : '') +'://'+ address.address +':'+ address.port;
});

/**
 * Register a new server/address in the Metroplex registry.
 *
 * @param {String|Server} address The server to add.
 * @param {Function} fn Optional callback;
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('register', function register(address, fn) {
  var metroplex = this;

  metroplex.address = this.parse(address || metroplex.address);
  if (!metroplex.address) {
    if (fn) fn();
    return this;
  }

  metroplex.leverage.annihilate(metroplex.address, function annihilate(err) {
    if (err) {
      if (fn) return fn(err);
      return metroplex.emit('error', err);
    }

    metroplex.redis.multi()
      .setex(metroplex.namespace + metroplex.address, metroplex.interval, Date.now())
      .sadd(metroplex.namespace +'servers', metroplex.address)
    .exec(function register(err) {
      if (err) {
        if (fn) return fn(err);
        return metroplex.emit('error', err);
      }

      metroplex.emit('register', metroplex.address);
      metroplex.setInterval();

      if (fn) fn(err, metroplex.address);
    });
  });
});

/**
 * Remove a server/address from the Metroplex registry.
 *
 * @param {String|Server} address The server to remove.
 * @param {Function} fn Optional callback.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('unregister', function unregister(address, fn) {
  var metroplex = this;

  address = this.parse(address || metroplex.address);
  if (!metroplex.address) {
    if (fn) fn();
    return this;
  }

  metroplex.leverage.annihilate(address, function annihilate(err) {
    if (err) {
      if (fn) return fn(err);
      return metroplex.emit('error', err);
    }

    metroplex.emit('unregister', address);

    if (metroplex.timer) clearInterval(metroplex.timer);
    if (fn) fn(err, address);
  });

  return this;
});

/**
 * Add a new connection for our registered address.
 *
 * @param {Spark} spark The connection/spark from Primus.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('connect', function connect(spark) {
  this.redis.multi()
    .hset(this.namespace +'sparks', spark.id, this.address)
    .sadd(this.namespace + this.address +':sparks', spark.id)
  .exec();

  return this;
});

/**
 * Remove a connection for our registered address.
 *
 * @param {Spark} spark The connection/spark from Primus.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('disconnect', function disconnect(spark) {
  this.redis.multi()
    .hdel(this.namespace +'sparks', spark.id)
    .srem(this.namespace + this.address +':sparks', spark.id)
  .exec();

  return this;
});

/**
 * Get all current registered servers except our selfs.
 *
 * @param {Function} fn Callback
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('servers', function servers(self, fn) {
  var metroplex = this;

  if ('boolean' !== typeof self) {
    fn = self;
    self = 0;
  }

  this.redis.smembers(this.namespace +'servers', function smembers(err, members) {
    if (self) return fn(err, members);

    fn(err, (members || []).filter(function filter(address) {
      return address !== metroplex.address;
    }));
  });

  return this;
});

/**
 * Get the server address for a given spark id.
 *
 * @param {String} id The spark id who's server address we want to retrieve.
 * @param {Function} fn Callback
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('spark', function spark(id, fn) {
  this.redis.hget(this.namespace +'sparks', id, fn);
  return this;
});

/**
 * Get all server addresses for the given spark ids.
 *
 * @param {Array} args The spark id's we need to look up
 * @param {Function} fn Callback.
 * @returns {Metroplex}
 * @api public
 */
Metroplex.readable('sparks', function sparks(args, fn) {
  args.push(fn);
  args.shift(this.namespace +'sparks');
  this.redis.hmget.apply(this.redis, args);

  return this;
});

/**
 * We need to make sure that this server is alive, the most easy and dirty way
 * of doing this is setting an interval which bumps the expire of our
 * dedicated server key. If we go off line, the key will expire and we will be
 * K.O. The value indicates the last "ping" that we got from the node server
 * so you can see when the last update was.
 *
 * @api private
 */
Metroplex.readable('setInterval', function setIntervals() {
  if (this.timer) clearInterval(this.timer);

  var alive = this.namespace + this.address
    , redis = this.redis
    , metroplex = this;

  this.timer = setInterval(function interval() {
    //
    // Redis expects the expire value in seconds instead of milliseconds so we
    // need to correct our interval.
    //
    redis.setex(alive, metroplex.interval / 1000, Date.now());

    metroplex.servers(function servers(err, list) {
      if (err) return metroplex.emit('error', err);

      list.forEach(function expired(address) {
        redis.get(metroplex.namespace + address, function get(err, stamp) {
          if (err || Date.now() - +stamp < metroplex.interval) return;

          metroplex.leverage.annihilate(address, function murdered(err) {
            if (err) return metroplex.emit('error', err);
          });
        });
      });
    });
  }, this.interval - this.latency);
});

//
// Expose the Metroplex library/registry/api
//
module.exports = Metroplex;
<|endoftext|>


<commit_before>'use strict';
var pigParser = require('../pig-parser/index.js');
var fs        = require('fs');
var _         = require('lodash');
//var spawn     = require('child_process').spawn;
var logger    = require('../../config/logger.js');
var path      = require('path');
//var ds        = require('nedb');
//var connect   = require('camo').connect;
var Document  = require('camo').Document;
var EmbeddedDocument  = require('camo').EmbeddedDocument;
var diffmatchpatch = require('diff-match-patch');
var dmp = new diffmatchpatch();

class Version extends EmbeddedDocument {
  constructor()
  {
    super();
    this.version    = String;
    this.current    = Boolean;
    this.diff       = [];
    this.timeStamp  = {
      type: Date,
      default: Date.now
    };
  }
}
class Pig extends Document {
  constructor()
  {
    super();
    this.name         = String;
    this.data         = String;
    this.args         = [];
    this.version      = {
      type: String,
      default: "0.0.0"
    };
    this.script_loc   = String;
    this.history      = [Version];
    this.type         = String;
    this.graph_type   = String;
    this.graph_count  = Number;
    this.nodes        = [];
    this.links        = [];
    this.lastModified = {
      type: Date,
      default: Date.now
    }
  }
  static collectionName() {
        return 'pig.data';
    }
  run(stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB, killCB)
  {
    var script_location = '';
    if (this.script_loc)
    {
      script_location = this.script_loc;
    }
    else
    {
      script_location = path.join(__dirname, '../../',  'scripts/pig/', this.name +  '.pig');
    }

    pigParser.run(this.args, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB, killCB);
  }
  runAndTrack(stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB, killCB)
  {
    var script_location = '';
    if (this.script_loc)
    {
      script_location = this.script_loc;
    }
    else
    {
      script_location = path.join(__dirname, '../../',  'scripts/pig/', this.name +  '.pig');
    }

    pigParser.trackTasks(this.args, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB, killCB);
  }
  bumpMajor()
  {
    return parseFloat(this.version.split('.')[0]) + 1;
  }
  bumpMinor()
  {
    var v = this.version.split('.');
    var vv = parseFloat(v[1]);
    if(vv + 1 >= 10)
    {
      return 0;
    }
    else
    {
      return vv + 1;
    }
  }
  bumpRelease()
  {
    var v = this.version.split('.');
    var vv = parseFloat(v[2]);
    if(vv + 1 >= 10)
    {
      return 0;
    }
    else
    {
      return vv + 1;
    }
  }
  bump()
  {
    console.log('in bump')
    var v = this.version.split('.');
    var release = this.bumpRelease();
    var minor = v[1];
    var major = v[0];
    if (release == 0)
    {
      minor = this.bumpMinor();
      if(minor == 0)
      {
        major = this.bumpMajor();
      }
    }
    this.version = ''.concat(major,'.',minor,'.',release);
    return this.version;
  }
  preSave(d)
  {
    //this.bump();
    console.log('in presave', d);
    var that = this;
    try {
      console.log('creating a new time for modification')
    this.lastModified = Date.now();
    } catch (error) {
      console.log('caught: ', error);
    }

    console.log('returning the promise')
      return Promise.all([this.saveScript()])
  }
  rename(newPath)
  {
    var that = this;
    var script_location;
    console.log('beginning rename');
    if (this.script_loc)
    {
      script_location = this.script_loc;
      console.log('script location 3: ', script_location)
    }
    else
    {
      script_location = path.join(__dirname, '../../',  'scripts/pig/', this.name +  '.pig');
      console.log('script location 4: ', script_location)
    }
    console.log('renaming ', script_location, ' to ', newPath);
    var p = new Promise(
      function(resolve, reject)
      {
        fs.rename(script_location, newPath,
          function(err)
          {
            console.log('finished renaming', err);
            if(err)
            {
              reject(err);
            }
            else
            {
              that.script_loc = newPath;
              resolve();
            }
          });
      });
    return p;
  }
  saveScript()
  {
    var that = this;
     var p = new Promise(
      function(resolve, reject)
      {
        console.log('writing script');
        fs.writeFile(path.join(__dirname, '../../scripts/pig/' + that.name + '.pig'), that.data, 'utf-8',
          function(err)
          {
            console.log('wrote file', err);
            if(err)
            {
              logger.error('Error on creation: ', err)
              reject(err);
            }
            else
            {
              console.log('resolved')
              that.script_loc = path.join(__dirname, '../../scripts/pig/', that.name + '.pig');
              resolve(that);
            }
          });
      });
    return p;
  }
  diff(oldData, save, newData)
  {
    var d;
    var version;
    if(newData)
    {
      d = dmp.diff_main(this.data, newData.data);
      version = newData.version;
    }
    else
    {
      d = dmp.diff_main(oldData.data, this.data)
      version = this.version;
    }
    console.log('starting diff');
    //var d = diff.diffTrimmedLines(this.data, newData.data)
    //var d = dmp.diff_main(this.data, newData.data);
    //var d = dmp.diff_main(oldData.data, this.data);
    dmp.diff_cleanupEfficiency(d);
    if(save)
    {
      console.log('diff', d, 'creating new Version: ', version);
      try {
        var vers = Version.create({
        version: version,
        current: true,
        diff: d
      });
      } catch (error) {
        console.log(error);
      }

      console.log('version', vers, 'created');
      this.history.forEach(function(e) { e.current = false;});
      console.log('all currents set to false');
      this.history.push(vers);
      console.log('pushed new version');
    }
    return d;
  }
  update(data)
  {
    this.name         = data.name;
    this.data         = data.data;
    this.args         = data.args
    this.version      = data.version;
    this.script_loc   = data.script_loc;
    this.type         = data.type;
    this.graph_type   = data.graph_type;
    this.graph_count  = data.graph_count;
    this.nodes        = data.nodes;
    this.links        = data.links;
  }
}

exports.Pig = Pig;
exports.init = function(cb)
{
  cb(null);
  /*var uri = 'nedb://' + path.join(__dirname);
  connect(uri).then(function(db) {
    logger.info('connected to DB', db, uri);
    cb(null, db);
  })*/
}
/*
var collection = new ds({filename: 'server/api/pig/pig.data.db', autoload: true, onload: function (err) { if(err) { logger.error('Error on load: ', err) }}});

exports.create = function(obj, cb)
{
  //logger.debug('Creating Script: ', JSON.parse(obj));
  collection.insert(JSON.parse(obj),
    function(err, doc)
    {
      logger.debug('Document Inserted: ', doc, err);
      if(err)
      {
        logger.error('Error on creation: ', err)
      }
      else
      {
        fs.writeFile(path.join(__dirname, '../../scripts/pig/' + doc["name"] + '.pig'), doc.data, 'utf-8',
          function(err)
          {
            if(err) { logger.error('Error on creation: ', err) }
            cb(err,doc)
          });
      }
    });
}
exports.list = function(cb)
{
  collection.find({}, cb);
}
exports.find = function(id, cb)
{
  collection.findOne({_id: id}, cb);
}
exports.update = function(id, changes, cb)
{
  changes = JSON.parse(changes);
  collection.findOne({_id: id},
    function(err, doc)
    {
      if(err)
      {
        logger.error(err);
        return cb(err);
      }
      collection.update({_id: id}, changes, {upsert: true, returnUpdatedDocs: true},
        function(err, numAffected, affectedDocuments, upsert)
        {
          if(err)
          {
            logger.error(err);
            return cb(err);
          }
          //logger.debug('doc: ', doc, 'Changes: ', changes, 'affected Documents: ', affectedDocuments, 'Error', err, ' num affected: ', numAffected, 'upsert: ', upsert);
          if(changes.name != doc.name)
          {
            fs.rename('server/scripts/pig/' + doc.name + '.pig', 'server/scripts/pig/' + changes.name + '.pig', function(err) { if (err) logger.error(err); });
          }

          fs.writeFile('server/scripts/pig/' + changes.name + '.pig', changes.data, 'utf-8', function(err) { if (err) { logger.error (err) } });
          cb(null, affectedDocuments);
        });
    });
}
exports.delete = function(id, cb)
{
  collection.remove({_id: id},cb);
}
exports.run = function(id, stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB)
{
  logger.debug('Running Pig Script: ', id);
  var nArgs = ["-x", "local"];

  collection.findOne({_id: id},
    function(err, doc)
    {
      if(err)
      {
        return errCB(err);
      }

      if (doc.args)
      {
        nArgs = doc.args;
      }

      var script_location = path.join(__dirname, '../../',  'scripts/pig/', doc.name +  '.pig');

      pigParser.run(nArgs, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB);
    });

}
exports.runAndTrack = function(id, stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB)
{
  logger.debug('Running Pig Script: ', id);
  var nArgs = ["-x", "local"];

  collection.findOne({_id: id},
    function(err, doc)
    {
      if(err)
      {
        return errCB(err);
      }

      if (doc.args)
      {
        nArgs = doc.args;
      }

      var script_location = path.join(__dirname, '../../',  'scripts/pig/', doc.name +  '.pig');

      pigParser.trackTasks(nArgs, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB);
    });

};
*/
<commit_msg>fixed time modified issue<commit_after>'use strict';
var pigParser = require('../pig-parser/index.js');
var fs        = require('fs');
var _         = require('lodash');
//var spawn     = require('child_process').spawn;
var logger    = require('../../config/logger.js');
var path      = require('path');
//var ds        = require('nedb');
//var connect   = require('camo').connect;
var Document  = require('camo').Document;
var EmbeddedDocument  = require('camo').EmbeddedDocument;
var diffmatchpatch = require('diff-match-patch');
var dmp = new diffmatchpatch();

class Version extends EmbeddedDocument {
  constructor()
  {
    super();
    this.version    = String;
    this.current    = Boolean;
    this.diff       = [];
    this.timeStamp  = {
      type: Date,
      default: Date.now
    };
  }
}
class Pig extends Document {
  constructor()
  {
    super();
    this.name         = String;
    this.data         = String;
    this.args         = [];
    this.version      = {
      type: String,
      default: "0.0.0"
    };
    this.script_loc   = String;
    this.history      = [Version];
    this.type         = String;
    this.graph_type   = String;
    this.graph_count  = Number;
    this.nodes        = [];
    this.links        = [];
    this.lastModified = {
      type: Date,
      default: Date.now
    }
  }
  static collectionName() {
        return 'pig.data';
    }
  run(stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB, killCB)
  {
    var script_location = '';
    if (this.script_loc)
    {
      script_location = this.script_loc;
    }
    else
    {
      script_location = path.join(__dirname, '../../',  'scripts/pig/', this.name +  '.pig');
    }

    pigParser.run(this.args, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB, killCB);
  }
  runAndTrack(stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB, killCB)
  {
    var script_location = '';
    if (this.script_loc)
    {
      script_location = this.script_loc;
    }
    else
    {
      script_location = path.join(__dirname, '../../',  'scripts/pig/', this.name +  '.pig');
    }

    pigParser.trackTasks(this.args, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB, killCB);
  }
  bumpMajor()
  {
    return parseFloat(this.version.split('.')[0]) + 1;
  }
  bumpMinor()
  {
    var v = this.version.split('.');
    var vv = parseFloat(v[1]);
    if(vv + 1 >= 10)
    {
      return 0;
    }
    else
    {
      return vv + 1;
    }
  }
  bumpRelease()
  {
    var v = this.version.split('.');
    var vv = parseFloat(v[2]);
    if(vv + 1 >= 10)
    {
      return 0;
    }
    else
    {
      return vv + 1;
    }
  }
  bump()
  {
    console.log('in bump')
    var v = this.version.split('.');
    var release = this.bumpRelease();
    var minor = v[1];
    var major = v[0];
    if (release == 0)
    {
      minor = this.bumpMinor();
      if(minor == 0)
      {
        major = this.bumpMajor();
      }
    }
    this.version = ''.concat(major,'.',minor,'.',release);
    return this.version;
  }
  preSave(d)
  {
    //this.bump();
    console.log('in presave', d);
    var that = this;
    try {
      console.log('creating a new time for modification')
      console.log('time: ', this.lastModified, typeof this.lastModified);
    //that.lastModified = null; //new Date();
      console.log('time again: ', this.lastModified, typeof this.lastModified);
    } catch (error) {
      console.log('caught: ', error);
    }

    console.log('returning the promise')
      return Promise.all([this.saveScript()])
  }
  rename(newPath)
  {
    var that = this;
    var script_location;
    console.log('beginning rename');
    if (this.script_loc)
    {
      script_location = this.script_loc;
      console.log('script location 3: ', script_location)
    }
    else
    {
      script_location = path.join(__dirname, '../../',  'scripts/pig/', this.name +  '.pig');
      console.log('script location 4: ', script_location)
    }
    console.log('renaming ', script_location, ' to ', newPath);
    var p = new Promise(
      function(resolve, reject)
      {
        fs.rename(script_location, newPath,
          function(err)
          {
            console.log('finished renaming', err);
            if(err)
            {
              reject(err);
            }
            else
            {
              that.script_loc = newPath;
              resolve();
            }
          });
      });
    return p;
  }
  saveScript()
  {
    var that = this;
     var p = new Promise(
      function(resolve, reject)
      {
        console.log('writing script');
        fs.writeFile(path.join(__dirname, '../../scripts/pig/' + that.name + '.pig'), that.data, 'utf-8',
          function(err)
          {
            console.log('wrote file', err);
            if(err)
            {
              logger.error('Error on creation: ', err)
              reject(err);
            }
            else
            {
              console.log('resolved')
              that.script_loc = path.join(__dirname, '../../scripts/pig/', that.name + '.pig');
              resolve(that);
            }
          });
      });
    return p;
  }
  diff(oldData, save, newData)
  {
    var d;
    var version;
    if(newData)
    {
      d = dmp.diff_main(this.data, newData.data);
      version = newData.version;
    }
    else
    {
      d = dmp.diff_main(oldData.data, this.data)
      version = this.version;
    }
    console.log('starting diff');
    //var d = diff.diffTrimmedLines(this.data, newData.data)
    //var d = dmp.diff_main(this.data, newData.data);
    //var d = dmp.diff_main(oldData.data, this.data);
    dmp.diff_cleanupEfficiency(d);
    if(save)
    {
      console.log('diff', d, 'creating new Version: ', version);
      try {
        var vers = Version.create({
        version: version,
        current: true,
        diff: d
      });
      } catch (error) {
        console.log(error);
      }

      console.log('version', vers, 'created');
      this.history.forEach(function(e) { e.current = false;});
      console.log('all currents set to false');
      this.history.push(vers);
      console.log('pushed new version');
    }
    return d;
  }
  update(data)
  {
    this.name         = data.name;
    this.data         = data.data;
    this.args         = data.args
    this.version      = data.version;
    this.script_loc   = data.script_loc;
    this.type         = data.type;
    this.graph_type   = data.graph_type;
    this.graph_count  = data.graph_count;
    this.nodes        = data.nodes;
    this.links        = data.links;
    this.lastModified = new Date();
  }
}

exports.Pig = Pig;
exports.init = function(cb)
{
  cb(null);
  /*var uri = 'nedb://' + path.join(__dirname);
  connect(uri).then(function(db) {
    logger.info('connected to DB', db, uri);
    cb(null, db);
  })*/
}
/*
var collection = new ds({filename: 'server/api/pig/pig.data.db', autoload: true, onload: function (err) { if(err) { logger.error('Error on load: ', err) }}});

exports.create = function(obj, cb)
{
  //logger.debug('Creating Script: ', JSON.parse(obj));
  collection.insert(JSON.parse(obj),
    function(err, doc)
    {
      logger.debug('Document Inserted: ', doc, err);
      if(err)
      {
        logger.error('Error on creation: ', err)
      }
      else
      {
        fs.writeFile(path.join(__dirname, '../../scripts/pig/' + doc["name"] + '.pig'), doc.data, 'utf-8',
          function(err)
          {
            if(err) { logger.error('Error on creation: ', err) }
            cb(err,doc)
          });
      }
    });
}
exports.list = function(cb)
{
  collection.find({}, cb);
}
exports.find = function(id, cb)
{
  collection.findOne({_id: id}, cb);
}
exports.update = function(id, changes, cb)
{
  changes = JSON.parse(changes);
  collection.findOne({_id: id},
    function(err, doc)
    {
      if(err)
      {
        logger.error(err);
        return cb(err);
      }
      collection.update({_id: id}, changes, {upsert: true, returnUpdatedDocs: true},
        function(err, numAffected, affectedDocuments, upsert)
        {
          if(err)
          {
            logger.error(err);
            return cb(err);
          }
          //logger.debug('doc: ', doc, 'Changes: ', changes, 'affected Documents: ', affectedDocuments, 'Error', err, ' num affected: ', numAffected, 'upsert: ', upsert);
          if(changes.name != doc.name)
          {
            fs.rename('server/scripts/pig/' + doc.name + '.pig', 'server/scripts/pig/' + changes.name + '.pig', function(err) { if (err) logger.error(err); });
          }

          fs.writeFile('server/scripts/pig/' + changes.name + '.pig', changes.data, 'utf-8', function(err) { if (err) { logger.error (err) } });
          cb(null, affectedDocuments);
        });
    });
}
exports.delete = function(id, cb)
{
  collection.remove({_id: id},cb);
}
exports.run = function(id, stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB)
{
  logger.debug('Running Pig Script: ', id);
  var nArgs = ["-x", "local"];

  collection.findOne({_id: id},
    function(err, doc)
    {
      if(err)
      {
        return errCB(err);
      }

      if (doc.args)
      {
        nArgs = doc.args;
      }

      var script_location = path.join(__dirname, '../../',  'scripts/pig/', doc.name +  '.pig');

      pigParser.run(nArgs, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, finishedCB);
    });

}
exports.runAndTrack = function(id, stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB)
{
  logger.debug('Running Pig Script: ', id);
  var nArgs = ["-x", "local"];

  collection.findOne({_id: id},
    function(err, doc)
    {
      if(err)
      {
        return errCB(err);
      }

      if (doc.args)
      {
        nArgs = doc.args;
      }

      var script_location = path.join(__dirname, '../../',  'scripts/pig/', doc.name +  '.pig');

      pigParser.trackTasks(nArgs, script_location, stdoutCB, stderrCB, stdlogCB, stdwarningCB, trackerCB, finishedCB);
    });

};
*/
<|endoftext|>


<commit_before>
//Will call bindButtons after the DOM loads
document.addEventListener('DOMContentLoaded', bindButtons);

var counter = 0;
var tagDict = {"baseCalls1":{"tagName":"PBAS", "tagNum":1, "typeToReturn":"getChar"},
    "baseCalls2":{"tagName":"PBAS", "tagNum":2, "typeToReturn":"getChar"},
    "qualNums":{"tagName":"PCON", "tagNum":2, "typeToReturn":"getNumber"},
    "peakLocations":{"tagName":"PLOC", "tagNum":2, "typeToReturn":"getShort"},
    "peakDev":{"tagName":"P1RL", "tagNum":1, "typeToReturn":"getShort"},
    "peakOneAmp":{"tagName":"P1AM", "tagNum":1, "typeToReturn":"getShort"},
    "colorDataA":{"tagName":"DATA", "tagNum":10, "typeToReturn":"getShort"},
    "colorDataT":{"tagName":"DATA", "tagNum":11, "typeToReturn":"getShort"},
    "colorDataG":{"tagName":"DATA", "tagNum":9, "typeToReturn":"getShort"},
    "colorDataC":{"tagName":"DATA", "tagNum":12, "typeToReturn":"getShort"}
    };

function bindButtons(){
    document.getElementById('fileName').addEventListener('change', function subBind(event){

        var fileName = document.getElementById("fileName").value;
        //Regex to remove the pathname and just keep filename
        fileName = fileName.replace(/.*[\/\\]/, '');
        document.getElementById("selectedFile").value = fileName;
        //Regex to remove file extension
        fileName = fileName.replace(/\.[^/.]+$/, '');
        document.getElementById("newFileName").value = fileName;
        document.getElementById("seqID").value = fileName;
        var oFiles = document.getElementById("fileName").files;
        var oneFile = oFiles[0];

        var fileObj = new FileReader();
        var output = "";
        fileObj.onload = function (e){
            var contents = e.target.result;
            var dataview = new DataView(contents);
            var converter = new abConverter(dataview);
            var painter = new drawTrace(converter.getTraceData());

            document.getElementById("fileType").innerHTML = converter.getFileID();
            document.getElementById("fileVersion").innerHTML = converter.getFileVersion();

            painter.paintCanvas();
            var header = fileName;
            var baseCalls = converter.getDataTag(tagDict.baseCalls2);
            var qualScores = converter.getDataTag(tagDict.qualNums);
            mottTrim(baseCalls, qualScores);
            var basesString = "";
            var scoreString = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
            var convertedScores = "";
            for (var baseCounter = 0; baseCounter < baseCalls.length; baseCounter++) {
                if (baseCounter != 0 && baseCounter % 80 === 0) {
                    basesString += "\r\n";
                    basesString += baseCalls[baseCounter];
                }
                else {
                    basesString += baseCalls[baseCounter];
                }

                convertedScores += scoreString.charAt(qualScores[baseCounter]);
            }
            var fasta = ">" + header + "\r\n" + basesString;
            var fastq = "@" + header + "\r\n" + basesString + "\r\n" + "+" + "\r\n" + convertedScores;
            document.getElementById("bases").textContent = basesString;

            var fastaDownload = document.getElementById('downloadFASTA');
            fastaDownload.onclick = function () {
                header = document.getElementById("seqID").value;
                fasta = ">" + header + "\r\n" + basesString;
                fastaDownload.href = window.URL.createObjectURL(new Blob([fasta], {type: 'text/plain'}));
                fastaDownload.download = document.getElementById("newFileName").value + '.fasta';
            }

            var fastqDownload = document.getElementById('downloadFASTQ');
            fastqDownload.onclick = function () {
                header = document.getElementById("seqID").value;
                fastq = "@" + header + "\r\n" + basesString + "\r\n" + "+" + "\r\n" + convertedScores;
                fastqDownload.href = window.URL.createObjectURL(new Blob([fastq], {type: 'text/plain'}));
                fastqDownload.download = document.getElementById("newFileName").value + '.fastq';
            }

        }
        fileObj.readAsArrayBuffer(oneFile);

        event.preventDefault();
    })
};

function abConverter(inputArrayBuffer) {
    var dirLocation = inputArrayBuffer.getInt32(26);
    var numElements = inputArrayBuffer.getInt32(18);
    var lastEntry = dirLocation + (numElements * 28);

    this.getFileID = function() {
        var output = "";
        for (var offset = 0; offset < 4; offset++) {
            output += String.fromCharCode(inputArrayBuffer.getInt8(offset));
        }
        return output;
    }

    this.getFileVersion = function () {
        return inputArrayBuffer.getInt16(4);
    }

    this.getDirectoryStruct = function () {
        var br = "<br>";
        var indent = "  ";
        var output = br;
        var name = "";
        for (var offset = 6; offset < 10; offset++) {
            name += String.fromCharCode(inputArrayBuffer.getInt8(offset));
        }
        output += ("- tag name: " + name + br);
        output += ("- tag number: " + inputArrayBuffer.getInt32(10) + br);
        output += ("- element type: " + inputArrayBuffer.getInt16(14) + br);
        output += ("- element size: " + inputArrayBuffer.getInt16(16) + br);
        output += ("- num elements: " + inputArrayBuffer.getInt32(18) + br);
        output += ("- data size: " + inputArrayBuffer.getInt32(22) + br);
        output += ("- data offset: " + inputArrayBuffer.getInt32(26) + br);
        return output;
    }

    this.getNumber = function (inOffset, numEntries) {
        var retArray = [];
        for (var counter = 0; counter < numEntries; counter += 1) {
            retArray.push(inputArrayBuffer.getInt8(inOffset + counter));
        }
        return retArray;
    }.bind(this);

    this.getChar = function (inOffset, numEntries) {
        var retArray = [];
        for (var counter = 0; counter < numEntries; counter += 1) {
            retArray.push(String.fromCharCode(inputArrayBuffer.getInt8(inOffset + counter)));
        }
        return retArray;
    }.bind(this);

    this.getShort = function (inOffset, numEntries) {
        var retArray = [];
        for (var counter = 0; counter < numEntries; counter += 2) {
            retArray.push(inputArrayBuffer.getInt16(inOffset + counter));
        }
        return retArray;

    }.bind(this);

    this.getByte = function (inOffset, counter) {
        return inputArrayBuffer.getUint8(inOffset + counter);
    }.bind(this);

    this.getWord = function (inOffset, numEntries) {
        var retVal = "";
        for (var counter = 0; counter < numEntries; counter += 2) {
            retVal += inputArrayBuffer.getUint16(inOffset + counter);
        }
        return retVal;

    }.bind(this);

    this.getLong = function (inOffset, counter) {
        return inputArrayBuffer.getInt32(inOffset);
    }.bind(this);

    this.getFloat = function (inOffset, counter) {
        return inputArrayBuffer.getFloat32(inOffset);
    }.bind(this);

    this.getDouble = function (inOffset, counter) {
        return inputArrayBuffer.getFloat64(inOffset);
    }.bind(this);

    this.getDate = function (inOffset, counter) {
        var date = "";
        date += inputArrayBuffer.getInt16(inOffset);
        date += inputArrayBuffer.getUint8(inOffset + 2);
        date += inputArrayBuffer.getUint8(inOffset + 3);
        return date;
    }.bind(this);

    this.getTime = function (inOffset, counter) {
        var time = "";
        time += inputArrayBuffer.getUint8(inOffset);
        time += inputArrayBuffer.getUint8(inOffset + 1);
        time += inputArrayBuffer.getUint8(inOffset + 2);
        time += inputArrayBuffer.getUint8(inOffset + 3);
        return time;
    }.bind(this);

    this.getPString = function (inOffset, counter) {
        var outString = "";
        for (var count = 1; count < inputArrayBuffer.getInt8(inOffset); count++) {
            outString += inputArrayBuffer.getInt8(inOffset + count);
        }
    }.bind(this);

    this.getCString = function (inOffset, counter) {
        var outString = "";
        var offset = inOffset;
        var currentByte = inputArrayBuffer.getInt8(offset);
        while (currentByte != 0) {
            outString += String.fromCharCode(currentByte);
            offset++;
            currentByte = inputArrayBuffer.getInt8(offset);
        }
        return outString;
    }.bind(this);

    this.getTagName = function (inOffset) {
        var name = "";
        for (var loopOffset = inOffset; loopOffset < inOffset + 4; loopOffset++) {
            name += String.fromCharCode(inputArrayBuffer.getInt8(loopOffset));
        }
        return name;
    }.bind(this);

    this.getDataTag = function (inTag) {
        var output;
        var curElem = dirLocation;
        do {
            var currTagName = this.getTagName(curElem);
            var tagNum = inputArrayBuffer.getInt32(curElem + 4);
            if (currTagName == inTag.tagName && tagNum === inTag.tagNum) {
                var numEntries = inputArrayBuffer.getInt32(curElem + 16);
                var entryOffset = inputArrayBuffer.getInt32(curElem + 20);
                output = this[inTag.typeToReturn](entryOffset, numEntries);
            }
            curElem += 28;
        } while (curElem < lastEntry);
        return output;
    }

    this.getTraceData = function () {
        var traceData = {};
        traceData.aTrace = this.getDataTag(tagDict.colorDataA);
        traceData.tTrace = this.getDataTag(tagDict.colorDataT);
        traceData.gTrace = this.getDataTag(tagDict.colorDataG);
        traceData.cTrace = this.getDataTag(tagDict.colorDataC);
        traceData.basePos = this.getDataTag(tagDict.peakLocations);
        traceData.baseCalls = this.getDataTag(tagDict.baseCalls2);
        traceData.qualNums = this.getDataTag(tagDict.qualNums);

        return traceData;
    }

    this.getFirstEntry = function () {

        var output = "";
        for (var curElem = dirLocation; curElem < lastEntry; curElem += 28) {
            var name = "";
            for (var offset = curElem; offset < curElem + 4; offset++) {
                name += String.fromCharCode(inputArrayBuffer.getInt8(offset));
            }
            output += (" - " + name);
        }
        return output;
    }
}

function drawTrace (traceData) {
    console.log("in draw trace");
    var colors = {adenine:"green", thymine:"red", guanine:"black", cytosine:"blue", other:"pink"};
    var peakCanvas = document.getElementById("peakCanvas");
    var ctx = peakCanvas.getContext("2d");

    var formattedPeaks = {a:[], t:[], g:[], c:[]};
    var bottomBuffer = 50;
    var baseBuffer = 35;
    var maxHeight = peakCanvas.height;
    var maxWidth = traceData.basePos[traceData.basePos.length - 1];
    peakCanvas.width = maxWidth;
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, maxWidth, peakCanvas.height);
    var scaledHeight = maxHeight - bottomBuffer;
    var scalePct = 0;

    this.findTallest = function () {
        var aMax = Math.max(...traceData.aTrace);
        var tMax = Math.max(...traceData.tTrace);
        var gMax = Math.max(...traceData.gTrace);
        var cMax = Math.max(...traceData.cTrace);
        scalePct = scaledHeight / Math.max(aMax, tMax, gMax, cMax);
    }

    this.scalePeaks = function (traceIn) {
        var newPeaks = [];
        for (var count = 0; count < traceIn.length; count++) {
            newPeaks[count] = scalePct * traceIn[count];
        }
        return newPeaks;
    }

    this.preparePeaks = function () {
        this.findTallest();
        formattedPeaks.a = this.scalePeaks(traceData.aTrace);
        formattedPeaks.t = this.scalePeaks(traceData.tTrace);
        formattedPeaks.g = this.scalePeaks(traceData.gTrace);
        formattedPeaks.c = this.scalePeaks(traceData.cTrace);
    }

    this.drawPeaks = function(trace, lineColor) {
        ctx.beginPath();
        ctx.moveTo(0, scaledHeight - trace[0])
        for (var counter = 1; counter < trace.length; counter++) {
            ctx.lineTo(counter, scaledHeight - trace[counter]);
            ctx.moveTo(counter, scaledHeight - trace[counter]);
        }
        ctx.strokeStyle = lineColor;
        ctx.stroke();
    }

    this.drawBases = function () {
        console.log("in drawbases");
        //ctx.font = "24px serif";
        var xOffset = -2;
        for (var count = 0; count < traceData.baseCalls.length; count++) {
            var baseCall = traceData.baseCalls[count];
            switch(baseCall) {
                case "A":
                    ctx.fillStyle = colors.adenine;
                    break;
                case "T":
                    ctx.fillStyle = colors.thymine;
                    break;
                case "G":
                    ctx.fillStyle = colors.guanine;
                    break;
                case "C":
                    ctx.fillStyle = colors.cytosine;
                    break;
                default:
                    ctx.fillStyle = colors.other;
            }
            ctx.fillText(baseCall, traceData.basePos[count] + xOffset, maxHeight - baseBuffer);
        }
    }

    this.paintCanvas = function () {
        this.preparePeaks();
        this.drawPeaks(formattedPeaks.a, colors.adenine);
        this.drawPeaks(formattedPeaks.t, colors.thymine);
        this.drawPeaks(formattedPeaks.g, colors.guanine);
        this.drawPeaks(formattedPeaks.c, colors.cytosine);
        this.drawBases();
    }
}

function mottTrim(baseCalls, qualScores) {

    console.log(qualScores);
    var startPos = 0;
    var endPos = 0;
    var tempStart = 0;
    var tempEnd;
    var score = 0;
    var cutoff = 0.01;
    for (var count = 0; count < qualScores.length; count++) {
        //console.log(Math.pow(10,(qualScores[count])/-10));
        score = score + cutoff - Math.pow(10,(qualScores[count])/-10);
        //console.log(score);
        if (score < 0) {
            tempStart = count;
        }
        if (count - tempStart > endPos - startPos) {
            startPos = tempStart;
            endPos = count;
        }
        //console.log(startPos);
    }
    var trimmed = baseCalls.slice(startPos, endPos + 1);
    console.log(trimmed);
}<commit_msg>Added header comment to describe usage.<commit_after>/*
Read binary Applied Biosystems AB1 files generated by Genetic Analyzer systems.
http://www6.appliedbiosystems.com/support/software_community/ABIF_File_Format.pdf
Incomplete as of 3/28/17.  Not all versions of AB1 files supported by default.
To use directly create a DataView with the AB1 file of interest, create a new
abConverter object by passing in that DataView, then display the directory structure
with a call to getDirectoryStruct.  You can then retrieve the data from each tag
displayed by getDirectoryStruct with a call to getDataTag and manually passing in
the tag name.

The event listener, bindButtons, and draw trace functions will draw the chromatogram
on an HTML canvas object.  An example HTML and CSS file is included in the repo.

The mottTrim function will return a sequence that is trimmed based on Mott's modified
trimming algorithm.
*/

//Will call bindButtons after the DOM loads
document.addEventListener('DOMContentLoaded', bindButtons);

var counter = 0;
var tagDict = {"baseCalls1":{"tagName":"PBAS", "tagNum":1, "typeToReturn":"getChar"},
    "baseCalls2":{"tagName":"PBAS", "tagNum":2, "typeToReturn":"getChar"},
    "qualNums":{"tagName":"PCON", "tagNum":2, "typeToReturn":"getNumber"},
    "peakLocations":{"tagName":"PLOC", "tagNum":2, "typeToReturn":"getShort"},
    "peakDev":{"tagName":"P1RL", "tagNum":1, "typeToReturn":"getShort"},
    "peakOneAmp":{"tagName":"P1AM", "tagNum":1, "typeToReturn":"getShort"},
    "colorDataA":{"tagName":"DATA", "tagNum":10, "typeToReturn":"getShort"},
    "colorDataT":{"tagName":"DATA", "tagNum":11, "typeToReturn":"getShort"},
    "colorDataG":{"tagName":"DATA", "tagNum":9, "typeToReturn":"getShort"},
    "colorDataC":{"tagName":"DATA", "tagNum":12, "typeToReturn":"getShort"}
    };

function bindButtons(){
    document.getElementById('fileName').addEventListener('change', function subBind(event){

        var fileName = document.getElementById("fileName").value;
        //Regex to remove the pathname and just keep filename
        fileName = fileName.replace(/.*[\/\\]/, '');
        document.getElementById("selectedFile").value = fileName;
        //Regex to remove file extension
        fileName = fileName.replace(/\.[^/.]+$/, '');
        document.getElementById("newFileName").value = fileName;
        document.getElementById("seqID").value = fileName;
        var oFiles = document.getElementById("fileName").files;
        var oneFile = oFiles[0];

        var fileObj = new FileReader();
        var output = "";
        fileObj.onload = function (e){
            var contents = e.target.result;
            var dataview = new DataView(contents);
            var converter = new abConverter(dataview);
            var painter = new drawTrace(converter.getTraceData());

            document.getElementById("fileType").innerHTML = converter.getFileID();
            document.getElementById("fileVersion").innerHTML = converter.getFileVersion();

            painter.paintCanvas();
            var header = fileName;
            var baseCalls = converter.getDataTag(tagDict.baseCalls2);
            var qualScores = converter.getDataTag(tagDict.qualNums);
            mottTrim(baseCalls, qualScores);
            var basesString = "";
            var scoreString = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
            var convertedScores = "";
            for (var baseCounter = 0; baseCounter < baseCalls.length; baseCounter++) {
                if (baseCounter != 0 && baseCounter % 80 === 0) {
                    basesString += "\r\n";
                    basesString += baseCalls[baseCounter];
                }
                else {
                    basesString += baseCalls[baseCounter];
                }

                convertedScores += scoreString.charAt(qualScores[baseCounter]);
            }
            var fasta = ">" + header + "\r\n" + basesString;
            var fastq = "@" + header + "\r\n" + basesString + "\r\n" + "+" + "\r\n" + convertedScores;
            document.getElementById("bases").textContent = basesString;

            var fastaDownload = document.getElementById('downloadFASTA');
            fastaDownload.onclick = function () {
                header = document.getElementById("seqID").value;
                fasta = ">" + header + "\r\n" + basesString;
                fastaDownload.href = window.URL.createObjectURL(new Blob([fasta], {type: 'text/plain'}));
                fastaDownload.download = document.getElementById("newFileName").value + '.fasta';
            }

            var fastqDownload = document.getElementById('downloadFASTQ');
            fastqDownload.onclick = function () {
                header = document.getElementById("seqID").value;
                fastq = "@" + header + "\r\n" + basesString + "\r\n" + "+" + "\r\n" + convertedScores;
                fastqDownload.href = window.URL.createObjectURL(new Blob([fastq], {type: 'text/plain'}));
                fastqDownload.download = document.getElementById("newFileName").value + '.fastq';
            }

        }
        fileObj.readAsArrayBuffer(oneFile);

        event.preventDefault();
    })
};

function abConverter(inputArrayBuffer) {
    var dirLocation = inputArrayBuffer.getInt32(26);
    var numElements = inputArrayBuffer.getInt32(18);
    var lastEntry = dirLocation + (numElements * 28);

    this.getFileID = function() {
        var output = "";
        for (var offset = 0; offset < 4; offset++) {
            output += String.fromCharCode(inputArrayBuffer.getInt8(offset));
        }
        return output;
    }

    this.getFileVersion = function () {
        return inputArrayBuffer.getInt16(4);
    }

    this.getDirectoryStruct = function () {
        var br = "<br>";
        var indent = "  ";
        var output = br;
        var name = "";
        for (var offset = 6; offset < 10; offset++) {
            name += String.fromCharCode(inputArrayBuffer.getInt8(offset));
        }
        output += ("- tag name: " + name + br);
        output += ("- tag number: " + inputArrayBuffer.getInt32(10) + br);
        output += ("- element type: " + inputArrayBuffer.getInt16(14) + br);
        output += ("- element size: " + inputArrayBuffer.getInt16(16) + br);
        output += ("- num elements: " + inputArrayBuffer.getInt32(18) + br);
        output += ("- data size: " + inputArrayBuffer.getInt32(22) + br);
        output += ("- data offset: " + inputArrayBuffer.getInt32(26) + br);
        return output;
    }

    this.getNumber = function (inOffset, numEntries) {
        var retArray = [];
        for (var counter = 0; counter < numEntries; counter += 1) {
            retArray.push(inputArrayBuffer.getInt8(inOffset + counter));
        }
        return retArray;
    }.bind(this);

    this.getChar = function (inOffset, numEntries) {
        var retArray = [];
        for (var counter = 0; counter < numEntries; counter += 1) {
            retArray.push(String.fromCharCode(inputArrayBuffer.getInt8(inOffset + counter)));
        }
        return retArray;
    }.bind(this);

    this.getShort = function (inOffset, numEntries) {
        var retArray = [];
        for (var counter = 0; counter < numEntries; counter += 2) {
            retArray.push(inputArrayBuffer.getInt16(inOffset + counter));
        }
        return retArray;

    }.bind(this);

    this.getByte = function (inOffset, counter) {
        return inputArrayBuffer.getUint8(inOffset + counter);
    }.bind(this);

    this.getWord = function (inOffset, numEntries) {
        var retVal = "";
        for (var counter = 0; counter < numEntries; counter += 2) {
            retVal += inputArrayBuffer.getUint16(inOffset + counter);
        }
        return retVal;

    }.bind(this);

    this.getLong = function (inOffset, counter) {
        return inputArrayBuffer.getInt32(inOffset);
    }.bind(this);

    this.getFloat = function (inOffset, counter) {
        return inputArrayBuffer.getFloat32(inOffset);
    }.bind(this);

    this.getDouble = function (inOffset, counter) {
        return inputArrayBuffer.getFloat64(inOffset);
    }.bind(this);

    this.getDate = function (inOffset, counter) {
        var date = "";
        date += inputArrayBuffer.getInt16(inOffset);
        date += inputArrayBuffer.getUint8(inOffset + 2);
        date += inputArrayBuffer.getUint8(inOffset + 3);
        return date;
    }.bind(this);

    this.getTime = function (inOffset, counter) {
        var time = "";
        time += inputArrayBuffer.getUint8(inOffset);
        time += inputArrayBuffer.getUint8(inOffset + 1);
        time += inputArrayBuffer.getUint8(inOffset + 2);
        time += inputArrayBuffer.getUint8(inOffset + 3);
        return time;
    }.bind(this);

    this.getPString = function (inOffset, counter) {
        var outString = "";
        for (var count = 1; count < inputArrayBuffer.getInt8(inOffset); count++) {
            outString += inputArrayBuffer.getInt8(inOffset + count);
        }
    }.bind(this);

    this.getCString = function (inOffset, counter) {
        var outString = "";
        var offset = inOffset;
        var currentByte = inputArrayBuffer.getInt8(offset);
        while (currentByte != 0) {
            outString += String.fromCharCode(currentByte);
            offset++;
            currentByte = inputArrayBuffer.getInt8(offset);
        }
        return outString;
    }.bind(this);

    this.getTagName = function (inOffset) {
        var name = "";
        for (var loopOffset = inOffset; loopOffset < inOffset + 4; loopOffset++) {
            name += String.fromCharCode(inputArrayBuffer.getInt8(loopOffset));
        }
        return name;
    }.bind(this);

    this.getDataTag = function (inTag) {
        var output;
        var curElem = dirLocation;
        do {
            var currTagName = this.getTagName(curElem);
            var tagNum = inputArrayBuffer.getInt32(curElem + 4);
            if (currTagName == inTag.tagName && tagNum === inTag.tagNum) {
                var numEntries = inputArrayBuffer.getInt32(curElem + 16);
                var entryOffset = inputArrayBuffer.getInt32(curElem + 20);
                output = this[inTag.typeToReturn](entryOffset, numEntries);
            }
            curElem += 28;
        } while (curElem < lastEntry);
        return output;
    }

    this.getTraceData = function () {
        var traceData = {};
        traceData.aTrace = this.getDataTag(tagDict.colorDataA);
        traceData.tTrace = this.getDataTag(tagDict.colorDataT);
        traceData.gTrace = this.getDataTag(tagDict.colorDataG);
        traceData.cTrace = this.getDataTag(tagDict.colorDataC);
        traceData.basePos = this.getDataTag(tagDict.peakLocations);
        traceData.baseCalls = this.getDataTag(tagDict.baseCalls2);
        traceData.qualNums = this.getDataTag(tagDict.qualNums);

        return traceData;
    }

    this.getFirstEntry = function () {

        var output = "";
        for (var curElem = dirLocation; curElem < lastEntry; curElem += 28) {
            var name = "";
            for (var offset = curElem; offset < curElem + 4; offset++) {
                name += String.fromCharCode(inputArrayBuffer.getInt8(offset));
            }
            output += (" - " + name);
        }
        return output;
    }
}

function drawTrace (traceData) {
    console.log("in draw trace");
    var colors = {adenine:"green", thymine:"red", guanine:"black", cytosine:"blue", other:"pink"};
    var peakCanvas = document.getElementById("peakCanvas");
    var ctx = peakCanvas.getContext("2d");

    var formattedPeaks = {a:[], t:[], g:[], c:[]};
    var bottomBuffer = 50;
    var baseBuffer = 35;
    var maxHeight = peakCanvas.height;
    var maxWidth = traceData.basePos[traceData.basePos.length - 1];
    peakCanvas.width = maxWidth;
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, maxWidth, peakCanvas.height);
    var scaledHeight = maxHeight - bottomBuffer;
    var scalePct = 0;

    this.findTallest = function () {
        var aMax = Math.max(...traceData.aTrace);
        var tMax = Math.max(...traceData.tTrace);
        var gMax = Math.max(...traceData.gTrace);
        var cMax = Math.max(...traceData.cTrace);
        scalePct = scaledHeight / Math.max(aMax, tMax, gMax, cMax);
    }

    this.scalePeaks = function (traceIn) {
        var newPeaks = [];
        for (var count = 0; count < traceIn.length; count++) {
            newPeaks[count] = scalePct * traceIn[count];
        }
        return newPeaks;
    }

    this.preparePeaks = function () {
        this.findTallest();
        formattedPeaks.a = this.scalePeaks(traceData.aTrace);
        formattedPeaks.t = this.scalePeaks(traceData.tTrace);
        formattedPeaks.g = this.scalePeaks(traceData.gTrace);
        formattedPeaks.c = this.scalePeaks(traceData.cTrace);
    }

    this.drawPeaks = function(trace, lineColor) {
        ctx.beginPath();
        ctx.moveTo(0, scaledHeight - trace[0])
        for (var counter = 1; counter < trace.length; counter++) {
            ctx.lineTo(counter, scaledHeight - trace[counter]);
            ctx.moveTo(counter, scaledHeight - trace[counter]);
        }
        ctx.strokeStyle = lineColor;
        ctx.stroke();
    }

    this.drawBases = function () {
        console.log("in drawbases");
        //ctx.font = "24px serif";
        var xOffset = -2;
        for (var count = 0; count < traceData.baseCalls.length; count++) {
            var baseCall = traceData.baseCalls[count];
            switch(baseCall) {
                case "A":
                    ctx.fillStyle = colors.adenine;
                    break;
                case "T":
                    ctx.fillStyle = colors.thymine;
                    break;
                case "G":
                    ctx.fillStyle = colors.guanine;
                    break;
                case "C":
                    ctx.fillStyle = colors.cytosine;
                    break;
                default:
                    ctx.fillStyle = colors.other;
            }
            ctx.fillText(baseCall, traceData.basePos[count] + xOffset, maxHeight - baseBuffer);
        }
    }

    this.paintCanvas = function () {
        this.preparePeaks();
        this.drawPeaks(formattedPeaks.a, colors.adenine);
        this.drawPeaks(formattedPeaks.t, colors.thymine);
        this.drawPeaks(formattedPeaks.g, colors.guanine);
        this.drawPeaks(formattedPeaks.c, colors.cytosine);
        this.drawBases();
    }
}

function mottTrim(baseCalls, qualScores) {

    console.log(qualScores);
    var startPos = 0;
    var endPos = 0;
    var tempStart = 0;
    var tempEnd;
    var score = 0;
    var cutoff = 0.01;
    for (var count = 0; count < qualScores.length; count++) {
        //console.log(Math.pow(10,(qualScores[count])/-10));
        score = score + cutoff - Math.pow(10,(qualScores[count])/-10);
        //console.log(score);
        if (score < 0) {
            tempStart = count;
        }
        if (count - tempStart > endPos - startPos) {
            startPos = tempStart;
            endPos = count;
        }
        //console.log(startPos);
    }
    var trimmed = baseCalls.slice(startPos, endPos + 1);
    console.log(trimmed);
}<|endoftext|>


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

    define(
        [
            'page',
            'querystring',
            'util/bind'
        ],
        function (page, qs, bind) {
            var routes, types = [ 'library', 'photographs', 'museum', 'memorials' ];

            routes = function () {
                page('/', function (context) {
                    return bind('ui/pages/static/home', 'ui/pages/static/StaticPage', context);
                });

                page('/about', function (context) {
                    return bind('ui/pages/static/about', 'ui/pages/static/StaticPage', context);
                });

                page('/:type/search', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/search/index', 'ui/pages/search/SearchPage', context);
                });

                page('/:type/detail/:id', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/detail/' + context.params.type, 'ui/pages/detail/DetailPage', context);
                });

                page('*', function (context) {
                    return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                });

                page();
            };

            routes.searchUrlFor = function (type, query) {
                return '/' + type + '/search' + (query ? '?' + qs.stringify(query) : '');
            };

            routes.detailUrlFor = function (type, id) {
                return '/' + type + '/detail/' + id;
            };

            routes.pushState = function (url) {
                return page(url);
            };

            return routes;
        }
    );
}());
<commit_msg>Add uncommitted change to routes config.<commit_after>(function () {
    'use strict';

    define(
        [
            'page',
            'querystring',
            'util/bind'
        ],
        function (page, qs, bind) {
            var routes, types = [ 'library', 'photographs', 'museum', 'memorials' ];

            routes = function () {
                page('/', function (context) {
                    return bind('ui/pages/static/home', 'ui/pages/static/StaticPage', context);
                });

                page('/about', function (context) {
                    return bind('ui/pages/static/about', 'ui/pages/static/StaticPage', context);
                });

                page('/:type/search', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/search/index', 'ui/pages/search/SearchPage', context);
                });

                page('/:type/detail/:id', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/detail/index', 'ui/pages/detail/DetailPage', context);
                });

                page('*', function (context) {
                    return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                });

                page();
            };

            routes.searchUrlFor = function (type, query) {
                return '/' + type + '/search' + (query ? '?' + qs.stringify(query) : '');
            };

            routes.detailUrlFor = function (type, id) {
                return '/' + type + '/detail/' + id;
            };

            routes.pushState = function (url) {
                return page(url);
            };

            return routes;
        }
    );
}());
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

var meta;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        meta = o.meta;
        return this;
    },
    init: function () {
        var base64name, arr, groups, metaData, i, l, count, displayInfo, tooltip;
        groups = [];
        metaData = meta.getMetaDataLatestLoaded();
        for (i = 0; i < metaData.data.length; ++i) {
            groups[i] = metaData.data[i].layergroup;
        }
        arr = array_unique(groups.reverse());
        metaData.data.reverse();
        for (i = 0; i < arr.length; ++i) {
            if (arr[i] && arr[i] !== "[Ungrouped]") {
                l = [];
                base64name = Base64.encode(arr[i]).replace(/=/g, "");

                // Add group container
                // Only if container doesn't exist
                // ===============================
                if ($("#layer-panel-" + base64name).length === 0) {
                    $("#layers").append('

0 /
 ' + arr[i] + '

');

                    // Append to inner group container
                    // ===============================
                    $("#group-" + base64name).append('

');
                }

                // Add layers
                // ==========
                for (var u = 0; u < metaData.data.length; ++u) {
                    if (metaData.data[u].layergroup == arr[i]) {
                        var text = (metaData.data[u].f_table_title === null || metaData.data[u].f_table_title === "") ? metaData.data[u].f_table_name : metaData.data[u].f_table_title;
                        if (metaData.data[u].baselayer) {
                            $("#base-layer-list").append(
                                "

<input type='radio' name='baselayers'>" + text + "

"
                            );
                        }
                        else {
                            displayInfo = ((metaData.data[u].meta !== null && $.parseJSON(metaData.data[u].meta) !== null && typeof $.parseJSON(metaData.data[u].meta).meta_desc !== "undefined" && $.parseJSON(metaData.data[u].meta).meta_desc !== "") || metaData.data[u].f_table_abstract) ? "inline" : "none";
                            tooltip = metaData.data[u].f_table_abstract || "";
                            $("#collapse" + base64name).append('

<input type="checkbox" id="' + metaData.data[u].f_table_name + '" data-gc2-id="' + metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name + '">' + text + 'Info

');
                            l.push({});
                        }
                    }
                }
                if (!isNaN(parseInt($($("#layer-panel-" + base64name + " .layer-count span")[1]).html()))) {
                    count = parseInt($($("#layer-panel-" + base64name + " .layer-count span")[1]).html()) + l.length;
                } else {
                    count = l.length;
                }

                $("#layer-panel-" + base64name + " span:eq(1)").html(count);
                // Remove the group if empty
                if (l.length === 0) {
                    $("#layer-panel-" + base64name).remove();
                }
            }
        }
    }
};<commit_msg>Open the first panel in the layer tree<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

var meta;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        meta = o.meta;
        return this;
    },
    init: function () {
        var base64name, arr, groups, metaData, i, l, count, displayInfo, tooltip;
        groups = [];
        metaData = meta.getMetaDataLatestLoaded();
        for (i = 0; i < metaData.data.length; ++i) {
            groups[i] = metaData.data[i].layergroup;
        }
        arr = array_unique(groups.reverse());
        metaData.data.reverse();
        for (i = 0; i < arr.length; ++i) {
            if (arr[i] && arr[i] !== "[Ungrouped]") {
                l = [];
                base64name = Base64.encode(arr[i]).replace(/=/g, "");

                // Add group container
                // Only if container doesn't exist
                // ===============================
                if ($("#layer-panel-" + base64name).length === 0) {
                    $("#layers").append('

0 /
 ' + arr[i] + '

');

                    // Append to inner group container
                    // ===============================
                    $("#group-" + base64name).append('

');
                }

                // Add layers
                // ==========
                for (var u = 0; u < metaData.data.length; ++u) {
                    if (metaData.data[u].layergroup == arr[i]) {
                        var text = (metaData.data[u].f_table_title === null || metaData.data[u].f_table_title === "") ? metaData.data[u].f_table_name : metaData.data[u].f_table_title;
                        if (metaData.data[u].baselayer) {
                            $("#base-layer-list").append(
                                "

<input type='radio' name='baselayers'>" + text + "

"
                            );
                        }
                        else {
                            displayInfo = ((metaData.data[u].meta !== null && $.parseJSON(metaData.data[u].meta) !== null && typeof $.parseJSON(metaData.data[u].meta).meta_desc !== "undefined" && $.parseJSON(metaData.data[u].meta).meta_desc !== "") || metaData.data[u].f_table_abstract) ? "inline" : "none";
                            tooltip = metaData.data[u].f_table_abstract || "";
                            $("#collapse" + base64name).append('

<input type="checkbox" id="' + metaData.data[u].f_table_name + '" data-gc2-id="' + metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name + '">' + text + 'Info

');
                            l.push({});
                        }
                    }
                }
                if (!isNaN(parseInt($($("#layer-panel-" + base64name + " .layer-count span")[1]).html()))) {
                    count = parseInt($($("#layer-panel-" + base64name + " .layer-count span")[1]).html()) + l.length;
                } else {
                    count = l.length;
                }

                $("#layer-panel-" + base64name + " span:eq(1)").html(count);
                // Remove the group if empty
                if (l.length === 0) {
                    $("#layer-panel-" + base64name).remove();
                }
            }
        }

        // Open the first panel
        // ====================

        $("#layers div:first").find("a").trigger("click");
    }
};<|endoftext|>


<commit_before>var ProjectilePool = require('../common/ProjectilePool');
var Explosion = require('../common/Explosion');
var Beam = require('../common/Beam');

// Define constants
var LAZER_DELAY = 2500; //ms (0.5/sec)

module.exports = {
    create: function(){

        this.background = this.add.sprite(0, 0, 'background');

        this.themeSound = this.game.add.audio('themeSound').play();
        this.themeSound.volume = 0.05;

        this.lastLazerShotAt = 0;

        this.explosion = new Explosion(this.game, 0, 0);

        this.game.physics.startSystem(Phaser.Physics.P2JS);
        this.game.physics.p2.setImpactEvents(true);
        this.bulletCollisionGroup = game.physics.p2.createCollisionGroup();
        this.beamCollisionGroup = game.physics.p2.createCollisionGroup();
        //this.game.physics.p2.updateBoundsCollisionGroup();
        this.bulletPool = new ProjectilePool(this.game, this.bulletCollisionGroup, [this.bulletCollisionGroup, this.beamCollisionGroup]);
        this.bulletPool2 = new ProjectilePool(this.game, this.bulletCollisionGroup, [this.bulletCollisionGroup, this.beamCollisionGroup]);

        this.beam = this.add.existing(new Beam(this.game, this.beamCollisionGroup, this.bulletCollisionGroup));
        this.beam.body.collides(this.bulletCollisionGroup, function(obj1, obj2){
            // Create an explosion
            this.explosion.boom(obj2.x, obj2.y);

            // Kill the bullet
            obj2.sprite.kill();
        }, this);

        this._barbarian = this.add.sprite(300, 300, 'barbarian');
        this._barbarian.anchor.set(0.5, 0.5);

        this._barbarian.animations.add('walk', [0, 1, 2, 3, 4, 5, 6, 7, 8]);
        this._barbarian.animations.add('run', [11, 12, 13, 14, 15, 16, 17, 18]);
        this._barbarian.animations.add('attack', [19, 20, 21]);

        this.game.physics.arcade.enable(this._barbarian);

        this._cursors = this.game.input.keyboard.createCursorKeys();
        this._shift = this.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);

        this._isAttacking = 0;
    },
    update: function(){

        // Shoot a bullet
        if (this.game.input.activePointer.isDown) {
            if (!this._isAttacking) {
                //others have magic mike
                //we have magic numbers
                this._isAttacking = 15;
            }
        }
        // Check if bullets have collided
 /*       this.game.physics.arcade.collide(this.bulletPool.bulletPool, this.bulletPool2.bulletPool, function(bullet, bullet2) {
            // Create an explosion
            this.explosion.boom(bullet.x, bullet.y);

            // Kill the bullet
            bullet.kill();
            bullet2.kill();
        }, null, this);

        // Check if bullets have collided with beams
        this.game.physics.arcade.collide(this.bulletPool2.bulletPool, this.beam, function(beam, bullet) {
            // Create an explosion
            this.explosion.boom(bullet.x, bullet.y);

            // Kill the bullet
            bullet.kill();
        }, null, this);
*/

        this._barbarian.body.velocity.x = 0;
        this._barbarian.body.velocity.y = 0;

        if (this._isAttacking) {
            //others have magic mike
            //we have magic numbers
            this._barbarian.animations.play('attack', 10);
        } else if (this._cursors.left.isDown || this._cursors.right.isDown || this._cursors.up.isDown || this._cursors.down.isDown) {
            this._barbarian.animations.play(this._shift.isDown ? 'run' : 'walk', 30, true);
        } else {
            this._barbarian.animations.stop('walk');
            this._barbarian.animations.stop('run');
            this._barbarian.frame = 0;
        }

        if (this._isAttacking && this._isAttacking--) {
            //others have magic mike
            //we have magic numbers
            if (this._isAttacking === 8) {
                //this.bulletPool.shoot(this._barbarian.x + 60, this._barbarian.y - 15);
                this.bulletPool2.shoot(600, 600);
            }

            if (this.game.time.now - this.lastLazerShotAt > LAZER_DELAY) {
                this.lastLazerShotAt = this.game.time.now;
                this.beam.shoot(this._barbarian.x, this._barbarian.y);
            }
        }

        var speedModifier = this._shift.isDown ? 2 : 1;

        if (this._cursors.left.isDown) {
            this._barbarian.body.velocity.x = speedModifier * -200;
        } else if (this._cursors.right.isDown) {
            this._barbarian.body.velocity.x = speedModifier * 200;
        }

        if (this._cursors.up.isDown) {
            this._barbarian.body.velocity.y = speedModifier * -200;
        } else if (this._cursors.down.isDown) {
            this._barbarian.body.velocity.y = speedModifier * 200;
        }
    }
};<commit_msg>loop?<commit_after>var ProjectilePool = require('../common/ProjectilePool');
var Explosion = require('../common/Explosion');
var Beam = require('../common/Beam');

// Define constants
var LAZER_DELAY = 2500; //ms (0.5/sec)

module.exports = {
    create: function(){

        this.background = this.add.sprite(0, 0, 'background');

        this.themeSound = this.game.add.audio('themeSound').play();
        this.themeSound.loop = true;
        this.themeSound.volume = 0.05;

        this.lastLazerShotAt = 0;

        this.explosion = new Explosion(this.game, 0, 0);

        this.game.physics.startSystem(Phaser.Physics.P2JS);
        this.game.physics.p2.setImpactEvents(true);
        this.bulletCollisionGroup = game.physics.p2.createCollisionGroup();
        this.beamCollisionGroup = game.physics.p2.createCollisionGroup();
        //this.game.physics.p2.updateBoundsCollisionGroup();
        this.bulletPool = new ProjectilePool(this.game, this.bulletCollisionGroup, [this.bulletCollisionGroup, this.beamCollisionGroup]);
        this.bulletPool2 = new ProjectilePool(this.game, this.bulletCollisionGroup, [this.bulletCollisionGroup, this.beamCollisionGroup]);

        this.beam = this.add.existing(new Beam(this.game, this.beamCollisionGroup, this.bulletCollisionGroup));
        this.beam.body.collides(this.bulletCollisionGroup, function(obj1, obj2){
            // Create an explosion
            this.explosion.boom(obj2.x, obj2.y);

            // Kill the bullet
            obj2.sprite.kill();
        }, this);

        this._barbarian = this.add.sprite(300, 300, 'barbarian');
        this._barbarian.anchor.set(0.5, 0.5);

        this._barbarian.animations.add('walk', [0, 1, 2, 3, 4, 5, 6, 7, 8]);
        this._barbarian.animations.add('run', [11, 12, 13, 14, 15, 16, 17, 18]);
        this._barbarian.animations.add('attack', [19, 20, 21]);

        this.game.physics.arcade.enable(this._barbarian);

        this._cursors = this.game.input.keyboard.createCursorKeys();
        this._shift = this.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);

        this._isAttacking = 0;
    },
    update: function(){

        // Shoot a bullet
        if (this.game.input.activePointer.isDown) {
            if (!this._isAttacking) {
                //others have magic mike
                //we have magic numbers
                this._isAttacking = 15;
            }
        }
        // Check if bullets have collided
 /*       this.game.physics.arcade.collide(this.bulletPool.bulletPool, this.bulletPool2.bulletPool, function(bullet, bullet2) {
            // Create an explosion
            this.explosion.boom(bullet.x, bullet.y);

            // Kill the bullet
            bullet.kill();
            bullet2.kill();
        }, null, this);

        // Check if bullets have collided with beams
        this.game.physics.arcade.collide(this.bulletPool2.bulletPool, this.beam, function(beam, bullet) {
            // Create an explosion
            this.explosion.boom(bullet.x, bullet.y);

            // Kill the bullet
            bullet.kill();
        }, null, this);
*/

        this._barbarian.body.velocity.x = 0;
        this._barbarian.body.velocity.y = 0;

        if (this._isAttacking) {
            //others have magic mike
            //we have magic numbers
            this._barbarian.animations.play('attack', 10);
        } else if (this._cursors.left.isDown || this._cursors.right.isDown || this._cursors.up.isDown || this._cursors.down.isDown) {
            this._barbarian.animations.play(this._shift.isDown ? 'run' : 'walk', 30, true);
        } else {
            this._barbarian.animations.stop('walk');
            this._barbarian.animations.stop('run');
            this._barbarian.frame = 0;
        }

        if (this._isAttacking && this._isAttacking--) {
            //others have magic mike
            //we have magic numbers
            if (this._isAttacking === 8) {
                //this.bulletPool.shoot(this._barbarian.x + 60, this._barbarian.y - 15);
                this.bulletPool2.shoot(600, 600);
            }

            if (this.game.time.now - this.lastLazerShotAt > LAZER_DELAY) {
                this.lastLazerShotAt = this.game.time.now;
                this.beam.shoot(this._barbarian.x, this._barbarian.y);
            }
        }

        var speedModifier = this._shift.isDown ? 2 : 1;

        if (this._cursors.left.isDown) {
            this._barbarian.body.velocity.x = speedModifier * -200;
        } else if (this._cursors.right.isDown) {
            this._barbarian.body.velocity.x = speedModifier * 200;
        }

        if (this._cursors.up.isDown) {
            this._barbarian.body.velocity.y = speedModifier * -200;
        } else if (this._cursors.down.isDown) {
            this._barbarian.body.velocity.y = speedModifier * 200;
        }
    }
};<|endoftext|>


<commit_before>import { getWrapper } from '../shared';
import NavigationBar from '../../src/components/NavigationBar';
import SettingsPanel from '../../src/components/SettingsPanel';
import CallingSettings from '../../src/components/CallingSettingsPanel';
import LinkLine from '../../src/components/LinkLine';
import Button from '../../src/components/Button';

let wrapper = null;
let panel = null;
let callingSettings = null;
beforeEach(async () => {
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 32000;
  wrapper = await getWrapper();
  const navigationBar = wrapper.find(NavigationBar).first();
  await navigationBar.props().goTo('/settings');
  panel = wrapper.find(SettingsPanel).first();
  const callingLinkLine = panel.find(LinkLine).at(0);
  await callingLinkLine.props().onClick();
  callingSettings = wrapper.find(CallingSettings).first();
});

describe('calling settings', () => {
  test('initial state', async () => {
    expect(callingSettings.find('div.label').first().props().children).toEqual('Calling');
  });

  test('button state', async () => {
    const saveButton = callingSettings.find(Button).first();
    expect(saveButton.props().disabled).toEqual(true);

    const items = callingSettings.find('.dropdownItem');
    const lastItem = items.at(items.length - 1);
    await lastItem.simulate('click');
    expect(saveButton.props().disabled).toEqual(false);
  });
});
<commit_msg>Test saving calling settings<commit_after>import { getWrapper } from '../shared';
import NavigationBar from '../../src/components/NavigationBar';
import SettingsPanel from '../../src/components/SettingsPanel';
import CallingSettings from '../../src/components/CallingSettingsPanel';
import LinkLine from '../../src/components/LinkLine';
import Button from '../../src/components/Button';

let wrapper = null;
let panel = null;
let callingSettings = null;
let store = null;
beforeEach(async () => {
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 32000;
  wrapper = await getWrapper();
  store = wrapper.props().phone.store;
  const navigationBar = wrapper.find(NavigationBar).first();
  await navigationBar.props().goTo('/settings');
  panel = wrapper.find(SettingsPanel).first();
  const callingLinkLine = panel.find(LinkLine).at(0);
  await callingLinkLine.props().onClick();
  callingSettings = wrapper.find(CallingSettings).first();
});

describe('calling settings', () => {
  test('initial state', async () => {
    expect(callingSettings.find('div.label').first().props().children).toEqual('Calling');
  });

  test('button state', async () => {
    const saveButton = callingSettings.find(Button).first();
    expect(saveButton.props().disabled).toEqual(true);

    const items = callingSettings.find('.dropdownItem');
    const lastItem = items.at(items.length - 1);
    await lastItem.simulate('click');
    expect(saveButton.props().disabled).toEqual(false);
  });

  test('save', async () => {
    const saveButton = callingSettings.find(Button).first();

    const items = callingSettings.find('.dropdownItem');
    const lastItem = items.at(items.length - 1);
    await lastItem.simulate('click');
    await saveButton.props().onClick();

    const messages = store.getState(wrapper).alert.messages;
    expect(messages.length).toEqual(1);
    const message = messages[0];
    expect(message.level).toEqual('info');
    expect(message.message).toMatch(/saveSuccess/);
  });
});
<|endoftext|>


<commit_before>var butter=function(n){function r(){var r=u();n("body").trigger("purposeResponse",[r.verb,l(r.tags)])}function o(){n(".purpose").on("click",r)}function t(n,r){return Math.floor(Math.random()*(r-n+1))+n}function e(){var n=t(0,i.length-1);return n==c&&(n=e()),c=n,n}function u(){var n="pass";return null!==i&&(n=i[e()]),n}function l(n){var r="butter";if(null!==f)if(0===n.forbid.length){var o=t(0,f.global.words.length-1);r=f.global.words[o]}else{var e=clone(f);n.forbid.forEach(function(n){delete e[n]});var u,l=0;for(var a in e)Math.random()<1/++l&&(u=a);r=u.words[t(0,u.words.length-1)]}return r}function a(){n.getJSON("build/words.compiled.json",function(n){i=n.verbs,f=n.tags})}var i=null,f=null,c=null;!function(){n(document).ready(o),a()}()}(jQuery);
var chatbox=function(o){function n(o,n,t){i("butterbot","what is my purpose?"),i("bigrick69","you "+n+" "+t+"."),r.scrollTop(r.prop("scrollHeight"))}function i(o,n){r.append('
'+o+": "+n+"
")}function t(){r=o("#history"),o("body").on("purposeResponse",n)}var r;!function(){o(document).ready(t)}()}(jQuery);
var interjections=function(n){}(jQuery);
//# sourceMappingURL=app.js.map
<commit_msg>Update app.js<commit_after>var butter=function(n){function r(){var r=u();n("body").trigger("purposeResponse",[r.verb,l(r.tags)])}function o(){n(".purpose").on("click",r)}function t(n,r){return Math.floor(Math.random()*(r-n+1))+n}function e(){var n=t(0,i.length-1);return n==c&&(n=e()),c=n,n}function u(){var n="pass";return null!==i&&(n=i[e()]),n}function l(n){var r="butter";if(null!==f)if(0===n.forbid.length){var o=t(0,f.global.words.length-1);r=f.global.words[o]}else{var e=clone(f);n.forbid.forEach(function(n){delete e[n]});var u,l=0;for(var a in e)Math.random()<1/++l&&(u=a);r=u.words[t(0,u.words.length-1)]}return r}function a(){n.getJSON("build/words.compiled.json",function(n){i=n.verbs,f=n.tags})}var i=null,f=null,c=null;!function(){n(document).ready(o),a()}()}(jQuery);
var chatbox=function(o){function n(o,n,t){i("butterbot","what is my purpose?"),i("rickest","you "+n+" "+t+"."),r.scrollTop(r.prop("scrollHeight"))}function i(o,n){r.append('
'+o+": "+n+"
")}function t(){r=o("#history"),o("body").on("purposeResponse",n)}var r;!function(){o(document).ready(t)}()}(jQuery);
var interjections=function(n){}(jQuery);
//# sourceMappingURL=app.js.map
<|endoftext|>