<commit_before>/*
 * Extension to detect ES6 and auto-load Traceur or Babel for processing
 */
(function() {
  // good enough ES6 module detection regex - format detections not designed to be accurate, but to handle the 99% use case
  var esmRegEx = /(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/;

  var traceurRuntimeRegEx = /\$traceurRuntime\s*\./;
  var babelHelpersRegEx = /babelHelpers\s*\./;

  hook('translate', function(translate) {
    return function(load) {
      var loader = this;
      return translate.call(loader, load)
      .then(function(source) {
        // detect & transpile ES6
        if (load.metadata.format == 'esm' || load.metadata.format == 'es6' || !load.metadata.format && loader.transpiler !== false && source.match(esmRegEx)) {
          if (load.metadata.format == 'es6')
            warn.call(loader, 'Module ' + load.name + ' has metadata setting its format to "es6", which is deprecated.\nThis should be updated to "esm".');

          load.metadata.format = 'esm';

          if (loader.transpiler === false) {
            // we accept translation to esm for builds though to enable eg rollup optimizations
            if (loader.builder)
              return source;
            throw new TypeError('Unable to dynamically transpile ES module as SystemJS.transpiler set to false.');
          }

          // setting _loader.loadedTranspiler = false tells the next block to
          // do checks for setting transpiler metadata
          loader._loader.loadedTranspiler = loader._loader.loadedTranspiler || false;
          if (loader.pluginLoader)
            loader.pluginLoader._loader.loadedTranspiler = loader._loader.loadedTranspiler || false;

          // do transpilation
          return (loader._loader.transpilerPromise || (
            loader._loader.transpilerPromise = Promise.resolve(
              __global[loader.transpiler == 'typescript' ? 'ts' : loader.transpiler] || (loader.pluginLoader || loader)['import'](loader.transpiler)
          ))).then(function(transpiler) {
            loader._loader.loadedTranspilerRuntime = true;

            // translate hooks means this is a transpiler plugin instead of a raw implementation
            if (transpiler.translate) {
              // if transpiler is the same as the plugin loader, then don't run twice
              if (transpiler == load.metadata.loaderModule)
                return load.source;

              // convert the source map into an object for transpilation chaining
              if (typeof load.metadata.sourceMap == 'string')
                load.metadata.sourceMap = JSON.parse(load.metadata.sourceMap);

              return Promise.resolve(transpiler.translate.call(loader, load))
              .then(function(source) {
                // sanitize sourceMap if an object not a JSON string
                var sourceMap = load.metadata.sourceMap;
                if (sourceMap && typeof sourceMap == 'object') {
                  var originalName = load.name.split('!')[0];

                  // force set the filename of the original file
                  sourceMap.file = originalName + '!transpiled';

                  // force set the sources list if only one source
                  if (!sourceMap.sources || sourceMap.sources.length <= 1)
                    sourceMap.sources = [originalName];
                }

                if (load.metadata.format == 'esm' && !loader.builder && detectRegisterFormat(source))
                  load.metadata.format = 'register';
                return source;
              });
            }

            // legacy builder support
            if (loader.builder)
              load.metadata.originalSource = load.source;

            // defined in es6-module-loader/src/transpile.js
            return transpile.call(loader, load)
            .then(function(source) {
              // clear sourceMap as transpiler embeds it
              load.metadata.sourceMap = undefined;
              return source;
            });
          });
        }

        // skip transpiler and transpiler runtime loading when transpiler is disabled
        if (loader.transpiler === false)
          return source;

        // load the transpiler correctly
        if (loader._loader.loadedTranspiler === false && (loader.transpiler == 'traceur' || loader.transpiler == 'typescript' || loader.transpiler == 'babel')
            && load.name == loader.normalizeSync(loader.transpiler)) {

          // always load transpiler as a global
          if (source.length > 100 && !load.metadata.format) {
            load.metadata.format = 'global';

            if (loader.transpiler === 'traceur')
              load.metadata.exports = 'traceur';
            if (loader.transpiler === 'typescript')
              load.metadata.exports = 'ts';
          }

          loader._loader.loadedTranspiler = true;
        }

        // load the transpiler runtime correctly
        if (loader._loader.loadedTranspilerRuntime === false) {
          if (load.name == loader.normalizeSync('traceur-runtime')
              || load.name == loader.normalizeSync('babel/external-helpers*')) {
            if (source.length > 100)
              load.metadata.format = load.metadata.format || 'global';

            loader._loader.loadedTranspilerRuntime = true;
          }
        }

        // detect transpiler runtime usage to load runtimes
        if ((load.metadata.format == 'register' || load.metadata.bundle) && loader._loader.loadedTranspilerRuntime !== true) {
          if (!__global.$traceurRuntime && load.source.match(traceurRuntimeRegEx)) {
            loader._loader.loadedTranspilerRuntime = loader._loader.loadedTranspilerRuntime || false;
            return loader['import']('traceur-runtime').then(function() {
              return source;
            });
          }
          if (!__global.babelHelpers && load.source.match(babelHelpersRegEx)) {
            loader._loader.loadedTranspilerRuntime = loader._loader.loadedTranspilerRuntime || false;
            return loader['import']('babel/external-helpers').then(function() {
              return source;
            });
          }
        }

        return source;
      });
    };
  });

})();
<commit_msg>update esm regex<commit_after>/*
 * Extension to detect ES6 and auto-load Traceur or Babel for processing
 */
(function() {
  // good enough ES6 module detection regex - format detections not designed to be accurate, but to handle the 99% use case
  var esmRegEx = /(^\s*|[}\);\n]\s*)(import\s*(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s*from\s*['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/;

  var traceurRuntimeRegEx = /\$traceurRuntime\s*\./;
  var babelHelpersRegEx = /babelHelpers\s*\./;

  hook('translate', function(translate) {
    return function(load) {
      var loader = this;
      return translate.call(loader, load)
      .then(function(source) {
        // detect & transpile ES6
        if (load.metadata.format == 'esm' || load.metadata.format == 'es6' || !load.metadata.format && loader.transpiler !== false && source.match(esmRegEx)) {
          if (load.metadata.format == 'es6')
            warn.call(loader, 'Module ' + load.name + ' has metadata setting its format to "es6", which is deprecated.\nThis should be updated to "esm".');

          load.metadata.format = 'esm';

          if (loader.transpiler === false) {
            // we accept translation to esm for builds though to enable eg rollup optimizations
            if (loader.builder)
              return source;
            throw new TypeError('Unable to dynamically transpile ES module as SystemJS.transpiler set to false.');
          }

          // setting _loader.loadedTranspiler = false tells the next block to
          // do checks for setting transpiler metadata
          loader._loader.loadedTranspiler = loader._loader.loadedTranspiler || false;
          if (loader.pluginLoader)
            loader.pluginLoader._loader.loadedTranspiler = loader._loader.loadedTranspiler || false;

          // do transpilation
          return (loader._loader.transpilerPromise || (
            loader._loader.transpilerPromise = Promise.resolve(
              __global[loader.transpiler == 'typescript' ? 'ts' : loader.transpiler] || (loader.pluginLoader || loader)['import'](loader.transpiler)
          ))).then(function(transpiler) {
            loader._loader.loadedTranspilerRuntime = true;

            // translate hooks means this is a transpiler plugin instead of a raw implementation
            if (transpiler.translate) {
              // if transpiler is the same as the plugin loader, then don't run twice
              if (transpiler == load.metadata.loaderModule)
                return load.source;

              // convert the source map into an object for transpilation chaining
              if (typeof load.metadata.sourceMap == 'string')
                load.metadata.sourceMap = JSON.parse(load.metadata.sourceMap);

              return Promise.resolve(transpiler.translate.call(loader, load))
              .then(function(source) {
                // sanitize sourceMap if an object not a JSON string
                var sourceMap = load.metadata.sourceMap;
                if (sourceMap && typeof sourceMap == 'object') {
                  var originalName = load.name.split('!')[0];

                  // force set the filename of the original file
                  sourceMap.file = originalName + '!transpiled';

                  // force set the sources list if only one source
                  if (!sourceMap.sources || sourceMap.sources.length <= 1)
                    sourceMap.sources = [originalName];
                }

                if (load.metadata.format == 'esm' && !loader.builder && detectRegisterFormat(source))
                  load.metadata.format = 'register';
                return source;
              });
            }

            // legacy builder support
            if (loader.builder)
              load.metadata.originalSource = load.source;

            // defined in es6-module-loader/src/transpile.js
            return transpile.call(loader, load)
            .then(function(source) {
              // clear sourceMap as transpiler embeds it
              load.metadata.sourceMap = undefined;
              return source;
            });
          });
        }

        // skip transpiler and transpiler runtime loading when transpiler is disabled
        if (loader.transpiler === false)
          return source;

        // load the transpiler correctly
        if (loader._loader.loadedTranspiler === false && (loader.transpiler == 'traceur' || loader.transpiler == 'typescript' || loader.transpiler == 'babel')
            && load.name == loader.normalizeSync(loader.transpiler)) {

          // always load transpiler as a global
          if (source.length > 100 && !load.metadata.format) {
            load.metadata.format = 'global';

            if (loader.transpiler === 'traceur')
              load.metadata.exports = 'traceur';
            if (loader.transpiler === 'typescript')
              load.metadata.exports = 'ts';
          }

          loader._loader.loadedTranspiler = true;
        }

        // load the transpiler runtime correctly
        if (loader._loader.loadedTranspilerRuntime === false) {
          if (load.name == loader.normalizeSync('traceur-runtime')
              || load.name == loader.normalizeSync('babel/external-helpers*')) {
            if (source.length > 100)
              load.metadata.format = load.metadata.format || 'global';

            loader._loader.loadedTranspilerRuntime = true;
          }
        }

        // detect transpiler runtime usage to load runtimes
        if ((load.metadata.format == 'register' || load.metadata.bundle) && loader._loader.loadedTranspilerRuntime !== true) {
          if (!__global.$traceurRuntime && load.source.match(traceurRuntimeRegEx)) {
            loader._loader.loadedTranspilerRuntime = loader._loader.loadedTranspilerRuntime || false;
            return loader['import']('traceur-runtime').then(function() {
              return source;
            });
          }
          if (!__global.babelHelpers && load.source.match(babelHelpersRegEx)) {
            loader._loader.loadedTranspilerRuntime = loader._loader.loadedTranspilerRuntime || false;
            return loader['import']('babel/external-helpers').then(function() {
              return source;
            });
          }
        }

        return source;
      });
    };
  });

})();
<|endoftext|>


<commit_before>(function(window, document, $) {
	var canvas = document.getElementById("game"),
		context = canvas.getContext("2d"),
		defaultColour = "#444",
		backgroundColour = "#eee",
		bits = [],
		cacti = [];

	function generateBits() {
		for (y = canvas.height - 10; y <= canvas.height; y += 8) {
			for (x = 0 + rand(0, 100); x <= canvas.width; x += rand(100, 200)) {
				bits.push({
					x: x,
					y: y,
					width: rand(2, 4)
				});
			}
		}
	}

	function updateCacti(offset) {
		var count = 0,
			buffer = 50; // used to force cacti off the screen
		while (cacti.length > count && cacti[count].x < offset - buffer) {
			count++;
		}

		cacti.splice(0, count);

		if (cacti.length === 0) {
			cacti.push({
				x: canvas.width + offset + buffer,
				scale: rand(0.8, 1.5),
				leftSize: rand(0.5, 1.5),
				rightSize: rand(0.5, 1.5)
			});
		}
	}

	function rand(min, max) {
  		return Math.random() * (max - min) + min;
	}

	function drawDinosaur(options) {
		var context = options.context,
			x = options.left,
			y = options.bottom;

		// background spacer
		context.fillStyle = backgroundColour;
		context.fillRect(x + 7, y - 14, 22, 18);

		// Dino!
		context.fillStyle = defaultColour;

		// tail
		context.fillRect(x, y - 36, 2, 16);
		context.fillRect(x + 2, y - 32, 2, 16);
		context.fillRect(x + 4, y - 30, 2, 16);
		context.fillRect(x + 6, y - 28, 2, 16);
		context.fillRect(x + 8, y - 28, 2, 18);
		context.fillRect(x + 10, y - 30, 2, 22);
		context.fillRect(x + 12, y - 32, 4, 26);
		context.fillRect(x + 16, y - 34, 4, 26);
		context.fillRect(x + 20, y - 36, 4, 30);
		context.fillRect(x + 24, y - 38, 2, 30);
		context.fillRect(x + 26, y - 38, 2, 28);
		context.fillRect(x + 28, y - 52, 2, 40);

		if (options.wideEyed) {
			context.fillRect(x + 30, y - 54, 6, 2);
			context.fillRect(x + 32, y - 50, 2, 2);
			context.fillRect(x + 30, y - 46, 2, 32);
			context.fillRect(x + 32, y - 46, 2, 30);
			context.fillRect(x + 34, y - 46, 2, 28);
			// context.fillRect(x + 32, y - 54, 2, 4);
			// context.fillRect(x + 32, y - 48, 2, 32);
			// context.fillRect(x + 34, y - 54, 2, 36);
		} else {
			context.fillRect(x + 30, y - 54, 2, 40);
			context.fillRect(x + 32, y - 54, 2, 4);
			context.fillRect(x + 32, y - 48, 2, 32);
			context.fillRect(x + 34, y - 54, 2, 36);
		}

		context.fillRect(x + 36, y - 54, 2, 34);
		context.fillRect(x + 38, y - 54, 2, 20);
		context.fillRect(x + 40, y - 54, 12, 16);
		context.fillRect(x + 52, y - 52, 2, 14);

		if (options.wideEyed) {
			context.fillRect(x + 38, y - 34, 8, 2);
		} else {
			context.fillRect(x + 40, y - 36, 8, 2);
		}

		// arm (singular)
		context.fillRect(x + 36, y - 26, 4, 2);
		context.fillRect(x + 40, y - 26, 2, 4);

		y = options.bottom;
		if (options.backLegUp) {
			y -= 4;
		}
		// back leg
		context.fillRect(x + 12, y, 4, 2);
		context.fillRect(x + 12, y - 6, 2, 8);
		context.fillRect(x + 14, y - 6, 2, 3);
		context.fillRect(x + 16, y - 8, 2, 3);

		y = options.bottom;
		if (options.frontLegUp) {
			y -= 6;
		}

		// front leg
		context.fillRect(x + 22, y, 4, 2);
		context.fillRect(x + 22, y - 6, 2, 8);
	}

	function drawBackground(options) {
		var context = options.context,
			x = 0,
			y = options.height;

		context.fillStyle = defaultColour;

		context.fillRect(x, y - 20, options.width, 1);

		for (var i = bits.length - 1; i >= 0; i--) {
			context.fillRect(options.width - ((bits[i].x + options.offset) % options.width), bits[i].y, bits[i].width, 1);
		}
	}

	function drawCactus(options) {
		var context = options.context,
			x = options.left,
			y = options.bottom,
			scale = options.scale;

		context.fillStyle = defaultColour;

		// center
		context.fillRect(x + 6 * scale, y - 40 * scale, 6 * scale, 40 * scale);
		context.fillRect(x + 7 * scale, y - 41 * scale, 4 * scale, 1 * scale);

		// left
		var height = 15 * options.leftSize;
		context.fillRect(x, y - (15 + height) * scale, 4 * scale, height * scale);
		context.fillRect(x + 1 * scale, y - (15 + height + 1) * scale, 2 * scale, 1 * scale);
		context.fillRect(x + 4 * scale, y - 19 * scale, 4 * scale, 4 * scale);

		// right
		height = 15 * options.rightSize;
		context.fillRect(x + 14 * scale, y - (15 + height) * scale, 4 * scale, height * scale);
		context.fillRect(x + 15 * scale, y - (15 + height + 1) * scale, 2 * scale, 1 * scale);
		context.fillRect(x + 12 * scale, y - 19 * scale, 4 * scale, 4 * scale);
	}

	var lastTick = null,
		jumping = false,
		score = 0,
		ground = canvas.height - 10,
		speed = 0.02; // 10 score per second

	function step(timestamp) {
		if (lastTick) {
			score += (timestamp - lastTick) * speed;

			context.clearRect ( 0, 0, canvas.width, canvas.height);

			var offset = score * 10;

			drawBackground({
				context: context,
				width: canvas.width,
				height: canvas.height,
				offset: offset,
			});

			updateCacti(offset);

			for (var i = 0; i < cacti.length; i++) {
				drawCactus({
					context: context,
					left: cacti[i].x - score * 10,
					bottom: canvas.height - 10,
					scale: cacti[i].scale,
					leftSize: cacti[i].leftSize,
					rightSize: cacti[i].rightSize
				});
			}

			drawDinosaur({
				context: context,
				left: 10,
				bottom: ground,
				backLegUp: Math.floor(score) % 3 === 0,
				frontLegUp: Math.floor(score) % 3 === 1
			});
		}
		lastTick = timestamp;
		window.requestAnimationFrame(step);
	}

	generateBits();
	window.requestAnimationFrame(step);

})(window, document, $);<commit_msg>added cactus clustering and a random centre<commit_after>(function(window, document, $) {
	var canvas = document.getElementById("game"),
		context = canvas.getContext("2d"),
		defaultColour = "#444",
		backgroundColour = "#eee",
		bits = [],
		cacti = [];

	function generateBits() {
		for (y = canvas.height - 10; y <= canvas.height; y += 8) {
			for (x = 0 + rand(0, 100); x <= canvas.width; x += rand(100, 200)) {
				bits.push({
					x: x,
					y: y,
					width: rand(2, 4)
				});
			}
		}
	}

	function updateCacti(offset) {
		var count = 0,
			buffer = 50; // used to force cacti off the screen
		while (cacti.length > count && cacti[count].x < offset - buffer) {
			count++;
		}

		cacti.splice(0, count);

		if (cacti.length === 0) {
			count = Math.floor(rand(1, 3.9));
			var scale = rand(0.8, 1.5);

			while (count--) {
				cacti.push({
					x: canvas.width + offset + buffer + (count * 20 * scale),
					scale: scale,
					leftSize: rand(0.5, 1.5),
					rightSize: rand(0.5, 1.5),
					centerSize: rand(0.5, 1.5)
				});
			}
		}
	}

	function rand(min, max) {
  		return Math.random() * (max - min) + min;
	}

	function drawDinosaur(options) {
		var context = options.context,
			x = options.left,
			y = options.bottom;

		// background spacer
		context.fillStyle = backgroundColour;
		context.fillRect(x + 7, y - 14, 22, 18);

		// Dino!
		context.fillStyle = defaultColour;

		// tail
		context.fillRect(x, y - 36, 2, 16);
		context.fillRect(x + 2, y - 32, 2, 16);
		context.fillRect(x + 4, y - 30, 2, 16);
		context.fillRect(x + 6, y - 28, 2, 16);
		context.fillRect(x + 8, y - 28, 2, 18);
		context.fillRect(x + 10, y - 30, 2, 22);
		context.fillRect(x + 12, y - 32, 4, 26);
		context.fillRect(x + 16, y - 34, 4, 26);
		context.fillRect(x + 20, y - 36, 4, 30);
		context.fillRect(x + 24, y - 38, 2, 30);
		context.fillRect(x + 26, y - 38, 2, 28);
		context.fillRect(x + 28, y - 52, 2, 40);

		if (options.wideEyed) {
			context.fillRect(x + 30, y - 54, 6, 2);
			context.fillRect(x + 32, y - 50, 2, 2);
			context.fillRect(x + 30, y - 46, 2, 32);
			context.fillRect(x + 32, y - 46, 2, 30);
			context.fillRect(x + 34, y - 46, 2, 28);
			// context.fillRect(x + 32, y - 54, 2, 4);
			// context.fillRect(x + 32, y - 48, 2, 32);
			// context.fillRect(x + 34, y - 54, 2, 36);
		} else {
			context.fillRect(x + 30, y - 54, 2, 40);
			context.fillRect(x + 32, y - 54, 2, 4);
			context.fillRect(x + 32, y - 48, 2, 32);
			context.fillRect(x + 34, y - 54, 2, 36);
		}

		context.fillRect(x + 36, y - 54, 2, 34);
		context.fillRect(x + 38, y - 54, 2, 20);
		context.fillRect(x + 40, y - 54, 12, 16);
		context.fillRect(x + 52, y - 52, 2, 14);

		if (options.wideEyed) {
			context.fillRect(x + 38, y - 34, 8, 2);
		} else {
			context.fillRect(x + 40, y - 36, 8, 2);
		}

		// arm (singular)
		context.fillRect(x + 36, y - 26, 4, 2);
		context.fillRect(x + 40, y - 26, 2, 4);

		y = options.bottom;
		if (options.backLegUp) {
			y -= 4;
		}
		// back leg
		context.fillRect(x + 12, y, 4, 2);
		context.fillRect(x + 12, y - 6, 2, 8);
		context.fillRect(x + 14, y - 6, 2, 3);
		context.fillRect(x + 16, y - 8, 2, 3);

		y = options.bottom;
		if (options.frontLegUp) {
			y -= 6;
		}

		// front leg
		context.fillRect(x + 22, y, 4, 2);
		context.fillRect(x + 22, y - 6, 2, 8);
	}

	function drawBackground(options) {
		var context = options.context,
			x = 0,
			y = options.height;

		context.fillStyle = defaultColour;

		context.fillRect(x, y - 20, options.width, 1);

		for (var i = bits.length - 1; i >= 0; i--) {
			context.fillRect(options.width - ((bits[i].x + options.offset) % options.width), bits[i].y, bits[i].width, 1);
		}
	}

	function drawCactus(options) {
		var context = options.context,
			x = options.left,
			y = options.bottom,
			scale = options.scale;

		context.fillStyle = defaultColour;

		// center
		var height = 15 * options.centerSize;
		context.fillRect(x + 6 * scale, y - (20 + height) * scale, 6 * scale, height * scale);
		context.fillRect(x + 7 * scale, y - (20 + height + 1) * scale, 4 * scale, 1 * scale);
		context.fillRect(x + 6 * scale, y - 20 * scale, 6 * scale, 20 * scale);

		// left
		height = 15 * options.leftSize;
		context.fillRect(x, y - (15 + height) * scale, 4 * scale, height * scale);
		context.fillRect(x + 1 * scale, y - (15 + height + 1) * scale, 2 * scale, 1 * scale);
		context.fillRect(x + 4 * scale, y - 19 * scale, 4 * scale, 4 * scale);

		// right
		height = 15 * options.rightSize;
		context.fillRect(x + 14 * scale, y - (15 + height) * scale, 4 * scale, height * scale);
		context.fillRect(x + 15 * scale, y - (15 + height + 1) * scale, 2 * scale, 1 * scale);
		context.fillRect(x + 12 * scale, y - 19 * scale, 4 * scale, 4 * scale);
	}

	var lastTick = null,
		jumping = false,
		score = 0,
		ground = canvas.height - 10,
		speed = 0.02; // 10 score per second

	function step(timestamp) {
		if (lastTick) {
			score += (timestamp - lastTick) * speed;

			context.clearRect ( 0, 0, canvas.width, canvas.height);

			var offset = score * 10;

			drawBackground({
				context: context,
				width: canvas.width,
				height: canvas.height,
				offset: offset,
			});

			updateCacti(offset);

			for (var i = 0; i < cacti.length; i++) {
				drawCactus({
					context: context,
					left: cacti[i].x - score * 10,
					bottom: canvas.height - 10,
					scale: cacti[i].scale,
					leftSize: cacti[i].leftSize,
					rightSize: cacti[i].rightSize,
					centerSize: cacti[i].centerSize
				});
			}

			drawDinosaur({
				context: context,
				left: 10,
				bottom: ground,
				backLegUp: Math.floor(score) % 3 === 0,
				frontLegUp: Math.floor(score) % 3 === 1
			});
		}
		lastTick = timestamp;
		window.requestAnimationFrame(step);
	}

	generateBits();
	window.requestAnimationFrame(step);

})(window, document, $);<|endoftext|>


<commit_before>var CONF = {
    space_width: 50,
    space_height: 50,
    boid_nbr : 100,

    boid_speed: 2.0,
    boid_range : 5.0,
    boid_sep: 0.005,
    boid_align: 0.0, // 0.00125,
    boid_cohesion: 0.0, //0.025
    boid_anchor_dist: -1.5,
    boid_grap_dist: 1.5,

    player_rot: 5.0,
    player_speed: 6.0,
    key_step: 1,
    min_chain: 3
};

function newBoid(id, x, y, u, v) {
    var g = new BoidGeometry();
    var boid = {
	id: id,
	pos: [ x, y, 0 ],
	v: [ u, v, 0 ],
	speed: CONF.boid_speed,
        geom: g
    };

    boid.update = function(dt, space) {
	var b1 = boid;
	var sep = [0,0,0];
	var align = [0,0,0];
	var cohesion = [0,0,0];

        // I am grabbed to a parent boid
	if (b1.parent !== undefined && b1.parent.anchor) {

            var dir = osg.Vec3.sub(b1.pos, b1.parent.anchor, []);
            var d = osg.Vec3.length(dir);

            var parentPosition = osg.Vec3.copy(b1.parent.pos, []);
            var childPosition = osg.Vec3.copy(b1.pos, []);
            var parentAnchor = osg.Vec3.copy(b1.parent.anchor, []);

            // wrap mode
            if (d > CONF.boid_grap_dist * 3) {
		//b1.timer += dt;
		//if (b1.timer < 5.0) {
                    if (dir[0] > 3*CONF.boid_grap_dist) {
			parentPosition[0] += CONF.space_width;
			parentAnchor[0] += CONF.space_width;
                    } else if (dir[0] < -3*CONF.boid_grap_dist) {
			childPosition [ 0 ] += CONF.space_width;
                    }

                    if (dir[1] > 3*CONF.boid_grap_dist) {
			parentPosition [ 1 ] += CONF.space_height;
			parentAnchor[1] += CONF.space_height;
                    } else if (dir[1] < -3*CONF.boid_grap_dist) {
			childPosition [ 1 ] += CONF.space_height;
                    }
	    /*} else {
		    var bb = b1;
		    delete bb.parent.child;
		    while(bb) {
			var child = bb.child;
			bb.speed = CONF.boid_speed;
			delete bb.parent;
			delete bb.locked;
			delete bb.child;
			bb = child;
		    }
		    return;
		    }*/
            } /*else {
		b1.timer = 0.0;
	    }*/

            var childDirection = [];

            osg.Vec3.sub([ (parentPosition[0] + parentAnchor[0]) / 2 ,
                           (parentPosition[1] + parentAnchor[1]) / 2 ,
                           0, 0], childPosition, childDirection);

            osg.Vec3.normalize(childDirection, b1.v);

            var p = osg.Vec3.normalize(osg.Vec3.sub(childPosition, parentAnchor, []), []);

            osg.Vec3.sub(childPosition, osg.Vec3.mult(p, osg.Vec3.length(p)*dt, []), b1.pos);

            return;
        }

        for(var j=space.boidsList.length-1; j >= 0 ; j--) {
            var b2 = space.boidsList[j];
            if (b1.id === b2.id) {
                continue;
            }

            if (b1.parent === undefined && b2.anchor !== undefined && b2.child === undefined) {
                if (osg.Vec3.length(osg.Vec3.sub(b1.pos, b2.anchor, [])) < CONF.boid_grap_dist) {
                    b1.locked = true;
                    b1.parent = b2;
                    b2.child = b1;
                    b1.speed = b2.speed;

		    for(var bb=b1, count=0; bb !== undefined; count++) {
			bb.count = count;
			bb = bb.parent;
		    }

                    osg.log("LOCKED!");
                    return;
                }
            }

            var dir = osg.Vec3.sub(b1.pos, b2.pos, []);
            var d = osg.Vec3.length(dir);

            if (d > CONF.boid_range) {
                continue;
            }

            var dir_n = osg.Vec3.normalize(dir, []);

            var dot = osg.Vec3.dot(dir_n, b1.v);

            if (b1.id === 0) {
                //                  osg.log(dot);
            }

            // separation
            osg.Vec3.sub(sep, osg.Vec3.mult(dir_n, d, []),  sep);

            // alignement
            osg.Vec3.add(align, b2.v, align);

            // cohesion
            osg.Vec3.sub(cohesion, osg.Vec3.sub(b1.v, b2.v, []), cohesion);

        }
	// separation
	osg.Vec3.sub(b1.v,
		     osg.Vec3.mult(sep, CONF.boid_sep, []),
		     b1.v);

	// alignement
	osg.Vec3.add(b1.v,
		     osg.Vec3.mult(osg.Vec3.normalize(align, align), CONF.boid_align, []),
		     b1.v);

	// cohesion
	osg.Vec3.add(b1.v,
		     osg.Vec3.mult(cohesion, CONF.boid_cohesion, []),
		     b1.v);

	osg.Vec3.normalize(b1.v, b1.v);
    };

    boid.step = function(dt, space) {
	var b = boid;
	b.v[2] = 0.0;
	osg.Vec3.normalize(b.v, b.v);
        var v = osg.Vec3.mult(b.v, dt*b.speed, []);
        osg.Vec3.add(b.pos, v, b.pos);

	// X boundary
	if (b.pos[0] > space.width) {
	    b.pos[0] -= space.width;
	} else if (b.pos[0] < 0) {
	    b.pos[0] += space.width;
	}

	// Y boundary
	if (b.pos[1] > space.height) {
	    b.pos[1] -= space.height;
	} else if (b.pos[1] < 0) {
	    b.pos[1] += space.height;
	}

	b.pos[2] = 0.0;

	if (b.locked) {
	    b.anchor = [];
	    osg.Vec3.add(b.pos, osg.Vec3.mult(b.v, CONF.boid_anchor_dist, []), b.anchor);
	} else {
	    b.anchor = undefined;
	}

        b.geom.updatePosition(b.pos, b.v);
    };

boid.computeAnchorPosition = function(position, result) {
	 osg.Vec3.add(position, osg.Vec3.mult(this.v, CONF.boid_anchor_dist, []), result);
         return result;
     };

    osg.Vec3.normalize(boid.v, boid.v);
    return boid;
}

function newPlayer(id, x, y, u, v) {
    var boid = newBoid(id, x, y, u, v);
    boid.speed = CONF.player_speed;
    boid.vTo = [ boid.v[0], boid.v[1], boid.v[2] ];
    boid.locked = true;
    boid.player = true;
    boid.update = function(dt, space) {

	var b1 = boid;
	if (b1.child !== undefined) {
	    for(var j=space.boidsList.length-1; j >= 0 ; j--) {
		var b2 = space.boidsList[j];
		if (b1.id === b2.id) {
		    continue;
		}

		if (b2.anchor !== undefined && b2.child === undefined && b1.child !== b2 && b1.count > CONF.min_chain) {
		    if (osg.Vec3.length(osg.Vec3.sub(b1.pos, b2.anchor, [])) < CONF.boid_grap_dist) {

			b1.child.parent = b2;
			b2.child = b1.child;

			delete b1.child;

			osg.log("LOCKED!");
			return;
		    }
		}
	    }
	}

	space.ctrl[2] /= 1 + (dt*2);
	//boid.speed = CONF.player_speed + (space.ctrl[2]/5);

	//var v = osg.Vec3.sub(boid.v, boid.vTo, []);
	var ctrl = -space.ctrl[0] + space.ctrl[1];
	//osg.log(ctrl);
	if(ctrl === 0 ) {
	    return;
	}
	var v = osg.Vec3.cross(boid.v, [0,0,1], []);

	osg.Vec3.mult(v, ctrl, v);

	osg.Vec3.add(boid.v, osg.Vec3.mult(v, dt*CONF.player_rot, []), boid.v);
	osg.Vec3.normalize(boid.v, boid.v);

    };
    return boid;
}

function newSpace() {
    var id = 0;
    var W = CONF.space_width;
    var H = CONF.space_height;
    var space = {
	width: W,
	height: H,
	boidsList: [],
	boidsMap: {},
	ctrl: [0, 0, 0]
    };

    space.newRandomBoid = function() {
	var boid;
	if (id === 0) {
	    boid = newPlayer(id++, Math.random()*W, Math.random()*H, 0.5-Math.random(), 0.5-Math.random());
	    space.player1 = boid;
	} else {
	    boid = newBoid(id++, Math.random()*W, Math.random()*H, 0.5-Math.random(), 0.5-Math.random());
	}
	space.boidsList.push(boid);
	space.boidsMap[boid.id] = boid;
	return boid;
    };

    space.update = function(dt) {
	var i;

	for(i=space.boidsList.length-1; i >= 0; i--) {
	    space.boidsList[i].update(dt, space);
	}

	for(i=space.boidsList.length-1; i >= 0; i--) {
            space.boidsList[i].step(dt, space);
        }

    };

    for(var i=0; i < CONF.boid_nbr; i++) {
	space.newRandomBoid();
    }

    return space;
}

var MainUpdate = function() {
    this._lastUpdate = undefined;
    this._space = newSpace();
};

MainUpdate.prototype = {

    playerInput: function(point) {
	//osg.Vec3.normalize(osg.Vec3.sub(this._space.player1.pos, point, []), this._space.player1.vTo);
    },

    playerInputUp: function(event) {
	//osg.log(event);
	if (event.keyCode === 39) {
	    this._space.ctrl[1] = 0;
	    this._space.ctrl[2]++;
	} else if (event.keyCode === 37) {
	    this._space.ctrl[0] = 0;
	    this._space.ctrl[2]++;
	}
    },

    playerInputDown: function(event) {
	//osg.log(event);
	if (event.keyCode === 39) {
	    this._space.ctrl[1] = 1;
	    this._space.ctrl[2]++;
	} else if (event.keyCode === 37) {
	    this._space.ctrl[0] = 1;
	    this._space.ctrl[2]++;
	}
    },

    update: function(node, nv) {
        var t = nv.getFrameStamp().getSimulationTime();
        if (this._lastUpdate === undefined) {
            this._lastUpdate = t;
        }
        var dt = t - this._lastUpdate;

        this._lastUpdate = t;
	this._space.update(dt);

        return true;
    }
};<commit_msg>release on stuck<commit_after>var CONF = {
    space_width: 50,
    space_height: 50,
    boid_nbr : 100,

    boid_speed: 2.0,
    boid_range : 5.0,
    boid_sep: 0.005,
    boid_align: 0.0, // 0.00125,
    boid_cohesion: 0.0, //0.025
    boid_anchor_dist: -1.5,
    boid_grap_dist: 1.5,

    player_rot: 5.0,
    player_speed: 6.0,
    key_step: 1,
    min_chain: 3,
    chain_timer: 3.0
};

function newBoid(id, x, y, u, v) {
    var g = new BoidGeometry();
    var boid = {
	id: id,
	pos: [ x, y, 0 ],
	v: [ u, v, 0 ],
	speed: CONF.boid_speed,
        geom: g
    };

    boid.update = function(dt, space) {
	var b1 = boid;
	var sep = [0,0,0];
	var align = [0,0,0];
	var cohesion = [0,0,0];

        // I am grabbed to a parent boid
	if (b1.parent !== undefined && b1.parent.anchor) {

            var dir = osg.Vec3.sub(b1.pos, b1.parent.anchor, []);
            var d = osg.Vec3.length(dir);

            var parentPosition = osg.Vec3.copy(b1.parent.pos, []);
            var childPosition = osg.Vec3.copy(b1.pos, []);
            var parentAnchor = osg.Vec3.copy(b1.parent.anchor, []);

            // wrap mode
            if (d > CONF.boid_grap_dist * 3) {
		b1.timer += dt;
		if (b1.timer < CONF.chain_timer) {
                    if (dir[0] > 3*CONF.boid_grap_dist) {
			parentPosition[0] += CONF.space_width;
			parentAnchor[0] += CONF.space_width;
                    } else if (dir[0] < -3*CONF.boid_grap_dist) {
			childPosition [ 0 ] += CONF.space_width;
                    }

                    if (dir[1] > 3*CONF.boid_grap_dist) {
			parentPosition [ 1 ] += CONF.space_height;
			parentAnchor[1] += CONF.space_height;
                    } else if (dir[1] < -3*CONF.boid_grap_dist) {
			childPosition [ 1 ] += CONF.space_height;
                    }
		} else {
		    var bb = b1;
		    delete bb.parent.child;
		    while(bb) {
			var child = bb.child;
			bb.speed = CONF.boid_speed;
			delete bb.parent;
			delete bb.child;
			bb.locked = false;
			bb = child;
		    }
		    return;
		}
            } else {
		b1.timer = 0.0;
	    }

            var childDirection = [];

            osg.Vec3.sub([ (parentPosition[0] + parentAnchor[0]) / 2 ,
                           (parentPosition[1] + parentAnchor[1]) / 2 ,
                           0, 0], childPosition, childDirection);

            osg.Vec3.normalize(childDirection, b1.v);

            var p = osg.Vec3.normalize(osg.Vec3.sub(childPosition, parentAnchor, []), []);

            osg.Vec3.sub(childPosition, osg.Vec3.mult(p, osg.Vec3.length(p)*dt, []), b1.pos);

            return;
        }

        for(var j=space.boidsList.length-1; j >= 0 ; j--) {
            var b2 = space.boidsList[j];
            if (b1.id === b2.id) {
                continue;
            }

            if (b1.parent === undefined && b2.anchor !== undefined && b2.child === undefined) {
                if (osg.Vec3.length(osg.Vec3.sub(b1.pos, b2.anchor, [])) < CONF.boid_grap_dist) {
                    b1.locked = true;
                    b1.parent = b2;
                    b2.child = b1;
                    b1.speed = b2.speed;

		    for(var bb=b1, count=0; bb !== undefined; count++) {
			bb.count = count;
			bb = bb.parent;
		    }

                    osg.log("LOCKED!");
                    return;
                }
            }

            var dir = osg.Vec3.sub(b1.pos, b2.pos, []);
            var d = osg.Vec3.length(dir);

            if (d > CONF.boid_range) {
                continue;
            }

            var dir_n = osg.Vec3.normalize(dir, []);

            var dot = osg.Vec3.dot(dir_n, b1.v);

            if (b1.id === 0) {
                //                  osg.log(dot);
            }

            // separation
            osg.Vec3.sub(sep, osg.Vec3.mult(dir_n, d, []),  sep);

            // alignement
            osg.Vec3.add(align, b2.v, align);

            // cohesion
            osg.Vec3.sub(cohesion, osg.Vec3.sub(b1.v, b2.v, []), cohesion);

        }
	// separation
	osg.Vec3.sub(b1.v,
		     osg.Vec3.mult(sep, CONF.boid_sep, []),
		     b1.v);

	// alignement
	osg.Vec3.add(b1.v,
		     osg.Vec3.mult(osg.Vec3.normalize(align, align), CONF.boid_align, []),
		     b1.v);

	// cohesion
	osg.Vec3.add(b1.v,
		     osg.Vec3.mult(cohesion, CONF.boid_cohesion, []),
		     b1.v);

	osg.Vec3.normalize(b1.v, b1.v);
    };

    boid.step = function(dt, space) {
	var b = boid;
	b.v[2] = 0.0;
	osg.Vec3.normalize(b.v, b.v);
        var v = osg.Vec3.mult(b.v, dt*b.speed, []);
        osg.Vec3.add(b.pos, v, b.pos);

	// X boundary
	if (b.pos[0] > space.width) {
	    b.pos[0] -= space.width;
	} else if (b.pos[0] < 0) {
	    b.pos[0] += space.width;
	}

	// Y boundary
	if (b.pos[1] > space.height) {
	    b.pos[1] -= space.height;
	} else if (b.pos[1] < 0) {
	    b.pos[1] += space.height;
	}

	b.pos[2] = 0.0;

	if (b.locked === true) {
	    b.anchor = [];
	    osg.Vec3.add(b.pos, osg.Vec3.mult(b.v, CONF.boid_anchor_dist, []), b.anchor);
	} else {
	    b.anchor = undefined;
	}

        b.geom.updatePosition(b.pos, b.v);
    };

boid.computeAnchorPosition = function(position, result) {
	 osg.Vec3.add(position, osg.Vec3.mult(this.v, CONF.boid_anchor_dist, []), result);
         return result;
     };

    osg.Vec3.normalize(boid.v, boid.v);
    return boid;
}

function newPlayer(id, x, y, u, v) {
    var boid = newBoid(id, x, y, u, v);
    boid.speed = CONF.player_speed;
    boid.vTo = [ boid.v[0], boid.v[1], boid.v[2] ];
    boid.locked = true;
    boid.player = true;
    boid.update = function(dt, space) {

	var b1 = boid;
	if (b1.child !== undefined) {
	    for(var j=space.boidsList.length-1; j >= 0 ; j--) {
		var b2 = space.boidsList[j];
		if (b1.id === b2.id) {
		    continue;
		}

		if (b2.anchor !== undefined && b2.child === undefined && b1.child !== b2 && b1.count > CONF.min_chain) {
		    if (osg.Vec3.length(osg.Vec3.sub(b1.pos, b2.anchor, [])) < CONF.boid_grap_dist) {

			b1.child.parent = b2;
			b2.child = b1.child;

			delete b1.child;

			osg.log("LOCKED!");
			return;
		    }
		}
	    }
	}

	space.ctrl[2] /= 1 + (dt*2);
	//boid.speed = CONF.player_speed + (space.ctrl[2]/5);

	//var v = osg.Vec3.sub(boid.v, boid.vTo, []);
	var ctrl = -space.ctrl[0] + space.ctrl[1];
	//osg.log(ctrl);
	if(ctrl === 0 ) {
	    return;
	}
	var v = osg.Vec3.cross(boid.v, [0,0,1], []);

	osg.Vec3.mult(v, ctrl, v);

	osg.Vec3.add(boid.v, osg.Vec3.mult(v, dt*CONF.player_rot, []), boid.v);
	osg.Vec3.normalize(boid.v, boid.v);

    };
    return boid;
}

function newSpace() {
    var id = 0;
    var W = CONF.space_width;
    var H = CONF.space_height;
    var space = {
	width: W,
	height: H,
	boidsList: [],
	boidsMap: {},
	ctrl: [0, 0, 0]
    };

    space.newRandomBoid = function() {
	var boid;
	if (id === 0) {
	    boid = newPlayer(id++, Math.random()*W, Math.random()*H, 0.5-Math.random(), 0.5-Math.random());
	    space.player1 = boid;
	} else {
	    boid = newBoid(id++, Math.random()*W, Math.random()*H, 0.5-Math.random(), 0.5-Math.random());
	}
	space.boidsList.push(boid);
	space.boidsMap[boid.id] = boid;
	return boid;
    };

    space.update = function(dt) {
	var i;

	for(i=space.boidsList.length-1; i >= 0; i--) {
	    space.boidsList[i].update(dt, space);
	}

	for(i=space.boidsList.length-1; i >= 0; i--) {
            space.boidsList[i].step(dt, space);
        }

    };

    for(var i=0; i < CONF.boid_nbr; i++) {
	space.newRandomBoid();
    }

    return space;
}

var MainUpdate = function() {
    this._lastUpdate = undefined;
    this._space = newSpace();
};

MainUpdate.prototype = {

    playerInput: function(point) {
	//osg.Vec3.normalize(osg.Vec3.sub(this._space.player1.pos, point, []), this._space.player1.vTo);
    },

    playerInputUp: function(event) {
	//osg.log(event);
	if (event.keyCode === 39) {
	    this._space.ctrl[1] = 0;
	    this._space.ctrl[2]++;
	} else if (event.keyCode === 37) {
	    this._space.ctrl[0] = 0;
	    this._space.ctrl[2]++;
	}
    },

    playerInputDown: function(event) {
	//osg.log(event);
	if (event.keyCode === 39) {
	    this._space.ctrl[1] = 1;
	    this._space.ctrl[2]++;
	} else if (event.keyCode === 37) {
	    this._space.ctrl[0] = 1;
	    this._space.ctrl[2]++;
	}
    },

    update: function(node, nv) {
        var t = nv.getFrameStamp().getSimulationTime();
        if (this._lastUpdate === undefined) {
            this._lastUpdate = t;
        }
        var dt = t - this._lastUpdate;

        this._lastUpdate = t;
	this._space.update(dt);

        return true;
    }
};<|endoftext|>


<commit_before>'use strict';

//Generic die constructor
function Die(maul, photo, footprint) {
  this.maul = maul;
  this.photo = photo;
  this.footprint = footprint;
}

//Method for generating random number
Die.prototype.randomNumber = function() {
  var baseNumber = Math.floor(Math.random() * (6) + 1);
  return baseNumber;
};

//Orange die constructor (hardest)
function Orange() {}
Orange.prototype = new Die(3,1,2);
//Blue die constructor (easiest)
function Blue() {}
Blue.prototype = new Die(1,3,2);
//Gray die constructor (medium)
function Gray() {}
Gray.prototype = new Die(2,2,2);

//Roll method for the orange dice
Orange.prototype.roll = function() {
  var random = this.randomNumber();
  console.log(random);
  if (random === 1 || random === 2 || random === 3) {
    return 'bad';
  } else if (random === 4) {
    return 'good';
  } else {
    return 'neutral';
  }
};
//Roll method for the blue dice
Blue.prototype.roll = function() {
  var random = this.randomNumber();
  console.log(random);
  if (random === 1) {
    return 'bad';
  } else if (random === 2 || random === 3 || random === 4) {
    return 'good';
  } else {
    return 'neutral';
  }
};
//Roll method for the gray dice
Gray.prototype.roll = function() {
  var random = this.randomNumber();
  console.log(random);
  if (random === 1 || random === 2) {
    return 'bad';
  } else if (random === 3 || random === 4) {
    return 'good';
  } else {
    return 'netural';
  }
};
<commit_msg>Adding arrays and a function to populate the arrays based on dice type.<commit_after>'use strict';

//Dice type arrays
var orangeDiceArray = [];
var blueDiceArray = [];
var grayDiceArray = [];

//Generic die constructor
function Die(maul, photo, footprint) {
  this.maul = maul;
  this.photo = photo;
  this.footprint = footprint;
  this.lastRoll = '';
}

//Method for generating random number
Die.prototype.randomNumber = function() {
  var baseNumber = Math.floor(Math.random() * (6) + 1);
  return baseNumber;
};

//Orange die constructor (hardest)
function Orange() {}
Orange.prototype = new Die(3,1,2);
//Blue die constructor (easiest)
function Blue() {}
Blue.prototype = new Die(1,3,2);
//Gray die constructor (medium)
function Gray() {}
Gray.prototype = new Die(2,2,2);

//Roll method for the orange dice
Orange.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2 || random === 3) {
    result = 'bad';
  } else if (random === 4) {
    result = 'good';
  } else {
    result = 'neutral';
  }
  this.lastRoll = result;
};
//Roll method for the blue dice
Blue.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1) {
    result = 'bad';
  } else if (random === 2 || random === 3 || random === 4) {
    result = 'good';
  } else {
    result = 'neutral';
  }
  this.lastRoll = result;
};
//Roll method for the gray dice
Gray.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2) {
    result = 'bad';
  } else if (random === 3 || random === 4) {
    result = 'good';
  } else {
    result = 'netural';
  }
  this.lastRoll = result;
};

//iffy to populate the dice arrays on page load
(function populateDieArrays(){
  for(var die = 0; die < 4; die++){
    var orange = new Orange();
    var blue = new Blue();
    var gray = new Gray();

    orangeDiceArray.push(orange);
    blueDiceArray.push(blue);
    grayDiceArray.push(gray);
  }
})();

function startRound(){

}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
  , gcr = new EventEmitter
  , log = require('npmlog')
  , fs = require('fs')
  , nconf = require('nconf')
  , mkdirp = require('mkdirp')
  , path = require('path')
  , home = process.env.HOME || process.env.USERPROFILE || '/root'
  , confFile = path.join(home, '.config', 'gcr.json')
  , slide = require('slide')
  , chain = slide.chain
  , which = require('which')

log.heading = 'gcr'

module.exports = gcr

gcr.root = path.dirname(confFile)
gcr.loaded = false
gcr.version = require('../package').version
gcr.key = path.join(home, '.ssh', 'gcr.pub')

gcr.utils = require('./utils')

gcr.load = function(opts, cb) {
  if ('function' === typeof opts) cb = opts, opts = {}
  if (gcr.loaded) return cb()
  mkdirp(gcr.root, function(err) {
    log.resume()
    if (err) {
      err.heading = '[mkdirp]'
      return cb(err)
    }
    nconf.file({ file: confFile })
    nconf.defaults(require('./config.default')(opts))
    if (opts.url) {
      nconf.set('url', opts.url)
    }
    if (opts.token) {
      nconf.set('token', opts.token)
    }
    if (opts.buildDir) {
      nconf.set('buildDir', opts.buildDir)
    }
    if (opts.npm) {
      nconf.set('npm', opts.npm)
    }
    if (opts.strictSSL) {
      nconf.set('strictSSL', opts.strictSSL)
    }
    if (opts.timeout) {
      nconf.set('timeout', opts.timeout)
    }
    if (!nconf.get('buildDir')) {
      nconf.set('buildDir', '/tmp/builds')
    }
    gcr.config = nconf
    chain([
        validateGit
      , validateSetup
      , saveConfig
    ], cb)
  })
}

function validateGit(cb) {
  if (nconf.get('git')) return cb()
  which('git', function(err, git) {
    if (err) {
      err.heading = '[which]'
      return cb(err)
    }
    nconf.set('git', git)
    cb()
  })
}

function validateSetup(cb) {
  mkdirp(gcr.config.get('buildDir'), function(err) {
    if (err) {
      err.heading = '[mkdirp]'
      return cb && cb(err)
    }

    fs.exists(gcr.key, function(e) {
      if (!e) {
        gcr.utils.genSSHKey(function(err) {
          if (err) {
            err.heading = '[ssh-keygen]'
            return cb && cb(err)
          }
          cb()
        })
      } else {
        cb()
      }
    })
  })
}

function saveConfig(cb) {
  nconf.save(function() {
    log.level = gcr.config.get('loglevel')
    log.heading = gcr.config.get('heading') || 'gcr'
    gcr.log = log
    gcr.loaded = true
    gcr.runner = require('./runner')()
    gcr.client = require('./client')()
    gcr.utils = require('./utils')
    cb()
  })
}

gcr.help = [
    ''
  , 'gcr v'+gcr.version
  , ''
  , '   Usage:'
  , ''
  , '     gcr [options]'
  , ''
  , '   Options:'
  , ''
  , '     -h, --help                  Show help and usage'
  , '     -l, --loglevel <level>      Set log level'
  , '     -v, --version               Show version'
  , '     -u, --url <url>             Set CI Server URL'
  , '     -t, --token <token>         Set Registration Token'
  , '     -T, --timeout <number>      Set the timeout in seconds'
  , '     -b, --buildDir <dir>        Set the builds directory'
  , '     -s, --strictSSL             Strict SSL'
  , '     -n, --npm                   Run npm install/test if no commands '+
    'are present'
  , ''
].join('\n')
<commit_msg>remove duplicate property declaration<commit_after>var EventEmitter = require('events').EventEmitter
  , gcr = new EventEmitter
  , log = require('npmlog')
  , fs = require('fs')
  , nconf = require('nconf')
  , mkdirp = require('mkdirp')
  , path = require('path')
  , home = process.env.HOME || process.env.USERPROFILE || '/root'
  , confFile = path.join(home, '.config', 'gcr.json')
  , slide = require('slide')
  , chain = slide.chain
  , which = require('which')

log.heading = 'gcr'

module.exports = gcr

gcr.root = path.dirname(confFile)
gcr.loaded = false
gcr.version = require('../package').version
gcr.key = path.join(home, '.ssh', 'gcr.pub')

gcr.utils = require('./utils')

gcr.load = function(opts, cb) {
  if ('function' === typeof opts) cb = opts, opts = {}
  if (gcr.loaded) return cb()
  mkdirp(gcr.root, function(err) {
    log.resume()
    if (err) {
      err.heading = '[mkdirp]'
      return cb(err)
    }
    nconf.file({ file: confFile })
    nconf.defaults(require('./config.default')(opts))
    if (opts.url) {
      nconf.set('url', opts.url)
    }
    if (opts.token) {
      nconf.set('token', opts.token)
    }
    if (opts.buildDir) {
      nconf.set('buildDir', opts.buildDir)
    }
    if (opts.npm) {
      nconf.set('npm', opts.npm)
    }
    if (opts.strictSSL) {
      nconf.set('strictSSL', opts.strictSSL)
    }
    if (opts.timeout) {
      nconf.set('timeout', opts.timeout)
    }
    if (!nconf.get('buildDir')) {
      nconf.set('buildDir', '/tmp/builds')
    }
    gcr.config = nconf
    chain([
        validateGit
      , validateSetup
      , saveConfig
    ], cb)
  })
}

function validateGit(cb) {
  if (nconf.get('git')) return cb()
  which('git', function(err, git) {
    if (err) {
      err.heading = '[which]'
      return cb(err)
    }
    nconf.set('git', git)
    cb()
  })
}

function validateSetup(cb) {
  mkdirp(gcr.config.get('buildDir'), function(err) {
    if (err) {
      err.heading = '[mkdirp]'
      return cb && cb(err)
    }

    fs.exists(gcr.key, function(e) {
      if (!e) {
        gcr.utils.genSSHKey(function(err) {
          if (err) {
            err.heading = '[ssh-keygen]'
            return cb && cb(err)
          }
          cb()
        })
      } else {
        cb()
      }
    })
  })
}

function saveConfig(cb) {
  nconf.save(function() {
    log.level = gcr.config.get('loglevel')
    log.heading = gcr.config.get('heading') || 'gcr'
    gcr.log = log
    gcr.loaded = true
    gcr.runner = require('./runner')()
    gcr.client = require('./client')()
    cb()
  })
}

gcr.help = [
    ''
  , 'gcr v'+gcr.version
  , ''
  , '   Usage:'
  , ''
  , '     gcr [options]'
  , ''
  , '   Options:'
  , ''
  , '     -h, --help                  Show help and usage'
  , '     -l, --loglevel <level>      Set log level'
  , '     -v, --version               Show version'
  , '     -u, --url <url>             Set CI Server URL'
  , '     -t, --token <token>         Set Registration Token'
  , '     -T, --timeout <number>      Set the timeout in seconds'
  , '     -b, --buildDir <dir>        Set the builds directory'
  , '     -s, --strictSSL             Strict SSL'
  , '     -n, --npm                   Run npm install/test if no commands '+
    'are present'
  , ''
].join('\n')
<|endoftext|>


<commit_before>/**
 * Get git config values.
 * @function get
 * @param {string} [namespace] - Namespace to get.
 * @param {object} options - Optional settings.
 * @param {string} [options.location] - Config file location. (global, system, or local)
 * @param {function} callback - Callback when done.
 */

"use strict";

var argx = require('argx'),
    async = require('async'),
    childProcess = require('child_process'),
    os = require('os'),
    objnest = require('objnest');

/** @lends get */
function get(namespace, options, callback) {
    var args = argx(arguments);
    callback = args.pop('function') || argx.noop;
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    async.waterfall([
        function (callback) {
            var cmd = _getCommand(options.location);
            childProcess.exec(cmd, callback);
        },
        function (stdout, stderr, callback) {
            if (stderr) {
                callback(new Error(stderr));
                return;
            }
            var config = _parseStdout(stdout, namespace);
            callback(null, config);
        }
    ], callback);
}

get.sync = function (namespace, options) {
    var args = argx(arguments);
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    var cmd = _getCommand(options.location);
    var stdout = childProcess.execSync(cmd);
    return _parseStdout(stdout, namespace);
};

function _getCommand(location) {
    var cmd = 'git config --list';
    if (location) {
        cmd += (' --' + location);
    }
    return cmd;
}
function _parseStdout(stdout, namespace) {
    var config = {};
    String(stdout).split(os.EOL).forEach(function (line) {
        if (!line) {
            return;
        }
        var keyVal = line.split('=');
        var key = keyVal.shift(),
            val = keyVal.pop();
        if (val === undefined) {
            return;
        }
        config[key] = val;
    });
    config = objnest.expand(config);
    if (namespace) {
        config = config[namespace];
    }
    return config;
}

module.exports = get;
<commit_msg>Adds support for dot notation in namespaces<commit_after>/**
 * Get git config values.
 * @function get
 * @param {string} [namespace] - Namespace to get.
 * @param {object} options - Optional settings.
 * @param {string} [options.location] - Config file location. (global, system, or local)
 * @param {function} callback - Callback when done.
 */

"use strict";

var argx = require('argx'),
    async = require('async'),
    childProcess = require('child_process'),
    os = require('os'),
    objnest = require('objnest');

/** @lends get */
function get(namespace, options, callback) {
    var args = argx(arguments);
    callback = args.pop('function') || argx.noop;
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    async.waterfall([
        function (callback) {
            var cmd = _getCommand(options.location);
            childProcess.exec(cmd, callback);
        },
        function (stdout, stderr, callback) {
            if (stderr) {
                callback(new Error(stderr));
                return;
            }
            var config = _parseStdout(stdout, namespace);
            callback(null, config);
        }
    ], callback);
}

get.sync = function (namespace, options) {
    var args = argx(arguments);
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    var cmd = _getCommand(options.location);
    var stdout = childProcess.execSync(cmd);
    return _parseStdout(stdout, namespace);
};

function _getCommand(location) {
    var cmd = 'git config --list';
    if (location) {
        cmd += (' --' + location);
    }
    return cmd;
}
function _parseStdout(stdout, namespace) {
    console.log('Parsing stdout')
    var config = {};
    String(stdout).split(os.EOL).forEach(function (line) {
        if (!line) {
            return;
        }
        var keyVal = line.split('=');
        var key = keyVal.shift(),
            val = keyVal.pop();
        if (val === undefined) {
            return;
        }
        config[key] = val;
    });
    config = objnest.expand(config);
    if (namespace) {
        var namespaceSplit = namespace.split('.')
        if (namespaceSplit.length === 1) {
            config = config[namespace];
        } else {
            namespaceSplit.forEach(function (namespace) {
                config = config[namespace]
            })
        }
    }
    return config;
}

module.exports = get;
<|endoftext|>


<commit_before>(function ($) {
	$(function () {
		//$(".dropdown-button").dropdown();
		$('.button-collapse').sideNav({
			menuWidth: 320, // Default is 240
			edge: 'left', // Choose the horizontal origin
			closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor
		});
		$('.scrollspy').scrollSpy();
		$('.slider').slider({
			full_width: true,
			indicators: true,
			height: 600,
			transition: 500,
			interval: 6000
		});
		$('.modal-trigger').leanModal();
		$('.carousel').carousel({
			time_constant: 200,
			dist: -50,
			shift: 40,
			padding: 50,
			//full_width: -100
		});
		nextCarousel();
	}); // end of document ready
})(jQuery); // end of jQuery name space
var intervalID = window.setInterval(nextCarousel, 3000);

function nextCarousel() {
	$('.carousel').carousel('next');
}
<commit_msg>Style Change<commit_after>(function ($) {
	$(function () {
		//$(".dropdown-button").dropdown();
		$('.button-collapse').sideNav({
			menuWidth: 320, // Default is 240
			edge: 'left', // Choose the horizontal origin
			closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor
		});
		$('.scrollspy').scrollSpy();
		$('.slider').slider({
			full_width: true,
			indicators: true,
			height: 600,
			transition: 500,
			interval: 6000
		});
		$('.modal-trigger').leanModal();
		$('.carousel').carousel({
			time_constant: 400,
			dist: -12,
			shift: 2,
			padding: 24,
			//full_width: 100
		});
		nextCarousel();
	}); // end of document ready
})(jQuery); // end of jQuery name space
var intervalID = window.setInterval(nextCarousel, 4000);

function nextCarousel() {
	$('.carousel').carousel('next');
}
<|endoftext|>


<commit_before>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

var play_html = '

';
var pause_html = '

';
var download_html = '

';
var bar_html = '

';
var inside_bar_html = '

';

SC.initialize({
  client_id: 'e58500f22069ebf6de412ec63b4939b3'
});

splitOnBar = function(s, d){
  var splitTitle = s.split("|");
  if (splitTitle.length == 2) return splitTitle;
  if (d == null || d == "") d = " ";
  return [s,d];
}

// stream track id 293
$(document).ready(function(){

  SC.get('/playlists/51633482', function(playlist) {
    if (playlist.tracks.length < 6){
      $('#tracks1').parent().addClass("col-sm-offset-3")
                   .removeClass("sm-50px-padding-right")
                   .removeClass("sm-right-border");
      $('#tracks2').parent().hide();
    }
    $(playlist.tracks.slice(0,10)).each(function(i,e){
      var trackDiv = $('

')
        .appendTo(i < 5 ? '#tracks1' : '#tracks2');
      $("
" + splitOnBar(e.title, e.description)[0] + "
").appendTo(trackDiv);
      $('
' + splitOnBar(e.title, e.description)[1] + "
").appendTo(trackDiv);
      var play = $(play_html).appendTo(trackDiv);
      var pause = $(pause_html).appendTo(trackDiv);
      pause.hide();
      var download = $(download_html).appendTo(trackDiv);
      var bar = $(bar_html).appendTo(trackDiv);
      var inside_bar = $(inside_bar_html).appendTo(bar);
      SC.stream("/tracks/" + e.id, function(sound){
        var intrvl;
        play.click(function(){
            sound.play();
            play.hide();
            pause.show();
            intrvl = setInterval(function () {
                var end = parseFloat(e.duration);
                var howMuchSoFar = parseFloat(sound.position);
                var fraction = howMuchSoFar / end;
                var percent = (fraction * parseFloat(100)) + "%";
                $(inside_bar).css("width", percent);
            }, 500);
        });
        pause.click(function(){
            clearInterval(intrvl);
            sound.pause();
            pause.hide();
            play.show();
        });
        download.click(function(){
          window.location = e.download_url + "?client_id=e58500f22069ebf6de412ec63b4939b3";
        });
      });
    });
  });
});<commit_msg>added nbsp<commit_after>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

var play_html = '

';
var pause_html = '

';
var download_html = '

';
var bar_html = '

';
var inside_bar_html = '

';

SC.initialize({
  client_id: 'e58500f22069ebf6de412ec63b4939b3'
});

splitOnBar = function(s, d){
  var splitTitle = s.split("|");
  if (splitTitle.length == 2) return splitTitle;
  if (d == null || d == "") d = " ";
  return [s,d];
}

// stream track id 293
$(document).ready(function(){

  SC.get('/playlists/51633482', function(playlist) {
    if (playlist.tracks.length < 6){
      $('#tracks1').parent().addClass("col-sm-offset-3")
                   .removeClass("sm-50px-padding-right")
                   .removeClass("sm-right-border");
      $('#tracks2').parent().hide();
    }
    $(playlist.tracks.slice(0,10)).each(function(i,e){
      var trackDiv = $('

')
        .appendTo(i < 5 ? '#tracks1' : '#tracks2');
      $("
" + splitOnBar(e.title, e.description)[0] + "
").appendTo(trackDiv);
      $('
' + splitOnBar(e.title, e.description)[1] + "
").appendTo(trackDiv);
      var play = $(play_html).appendTo(trackDiv);
      var pause = $(pause_html).appendTo(trackDiv);
      pause.hide();
      var download = $(download_html).appendTo(trackDiv);
      var bar = $(bar_html).appendTo(trackDiv);
      var inside_bar = $(inside_bar_html).appendTo(bar);
      SC.stream("/tracks/" + e.id, function(sound){
        var intrvl;
        play.click(function(){
            sound.play();
            play.hide();
            pause.show();
            intrvl = setInterval(function () {
                var end = parseFloat(e.duration);
                var howMuchSoFar = parseFloat(sound.position);
                var fraction = howMuchSoFar / end;
                var percent = (fraction * parseFloat(100)) + "%";
                $(inside_bar).css("width", percent);
            }, 500);
        });
        pause.click(function(){
            clearInterval(intrvl);
            sound.pause();
            pause.hide();
            play.show();
        });
        download.click(function(){
          window.location = e.download_url + "?client_id=e58500f22069ebf6de412ec63b4939b3";
        });
      });
    });
  });
});<|endoftext|>


<commit_before>define([
  "lodash",
  "bluebird",
  "./errors",
  "./query"
], function (_, Promise, Errors, Query) {

  Promise.longStackTraces();

  var IndexedDB, IDBKeyRange;

  IndexedDB = window.indexedDB ||
              window.webkitIndexedDB ||
              window.mozIndexedDB ||
              window.oIndexedDB ||
              window.msIndexedDB;
  IDBKeyRange = window.IDBKeyRange ||
                window.webkitIDBKeyRange;

  if (_.isUndefined(IndexedDB)) {
    throw new Errors.IndexedDbNotFound();
  }

  var getCursor = function (store) {
    var keyRange = IDBKeyRange.lowerBound(0);
    return store.openCursor(keyRange);
  };

  var getIndexedCursor = function (store, indexedField, indexedValue) {
    var keyRange = IDBKeyRange.only(indexedValue);
    return store.index(indexedField).openCursor(keyRange);
  };

  var accumulateResults = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      records.push(cursor.value);
    }
    cursor.continue();
  };

  var oneResult = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      records.push(cursor.value);
      return;
    }
    cursor.continue();
  };

  var deleteDatabase = function (dbName) {
    var request = IndexedDB.deleteDatabase(dbName);
    return new Promise(function (resolve, reject) {
      request.onsuccess = function (/* e */) {
        resolve();
      };

      request.onblocked = function (/* e */) {
        reject(true);
      };

      request.onerror = function (/* e */) {
        reject();
      };
    });
  };

  var openDatabase = function (dbName, schemaUpdateFn, version) {
    var connection, updateRequired;

    connection = version ?
      IndexedDB.open(dbName, version) :
      IndexedDB.open(dbName);

    updateRequired = !!schemaUpdateFn;

    return new Promise(function (resolve, reject) {
      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e.target.error));
      };

      connection.onsuccess = function (e) {
        var
          db = e.target.result,
          currentVersion = db.version;

        if (schemaUpdateFn && updateRequired) {
          db.close();
          resolve(openDatabase(dbName, schemaUpdateFn, currentVersion + 1));
        }

        resolve(e.target.result);
      };

      connection.onupgradeneeded = function (e) {
        var db = e.target.result;
        schemaUpdateFn(db);
        updateRequired = false;
      };
    });
  };

  var _createObjectStore = function (db, options) {
    if (!db.objectStoreNames.contains(options.dsName)) {
      var datastore = db.createObjectStore(options.dsName, {
        keyPath: options.keyPath,
        autoIncrement: options.autoIncrement
      });

      _.each(options.indexes, function (fieldOptions, fieldName) {
        datastore.createIndex(fieldName, fieldName, fieldOptions);
      });
    }
  };

  var createObjectStore = function (options) {
    return openDatabase(options.dbName, function (db) {
      _createObjectStore(db, options);
    }).then(function (db) {
      db.close();
    });
  };

  var deleteObjectStore = function (options) {
    return openDatabase(options.dbName, function (db) {
      db.deleteObjectStore(options.dsName);
    });
  };

  var createConfigIfMissing = function (dbName) {
    var connection = IndexedDB.open(dbName);

    return new Promise(function (resolve, reject) {
      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      connection.onsuccess = function (e) {
        var db = e.target.result;
        db.close();
        resolve();
      };

      connection.onupgradeneeded = function (e) {
        var db = e.target.result;
        _createObjectStore(db, {
          dsName: "_config",
          autoIncrement: false,
          keyPath: "dsName"
        });
      };
    });
  };

  var getMany = function (options) {
    options = options || {};

    var _db,
      query = new Query(options.query);

    return openDatabase(options.dbName)
      .then(function (db) {
        _db = db;

        var
          records = [],
          transaction = db.transaction([options.dsName], "readwrite"),
          store = transaction.objectStore(options.dsName),
          cursor = options.indexedFieldName ?
            getIndexedCursor(store, options.indexedFieldName, options.indexedValue) :
            getCursor(store);

        cursor.onsuccess = options.findMany ?
          _.partial(accumulateResults, records, query) :
          _.partial(oneResult, records, query);

        return new Promise(function (resolve, reject) {
          cursor.onerror = function (e) {
            reject(new Errors.CursorError(e));
          };

          transaction.oncomplete = function (/* e */) {
            resolve(records);
          };

          transaction.onerror = function (e) {
            reject(new Errors.TransactionError(e));
          };
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  var addMany = function (options) {
    var _db;
    options = options || {};

    return openDatabase(options.dbName)
      .then(function (db) {
        var transaction, store;
        _db = db;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);

        return new Promise(function (resolve, reject) {
          var
            ids = [];

          _.each(options.records, function (record) {
            var
              request = store.add(record);
            request.onsuccess = function (e) {
              ids.push(e.target.result);
            };
          });

          transaction.oncomplete = function (/* e */) {
            resolve(ids);
          };

          transaction.onerror = function (e) {
            reject(new Errors.TransactionError(e));
          };
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  var _update = function (newProperties, query, e) {
    var
      cursor = e.target.result,
      value = cursor.value;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      _.extend(value, newProperties);
      cursor.update(value);
    }
    cursor.continue();
  };

  var update = function (options) {
    var _db,
      query = new Query(options.query);

    return openDatabase(options.dbName)
      .then(function (db) {
        _db = db;
        var
          transaction = db.transaction([options.dsName], "readwrite"),
          store = transaction.objectStore(options.dsName),
          cursor = getCursor(store);

        cursor.onsuccess = _.partial(_update, options.newProperties, query);

        return new Promise(function (resolve, reject) {
          cursor.onerror = function (e) {
            reject(new Errors.CursorError(e));
          };

          transaction.oncomplete = function (/* e */) {
            resolve();
          };

          transaction.onerror = function (e) {
            reject(new Errors.TransactionError(e));
          };
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  var del = function (options) {
    var _db;
    return openDatabase(options.dbName)
      .then(function (db) {
        _db = db;
        var
          transaction = db.transaction([options.dsName], "readwrite"),
          store = transaction.objectStore(options.dsName);

        _.each(options.keys, function (key) {
          store.delete(key);
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  return {
    getMany: getMany,
    addMany: addMany,
    update: update,
    del: del,
    createObjectStore: createObjectStore,
    createConfigIfMissing: createConfigIfMissing,
    deleteDatabase: deleteDatabase,
    deleteObjectStore: deleteObjectStore
  };
});
<commit_msg>ensure database is closed when it should be<commit_after>define([
  "lodash",
  "bluebird",
  "./errors",
  "./query"
], function (_, Promise, Errors, Query) {

  Promise.longStackTraces();

  var IndexedDB, IDBKeyRange;

  IndexedDB = window.indexedDB ||
              window.webkitIndexedDB ||
              window.mozIndexedDB ||
              window.oIndexedDB ||
              window.msIndexedDB;
  IDBKeyRange = window.IDBKeyRange ||
                window.webkitIDBKeyRange;

  if (_.isUndefined(IndexedDB)) {
    throw new Errors.IndexedDbNotFound();
  }

  var getCursor = function (store) {
    var keyRange = IDBKeyRange.lowerBound(0);
    return store.openCursor(keyRange);
  };

  var getIndexedCursor = function (store, indexedField, indexedValue) {
    var keyRange = IDBKeyRange.only(indexedValue);
    return store.index(indexedField).openCursor(keyRange);
  };

  var accumulateResults = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      records.push(cursor.value);
    }
    cursor.continue();
  };

  var oneResult = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      records.push(cursor.value);
      return;
    }
    cursor.continue();
  };

  var deleteDatabase = function (dbName) {
    var request = IndexedDB.deleteDatabase(dbName);
    return new Promise(function (resolve, reject) {
      request.onsuccess = function (/* e */) {
        resolve();
      };

      request.onblocked = function (/* e */) {
        reject(true);
      };

      request.onerror = function (/* e */) {
        reject();
      };
    });
  };

  var openDatabase = function (dbName, schemaUpdateFn, version) {
    var connection, updateRequired;

    connection = version ?
      IndexedDB.open(dbName, version) :
      IndexedDB.open(dbName);

    updateRequired = !!schemaUpdateFn;

    return new Promise(function (resolve, reject) {
      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e.target.error));
      };

      connection.onsuccess = function (e) {
        var
          db = e.target.result,
          currentVersion = db.version;

        if (schemaUpdateFn && updateRequired) {
          db.close();
          resolve(openDatabase(dbName, schemaUpdateFn, currentVersion + 1));
        }

        resolve(e.target.result);
      };

      connection.onupgradeneeded = function (e) {
        var db = e.target.result;
        schemaUpdateFn(db);
        updateRequired = false;
      };
    });
  };

  var _createObjectStore = function (db, options) {
    if (!db.objectStoreNames.contains(options.dsName)) {
      var datastore = db.createObjectStore(options.dsName, {
        keyPath: options.keyPath,
        autoIncrement: options.autoIncrement
      });

      _.each(options.indexes, function (fieldOptions, fieldName) {
        datastore.createIndex(fieldName, fieldName, fieldOptions);
      });
    }
  };

  var createObjectStore = function (options) {
    return openDatabase(options.dbName, function (db) {
      _createObjectStore(db, options);
    }).finally(function (db) {
      db.close();
    });
  };

  var deleteObjectStore = function (options) {
    return openDatabase(options.dbName, function (db) {
      db.deleteObjectStore(options.dsName);
    }).finally(function (db) {
      db.close();
    });
  };

  var createConfigIfMissing = function (dbName) {
    var connection = IndexedDB.open(dbName);

    return new Promise(function (resolve, reject) {
      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      connection.onsuccess = function (e) {
        var db = e.target.result;
        db.close();
        resolve();
      };

      connection.onupgradeneeded = function (e) {
        var db = e.target.result;
        _createObjectStore(db, {
          dsName: "_config",
          autoIncrement: false,
          keyPath: "dsName"
        });
      };
    });
  };

  var getMany = function (options) {
    options = options || {};

    var _db,
      query = new Query(options.query);

    return openDatabase(options.dbName)
      .then(function (db) {
        _db = db;

        var
          records = [],
          transaction = db.transaction([options.dsName], "readwrite"),
          store = transaction.objectStore(options.dsName),
          cursor = options.indexedFieldName ?
            getIndexedCursor(store, options.indexedFieldName, options.indexedValue) :
            getCursor(store);

        cursor.onsuccess = options.findMany ?
          _.partial(accumulateResults, records, query) :
          _.partial(oneResult, records, query);

        return new Promise(function (resolve, reject) {
          cursor.onerror = function (e) {
            reject(new Errors.CursorError(e));
          };

          transaction.oncomplete = function (/* e */) {
            resolve(records);
          };

          transaction.onerror = function (e) {
            reject(new Errors.TransactionError(e));
          };
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  var addMany = function (options) {
    var _db;
    options = options || {};

    return openDatabase(options.dbName)
      .then(function (db) {
        var transaction, store;
        _db = db;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);

        return new Promise(function (resolve, reject) {
          var
            ids = [];

          _.each(options.records, function (record) {
            var
              request = store.add(record);
            request.onsuccess = function (e) {
              ids.push(e.target.result);
            };
          });

          transaction.oncomplete = function (/* e */) {
            resolve(ids);
          };

          transaction.onerror = function (e) {
            reject(new Errors.TransactionError(e));
          };
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  var _update = function (newProperties, query, e) {
    var
      cursor = e.target.result,
      value = cursor.value;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      _.extend(value, newProperties);
      cursor.update(value);
    }
    cursor.continue();
  };

  var update = function (options) {
    var _db,
      query = new Query(options.query);

    return openDatabase(options.dbName)
      .then(function (db) {
        _db = db;
        var
          transaction = db.transaction([options.dsName], "readwrite"),
          store = transaction.objectStore(options.dsName),
          cursor = getCursor(store);

        cursor.onsuccess = _.partial(_update, options.newProperties, query);

        return new Promise(function (resolve, reject) {
          cursor.onerror = function (e) {
            reject(new Errors.CursorError(e));
          };

          transaction.oncomplete = function (/* e */) {
            resolve();
          };

          transaction.onerror = function (e) {
            reject(new Errors.TransactionError(e));
          };
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  var del = function (options) {
    var _db;
    return openDatabase(options.dbName)
      .then(function (db) {
        _db = db;
        var
          transaction = db.transaction([options.dsName], "readwrite"),
          store = transaction.objectStore(options.dsName);

        _.each(options.keys, function (key) {
          store.delete(key);
        });
      })
      .finally(function () {
        _db.close();
      });
  };

  return {
    getMany: getMany,
    addMany: addMany,
    update: update,
    del: del,
    createObjectStore: createObjectStore,
    createConfigIfMissing: createConfigIfMissing,
    deleteDatabase: deleteDatabase,
    deleteObjectStore: deleteObjectStore
  };
});
<|endoftext|>