<commit_before>/*globals $, brackets, define*/
define(function (require, exports, module) {
    "use strict";

    var _              = brackets.getModule("thirdparty/lodash"),
        AppInit        = brackets.getModule("utils/AppInit"),
        CommandManager = brackets.getModule("command/CommandManager"),
        Commands       = brackets.getModule("command/Commands"),
        ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
        Menus          = brackets.getModule("command/Menus"),
        NodeDomain     = brackets.getModule("utils/NodeDomain"),
        ProjectManager = brackets.getModule("project/ProjectManager");

    var _currentProject = null;

    var _DEFAULT_CONFIG = {
        hostname: "0.0.0.0",
        port: 3000
    };

    var DOMAIN_ID = "sbruchmann.staticdev";
    var DOMAIN_PATH = ExtensionUtils.getModulePath(module, "node/domain.js");

    var domain = new NodeDomain(DOMAIN_ID, DOMAIN_PATH);

    var CMD_STATIC_PREVIEW = "sbruchmann.staticpreview";

    var _isRunning = false;

    function _closeServer() {
        var command = CommandManager.get(CMD_STATIC_PREVIEW);
        var deferred = new $.Deferred();

        domain.exec("closeServer")
            .fail(deferred.reject.bind(deferred))
            .then(function _callback() {
                _isRunning = false;
                console.debug("[Static Preview] server closed.");
                command.setChecked(_isRunning);
                deferred.resolve();
            });

        return deferred.promise();
    }

    function _handleProjectClose(event, directory) {
        if (_isRunning) {
            _closeServer();
        }
    }

    function _handleProjectOpen(event, directory) {
        _currentProject = directory;
    }

    function _launchServer() {
        var command = CommandManager.get(CMD_STATIC_PREVIEW);
        var config = _.cloneDeep(_DEFAULT_CONFIG);
        var deferred = new $.Deferred();

        // Make sure that we have a reference to the current project
        if (!_currentProject) {
            _currentProject = ProjectManager.getProjectRoot();
        }

        config.basepath = _currentProject.fullPath;

        domain.exec("launchServer", config)
            .fail(function _errback(err) {
                console.error("[Static Preview]", err);
                deferred.reject(err);
            })
            .then(function _callback() {
                _isRunning = true;
                console.debug("[Static Preview] Launched server.", config);
                command.setChecked(_isRunning);
                deferred.resolve(config);
            });

        return deferred.promise();
    }

    function _toggleStaticPreview() {
        return _isRunning ? _closeServer() : _launchServer();
    }

    function _onAppReady() {
        var FILE_MENU = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);

        $(ProjectManager).on({
            "projectOpen": _handleProjectOpen,
            "projectClose": _handleProjectClose
        });

        CommandManager.register("Static Preview", CMD_STATIC_PREVIEW, _toggleStaticPreview);
        FILE_MENU.addMenuItem(
            CMD_STATIC_PREVIEW,
            null,
            Menus.AFTER,
            Commands.FILE_LIVE_FILE_PREVIEW
        );
    }

    AppInit.appReady(_onAppReady);
});
<commit_msg>Listen on project changes only when needed<commit_after>/*globals $, brackets, define*/
define(function (require, exports, module) {
    "use strict";

    var _              = brackets.getModule("thirdparty/lodash"),
        AppInit        = brackets.getModule("utils/AppInit"),
        CommandManager = brackets.getModule("command/CommandManager"),
        Commands       = brackets.getModule("command/Commands"),
        ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
        Menus          = brackets.getModule("command/Menus"),
        NodeDomain     = brackets.getModule("utils/NodeDomain"),
        ProjectManager = brackets.getModule("project/ProjectManager");

    var _currentProject = null;

    var _DEFAULT_CONFIG = {
        hostname: "0.0.0.0",
        port: 3000
    };

    var DOMAIN_ID = "sbruchmann.staticdev";
    var DOMAIN_PATH = ExtensionUtils.getModulePath(module, "node/domain.js");

    var domain = new NodeDomain(DOMAIN_ID, DOMAIN_PATH);

    var CMD_STATIC_PREVIEW = "sbruchmann.staticpreview";

    var _isRunning = false;

    function _closeServer() {
        var command = CommandManager.get(CMD_STATIC_PREVIEW);
        var deferred = new $.Deferred();

        domain.exec("closeServer")
            .fail(deferred.reject.bind(deferred))
            .then(function _callback() {
                _isRunning = false;
                console.debug("[Static Preview] server closed.");
                command.setChecked(_isRunning);
                deferred.resolve();
            });

        return deferred.promise();
    }

    function _handleProjectClose(event, directory) {
        if (_isRunning) {
            _closeServer();
        }

        $(ProjectManager).off("projectClose", _handleProjectClose);
    }

    function _handleProjectOpen(event, directory) {
        _currentProject = directory;
    }

    function _launchServer() {
        var command = CommandManager.get(CMD_STATIC_PREVIEW);
        var config = _.cloneDeep(_DEFAULT_CONFIG);
        var deferred = new $.Deferred();

        // Make sure that we have a reference to the current project
        if (!_currentProject) {
            _currentProject = ProjectManager.getProjectRoot();
        }

        config.basepath = _currentProject.fullPath;

        $(ProjectManager).on("projectClose", _handleProjectClose);

        domain.exec("launchServer", config)
            .fail(function _errback(err) {
                console.error("[Static Preview]", err);
                deferred.reject(err);
            })
            .then(function _callback() {
                _isRunning = true;
                console.debug("[Static Preview] Launched server.", config);
                command.setChecked(_isRunning);
                deferred.resolve(config);
            });

        return deferred.promise();
    }

    function _toggleStaticPreview() {
        return _isRunning ? _closeServer() : _launchServer();
    }

    function _onAppReady() {
        var FILE_MENU = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);

        $(ProjectManager).on("projectOpen", _handleProjectOpen);

        CommandManager.register("Static Preview", CMD_STATIC_PREVIEW, _toggleStaticPreview);
        FILE_MENU.addMenuItem(
            CMD_STATIC_PREVIEW,
            null,
            Menus.AFTER,
            Commands.FILE_LIVE_FILE_PREVIEW
        );
    }

    AppInit.appReady(_onAppReady);
});
<|endoftext|>


<commit_before>/**
 * @description A logging tool for node js.
 * @file main.js
 * @author Johannes Tegnér
 * @contributors Henrik Myntti
 */

module.exports = (function(){

  /**
   * Color codes for console output.
   */
  var colors = {
      textnormal: {
      black   : "\033[0;30m",
      red     : "\033[0;31m",
      green   : "\033[0;32m",
      yellow  : "\033[0;33m",
      blue    : "\033[0;34m",
      purple  : "\033[0;35m",
      cyan    : "\033[0;36m",
      white   : "\033[0;37m"
    }
    , textbold: {
      black   : "\033[1;30m",
      red     : "\033[1;31m",
      green   : "\033[1;32m",
      yellow  : "\033[1;33m",
      blue    : "\033[1;34m",
      purple  : "\033[1;35m",
      cyan    : "\033[1;36m",
      white   : "\0331;37m"
    }
    , textunderline: {
      black   : "\033[4;30m",
      red     : "\033[4;31m",
      green   : "\033[4;32m",
      yellow  : "\033[4;33m",
      blue    : "\033[4;34m",
      purple  : "\033[4;35m",
      cyan    : "\033[4;36m",
      white   : "\033[4;37m"
    }
    , background: {
      black   : "\033[40m",
      red     : "\033[41m",
      green   : "\033[42m",
      yellow  : "\033[43m",
      blue    : "\033[44m",
      purple  : "\033[45m",
      cyan    : "\033[46m",
      white   : "\033[47m"
    }
    , reset     : "\033[0m"
  };

  /**
   * Tag list and status.
   */
  var tags = {
      trace:    true
    , debug:    true
    , error:    true
    , warning:  true
    , info:     true
  };

  var util = require('util');

 /**
   * Print a debug string formatted as "(date) tag: string with %s|d|j values" where % values will be replaced with passed arguments.
   * @param {string} tag Tag to use.
   * @param {string} string String to print.
   * @param {string} color Color code.
   * @param {null|undefined|Array} args Arguments.
   */
  var print = function(tag, string, color, args) {
    if(args !== undefined && args !== null) {
      for(var i=0; i<args.length; i++){
        string = util.format(string, args[i]);
      }
    }
    util.print(color + tag + colors.reset + colors.textnormal.cyan + "\t(" + (new Date()).toLocaleTimeString() + "): " + color + string + colors.reset + "\n");
  };

  return {
    /**
     * Depth to use when iterating objects.
     */
    depth: 3,
    /**
     * Set one or many tags to active or inactive.
     * @param {boolean} value True if active, false if inactive.
     * @param {...} args Argument list, one or many string of which to set to given value.
     */
    set: function(value, args) {
      for(var i=1;i<arguments.length;i++){
        var tag = arguments[i].toLowerCase();
        if(tags[tag] !== undefined){
          tags[tag] = value;
        } else {
          print("error", "Failed to set tag " + tag + " to " + (value ? "Active" : "Inactive") + ", tag do not exist.", colors.textnormal.red, null);
        }
      }
    },
    /**
     * Get current state of given tag.
     * @param {string} tag Tag as string.
     * @return {boolean} If tag is active, true, else false.
     */
    get: function(tag) {
      tag = tag.toLowerCase();
      if(tags[tag] !== undefined){
        return tags[tag];
      } else {
        print("error", "Failed to get tag " + tag + ", tag do not exist.", colors.textnormal.red, null);
      }
      return false;
    },
    /**
     * Output arguments to trace log.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    trace: function(args) {
      if(!tags.trace) {
        return "trace";
      }
      util.print(colors.textnormal.cyan + "trace" + colors.reset + colors.textnormal.cyan + "\t(" + (new Date()).toLocaleTimeString() + "): " + colors.reset + "\n");
      for (var i = 0, il = arguments.length; i < il; i++) {
        util.print(colors.textnormal.cyan + "*\t" + colors.reset);
        util.print(colors.textnormal.white + util.inspect(arguments[i], { showHidden: true, depth: logger.depth }) + colors.reset);
        util.print("\n");
      }
      util.print(colors.textnormal.cyan + "end trace" + colors.reset + "\n");
      return "trace";
    },
    /**
     * Prints a debug string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    debug: function(str, args) {
      if(!tags.debug) {
        return "debug";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Debug", str,colors.textnormal.cyan, argList);
      return "debug";
    },
    /**
     * Prints a error string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    error: function(str, args) {
       if(!tags.error) {
        return "error";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Error", str, colors.textnormal.red, argList);
      return "error";
    },
    /**
     * Prints a warning string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    warning: function(str, args) {
       if(!tags.warning) {
        return "warning";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Warning", str, colors.textnormal.yellow, argList);
      return "warning";
    },
    /**
     * Prints a info string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    info: function(str, args) {
       if(!tags.info) {
        return "info";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Info", str, colors.textnormal.white, argList);
      return "info";
    }
  };
})();
<commit_msg>Changed debug color to blue from cyan.<commit_after>/**
 * @description A logging tool for node js.
 * @file main.js
 * @author Johannes Tegnér
 * @contributors Henrik Myntti
 */

module.exports = (function(){

  /**
   * Color codes for console output.
   */
  var colors = {
      textnormal: {
      black   : "\033[0;30m",
      red     : "\033[0;31m",
      green   : "\033[0;32m",
      yellow  : "\033[0;33m",
      blue    : "\033[0;34m",
      purple  : "\033[0;35m",
      cyan    : "\033[0;36m",
      white   : "\033[0;37m"
    }
    , textbold: {
      black   : "\033[1;30m",
      red     : "\033[1;31m",
      green   : "\033[1;32m",
      yellow  : "\033[1;33m",
      blue    : "\033[1;34m",
      purple  : "\033[1;35m",
      cyan    : "\033[1;36m",
      white   : "\0331;37m"
    }
    , textunderline: {
      black   : "\033[4;30m",
      red     : "\033[4;31m",
      green   : "\033[4;32m",
      yellow  : "\033[4;33m",
      blue    : "\033[4;34m",
      purple  : "\033[4;35m",
      cyan    : "\033[4;36m",
      white   : "\033[4;37m"
    }
    , background: {
      black   : "\033[40m",
      red     : "\033[41m",
      green   : "\033[42m",
      yellow  : "\033[43m",
      blue    : "\033[44m",
      purple  : "\033[45m",
      cyan    : "\033[46m",
      white   : "\033[47m"
    }
    , reset     : "\033[0m"
  };

  /**
   * Tag list and status.
   */
  var tags = {
      trace:    true
    , debug:    true
    , error:    true
    , warning:  true
    , info:     true
  };

  var util = require('util');

 /**
   * Print a debug string formatted as "(date) tag: string with %s|d|j values" where % values will be replaced with passed arguments.
   * @param {string} tag Tag to use.
   * @param {string} string String to print.
   * @param {string} color Color code.
   * @param {null|undefined|Array} args Arguments.
   */
  var print = function(tag, string, color, args) {
    if(args !== undefined && args !== null) {
      for(var i=0; i<args.length; i++){
        string = util.format(string, args[i]);
      }
    }
    util.print(color + tag + colors.reset + colors.textnormal.cyan + "\t(" + (new Date()).toLocaleTimeString() + "): " + color + string + colors.reset + "\n");
  };

  return {
    /**
     * Depth to use when iterating objects.
     */
    depth: 3,
    /**
     * Set one or many tags to active or inactive.
     * @param {boolean} value True if active, false if inactive.
     * @param {...} args Argument list, one or many string of which to set to given value.
     */
    set: function(value, args) {
      for(var i=1;i<arguments.length;i++){
        var tag = arguments[i].toLowerCase();
        if(tags[tag] !== undefined){
          tags[tag] = value;
        } else {
          print("error", "Failed to set tag " + tag + " to " + (value ? "Active" : "Inactive") + ", tag do not exist.", colors.textnormal.red, null);
        }
      }
    },
    /**
     * Get current state of given tag.
     * @param {string} tag Tag as string.
     * @return {boolean} If tag is active, true, else false.
     */
    get: function(tag) {
      tag = tag.toLowerCase();
      if(tags[tag] !== undefined){
        return tags[tag];
      } else {
        print("error", "Failed to get tag " + tag + ", tag do not exist.", colors.textnormal.red, null);
      }
      return false;
    },
    /**
     * Output arguments to trace log.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    trace: function(args) {
      if(!tags.trace) {
        return "trace";
      }
      util.print(colors.textnormal.cyan + "trace" + colors.reset + colors.textnormal.cyan + "\t(" + (new Date()).toLocaleTimeString() + "): " + colors.reset + "\n");
      for (var i = 0, il = arguments.length; i < il; i++) {
        util.print(colors.textnormal.cyan + "*\t" + colors.reset);
        util.print(colors.textnormal.white + util.inspect(arguments[i], { showHidden: true, depth: logger.depth }) + colors.reset);
        util.print("\n");
      }
      util.print(colors.textnormal.cyan + "end trace" + colors.reset + "\n");
      return "trace";
    },
    /**
     * Prints a debug string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    debug: function(str, args) {
      if(!tags.debug) {
        return "debug";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Debug", str,colors.textnormal.blue, argList);
      return "debug";
    },
    /**
     * Prints a error string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    error: function(str, args) {
       if(!tags.error) {
        return "error";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Error", str, colors.textnormal.red, argList);
      return "error";
    },
    /**
     * Prints a warning string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    warning: function(str, args) {
       if(!tags.warning) {
        return "warning";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Warning", str, colors.textnormal.yellow, argList);
      return "warning";
    },
    /**
     * Prints a info string to stdout.
     * The string uses % placeholders and replaces them with arguments passed.
     * Possible placeholders: %s - string, %d - number, %j json.
     * @param {string} str String to print.
     * @param {...} args Argument list.
     * @return {string} Tag name.
     */
    info: function(str, args) {
       if(!tags.info) {
        return "info";
      }
      var argList = [];
      if(args !== undefined) {
        argList = Array.prototype.slice.call(arguments, 1);
      }
      print("Info", str, colors.textnormal.white, argList);
      return "info";
    }
  };
})();
<|endoftext|>


<commit_before>const statusIcon = '●';
const request = 'Request Headers:
';
const response = 'Response Headers:
';
const statusline = 'Status Line:
';

const ext_version = 0.05;
var isCapture = true;

$(document).ready(function() {
	if (ext_version < version) {
		$('div#header hr').before(' | New version available!');
	}
});

chrome.experimental.webRequest.onSendHeaders.addListener(onSendHeaders, { }, ['requestHeaders']);

chrome.experimental.webRequest.onCompleted.addListener(function(details) {
	if (isCapture && !$('div#' + details.requestId)) {
		return;
	}
	if (isCapture) {
		var addCls;
		if (details.statusLine.match('404') || details.statusLine.match('400') || details.statusLine.match('403') || details.statusLine.match('405') || details.statusLine.match('406') || details.statusLine.match('401') || details.statusLine.match('500') || details.statusLine.match('502') || details.statusLine.match('503') || details.statusLine.match('504')) {
			addCls = 'error';
		} else {
			addCls = 'ok';
		}
		$('div#' + details.requestId).children('span.sent')
							.removeClass('sent')
							.addClass(addCls); // TODO

		var str = $('div#' + details.requestId).next().html();
		str = statusline + details.statusLine + '
' + str;
		str += response;

		for (var key in details.responseHeaders) {
			str += '' + text(details.responseHeaders[key].name) + ': ' + text(details.responseHeaders[key].value) + '
';
		}

		$('div#' + details.requestId).next().html(str);
	}
}, { }, ['statusLine', 'responseHeaders']);

chrome.experimental.webRequest.onErrorOccurred.addListener(function(details) {
	if (isCapture && !$('div#' + details.requestId)) {
		return;
	}
	if (isCapture) {
		$('div#' + details.requestId).children('span.sent')
							.removeClass('sent')
							.addClass('error');
		var str = $('div#' + details.requestId).next().html();
		str += '
Error:
' + details.error;
		$('div#' + details.requestId).next().html(str);
	}
}, { });

function text(str) {
	str = str.split('&').join('&'); //.replace('&', '&');
	str = str.split('"').join('"'); //.replace('"', '"');
	str = str.split('<').join('<'); //.replace('<', '<');
	str = str.split('>').join('>'); //.replace('>', '>');
	str = str.split("'").join('''); //.replace("'", ''');
	return str;
}

function onSendHeaders(details) {
	if (isCapture) {
		var str = '';
		for (var key in details.requestHeaders) {
			str += '' + text(details.requestHeaders[key].name) + ': ' + text(details.requestHeaders[key].value) + '
';
		}
		$('
').html(statusIcon + text(details.url))
				.addClass('caption')
				.attr('id', details.requestId)
				.click(function() {
					$(this).next().toggle();
				}).appendTo($('div#content'));//$(document.body));

		$('
').html(request + str)
				.addClass('detail')
				.css('display', 'none')
				.appendTo($('div#content'));//$(document.body));
		if ($('#as').attr('checked')) {
			_scroll($(document).height(), 0);
		}
	}
}

function _scroll(height, duration) {
	$(document.body).animate({scrollTop:height}, duration);
}<commit_msg>バージョン情報を修正<commit_after>const statusIcon = '●';
const request = 'Request Headers:
';
const response = 'Response Headers:
';
const statusline = 'Status Line:
';

const ext_version = 0.1;
var isCapture = true;

$(document).ready(function() {
	if (ext_version < version) {
		$('div#header hr').before(' | New version available!');
	}
});

chrome.experimental.webRequest.onSendHeaders.addListener(onSendHeaders, { }, ['requestHeaders']);

chrome.experimental.webRequest.onCompleted.addListener(function(details) {
	if (isCapture && !$('div#' + details.requestId)) {
		return;
	}
	if (isCapture) {
		var addCls;
		if (details.statusLine.match('404') || details.statusLine.match('400') || details.statusLine.match('403') || details.statusLine.match('405') || details.statusLine.match('406') || details.statusLine.match('401') || details.statusLine.match('500') || details.statusLine.match('502') || details.statusLine.match('503') || details.statusLine.match('504')) {
			addCls = 'error';
		} else {
			addCls = 'ok';
		}
		$('div#' + details.requestId).children('span.sent')
							.removeClass('sent')
							.addClass(addCls); // TODO

		var str = $('div#' + details.requestId).next().html();
		str = statusline + details.statusLine + '
' + str;
		str += response;

		for (var key in details.responseHeaders) {
			str += '' + text(details.responseHeaders[key].name) + ': ' + text(details.responseHeaders[key].value) + '
';
		}

		$('div#' + details.requestId).next().html(str);
	}
}, { }, ['statusLine', 'responseHeaders']);

chrome.experimental.webRequest.onErrorOccurred.addListener(function(details) {
	if (isCapture && !$('div#' + details.requestId)) {
		return;
	}
	if (isCapture) {
		$('div#' + details.requestId).children('span.sent')
							.removeClass('sent')
							.addClass('error');
		var str = $('div#' + details.requestId).next().html();
		str += '
Error:
' + details.error;
		$('div#' + details.requestId).next().html(str);
	}
}, { });

function text(str) {
	str = str.split('&').join('&'); //.replace('&', '&');
	str = str.split('"').join('"'); //.replace('"', '"');
	str = str.split('<').join('<'); //.replace('<', '<');
	str = str.split('>').join('>'); //.replace('>', '>');
	str = str.split("'").join('''); //.replace("'", ''');
	return str;
}

function onSendHeaders(details) {
	if (isCapture) {
		var str = '';
		for (var key in details.requestHeaders) {
			str += '' + text(details.requestHeaders[key].name) + ': ' + text(details.requestHeaders[key].value) + '
';
		}
		$('
').html(statusIcon + text(details.url))
				.addClass('caption')
				.attr('id', details.requestId)
				.click(function() {
					$(this).next().toggle();
				}).appendTo($('div#content'));//$(document.body));

		$('
').html(request + str)
				.addClass('detail')
				.css('display', 'none')
				.appendTo($('div#content'));//$(document.body));
		if ($('#as').attr('checked')) {
			_scroll($(document).height(), 0);
		}
	}
}

function _scroll(height, duration) {
	$(document.body).animate({scrollTop:height}, duration);
}<|endoftext|>


<commit_before>
var Mariaws = require("./mariawa.js")

Mariaws.log(arg("log"))

var stop = Mariaws.start({
  ws_port: arg("ws-port"),
  sql_port: arg("sql-port"),
  sql_host: arg("sql-host"),
  heartrate: arg("heartrate")
})

process.on("SIGINT", stop)
process.on("SIGTERM", stop)

function arg (name) {
  var key = name+"="
  for (var i=0; i<process.argv.length; i++) {
    if (process.argv[i].indexOf(key) === 0) {
      return process.argv[i].replace(key)
    }
  }
  return null
}
<commit_msg>just checking npm<commit_after>
var Mariaws = require("./mariawa.js")

Mariaws.log(arg("log"))

var stop = Mariaws.start({
  ws_port: arg("ws-port"),
  sql_port: arg("sql-port"),
  sql_host: arg("sql-host"),
  heartrate: arg("heartrate")
})

process.on("SIGINT", stop)
process.on("SIGTERM", stop)

function arg (name) {
  var key = name+"="
  for (var i=0; i<process.argv.length; i++) {
    if (process.argv[i].indexOf(key) === 0) {
      return process.argv[i].replace(key)
    }
  }
  return null
}
<|endoftext|>


<commit_before>var crc = require('crc').crc32;
var fs = require('fs');
var zlib = require('zlib');

function positiveNumberToBytes(number, bytes) {
  bytes = bytes || 4;
  var result = '';
  for(var i = 0; i < bytes; i++){
    result = String.fromCharCode(number % 256) + result;
    number = number / 256 | 0;
  }
  return result;
}

function chunk(type, data) {
  var length = positiveNumberToBytes(data.length, 4);
  return Buffer.concat([
      new Buffer(length, 'binary'),
      new Buffer(type + data, 'binary'),
      new Buffer(positiveNumberToBytes(crc(new Buffer(type + data, 'binary')), 4), 'binary')
  ]);
}

function compress(projectPath, payload, callback) {

  while(payload.length % 3) {
    payload += ' ';
  }

  var width = Math.ceil(Math.sqrt(payload.length / 3));
  var height = width;
  var padding = width * height - payload.length / 3;

  while(padding --> 0) {
    payload += '   ';
  }

  var fileSignature = new Buffer('\x89\x50\x4e\x47\x0d\x0a\x1a\x0a', 'binary');
  var IHDRChunk = chunk('IHDR',
    positiveNumberToBytes(width, 4) +
    positiveNumberToBytes(height, 4) +
    positiveNumberToBytes(8, 1) +
    positiveNumberToBytes(2, 1) +
    positiveNumberToBytes(0, 1) +
    positiveNumberToBytes(0, 1) +
    positiveNumberToBytes(0, 1));

  var customHtml = '';
  try {
    customHtml = fs.readFileSync(projectPath + '/index.html', {encoding: 'utf8'});
  } catch(e) {
    customHtml = fs.readFileSync(__dirname + '/index.html', {encoding: 'utf8'});
  }
  var html =
    customHtml +
    '<canvas class=hide height='+ height + ' width=' + width + '></canvas> 0) {
    payload = Buffer.concat([payload, new Buffer([0, 0, 0])]);
  }

  var fileSignature = new Buffer('\x89\x50\x4e\x47\x0d\x0a\x1a\x0a', 'binary');
  var IHDRChunk = chunk('IHDR', Buffer.concat([
    positiveNumberToBytes(width, 4),
    positiveNumberToBytes(height, 4),
    positiveNumberToBytes(8, 1),
    positiveNumberToBytes(2, 1),
    positiveNumberToBytes(0, 1),
    positiveNumberToBytes(0, 1),
    positiveNumberToBytes(0, 1)
  ]));

  var customHtml = '';
  try {
    customHtml = fs.readFileSync(projectPath + '/index.html', {encoding: 'utf8'});
  } catch(e) {
    customHtml = fs.readFileSync(__dirname + '/index.html', {encoding: 'utf8'});
  }
  var html =
    customHtml +
    '<canvas class=hide height='+ height + ' width=' + width + '></canvas>


<commit_before>/**
* https://node-postgres.com/
*
*/

const http = require('http');
const { Pool, Client } = require('pg');

const pool = new Pool({
  user: '',
  host: '127.0.0.1',
  database: '',
  password: '',
  port: 5432,
});

const hostname="127.0.0.1";
const port = 3000;

const server = http.createServer((req,res) => {

  res.statusCode= 200;
  res.setHeader('Content-type','application/json');

  pool.query('SELECT * FROM mvbusquedas LIMIT 100',(err,result) => {
    if(err){
      throw err;
    }
    res.write(JSON.stringify(result));
  }
  pool.end();
  res.end();
});

server.listen(port,hostname, () => {
  console.log(hostname+':'+port);
});
<commit_msg>Correciones primer versión que tira de SQL a json<commit_after>/**
* https://node-postgres.com/
*
*/

const http = require('http');
const { Pool, Client } = require('pg');

const pool = new Pool({
	  user: 'userrenic',
  host: '127.0.0.1',
  database: 'nuevadbrenic',
  password: '',
  port: 5432
});

const hostname="127.0.0.1";
const port = 3000;

const server = http.createServer((req,res) => {

  res.statusCode= 200;
  res.setHeader('Content-type','application/json');

  pool.query('SELECT * FROM mvbusquedas LIMIT 100',(err,result) => {
    res.write(JSON.stringify(result));
    res.end();
  });
  pool.end();
});

server.listen(port,hostname, () => {
  console.log(hostname+':'+port);
});
<|endoftext|>


<commit_before>/*** Map ***/

var styles = {
    "daycycle": "daynight.yaml",

    "highways": "//cdn.rawgit.com/tangrams/highways-demo/a95a428fad9adcf07df1118c859e317c52e1b5c1/scene.yaml",

    "halftone": "halftone.yaml",

    "tron": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/tron.yaml",

    "crosshatch": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/crosshatch.yaml",

    "glitter": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/specular-dust.yaml",

    "traditional": "traditional.yaml"
};

var currentStyle = "daycycle";
var qs = window.location.search;
if (qs) {
    qs = qs.slice(1);
    if (qs[qs.length-1] === '/') {
        qs = qs.slice(0, qs.length-1);
    }
    if (styles[qs]) {
        currentStyle = qs;
    }
}

var map = L.map('map',
    {'keyboardZoomOffset': .05}
);

var layer = Tangram.leafletLayer({
    scene: styles[currentStyle],
    preUpdate: preUpdate,
    postUpdate: postUpdate,
    attribution: 'Tangram | © OSM contributors | Mapzen'
});

var scene = layer.scene;

layer.on('init', function() {
   // everything's good, carry on
  window.addEventListener('resize', resizeMap);
  resizeMap();
});

layer.on('error', function(error) {
  // something went wrong
  var errorEL = document.createElement('div');
  errorEL.setAttribute("class", "error-msg");
     // WebGL not supported (or at least didn't initialize properly!)
  if (layer.scene && !layer.scene.gl) {
    var noticeTxt = document.createTextNode("Your browser doesn't support WebGL. Please try with recent Firefox or Chrome, Tangram is totally worth it.");
    errorEL.appendChild(noticeTxt);
   }
   // Something else went wrong, generic error message
   else {
    var noticeTxt = document.createTextNode("We are sorry, but something went wrong, please try later.");
    errorEL.appendChild(noticeTxt);
   }
   document.body.appendChild(errorEL);
});

layer.addTo(map);

// leaflet-style URL hash pattern:
// ?style.yaml#[zoom],[lat],[lng]
var map_start_location = [40.7076, -74.0094, 15];
var url_hash = window.location.hash.slice(1).split('/');
if (url_hash.length === 3) {
    map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
    // convert from strings
    map_start_location = map_start_location.map(Number);
}

map.setView(map_start_location.slice(0, 2), map_start_location[2]);

var hash = new L.Hash(map);

// Resize map to window
function resizeMap() {
    document.getElementById('map').style.width = window.innerWidth + 'px';
    document.getElementById('map').style.height = window.innerHeight + 'px';
    map.invalidateSize(false);
}

function switchStyles(style) {
    currentStyle = style;
    layer.scene.reload(styles[style]);
}

function preUpdate(will_render) {
    if (!will_render) {
        return;
    }

    switch(currentStyle) {
        case "daycycle":
            daycycle();
            break;
    }
}

function postUpdate() {
}

function daycycle() {
    d = new Date();
    t = d.getTime()/10000;

    x = Math.sin(t);
    y = Math.sin(t+(3.14159/2)); // 1/4 offset
    z = Math.sin(t+(3.14159)); // 1/2 offset

    scene.camera.axis = {x: x, y: y};

    // offset blue and red for sunset and moonlight effect
    B = x + Math.abs(Math.sin(t+(3.14159*.5)))/4;
    R = y + Math.abs(Math.sin(t*2))/4;

    scene.lights.sun.diffuse = [R, y, B, 1];
    scene.lights.sun.direction = [x, 1, -.5];

    px = Math.min(x, 0); // positive x
    py = Math.min(y, 0); // positive y
    // light up the roads at night
    scene.styles["roads"].material.emission.amount = [-py, -py, -py, 1];
    // turn water black at night
    scene.styles["water"].material.ambient.amount = [py+1, py+1, py+1, 1];
    scene.styles["water"].material.diffuse.amount = [py+1, py+1, py+1, 1];

    // turn up buildings' ambient response at night
    ba = -py*.75+.75;
    scene.styles["buildings"].material.ambient.amount = [ba, ba, ba, 1];

    scene.animated = true;
}

// iFrame integration
window.addEventListener("DOMContentLoaded", function() {

  if (window.self !== window.top) {
    //disable scroll zoom if it is iframed
    map.scrollWheelZoom.disable();
    //sending message that child frame is ready to parent window
    window.parent.postMessage("loaded", "*");
    window.addEventListener("message", function(e) {
      switchStyles(e.data);
    }, false);
  }else{

    }
}, false);
<commit_msg>only set style if it's valid<commit_after>/*** Map ***/

var styles = {
    "daycycle": "daynight.yaml",

    "highways": "//cdn.rawgit.com/tangrams/highways-demo/a95a428fad9adcf07df1118c859e317c52e1b5c1/scene.yaml",

    "halftone": "halftone.yaml",

    "tron": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/tron.yaml",

    "crosshatch": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/crosshatch.yaml",

    "glitter": "//cdn.rawgit.com/tangrams/tangram-sandbox/dac373596f80065d6e77ec4f6fc7c5541fcb3775/styles/specular-dust.yaml",

    "traditional": "traditional.yaml"
};

var currentStyle = "daycycle";
var qs = window.location.search;
if (qs) {
    qs = qs.slice(1);
    if (qs[qs.length-1] === '/') {
        qs = qs.slice(0, qs.length-1);
    }
    if (styles[qs]) {
        currentStyle = qs;
    }
}

var map = L.map('map',
    {'keyboardZoomOffset': .05}
);

var layer = Tangram.leafletLayer({
    scene: styles[currentStyle],
    preUpdate: preUpdate,
    postUpdate: postUpdate,
    attribution: 'Tangram | © OSM contributors | Mapzen'
});

var scene = layer.scene;

layer.on('init', function() {
   // everything's good, carry on
  window.addEventListener('resize', resizeMap);
  resizeMap();
});

layer.on('error', function(error) {
  // something went wrong
  var errorEL = document.createElement('div');
  errorEL.setAttribute("class", "error-msg");
     // WebGL not supported (or at least didn't initialize properly!)
  if (layer.scene && !layer.scene.gl) {
    var noticeTxt = document.createTextNode("Your browser doesn't support WebGL. Please try with recent Firefox or Chrome, Tangram is totally worth it.");
    errorEL.appendChild(noticeTxt);
   }
   // Something else went wrong, generic error message
   else {
    var noticeTxt = document.createTextNode("We are sorry, but something went wrong, please try later.");
    errorEL.appendChild(noticeTxt);
   }
   document.body.appendChild(errorEL);
});

layer.addTo(map);

// leaflet-style URL hash pattern:
// ?style.yaml#[zoom],[lat],[lng]
var map_start_location = [40.7076, -74.0094, 15];
var url_hash = window.location.hash.slice(1).split('/');
if (url_hash.length === 3) {
    map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
    // convert from strings
    map_start_location = map_start_location.map(Number);
}

map.setView(map_start_location.slice(0, 2), map_start_location[2]);

var hash = new L.Hash(map);

// Resize map to window
function resizeMap() {
    document.getElementById('map').style.width = window.innerWidth + 'px';
    document.getElementById('map').style.height = window.innerHeight + 'px';
    map.invalidateSize(false);
}

function switchStyles(style) {
    if (styles[style]) {
        currentStyle = style;
        layer.scene.reload(styles[currentStyle]);
    }
}

function preUpdate(will_render) {
    if (!will_render) {
        return;
    }

    switch(currentStyle) {
        case "daycycle":
            daycycle();
            break;
    }
}

function postUpdate() {
}

function daycycle() {
    d = new Date();
    t = d.getTime()/10000;

    x = Math.sin(t);
    y = Math.sin(t+(3.14159/2)); // 1/4 offset
    z = Math.sin(t+(3.14159)); // 1/2 offset

    scene.camera.axis = {x: x, y: y};

    // offset blue and red for sunset and moonlight effect
    B = x + Math.abs(Math.sin(t+(3.14159*.5)))/4;
    R = y + Math.abs(Math.sin(t*2))/4;

    scene.lights.sun.diffuse = [R, y, B, 1];
    scene.lights.sun.direction = [x, 1, -.5];

    px = Math.min(x, 0); // positive x
    py = Math.min(y, 0); // positive y
    // light up the roads at night
    scene.styles["roads"].material.emission.amount = [-py, -py, -py, 1];
    // turn water black at night
    scene.styles["water"].material.ambient.amount = [py+1, py+1, py+1, 1];
    scene.styles["water"].material.diffuse.amount = [py+1, py+1, py+1, 1];

    // turn up buildings' ambient response at night
    ba = -py*.75+.75;
    scene.styles["buildings"].material.ambient.amount = [ba, ba, ba, 1];

    scene.animated = true;
}

// iFrame integration
window.addEventListener("DOMContentLoaded", function() {

  if (window.self !== window.top) {
    //disable scroll zoom if it is iframed
    map.scrollWheelZoom.disable();
    //sending message that child frame is ready to parent window
    window.parent.postMessage("loaded", "*");
    window.addEventListener("message", function(e) {
      switchStyles(e.data);
    }, false);
  }else{

    }
}, false);
<|endoftext|>


<commit_before>
module.exports = (type) => {
  function prefix(n2k, state) {
    return `electrical.${type}.${state.deviceInstance || 0}.total`
  }
  return [
    {
      node: function (n2k, state) {
        return `${prefix(n2k, state)}.energyExport`
      },
      value: (n2k) => {
        return n2k.fields['Total Energy Export'] * 3.6e+6
      },
      filter: (n2k, state) => {
        return n2k.fields['Total Energy Export'] != null &&
          state.deviceInstance != null
      }
    },
    {
      node: function (n2k, state) {
        return `${prefix(n2k, state)}.energyImport`
      },
      value: (n2k) => {
        return n2k.fields['Total Energy Import'] * 3.6e+6
      },
      filter: (n2k, state) => {
        return n2k.fields['Total Energy Import'] != null &&
          state.deviceInstance != null
      }
    }
  ]
}
<commit_msg>fix: removes conversion of totalEnergy to joules (#210)<commit_after>
module.exports = (type) => {
  function prefix(n2k, state) {
    return `electrical.${type}.${state.deviceInstance || 0}.total`
  }
  return [
    {
      node: function (n2k, state) {
        return `${prefix(n2k, state)}.energyExport`
      },
      value: (n2k) => {
        return n2k.fields['Total Energy Export']
      },
      filter: (n2k, state) => {
        return n2k.fields['Total Energy Export'] != null &&
          state.deviceInstance != null
      }
    },
    {
      node: function (n2k, state) {
        return `${prefix(n2k, state)}.energyImport`
      },
      value: (n2k) => {
        return n2k.fields['Total Energy Import']
      },
      filter: (n2k, state) => {
        return n2k.fields['Total Energy Import'] != null &&
          state.deviceInstance != null
      }
    }
  ]
}
<|endoftext|>


<commit_before>'use strict';

var pike = {
  store: '1st and Pike',
  minCust: 23,
  maxCust: 65,
  cookies: [], // initialize cookies per hour array
  avgCookies: 6.3,
  totalCookies: 0,
  timeOfDay: ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'],
  // generate random method
  generateRandom: function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  },
  // cookies per hour method
  cookiesPerHour: function() {
    for (var i = 0; i < this.timeOfDay.length; i++) {

      var hourly = Math.floor(this.generateRandom() * this.avgCookies);
      console.log('Cookies per hour', hourly);
      this.cookies.push(hourly); // store cookies per hour in array
    }
  },
  // cookies per day method
  cookiesPerDay: function() {
    for (var j = 0; j < this.cookies.length; j++) {
      this.totalCookies += this.cookies[j];
      console.log('Total cookies:', this.totalCookies);
    }
    return this.totalCookies; // this code may not be neccessary since this function updates a variable
  },
  // method to render list to browser
  render: function() {
    // calls previous methods so their output is usable in the render function
    pike.cookiesPerHour();
    pike.cookiesPerDay();
    // create new elements
    var main = document.getElementById('store_info');
    var h2 = document.createElement('h2');
    var ul = document.createElement('ul');
    // adds header
    h2.textContent = this.store;
    main.appendChild(ul);
    // adds list to page under h2
    ul.appendChild(h2);
    // loops through each hour, adding list items
    for (var k = 0; k <= this.cookies.length; k++) {
      var li = document.createElement('li');
      li.textContent = this.timeOfDay[k] + ': ' + this.cookies[k] + ' cookies';
      ul.appendChild(li);
    }
    // adds list item for total cookies
    li.textContent = 'Total: ' + this.totalCookies + ' cookies';

    console.log('Total:', this.totalCookies);
  }
};
pike.render();
<commit_msg>added remaining stores as objects<commit_after>'use strict';

// 1st and Pike
var pike = {
  store: '1st and Pike',
  minCust: 23,
  maxCust: 65,
  cookies: [], // initialize cookies per hour array
  avgCookies: 6.3,
  totalCookies: 0,
  timeOfDay: ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'],
  // generate random method
  generateRandom: function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  },
  // cookies per hour method
  cookiesPerHour: function() {
    for (var i = 0; i < this.timeOfDay.length; i++) {

      var hourly = Math.floor(this.generateRandom() * this.avgCookies);
      console.log('Cookies per hour', hourly);
      this.cookies.push(hourly); // store cookies per hour in array
    }
  },
  // cookies per day method
  cookiesPerDay: function() {
    for (var j = 0; j < this.cookies.length; j++) {
      this.totalCookies += this.cookies[j];
      console.log('Total cookies:', this.totalCookies);
    }
    return this.totalCookies; // this code may not be neccessary since this function updates a variable
  },
  // method to render list to browser
  render: function() {
    // calls previous methods so their output is usable in the render function
    pike.cookiesPerHour();
    pike.cookiesPerDay();
    // create new elements
    var main = document.getElementById('store_info');
    var h2 = document.createElement('h2');
    var ul = document.createElement('ul');
    // adds header
    h2.textContent = this.store;
    main.appendChild(ul);
    // adds list to page under h2
    ul.appendChild(h2);
    // loops through each hour, adding list items
    for (var k = 0; k <= this.cookies.length; k++) {
      var li = document.createElement('li');
      li.textContent = this.timeOfDay[k] + ': ' + this.cookies[k] + ' cookies';
      ul.appendChild(li);
    }
    // adds list item for total cookies
    li.textContent = 'Total: ' + this.totalCookies + ' cookies';

    console.log('Total:', this.totalCookies);
  }
};
pike.render();

// SeaTac Airport
var seaTac = {
  store: 'SeaTac Airport',
  minCust: 3,
  maxCust: 24,
  avgCookies: 1.2,
  cookies: [], // initialize cookies per hour array
  totalCookies: 0,
  timeOfDay: ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'],
  // generate random method
  generateRandom: function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  },
  // cookies per hour method
  cookiesPerHour: function() {
    for (var i = 0; i < this.timeOfDay.length; i++) {

      var hourly = Math.floor(this.generateRandom() * this.avgCookies);
      console.log('Cookies per hour', hourly);
      this.cookies.push(hourly); // store cookies per hour in array
    }
  },
  // cookies per day method
  cookiesPerDay: function() {
    for (var j = 0; j < this.cookies.length; j++) {
      this.totalCookies += this.cookies[j];
      console.log('Total cookies:', this.totalCookies);
    }
    return this.totalCookies; // this code may not be neccessary since this function updates a variable
  },
  // method to render list to browser
  render: function() {
    // calls previous methods so their output is usable in the render function
    seaTac.cookiesPerHour();
    seaTac.cookiesPerDay();
    // create new elements
    var main = document.getElementById('store_info');
    var h2 = document.createElement('h2');
    var ul = document.createElement('ul');
    // adds header
    h2.textContent = this.store;
    main.appendChild(ul);
    // adds list to page under h2
    ul.appendChild(h2);
    // loops through each hour, adding list items
    for (var k = 0; k <= this.cookies.length; k++) {
      var li = document.createElement('li');
      li.textContent = this.timeOfDay[k] + ': ' + this.cookies[k] + ' cookies';
      ul.appendChild(li);
    }
    // adds list item for total cookies
    li.textContent = 'Total: ' + this.totalCookies + ' cookies';

    console.log('Total:', this.totalCookies);
  }
};
seaTac.render();

// Seattle Center
var seattleCenter = {
  store: 'Seattle Center',
  minCust: 11,
  maxCust: 38,
  avgCookies: 3.7,
  cookies: [], // initialize cookies per hour array
  totalCookies: 0,
  timeOfDay: ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'],
  // generate random method
  generateRandom: function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  },
  // cookies per hour method
  cookiesPerHour: function() {
    for (var i = 0; i < this.timeOfDay.length; i++) {

      var hourly = Math.floor(this.generateRandom() * this.avgCookies);
      console.log('Cookies per hour', hourly);
      this.cookies.push(hourly); // store cookies per hour in array
    }
  },
  // cookies per day method
  cookiesPerDay: function() {
    for (var j = 0; j < this.cookies.length; j++) {
      this.totalCookies += this.cookies[j];
      console.log('Total cookies:', this.totalCookies);
    }
    return this.totalCookies; // this code may not be neccessary since this function updates a variable
  },
  // method to render list to browser
  render: function() {
    // calls previous methods so their output is usable in the render function
    seattleCenter.cookiesPerHour();
    seattleCenter.cookiesPerDay();
    // create new elements
    var main = document.getElementById('store_info');
    var h2 = document.createElement('h2');
    var ul = document.createElement('ul');
    // adds header
    h2.textContent = this.store;
    main.appendChild(ul);
    // adds list to page under h2
    ul.appendChild(h2);
    // loops through each hour, adding list items
    for (var k = 0; k <= this.cookies.length; k++) {
      var li = document.createElement('li');
      li.textContent = this.timeOfDay[k] + ': ' + this.cookies[k] + ' cookies';
      ul.appendChild(li);
    }
    // adds list item for total cookies
    li.textContent = 'Total: ' + this.totalCookies + ' cookies';

    console.log('Total:', this.totalCookies);
  }
};
seattleCenter.render();

// Capitol Hill
var capitolHill = {
  store: 'Capitol Hill',
  minCust: 20,
  maxCust: 38,
  avgCookies: 2.3,
  cookies: [], // initialize cookies per hour array
  totalCookies: 0,
  timeOfDay: ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'],
  // generate random method
  generateRandom: function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  },
  // cookies per hour method
  cookiesPerHour: function() {
    for (var i = 0; i < this.timeOfDay.length; i++) {

      var hourly = Math.floor(this.generateRandom() * this.avgCookies);
      console.log('Cookies per hour', hourly);
      this.cookies.push(hourly); // store cookies per hour in array
    }
  },
  // cookies per day method
  cookiesPerDay: function() {
    for (var j = 0; j < this.cookies.length; j++) {
      this.totalCookies += this.cookies[j];
      console.log('Total cookies:', this.totalCookies);
    }
    return this.totalCookies; // this code may not be neccessary since this function updates a variable
  },
  // method to render list to browser
  render: function() {
    // calls previous methods so their output is usable in the render function
    capitolHill.cookiesPerHour();
    capitolHill.cookiesPerDay();
    // create new elements
    var main = document.getElementById('store_info');
    var h2 = document.createElement('h2');
    var ul = document.createElement('ul');
    // adds header
    h2.textContent = this.store;
    main.appendChild(ul);
    // adds list to page under h2
    ul.appendChild(h2);
    // loops through each hour, adding list items
    for (var k = 0; k <= this.cookies.length; k++) {
      var li = document.createElement('li');
      li.textContent = this.timeOfDay[k] + ': ' + this.cookies[k] + ' cookies';
      ul.appendChild(li);
    }
    // adds list item for total cookies
    li.textContent = 'Total: ' + this.totalCookies + ' cookies';

    console.log('Total:', this.totalCookies);
  }
};
capitolHill.render();

// Alki
var alki = {
  store: 'Alki',
  minCust: 2,
  maxCust: 16,
  avgCookies: 4.6,
  cookies: [], // initialize cookies per hour array
  totalCookies: 0,
  timeOfDay: ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'],
  // generate random method
  generateRandom: function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  },
  // cookies per hour method
  cookiesPerHour: function() {
    for (var i = 0; i < this.timeOfDay.length; i++) {

      var hourly = Math.floor(this.generateRandom() * this.avgCookies);
      console.log('Cookies per hour', hourly);
      this.cookies.push(hourly); // store cookies per hour in array
    }
  },
  // cookies per day method
  cookiesPerDay: function() {
    for (var j = 0; j < this.cookies.length; j++) {
      this.totalCookies += this.cookies[j];
      console.log('Total cookies:', this.totalCookies);
    }
    return this.totalCookies; // this code may not be neccessary since this function updates a variable
  },
  // method to render list to browser
  render: function() {
    // calls previous methods so their output is usable in the render function
    alki.cookiesPerHour();
    alki.cookiesPerDay();
    // create new elements
    var main = document.getElementById('store_info');
    var h2 = document.createElement('h2');
    var ul = document.createElement('ul');
    // adds header
    h2.textContent = this.store;
    main.appendChild(ul);
    // adds list to page under h2
    ul.appendChild(h2);
    // loops through each hour, adding list items
    for (var k = 0; k <= this.cookies.length; k++) {
      var li = document.createElement('li');
      li.textContent = this.timeOfDay[k] + ': ' + this.cookies[k] + ' cookies';
      ul.appendChild(li);
    }
    // adds list item for total cookies
    li.textContent = 'Total: ' + this.totalCookies + ' cookies';

    console.log('Total:', this.totalCookies);
  }
};
alki.render();
<|endoftext|>


<commit_before>import vendorLinker from './vendorLinker';
import ns from './namespace';
import ObjectContainer from './ObjectContainer';
import Bootstrap from './Bootstrap';

import { init as initBindIma } from 'ima/config/bind';
import { init as initServicesIma } from 'ima/config/services';

function getInitialImaConfigFunctions() {
	return { initBindIma, initServicesIma };
}

function getNamespace() {
	return ns;
}

function getInitialPluginConfig() {
	return { plugins: vendorLinker.getImaPlugins() };
}

function _getRoot() {
	return _isClient() ? window : global;
}

function _isClient() {
	return typeof window !== 'undefined' && window !== null;
}

function createImaApp() {
	let oc = new ObjectContainer(ns);
	let bootstrap = new Bootstrap(oc);

	return { oc, bootstrap };
}

function getClientBootConfig(initialAppConfigFunctions) {
	let root = _getRoot();

	if ($Debug && _isClient()) {
		if ($IMA.$Protocol !== root.location.protocol) {
			throw new Error(`Your client's protocol is not same as server's ` +
					`protocol. For right setting protocol on the server ` +
					`site set 'X-Forwarded-Proto' header.`);
		}

		if ($IMA.$Host !== root.location.host) {
			throw new Error(`Your client's host is not same as server's ` +
					`host. For right setting host on the server site set ` +
					`'X-Forwarded-Host' header.`);
		}
	}

	let bootConfig = {
		services: {
			respond: null,
			request: null,
			$IMA: $IMA,
			dictionary: {
				$Language: $IMA.$Language,
				dictionary: $IMA.i18n
			},
			router: {
				$Protocol: $IMA.$Protocol,
				$Host: $IMA.$Host,
				$Root: $IMA.$Root,
				$LanguagePartPath: $IMA.$LanguagePartPath
			}
		},
		settings: {
			$Debug: $IMA.$Debug,
			$Env: $IMA.$Env,
			$Version: $IMA.$Version,
			$App: $IMA.$App,
			$Protocol: $IMA.$Protocol,
			$Language: $IMA.$Language,
			$Host: $IMA.$Host,
			$Root: $IMA.$Root,
			$LanguagePartPath: $IMA.$LanguagePartPath
		}
	};

	return Object.assign(
		bootConfig,
		initialAppConfigFunctions,
		getInitialPluginConfig(),
		getInitialImaConfigFunctions()
	);
}

function getTestClientBootConfig(initialAppConfigFunctions) {
	let root = _getRoot();
	$IMA.$Debug = true;
	root.$Debug = $IMA.$Debug;

	let bootConfig = {
		services: {
			respond: null,
			request: null,
			$IMA: $IMA,
			dictionary: {
				$Language: $IMA.$Language,
				dictionary: $IMA.i18n
			},
			router: {
				$Host: $IMA.$Host,
				$Root: $IMA.$Root,
				$LanguagePartPath: $IMA.$LanguagePartPath
			}
		},
		settings: {
			$Env: 'dev',
			$Language: 'en',
			$Protocol: 'http:',
			$Debug: $IMA.$Debug,
			$App: {}
		},
		plugins: []
	};

	return Object.assign(
		bootConfig,
		initialAppConfigFunctions,
		getInitialPluginConfig(),
		getInitialImaConfigFunctions()
	);
}

function bootClientApp(app, bootConfig) {
	app.bootstrap.run(bootConfig);

	let cache = app.oc.get('$Cache');
	cache.deserialize($IMA.Cache || {});

	return app;
}

function routeClientApp(app) {
	let router = app.oc.get('$Router');

	return router
		.listen()
		.route(router.getPath())
		.catch((error) => {
			if (typeof $IMA.fatalErrorHandler === 'function') {
				$IMA.fatalErrorHandler(error);
			} else {
				console.warn('Define function config.$IMA.fatalErrorHandler ' +
						'in services.js.');
			}
		});
}

function hotReloadClientApp(initialAppConfigFunctions) {
	if (!$Debug) {
		return;
	}

	let app = createImaApp();
	let bootConfig = getClientBootConfig(initialAppConfigFunctions);
	app = bootClientApp(app, bootConfig);

	let router = app.oc.get('$Router');
	let pageManager = app.oc.get('$PageManager');
	let currentRouteInfo = router.getCurrentRouteInfo();
	let currentRoute = currentRouteInfo.route;
	let currentRouteOptions = Object.assign(
		{},
		currentRoute.getOptions(),
		{
			onlyUpdate: false,
			autoScroll: false,
			allowSPA: false
		}
	);

	router.listen();

	try {
		return pageManager
			.manage(
				currentRoute.getController(),
				currentRoute.getView(),
				currentRouteOptions,
				currentRouteInfo.params
			)
			.catch((error) => {
				return router.handleError({ error });
			})
			.catch((error) => {
				if (typeof $IMA.fatalErrorHandler === 'function') {
					$IMA.fatalErrorHandler(error);
				} else {
					console.warn('Define function ' +
							'config.$IMA.fatalErrorHandler in services.js.');
				}
			});
	} catch (error) {
		return router.handleError({ error });
	}
}

function reviveClientApp (initialAppConfigFunctions) {
	let root = _getRoot();

	if (_isClient()) {
		// hack for the Chrome browser, which sometimes has problems with
		// rendering the page
		document.body.style.display = 'none';
		document.body.offsetHeight; //eslint-disable-line
		document.body.style.display = '';
	}

	//set React for ReactJS extension for browser
	root.React = vendorLinker.get('react');
	root.$Debug = root.$IMA.$Debug;

	let app = createImaApp();
	let bootConfig = getClientBootConfig(initialAppConfigFunctions);
	app = bootClientApp(app, bootConfig);

	return routeClientApp(app);
}

function reviveTestClientApp(initialAppConfigFunctions) {
	let root = _getRoot();
	let app = createImaApp();
	let bootConfig = getTestClientBootConfig(initialAppConfigFunctions);

	app = bootClientApp(app, bootConfig);

	root.ns = ns;
	root.oc = app.oc;
}

function onLoad(callback) {
	if (!_isClient()) {
		return;
	}

	if (
		(document.readyState === 'complete') ||
		(document.readyState === 'interactive')
	) {
		$IMA.Loader.initAllModules()
			.then(callback)
			.catch((error) => {
				console.error(error);
			});
	} else {
		window.addEventListener('DOMContentLoaded', () => {
			$IMA.Loader.initAllModules()
				.then(callback)
				.catch((error) => {
					console.error(error);
				});
		});
	}
}

vendorLinker.bindToNamespace(ns);

export {
	getInitialImaConfigFunctions,
	getNamespace,
	getInitialPluginConfig,
	createImaApp,
	getClientBootConfig,
	getTestClientBootConfig,
	bootClientApp,
	routeClientApp,
	hotReloadClientApp,
	reviveClientApp,
	reviveTestClientApp,
	onLoad
};
<commit_msg>#! IMA onLoad mehtod returns promise<commit_after>import vendorLinker from './vendorLinker';
import ns from './namespace';
import ObjectContainer from './ObjectContainer';
import Bootstrap from './Bootstrap';

import { init as initBindIma } from 'ima/config/bind';
import { init as initServicesIma } from 'ima/config/services';

function getInitialImaConfigFunctions() {
	return { initBindIma, initServicesIma };
}

function getNamespace() {
	return ns;
}

function getInitialPluginConfig() {
	return { plugins: vendorLinker.getImaPlugins() };
}

function _getRoot() {
	return _isClient() ? window : global;
}

function _isClient() {
	return typeof window !== 'undefined' && window !== null;
}

function createImaApp() {
	let oc = new ObjectContainer(ns);
	let bootstrap = new Bootstrap(oc);

	return { oc, bootstrap };
}

function getClientBootConfig(initialAppConfigFunctions) {
	let root = _getRoot();

	if ($Debug && _isClient()) {
		if ($IMA.$Protocol !== root.location.protocol) {
			throw new Error(`Your client's protocol is not same as server's ` +
					`protocol. For right setting protocol on the server ` +
					`site set 'X-Forwarded-Proto' header.`);
		}

		if ($IMA.$Host !== root.location.host) {
			throw new Error(`Your client's host is not same as server's ` +
					`host. For right setting host on the server site set ` +
					`'X-Forwarded-Host' header.`);
		}
	}

	let bootConfig = {
		services: {
			respond: null,
			request: null,
			$IMA: $IMA,
			dictionary: {
				$Language: $IMA.$Language,
				dictionary: $IMA.i18n
			},
			router: {
				$Protocol: $IMA.$Protocol,
				$Host: $IMA.$Host,
				$Root: $IMA.$Root,
				$LanguagePartPath: $IMA.$LanguagePartPath
			}
		},
		settings: {
			$Debug: $IMA.$Debug,
			$Env: $IMA.$Env,
			$Version: $IMA.$Version,
			$App: $IMA.$App,
			$Protocol: $IMA.$Protocol,
			$Language: $IMA.$Language,
			$Host: $IMA.$Host,
			$Root: $IMA.$Root,
			$LanguagePartPath: $IMA.$LanguagePartPath
		}
	};

	return Object.assign(
		bootConfig,
		initialAppConfigFunctions,
		getInitialPluginConfig(),
		getInitialImaConfigFunctions()
	);
}

function getTestClientBootConfig(initialAppConfigFunctions) {
	let root = _getRoot();
	$IMA.$Debug = true;
	root.$Debug = $IMA.$Debug;

	let bootConfig = {
		services: {
			respond: null,
			request: null,
			$IMA: $IMA,
			dictionary: {
				$Language: $IMA.$Language,
				dictionary: $IMA.i18n
			},
			router: {
				$Host: $IMA.$Host,
				$Root: $IMA.$Root,
				$LanguagePartPath: $IMA.$LanguagePartPath
			}
		},
		settings: {
			$Env: 'dev',
			$Language: 'en',
			$Protocol: 'http:',
			$Debug: $IMA.$Debug,
			$App: {}
		},
		plugins: []
	};

	return Object.assign(
		bootConfig,
		initialAppConfigFunctions,
		getInitialPluginConfig(),
		getInitialImaConfigFunctions()
	);
}

function bootClientApp(app, bootConfig) {
	app.bootstrap.run(bootConfig);

	let cache = app.oc.get('$Cache');
	cache.deserialize($IMA.Cache || {});

	return app;
}

function routeClientApp(app) {
	let router = app.oc.get('$Router');

	return router
		.listen()
		.route(router.getPath())
		.catch((error) => {
			if (typeof $IMA.fatalErrorHandler === 'function') {
				$IMA.fatalErrorHandler(error);
			} else {
				console.warn('Define function config.$IMA.fatalErrorHandler ' +
						'in services.js.');
			}
		});
}

function hotReloadClientApp(initialAppConfigFunctions) {
	if (!$Debug) {
		return;
	}

	let app = createImaApp();
	let bootConfig = getClientBootConfig(initialAppConfigFunctions);
	app = bootClientApp(app, bootConfig);

	let router = app.oc.get('$Router');
	let pageManager = app.oc.get('$PageManager');
	let currentRouteInfo = router.getCurrentRouteInfo();
	let currentRoute = currentRouteInfo.route;
	let currentRouteOptions = Object.assign(
		{},
		currentRoute.getOptions(),
		{
			onlyUpdate: false,
			autoScroll: false,
			allowSPA: false
		}
	);

	router.listen();

	try {
		return pageManager
			.manage(
				currentRoute.getController(),
				currentRoute.getView(),
				currentRouteOptions,
				currentRouteInfo.params
			)
			.catch((error) => {
				return router.handleError({ error });
			})
			.catch((error) => {
				if (typeof $IMA.fatalErrorHandler === 'function') {
					$IMA.fatalErrorHandler(error);
				} else {
					console.warn('Define function ' +
							'config.$IMA.fatalErrorHandler in services.js.');
				}
			});
	} catch (error) {
		return router.handleError({ error });
	}
}

function reviveClientApp (initialAppConfigFunctions) {
	let root = _getRoot();

	if (_isClient()) {
		// hack for the Chrome browser, which sometimes has problems with
		// rendering the page
		document.body.style.display = 'none';
		document.body.offsetHeight; //eslint-disable-line
		document.body.style.display = '';
	}

	//set React for ReactJS extension for browser
	root.React = vendorLinker.get('react');
	root.$Debug = root.$IMA.$Debug;

	let app = createImaApp();
	let bootConfig = getClientBootConfig(initialAppConfigFunctions);
	app = bootClientApp(app, bootConfig);

	return routeClientApp(app);
}

function reviveTestClientApp(initialAppConfigFunctions) {
	let root = _getRoot();
	let app = createImaApp();
	let bootConfig = getTestClientBootConfig(initialAppConfigFunctions);

	app = bootClientApp(app, bootConfig);

	root.ns = ns;
	root.oc = app.oc;
}

function onLoad(callback) {
	//TODO remove @0.15.0
	if ($IMA.$Debug && typeof callback === 'function') {
		throw new Error(`The onLoad method use promise pattern ` +
				`instead of callback pattern. Update your app/main.js file.`);
	}

	if (!_isClient()) {
		return Promise.reject(null);
	}

	return new Promise((resolve) => {
		if (
			(document.readyState === 'complete') ||
			(document.readyState === 'interactive')
		) {
			$IMA.Loader.initAllModules()
				.then(resolve)
				.catch((error) => {
					reject(error);
				});
		} else {
			window.addEventListener('DOMContentLoaded', () => {
				$IMA.Loader.initAllModules()
					.then(resolve)
					.catch((error) => {
						reject(error);
					});
			});
		}
	});
}

vendorLinker.bindToNamespace(ns);

export {
	getInitialImaConfigFunctions,
	getNamespace,
	getInitialPluginConfig,
	createImaApp,
	getClientBootConfig,
	getTestClientBootConfig,
	bootClientApp,
	routeClientApp,
	hotReloadClientApp,
	reviveClientApp,
	reviveTestClientApp,
	onLoad
};
<|endoftext|>


<commit_before>import {
	pxToInch
} from './utils';

import {
	IMAGES,
	BACKGROUNDS
} from './sbks-assets/images';

const PPTX_COLORS = {
	TEXT1: 'tx1',
	TEXT2: 'tx2',
	BACKGROUND1: 'bg1',
	BACKGROUND2: 'bg2',
	ACCENT1: 'accent1',
	ACCENT2: 'accent2',
	ACCENT3: 'accent3',
	ACCENT4: 'accent4',
	ACCENT5: 'accent5',
	ACCENT6: 'accent6',
}

const SETTINGS = {
	LAYOUT: 'LAYOUT_WIDE',
	MARGIN: 0.3
}

const COLORS = {
	BACKGROUND: 'f1f1f4',
	DEFAULT_COLOR: 'ff0000',
	TITLE_COLOR: '00ff00',
	FOOTER_BACKGROUND: 'f1f1f4',
	SCHEME: {
		dk1: '2F3744',
		dk2: 'F3F3F5',
		lt1: '6B7883',
		lt2: 'FFFFFF',
		accent1: '1A3A82',
		accent2: '38C0C0',
		accent3: '3B922B',
		accent4: 'FFCC00',
		accent5: 'A22323',
		accent6: '66245F'
	}
}

const FONTS = {
	DEFAULT_FONT_FACE: 'Arial',
	FOOTER_FONT_SIZE: 9,
}

const FOOTER_BAR = {
	y: '91%',
	h: '9%',
	SBKS_LOGO: {
		w: IMAGES.SBKS_LOGO.w / 2.8,
		h: IMAGES.SBKS_LOGO.h / 2.8
	}
}

let _footerBar = [{
	rect: {
		x: 0,
		y: FOOTER_BAR.y,
		w: '100%',
		h: FOOTER_BAR.h,
		fill: COLORS.FOOTER_BACKGROUND
	}
}, {
	image: {
		x: '3%',
		y: '93%',
		w: pxToInch(FOOTER_BAR.SBKS_LOGO.w),
		h: pxToInch(FOOTER_BAR.SBKS_LOGO.h),
		data: IMAGES.SBKS_LOGO.data
	}
}];

const MASTER_FILE = {
	MASTER_SLIDE: {
		definitions: {
			title: 'Socialbakers Slide Master',
			bkgd: COLORS.BACKGROUND,
			color: COLORS.DEFAULT_COLOR,
			margin: SETTINGS.MARGIN,
			objects: [].concat(_footerBar),
			placeholders: [
				{
					type: 'title',
					text: 'Click to edit title',
					name: 'title',
					options: {
						x: '3%',
						y: '3.5%',
						w: '94%',
						h: '7.5%'
					}
				}, {
					type: 'footer',
					text: 'Click to edit footer',
					name: 'footer',
					options: {
						x: '15%',
						y: '93%',
						w: '50%',
						h: '4%',
						font_size: 9
					}
				}, {
					type: 'sldNum',
					name: 'slideNumber',
					options: {
						x: '93%',
						y: '93%',
						w: '6%',
						h: '4%',
						align:'right',
						font_size: 9,
					},
				}
			]
		},
		styles: {
			title: {
				list: [{"align":"left","color":PPTX_COLORS.TEXT1,"font_face":FONTS.DEFAULT_FONT_FACE,"font_size":24,"valign":"center"}]
			},
			body: {
				list: [{"align":"left","color":PPTX_COLORS.TEXT1,"font_face":FONTS.DEFAULT_FONT_FACE,"font_size":16,"valign":"top"}]
			},
			other: {
				list: [{"align":"left","color":PPTX_COLORS.TEXT1,"font_face":FONTS.DEFAULT_FONT_FACE,"font_size":16,"valign":"t"}]
			}
		}
	},
	INTRO_SLIDE: {
		title: 'Title Slide',
		type: 'title',
		hasSlideNumber: false,
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Dashboard Name',
				name: 'title',
				options: {
					x: '3%',
					y: '10%',
					w: '94%',
					h: '35%',
					font_size: 48,
					color: COLORS.SCHEME.dk2,
					align: 'center',
					valign: 'bottom'
				}
			}, {
				type: 'subTitle',
				text: 'Data Range of the Report',
				name: 'subTitle',
				options: {
					x: '3%',
					y: '47%',
					w: '94%',
					h: '23%',
					font_size: 20,
					color: COLORS.SCHEME.dk2,
					align: 'center',
					valign: 'top'
				}
			}
		]
	},
	TITLE_AND_CONTENT: {
		title: 'Title and Content',
		type: 'obj',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content',
				options: {
					x: '3%',
					y: '12%',
					w: '94%',
					h: '76.5%',
					valign: 'top',
				}
			}
		]
	},
	SECOND_HEADER: {
		title: 'Section Header',
		type: 'secHead',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text',
				options: {
					x: '3%',
					y: '12%',
					w: '94%',
					h: '4%',
					valign: 'top',
				}
			}
		]
	},
	TWO_CONTENT: {
		title: 'Two Content',
		type: 'twoObj',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_one',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_two',
				options: {
					x: '51%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}
		]
	},
	COMPARISON: {
		title: 'Comparison',
		type: 'twoTxTwoObj',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text_one',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '4%',
					valign: 'top',
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text_two',
				options: {
					x: '51%',
					y: '12%',
					w: '46%',
					h: '4%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_one',
				options: {
					x: '3%',
					y: '20%',
					w: '46%',
					h: '68.5%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_two',
				options: {
					x: '51%',
					y: '20%',
					w: '46%',
					h: '68ß.5%',
					valign: 'top',
				}
			}
		]
	},
	TITLE_ONLY: {
		title: 'Title Only',
		type: 'titleOnly',
		hasSlideNumber: 'titleOnly',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '11%',
					w: '94%',
					h: '37%',
					font_size: 32,
					align: 'center',
					valign: 'bottom'
				}
			}
		]
	},
	BLANK: {
		title: 'Blank',
		type: 'blank',
		objects: [].concat(_footerBar),
	},
	CONTENT_WITH_CAPTION: {
		title: 'Content with Caption',
		type: 'objTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '46%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to add text',
				name: 'text',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content',
				options: {
					x: '51%',
					y: '3.5%',
					w: '46%',
					h: '85%',
					valign: 'top',
				}
			}
		]
	},
	PICTURE_WITH_CAPTION: {
		title: 'Picture with Caption',
		type: 'picTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '46%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to add text',
				name: 'text',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}, {
				type: 'image',
				text: 'Click to add image',
				name: 'image',
				options: {
					x: '51%',
					y: '3.5%',
					w: '46%',
					h: '85%'
				}
			}
		]
	},
	TITLE_AND_VERTICAL_TEXT: {
		title: 'Title and Vertical Text',
		type: 'vertTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text',
				options: {
					x: '29%',
					y: '-33%',
					w: '42%',
					h: '167%',
					valign: 'top',
					rotate: '90'
				}
			}
		]
	},
	VERTICAL_TITLE_AND_TEXT: {
		title: 'Vertical Title and Text',
		type: 'vertTitleAndTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '72%',
					y: '42%',
					w: '47%',
					h: '7.5%',
					valign: 'top',
					rotate: '90'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text',
				options: {
					x: '24%',
					y: '-34%',
					w: '47%',
					h: '160%',
					valign: 'top',
					rotate: '90'
				}
			}
		]
	}
}

export {
	SETTINGS,
	COLORS,
	FONTS,
	MASTER_FILE
};<commit_msg>updated example master file<commit_after>import {
	pxToInch
} from './utils';

import {
	IMAGES,
	BACKGROUNDS
} from './sbks-assets/images';

const PPTX_COLORS = {
	TEXT1: 'tx1',
	TEXT2: 'tx2',
	BACKGROUND1: 'bg1',
	BACKGROUND2: 'bg2',
	ACCENT1: 'accent1',
	ACCENT2: 'accent2',
	ACCENT3: 'accent3',
	ACCENT4: 'accent4',
	ACCENT5: 'accent5',
	ACCENT6: 'accent6',
	HLINK: 'hlink',
	FOLHLINK: 'folHlink'
}

const SETTINGS = {
	LAYOUT: 'LAYOUT_WIDE',
	MARGIN: 0.3
}

const COLORS = {
	BACKGROUND: 'f1f1f4',
	DEFAULT_COLOR: 'ff0000',
	TITLE_COLOR: '00ff00',
	FOOTER_BACKGROUND: 'f1f1f4',
	SCHEME: {
		dk1: '2F3744',
		dk2: '6B7883',
		lt1: 'F3F3F5',
		lt2: 'FFFFFF',
		accent1: '1A3A82',
		accent2: '38C0C0',
		accent3: '3B922B',
		accent4: 'FFCC00',
		accent5: 'A22323',
		accent6: '66245F',
		hlink: '1869B7',
		folHlink: '1869B7'
	}
}

const FONTS = {
	DEFAULT_FONT_FACE: 'Arial',
	FOOTER_FONT_SIZE: 9,
}

const FOOTER_BAR = {
	y: '91%',
	h: '9%',
	SBKS_LOGO: {
		w: IMAGES.SBKS_LOGO.w / 2.8,
		h: IMAGES.SBKS_LOGO.h / 2.8
	}
}

let _footerBar = [{
	rect: {
		x: 0,
		y: FOOTER_BAR.y,
		w: '100%',
		h: FOOTER_BAR.h,
		fill: PPTX_COLORS.BACKGROUND1,
		preserve: true
	}
}, {
	image: {
		x: '3%',
		y: '93%',
		w: pxToInch(FOOTER_BAR.SBKS_LOGO.w),
		h: pxToInch(FOOTER_BAR.SBKS_LOGO.h),
		data: IMAGES.SBKS_LOGO.data,
		preserve: true
	}
}];

const MASTER_FILE = {
	MASTER_SLIDE: {
		definitions: {
			title: 'Slide Master',
			bkgd: COLORS.BACKGROUND,
			color: COLORS.DEFAULT_COLOR,
			margin: SETTINGS.MARGIN,
			objects: [].concat(_footerBar),
			placeholders: [
				{
					type: 'title',
					text: 'Click to edit title',
					name: 'title',
					options: {
						x: '3%',
						y: '3.5%',
						w: '94%',
						h: '7.5%'
					}
				}, {
					type: 'footer',
					text: 'Click to edit footer',
					name: 'footer',
					options: {
						x: '15%',
						y: '93%',
						w: '50%',
						h: '4%',
						font_size: 9
					}
				}, {
					type: 'sldNum',
					name: 'slideNumber',
					options: {
						x: '93%',
						y: '93%',
						w: '6%',
						h: '4%',
						align:'right',
						font_size: 9,
					},
				}
			]
		},
		styles: {
			title: {
				list: [{"align":"left","color":PPTX_COLORS.TEXT1,"font_face":FONTS.DEFAULT_FONT_FACE,"font_size":24,"valign":"center"}]
			},
			body: {
				list: [{"align":"left","color":PPTX_COLORS.TEXT1,"font_face":FONTS.DEFAULT_FONT_FACE,"font_size":16,"valign":"top"}]
			},
			other: {
				list: [{"align":"left","color":PPTX_COLORS.TEXT1,"font_face":FONTS.DEFAULT_FONT_FACE,"font_size":16,"valign":"t"}]
			}
		}
	},
	TITLE_SLIDE: {
		title: 'Title Slide',
		type: 'title',
		hasSlideNumber: false,
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '10%',
					w: '94%',
					h: '35%',
					font_size: 48,
					align: 'center',
					valign: 'bottom'
				}
			}, {
				type: 'subTitle',
				text: 'Click to add subtitle',
				name: 'subTitle',
				options: {
					x: '3%',
					y: '47%',
					w: '94%',
					h: '23%',
					font_size: 20,
					align: 'center',
					valign: 'top'
				}
			}
		]
	},
	TITLE_AND_CONTENT: {
		title: 'Title and Content',
		type: 'obj',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content',
				options: {
					x: '3%',
					y: '12%',
					w: '94%',
					h: '76.5%',
					valign: 'top',
				}
			}
		]
	},
	SECOND_HEADER: {
		title: 'Section Header',
		type: 'secHead',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '10%',
					w: '94%',
					h: '35%',
					align: 'center',
					valign: 'bottom'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text',
				options: {
					x: '3%',
					y: '47%',
					w: '94%',
					h: '23%',
					align: 'center',
					valign: 'top'
				}
			}
		]
	},
	TWO_CONTENT: {
		title: 'Two Content',
		type: 'twoObj',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_one',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_two',
				options: {
					x: '51%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}
		]
	},
	COMPARISON: {
		title: 'Comparison',
		type: 'twoTxTwoObj',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text_one',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '4%',
					valign: 'top',
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text_two',
				options: {
					x: '51%',
					y: '12%',
					w: '46%',
					h: '4%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_one',
				options: {
					x: '3%',
					y: '20%',
					w: '46%',
					h: '68.5%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content_two',
				options: {
					x: '51%',
					y: '20%',
					w: '46%',
					h: '68ß.5%',
					valign: 'top',
				}
			}
		]
	},
	TITLE_ONLY: {
		title: 'Title Only',
		type: 'titleOnly',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '11%',
					w: '94%',
					h: '37%',
					font_size: 32,
					align: 'center',
					valign: 'bottom'
				}
			}
		]
	},
	BLANK: {
		title: 'Blank',
		type: 'blank',
		objects: [].concat(_footerBar),
	},
	CONTENT_WITH_CAPTION: {
		title: 'Content with Caption',
		type: 'objTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '46%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to add text',
				name: 'text',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}, {
				type: 'content',
				text: 'Click to add text',
				name: 'content',
				options: {
					x: '51%',
					y: '3.5%',
					w: '46%',
					h: '85%',
					valign: 'top',
				}
			}
		]
	},
	PICTURE_WITH_CAPTION: {
		title: 'Picture with Caption',
		type: 'picTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '46%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to add text',
				name: 'text',
				options: {
					x: '3%',
					y: '12%',
					w: '46%',
					h: '76.5%',
					valign: 'top',
				}
			}, {
				type: 'image',
				text: 'Click to add image',
				name: 'image',
				options: {
					x: '51%',
					y: '3.5%',
					w: '46%',
					h: '85%'
				}
			}
		]
	},
	TITLE_AND_VERTICAL_TEXT: {
		title: 'Title and Vertical Text',
		type: 'vertTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '3%',
					y: '3.5%',
					w: '94%',
					h: '7.5%'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text',
				options: {
					x: '29%',
					y: '-33%',
					w: '42%',
					h: '167%',
					valign: 'top',
					rotate: '90'
				}
			}
		]
	},
	VERTICAL_TITLE_AND_TEXT: {
		title: 'Vertical Title and Text',
		type: 'vertTitleAndTx',
		objects: [].concat(_footerBar),
		placeholders: [
			{
				type: 'title',
				text: 'Click to add title',
				name: 'title',
				options: {
					x: '72%',
					y: '42%',
					w: '47%',
					h: '7.5%',
					valign: 'top',
					rotate: '90'
				}
			}, {
				type: 'text',
				text: 'Click to edit text',
				name: 'text',
				options: {
					x: '24%',
					y: '-34%',
					w: '47%',
					h: '160%',
					valign: 'top',
					rotate: '90'
				}
			}
		]
	}
}

export {
	SETTINGS,
	COLORS,
	FONTS,
	MASTER_FILE
};<|endoftext|>


<commit_before>// Javascript for parsing and displaying departure information
var routes = {};
var url = "http://bustracker.pvta.com/InfoPoint/rest/";
var body;
var refresh_id;
var error_check_id;
var stops;
var sort_function;
var allowed_routes = [];
var stop_index = 0;
var REFRESH_TIME = 30000; // time in ms between refreshes
var CASCADE_SPEED = 75; // time in ms which each row will take to cascade

// Parse apart query string, conveniently tagged onto jQuery
(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

$(function(){
  body = $('body');
  parseQueryString();
  initBoard();
});

function startErrorRoutine() {
  stopRefreshing();
  body.append('
No Bus Information Available
');
  $('.connectivity_note').removeClass('hidden');
  error_check_id = setInterval(function(){
    console.log("Checking");
    $.ajax({
      url: url + "PublicMessages/GetCurrentMessages",
      success: function(route_data) {
        body.empty();
        console.log("It lives!");
        clearInterval(error_check_id);
        initBoard();
      }
    });
  }, 5000);

}

function parseQueryString() {
  var stop_query_string = $.QueryString["stops"];
  // Check if a query string has been specified
  if (typeof stop_query_string !== "undefined") {
    stops = [];
    var query_parts = stop_query_string.split(" ");
    for (var i = 0; i < query_parts.length; i++) {
      if (query_parts[i]) {
        stops.push(query_parts[i]);
      }
    }
  }
  // If they didn't enter any stops, or they screwed up, default to stop ID 64, the Integrative Learning Center
  if (typeof stops === "undefined" || (typeof stops !== "undefined" && stops.length == 0)) {
    stops = [64];
  }

  var route_query_string = $.QueryString["routes"];

  if (typeof route_query_string !== "undefined") {
    routes = [];
    var query_parts = route_query_string.split(" ");
    for (var i = 0; i < query_parts.length; i++) {
      if (query_parts[i]) {
        allowed_routes.push(query_parts[i]);
      }
    }
  }

  var sort_query_string = $.QueryString["sort"];

  if (typeof sort_query_string !== "undefined") {
    if (sort_query_string == "time") {
      sort_function = function(a, b) {
        return a.Departure.EDT < b.Departure.EDT ? -1 : 1;
      }
    }
  }
}

function initBoard() {
  // Let's start by preloading all of the route info, because when we query
  // departures, we'll only have the route ID
  $.ajax({
    url: url + "routes/getvisibleroutes",
    success: function(route_data) {
    for (var i = 0; i < route_data.length; i++) {
      routes[route_data[i].RouteId] = route_data[i];
    }
    addTables();
    startRefreshing();
  },
  dataType: 'json',
  error: startErrorRoutine});
}

function startRefreshing() {
  // Refresh the board every 30 seconds
  refresh_id = setInterval(function() {
    body.empty();
    addTables();
  }, REFRESH_TIME);
}

function stopRefreshing() {
  clearInterval(refresh_id);
}

function addTables() {
  // There are two separate calls here,
  $.ajax({
    url: url + "stops/get/"+stops[stop_index],
    success: function(stop_info) {
      $.ajax({
        url: url + "stopdepartures/get/" + stops[stop_index],
        success: function(departure_data) {
          // Draw the header for each stop
          body.append('
' + stop_info.Name + "
");
          var infos = getDepartureInfo(departure_data[0].RouteDirections);
          if (infos.length == 0){
            body.append('
No remaining scheduled departures.
');
          }
          var i = 0;
          // For that soothing cascading effect
          var id = setInterval(function() {
              // If we still have rows to render
              if (i < infos.length) {
                renderRow(infos[i]);
                i++;
              } else { // If not, clear out the timer and move onto the next route
                clearTimeout(id);
                stop_index++;
                // If we run out of stops, reset our index and don't do anything
                if (stop_index < stops.length) {
                  addTables(stops);
                } else {
                  stop_index = 0;
                }
              }
            }, CASCADE_SPEED);
      },
      dataType: 'json',
      error: startErrorRoutine});
    },
    dataType: 'json',
    error: startErrorRoutine});
}

// A bit of a misnomer, we will occassionally render more that one row in here,
// as explained below
function renderRow(info) {
  body.append(
      '
' +
      '
' +
      info.Route.ShortName + " " + info.Departure.Trip.InternetServiceDesc +
      '
' +
      '
' +
      moment(info.Departure.EDT).fromNow(true) +
      '
' +
      '

' +
      '
'
      );
}

function getDepartureInfo(directions) {
  // This is a little tricky. There's a sort of edge case where we want to
  // display information for multiple buses on the same route, that are doing
  // different things. We differentiate them by using their
  // InternetServiceDesc, which will be different. Since the departures are
  // ordered from soonest to furthest away, we care about the first one with
  // a unique InternetServiceDesc, and that's what we're checking here.
  var unique_ISC = [];
  departures = [];
  for (var i = 0; i < directions.length; i++) {
    var direction = directions[i];
    var route = routes[direction.RouteId];
    for (var j = 0; j < direction.Departures.length; j++) {
      var departure = direction.Departures[j];
      if ($.inArray(departure.Trip.InternetServiceDesc, unique_ISC) == -1
          && (allowed_routes.length == 0 || $.inArray(route.ShortName, allowed_routes) != -1)
          && moment(departure.EDT).isAfter(Date.now())) {
        unique_ISC.push(departure.Trip.InternetServiceDesc);
        departures.push({Departure: departure, Route: route});
      }
    }
  }
  if (typeof sort_function !== "undefined") {
    return departures.sort(sort_function);
  } else {
    return departures;
  }
}
<commit_msg>Allowing the user to specify which animate.css animation they'd like to go with<commit_after>// Javascript for parsing and displaying departure information
var routes = {};
var url = "http://bustracker.pvta.com/InfoPoint/rest/";
var body;
var refresh_id;
var error_check_id;
var stops;
var sort_function;
var allowed_routes = [];
var animation_type = 'fadeInDown';
var stop_index = 0;
var REFRESH_TIME = 30000; // time in ms between refreshes
var CASCADE_SPEED = 75; // time in ms which each row will take to cascade

// Parse apart query string, conveniently tagged onto jQuery
(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

$(function(){
  body = $('body');
  parseQueryString();
  initBoard();
});

function startErrorRoutine() {
  stopRefreshing();
  body.append('
No Bus Information Available
');
  $('.connectivity_note').removeClass('hidden');
  error_check_id = setInterval(function(){
    console.log("Checking");
    $.ajax({
      url: url + "PublicMessages/GetCurrentMessages",
      success: function(route_data) {
        body.empty();
        console.log("It lives!");
        clearInterval(error_check_id);
        initBoard();
      }
    });
  }, 5000);

}

function parseQueryString() {
  var stop_query_string = $.QueryString["stops"];
  // Check if a query string has been specified
  if (typeof stop_query_string !== "undefined") {
    stops = [];
    var query_parts = stop_query_string.split(" ");
    for (var i = 0; i < query_parts.length; i++) {
      if (query_parts[i]) {
        stops.push(query_parts[i]);
      }
    }
  }
  // If they didn't enter any stops, or they screwed up, default to stop ID 64, the Integrative Learning Center
  if (typeof stops === "undefined" || (typeof stops !== "undefined" && stops.length == 0)) {
    stops = [64];
  }

  var route_query_string = $.QueryString["routes"];

  if (typeof route_query_string !== "undefined") {
    routes = [];
    var query_parts = route_query_string.split(" ");
    for (var i = 0; i < query_parts.length; i++) {
      if (query_parts[i]) {
        allowed_routes.push(query_parts[i]);
      }
    }
  }

  var sort_query_string = $.QueryString["sort"];

  if (typeof sort_query_string !== "undefined") {
    if (sort_query_string == "time") {
      sort_function = function(a, b) {
        return a.Departure.EDT < b.Departure.EDT ? -1 : 1;
      }
    }
  }
  var animation_query_string = $.QueryString['animation'];
  if (typeof animation_query_string !== 'undefined'){
    animation_type = animation_query_string
  }
}

function initBoard() {
  // Let's start by preloading all of the route info, because when we query
  // departures, we'll only have the route ID
  $.ajax({
    url: url + "routes/getvisibleroutes",
    success: function(route_data) {
    for (var i = 0; i < route_data.length; i++) {
      routes[route_data[i].RouteId] = route_data[i];
    }
    addTables();
    startRefreshing();
  },
  dataType: 'json',
  error: startErrorRoutine});
}

function startRefreshing() {
  // Refresh the board every REFRESH_TIME ms
  refresh_id = setInterval(function() {
    body.empty();
    addTables();
  }, REFRESH_TIME);
}

function stopRefreshing() {
  clearInterval(refresh_id);
}

function addTables() {
  // There are two separate calls here,
  $.ajax({
    url: url + "stops/get/"+stops[stop_index],
    success: function(stop_info) {
      $.ajax({
        url: url + "stopdepartures/get/" + stops[stop_index],
        success: function(departure_data) {
          // Draw the header for each stop
          body.append('
' + stop_info.Name + "
");
          var infos = getDepartureInfo(departure_data[0].RouteDirections);
          if (infos.length == 0){
            body.append('
No remaining scheduled departures.
');
          }
          var i = 0;
          // For that soothing cascading effect
          var id = setInterval(function() {
              // If we still have rows to render
              if (i < infos.length) {
                renderRow(infos[i]);
                i++;
              } else { // If not, clear out the timer and move onto the next route
                clearTimeout(id);
                stop_index++;
                // If we run out of stops, reset our index and don't do anything
                if (stop_index < stops.length) {
                  addTables(stops);
                } else {
                  stop_index = 0;
                }
              }
            }, CASCADE_SPEED);
      },
      dataType: 'json',
      error: startErrorRoutine});
    },
    dataType: 'json',
    error: startErrorRoutine});
}

// A bit of a misnomer, we will occassionally render more that one row in here,
// as explained below
function renderRow(info) {
  body.append(
      '
' +
      '
' +
      info.Route.ShortName + " " + info.Departure.Trip.InternetServiceDesc +
      '
' +
      '
' +
      moment(info.Departure.EDT).fromNow(true) +
      '
' +
      '

' +
      '
'
      );
}

function getDepartureInfo(directions) {
  // This is a little tricky. There's a sort of edge case where we want to
  // display information for multiple buses on the same route, that are doing
  // different things. We differentiate them by using their
  // InternetServiceDesc, which will be different. Since the departures are
  // ordered from soonest to furthest away, we care about the first one with
  // a unique InternetServiceDesc, and that's what we're checking here.
  var unique_ISDs = [];
  departures = [];
  for (var i = 0; i < directions.length; i++) {
    var direction = directions[i];
    var route = routes[direction.RouteId];
    for (var j = 0; j < direction.Departures.length; j++) {
      var departure = direction.Departures[j];
      //If the departure has a unique InternetServiceDesc,
      if ($.inArray(departure.Trip.InternetServiceDesc, unique_ISDs) == -1
          //and if it's in the allowed routes,
          && (allowed_routes.length == 0 || $.inArray(route.ShortName, allowed_routes) != -1)
          //and if it's in the future,
          && moment(departure.EDT).isAfter(Date.now())) {
        // then we push it to the list, and push its ISD to the unique ISDs list.
        unique_ISDs.push(departure.Trip.InternetServiceDesc);
        departures.push({Departure: departure, Route: route});
      }
    }
  }
  if (typeof sort_function !== "undefined") {
    return departures.sort(sort_function);
  } else {
    return departures;
  }
}
<|endoftext|>