<commit_before>
// Express - Request - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

/**
 * Module dependencies.
 */

var Event = require('express/event').Event,
    showExceptions = require('express/pages/show-exceptions'),
    notFound = require('express/pages/not-found'),
    statusBodies = require('http').STATUS_CODES,
    queryString = require('querystring'),
    mime = require('express/mime'),
    url = require('url'),
    ext = require('ext')

// --- Helpers

/**
 * Normalize the given _path_.
 * Strips trailing slashes and whitespace.
 *
 * @param  {string} path
 * @return {string}
 * @api public
 */

exports.normalizePath = function(path) {
  return path.replace(/[\s\/]*$/g, '')
}

// --- Request

exports.Request = new Class({

  /**
   * Initialize with node's _request_ and _response_ objects.
   *
   *  - Defaults headers to {}
   *  - Parses request url
   *  - Normalizes url pathname
   *  - Parses GET params when available
   *  - Initializes plugins
   *
   * @param  {object} request
   * @param  {object} response
   * @api private
   */

  constructor: function(request, response) {
    Object.merge(this, request)
    response.headers = {}
    this.response = response
    this.url = url.parse(this.url)
    this.url.pathname = exports.normalizePath(this.url.pathname)
    this.params = {}
    this.params.path = {}
    this.params.get = this.url.query ? queryString.parseQuery(this.url.query) : {}
    this.params.post = this.params.post || {}
    this.plugins = Express.plugins.map(function(plugin){
      return new plugin.klass(plugin.options)
    })
  },

  /**
   * Set response header _key_ and _val_ or get
   * request header value by _key_.
   *
   * @param  {string} key
   * @param  {string} val
   * @return {string}
   * @api public
   */

  header: function(key, val) {
    return val === undefined
      ? this.headers[key.lowercase]
      : this.response.headers[key] = val
  },

  /**
   * Return the param _key_ value or undefined.
   *
   *  - Checks GET parameters
   *  - Checks POST parameters
   *  - Checks route populated path parameters
   *
   * @param  {string} key
   * @return {string}
   * @api public
   */

  param: function(key) {
    if (key in this.params.get)
      return this.params.get[key]
    if (key in this.params.post)
      return this.params.post[key]
    if (key in this.params.path)
      return this.params.path[key]
  },

  /**
   * Check if Accept header includes the mime type
   * for any of the given paths, which calls mime.type().
   *
   * When no Accept header is present true will be
   * returned as stated in the HTTP specification.
   *
   * Example:
   *
   *   this.accepts('png')
   *   this.accepts('png', 'jpg', 'gif')
   *   this.accepts('image.png')
   *   this.accepts('path/to/image.png')
   *
   * @param  {mixed} ...
   * @return {bool}
   * @api public
   */

  accepts: function() {
    var accept = this.header('accept')
    if (!accept || accept === '*/*') return true
    return arguments.any(function(path){
      var type = mime.type(path)
      return accept.indexOf(type) !== -1 ||
             accept.indexOf(type.split('/')[0] + '/*') !== -1
    })
  },

  /**
   * Check if the request was an xmlHttpRequest (ajax).
   *
   * @return {bool}
   * @api public
   */

  get isXHR() {
    return (this.header('X-Requested-With') || '').lowercase === 'xmlhttprequest'
  },

  /**
   * Set response status to _code_.
   *
   * @param  {int} code
   * @return {Request}
   * @api public
   */

  status: function(code) {
    this.response.status = code
    return this
  },

  /**
   * Respond with response _code_, and optional _body_.
   *
   * The status _code_ defaults to to 404, and _body_ will
   * default to the default body associated with the response
   * _code_.
   *
   * Examples:
   *
   *    request.respond()
   *    // 404 "Not Found"
   *
   *    request.respond(500)
   *    // 500 "Internal Server Error"
   *
   *    request.respond(200, "im ok")
   *    // 200 "im ok"
   *
   *    request.respond(200, "√ woot", "utf8")
   *    // "utf8" will set Request#charset to 'UTF-8'
   *
   * @param  {int} code
   * @param  {string} body
   * @param  {string} encoding
   * @see statusBodies
   * @api public
   */

  respond: function(code, body, encoding) {
    var self = this
    this.status(code = code || 404)
    if (body !== null)
      body = body || statusBodies[code]
    if (encoding === 'utf8' ||
        encoding === 'utf-8')
      this.charset = 'UTF-8'
    this.response.body = body
    this.trigger('response', function(err) {
      if (err) return self.error(err)
      self.sendHead()
      if (body) self.response.write(self.response.body, encoding)
      self.response.end()
    }, true)
  },

  // >>> DEPRECATED: remove in 1.0

  halt: function(){
    ext.warn('Request#halt() has been renamed Request#respond()')
    this.respond.apply(this, arguments)
  },

  // <<< DEPRECATED

  /**
   * Transfer the given _stream_ with optional _callback_.
   *
   * @param  {Stream} stream
   * @param  {function} callback
   * @return {Request}
   * @api public
   */

  stream: function(stream, callback) {
    var self = this,
        first = true
    stream
      .addListener('error', function(err){
        if (first)
          return self.error(err, callback)
        stream.destroy()
        self.response.end()
      })
      .addListener('data', function(data){
        if (first) {
          first = false
          self.header('Transfer-Encoding', 'chunked')
          self.status(200)
          self.contentType(stream.path)
          self.sendHead()
        }
        self.response.write(data, 'binary')
      })
      .addListener('end', function(){
        self.trigger('response', function(err){
          if (err)
            return self.error(err, callback)
          self.response.end()
        }, true)
      })
  },

  /**
   * Send the response header.
   *
   * If Request#charset is defined, and the
   * "Content-Type" header, then "; charset=CHARSET" is
   * appended.
   *
   * @return {Request}
   * @api public
   */

  sendHead: function(){
    if (this.charset && this.response.headers['Content-Type'])
      this.response.headers['Content-Type'] += '; charset=' + this.charset
    this.response.writeHead(this.response.status, this.response.headers)
    return this
  },

  /**
   * Pass control to the next matching route, or
   * the given _path_.
   *
   * NOTE: _path_ may be the request pathname only,
   * and may not contain a query string etc.
   *
   * @param {string} path
   * @api public
   */

  pass: function(path) {
    this.passed = path || true
    return this
  },

  /**
   * Set Content-Type header to the mime type
   * for the given _path_, which calls mime.type().
   *
   * @param  {string} path
   * @return {Request}
   * @api public
   */

  contentType: function(path) {
    this.header('Content-Type', mime.type(path))
    return this
  },

  /**
   * Trigger event _name_ with optional _data_ and _callback_ function.
   * The _callback_ function may be the second or third argument.
   *
   * @param  {string} name
   * @param  {object} data
   * @param  {function} callback
   * @param  {bool} reverse
   * @return {Request}
   * @api public
   */

  trigger: function(name, data, callback, reverse) {
    if (data instanceof Function)
      reverse = callback,
      callback = data,
      data = null
    data = Object.merge({ request: this, response: this.response }, data)
    // TODO: no need to reverse plugins every time....
    var self = this,
        complete = 0,
        total = this.plugins.length,
        plugins = reverse
          ? self.plugins.reverse()
          : self.plugins
    ;(function next(err) {
      if (err || complete === total)
        callback(err)
      else {
        if (plugins.at(complete++).trigger(new Event(name, data), next) !== true)
          next()
      }
    })()
    return this
  },

  /**
   * Set Content-Disposition header to 'attachment',
   * with optional file _filename_.
   *
   * @param  {string} filename
   * @return {Request}
   * @api public
   */

  attachment: function(filename) {
    this.header('Content-Disposition', filename
      ? 'attachment; filename="' + filename + '"'
      : 'attachment')
    return this
  },

  /**
   * Handle exceptions.
   *
   * When an error route is defined via the DSL it
   * will then be called regardless of any setting that
   * may be present. ("throw exceptions" will still work)
   *
   *   error(function(err){
   *     this.respond(500, 'your app sucks!')
   *   })
   *
   * When "show exceptions" is enabled the show-exceptions page will be shown for "text/html",
   * a plain-text representation of the error for "text/plain" and JSON for "application/json".
   * Otherwise the request will halt with default 500 status body.
   *
   * When "throw exceptions" is enabled the error will be
   * re-thrown, terminating the process (unless otherwise caught).
   *
   * Also a _callback_ function may be supplied, which when defined
   * will be called, by-passing the process mentioned above.
   *
   * @param  {Error} err
   * @param  {function} callback
   * @return {Request}
   * @settings 'throw exceptions', 'show exceptions'
   * @api public
   */

  error: function(err, callback) {
    if (callback)
      return callback(err)
    if (Express.error)
      Express.error.call(this, err)
    else if (set('show exceptions'))
      if (this.accepts('html'))
        this.respond(500, showExceptions.render(this, err))
      else if (this.accepts('json'))
        this.respond(500, showExceptions.renderJSON(this, err))
      else if (this.accepts('text'))
        this.respond(500, showExceptions.renderText(this, err))
      else
        this.respond(500)
    else
      this.respond(500)
    if (set('throw exceptions'))
      throw err
    return this
  },

  /**
   * Halt with 404 Not Found.
   *
   * When a notFound route is defined via the DSL it
   * will then be called regardless of any settings that
   * may be present.
   *
   *   notFound(function(){
   *     this.respond(404, 'Sorry your page cannot be found')
   *   })
   *
   * When "html" is accepted, and "helpful 404" is enabled
   * the not-found page will be shown, otherwise  the
   * request will halt with default 404 status body.
   *
   * @return {Request}
   * @api public
   */

  notFound: function() {
    if (Express.notFound)
      Express.notFound.call(this)
    else if (this.accepts('html') && set('helpful 404'))
      this.respond(404, notFound.render(this))
    else
      this.respond()
    return this
  }
})<commit_msg>Request#accepts() fixed due to ext changes<commit_after>
// Express - Request - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

/**
 * Module dependencies.
 */

var Event = require('express/event').Event,
    showExceptions = require('express/pages/show-exceptions'),
    notFound = require('express/pages/not-found'),
    statusBodies = require('http').STATUS_CODES,
    queryString = require('querystring'),
    mime = require('express/mime'),
    url = require('url'),
    ext = require('ext')

// --- Helpers

/**
 * Normalize the given _path_.
 * Strips trailing slashes and whitespace.
 *
 * @param  {string} path
 * @return {string}
 * @api public
 */

exports.normalizePath = function(path) {
  return path.replace(/[\s\/]*$/g, '')
}

// --- Request

exports.Request = new Class({

  /**
   * Initialize with node's _request_ and _response_ objects.
   *
   *  - Defaults headers to {}
   *  - Parses request url
   *  - Normalizes url pathname
   *  - Parses GET params when available
   *  - Initializes plugins
   *
   * @param  {object} request
   * @param  {object} response
   * @api private
   */

  constructor: function(request, response) {
    Object.merge(this, request)
    response.headers = {}
    this.response = response
    this.url = url.parse(this.url)
    this.url.pathname = exports.normalizePath(this.url.pathname)
    this.params = {}
    this.params.path = {}
    this.params.get = this.url.query ? queryString.parseQuery(this.url.query) : {}
    this.params.post = this.params.post || {}
    this.plugins = Express.plugins.map(function(plugin){
      return new plugin.klass(plugin.options)
    })
  },

  /**
   * Set response header _key_ and _val_ or get
   * request header value by _key_.
   *
   * @param  {string} key
   * @param  {string} val
   * @return {string}
   * @api public
   */

  header: function(key, val) {
    return val === undefined
      ? this.headers[key.lowercase]
      : this.response.headers[key] = val
  },

  /**
   * Return the param _key_ value or undefined.
   *
   *  - Checks GET parameters
   *  - Checks POST parameters
   *  - Checks route populated path parameters
   *
   * @param  {string} key
   * @return {string}
   * @api public
   */

  param: function(key) {
    if (key in this.params.get)
      return this.params.get[key]
    if (key in this.params.post)
      return this.params.post[key]
    if (key in this.params.path)
      return this.params.path[key]
  },

  /**
   * Check if Accept header includes the mime type
   * for any of the given paths, which calls mime.type().
   *
   * When no Accept header is present true will be
   * returned as stated in the HTTP specification.
   *
   * Example:
   *
   *   this.accepts('png')
   *   this.accepts('png', 'jpg', 'gif')
   *   this.accepts('image.png')
   *   this.accepts('path/to/image.png')
   *
   * @param  {mixed} ...
   * @return {bool}
   * @api public
   */

  accepts: function() {
    var accept = this.header('accept')
    if (!accept || accept === '*/*') return true
    return Object.values(arguments).any(function(path){
      var type = mime.type(path)
      return accept.indexOf(type) !== -1 ||
             accept.indexOf(type.split('/')[0] + '/*') !== -1
    })
  },

  /**
   * Check if the request was an xmlHttpRequest (ajax).
   *
   * @return {bool}
   * @api public
   */

  get isXHR() {
    return (this.header('X-Requested-With') || '').lowercase === 'xmlhttprequest'
  },

  /**
   * Set response status to _code_.
   *
   * @param  {int} code
   * @return {Request}
   * @api public
   */

  status: function(code) {
    this.response.status = code
    return this
  },

  /**
   * Respond with response _code_, and optional _body_.
   *
   * The status _code_ defaults to to 404, and _body_ will
   * default to the default body associated with the response
   * _code_.
   *
   * Examples:
   *
   *    request.respond()
   *    // 404 "Not Found"
   *
   *    request.respond(500)
   *    // 500 "Internal Server Error"
   *
   *    request.respond(200, "im ok")
   *    // 200 "im ok"
   *
   *    request.respond(200, "√ woot", "utf8")
   *    // "utf8" will set Request#charset to 'UTF-8'
   *
   * @param  {int} code
   * @param  {string} body
   * @param  {string} encoding
   * @see statusBodies
   * @api public
   */

  respond: function(code, body, encoding) {
    var self = this
    this.status(code = code || 404)
    if (body !== null)
      body = body || statusBodies[code]
    if (encoding === 'utf8' ||
        encoding === 'utf-8')
      this.charset = 'UTF-8'
    this.response.body = body
    this.trigger('response', function(err) {
      if (err) return self.error(err)
      self.sendHead()
      if (body) self.response.write(self.response.body, encoding)
      self.response.end()
    }, true)
  },

  // >>> DEPRECATED: remove in 1.0

  halt: function(){
    ext.warn('Request#halt() has been renamed Request#respond()')
    this.respond.apply(this, arguments)
  },

  // <<< DEPRECATED

  /**
   * Transfer the given _stream_ with optional _callback_.
   *
   * @param  {Stream} stream
   * @param  {function} callback
   * @return {Request}
   * @api public
   */

  stream: function(stream, callback) {
    var self = this,
        first = true
    stream
      .addListener('error', function(err){
        if (first)
          return self.error(err, callback)
        stream.destroy()
        self.response.end()
      })
      .addListener('data', function(data){
        if (first) {
          first = false
          self.header('Transfer-Encoding', 'chunked')
          self.status(200)
          self.contentType(stream.path)
          self.sendHead()
        }
        self.response.write(data, 'binary')
      })
      .addListener('end', function(){
        self.trigger('response', function(err){
          if (err)
            return self.error(err, callback)
          self.response.end()
        }, true)
      })
  },

  /**
   * Send the response header.
   *
   * If Request#charset is defined, and the
   * "Content-Type" header, then "; charset=CHARSET" is
   * appended.
   *
   * @return {Request}
   * @api public
   */

  sendHead: function(){
    if (this.charset && this.response.headers['Content-Type'])
      this.response.headers['Content-Type'] += '; charset=' + this.charset
    this.response.writeHead(this.response.status, this.response.headers)
    return this
  },

  /**
   * Pass control to the next matching route, or
   * the given _path_.
   *
   * NOTE: _path_ may be the request pathname only,
   * and may not contain a query string etc.
   *
   * @param {string} path
   * @api public
   */

  pass: function(path) {
    this.passed = path || true
    return this
  },

  /**
   * Set Content-Type header to the mime type
   * for the given _path_, which calls mime.type().
   *
   * @param  {string} path
   * @return {Request}
   * @api public
   */

  contentType: function(path) {
    this.header('Content-Type', mime.type(path))
    return this
  },

  /**
   * Trigger event _name_ with optional _data_ and _callback_ function.
   * The _callback_ function may be the second or third argument.
   *
   * @param  {string} name
   * @param  {object} data
   * @param  {function} callback
   * @param  {bool} reverse
   * @return {Request}
   * @api public
   */

  trigger: function(name, data, callback, reverse) {
    if (data instanceof Function)
      reverse = callback,
      callback = data,
      data = null
    data = Object.merge({ request: this, response: this.response }, data)
    // TODO: no need to reverse plugins every time....
    var self = this,
        complete = 0,
        total = this.plugins.length,
        plugins = reverse
          ? self.plugins.reverse()
          : self.plugins
    ;(function next(err) {
      if (err || complete === total)
        callback(err)
      else {
        if (plugins.at(complete++).trigger(new Event(name, data), next) !== true)
          next()
      }
    })()
    return this
  },

  /**
   * Set Content-Disposition header to 'attachment',
   * with optional file _filename_.
   *
   * @param  {string} filename
   * @return {Request}
   * @api public
   */

  attachment: function(filename) {
    this.header('Content-Disposition', filename
      ? 'attachment; filename="' + filename + '"'
      : 'attachment')
    return this
  },

  /**
   * Handle exceptions.
   *
   * When an error route is defined via the DSL it
   * will then be called regardless of any setting that
   * may be present. ("throw exceptions" will still work)
   *
   *   error(function(err){
   *     this.respond(500, 'your app sucks!')
   *   })
   *
   * When "show exceptions" is enabled the show-exceptions page will be shown for "text/html",
   * a plain-text representation of the error for "text/plain" and JSON for "application/json".
   * Otherwise the request will halt with default 500 status body.
   *
   * When "throw exceptions" is enabled the error will be
   * re-thrown, terminating the process (unless otherwise caught).
   *
   * Also a _callback_ function may be supplied, which when defined
   * will be called, by-passing the process mentioned above.
   *
   * @param  {Error} err
   * @param  {function} callback
   * @return {Request}
   * @settings 'throw exceptions', 'show exceptions'
   * @api public
   */

  error: function(err, callback) {
    if (callback)
      return callback(err)
    if (Express.error)
      Express.error.call(this, err)
    else if (set('show exceptions'))
      if (this.accepts('html'))
        this.respond(500, showExceptions.render(this, err))
      else if (this.accepts('json'))
        this.respond(500, showExceptions.renderJSON(this, err))
      else if (this.accepts('text'))
        this.respond(500, showExceptions.renderText(this, err))
      else
        this.respond(500)
    else
      this.respond(500)
    if (set('throw exceptions'))
      throw err
    return this
  },

  /**
   * Halt with 404 Not Found.
   *
   * When a notFound route is defined via the DSL it
   * will then be called regardless of any settings that
   * may be present.
   *
   *   notFound(function(){
   *     this.respond(404, 'Sorry your page cannot be found')
   *   })
   *
   * When "html" is accepted, and "helpful 404" is enabled
   * the not-found page will be shown, otherwise  the
   * request will halt with default 404 status body.
   *
   * @return {Request}
   * @api public
   */

  notFound: function() {
    if (Express.notFound)
      Express.notFound.call(this)
    else if (this.accepts('html') && set('helpful 404'))
      this.respond(404, notFound.render(this))
    else
      this.respond()
    return this
  }
})<|endoftext|>


<commit_before>/* Copyright (c) 2006 MetaCarta, Inc., published under a modified BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/repository-license.txt
 * for the full text of the license. */

/**
 * @class
 *
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Control/MouseDefaults.js
 */
OpenLayers.Control.MouseToolbar = OpenLayers.Class.create();
OpenLayers.Control.MouseToolbar.X = 6;
OpenLayers.Control.MouseToolbar.Y = 300;
OpenLayers.Control.MouseToolbar.prototype =
  OpenLayers.Class.inherit( OpenLayers.Control.MouseDefaults, {

    /** WARNING WARNING WARNING!!!
        This class is DEPRECATED in 2.4 and will be removed by 3.0.
        If you need this functionality, use Control.NavToolbar instead!!! */

    mode: null,

    buttons: null,

    direction: "vertical",

    /** @type String */
    buttonClicked: null,

    initialize: function(position, direction) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.position = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,
                                             OpenLayers.Control.MouseToolbar.Y);
        if (position) {
            this.position = position;
        }
        if (direction) {
            this.direction = direction;
        }
        this.measureDivs = [];
    },

    /**
     *
     */
    destroy: function() {
        for( var btnId in this.buttons) {
            var btn = this.buttons[btnId];
            btn.map = null;
            btn.events.destroy();
        }
        OpenLayers.Control.MouseDefaults.prototype.destroy.apply(this,
                                                                 arguments);
    },

    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);
        OpenLayers.Control.MouseDefaults.prototype.draw.apply(this, arguments);
        this.buttons = new Object();
        var sz = new OpenLayers.Size(28,28);
        var centered = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,0);
        this._addButton("zoombox", "drag-rectangle-off.png", "drag-rectangle-on.png", centered, sz, "Shift->Drag to zoom to area");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this._addButton("pan", "panning-hand-off.png", "panning-hand-on.png", centered, sz, "Drag the map to pan.");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this.switchModeTo("pan");

        this.registerWheelEvents();

        return this.div;
    },

    _addButton:function(id, img, activeImg, xy, sz, title) {
        var imgLocation = OpenLayers.Util.getImagesLocation() + img;
        var activeImgLocation = OpenLayers.Util.getImagesLocation() + activeImg;
        // var btn = new ol.AlphaImage("_"+id, imgLocation, xy, sz);
        var btn = OpenLayers.Util.createAlphaImageDiv(
                                    "OpenLayers_Control_MouseToolbar_" + id,
                                    xy, sz, imgLocation, "absolute");

        //we want to add the outer div
        this.div.appendChild(btn);
        btn.imgLocation = imgLocation;
        btn.activeImgLocation = activeImgLocation;

        btn.events = new OpenLayers.Events(this, btn, null, true);
        btn.events.register("mousedown", this, this.buttonDown);
        btn.events.register("mouseup", this, this.buttonUp);
        btn.events.register("dblclick", this, OpenLayers.Event.stop);
        btn.action = id;
        btn.title = title;
        btn.alt = title;
        btn.map = this.map;

        //we want to remember/reference the outer div
        this.buttons[id] = btn;
        return btn;
    },

    /**
     * @param {Event} evt
     */
    buttonDown: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.buttonClicked = evt.element.action;
        OpenLayers.Event.stop(evt);
    },

    /**
     * @param {Event} evt
     */
    buttonUp: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        if (this.buttonClicked != null) {
            if (this.buttonClicked == evt.element.action) {
                this.switchModeTo(evt.element.action);
            }
            OpenLayers.Event.stop(evt);
            this.buttonClicked = null;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultDblClick: function (evt) {
        this.switchModeTo("pan");
        this.performedDrag = false;
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
        OpenLayers.Event.stop(evt);
        return false;
    },

    /**
    * @param {Event} evt
    */
    defaultMouseDown: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.mouseDragStart = evt.xy.clone();
        this.performedDrag = false;
        this.startViaKeyboard = false;
        if (evt.shiftKey && this.mode !="zoombox") {
            this.switchModeTo("zoombox");
            this.startViaKeyboard = true;
        } else if (evt.altKey && this.mode !="measure") {
            this.switchModeTo("measure");
        } else if (!this.mode) {
            this.switchModeTo("pan");
        }

        switch (this.mode) {
            case "zoombox":
                this.map.div.style.cursor = "crosshair";
                this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
                                                         this.mouseDragStart,
                                                         null,
                                                         null,
                                                         "absolute",
                                                         "2px solid red");
                this.zoomBox.style.backgroundColor = "white";
                this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
                this.zoomBox.style.opacity = "0.50";
                this.zoomBox.style.fontSize = "1px";
                this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.viewPortDiv.appendChild(this.zoomBox);
                this.performedDrag = true;
                break;
            case "measure":
                var distance = "";
                if (this.measureStart) {
                    measureEnd = this.map.getLonLatFromViewPortPx(this.mouseDragStart);
                    distance = OpenLayers.Util.distVincenty(this.measureStart, measureEnd);
                    distance = Math.round(distance * 100) / 100;
                    distance = distance + "km";
                    this.measureStartBox = this.measureBox;
                }
                this.measureStart = this.map.getLonLatFromViewPortPx(this.mouseDragStart);;
                this.measureBox = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           -2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");
                this.measureBox.style.width="4px";
                this.measureBox.style.height="4px";
                this.measureBox.style.fontSize = "1px";
                this.measureBox.style.backgroundColor="red";
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                if (distance) {
                    this.measureBoxDistance = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");

                    this.measureBoxDistance.innerHTML = distance;
                    this.measureBoxDistance.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                    this.map.layerContainerDiv.appendChild(this.measureBoxDistance);
                    this.measureDivs.push(this.measureBoxDistance);
                }
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                this.measureDivs.push(this.measureBox);
                break;
            default:
                this.map.div.style.cursor = "move";
                break;
        }
        document.onselectstart = function() { return false; }
        OpenLayers.Event.stop(evt);
    },

    switchModeTo: function(mode) {
        if (mode != this.mode) {

            if (this.mode && this.buttons[this.mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[this.mode], null, null, null, this.buttons[this.mode].imgLocation);
            }
            if (this.mode == "measure" && mode != "measure") {
                for(var i = 0; i < this.measureDivs.length; i++) {
                    if (this.measureDivs[i]) {
                        this.map.layerContainerDiv.removeChild(this.measureDivs[i]);
                    }
                }
                this.measureDivs = [];
                this.measureStart = null;
            }
            this.mode = mode;
            if (this.buttons[mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[mode], null, null, null, this.buttons[mode].activeImgLocation);
            }
            switch (this.mode) {
                case "zoombox":
                    this.map.div.style.cursor = "crosshair";
                    break;
                default:
                    this.map.div.style.cursor = "default";
                    break;
            }

        }
    },

    leaveMode: function() {
        this.switchModeTo("pan");
    },

    /**
    * @param {Event} evt
    */
    defaultMouseMove: function (evt) {
        if (this.mouseDragStart != null) {
            switch (this.mode) {
                case "zoombox":
                    var deltaX = Math.abs(this.mouseDragStart.x - evt.xy.x);
                    var deltaY = Math.abs(this.mouseDragStart.y - evt.xy.y);
                    this.zoomBox.style.width = Math.max(1, deltaX) + "px";
                    this.zoomBox.style.height = Math.max(1, deltaY) + "px";
                    if (evt.xy.x < this.mouseDragStart.x) {
                        this.zoomBox.style.left = evt.xy.x+"px";
                    }
                    if (evt.xy.y < this.mouseDragStart.y) {
                        this.zoomBox.style.top = evt.xy.y+"px";
                    }
                    break;
                default:
                    var deltaX = this.mouseDragStart.x - evt.xy.x;
                    var deltaY = this.mouseDragStart.y - evt.xy.y;
                    var size = this.map.getSize();
                    var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
                                                     size.h / 2 + deltaY);
                    var newCenter = this.map.getLonLatFromViewPortPx( newXY );
                    this.map.setCenter(newCenter, null, true);
                    this.mouseDragStart = evt.xy.clone();
            }
            this.performedDrag = true;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultMouseUp: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        switch (this.mode) {
            case "zoombox":
                this.zoomBoxEnd(evt);
                if (this.startViaKeyboard) this.leaveMode();
                break;
            case "pan":
                if (this.performedDrag) {
                    this.map.setCenter(this.map.center);
                }
        }
        document.onselectstart = null;
        this.mouseDragStart = null;
        this.map.div.style.cursor = "default";
    },

    /**
    * @param {Event} evt
    */
    defaultMouseOut: function (evt) {
        if (this.mouseDragStart != null
            && OpenLayers.Util.mouseLeft(evt, this.map.div)) {
            if (this.zoomBox) {
                this.removeZoomBox();
                if (this.startViaKeyboard) this.leaveMode();
            }
            this.mouseDragStart = null;
            this.map.div.style.cursor = "default";
        }
    },

    defaultClick: function (evt) {
        if (this.performedDrag)  {
            this.performedDrag = false;
            return false;
        }
    }
});

<commit_msg>Don't call registerWheelEvents twice in MouseToolbar. Fixes #602. Rar.<commit_after>/* Copyright (c) 2006 MetaCarta, Inc., published under a modified BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/repository-license.txt
 * for the full text of the license. */

/**
 * @class
 *
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Control/MouseDefaults.js
 */
OpenLayers.Control.MouseToolbar = OpenLayers.Class.create();
OpenLayers.Control.MouseToolbar.X = 6;
OpenLayers.Control.MouseToolbar.Y = 300;
OpenLayers.Control.MouseToolbar.prototype =
  OpenLayers.Class.inherit( OpenLayers.Control.MouseDefaults, {

    /** WARNING WARNING WARNING!!!
        This class is DEPRECATED in 2.4 and will be removed by 3.0.
        If you need this functionality, use Control.NavToolbar instead!!! */

    mode: null,

    buttons: null,

    direction: "vertical",

    /** @type String */
    buttonClicked: null,

    initialize: function(position, direction) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.position = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,
                                             OpenLayers.Control.MouseToolbar.Y);
        if (position) {
            this.position = position;
        }
        if (direction) {
            this.direction = direction;
        }
        this.measureDivs = [];
    },

    /**
     *
     */
    destroy: function() {
        for( var btnId in this.buttons) {
            var btn = this.buttons[btnId];
            btn.map = null;
            btn.events.destroy();
        }
        OpenLayers.Control.MouseDefaults.prototype.destroy.apply(this,
                                                                 arguments);
    },

    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);
        OpenLayers.Control.MouseDefaults.prototype.draw.apply(this, arguments);
        this.buttons = new Object();
        var sz = new OpenLayers.Size(28,28);
        var centered = new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,0);
        this._addButton("zoombox", "drag-rectangle-off.png", "drag-rectangle-on.png", centered, sz, "Shift->Drag to zoom to area");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this._addButton("pan", "panning-hand-off.png", "panning-hand-on.png", centered, sz, "Drag the map to pan.");
        centered = centered.add((this.direction == "vertical" ? 0 : sz.w), (this.direction == "vertical" ? sz.h : 0));
        this.switchModeTo("pan");

        return this.div;
    },

    _addButton:function(id, img, activeImg, xy, sz, title) {
        var imgLocation = OpenLayers.Util.getImagesLocation() + img;
        var activeImgLocation = OpenLayers.Util.getImagesLocation() + activeImg;
        // var btn = new ol.AlphaImage("_"+id, imgLocation, xy, sz);
        var btn = OpenLayers.Util.createAlphaImageDiv(
                                    "OpenLayers_Control_MouseToolbar_" + id,
                                    xy, sz, imgLocation, "absolute");

        //we want to add the outer div
        this.div.appendChild(btn);
        btn.imgLocation = imgLocation;
        btn.activeImgLocation = activeImgLocation;

        btn.events = new OpenLayers.Events(this, btn, null, true);
        btn.events.register("mousedown", this, this.buttonDown);
        btn.events.register("mouseup", this, this.buttonUp);
        btn.events.register("dblclick", this, OpenLayers.Event.stop);
        btn.action = id;
        btn.title = title;
        btn.alt = title;
        btn.map = this.map;

        //we want to remember/reference the outer div
        this.buttons[id] = btn;
        return btn;
    },

    /**
     * @param {Event} evt
     */
    buttonDown: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.buttonClicked = evt.element.action;
        OpenLayers.Event.stop(evt);
    },

    /**
     * @param {Event} evt
     */
    buttonUp: function(evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        if (this.buttonClicked != null) {
            if (this.buttonClicked == evt.element.action) {
                this.switchModeTo(evt.element.action);
            }
            OpenLayers.Event.stop(evt);
            this.buttonClicked = null;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultDblClick: function (evt) {
        this.switchModeTo("pan");
        this.performedDrag = false;
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
        OpenLayers.Event.stop(evt);
        return false;
    },

    /**
    * @param {Event} evt
    */
    defaultMouseDown: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        this.mouseDragStart = evt.xy.clone();
        this.performedDrag = false;
        this.startViaKeyboard = false;
        if (evt.shiftKey && this.mode !="zoombox") {
            this.switchModeTo("zoombox");
            this.startViaKeyboard = true;
        } else if (evt.altKey && this.mode !="measure") {
            this.switchModeTo("measure");
        } else if (!this.mode) {
            this.switchModeTo("pan");
        }

        switch (this.mode) {
            case "zoombox":
                this.map.div.style.cursor = "crosshair";
                this.zoomBox = OpenLayers.Util.createDiv('zoomBox',
                                                         this.mouseDragStart,
                                                         null,
                                                         null,
                                                         "absolute",
                                                         "2px solid red");
                this.zoomBox.style.backgroundColor = "white";
                this.zoomBox.style.filter = "alpha(opacity=50)"; // IE
                this.zoomBox.style.opacity = "0.50";
                this.zoomBox.style.fontSize = "1px";
                this.zoomBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.viewPortDiv.appendChild(this.zoomBox);
                this.performedDrag = true;
                break;
            case "measure":
                var distance = "";
                if (this.measureStart) {
                    measureEnd = this.map.getLonLatFromViewPortPx(this.mouseDragStart);
                    distance = OpenLayers.Util.distVincenty(this.measureStart, measureEnd);
                    distance = Math.round(distance * 100) / 100;
                    distance = distance + "km";
                    this.measureStartBox = this.measureBox;
                }
                this.measureStart = this.map.getLonLatFromViewPortPx(this.mouseDragStart);;
                this.measureBox = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           -2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");
                this.measureBox.style.width="4px";
                this.measureBox.style.height="4px";
                this.measureBox.style.fontSize = "1px";
                this.measureBox.style.backgroundColor="red";
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                if (distance) {
                    this.measureBoxDistance = OpenLayers.Util.createDiv(null,
                                                         this.mouseDragStart.add(
                                                           -2-parseInt(this.map.layerContainerDiv.style.left),
                                                           2-parseInt(this.map.layerContainerDiv.style.top)),
                                                         null,
                                                         null,
                                                         "absolute");

                    this.measureBoxDistance.innerHTML = distance;
                    this.measureBoxDistance.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                    this.map.layerContainerDiv.appendChild(this.measureBoxDistance);
                    this.measureDivs.push(this.measureBoxDistance);
                }
                this.measureBox.style.zIndex = this.map.Z_INDEX_BASE["Popup"] - 1;
                this.map.layerContainerDiv.appendChild(this.measureBox);
                this.measureDivs.push(this.measureBox);
                break;
            default:
                this.map.div.style.cursor = "move";
                break;
        }
        document.onselectstart = function() { return false; }
        OpenLayers.Event.stop(evt);
    },

    switchModeTo: function(mode) {
        if (mode != this.mode) {

            if (this.mode && this.buttons[this.mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[this.mode], null, null, null, this.buttons[this.mode].imgLocation);
            }
            if (this.mode == "measure" && mode != "measure") {
                for(var i = 0; i < this.measureDivs.length; i++) {
                    if (this.measureDivs[i]) {
                        this.map.layerContainerDiv.removeChild(this.measureDivs[i]);
                    }
                }
                this.measureDivs = [];
                this.measureStart = null;
            }
            this.mode = mode;
            if (this.buttons[mode]) {
                OpenLayers.Util.modifyAlphaImageDiv(this.buttons[mode], null, null, null, this.buttons[mode].activeImgLocation);
            }
            switch (this.mode) {
                case "zoombox":
                    this.map.div.style.cursor = "crosshair";
                    break;
                default:
                    this.map.div.style.cursor = "default";
                    break;
            }

        }
    },

    leaveMode: function() {
        this.switchModeTo("pan");
    },

    /**
    * @param {Event} evt
    */
    defaultMouseMove: function (evt) {
        if (this.mouseDragStart != null) {
            switch (this.mode) {
                case "zoombox":
                    var deltaX = Math.abs(this.mouseDragStart.x - evt.xy.x);
                    var deltaY = Math.abs(this.mouseDragStart.y - evt.xy.y);
                    this.zoomBox.style.width = Math.max(1, deltaX) + "px";
                    this.zoomBox.style.height = Math.max(1, deltaY) + "px";
                    if (evt.xy.x < this.mouseDragStart.x) {
                        this.zoomBox.style.left = evt.xy.x+"px";
                    }
                    if (evt.xy.y < this.mouseDragStart.y) {
                        this.zoomBox.style.top = evt.xy.y+"px";
                    }
                    break;
                default:
                    var deltaX = this.mouseDragStart.x - evt.xy.x;
                    var deltaY = this.mouseDragStart.y - evt.xy.y;
                    var size = this.map.getSize();
                    var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
                                                     size.h / 2 + deltaY);
                    var newCenter = this.map.getLonLatFromViewPortPx( newXY );
                    this.map.setCenter(newCenter, null, true);
                    this.mouseDragStart = evt.xy.clone();
            }
            this.performedDrag = true;
        }
    },

    /**
    * @param {Event} evt
    */
    defaultMouseUp: function (evt) {
        if (!OpenLayers.Event.isLeftClick(evt)) return;
        switch (this.mode) {
            case "zoombox":
                this.zoomBoxEnd(evt);
                if (this.startViaKeyboard) this.leaveMode();
                break;
            case "pan":
                if (this.performedDrag) {
                    this.map.setCenter(this.map.center);
                }
        }
        document.onselectstart = null;
        this.mouseDragStart = null;
        this.map.div.style.cursor = "default";
    },

    /**
    * @param {Event} evt
    */
    defaultMouseOut: function (evt) {
        if (this.mouseDragStart != null
            && OpenLayers.Util.mouseLeft(evt, this.map.div)) {
            if (this.zoomBox) {
                this.removeZoomBox();
                if (this.startViaKeyboard) this.leaveMode();
            }
            this.mouseDragStart = null;
            this.map.div.style.cursor = "default";
        }
    },

    defaultClick: function (evt) {
        if (this.performedDrag)  {
            this.performedDrag = false;
            return false;
        }
    }
});

<|endoftext|>


<commit_before>var connectedDevices = require('./../dbmodels/connected_devices.js');
module.exports = function(mosca, socket, socketIO){
connectedDevicesList = [];

var mosca_message = {
        topic: 'patient',
        payload: 'asdfghjk', // or a Buffer
        qos: 0, // 0, 1, or 2
        retain: false // or true
        };

socket.on('get_devices', function(){
    // socket.emit('get_devices', connectedDevices);
    console.log('get devices call made');
    getConnectedDevices();
});

function getConnectedDevices(){
    connectedDevices.findOne({}, function(err, devices){
        if(err) console.log(err);
        if(!err){
            console.log("CONNECTED DEVICES: ", devices.connectedDevices);
            socket.emit('get_devices', devices.connectedDevices)

        }
    })
}

// var devices = connectedDevices({
//     connectedDevices:[]
// }).save(function(err) {
//     if(err) console.log(err);
//     console.log('DEVICES INIT')
// })

socket.on('set_patient_device', function(ids){
    if(ids.p_id && ids.device_id){
        var mosca_message = {
            topic: ids.device_id,
            payload: ids.p_id, // or a Buffer
            qos: 0, // 0, 1, or 2
            retain: false // or true
        };
    mosca.publish(mosca_message,function(asd){console.log(asd)});
    }
})

mosca.on('clientConnected', function(client) {
    console.log('client connected', client.id);
    connectedDevicesList.push(client.id);
    console.log('connected devices list :',connectedDevicesList);
    connectedDevices.update({},{$addToSet:{connectedDevices:client.id}}, function(err){

        if(err) console.log('ERROR ON UPDATING RECORD');
        if(!err) console.log ('NEW DEVICE ADDED TO DATABBASE');
        getConnectedDevices();
    });
        var booleanValue = true;
        // setInterval(()=> {
        //     message1.payload = ""+(booleanValue=!booleanValue);
        //     mosca.publish(message1, cb)
        // }, 4000 );

        function cb() { console.log('done!'); }
});

// fired when a message is received
mosca.on('published', function(packet, client) {
  console.log('Published', packet.payload.toString());
});

mosca.on('ready', setup);

mosca.on('clientDisconnected', function(client) {
    console.log('Client Disconnected:', client.id);
    connectedDevices.update({}, {$pull: {connectedDevices: client.id}}, function(err){
        if(err) console.log('ERROR AT UPDAING WHEN REMOVING DEVICE', err);
        if(!err){
            console.log('[MONGODB] DEVICE REMOVED SUCCESSFULLY');
            getConnectedDevices();
        }

    });
});

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running');
}
}<commit_msg>android to node to client done<commit_after>var connectedDevices = require('./../dbmodels/connected_devices.js');
module.exports = function(mosca, socket, socketIO){
connectedDevicesList = [];

var mosca_message = {
        topic: 'patient',
        payload: 'asdfghjk', // or a Buffer
        qos: 0, // 0, 1, or 2
        retain: false // or true
        };

socket.on('get_devices', function(){
    // socket.emit('get_devices', connectedDevices);
    console.log('get devices call made');
    getConnectedDevices();
});

function getConnectedDevices(){
    connectedDevices.findOne({}, function(err, devices){
        if(err) console.log(err);
        if(!err){
            console.log("CONNECTED DEVICES: ", devices.connectedDevices);
            socket.emit('get_devices', devices.connectedDevices)

        }
    })
}

// var devices = connectedDevices({
//     connectedDevices:[]
// }).save(function(err) {
//     if(err) console.log(err);
//     console.log('DEVICES INIT')
// })

socket.on('set_patient_device', function(ids){
    if(ids.p_id && ids.device_id){
        var mosca_message = {
            topic: ids.device_id,
            payload: ids.p_id, // or a Buffer
            qos: 0, // 0, 1, or 2
            retain: false // or true
        };

    mosca.publish(mosca_message ,function(asd){console.log('SET PATIENT DEVICE CB')});
    }
})

mosca.on('clientConnected', function(client) {
    console.log('client connected', client.id);
    connectedDevicesList.push(client.id);
    console.log('connected devices list :',connectedDevicesList);
    connectedDevices.update({},{$addToSet:{connectedDevices:client.id}}, function(err){

        if(err) console.log('ERROR ON UPDATING RECORD');
        if(!err) console.log ('NEW DEVICE ADDED TO DATABBASE');
        getConnectedDevices();
    });
        var booleanValue = true;
        setInterval(()=> {
            mosca_message.payload = "true";
            mosca_message.topic = `${booleanValue = !booleanValue}`;
            mosca.publish(mosca_message, cb)
        }, 3000 );

        function cb() { }
});

// fired when a message is received
mosca.on('published', function(packet, client) {
  console.log('Published', packet.payload.toString());
});

mosca.on('ready', setup);

mosca.on('clientDisconnected', function(client) {
    console.log('Client Disconnected:', client.id);
    connectedDevices.update({}, {$pull: {connectedDevices: client.id}}, function(err){
        if(err) console.log('ERROR AT UPDAING WHEN REMOVING DEVICE', err);
        if(!err){
            console.log('[MONGODB] DEVICE REMOVED SUCCESSFULLY');
            getConnectedDevices();
        }

    });
});

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running');
}
}<|endoftext|>


<commit_before>'use strict';

import sinon from 'sinon'
import Promise from 'bluebird'

import { Dispatcher } from '../../'

class TestApp extends Dispatcher {
  constructor() {
    super()

    this.log = sinon.spy();
    this.config = {};

    this.on = sinon.spy(this.on);
    this.once = sinon.spy(this.once);

    this.await = sinon.spy();

    this._gather = sinon.createStubInstance(Promise);
    this._send_with = sinon.createStubInstance(Promise);
    this._send = {
      with: sinon.stub().returns(this._send_with)
    }
    this._get = {
      gather: sinon.stub().returns(this._gather),
      send: sinon.stub().returns(this._send)
    };
    this.get = sinon.stub().returns(this._get);

  }

  launch() {
    return new Promise.mapSeries(['init', 'load', 'startup', 'launch'], (e) => {
      return this.emit(e).with();
    })
  }

}

export default TestApp;
<commit_msg>Add module on to TestApp<commit_after>'use strict';

import sinon from 'sinon'
import Promise from 'bluebird'

import { Dispatcher } from '../../'

class TestApp extends Dispatcher {
  constructor() {
    super()

    this.log = sinon.spy();
    this.config = {};

    this.on = sinon.spy(this.on);
    this.once = sinon.spy(this.once);

    this._gather = sinon.createStubInstance(Promise);
    this._send_with = sinon.createStubInstance(Promise);
    this._get_on = sinon.spy();
    this._get_once = sinon.spy();
    this._send = {
      with: sinon.stub().returns(this._send_with)
    }
    this._get = {
      gather: sinon.stub().returns(this._gather),
      send: sinon.stub().returns(this._send),
      on: sinon.stub().returns(this._get_on)
      once: sinon.stub().returns(this._get_once)
    };
    this.get = sinon.stub().returns(this._get);

  }

  launch() {
    return new Promise.mapSeries(['init', 'load', 'startup', 'launch'], (e) => {
      return this.emit(e).with();
    })
  }

}

export default TestApp;
<|endoftext|>


<commit_before>//     autocell.js 0.0.1
//     https://github.com/buzzdecafe/autocell
//     (c) 2014 Michael Hurley
//     AutoCell may be freely distributed under the MIT license.
//
// AutoCell
// -----
// Tinkering with cellular automata.
//
// Basic Setup
// -----------
// Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser,
// with or without an AMD-style loader.
//
//  [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js

(function (root, factory) {if (typeof exports === 'object') {module.exports = factory(root);} else if (typeof define === 'function' && define.amd) {define(factory);} else {root.autocell = factory(root);}}(this, function (global) {

    return  (function() {

      function trampoline(fn) {
        var result = fn.apply(this, [].slice.call(arguments, 1));
        while (typeof result === 'function') {
          result = result();
        }
        return result;
      }

      // draw the state to the screen
      function display(state) {
        // override me
        console.log(state);
      }

      // simple 1D grid
      function applyRule(rule, state) {
        return state.map(function(cell, idx, arr) {
          var west = idx > 0 ? arr[idx - 1] : 0;
          var east = idx < state.length ? arr[idx + 1] : 0;
          return rule(west, cell, east);
        });
      }

      // `rule` is a map from state to state
      // `state` is the current state of the automaton
      // `steps` is the number of iterations to run
      function autocell(rule, state, steps) {
        var ac = function(r, s, t) {
          display(s);
          return (t <= 0) ? s : function() { setTimeout(function () { ac(r, applyRule(r, s), t - 1); }, 500); };
        };
        return trampoline(ac, rule, state, steps);
      }

      return autocell;

    }());
}));
<commit_msg>classic off-by-one error<commit_after>//     autocell.js 0.0.1
//     https://github.com/buzzdecafe/autocell
//     (c) 2014 Michael Hurley
//     AutoCell may be freely distributed under the MIT license.
//
// AutoCell
// -----
// Tinkering with cellular automata.
//
// Basic Setup
// -----------
// Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser,
// with or without an AMD-style loader.
//
//  [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js

(function (root, factory) {if (typeof exports === 'object') {module.exports = factory(root);} else if (typeof define === 'function' && define.amd) {define(factory);} else {root.autocell = factory(root);}}(this, function (global) {

    return  (function() {

      function trampoline(fn) {
        var result = fn.apply(this, [].slice.call(arguments, 1));
        while (typeof result === 'function') {
          result = result();
        }
        return result;
      }

      // draw the state to the screen
      function display(state) {
        // override me
        console.log(state);
      }

      // simple 1D grid
      function applyRule(rule, state) {
        return state.map(function(cell, idx, arr) {
          var west = idx > 0 ? arr[idx - 1] : 0;
          var east = idx < state.length - 1 ? arr[idx + 1] : 0;
          return rule(west, cell, east);
        });
      }

      // `rule` is a map from state to state
      // `state` is the current state of the automaton
      // `steps` is the number of iterations to run
      function autocell(rule, state, steps) {
        var ac = function(r, s, t) {
          display(s);
          return (t <= 0) ? s : function() { setTimeout(function () { ac(r, applyRule(r, s), t - 1); }, 500); };
        };
        return trampoline(ac, rule, state, steps);
      }

      return autocell;

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


<commit_before>// Copyright (c) 2017 - Kyle Derby MacInnis
// Any unauthorized distribution or transfer
// of this work is strictly prohibited.
// All Rights Reserved.
//

// REFER TO THE LICENSE FILE FOR INFORMATION REGARDING LICENSING

// AUTHOR: Kyle Derby MacInnis
// VERSION: 0.1.0
// DATE : FEBRUARY 7, 2017

// DISCLAIMER:
//
// ** THIS FILE IS FOR NON-COMMERCIAL USE IN ALL FORMS ** EXCEPT THE FOLLOWING EXCEPTIONS **
//
// -- THIS FILE CAN BE USED FOR EDUCATIONAL PURPOSES - AS LONG AS SUCH EDUCATION IS PURELY INDIVIDUAL
//
// -- THIS FILE CAN BE EXAMINED INDIVIDUALLY - BUT CANNOT BE SHARED - DISCUSSED - OR DISTRIBUTED OPENLY OR PRIVATELY WITHOUT CONSENT FROM THE AUTHOR
//
// -- THIS FILE CANNOT BE USED BY ANY AFFILIATE OF PAPER INTERACTIVE INCORPORATED WITHOUT EXPLICIT PERMISSION FROM THE AUTHOR

// DESCRIPTION:
// Functions for Latex Document Transpiling & Compilation (PDF + DVI)

// THIRD-PARTY LIBRARIES
const LTX = require('latex-ex'); // For Compiling into PDF (Requires TexLive)
const toolLib = require('./library.js');

// Main Object for Export
const latexEngine = {

    // -------FLAGS AND STORAGE-------
    // ================================>
    // Header & System Generated Stuff here
    _sys: [],
    // System related stuff goes here based on usage
    _macro: [],
    // Blank Array for Buffer (User Driven Content Goes Here)
    _latex: [],
    // PDF Stream (Output)
    _pdf: [],
    // DVI Stream (Output)
    _dvi: [],
    // Export Flag for Drafting
    _export: false,
    // Watermark Text (if-any)
    _watermark: "",
    // Colours (for Styling Purposes)
    _colours: [],
    // Styles
    _styles: [],
    // Images
    _images: [],
    // Files
    _files: [],

    // ----------MAIN FUNCTIONS----------
    // =================================>
    // Initializes Stream + Setups Flags
    init: (ltxStream, exportFlag, colours) => {
        this._latex = ltxStream;
        this._export = exportFlag;
        if (colours && colours.length) {
            let i = colours.length;
            while (i--) {
                this.setColour(colours[i].name, colours[i].val, colours[i].type);
            }
        }
        // Setup System configuration
        this._initSystemConfig();
        // Setup Macros
        this._initDefaultMacros();
        // Establish Styles for Use (Defaults)
        this._setStyle("bf", "\\textbf{", "}");
        this._setStyle("it", "\\emph{", "}");
        this._setStyle("ul", "\\ul{", "}");
        this._setStyle("st", "\\st{", "}");
        // Establish colours available for use (Defaults)
        this._setColour("text", "#000000", "HTML"); // Default Colour
        this._setColour("new", "#0000AA", "HTML"); // Revision Highlighting
        this._setColour("old", "#AA0000", "HTML"); // Revision Highlighting
        this._setColour("eq", "#5533AA", "HTML"); // Equal
        this._setColour("neq", "#337711", "HTML"); // Not Equal
    },
    // System Configuration
    _initSystemConfig: () => {
        // Setup System
        this._sys.push("\\batchmode\n");
    },
    // Macro Initialization
    _initDefaultMacros: () => {
        // Setup Macros
    },
    // Adds in configuration for a new colour in Latex
    _setColour: (name, val, type) => {
        this._colours["_" + name] = {
            name: name,
            val: val,
            type: type,
            ltx: "\\colour{" + name + "}"
        };
        this._colours[name] = () => this._colours["_" + name].ltx
        // Append Latex Command for New Colour to Macros
        this._macro.push["\\definecolour{" + name + "}{" + type + "}{" + val + "}"];
    },
    // Adds in configuration for a new colour in Latex
    _setStyle: (name, pre, post) => {
        this._styles["_" + name] = {
            name: name,
            pre: pre,
            post: post,
            ltx: (text) => {
                return "\\" + name + "{" + text + "}"
            }
        };
        this._styles[name] = (text) => this._styles["_" + name].ltx(text);
        // Append Latex Command for New Colour to Macros
        this._macro.push["\\def\\" + name + "<#1>{" + pre + "#1" + post + "}"];
    },

    // ---- FILE COMMAND UTILITIES ----
    // ================================>
    // Generate PDF File
    toPDF: () => {
        // Store to this._pdf & return
    },
    // Generate DVI File
    toDVI: () => {
        // Store to this._dvi & return
    },
    // Generate Latex File
    toLTX: () => {
        let output = this._sys.concat(this._macro).concat(this._latex)
        return output.join("");
    },

    // -----STREAM BASED UTILITIES-----
    // ===============================>
    // Push Raw Text into Stream
    push: (item) => {
        this._latex.push(item);
    },
    // Push If
    pushIf: (condition, item) => {
        let itm = condition ? item : "";
        this._latex.push(itm);
    },
    // Push If/Else
    pushIfElse: (condition, item, otheritem) => {
        let itm = condition ? item : otheritem;
        this._latex.push(itm);
    },
    // Push Clean Text into Stream
    cpush: (item) => {
        this._latex.push(this.clean(item));
    },
    // Clean & Push If
    cpushIf: (condition, item) => {
        let itm = condition ? item : "";
        this._latex.push(this.clean(itm));
    },
    // Push & Clean If/Else
    cpushIfElse: (condition, item, otherItem) => {
        let itm = condition ? item : otheritem;
        this._latex.push(this.clean(itm));
    },
    // Pop Raw Text from Stream
    pop: () => {
        return this._latex.pop();
    },
    // Pop If
    popIf: (test) => {
        if (test) {
            return this._latex.pop();
        }
    },

    // ----- TEXT BASED UTILITIES ------
    // =================================>
    // Cleans Input of all Latex Special Characters
    clean: (str) => {
        return str ?
            String(str)
            .replace(/\^/g, '\\textasciicircum{}')
            .replace(/\~/g, '\\textasciitilde{}')
            .replace(/\{/g, '\\\{')
            .replace(/\}/g, '\\\}')
            .replace(/\_/g, '\\\_')
            .replace(/\%/g, '\\\%')
            .replace(/\$/g, '\\\$')
            .replace(/\&/g, '\\\&')
            .replace(/\#/g, '\\\#')
            .replace(/\\/g, '') :
            "";
    },
    // Returns comparison between two variables
    compare: (one, two) => {
        if (one === two) {
            return "eq"
        } else if (two === "") {
            return "one"
        } else if (one === "") {
            return "two"
        } else {
            return "neq"
        }
    },

    // Conditional Put
    putIf: (condition, t_str) => {
        return condition ?
            t_str :
            "";
    },
    // If/Else
    putIfElse: (condition, t_str, f_str) => {
        return condition ?
            t_str :
            f_str;
    },
    //  Put
    cputIf: (condition, t_str) => {
        return condition ?
            this.clean(t_str) :
            "";
    },
    // If/Else
    cputIfElse: (condition, t_str, f_str) => {
        return condition ?
            this.clean(t_str) :
            this.clean(f_str);
    },

    // ----- STRUCTURES & DOCUMENT TEMPLATES ------
    // ===========================================>

    // Generate a Dynamic Table
    table: (columns, array) => {
        let coltypes = ["| "];
        let entries = [];
        for (let i = 0; i < columns.length; i++) {
            coltypes.push(" " + columns[i] + " | ");
        }
        for (let i = 0; i < array.length; i++) {
            entries.push("\\bottomrule\n")
            for (let j = 0; j < columns.length; j++) {
                j == column.length - 1 ?
                    entries.push(array[i][j] + "\\\\") :
                    entries.push(array[i][j] + " & ");
            }
            entries.push("\n\\toprule\n");
            if (i == 0) {
                entries.push("\\endhead\n");
            }
        }
        var out = ["\\newcolumntype{g}{>{\\vfill\\centering}X}~\n",
            "\\newcolumntype{Y}{>{\\vfill\\RaggedRight\\arraybackslash}X}~\n",
            "\\newcolumntype{Z}{>{\\vfill\\centering\\arraybackslash}X}",
            "\\begin{tabularx}{\\textwidth}{" + coltypes.join("") + "}\n",
            entries.join("") + "\n",
            "\\end{tabularx}\n\\flushleft"
        ];
        this._push(out.join(""));
    },

    // List (for enumerated lists)
    list: (array) => {
        let out = ["\\lst\n"];
        for (let i = 0; i < array.length; i++) {
            out.push("{(" + String.fromCharCode(97 + i) + ")}{" + array[i] + "}\n");
        }
        out.push("\\stoplst");
        return out.join("");
    },

    // ---LATEX FORMATTING & STYLE FUNCTIONS---
    // =======================================>

    // Generate Custom Styles
    style: (text, flags) => {
        let ltx = [];
        // Determine Colour
        flags.new ? ltx.push(this._colours.new()) : ltx.push("");
        flags.old ? ltx.push(this._colours.old()) : ltx.push("");
        flags.eq ? ltx.push(this._colours.eq()) : ltx.push("");
        flags.neq ? ltx.push(this._colours.neq()) : ltx.push("");
        // Apply Formatting
        text = flags.cl ? this.clean(text) : text;
        text = flags.st ? this._styles.st(text) : text;
        text = flags.bf ? this._styles.bf(text) : text;
        text = flags.ul ? this._styles.ul(text) : text;
        // Push and Finalize
        ltx.push(text);
        ltx.push(this._colours.text());
        return ltx.join("");
    },

    // Generate Flags Object for Use
    genFlags: () => {
        return {
            new: false,
            old: false,
            ul: false,
            cl: false,
            st: false,
            eq: false,
            neq: false,
        };
    }
}
module.exports = latexEngine;<commit_msg>Styling stuff for engine<commit_after>// Copyright (c) 2017 - Kyle Derby MacInnis
// Any unauthorized distribution or transfer
// of this work is strictly prohibited.
// All Rights Reserved.
//

// REFER TO THE LICENSE FILE FOR INFORMATION REGARDING LICENSING

// AUTHOR: Kyle Derby MacInnis
// VERSION: 0.1.0
// DATE : FEBRUARY 7, 2017

// DISCLAIMER:
//
// ** THIS FILE IS FOR NON-COMMERCIAL USE IN ALL FORMS ** EXCEPT THE FOLLOWING EXCEPTIONS **
//
// -- THIS FILE CAN BE USED FOR EDUCATIONAL PURPOSES - AS LONG AS SUCH EDUCATION IS PURELY INDIVIDUAL
//
// -- THIS FILE CAN BE EXAMINED INDIVIDUALLY - BUT CANNOT BE SHARED - DISCUSSED - OR DISTRIBUTED OPENLY OR PRIVATELY WITHOUT CONSENT FROM THE AUTHOR
//
// -- THIS FILE CANNOT BE USED BY ANY AFFILIATE OF PAPER INTERACTIVE INCORPORATED WITHOUT EXPLICIT PERMISSION FROM THE AUTHOR

// DESCRIPTION:
// Functions for Latex Document Transpiling & Compilation (PDF + DVI)

// THIRD-PARTY LIBRARIES
const LTX = require('latex-ex'); // For Compiling into PDF (Requires TexLive)
const toolLib = require('./library.js');

// Main Object for Export
const latexEngine = {

    // -------FLAGS AND STORAGE-------
    // ================================>
    // Header & System Generated Stuff here
    _sys: [],
    // System related stuff goes here based on usage
    _macro: [],
    // Blank Array for Buffer (User Driven Content Goes Here)
    _latex: [],
    // PDF Stream (Output)
    _pdf: [],
    // DVI Stream (Output)
    _dvi: [],
    // Export Flag for Drafting
    _export: false,
    // Watermark Text (if-any)
    _watermark: "",
    // Colours (for Styling Purposes)
    _colours: [],
    // Styles
    _styles: [],
    // Images
    _images: [],
    // Files
    _files: [],

    // ----------MAIN FUNCTIONS----------
    // =================================>
    // Initializes Stream + Setups Flags
    init: (ltxStream, exportFlag, colours) => {
        this._latex = ltxStream;
        this._export = exportFlag;
        if (colours && colours.length) {
            let i = colours.length;
            while (i--) {
                this.setColour(colours[i].name, colours[i].val, colours[i].type);
            }
        }
        // Setup System configuration
        this._initSystemConfig();
        // Setup Macros
        this._initDefaultMacros();

        // Establish Styles for Use (Defaults) (extensible)
        this._setStyle("bf", "\\textbf{", "}");
        this._setStyle("it", "\\emph{", "}");
        this._setStyle("ul", "\\ul{", "}");
        this._setStyle("st", "\\st{", "}");

        // Establish colours available for use (Defaults) (Extensible)
        this._setColour("text", "#000000", "HTML"); // Default Colour
        this._setColour("new", "#0000AA", "HTML"); // Revision Highlighting
        this._setColour("old", "#AA0000", "HTML"); // Revision Highlighting
        this._setColour("eq", "#5533AA", "HTML"); // Equal
        this._setColour("neq", "#337711", "HTML"); // Not Equal
    },
    // System Configuration
    _initSystemConfig: () => {
        // Setup System
        this._sys.push("\\batchmode\n");
    },
    // Macro Initialization
    _initDefaultMacros: () => {
        // Setup Macros
    },
    // Adds in configuration for a new colour in Latex
    _setColour: (name, val, type) => {
        this._colours["_" + name] = {
            name: name,
            val: val,
            type: type,
            ltx: "\\colour{" + name + "}"
        };
        this._colours[name] = () => this._colours["_" + name].ltx
        // Append Latex Command for New Colour to Macros
        this._macro.push["\\definecolour{" + name + "}{" + type + "}{" + val + "}"];
    },
    // Adds in configuration for a new colour in Latex
    _setStyle: (name, pre, post) => {
        this._styles["_" + name] = {
            name: name,
            pre: pre,
            post: post,
            ltx: (text) => {
                return "\\" + name + "{" + text + "}"
            }
        };
        this._styles[name] = (text) => this._styles["_" + name].ltx(text);
        // Append Latex Command for New Colour to Macros
        this._macro.push["\\def\\" + name + "<#1>{" + pre + "#1" + post + "}"];
    },

    // ---- FILE COMMAND UTILITIES ----
    // ================================>
    // Generate PDF File
    toPDF: () => {
        return new Promise((resolve, reject) => {
            let input = this._sys.concat(this._macro).concat(this._latex)
            // Store to this._pdf & return
            let stream = LTX(input.join(""));
            let pdfData = [];
            try {
                stream.on('data', (chunk) => {
                    pdfData.push(chunk);
                });
                stream.on('end', () => {
                    this._pdf = pdfData;
                    resolve(pdfData);
                })
            } catch (e) {
                console.error(e);
                reject(e);
            }
        });
    },
    // Generate base64 Encoded PDF File
    toPDF64: () => {
        return new Promise((resolve, reject) => {
            let input = this._sys.concat(this._macro).concat(this._latex)
            // Store to this._pdf & return
            let stream = LTX(input.join(""));
            let pdfData = [];
            try {
                stream.on('data', (chunk) => {
                    pdfData.push(chunk.toString('base64'));
                });
                stream.on('end', () => {
                    this._pdf = pdfData;
                    resolve(pdfData);
                })
            } catch (e) {
                console.error(e);
                reject(e);
            }
        });
    },
    // Generate DVI File
    toDVI: () => {
        // Store to this._dvi & return
        return new Promise((resolve, reject) => {
            let input = this._sys.concat(this._macro).concat(this._latex)
            // Store to this._pdf & return
            let stream = LTX(input.join(""), {
                format: 'dvi'
            });
            let pdfData = [];
            try {
                stream.on('data', (chunk) => {
                    pdfData.push(chunk);
                });
                stream.on('end', () => {
                    this._pdf = pdfData;
                    resolve(pdfData);
                })
            } catch (e) {
                console.error(e);
                reject(e);
            }
        });
    },
    // Generate Latex File
    toLTX: () => {
        let output = this._sys.concat(this._macro).concat(this._latex)
        return Promise.resolve(output.join(""));
    },

    // -----STREAM BASED UTILITIES-----
    // ===============================>
    // Push Raw Text into Stream
    push: (item) => {
        this._latex.push(item);
    },
    // Push If
    pushIf: (condition, item) => {
        let itm = condition ? item : "";
        this._latex.push(itm);
    },
    // Push If/Else
    pushIfElse: (condition, item, otheritem) => {
        let itm = condition ? item : otheritem;
        this._latex.push(itm);
    },
    // Push Clean Text into Stream
    cpush: (item) => {
        this._latex.push(this.clean(item));
    },
    // Clean & Push If
    cpushIf: (condition, item) => {
        let itm = condition ? item : "";
        this._latex.push(this.clean(itm));
    },
    // Push & Clean If/Else
    cpushIfElse: (condition, item, otherItem) => {
        let itm = condition ? item : otheritem;
        this._latex.push(this.clean(itm));
    },
    // Pop Raw Text from Stream
    pop: () => {
        return this._latex.pop();
    },
    // Pop If
    popIf: (test) => {
        if (test) {
            return this._latex.pop();
        }
    },

    // ----- TEXT BASED UTILITIES ------
    // =================================>
    // Cleans Input of all Latex Special Characters
    clean: (str) => {
        return str ?
            String(str)
            .replace(/\^/g, '\\textasciicircum{}')
            .replace(/\~/g, '\\textasciitilde{}')
            .replace(/\{/g, '\\\{')
            .replace(/\}/g, '\\\}')
            .replace(/\_/g, '\\\_')
            .replace(/\%/g, '\\\%')
            .replace(/\$/g, '\\\$')
            .replace(/\&/g, '\\\&')
            .replace(/\#/g, '\\\#')
            .replace(/\\/g, '') :
            "";
    },
    // Returns comparison between two variables
    compare: (one, two) => {
        if (one === two) {
            return "eq"
        } else if (two === "") {
            return "one"
        } else if (one === "") {
            return "two"
        } else {
            return "neq"
        }
    },
    // Conditional Put
    putIf: (condition, t_str) => {
        return condition ?
            t_str :
            "";
    },
    // If/Else
    putIfElse: (condition, t_str, f_str) => {
        return condition ?
            t_str :
            f_str;
    },
    //  Put
    cputIf: (condition, t_str) => {
        return condition ?
            this.clean(t_str) :
            "";
    },
    // If/Else
    cputIfElse: (condition, t_str, f_str) => {
        return condition ?
            this.clean(t_str) :
            this.clean(f_str);
    },

    // ----- STRUCTURES & DOCUMENT TEMPLATES ------
    // ===========================================>
    // Generate a Dynamic Table
    table: (columns, array) => {
        let coltypes = ["| "];
        let entries = [];
        for (let i = 0; i < columns.length; i++) {
            coltypes.push(" " + columns[i] + " | ");
        }
        for (let i = 0; i < array.length; i++) {
            entries.push("\\bottomrule\n")
            for (let j = 0; j < columns.length; j++) {
                j === column.length - 1 ?
                    entries.push(array[i][j] + "\\\\") :
                    entries.push(array[i][j] + " & ");
            }
            entries.push("\n\\toprule\n");
            if (i === 0) {
                entries.push("\\endhead\n");
            }
        }
        let out = [];
        out.push("\\newcolumntype{g}{>{\\vfill\\centering}X}~\n");
        out.push("\\newcolumntype{Y}{>{\\vfill\\RaggedRight\\arraybackslash}X}~\n");
        out.push("\\newcolumntype{Z}{>{\\vfill\\centering\\arraybackslash}X}");
        out.push("\\begin{tabularx}{\\textwidth}{" + coltypes.join("") + "}\n");
        out.push(entries.join("") + "\n");
        out.push("\\end{tabularx}\n\\flushleft")
        this._push(out.join(""));
    },
    // List (for enumerated lists)
    list: (array) => {
        let out = ["\\lst\n"];
        for (let i = 0; i < array.length; i++) {
            out.push("{(" + String.fromCharCode(97 + i) + ")}{" + array[i] + "}\n");
        }
        out.push("\\stoplst");
        return out.join("");
    },
    // Section Heading
    section: (hd) => {
        var out = ["\n\\section*{" + hd + "}\n"];
        this._latex.push(out.join(""));
    },
    // Subsection Heading
    subsection: (hd) => {
        var out = ["\n\\subsection*{" + hd + "}\n"];
        this._latex.push(out.join(""));
    },
    // Definition
    definition: (def, txt) => {
        var out = ["\\paragraph{\"" + def + "\"}{" + txt + "}\n"];
        this._latex.push(out.join(""));
    },
    // Line Break
    br: () => {
        this.push("\\ \\linebreak\n");
    },
    // New Page
    np: () => {
        this.push("\\pagebreak\n");
    },
    // Plain Text
    plain: (txt) => {
        var out = ["\\noindent " + txt + "\n"];
        this._latex.push(out.join(""));
    },
    // Indented Text
    indent: (txt) => {
        var out = ["\\indent" + txt + "\n"];
        this._latex.push(out.join(""));
    },
    // Bold Font
    bf: (txt) => {
        var out = ["\\textbf{" + txt + "}\n"];
        this._latex.push(out.join(""));
    },
     // Underline
    ul: (txt) => {
        var out = ["\\underline{" + txt + "}\n"];
        this._latex.push(out.join(""));
    },
    // Paragraph Entry
    par: (bold, txt) => {
        this._push("\\paragraph{" + bold + "}{" + txt + "}\n");
    },
    // Enumerated Paragraphs (uses counter)
    enum: (title, txt) => {
        var out = ["\\stepcounter{clausecount}\n\\reversemarginpar",
            "\\marginnote{\\textbf{\\theclausecount .}}[0.9cm]\\paragraph{" + title + "}\\nonfrenchspacing " + txt + "\n"
        ];
        this._latex.push(out.join(""));
    },
    // Enumerated Heading (uses counter)
    enumHead: (title) => {
        var out = ["\\stepcounter{artcount}\n",
            "\\subsubsection*{\\bf ARTICLE \\theartcount\\ -\\ " + title + "}\n"
        ];
        this._latex.push(out.join(""));
    },
    // Floating Title (Right)
    floatRightHead: (heading) => {
        var out = ["\\hfill\\begin{minipage}{\\dimexpr\\textwidth-8cm}\n",
            "\\parfillskip0pt\n\\parindent0pt\n\\fontdimen3\\font.25in\n",
            "\\frenchspacing\n\\bf " + heading + "\n\\end{minipage}\\ ",
            "\\linebreak \\ \\linebreak\\nonfrenchspacing\n"
        ];
        this._latex.push(out.join(""));
    },
    // Floating Title (Left)
    floatLeftHead: (heading) => {
        var out = ["\\begin{minipage}{\\dimexpr\\textwidth-8cm}\n",
            "\\parfillskip0pt\n\\parindent0pt\n\\fontdimen3\\font.25in\n",
            "\\frenchspacing\n\\bf " + heading + "\n\\end{minipage}\\hfill\\ ",
            "\\linebreak \\ \\linebreak\\nonfrenchspacing\n"
        ];
        this._latex.push(out.join(""));
    },

    // ---LATEX FORMATTING & STYLE FUNCTIONS---
    // =======================================>
    // Generate Custom Styles
    newStyle: (text, flags) => {
        let ltx = [];
        // Determine Colour
        flags.new ? ltx.push(this._colours.new()) : ltx.push("");
        flags.old ? ltx.push(this._colours.old()) : ltx.push("");
        flags.eq ? ltx.push(this._colours.eq()) : ltx.push("");
        flags.neq ? ltx.push(this._colours.neq()) : ltx.push("");
        // Apply Formatting
        text = flags.cl ? this.clean(text) : text;
        text = flags.st ? this._styles.st(text) : text;
        text = flags.bf ? this._styles.bf(text) : text;
        text = flags.it ? this._styles.it(text) : text;
        text = flags.ul ? this._styles.ul(text) : text;
        // Push and Finalize
        ltx.push(text);
        ltx.push(this._colours.text());
        return ltx.join("");
    },
    // Generate Flags Object for Use (defaults)
    genFlags: () => {
        return {
            new: false,
            old: false,
            ul: false,
            cl: false,
            st: false,
            eq: false,
            neq: false,
        };
    },
    // New Style Formatting
    styleAs: {
        // Highlighted
        new: (revHistory, n) => {
            let index = n ? n : 0;
            return this.newStyle(revHistory[index], {
                new: true,
                ul: true
            });
        },
        // Modified Style Formatting
        neq: (revHistory, n, m) => {
            let ltx = [];
            let newIndex = n ? n : 0;
            let oldIndex = m ? m : 0;
            ltx.push(this.newStyle(revHistory[oldIndex], {
                old: true,
                st: true
            }));
            ltx.push(this.newStyle(revHistory[newIndex], {
                new: true,
                ul: true,
                cl: true
            }));
            return ltx.join("");
        },
        // Removed Style Formatting
        old: (revHistory, n) => {
            let index = n ? n : 0;
            return this.newStyle(revHistory[index], {
                old: true,
                st: true
            });
        },
        // Equal (unchanged) Formatting
        eq: (v) => {
            return this.newStyle(v.curr, {
                eq: true
            });
        },
        // New (cleaned)
        newClean: (revHistory, n) => {
            let index = n ? n : 0;
            return this.newStyle(revHistory[index], {
                new: true,
                ul: true,
                cl: true
            });
        },
        // Modified (Cleaned)
        neqClean: (revHistory, n, m) => {
            let ltx = [];
            let newIndex = n ? n : 0;
            let oldIndex = m ? m : 0;
            ltx.push(this.newStyle(revHistory[oldIndex], {
                old: true,
                st: true,
                cl: true
            }));
            ltx.push(this.newStyle(revHistory[newIndex], {
                new: true,
                ul: true,
                cl: true
            }));
            return ltx.join("");
        },

        // Removed (Cleaned)
        oldClean: (revHistory, n) => {
            let index = n ? n : 0;
            return this.newStyle(revHistory[index], {
                old: true,
                st: true,
                cl: true
            });
        },

        // Equal (Cleaned)
        eqClean: (revHistory, n) => {
            let index = n ? n : 0;
            return this.newStyle(revHistory[index], {
                eq: true,
                cl: true
            });
        }
    },
    // Return Styled Result
    putRev: (revHistory, style, n, m) => {
        if (m) {
            return this.styleAs[style](revHistory, n, m);
        } else {
            return this.styleAs[style](revHistory, n);
        }
    },
    // Return Styled Result from Direct Input
    putRevD: (rev, style) => {
        return this.styleAs[style](rev, style, 0);
    },
}
module.exports = latexEngine;<|endoftext|>


<commit_before>'use strict';

var Harness = require('./support');
var customer = Harness.defineCustomerTable();
var post = Harness.definePostTable();

Harness.test({
  query: customer.select().where(customer.age.isNotNull()),
  pg: {
    text  : 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)',
    string: 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)'
  },
  sqlite: {
    text  : 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)',
    string: 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)'
  },
  mysql: {
    text  : 'SELECT `customer`.* FROM `customer` WHERE (`customer`.`age` IS NOT NULL)',
    string: 'SELECT `customer`.* FROM `customer` WHERE (`customer`.`age` IS NOT NULL)'
  },
  params: []
});

Harness.test({
  query: post.select().where(post.userId. in (customer.subQuery().select(customer.id).where(customer.age.isNull()))),
  pg: {
    text  : 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))',
    string: 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))'
  },
  sqlite: {
    text  : 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))',
    string: 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))'
  },
  mysql: {
    text  : 'SELECT `post`.* FROM `post` WHERE (`post`.`userId` IN (SELECT `customer`.`id` FROM `customer` WHERE (`customer`.`age` IS NULL)))',
    string: 'SELECT `post`.* FROM `post` WHERE (`post`.`userId` IN (SELECT `customer`.`id` FROM `customer` WHERE (`customer`.`age` IS NULL)))'
  },
  params: []
});
<commit_msg>Added unary-clause-tests for SqlServer.<commit_after>'use strict';

var Harness = require('./support');
var customer = Harness.defineCustomerTable();
var post = Harness.definePostTable();

Harness.test({
  query: customer.select().where(customer.age.isNotNull()),
  pg: {
    text  : 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)',
    string: 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)'
  },
  sqlite: {
    text  : 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)',
    string: 'SELECT "customer".* FROM "customer" WHERE ("customer"."age" IS NOT NULL)'
  },
  mysql: {
    text  : 'SELECT `customer`.* FROM `customer` WHERE (`customer`.`age` IS NOT NULL)',
    string: 'SELECT `customer`.* FROM `customer` WHERE (`customer`.`age` IS NOT NULL)'
  },
  sqlserver: {
    text  : 'SELECT [customer].* FROM [customer] WHERE ([customer].[age] IS NOT NULL)',
    string: 'SELECT [customer].* FROM [customer] WHERE ([customer].[age] IS NOT NULL)'
  },
  params: []
});

Harness.test({
  query: post.select().where(post.userId. in (customer.subQuery().select(customer.id).where(customer.age.isNull()))),
  pg: {
    text  : 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))',
    string: 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))'
  },
  sqlite: {
    text  : 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))',
    string: 'SELECT "post".* FROM "post" WHERE ("post"."userId" IN (SELECT "customer"."id" FROM "customer" WHERE ("customer"."age" IS NULL)))'
  },
  mysql: {
    text  : 'SELECT `post`.* FROM `post` WHERE (`post`.`userId` IN (SELECT `customer`.`id` FROM `customer` WHERE (`customer`.`age` IS NULL)))',
    string: 'SELECT `post`.* FROM `post` WHERE (`post`.`userId` IN (SELECT `customer`.`id` FROM `customer` WHERE (`customer`.`age` IS NULL)))'
  },
  sqlserver: {
    text  : 'SELECT [post].* FROM [post] WHERE ([post].[userId] IN (SELECT [customer].[id] FROM [customer] WHERE ([customer].[age] IS NULL)))',
    string: 'SELECT [post].* FROM [post] WHERE ([post].[userId] IN (SELECT [customer].[id] FROM [customer] WHERE ([customer].[age] IS NULL)))'
  },
  params: []
});
<|endoftext|>