<commit_before>!function($) {
$.fn.toc = function(options) {
  var self = this;
  var opts = $.extend({}, jQuery.fn.toc.defaults, options);

  var container = $(opts.container);
  var headings = $(opts.selectors, container);
  var headingOffsets = [];
  var activeClassName = opts.prefix+'-active';

  var scrollTo = function(e) {
    if (opts.smoothScrolling) {
      e.preventDefault();
      var elScrollTo = $(e.target).attr('href');
      var $el = $(elScrollTo);
      $(opts.container).animate({ scrollTop: $el.offset().top }, 400, 'swing', function() {
        location.hash = elScrollTo;
      });
    }
    $('li', self).removeClass(activeClassName);
    $(e.target).parent().addClass(activeClassName);
  };

  //highlight on scroll
  var timeout;
  var highlightOnScroll = function(e) {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
      var top = $(window).scrollTop();
      for (var i = 0, c = headingOffsets.length; i < c; i++) {
        if (headingOffsets[i] >= top) {
          $('li', self).removeClass(activeClassName);
          $('li:eq('+(i-1)+')', self).addClass(activeClassName);
          break;
        }
      }
    }, 50);
  };
  if (opts.highlightOnScroll) {
    $(window).bind('scroll', highlightOnScroll);
    highlightOnScroll();
  }

  return this.each(function() {
    //build TOC
    var ul = $('<ul/>');
    headings.each(function(i, heading) {
      var $h = $(heading);
      headingOffsets.push($h.offset().top - opts.highlightOffset);

      //add anchor
      var anchor = $('<span/>').attr('id', opts.prefix+i).insertBefore($h);

      //build TOC item
      var a = $('<a/>')
      .text($h.text())
      .attr('href', '#'+opts.prefix+i)
      .bind('click', scrollTo);

      var li = $('<li/>')
      .addClass(opts.prefix+'-'+$h[0].tagName.toLowerCase())
      .append(a);

      ul.append(li);
    });
    var el = $(this);
    el.html(ul);
  });
};

jQuery.fn.toc.defaults = {
  container: 'body',
  selectors: 'h1,h2,h3',
  smoothScrolling: true,
  prefix: 'toc',
  highlightOnScroll: true,
  highlightOffset: 100
};

}(jQuery);
<commit_msg>Issue [#2](https://github.com/jgallen23/toc/issues/2 "Issue #2")<commit_after>!function($) {
$.fn.toc = function(options) {
  var self = this;
  var opts = $.extend({}, jQuery.fn.toc.defaults, options);

  var container = $(opts.container);
  var headings = $(opts.selectors, container);
  var headingOffsets = [];
  var activeClassName = opts.prefix+'-active';

  var scrollTo = function(e) {
    if (opts.smoothScrolling) {
      e.preventDefault();
      var elScrollTo = $(e.target).attr('href');
      var $el = $(elScrollTo);
      $(opts.container).animate({ scrollTop: $el.offset().top }, 400, 'swing', function() {
        location.hash = elScrollTo;
      });
    }
    $('li', self).removeClass(activeClassName);
    $(e.target).parent().addClass(activeClassName);
  };

  //highlight on scroll
  var timeout;
  var highlightOnScroll = function(e) {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
      var top = $(window).scrollTop();
      for (var i = 0, c = headingOffsets.length; i < c; i++) {
        if (headingOffsets[i] >= top) {
          $('li', self).removeClass(activeClassName);
          $('li:eq('+(i-1)+')', self).addClass(activeClassName);
          break;
        }
      }
    }, 50);
  };
  if (opts.highlightOnScroll) {
    $(window).bind('scroll', highlightOnScroll);
    highlightOnScroll();
  }

  return this.each(function() {
    //build TOC
    var ul = $('<ul/>');
    headings.each(function(i, heading) {
      var $h = $(heading);
      headingOffsets.push($h.offset().top - opts.highlightOffset);

      //add anchor
	var anchor = $('<span/>').attr('id', opts.anchorName(i, heading, opts.prefix)).insertBefore($h);

      //build TOC item
      var a = $('<a/>')
      .text($h.text())
      .attr('href', '#' + opts.anchorName(i, heading, opts.prefix))
      .bind('click', scrollTo);

      var li = $('<li/>')
      .addClass(opts.prefix+'-'+$h[0].tagName.toLowerCase())
      .append(a);

      ul.append(li);
    });
    var el = $(this);
    el.html(ul);
  });
};

jQuery.fn.toc.defaults = {
  container: 'body',
  selectors: 'h1,h2,h3',
  smoothScrolling: true,
  prefix: 'toc',
  highlightOnScroll: true,
  highlightOffset: 100,
  anchorName: function(i, heading, prefix) {
    return prefix+i;
  }
};

}(jQuery);
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Narrow Browser
// @namespace   http://boris.joff3.com
// @description Remove horizontal scrolling by setting max-width on scripts
// @include     *
// @exclude     https://*.newegg.com/*
// @exclude     https://*.wunderground.com/*
// @exclude     https://github.com/*
// @version     1.1.4
// @author      borisjoffe
// @run-at      document-start
// @grant       none
// ==/UserScript==

/*
The MIT License (MIT)

Copyright (c) 2016 Boris Joffe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

(function() {
	'use strict';

	var DBG = false;

	function log() {
	 if (DBG)
		console.log.apply(console, arguments);
	 return arguments[0];
	}

	var changeMinWidth = true;

	var MAXWIDTH = {
		log: log,
		DBG: DBG,
		changeMinWidth: changeMinWidth,
		elements: [
			'p',
			'span',
			'h1, h2, h3, h4, h5, h6',
			'div',
			'nav',
			'a',
			'pre',
			'li',
			'input',
			'body'
		].join(','),

		screenWidth: function () {
			return log(window.innerWidth, '- innerWidth');
		}
	};

	MAXWIDTH.width = function () {
		return log(MAXWIDTH.screenWidth() - 10, ' - width');
	};

	MAXWIDTH.css = function () {
		return log(
			MAXWIDTH.elements + ' { max-width: ' + MAXWIDTH.width() + 'px !important;' +
			// TODO: change minWidth better - only if it's set
			(changeMinWidth ? 'min-width: 0px !important; ' : '') +
			' }',
			' - css'
		);
	};

	if (DBG)
		window.MAXWIDTH = MAXWIDTH;

	function addCss() {
		var css = MAXWIDTH.css();

		if (typeof GM_addStyle != "undefined") {
			GM_addStyle(css);
		} else if (typeof PRO_addStyle != "undefined") {
			PRO_addStyle(css);
		} else if (typeof addStyle != "undefined") {
			addStyle(css);
		} else {
			var node = document.createElement("style");
			node.type = "text/css";
			node.appendChild(document.createTextNode(css));
			var heads = document.getElementsByTagName("head");
			if (heads.length > 0) {
				heads[0].appendChild(node);
			} else {
				// no head yet, stick it whereever
				document.documentElement.appendChild(node);
			}
		}
	}

	addCss();

	// TODO: adjust previous css instead of adding more css
	// to avoid bloat
	window.onresize = addCss;

})();
<commit_msg>exclude newegg (http)<commit_after>// ==UserScript==
// @name        Narrow Browser
// @namespace   http://boris.joff3.com
// @description Remove horizontal scrolling by setting max-width on scripts
// @include     *
// @exclude     https://*.newegg.com/*
// @exclude     http://*.newegg.com/*
// @exclude     https://*.wunderground.com/*
// @exclude     https://github.com/*
// @version     1.1.5
// @author      borisjoffe
// @run-at      document-start
// @grant       none
// ==/UserScript==

/*
The MIT License (MIT)

Copyright (c) 2016 Boris Joffe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

(function() {
	'use strict';

	var DBG = false;

	function log() {
	 if (DBG)
		console.log.apply(console, arguments);
	 return arguments[0];
	}

	var changeMinWidth = true;

	var MAXWIDTH = {
		log: log,
		DBG: DBG,
		changeMinWidth: changeMinWidth,
		elements: [
			'p',
			'span',
			'h1, h2, h3, h4, h5, h6',
			'div',
			'nav',
			'a',
			'pre',
			'li',
			'input',
			'body'
		].join(','),

		screenWidth: function () {
			return log(window.innerWidth, '- innerWidth');
		}
	};

	MAXWIDTH.width = function () {
		return log(MAXWIDTH.screenWidth() - 10, ' - width');
	};

	MAXWIDTH.css = function () {
		return log(
			MAXWIDTH.elements + ' { max-width: ' + MAXWIDTH.width() + 'px !important;' +
			// TODO: change minWidth better - only if it's set
			(changeMinWidth ? 'min-width: 0px !important; ' : '') +
			' }',
			' - css'
		);
	};

	if (DBG)
		window.MAXWIDTH = MAXWIDTH;

	function addCss() {
		var css = MAXWIDTH.css();

		if (typeof GM_addStyle != "undefined") {
			GM_addStyle(css);
		} else if (typeof PRO_addStyle != "undefined") {
			PRO_addStyle(css);
		} else if (typeof addStyle != "undefined") {
			addStyle(css);
		} else {
			var node = document.createElement("style");
			node.type = "text/css";
			node.appendChild(document.createTextNode(css));
			var heads = document.getElementsByTagName("head");
			if (heads.length > 0) {
				heads[0].appendChild(node);
			} else {
				// no head yet, stick it whereever
				document.documentElement.appendChild(node);
			}
		}
	}

	addCss();

	// TODO: adjust previous css instead of adding more css
	// to avoid bloat
	window.onresize = addCss;

})();
<|endoftext|>


<commit_before>/*
 * grunt-mock-s3
 * https://github.com/MathieuLoutre/grunt-mock-s3
 *
 * Copyright (c) 2013 Mathieu Triay
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('underscore');
var fs = require('fs-extra');
var crypto = require('crypto');
var path = require("path");

// Gathered from http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search
exports.walk = function (dir) {

	var results = [];
	var list = fs.readdirSync(dir);

	list.forEach(function (file) {

		file = dir + '/' + file;
		var stat = fs.statSync(file);

		if (stat && stat.isDirectory()) {
			results = results.concat(exports.walk(file));
		}
		else {
			results.push(file);
		}
	});

	return results;
};

exports.S3 = function (options) {

	exports.endpoint = {
		href: ''
	};
	return exports;
};

exports.listObjects = function (search, callback) {

	var files = exports.walk(search.Bucket);

	var filtered_files = _.filter(files, function (file) { return file.replace(search.Bucket + '/', '').indexOf(search.Prefix) === 0; });
	var start = 0;
	var marker = null;
	var truncated = false;

	if (search.Marker) {
		start = filtered_files.indexOf(search.Bucket  + '/' + search.Marker);
	}

	filtered_files = _.rest(filtered_files, start);

	if (filtered_files.length > 1000) {
		truncated = true;
		filtered_files = filtered_files.slice(0, 1000);
	}

	var result = {
		Contents: _.map(filtered_files, function (path) {

			return {
				Key: path.replace(search.Bucket + '/', ''),
				ETag: '"' + crypto.createHash('md5').update(fs.readFileSync(path)).digest('hex') + '"',
				LastModified: fs.statSync(path).mtime
			};
		}),
		IsTruncated: truncated
	};

	if (truncated) {
		result.Marker = _.last(result.Contents).Key;
	}

	callback(null, result);
};

exports.deleteObjects = function (search, callback) {

	var deleted = [];
	var errors = [];

	_.each(search.Delete.Objects, function (file) {

		if (fs.existsSync(search.Bucket + '/' + file.Key)) {
			deleted.push(file);
			fs.unlinkSync(search.Bucket + '/' + file.Key);
		}
		else {
			errors.push(file);
		}
	});

	if (errors.length > 0) {
		callback("Error deleting objects", {Errors: errors, Deleted: deleted});
	}
	else {
		callback(null, {Deleted: deleted});
	}
};

function FakeStream (search) {
    this.src = search.Bucket + '/' + search.Key;
}

FakeStream.prototype.createReadStream = function () {
    return fs.createReadStream(this.src);
};

exports.getObject = function (search, callback) {

	if (!callback) {
		return new FakeStream(search);
	}
	else {
		fs.readFile(search.Bucket + '/' + search.Key, function (err, data) {

			if (!err) {
				callback(null, {
					Key: search.Key,
					ETag: '"' + crypto.createHash('md5').update(data).digest('hex') + '"',
					Body: data
				});
			}
			else {
				callback(err, search);
			}
		});
	}
};

exports.putObject = function (search, callback) {

	var dest = search.Bucket + '/' + search.Key;

	if (search.Body instanceof Buffer) {
		fs.createFileSync(dest);
		fs.writeFile(dest, search.Body, function (err) {
			callback(err);
		});
	}
	else {
		fs.mkdirsSync(path.dirname(dest));

		var stream = fs.createWriteStream(dest);

		stream.on('finish', function () {
			callback(null, true);
		});

		search.Body.on('error', function (err) {
			callback(err);
		});

		stream.on('error', function (err) {
			callback(err);
		});

		search.Body.pipe(stream);
	}
};<commit_msg>Add deleteObject method<commit_after>/*
 * grunt-mock-s3
 * https://github.com/MathieuLoutre/grunt-mock-s3
 *
 * Copyright (c) 2013 Mathieu Triay
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('underscore');
var fs = require('fs-extra');
var crypto = require('crypto');
var path = require("path");

// Gathered from http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search
exports.walk = function (dir) {

	var results = [];
	var list = fs.readdirSync(dir);

	list.forEach(function (file) {

		file = dir + '/' + file;
		var stat = fs.statSync(file);

		if (stat && stat.isDirectory()) {
			results = results.concat(exports.walk(file));
		}
		else {
			results.push(file);
		}
	});

	return results;
};

exports.S3 = function (options) {

	exports.endpoint = {
		href: ''
	};
	return exports;
};

exports.listObjects = function (search, callback) {

	var files = exports.walk(search.Bucket);

	var filtered_files = _.filter(files, function (file) { return file.replace(search.Bucket + '/', '').indexOf(search.Prefix) === 0; });
	var start = 0;
	var marker = null;
	var truncated = false;

	if (search.Marker) {
		start = filtered_files.indexOf(search.Bucket  + '/' + search.Marker);
	}

	filtered_files = _.rest(filtered_files, start);

	if (filtered_files.length > 1000) {
		truncated = true;
		filtered_files = filtered_files.slice(0, 1000);
	}

	var result = {
		Contents: _.map(filtered_files, function (path) {

			return {
				Key: path.replace(search.Bucket + '/', ''),
				ETag: '"' + crypto.createHash('md5').update(fs.readFileSync(path)).digest('hex') + '"',
				LastModified: fs.statSync(path).mtime
			};
		}),
		IsTruncated: truncated
	};

	if (truncated) {
		result.Marker = _.last(result.Contents).Key;
	}

	callback(null, result);
};

exports.deleteObjects = function (search, callback) {

	var deleted = [];
	var errors = [];

	_.each(search.Delete.Objects, function (file) {

		if (fs.existsSync(search.Bucket + '/' + file.Key)) {
			deleted.push(file);
			fs.unlinkSync(search.Bucket + '/' + file.Key);
		}
		else {
			errors.push(file);
		}
	});

	if (errors.length > 0) {
		callback("Error deleting objects", {Errors: errors, Deleted: deleted});
	}
	else {
		callback(null, {Deleted: deleted});
	}
};

exports.deleteObject = function (search, callback) {

	if (fs.existsSync(search.Bucket + '/' + file.Key)) {
		fs.unlinkSync(search.Bucket + '/' + file.Key);
		callback(null, true);
	}
	else {
		callback("Error deleting object");
	}
};

function FakeStream (search) {
    this.src = search.Bucket + '/' + search.Key;
}

FakeStream.prototype.createReadStream = function () {
    return fs.createReadStream(this.src);
};

exports.getObject = function (search, callback) {

	if (!callback) {
		return new FakeStream(search);
	}
	else {
		fs.readFile(search.Bucket + '/' + search.Key, function (err, data) {

			if (!err) {
				callback(null, {
					Key: search.Key,
					ETag: '"' + crypto.createHash('md5').update(data).digest('hex') + '"',
					Body: data
				});
			}
			else {
				callback(err, search);
			}
		});
	}
};

exports.putObject = function (search, callback) {

	var dest = search.Bucket + '/' + search.Key;

	if (search.Body instanceof Buffer) {
		fs.createFileSync(dest);
		fs.writeFile(dest, search.Body, function (err) {
			callback(err);
		});
	}
	else {
		fs.mkdirsSync(path.dirname(dest));

		var stream = fs.createWriteStream(dest);

		stream.on('finish', function () {
			callback(null, true);
		});

		search.Body.on('error', function (err) {
			callback(err);
		});

		stream.on('error', function (err) {
			callback(err);
		});

		search.Body.pipe(stream);
	}
};
<|endoftext|>


<commit_before>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/serviceWorker.js',{scope:'./'});
}
<commit_msg>Update site.js<commit_after>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/serviceWorker.js',{scope:'/'});
  navigator.serviceWorker.register('/serviceWorker.js',{scope:'/index.html'});
  navigator.serviceWorker.register('/serviceWorker.js',{scope:'/other.html'});
  navigator.serviceWorker.register('/serviceWorker.js',{scope:'/code/'});
}
<|endoftext|>


<commit_before>/* global process */

/**
 * Module dependencies
 */

var chalk = require('chalk')
var Table = require('cli-table')
var request = require('request-promise')

/**
 * Client commands
 */

function registerClient (cli, options, done) {
  var clientCmd = cli.command('client')

  /**
   * API Error Response Handler
   */

  function apiError (err) {
    if (err.statusCode && [401,403].indexOf(err.statusCode) !== -1) {
      cli.log.error('Please login to the issuer.')
    } else {
      console.log(err)
    }

    process.exit(1)
  }

  clientCmd
    .handler(function (data, flags, done) {
      done()
    })

  /**
   * Client registration
   */

  clientCmd
    .task('register')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            cli.prompt([
              {
                type: 'confirm',
                name: 'trusted',
                message: 'Will this be a trusted client?',
                value: flags['trusted'] || flags.t,
                default: false
              },
              {
                type: 'input',
                name: 'client_name',
                message: 'Enter a name',
                value: flags['name'] || flags.n,
                trim: true,
                required: true
              },
              {
                type: 'input',
                name: 'client_uri',
                message: 'Enter a URI',
                value: flags['uri'] || flags.u,
                format: 'url',
                trim: true
              },
              {
                type: 'input',
                name: 'logo_uri',
                message: 'Enter a logo URI',
                value: flags['logo-uri'] || flags.l,
                format: 'url',
                trim: true
              },
              {
                type: 'list',
                name: 'application_type',
                message: 'Choose an application type',
                choices: ['web', 'native', 'service'],
                default: 'web',
                value: flags['application-type'] || flags.a
              },
              {
                type: 'checkbox',
                name: 'response_types',
                message: 'Select response types',
                choices: [
                  { name: 'code', checked: true },
                  { name: 'id_token token' },
                  { name: 'code id_token token' },
                  { name: 'token' },
                  { name: 'none' }
                ],
                value: flags['response-type'] || flags.r
              },
              {
                type: 'checkbox',
                name: 'grant_types',
                message: 'Select grant types',
                choices: function (answers) {
                  var choices = [
                    { name: 'authorization_code', checked: true },
                    { name: 'implicit' },
                    { name: 'refresh_token' },
                    { name: 'client_credentials' }
                  ]

                  if (answers.response_types) {
                    if (
                      answers.response_types.indexOf('code') !== -1 ||
                      answers.response_types.indexOf('code id_token token') !== -1
                    ) {
                      choices[0].disabled = 'Required for code response type'
                    }
                    if (
                      answers.response_types.indexOf('id_token token') !== -1 ||
                      answers.response_types.indexOf('code id_token token') !== -1 ||
                      answers.response_types.indexOf('token') !== -1
                    ) {
                      choices[1].checked = true
                      choices[1].disabled = 'Required for token and/or id_token response types'
                    }
                  }

                  return choices
                },
                value: flags['grant-type'] || flags.g
              },
              {
                type: 'input',
                name: 'default_max_age',
                message: 'Set the default max age (in seconds)',
                default: 3600,
                value: flags['default-max-age'] || flags.d,
                dataType: 'integer',
                minimum: 0
              },
              {
                type: 'multiinput',
                name: 'redirect_uris',
                message: 'Define redirect URIs',
                format: 'url',
                required: true,
                trim: true,
                value: flags['redirect-uris'] || flags.s
              },
              {
                type: 'multiinput',
                name: 'post_logout_redirect_uris',
                message: 'Define post logout redirect URIs',
                format: 'url',
                trim: true,
                value: flags['post-logout-redirect-uris'] || flags.p
              }
            ], function (answers) {
              // register the client
              anvil.register(answers)
                .then(function (registration) {
                  cli.log()
                  cli.log('Successfully registered a new client:')
                  cli.log('Client ID:\t' + registration.client_id)
                  cli.log('Client Secret:\t' + registration.client_secret)
                  cli.log()
                  done()
                })
                // registration error
                .catch(apiError)
            })
          })
          // discover error
          .catch(apiError)
      })
    })

  /**
   * Client list
   */

  clientCmd
    .task('list')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return anvil.clients.list()
          })
          .then(function (clients) {
            var table = new Table({
              head: ['Name', 'Client ID', 'URI']
            })

            clients.forEach(function (client) {
              var name = chalk.bold(client.client_name)
              var clientId = chalk.yellow(client._id)
              var uri = (client.client_uri) ? chalk.cyan(client.client_uri) : ''
              table.push([name, clientId, uri])
            })

            cli.log(table.toString())
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Client info
   */

  clientCmd
    .task('info')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.clients.list()
                  .then(function (clients) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'clientId',
                        message: 'Select a client',
                        choices: clients.map(function (client) {
                          return {
                            name: client.client_name + ' – ' + chalk.yellow(client._id),
                            value: client._id
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.clientId)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (clientId) {
            return anvil.clients.get(clientId)
          })
          .then(function (data) {
            cli.log()
            cli.log('Name:\t\t\t' + chalk.bold(data.client_name))
            cli.log('Client ID\t\t' + chalk.yellow(data._id))
            cli.log('Client Secret\t\t' + chalk.yellow(data.client_secret))
            cli.log('Client URI\t\t' + chalk.cyan(data.client_uri))
            cli.log('Application type\t' + data.application_type)
            cli.log('Response types\t\t' + data.response_types)
            cli.log('Grant types\t\t' + data.grant_types)
            cli.log('Token auth method\t' + data.token_endpoint_auth_method)
            cli.log('Default max age\t\t' + data.default_max_age)
            cli.log('Redirect URIs\t\t' + data.redirect_uris.map(function (uri) {
              return chalk.cyan(uri)
            }).join('\n\t\t\t'))
            cli.log('Logout Redirect URIs\t' + data.post_logout_redirect_uris.map(function (uri) {
              return chalk.cyan(uri)
            }).join('\n\t\t\t'))
            cli.log('User ID\t\t\t' + chalk.yellow(data.userId))
            cli.log('Trusted\t\t\t' + chalk[data.trusted ? 'green' : 'gray'](data.trusted))
            cli.log('Scopes:\t\t\t' + data.scopes)
            cli.log('Created\t\t\t' + new Date(data.created))
            cli.log('Modified\t\t' + new Date(data.modified))
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Client update
   */

  clientCmd
    .task('update')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.clients.list()
                  .then(function (clients) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'clientId',
                        message: 'Select a client',
                        choices: clients.map(function (client) {
                          return {
                            name: client.client_name + ' – ' + chalk.yellow(client._id),
                            value: client._id
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.clientId)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (clientId) {
            return anvil.clients.update(clientId, {})
          })
          .then(function (data) {
            console.log(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Client delete
   */

  clientCmd
    .task('delete')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.clients.list()
                  .then(function (clients) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'clientId',
                        message: 'Select a client',
                        choices: clients.map(function (client) {
                          return {
                            name: client.client_name + ' – ' + chalk.yellow(client._id),
                            value: client._id
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.clientId)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (clientId) {
            return anvil.clients.delete(clientId)
          })
          .then(function () {
            done()
          })
          .catch(apiError)
      })
    })

  done()
}

/**
 * Exports
 */

module.exports = registerClient
<commit_msg>refactor(clients): use helper to display client<commit_after>/* global process */

/**
 * Module dependencies
 */

var chalk = require('chalk')
var Table = require('cli-table')
var request = require('request-promise')

/**
 * Client commands
 */

function registerClient (cli, options, done) {
  var clientCmd = cli.command('client')

  /**
   * API Error Response Handler
   */

  function apiError (err) {
    if (err.statusCode && [401,403].indexOf(err.statusCode) !== -1) {
      cli.log.error('Please login to the issuer.')
    } else {
      console.log(err)
    }

    process.exit(1)
  }

  /**
   * Display Field
   */

  function displayField (key, value, format) {
    if (typeof value !== 'undefined' && !(Array.isArray(value) && value.length === 0)) {
      // determine the number of tab characters to use
      var tabs = '\t'
      var diff = 24 - key.length
      if (diff > 8) { tabs += '\t' }
      if (diff > 16) { tabs += '\t' }

      // format the value
      if (Array.isArray(value)) {
        value = value.map(function (item) {
          return (format) ? chalk[format](item) : item
        }).join('\n\t\t\t')
      } else {
        value = (format) ? chalk[format](value) : value
      }

      cli.log(key + tabs + value)
    }
  }

  /**
   * Display Client
   */

  function displayClient (data) {
    cli.log()
    displayField('Name', data.client_name, 'bold')
    displayField('Client ID', data._id, 'yellow')
    displayField('Client Secret', data.client_secret, 'yellow')
    displayField('Client URI', data.client_uri, 'cyan')
    displayField('Application type', data.application_type)
    displayField('Response types', data.response_types)
    displayField('Grant types', data.grant_types)
    displayField('Token auth method', data.token_endpoint_auth_method)
    displayField('Default max age', data.default_max_age)
    displayField('Redirect URIs', data.redirect_uris, 'cyan')
    displayField('Logout Redirect URIs', data.post_logout_redirect_uris, 'cyan')
    displayField('User ID', data.userId, 'yellow')
    displayField('Trusted', data.trusted || false, (data.trusted) ? 'green' : 'gray')
    displayField('Scopes', data.scopes)
    displayField('Created', data.created && new Date(data.created))
    displayField('Modified', data.modified && new Date(data.modified))
  }

  clientCmd
    .handler(function (data, flags, done) {
      done()
    })

  /**
   * Client registration
   */

  clientCmd
    .task('register')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            cli.prompt([
              {
                type: 'confirm',
                name: 'trusted',
                message: 'Will this be a trusted client?',
                value: flags['trusted'] || flags.t,
                default: false
              },
              {
                type: 'input',
                name: 'client_name',
                message: 'Enter a name',
                value: flags['name'] || flags.n,
                trim: true,
                required: true
              },
              {
                type: 'input',
                name: 'client_uri',
                message: 'Enter a URI',
                value: flags['uri'] || flags.u,
                format: 'url',
                trim: true
              },
              {
                type: 'input',
                name: 'logo_uri',
                message: 'Enter a logo URI',
                value: flags['logo-uri'] || flags.l,
                format: 'url',
                trim: true
              },
              {
                type: 'list',
                name: 'application_type',
                message: 'Choose an application type',
                choices: ['web', 'native', 'service'],
                default: 'web',
                value: flags['application-type'] || flags.a
              },
              {
                type: 'checkbox',
                name: 'response_types',
                message: 'Select response types',
                choices: [
                  { name: 'code', checked: true },
                  { name: 'id_token token' },
                  { name: 'code id_token token' },
                  { name: 'token' },
                  { name: 'none' }
                ],
                value: flags['response-type'] || flags.r
              },
              {
                type: 'checkbox',
                name: 'grant_types',
                message: 'Select grant types',
                choices: function (answers) {
                  var choices = [
                    { name: 'authorization_code', checked: true },
                    { name: 'implicit' },
                    { name: 'refresh_token' },
                    { name: 'client_credentials' }
                  ]

                  if (answers.response_types) {
                    if (
                      answers.response_types.indexOf('code') !== -1 ||
                      answers.response_types.indexOf('code id_token token') !== -1
                    ) {
                      choices[0].disabled = 'Required for code response type'
                    }
                    if (
                      answers.response_types.indexOf('id_token token') !== -1 ||
                      answers.response_types.indexOf('code id_token token') !== -1 ||
                      answers.response_types.indexOf('token') !== -1
                    ) {
                      choices[1].checked = true
                      choices[1].disabled = 'Required for token and/or id_token response types'
                    }
                  }

                  return choices
                },
                value: flags['grant-type'] || flags.g
              },
              {
                type: 'input',
                name: 'default_max_age',
                message: 'Set the default max age (in seconds)',
                default: 3600,
                value: flags['default-max-age'] || flags.d,
                dataType: 'integer',
                minimum: 0
              },
              {
                type: 'multiinput',
                name: 'redirect_uris',
                message: 'Define redirect URIs',
                format: 'url',
                required: true,
                trim: true,
                value: flags['redirect-uris'] || flags.s
              },
              {
                type: 'multiinput',
                name: 'post_logout_redirect_uris',
                message: 'Define post logout redirect URIs',
                format: 'url',
                trim: true,
                value: flags['post-logout-redirect-uris'] || flags.p
              }
            ], function (answers) {
              // register the client
              anvil.clients.create(answers)
                .then(function (registration) {
                  displayClient(registration)
                  done()
                })
                // registration error
                .catch(apiError)
            })
          })
          // discover error
          .catch(apiError)
      })
    })

  /**
   * Client list
   */

  clientCmd
    .task('list')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return anvil.clients.list()
          })
          .then(function (clients) {
            var table = new Table({
              head: ['Name', 'Client ID', 'URI']
            })

            clients.forEach(function (client) {
              var name = chalk.bold(client.client_name)
              var clientId = chalk.yellow(client._id)
              var uri = (client.client_uri) ? chalk.cyan(client.client_uri) : ''
              table.push([name, clientId, uri])
            })

            cli.log(table.toString())
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Client info
   */

  clientCmd
    .task('info')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.clients.list()
                  .then(function (clients) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'clientId',
                        message: 'Select a client',
                        choices: clients.map(function (client) {
                          return {
                            name: client.client_name + ' – ' + chalk.yellow(client._id),
                            value: client._id
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.clientId)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (clientId) {
            return anvil.clients.get(clientId)
          })
          .then(function (data) {
            displayClient(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Client update
   */

  clientCmd
    .task('update')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.clients.list()
                  .then(function (clients) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'clientId',
                        message: 'Select a client',
                        choices: clients.map(function (client) {
                          return {
                            name: client.client_name + ' – ' + chalk.yellow(client._id),
                            value: client._id
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.clientId)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (clientId) {
            return anvil.clients.update(clientId, {})
          })
          .then(function (data) {
            console.log(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Client delete
   */

  clientCmd
    .task('delete')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(data[0], function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.clients.list()
                  .then(function (clients) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'clientId',
                        message: 'Select a client',
                        choices: clients.map(function (client) {
                          return {
                            name: client.client_name + ' – ' + chalk.yellow(client._id),
                            value: client._id
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.clientId)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (clientId) {
            return anvil.clients.delete(clientId)
          })
          .then(function () {
            done()
          })
          .catch(apiError)
      })
    })

  done()
}

/**
 * Exports
 */

module.exports = registerClient
<|endoftext|>


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

scheme.initString = function(env) {
    scheme.addPrimProc(env, "string?", string_p, 1);
    scheme.addPrimProc(env, "make-string", makeString, 1, 2);
    scheme.addPrimProc(env, "string", string, 0, -1);
    scheme.addPrimProc(env, "string-length", stringLength, 1);
    scheme.addPrimProc(env, "string-ref", stringRef, 2);
    scheme.addPrimProc(env, "string-set!", stringSet, 3);
    scheme.addPrimProc(env, "string=?", stringEqual, 2);
    scheme.addPrimProc(env, "string-ci=?", stringCIEqual, 2);
    scheme.addPrimProc(env, "substring", substring, 3);
    scheme.addPrimProc(env, "string->list", stringToList, 1);
    scheme.addPrimProc(env, "list->string", listToString, 1);
    scheme.addPrimProc(env, "string-copy", stringCopy, 1);
    scheme.addPrimProc(env, "string-fill!", stringFill, 2);
    scheme.addPrimProc(env, "string-append", stringAppend, 0, -1);
}

scheme.makeString = function(val) {
    if(typeof val == "string")
        val = val.split("");
    return new scheme.Object(scheme_char_string_type, val);
}
scheme.charArrayVal = function(obj) { return obj.val; }
scheme.stringVal = function(obj) { return obj.val.join(""); }
scheme.stringLen = function(obj) { return obj.val.length; }

function string_p(argv) {
    return scheme.getBoolean(scheme.isString(argv[0]));
}

function makeString(argv) {
    var k = argv[0];
    if(!isExactNonnegativeInteger(k))
        return scheme.wrongContract("make-string", "exact-nonnegative-integer?", 0, argv);
    k = scheme.intVal(k);
    var c = '\0';
    if(argv.length == 2) {
        c = argv[1];
        if(!scheme.isChar(c))
            return scheme.wrongContract("make-string", "char?", 1, argv);
        c = scheme.charVal(c);
    }
    var charArray = [];
    for(; k > 0; k--)
        charArray.push(c);
    return scheme.makeString(charArray);
}

function string(argv) {
    var charArray = [];
    for(var i = 0; i < argv.length; i++) {
        var obj = argv[i];
        if(!scheme.isChar(obj))
            return scheme.wrongContract("string", "char?", i, argv);
        charArray.push(scheme.charVal(obj));
    }
    return scheme.makeString(charArray);
}

function stringLength(argv) {
    var obj = argv[0];
    if(!scheme.isString(obj))
        return scheme.wrongContract("string-length", "string?", 0, argv);
    return scheme.makeInt(scheme.stringLen(obj));
}

function stringRef(argv) {
    var str = argv[0];
    var k = argv[1];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-ref", "string?", 0, argv);
    if(!isExactNonnegativeInteger(k))
        return scheme.wrongContract("string-ref", "exact-nonnegative-integer?", 1, argv);
    k = scheme.intVal(k);
    if(indexRangeCheck("string-ref", "string", k, -1, scheme.stringLen(str), str))
        return scheme.makeChar(scheme.charArrayVal(str)[k]);
}

function stringSet(argv) {
    var str = argv[0];
    var k = argv[1];
    var c = argv[2];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-set!", "string?", 0, argv);
    if(!isExactNonnegativeInteger(k))
        return scheme.wrongContract("string-set!", "exact-nonnegative-integer?", 1, argv);
    if(!scheme.isChar(c))
        return scheme.wrongContract("string-set!", "char?", 2, argv);
    k = scheme.intVal(k);
    if(indexRangeCheck("string-set!", "string", k, -1, scheme.stringLen(str), str)) {
        scheme.charArrayVal(str)[k] = scheme.charVal(c);
        return scheme.voidValue;
    }
}

function stringEqual(argv) {
    var str1 = argv[0];
    var str2 = argv[1];
    if(!scheme.isString(str1))
        return scheme.wrongContract("string=?", "string?", 0, argv);
    if(!str2.isString())
        return scheme.wrongContract("string=?", "string?", 1, argv);
    return scheme.getBoolean(scheme.stringVal(str1) == scheme.stringVal(str2));
}

function stringCIEqual(argv) {
    var str1 = argv[0];
    var str2 = argv[1];
    if(!scheme.isString(str1))
        return scheme.wrongContract("string=?", "string?", 0, argv);
    if(!str2.isString())
        return scheme.wrongContract("string=?", "string?", 1, argv);
    return scheme.getBoolean(
        scheme.stringVal(str1).toLowerCase() == scheme.stringVal(str2).toLowerCase());
}

function substring(argv) {
    var str = argv[0];
    var start = argv[1];
    var end = argv[2];
    if(!scheme.isString(str))
        return scheme.wrongContract("substring", "string?", 0, argv);
    if(!isExactNonnegativeInteger(start))
        return scheme.wrongContract("substring", "exact-nonnegative-integer?", 1, argv);
    if(!isExactNonnegativeInteger(end))
        return scheme.wrongContract("substring", "exact-nonnegative-integer?", 2, argv);
    start = scheme.intVal(start);
    end = scheme.intVal(end);
    if(indexRangeCheck("substring", "string", start, end, scheme.stringLen(str), str)) {
        return scheme.makeString(scheme.charArrayVal(str).slice(start, end));
    }
}

function stringAppend(argv) {
    var charArray = [];
    for(var i = 0; i < argv.length; i++) {
        var obj = argv[i];
        if(!scheme.isString(obj))
            return scheme.wrongContract("string-append", "string?", i, argv);
        charArray = charArray.concat(scheme.charArrayVal(obj));
    }
    return scheme.makeString(charArray);
}

function stringToList(argv) {
    var obj = argv[0];
    if(!scheme.isString(obj))
        return scheme.wrongContract("string->list", "string?", 0, argv);
    var list = scheme.nil;
    for(var charArray = scheme.stringVal(obj), i = charArray.length - 1; i >= 0; i--) {
        list = scheme.cons(scheme.makeChar(charArray[i]), list);
    }
    return list;
}

function listToString(argv) {
    var list = argv[0];
    if(!scheme.isList(list))
        return scheme.wrongContract("list->string", "list?", 0, argv);
    var obj;
    var charArray = [];
    for(var i = 0; !scheme.isEmptyList(list); list = scheme.cdr(list), i++) {
        obj = scheme.car(list);
        if(!scheme.isChar(obj))
            return scheme.wrongContract("list->string", "(listof char?)", 0, argv);
        charArray.push(scheme.charVal(obj));
    }
    return scheme.makeString(charArray);
}

function stringCopy(argv) {
    var str = argv[0];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-copy", "string?", 0, argv);
    return scheme.makeString(scheme.charArrayVal(str).slice(0));
}

function stringFill(argv) {
    var str = argv[0];
    var c = argv[1];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-fill!", "string?", 0, argv);
    if(!scheme.isChar(c))
        return scheme.wrongContract("string-fill!", "char?", 1, argv);
    c = scheme.charVal(c);
    var charArray = scheme.charArrayVal(str);
    for(var i in charArray)
        charArray[i] = c;
    return scheme.voidValue;
}

//--------------------
//contract & check functions
//--------------------
function isExactNonnegativeInteger(obj) {
    return scheme.isInteger(obj) && scheme.intVal(obj) >= 0;
}

function indexRangeCheck(procedureName, type, startIndex, endIndex, length, obj) {
    var invalid = false;
    if(endIndex == -1) {
        if(startIndex >= length || length == 0)
            invalid = "index";
    }
    else if(!(0 <= startIndex && startIndex <= endIndex && startIndex <= length))
        invalid = "starting";
    else if(endIndex > length)
        invalid = "ending";
    if(invalid)
        return scheme.indexOutRangeError(procedureName, type, startIndex, endIndex, invalid, length, obj);

    return true;
}

})(scheme);
<commit_msg>fix str2.isString -> scm.isString(str2)<commit_after>(function(scheme){
"use strict";

scheme.initString = function(env) {
    scheme.addPrimProc(env, "string?", string_p, 1);
    scheme.addPrimProc(env, "make-string", makeString, 1, 2);
    scheme.addPrimProc(env, "string", string, 0, -1);
    scheme.addPrimProc(env, "string-length", stringLength, 1);
    scheme.addPrimProc(env, "string-ref", stringRef, 2);
    scheme.addPrimProc(env, "string-set!", stringSet, 3);
    scheme.addPrimProc(env, "string=?", stringEqual, 2);
    scheme.addPrimProc(env, "string-ci=?", stringCIEqual, 2);
    scheme.addPrimProc(env, "substring", substring, 3);
    scheme.addPrimProc(env, "string->list", stringToList, 1);
    scheme.addPrimProc(env, "list->string", listToString, 1);
    scheme.addPrimProc(env, "string-copy", stringCopy, 1);
    scheme.addPrimProc(env, "string-fill!", stringFill, 2);
    scheme.addPrimProc(env, "string-append", stringAppend, 0, -1);
}

scheme.makeString = function(val) {
    if(typeof val == "string")
        val = val.split("");
    return new scheme.Object(scheme_char_string_type, val);
}
scheme.charArrayVal = function(obj) { return obj.val; }
scheme.stringVal = function(obj) { return obj.val.join(""); }
scheme.stringLen = function(obj) { return obj.val.length; }

function string_p(argv) {
    return scheme.getBoolean(scheme.isString(argv[0]));
}

function makeString(argv) {
    var k = argv[0];
    if(!isExactNonnegativeInteger(k))
        return scheme.wrongContract("make-string", "exact-nonnegative-integer?", 0, argv);
    k = scheme.intVal(k);
    var c = '\0';
    if(argv.length == 2) {
        c = argv[1];
        if(!scheme.isChar(c))
            return scheme.wrongContract("make-string", "char?", 1, argv);
        c = scheme.charVal(c);
    }
    var charArray = [];
    for(; k > 0; k--)
        charArray.push(c);
    return scheme.makeString(charArray);
}

function string(argv) {
    var charArray = [];
    for(var i = 0; i < argv.length; i++) {
        var obj = argv[i];
        if(!scheme.isChar(obj))
            return scheme.wrongContract("string", "char?", i, argv);
        charArray.push(scheme.charVal(obj));
    }
    return scheme.makeString(charArray);
}

function stringLength(argv) {
    var obj = argv[0];
    if(!scheme.isString(obj))
        return scheme.wrongContract("string-length", "string?", 0, argv);
    return scheme.makeInt(scheme.stringLen(obj));
}

function stringRef(argv) {
    var str = argv[0];
    var k = argv[1];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-ref", "string?", 0, argv);
    if(!isExactNonnegativeInteger(k))
        return scheme.wrongContract("string-ref", "exact-nonnegative-integer?", 1, argv);
    k = scheme.intVal(k);
    if(indexRangeCheck("string-ref", "string", k, -1, scheme.stringLen(str), str))
        return scheme.makeChar(scheme.charArrayVal(str)[k]);
}

function stringSet(argv) {
    var str = argv[0];
    var k = argv[1];
    var c = argv[2];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-set!", "string?", 0, argv);
    if(!isExactNonnegativeInteger(k))
        return scheme.wrongContract("string-set!", "exact-nonnegative-integer?", 1, argv);
    if(!scheme.isChar(c))
        return scheme.wrongContract("string-set!", "char?", 2, argv);
    k = scheme.intVal(k);
    if(indexRangeCheck("string-set!", "string", k, -1, scheme.stringLen(str), str)) {
        scheme.charArrayVal(str)[k] = scheme.charVal(c);
        return scheme.voidValue;
    }
}

function stringEqual(argv) {
    var str1 = argv[0];
    var str2 = argv[1];
    if(!scheme.isString(str1))
        return scheme.wrongContract("string=?", "string?", 0, argv);
    if(!scheme.isString(str2))
        return scheme.wrongContract("string=?", "string?", 1, argv);
    return scheme.getBoolean(scheme.stringVal(str1) == scheme.stringVal(str2));
}

function stringCIEqual(argv) {
    var str1 = argv[0];
    var str2 = argv[1];
    if(!scheme.isString(str1))
        return scheme.wrongContract("string=?", "string?", 0, argv);
    if(!str2.isString())
        return scheme.wrongContract("string=?", "string?", 1, argv);
    return scheme.getBoolean(
        scheme.stringVal(str1).toLowerCase() == scheme.stringVal(str2).toLowerCase());
}

function substring(argv) {
    var str = argv[0];
    var start = argv[1];
    var end = argv[2];
    if(!scheme.isString(str))
        return scheme.wrongContract("substring", "string?", 0, argv);
    if(!isExactNonnegativeInteger(start))
        return scheme.wrongContract("substring", "exact-nonnegative-integer?", 1, argv);
    if(!isExactNonnegativeInteger(end))
        return scheme.wrongContract("substring", "exact-nonnegative-integer?", 2, argv);
    start = scheme.intVal(start);
    end = scheme.intVal(end);
    if(indexRangeCheck("substring", "string", start, end, scheme.stringLen(str), str)) {
        return scheme.makeString(scheme.charArrayVal(str).slice(start, end));
    }
}

function stringAppend(argv) {
    var charArray = [];
    for(var i = 0; i < argv.length; i++) {
        var obj = argv[i];
        if(!scheme.isString(obj))
            return scheme.wrongContract("string-append", "string?", i, argv);
        charArray = charArray.concat(scheme.charArrayVal(obj));
    }
    return scheme.makeString(charArray);
}

function stringToList(argv) {
    var obj = argv[0];
    if(!scheme.isString(obj))
        return scheme.wrongContract("string->list", "string?", 0, argv);
    var list = scheme.nil;
    for(var charArray = scheme.stringVal(obj), i = charArray.length - 1; i >= 0; i--) {
        list = scheme.cons(scheme.makeChar(charArray[i]), list);
    }
    return list;
}

function listToString(argv) {
    var list = argv[0];
    if(!scheme.isList(list))
        return scheme.wrongContract("list->string", "list?", 0, argv);
    var obj;
    var charArray = [];
    for(var i = 0; !scheme.isEmptyList(list); list = scheme.cdr(list), i++) {
        obj = scheme.car(list);
        if(!scheme.isChar(obj))
            return scheme.wrongContract("list->string", "(listof char?)", 0, argv);
        charArray.push(scheme.charVal(obj));
    }
    return scheme.makeString(charArray);
}

function stringCopy(argv) {
    var str = argv[0];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-copy", "string?", 0, argv);
    return scheme.makeString(scheme.charArrayVal(str).slice(0));
}

function stringFill(argv) {
    var str = argv[0];
    var c = argv[1];
    if(!scheme.isString(str))
        return scheme.wrongContract("string-fill!", "string?", 0, argv);
    if(!scheme.isChar(c))
        return scheme.wrongContract("string-fill!", "char?", 1, argv);
    c = scheme.charVal(c);
    var charArray = scheme.charArrayVal(str);
    for(var i in charArray)
        charArray[i] = c;
    return scheme.voidValue;
}

//--------------------
//contract & check functions
//--------------------
function isExactNonnegativeInteger(obj) {
    return scheme.isInteger(obj) && scheme.intVal(obj) >= 0;
}

function indexRangeCheck(procedureName, type, startIndex, endIndex, length, obj) {
    var invalid = false;
    if(endIndex == -1) {
        if(startIndex >= length || length == 0)
            invalid = "index";
    }
    else if(!(0 <= startIndex && startIndex <= endIndex && startIndex <= length))
        invalid = "starting";
    else if(endIndex > length)
        invalid = "ending";
    if(invalid)
        return scheme.indexOutRangeError(procedureName, type, startIndex, endIndex, invalid, length, obj);

    return true;
}

})(scheme);
<|endoftext|>


<commit_before> function main() {
         var map = new L.Map('map', {
             zoomControl: false,
             center: [44.908, -75.83],
             zoom: 15
         });
         L.tileLayer(
             'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
                 attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
                 maxZoom: 16
             }).addTo(map);
         // load 10k course route
         $.getJSON("10k.geojson", function(data) {
             // add GeoJSON layer to the map once the file is loaded
             L.geoJson(data).addTo(map);
         });
         L.marker([-75.842136004738762, 44.915590473006233], {
             icon: L.AwesomeMarkers.icon({
				// start/finish
                 icon: 'spinner',
                 prefix: 'fa',
                 markerColor: 'red',
                 spin: true
             })
         }).addTo(map);
         L.marker([-75.832060018123741, 44.914413549299333], {
             icon: L.AwesomeMarkers.icon({
				// 1km marker
                 icon: 'coffee',
                 prefix: 'fa',
                 markerColor: 'red',
                 iconColor: '#f28f82'
             })
         }).addTo(map);
         L.marker([-75.822561794950488, 44.911647589142717], {
             icon: L.AwesomeMarkers.icon({
				// 2km marker
                 icon: 'cog',
                 prefix: 'fa',
                 markerColor: 'purple',
                 iconColor: 'black'
             })
         }).addTo(map);
         L.marker([-75.814411333682742, 44.904838590895402], {
             icon: L.AwesomeMarkers.icon({
				// 3km marker
                 icon: 'glass',
                 prefix: 'fa',
                 markerColor: 'green'
             })
         }).addTo(map);
         L.marker([-75.819099035460027, 44.904847825524257], {
             icon: L.AwesomeMarkers.icon({
				// 4km marker
                 icon: 'shopping-cart',
                 prefix: 'fa',
                 markerColor: 'blue'
             })
         }).addTo(map);
         L.marker([-75.819222734458137, 44.908766479203578], {
             icon: L.AwesomeMarkers.icon({
				// 5km marker
                 icon: 'info',
                 prefix: 'fa',
                 markerColor: 'orange'
             })
         }).addTo(map);
		 L.marker([-75.821638143643241, 44.909619921084101], {
             icon: L.AwesomeMarkers.icon({
				// 6km marker
                 icon: 'group',
                 prefix: 'fa',
                 markerColor: 'darkred'
             })
         L.marker([-75.829359263348891, 44.910911354101088], {
             icon: L.AwesomeMarkers.icon({
				// 7km marker
                 icon: 'group',
                 prefix: 'fa',
                 markerColor: 'darkred'
             })
         }).addTo(map);
         L.marker([-75.838807385644841, 44.905404992249714], {
             icon: L.AwesomeMarkers.icon({
				// 8km marker
                 icon: 'arrow-right',
                 prefix: 'fa',
                 markerColor: 'darkblue'
             })
         }).addTo(map);
         L.marker([-75.840375322159417, 44.909046491288322], {
             icon: L.AwesomeMarkers.icon({
				// 9km marker
                 icon: 'twitter',
                 prefix: 'fa',
                 markerColor: 'cadetblue'
             })
         }).addTo(map);
         // load 10k course route features
         //$.getJSON("features.geojson", function(data) {
         //add GeoJSON layer to the map once the file is loaded
         //L.geoJson(data).addTo(map);
         //});
         //$.getJSON("features.geojson", function(featData) {
         //L.geoJson(featData, {
         // style: function(feature) {
         //var ptSymbol,
         // feat = feature.properties.cng_(
         // Meters);
         // if (feat = 0.0) ptSymbol = L.AwesomeMarkers
         //.icon({
         //  icon: 'coffee',
         //  markerColor: 'red'
         //})
         //}).addTo(map);
         //});
     }
     // you could use $(window).load(main);
 window.onload = main;<commit_msg>change marker style<commit_after> function main() {
         var map = new L.Map('map', {
             zoomControl: false,
             center: [44.908, -75.83],
             zoom: 15
         });
         L.tileLayer(
             'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
                 attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
                 maxZoom: 16
             }).addTo(map);
         // load 10k course route
         $.getJSON("10k.geojson", function(data) {
             // add GeoJSON layer to the map once the file is loaded
             L.geoJson(data).addTo(map);
         });

         // load 10k course route features
         //$.getJSON("features.geojson", function(data) {
         //add GeoJSON layer to the map once the file is loaded
         //L.geoJson(data).addTo(map);
         //});
         //$.getJSON("features.geojson", function(featData) {
         //L.geoJson(featData, {
         // style: function(feature) {
         //var ptSymbol,
         // feat = feature.properties.cng_(
         // Meters);
         // if (feat = 0.0) ptSymbol = L.AwesomeMarkers
         //.icon({
         //  icon: 'coffee',
         //  markerColor: 'red'
         //})
         //}).addTo(map);
         //});
     }
     // you could use $(window).load(main);
 window.onload = main;<|endoftext|>


<commit_before>/*jshint worker: true*/
import Utils from './utils/utils';
import WorkerBroker from './utils/worker_broker'; // jshint ignore:line
import Tile from './tile';
import DataSource from './data_source.js';
import FeatureSelection from './selection';
import {StyleParser} from './styles/style_parser';
import {StyleManager} from './styles/style_manager';
import {parseRules} from './styles/rule';
import Texture from './gl/texture';

export var SceneWorker = self;

// Worker functionality will only be defined in worker thread
if (Utils.isWorkerThread) {
    Object.assign(self, {

        sources: {
            tiles: {},
            objects: {}
        },
        styles: {},
        rules: {},
        layers: {},
        tiles: {},
        objects: {},
        config: {},

        // Initialize worker
        init (worker_id, num_workers, device_pixel_ratio) {
            self._worker_id = worker_id;
            self.num_workers = num_workers;
            Utils.device_pixel_ratio = device_pixel_ratio;
            FeatureSelection.setPrefix(self._worker_id);
            return worker_id;
        },

        // Starts a config refresh
        updateConfig ({ config, generation }) {
            self.config = null;
            config = JSON.parse(config);

            self.generation = generation;
            self.styles = null;

            // Data block functions are not macro'ed and wrapped like the rest of the style functions are
            // TODO: probably want a cleaner way to exclude these
            for (var layer in config.layers) {
                config.layers[layer].data = Utils.stringsToFunctions(config.layers[layer].data);
            }

            // Create data sources
            config.sources = Utils.stringsToFunctions(StyleParser.expandMacros(config.sources));
            for (var name in config.sources) {
                let source = DataSource.create(Object.assign(config.sources[name], {name}));
                if (source.tiled) {
                    self.sources.tiles[name] = source;
                }
                else {
                    // Distribute object sources across workers
                    if (source.id % self.num_workers === self._worker_id) {
                        // Load source if not cached
                        self.sources.objects[name] = source;
                        if (!self.objects[source.name]) {
                            self.objects[source.name] = {};
                            source.load(self.objects[source.name]);
                        }
                    }
                }
            }

            // Expand styles
            self.config = Utils.stringsToFunctions(StyleParser.expandMacros(config), StyleParser.wrapFunction);
            self.styles = StyleManager.build(self.config.styles, { generation: self.generation });

            // Parse each top-level layer as a separate rule tree
            // TODO: find a more graceful way to incorporate this

            self.rules = parseRules(self.config.layers);

            // Sync tetxure info from main thread
            self.syncing_textures = self.syncTextures();

            // Return promise for when config refresh finishes
            self.configuring = self.syncing_textures.then(() => {
                Utils.log('debug', `updated config`);
            });
        },

        // Returns a promise that fulfills when config refresh is finished
        awaitConfiguration () {
            return self.configuring;
        },

        // Build a tile: load from tile source if building for first time, otherwise rebuild with existing data
        buildTile ({ tile }) {
            // Tile cached?
            if (self.tiles[tile.key] != null) {
                // Already loading?
                if (self.tiles[tile.key].loading === true) {
                    return;
                }
            }

            // Update tile cache
            tile = self.tiles[tile.key] = Object.assign(self.tiles[tile.key] || {}, tile);

            // Update config (styles, etc.), then build tile
            return self.awaitConfiguration().then(() => {
                // First time building the tile
                if (tile.loaded !== true) {

                    return new Promise((resolve, reject) => {

                        tile.loading = true;
                        tile.loaded = false;
                        tile.error = null;

                        self.loadSourcesIntoTile(tile).then(() => {
                            // Any errors? Warn and continue
                            let e = Object.keys(tile.sources).
                                map(s => tile.sources[s].error && `[source '${s}': ${tile.sources[s].error}]`).
                                filter(x => x);
                            if (e.length > 0) {
                                Utils.log('warn', `tile load error(s) for ${tile.key}: ${e.join(', ')}`);
                            }

                            tile.loading = false;
                            tile.loaded = true;
                            Tile.buildGeometry(tile, self.config.layers, self.rules, self.styles).then(keys => {
                                resolve({ tile: Tile.slice(tile, keys) });
                            });
                        }).catch((error) => {
                            tile.loading = false;
                            tile.loaded = false;
                            tile.error = error.toString();
                            Utils.log('error', `tile load error for ${tile.key}: ${error.stack}`);

                            resolve({ tile: Tile.slice(tile) });
                        });
                    });
                }
                // Tile already loaded, just rebuild
                else {
                    Utils.log('trace', `used worker cache for tile ${tile.key}`);

                    // Build geometry
                    return Tile.buildGeometry(tile, self.config.layers, self.rules, self.styles).then(keys => {
                        return { tile: Tile.slice(tile, keys) };
                    });
                }
            });
        },

        // Load all data sources into a tile
        loadSourcesIntoTile (tile) {
            return Promise.all(
                Object.keys(self.sources.tiles)
                    .map(x => self.sources.tiles[x].load(tile))
            );
        },

        // Remove tile
        removeTile (key) {
            var tile = self.tiles[key];

            if (tile != null) {
                // Cancel if loading
                if (tile.loading === true) {
                    Utils.log('trace', `cancel tile load for ${key}`);
                    tile.loading = false;
                }

                Tile.cancel(tile);

                // Remove from cache
                FeatureSelection.clearTile(key);
                delete self.tiles[key];
                Utils.log('trace', `remove tile from cache for ${key}`);
            }
        },

        // Get a feature from the selection map
        getFeatureSelection ({ id, key } = {}) {
            var selection = FeatureSelection.map[key];

            return {
                id: id,
                feature: (selection && selection.feature)
            };
        },

        // Resets the feature selection state
        resetFeatureSelection () {
            FeatureSelection.reset();
        },

        // Selection map size for this worker
        getFeatureSelectionMapSize () {
            return FeatureSelection.getMapSize();
        },

        // Texture info needs to be synced from main thread
        syncTextures () {
            // We're only syncing the textures that have sprites defined, since these are (currently) the only ones we
            // need info about for geometry construction (e.g. width/height, which we only know after the texture loads)
            let textures = [];
            if (self.config.textures) {
                for (let [texname, texture] of Utils.entries(self.config.textures)) {
                    if (texture.sprites) {
                        textures.push(texname);
                    }
                }
            }

            Utils.log('trace', 'sync textures to worker:', textures);
            if (textures.length > 0) {
                return Texture.syncTexturesToWorker(textures);
            }
            return Promise.resolve();
        },

        // Profiling helpers
        profile (name) {
            console.profile(`worker ${self._worker_id}: ${name}`);
        },

        profileEnd (name) {
            console.profileEnd(`worker ${self._worker_id}: ${name}`);
        }

    });
}<commit_msg>pull indentation in a level<commit_after>/*jshint worker: true*/
import Utils from './utils/utils';
import WorkerBroker from './utils/worker_broker'; // jshint ignore:line
import Tile from './tile';
import DataSource from './data_source.js';
import FeatureSelection from './selection';
import {StyleParser} from './styles/style_parser';
import {StyleManager} from './styles/style_manager';
import {parseRules} from './styles/rule';
import Texture from './gl/texture';

export var SceneWorker = self;

// Worker functionality will only be defined in worker thread
Utils.isWorkerThread && Object.assign(self, {

    sources: {
        tiles: {},
        objects: {}
    },
    styles: {},
    rules: {},
    layers: {},
    tiles: {},
    objects: {},
    config: {},

    // Initialize worker
    init (worker_id, num_workers, device_pixel_ratio) {
        self._worker_id = worker_id;
        self.num_workers = num_workers;
        Utils.device_pixel_ratio = device_pixel_ratio;
        FeatureSelection.setPrefix(self._worker_id);
        return worker_id;
    },

    // Starts a config refresh
    updateConfig ({ config, generation }) {
        self.config = null;
        config = JSON.parse(config);

        self.generation = generation;
        self.styles = null;

        // Data block functions are not macro'ed and wrapped like the rest of the style functions are
        // TODO: probably want a cleaner way to exclude these
        for (var layer in config.layers) {
            config.layers[layer].data = Utils.stringsToFunctions(config.layers[layer].data);
        }

        // Create data sources
        config.sources = Utils.stringsToFunctions(StyleParser.expandMacros(config.sources));
        for (var name in config.sources) {
            let source = DataSource.create(Object.assign(config.sources[name], {name}));
            if (source.tiled) {
                self.sources.tiles[name] = source;
            }
            else {
                // Distribute object sources across workers
                if (source.id % self.num_workers === self._worker_id) {
                    // Load source if not cached
                    self.sources.objects[name] = source;
                    if (!self.objects[source.name]) {
                        self.objects[source.name] = {};
                        source.load(self.objects[source.name]);
                    }
                }
            }
        }

        // Expand styles
        self.config = Utils.stringsToFunctions(StyleParser.expandMacros(config), StyleParser.wrapFunction);
        self.styles = StyleManager.build(self.config.styles, { generation: self.generation });

        // Parse each top-level layer as a separate rule tree
        // TODO: find a more graceful way to incorporate this

        self.rules = parseRules(self.config.layers);

        // Sync tetxure info from main thread
        self.syncing_textures = self.syncTextures();

        // Return promise for when config refresh finishes
        self.configuring = self.syncing_textures.then(() => {
            Utils.log('debug', `updated config`);
        });
    },

    // Returns a promise that fulfills when config refresh is finished
    awaitConfiguration () {
        return self.configuring;
    },

    // Build a tile: load from tile source if building for first time, otherwise rebuild with existing data
    buildTile ({ tile }) {
        // Tile cached?
        if (self.tiles[tile.key] != null) {
            // Already loading?
            if (self.tiles[tile.key].loading === true) {
                return;
            }
        }

        // Update tile cache
        tile = self.tiles[tile.key] = Object.assign(self.tiles[tile.key] || {}, tile);

        // Update config (styles, etc.), then build tile
        return self.awaitConfiguration().then(() => {
            // First time building the tile
            if (tile.loaded !== true) {

                return new Promise((resolve, reject) => {

                    tile.loading = true;
                    tile.loaded = false;
                    tile.error = null;

                    self.loadSourcesIntoTile(tile).then(() => {
                        // Any errors? Warn and continue
                        let e = Object.keys(tile.sources).
                            map(s => tile.sources[s].error && `[source '${s}': ${tile.sources[s].error}]`).
                            filter(x => x);
                        if (e.length > 0) {
                            Utils.log('warn', `tile load error(s) for ${tile.key}: ${e.join(', ')}`);
                        }

                        tile.loading = false;
                        tile.loaded = true;
                        Tile.buildGeometry(tile, self.config.layers, self.rules, self.styles).then(keys => {
                            resolve({ tile: Tile.slice(tile, keys) });
                        });
                    }).catch((error) => {
                        tile.loading = false;
                        tile.loaded = false;
                        tile.error = error.toString();
                        Utils.log('error', `tile load error for ${tile.key}: ${error.stack}`);

                        resolve({ tile: Tile.slice(tile) });
                    });
                });
            }
            // Tile already loaded, just rebuild
            else {
                Utils.log('trace', `used worker cache for tile ${tile.key}`);

                // Build geometry
                return Tile.buildGeometry(tile, self.config.layers, self.rules, self.styles).then(keys => {
                    return { tile: Tile.slice(tile, keys) };
                });
            }
        });
    },

    // Load all data sources into a tile
    loadSourcesIntoTile (tile) {
        return Promise.all(
            Object.keys(self.sources.tiles)
                .map(x => self.sources.tiles[x].load(tile))
        );
    },

    // Remove tile
    removeTile (key) {
        var tile = self.tiles[key];

        if (tile != null) {
            // Cancel if loading
            if (tile.loading === true) {
                Utils.log('trace', `cancel tile load for ${key}`);
                tile.loading = false;
            }

            Tile.cancel(tile);

            // Remove from cache
            FeatureSelection.clearTile(key);
            delete self.tiles[key];
            Utils.log('trace', `remove tile from cache for ${key}`);
        }
    },

    // Get a feature from the selection map
    getFeatureSelection ({ id, key } = {}) {
        var selection = FeatureSelection.map[key];

        return {
            id: id,
            feature: (selection && selection.feature)
        };
    },

    // Resets the feature selection state
    resetFeatureSelection () {
        FeatureSelection.reset();
    },

    // Selection map size for this worker
    getFeatureSelectionMapSize () {
        return FeatureSelection.getMapSize();
    },

    // Texture info needs to be synced from main thread
    syncTextures () {
        // We're only syncing the textures that have sprites defined, since these are (currently) the only ones we
        // need info about for geometry construction (e.g. width/height, which we only know after the texture loads)
        let textures = [];
        if (self.config.textures) {
            for (let [texname, texture] of Utils.entries(self.config.textures)) {
                if (texture.sprites) {
                    textures.push(texname);
                }
            }
        }

        Utils.log('trace', 'sync textures to worker:', textures);
        if (textures.length > 0) {
            return Texture.syncTexturesToWorker(textures);
        }
        return Promise.resolve();
    },

    // Profiling helpers
    profile (name) {
        console.profile(`worker ${self._worker_id}: ${name}`);
    },

    profileEnd (name) {
        console.profileEnd(`worker ${self._worker_id}: ${name}`);
    }

});
<|endoftext|>


<commit_before>/**
* @module lifterPrompts
*/
var validation = require('../validation/validation.js');

/**
* Object containing questions for CLI (each within their own object)
* @object
* @memberof module:lifterPrompts
* @param {object} obj Object of objects each containing a question asked within command line interface, possible selectionoptions (if any), validation methods and conditional next questions
*/
var promptList = {
  username: {
    promptText: 'Please ensure you are in the parent directory of your application before continuing with Lifter Config\n' +
      'What is your Docker Hub username?\nIf you don\'t have a Docker Hub account, ' +
      'get one at https://hub.docker.com/account/signup/',
    promptClass: 'username',
    validation: validation.hasValue,
    nextClass: function() {return 'containerName';}
  },

/*
  password: {
    promptText: 'What is your dockerHub password?',
    promptClass: 'password',
    validation: validation.authenticateUser,
    nextClass: 'containerName'
  },
*/

  containerName: {
    promptText: 'Name your Docker container',
    promptClass: 'containerName',
    validation: validation.hasValue,
    nextClass: function() {return 'repoName';}
  },

  repoName: {
    promptText: 'Name your repo',
    promptClass: 'repoName',
    validation: validation.isValidRepoName,
    nextClass: function() {return 'launchCommand';}
  },

  launchCommand: {
    promptText: 'Enter the command you want to launch when you start up your container.',
    promptClass: 'launchCommand',
    validation: validation.hasValue,
    nextClass: function() {return 'portPrivate';}
  },

  // launchPath: {
  //   promptText: 'What is the filepath that corresponds to your command? \nType \'.\' if you want to execute your command this directory.',
  //   promptClass: 'launchPath',
  //   validation: validation.hasValue,
  //   nextClass: function() {return 'portPrivate';}
  // },

  portPrivate: {
    promptText: 'What port does your application use? (Example: 49160)',
    promptClass: 'portPrivate',
    validation: validation.inPortRange,
    nextClass: function() {return 'portPublic';}
  },

  portPublic: {
    promptText: 'What port can access your Docker container? (Example: 80)',
    promptClass: 'portPublic',
    validation: validation.inPortRange,
    nextClass: function() {return 'db';}
  },

  // Future Linux OS options may include 'Ubuntu', 'Fedora', 'Red Hat', 'Linux'
/*
  linuxOS: {
    promptText: 'Pick an OS',
    promptOptions: ['centos:6'],
    yamlSyntax: {'centos:6': 'centos:centos6'},
    promptClass: 'linuxOS',
    validation: validation.inOptions,
    nextClass: function() {return 'envVar';}
  },
*/

/*
  envVar: {
    promptText: 'Enter any environmental variables your app needs to run.',
    promptClass: 'envVar',
    validation: validation.noValidation,
    nextClass: function() {return 'db';}
  },
*/

  db: {
    promptText: 'Pick a database',
    promptOptions: ['mongoDB', 'mySQL', 'redis', 'No Database'],
    yamlSyntax: {'mongoDB': 'mongoDB', 'mySQL': 'mySQL', 'redis': 'redis', 'No Database': 'None'},
    promptClass: 'db',
    validation: validation.inOptions,
    nextClass: function() {return null;}
  },

  // Temporarily disabling scaffolding (feature has not been developed yet)
  // scaffolding: {
  //   promptText: 'Do you want scaffolding?',
  //   promptOptions: ['Yes!', 'Nope.'],
  //   promptClass: 'scaffolding',
  //   validation: validation.inOptions,
  //   nextClass: function(answer) {
  //     console.log('In nextClass key of scaffolding');
  //     if(answer === 'Yes!') {
  //       return 'appServer';
  //     } else {
  //       return null;
  //     }
  //   }
  // },

  // appServer: {
  //   promptText: 'Pick a back end',
  //   promptOptions: ['Node with Express', 'Node without Express', 'Apache'],
  //   promptClass: 'appServer',
  //   validation: validation.inOptions,
  //   nextClass: function() {return 'mvc';}
  // },
  //
  //
  // mvc: {
  //   promptText: 'Pick an MVC',
  //   promptOptions: ['Angular', 'Backbone', 'No MVC'],
  //   promptClass: 'mvc',
  //   validation: validation.inOptions,
  //   nextClass: function() {return null;}
  // },

};

module.exports = {
  promptList : promptList
}
<commit_msg>Change prompts for order and db options<commit_after>/**
* @module lifterPrompts
*/
var validation = require('../validation/validation.js');

/**
* Object containing questions for CLI (each within their own object)
* @object
* @memberof module:lifterPrompts
* @param {object} obj Object of objects each containing a question asked within command line interface, possible selectionoptions (if any), validation methods and conditional next questions
*/
var promptList = {
  username: {
    promptText: 'Please ensure you are in the parent directory of your application before continuing with Lifter Config\n' +
      'What is your Docker Hub username?\nIf you don\'t have a Docker Hub account, ' +
      'get one at https://hub.docker.com/account/signup/',
    promptClass: 'username',
    validation: validation.hasValue,
    nextClass: function() {return 'containerName';}
  },

/*
  password: {
    promptText: 'What is your dockerHub password?',
    promptClass: 'password',
    validation: validation.authenticateUser,
    nextClass: 'containerName'
  },
*/

  containerName: {
    promptText: 'Name your Docker container',
    promptClass: 'containerName',
    validation: validation.hasValue,
    nextClass: function() {return 'repoName';}
  },

  repoName: {
    promptText: 'Name your repo',
    promptClass: 'repoName',
    validation: validation.isValidRepoName,
    nextClass: function() {return 'launchCommand';}
  },

  launchCommand: {
    promptText: 'Enter the command you want to launch when you start up your container.',
    promptClass: 'launchCommand',
    validation: validation.hasValue,
    nextClass: function() {return 'portPublic';}
  },

  // launchPath: {
  //   promptText: 'What is the filepath that corresponds to your command? \nType \'.\' if you want to execute your command this directory.',
  //   promptClass: 'launchPath',
  //   validation: validation.hasValue,
  //   nextClass: function() {return 'portPrivate';}
  // },

  portPublic: {
    promptText: 'What port can access your Docker container? (Example: 80)',
    promptClass: 'portPublic',
    validation: validation.inPortRange,
    nextClass: function() {return 'portPrivate';}
  },

  portPrivate: {
    promptText: 'What port does your application use? (Example: 49160)',
    promptClass: 'portPrivate',
    validation: validation.inPortRange,
    nextClass: function() {return 'db';}
  },

  // Future Linux OS options may include 'Ubuntu', 'Fedora', 'Red Hat', 'Linux'
/*
  linuxOS: {
    promptText: 'Pick an OS',
    promptOptions: ['centos:6'],
    yamlSyntax: {'centos:6': 'centos:centos6'},
    promptClass: 'linuxOS',
    validation: validation.inOptions,
    nextClass: function() {return 'envVar';}
  },
*/

/*
  envVar: {
    promptText: 'Enter any environmental variables your app needs to run.',
    promptClass: 'envVar',
    validation: validation.noValidation,
    nextClass: function() {return 'db';}
  },
*/

  db: {
    promptText: 'Pick a database',
    promptOptions: ['mongoDB', 'No Database'],
    yamlSyntax: {'mongoDB': 'mongoDB', 'No Database': 'None'},
/*
    promptOptions: ['mongoDB', 'mySQL', 'redis', 'No Database'],
    yamlSyntax: {'mongoDB': 'mongoDB', 'mySQL': 'mySQL', 'redis': 'redis', 'No Database': 'None'},
*/
    promptClass: 'db',
    validation: validation.inOptions,
    nextClass: function() {return null;}
  },

  // Temporarily disabling scaffolding (feature has not been developed yet)
  // scaffolding: {
  //   promptText: 'Do you want scaffolding?',
  //   promptOptions: ['Yes!', 'Nope.'],
  //   promptClass: 'scaffolding',
  //   validation: validation.inOptions,
  //   nextClass: function(answer) {
  //     console.log('In nextClass key of scaffolding');
  //     if(answer === 'Yes!') {
  //       return 'appServer';
  //     } else {
  //       return null;
  //     }
  //   }
  // },

  // appServer: {
  //   promptText: 'Pick a back end',
  //   promptOptions: ['Node with Express', 'Node without Express', 'Apache'],
  //   promptClass: 'appServer',
  //   validation: validation.inOptions,
  //   nextClass: function() {return 'mvc';}
  // },
  //
  //
  // mvc: {
  //   promptText: 'Pick an MVC',
  //   promptOptions: ['Angular', 'Backbone', 'No MVC'],
  //   promptClass: 'mvc',
  //   validation: validation.inOptions,
  //   nextClass: function() {return null;}
  // },

};

module.exports = {
  promptList : promptList
}
<|endoftext|>