<commit_before>#!/usr/bin/env node

var debug = true;

// include packages
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var minimist = require('minimist');
var moment = require('moment');
require('moment-duration-format');
var sqlite = require('sqlite3');
var os = require('os');
var tmpdir = (os.tmpdir || os.tmpDir)();
var printf = require('sprintf-js').sprintf;
var readline = require('readline');

// parse commandline args
var argv = minimist(process.argv.slice(2), {
	alias: { v: 'verbose', h: 'help', c: 'client', s: 'short', t: 'title', d: 'description', f: 'filter' }
});

// create data directory and config
var dbopen = false;
var HOME = process.env.HOME || process.env.USERPROFILE;
var datadir = argv.datadir || path.join(HOME, '.tim');
mkdirp.sync(datadir);
var confpath = path.join(datadir, 'settings.json');
var conf;
try { conf = fs.statSync(confpath) } catch (err) { conf = { isFile: function () { return false; } } }
conf = (conf.isFile()) ? fs.readFileSync(confpath, { encoding: 'utf8' }).toString() : "";
conf = (conf.trim() === "") ? {} : JSON.parse(conf);

//TODO: make this setting accessable for the user in order to let him save it in dropbox or so
var dblogging = console.log;
var dbname = (process.env.DEV) ? 'db.dev.sqlite' : 'db.sqlite';
debuglog("dbname: " + dbname);
var m = require('./model.js')(path.join(datadir, dbname), debug);

/**
 *  processes commandline args
 */
function proc(argv) {

	var verb = argv._[0];
	if (argv.h) {
		usage(0);
	}

	// ##### SEARCH #####
	// search something on the database
	// for now you can only search clients
	else if (verb === 'search') {
		var target = argv._[1];
		if (target === 'help')
			return usage('search', false);
		// search clients
		if (target === 'client' || !target) {
			var spattern = "";
			var stype = "";
			if (argv.c || argv.name) {
				spattern = (argv.c) ? argv.c : argv.name;
				stype = "name";
			}
			else if (argv.s) {
				spattern = argv.s;
				stype = "short";
			}
			else {
				//console.log("Please specify a client name with -c|--client or a short key with -s|--short!");
				return usage('search', true);
			}

			getClient(spattern, stype, function (err, clients) {
				if (err) {
					console.log(err);
					process.exit(-1);
				}
				if (typeof clients == 'undefined' || ! clients) {
					console.log('No clients with that name or short-code found!\n');
					return 0;
				}

				console.log(printf("%-5s | %-15s | %-20s | %-6s | %-20s | %-10s", "ID", "Name", "Street 1", "Zip", "City", "Shortkey"));
				clients.forEach(function(client) {
					console.log(printf("%-5s | %-15s | %-20s | %-6s | %-20s | %-10s", client.id, client.name, stripNull(client.street1), stripNull(client.zip), stripNull(client.city), stripNull(client.short)));
				});
			});
		}
    else {
      return usage('search', true);
    }
	}

	// ##### ADD #####
	// add a client to the database
	else if (verb === 'add') {
		var type = argv._[1];
		if (type === 'client') {
			if (typeof argv.name === 'undefined' || argv.name.trim() === "") {
				console.log("Please supply at least a name for the new customer!");
				process.exit(-1);
			}
			m.Client.create({
				$name: argv.name,
				$street1: argv.street1 || "",
				$zip: argv.zip+"" || "",
					$city: argv.city || "",
					$street2: argv.street2 || "",
						$short: argv.short || null
			});
		}
		else {
			usage('add', true);
		}
	}

	// ###### START ####
	// start time measurement
	else if (verb === 'start') {
		var spattern = "";
		var stype = "";

		// get search type for client
		if (argv.c) {
			spattern = argv.c;
			stype = "name";
		}
		else if (argv.s) {
			spattern = argv.s;
			stype = "short";
		}
		else {
			console.log("Please specify a client name with -c|--client or a short key with -s|--short!");
			return;
		}

		getClient(spattern, stype, function(err, clients) {
			if (err) {
				console.log(err);
				process.exist(-1);
			}

			if (typeof clients === 'undefined' || clients === null) {
				console.log("No clients with that search pattern found!");
				process.exit(-1);
			}

			if (clients.length > 1) {
				//TODO: ask which client to use
				console.log("there's more than one client in the result set!");
				process.exit(-1);
			}
			else {
				timeTrack(clients, argv.t, argv.d, argv.start);
			}
		});
	}

	// ##### STATUS ####
	// print status of time measurement
	else if (verb === 'status') {
		m.Time.status(function (err, data) {
			if (err)
				console.log("There was an error while querying for actual status: " + err);

      // output status information if there's an open time track
			if (data) {
				// found a record, telling the user about the status
				console.log(printf("Time tracking started!\n\t%-15s %s\n\t%-15s %s\n\t%-15s %s\n\t%-15s %s\n\t%-15s %s",
                          "Client:",
                          data.row.clientname,
                          "Title:",
                          data.row.title,
                          "Description:",
                          data.row.description,
                          "Since:",
                          moment(data.row.start).format('llll'),
                          "Duration:",
                          data.diff.format('H [h] m [min] s [sec]')));
      }
      else {
        console.log("No time tracking running!");
      }
		});
	}

  // ##### STOP ####
  // stop time tracking
  else if (verb === 'stop') {
    var end = (argv.end) ? argv.end : new Date();

    m.Time.stop(end, function(err) {
      if (err)
        console.log("There was an error ending the timetracking:\n" + err);
    });
  }

  // #### LIST ####
  // list tracked times
  else if (verb === 'list') {
    var filts = null;
    if (argv.f) {
      var filts = JSON.parse(argv.f);
    }

    m.Time.list(filts, function(err, rows) {
      if (!err)
        console.log(JSON.stringify(rows, null, 2));
      else
        throw err;
    });
  }

  // #### HELP ####
  // output help for parameter
  else if (verb === 'help') {
    usage(argv._[1], false);
  }

	// ##### TEST ####
	// for testing stuff
	else if (verb === 'test') {
		var inv = require('./invoice.js')("./tpl/invoice.ejs");
    var cli = { "name": "Kunde", "street1": "Kundenstraße 15", "street2": "Apartment 1a", "zip": 55411, "city": "Bingen" };
    var pos = [{ "title": "Programmierung", "quantity": 5, "value": 20, "description": "code tests" }, { "title": "Programmierung", "quantity": 5, "value": 20, "description": "code tests" }];
    inv.create(cli, pos, 10, new Date());
	}

  else if (verb === 'init') {
    m.initDb();
  }

	else {
		usage(null, true);
	}
}

/**
 * starts timetracking for a specific client.
 * mandatory parameters:
 * - client
 * - title
 */
function timeTrack(client, title, description, date, action) {
	action = typeof action === 'undefined' ? "start" : action;
	if (typeof client === 'undefined' || client === null)
		throw "Please specify a client to track the time for!";
	if (typeof title === 'undefined' || title === null)
		throw "You need to specify a title!";
	description = typeof description !== 'undefined' ? description : null;

	// parse date here
	date = typeof date !== 'undefined' ? new Date(date) : new Date();
	if (!(date instanceof Date || date.toString() === "Invalid Date"))
		throw "This is not a valid Date";

	//debuglog('\nClient object:\n', JSON.stringify(client, null, 2));
	if (action === 'start') {
		m.Time.start(client, title, description, date, function (err) {
			if (err)
				throw err;
			else
				console.log("insert successful!");
		});
	}
	else if (action === 'stop') {
		//TODO implement
	}
}

/**
 * gets clients based on search-pattern (spattern) and search-type (stype)
 * and passes the results to callback
 */
function getClient(spattern, stype, callback) {
	// search for client name
	if (stype==='name') {
		debuglog("searching client by name: " + spattern);
		m.Client.findByName({ $name: spattern	}, callback)
	}
	// search for short code
	else if (stype==='short') {
		debuglog("searching client by shortkey:" + spattern);
		m.Client.findByKey({ $short: spattern }, callback);
	}
	else {
		console.log("Not a valid search option: " + stype);
		process.exit(-1);
	}
}

/**
 * saves the configuration
 */
function saveConfig() {
	fs.writeFileSync(confpath, JSON.stringify(conf), { encoding: 'utf8' }, function (err) {
		if (err) throw err;
		console.log('Config saved!');
	});
}

/**
 * prints usage information for tim
 */
function usage(arg, invalid) {
	// parse arguments
	invalid = typeof invalid === 'undefined' ? false : invalid;
	if (invalid) console.log("Invalid command!");

	// define usage strings
	var usage = new Array();

	// help for search keyword
	usage['search'] = new Array();
	usage['search'][0] = "\ttim search [client] (-c|--client pattern)|(-s|--short key)";

	// help for add keyword
	usage['add'] = new Array();
	usage['add'][0] = "\ttim add client -c|--client ClientName [--street1 value] [--street2 value] [--zip zip] [--city city] [--short shortkey]";

  // start keyword
  usage['start'] = new Array();
  usage['start'][0] = "\ttim start ((-c|--client ClientName)|(-s|--short ShortKey)) -t|--title Title [--description] [--start StartTime]";

  usage['status'] = new Array();
  usage['status'][0] = "\ttim status";

  usage['stop'] = new Array();
  usage['stop'][0] = "\ttim stop [--end EndTime]";

	// output usage / help
	console.log("Usage - incomplete but please go ahead and read what's already there:\n");
	if (arg && usage[arg] != undefined) {
		console.log("Usage for tim " + arg + ":");
		usage[arg].forEach(function (val) {
			console.log(val);
		});
	}
	else {
		for (var usg in usage) {
			usage[usg].forEach(function (val) {
				console.log(val);
			});
		}
	}

	process.exit(invalid ? -1 : 0);
}

function debuglog(str) {
	if (debug)
		console.log("[DEBUG] " + str);
}

function stripNull(str) {
	if (typeof str === 'undefined' || str === null)
		return "";
	else
		return str;
}

proc(argv);
<commit_msg>fixed issue with --end parameter not parsing dates when calling tim stop<commit_after>#!/usr/bin/env node

var debug = true;

// include packages
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var minimist = require('minimist');
var moment = require('moment');
require('moment-duration-format');
var sqlite = require('sqlite3');
var os = require('os');
var tmpdir = (os.tmpdir || os.tmpDir)();
var printf = require('sprintf-js').sprintf;
var readline = require('readline');

// parse commandline args
var argv = minimist(process.argv.slice(2), {
	alias: { v: 'verbose', h: 'help', c: 'client', s: 'short', t: 'title', d: 'description', f: 'filter' }
});

// create data directory and config
var dbopen = false;
var HOME = process.env.HOME || process.env.USERPROFILE;
var datadir = argv.datadir || path.join(HOME, '.tim');
mkdirp.sync(datadir);
var confpath = path.join(datadir, 'settings.json');
var conf;
try { conf = fs.statSync(confpath) } catch (err) { conf = { isFile: function () { return false; } } }
conf = (conf.isFile()) ? fs.readFileSync(confpath, { encoding: 'utf8' }).toString() : "";
conf = (conf.trim() === "") ? {} : JSON.parse(conf);

//TODO: make this setting accessable for the user in order to let him save it in dropbox or so
var dblogging = console.log;
var dbname = (process.env.DEV) ? 'db.dev.sqlite' : 'db.sqlite';
debuglog("dbname: " + dbname);
var m = require('./model.js')(path.join(datadir, dbname), debug);

/**
 *  processes commandline args
 */
function proc(argv) {

	var verb = argv._[0];
	if (argv.h) {
		usage(0);
	}

	// ##### SEARCH #####
	// search something on the database
	// for now you can only search clients
	else if (verb === 'search') {
		var target = argv._[1];
		if (target === 'help')
			return usage('search', false);
		// search clients
		if (target === 'client' || !target) {
			var spattern = "";
			var stype = "";
			if (argv.c || argv.name) {
				spattern = (argv.c) ? argv.c : argv.name;
				stype = "name";
			}
			else if (argv.s) {
				spattern = argv.s;
				stype = "short";
			}
			else {
				//console.log("Please specify a client name with -c|--client or a short key with -s|--short!");
				return usage('search', true);
			}

			getClient(spattern, stype, function (err, clients) {
				if (err) {
					console.log(err);
					process.exit(-1);
				}
				if (typeof clients == 'undefined' || ! clients) {
					console.log('No clients with that name or short-code found!\n');
					return 0;
				}

				console.log(printf("%-5s | %-15s | %-20s | %-6s | %-20s | %-10s", "ID", "Name", "Street 1", "Zip", "City", "Shortkey"));
				clients.forEach(function(client) {
					console.log(printf("%-5s | %-15s | %-20s | %-6s | %-20s | %-10s", client.id, client.name, stripNull(client.street1), stripNull(client.zip), stripNull(client.city), stripNull(client.short)));
				});
			});
		}
    else {
      return usage('search', true);
    }
	}

	// ##### ADD #####
	// add a client to the database
	else if (verb === 'add') {
		var type = argv._[1];
		if (type === 'client') {
			if (typeof argv.name === 'undefined' || argv.name.trim() === "") {
				console.log("Please supply at least a name for the new customer!");
				process.exit(-1);
			}
			m.Client.create({
				$name: argv.name,
				$street1: argv.street1 || "",
				$zip: argv.zip+"" || "",
					$city: argv.city || "",
					$street2: argv.street2 || "",
						$short: argv.short || null
			});
		}
		else {
			usage('add', true);
		}
	}

	// ###### START ####
	// start time measurement
	else if (verb === 'start') {
		var spattern = "";
		var stype = "";

		// get search type for client
		if (argv.c) {
			spattern = argv.c;
			stype = "name";
		}
		else if (argv.s) {
			spattern = argv.s;
			stype = "short";
		}
		else {
			console.log("Please specify a client name with -c|--client or a short key with -s|--short!");
			return;
		}

		getClient(spattern, stype, function(err, clients) {
			if (err) {
				console.log(err);
				process.exist(-1);
			}

			if (typeof clients === 'undefined' || clients === null) {
				console.log("No clients with that search pattern found!");
				process.exit(-1);
			}

			if (clients.length > 1) {
				//TODO: ask which client to use
				console.log("there's more than one client in the result set!");
				process.exit(-1);
			}
			else {
				timeTrack(clients, argv.t, argv.d, argv.start);
			}
		});
	}

	// ##### STATUS ####
	// print status of time measurement
	else if (verb === 'status') {
		m.Time.status(function (err, data) {
			if (err)
				console.log("There was an error while querying for actual status: " + err);

      // output status information if there's an open time track
			if (data) {
				// found a record, telling the user about the status
				console.log(printf("Time tracking started!\n\t%-15s %s\n\t%-15s %s\n\t%-15s %s\n\t%-15s %s\n\t%-15s %s",
                          "Client:",
                          data.row.clientname,
                          "Title:",
                          data.row.title,
                          "Description:",
                          data.row.description,
                          "Since:",
                          moment(data.row.start).format('llll'),
                          "Duration:",
                          data.diff.format('H [h] m [min] s [sec]')));
      }
      else {
        console.log("No time tracking running!");
      }
		});
	}

  // ##### STOP ####
  // stop time tracking
  else if (verb === 'stop') {
    var end = (argv.end) ? new Date(argv.end) : new Date();

    m.Time.stop(end, function(err) {
      if (err)
        console.log("There was an error ending the timetracking:\n" + err);
    });
  }

  // #### LIST ####
  // list tracked times
  else if (verb === 'list') {
    var filts = null;
    if (argv.f) {
      var filts = JSON.parse(argv.f);
    }

    m.Time.list(filts, function(err, rows) {
      if (err)
        throw err;

      //TODO: print this as a nice table
      console.log(JSON.stringify(rows, null, 2));
    });
  }

  // #### STAGE ###
  // stages tracked times or invoice positions
  else if (verb === 'stage') {
    //TODO
  }

  // #### HELP ####
  // output help for parameter
  else if (verb === 'help') {
    usage(argv._[1], false);
  }

	// ##### TEST ####
	// for testing stuff
	else if (verb === 'test') {
		var inv = require('./invoice.js')("./tpl/invoice.ejs");
    var cli = { "name": "Kunde", "street1": "Kundenstraße 15", "street2": "Apartment 1a", "zip": 55411, "city": "Bingen" };
    var pos = [{ "title": "Programmierung", "quantity": 5, "value": 20, "description": "code tests" }, { "title": "Programmierung", "quantity": 5, "value": 20, "description": "code tests" }];
    inv.create(cli, pos, 10, new Date());
	}

  else if (verb === 'init') {
    m.initDb();
  }

	else {
		usage(null, true);
	}
}

/**
 * starts timetracking for a specific client.
 * mandatory parameters:
 * - client
 * - title
 */
function timeTrack(client, title, description, date, action) {
	action = typeof action === 'undefined' ? "start" : action;
	if (typeof client === 'undefined' || client === null)
		throw "Please specify a client to track the time for!";
	if (typeof title === 'undefined' || title === null)
		throw "You need to specify a title!";
	description = typeof description !== 'undefined' ? description : null;

	// parse date here
	date = typeof date !== 'undefined' ? new Date(date) : new Date();
	if (!(date instanceof Date || date.toString() === "Invalid Date"))
		throw "This is not a valid Date";

	//debuglog('\nClient object:\n', JSON.stringify(client, null, 2));
	if (action === 'start') {
		m.Time.start(client, title, description, date, function (err) {
			if (err)
				throw err;
			else
				console.log("insert successful!");
		});
	}
	else if (action === 'stop') {
		//TODO implement
	}
}

/**
 * gets clients based on search-pattern (spattern) and search-type (stype)
 * and passes the results to callback
 */
function getClient(spattern, stype, callback) {
	// search for client name
	if (stype==='name') {
		debuglog("searching client by name: " + spattern);
		m.Client.findByName({ $name: spattern	}, callback)
	}
	// search for short code
	else if (stype==='short') {
		debuglog("searching client by shortkey:" + spattern);
		m.Client.findByKey({ $short: spattern }, callback);
	}
	else {
		console.log("Not a valid search option: " + stype);
		process.exit(-1);
	}
}

/**
 * saves the configuration
 */
function saveConfig() {
	fs.writeFileSync(confpath, JSON.stringify(conf), { encoding: 'utf8' }, function (err) {
		if (err) throw err;
		console.log('Config saved!');
	});
}

/**
 * prints usage information for tim
 */
function usage(arg, invalid) {
	// parse arguments
	invalid = typeof invalid === 'undefined' ? false : invalid;
	if (invalid) console.log("Invalid command!");

	// define usage strings
	var usage = new Array();

	// help for search keyword
	usage['search'] = new Array();
	usage['search'][0] = "\ttim search [client] (-c|--client pattern)|(-s|--short key)";

	// help for add keyword
	usage['add'] = new Array();
	usage['add'][0] = "\ttim add client -c|--client ClientName [--street1 value] [--street2 value] [--zip zip] [--city city] [--short shortkey]";

  // start keyword
  usage['start'] = new Array();
  usage['start'][0] = "\ttim start ((-c|--client ClientName)|(-s|--short ShortKey)) -t|--title Title [--description] [--start StartTime]";

  usage['status'] = new Array();
  usage['status'][0] = "\ttim status";

  usage['stop'] = new Array();
  usage['stop'][0] = "\ttim stop [--end EndTime]";

	// output usage / help
	console.log("Usage - incomplete but please go ahead and read what's already there:\n");
	if (arg && usage[arg] != undefined) {
		console.log("Usage for tim " + arg + ":");
		usage[arg].forEach(function (val) {
			console.log(val);
		});
	}
	else {
		for (var usg in usage) {
			usage[usg].forEach(function (val) {
				console.log(val);
			});
		}
	}

	process.exit(invalid ? -1 : 0);
}

function debuglog(str) {
	if (debug)
		console.log("[DEBUG] " + str);
}

function stripNull(str) {
	if (typeof str === 'undefined' || str === null)
		return "";
	else
		return str;
}

proc(argv);
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2016 The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

/* global define, EXIF */
"use strict";

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  var filePath = getParameterByName("cp");

  var imageRotationClass = "";
  var isCordova = parent.isCordova;
  var isWeb = document.URL.indexOf('http') === 0;

  if (isCordova || isWeb) {

  } else {
    filePath = "file://" + filePath;
  }

  var $imgViewer = $("#imgViewer");

  $("#imageContent")
    .attr("src", filePath)
    .bind("load", function() {
      $(this).addClass("transparentImageBackground");
      $imgViewer.addClass("imgViewer");
      if (filePath.toLowerCase().indexOf("jpg") === (filePath.length - 3) ||
        filePath.toLowerCase().indexOf("jpeg") === (filePath.length - 4)) {
        EXIF.getData(this, function() {
          var orientation = EXIF.getTag(this, "Orientation");
          correctOrientation(orientation);
          //console.log(EXIF.pretty(this));
        });
      }
    });

  $imgViewer
    .panzoom({
      $zoomIn: $("#zoomInButton"),
      $zoomOut: $("#zoomOutButton"),
      $reset: $("#zoomResetButton"),
      minScale: 0.1,
      maxScale: 10,
      increment: 0.2,
      easing: "ease-in-out",
      contain: 'invert'
    })
    .parent().on('mousewheel.focal', function(e) {
      e.preventDefault();
      var delta = e.delta || e.originalEvent.wheelDelta;
      var zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;
      $imgViewer.panzoom('zoom', zoomOut, {
        increment: 0.1,
        focal: e,
        animate: false
      });
    });

  function correctOrientation(orientation) {
    var $image = $("#imageContent");
    $image.removeClass(imageRotationClass);
    console.log("ORIENTATION: " + orientation);
    switch (orientation) {
      case 8:
        imageRotationClass = "rotate270";
        break;
      case 3:
        imageRotationClass = "rotate180";
        break;
      case 6:
        imageRotationClass = "rotate90";
        break;
      case 1:
        imageRotationClass = "";
        break;
      default:
        imageRotationClass = "";
    }
    $image.addClass(imageRotationClass);
  }

  $("#rotateLeftButton").on("click", function() {
    //console.log("Rotate Left");
    var $image = $("#imageContent");
    $image.removeClass(imageRotationClass);
    switch (imageRotationClass) {
      case "":
        imageRotationClass = "rotate270";
        break;
      case "rotate270":
        imageRotationClass = "rotate180";
        break;
      case "rotate180":
        imageRotationClass = "rotate90";
        break;
      case "rotate90":
        imageRotationClass = "";
        break;
      default:
        imageRotationClass = "";
    }
    $image.addClass(imageRotationClass);
  });

  $("#rotateRightButton").on("click", function() {
    //console.log("Rotate Right");
    var $image = $("#imageContent");
    $image.removeClass(imageRotationClass);
    switch (imageRotationClass) {
      case "":
        imageRotationClass = "rotate90";
        break;
      case "rotate90":
        imageRotationClass = "rotate180";
        break;
      case "rotate180":
        imageRotationClass = "rotate270";
        break;
      case "rotate270":
        imageRotationClass = "";
        break;
      default:
        imageRotationClass = "";
    }
    $image.addClass(imageRotationClass);
  });

  $("#printButton").on("click", function() {
    $(".dropdown-menu").dropdown('toggle');
    window.print();
  });

  if (isCordova) {
    $("#zoomInButton").hide();
    $("#zoomOutButton").hide();
    $("#printButton").hide();
  }

  // Init internationalization
  $.i18n.init({
    ns: {namespaces: ['ns.viewerImage']},
    debug: true,
    fallbackLng: 'en_US'
  }, function() {
    $('[data-i18n]').i18n();
  });

});
<commit_msg>adding initial support for additional EXIF data<commit_after>/* Copyright (c) 2013-2016 The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

/* global define, EXIF */
"use strict";

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  var filePath = getParameterByName("cp");

  var imageRotationClass = "";
  var isCordova = parent.isCordova;
  var isWeb = document.URL.indexOf('http') === 0;

  if (isCordova || isWeb) {

  } else {
    filePath = "file://" + filePath;
  }

  var $imgViewer = $("#imgViewer");

  $("#imageContent")
    .attr("src", filePath)
    .bind("load", function() {
      $(this).addClass("transparentImageBackground");
      $imgViewer.addClass("imgViewer");
      if (filePath.toLowerCase().indexOf("jpg") === (filePath.length - 3) ||
        filePath.toLowerCase().indexOf("jpeg") === (filePath.length - 4)) {
        EXIF.getData(this, function() {
          var orientation = EXIF.getTag(this, "Orientation");
          correctOrientation(orientation);
          //console.log(EXIF.pretty(this));
          var obj = {};
          var tags = ['Make', 'Model', 'DateTime', 'Artist', 'Copyright', 'ExposureTime ', 'FNumber', 'ISOSpeedRatings', 'ShutterSpeedValue', 'ApertureValue', 'FocalLength'];
          for (var tag in tags) {
            var prop = tags[tag];
            if (this.exifdata.hasOwnProperty(prop)) {
              obj[prop] = this.exifdata[prop];
            }
          }
          jQuery.extend(obj, this.iptcdata);
          console.log("EXIF Object" + JSON.stringify(obj));
        });
      }
    });

  $imgViewer
    .panzoom({
      $zoomIn: $("#zoomInButton"),
      $zoomOut: $("#zoomOutButton"),
      $reset: $("#zoomResetButton"),
      minScale: 0.1,
      maxScale: 10,
      increment: 0.2,
      easing: "ease-in-out",
      contain: 'invert'
    })
    .parent().on('mousewheel.focal', function(e) {
      e.preventDefault();
      var delta = e.delta || e.originalEvent.wheelDelta;
      var zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;
      $imgViewer.panzoom('zoom', zoomOut, {
        increment: 0.1,
        focal: e,
        animate: false
      });
    });

  function correctOrientation(orientation) {
    var $image = $("#imageContent");
    $image.removeClass(imageRotationClass);
    console.log("ORIENTATION: " + orientation);
    switch (orientation) {
      case 8:
        imageRotationClass = "rotate270";
        break;
      case 3:
        imageRotationClass = "rotate180";
        break;
      case 6:
        imageRotationClass = "rotate90";
        break;
      case 1:
        imageRotationClass = "";
        break;
      default:
        imageRotationClass = "";
    }
    $image.addClass(imageRotationClass);
  }

  $("#rotateLeftButton").on("click", function() {
    //console.log("Rotate Left");
    var $image = $("#imageContent");
    $image.removeClass(imageRotationClass);
    switch (imageRotationClass) {
      case "":
        imageRotationClass = "rotate270";
        break;
      case "rotate270":
        imageRotationClass = "rotate180";
        break;
      case "rotate180":
        imageRotationClass = "rotate90";
        break;
      case "rotate90":
        imageRotationClass = "";
        break;
      default:
        imageRotationClass = "";
    }
    $image.addClass(imageRotationClass);
  });

  $("#rotateRightButton").on("click", function() {
    //console.log("Rotate Right");
    var $image = $("#imageContent");
    $image.removeClass(imageRotationClass);
    switch (imageRotationClass) {
      case "":
        imageRotationClass = "rotate90";
        break;
      case "rotate90":
        imageRotationClass = "rotate180";
        break;
      case "rotate180":
        imageRotationClass = "rotate270";
        break;
      case "rotate270":
        imageRotationClass = "";
        break;
      default:
        imageRotationClass = "";
    }
    $image.addClass(imageRotationClass);
  });

  $("#printButton").on("click", function() {
    $(".dropdown-menu").dropdown('toggle');
    window.print();
  });

  if (isCordova) {
    $("#zoomInButton").hide();
    $("#zoomOutButton").hide();
    $("#printButton").hide();
  }

  // Init internationalization
  $.i18n.init({
    ns: {namespaces: ['ns.viewerImage']},
    debug: true,
    fallbackLng: 'en_US'
  }, function() {
    $('[data-i18n]').i18n();
  });

});
<|endoftext|>


<commit_before>const path = require('path');

const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  entry: './app.js',
  output: {
    path: path.join(__dirname, '../../public/js/'),
    filename: 'bundle.min.js'
  },
  devtool: 'source-map',
  module: {
    loaders: [
      // {
      //   test: /\.js$/,
      //   exclude: /(node_modules)/,
      //   loader: 'babel-loader',
      //   query: {
      //     presets: ['es2015']
      //   }
      // }
    ]
  },
  // plugins: [
  //   new webpack.optimize.UglifyJsPlugin({
  //     compress: isProduction,
  //     compress: {
  //       warnings: false
  //     }
  //   })
  // ]
}
<commit_msg>webpack config babel browser compat<commit_after>const path = require('path');
const webpack = require('webpack');

const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  entry: './app.js',
  output: {
    path: path.join(__dirname, '../../public/js/'),
    filename: 'bundle.min.js'
  },
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        }
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: isProduction,
      compress: {
        warnings: false
      }
    })
  ]
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

process.title = 'MEGAJS'

// The require('yargs').argv getter have side effects
// so the ESHint error needs to be ignored.

require('yargs') // eslint-disable-line no-unused-expressions
  .commandDir('../lib/commands')
  .recommendCommands()
  .demandCommand(1, 'You need at least one command before moving on')
  .help()
  .epilogue('for more information check ' + pkg.homepage)
  .argv
<commit_msg>Fix bug<commit_after>#!/usr/bin/env node

process.title = 'MEGAJS'

// The require('yargs').argv getter have side effects
// so the ESHint error needs to be ignored.

require('yargs') // eslint-disable-line no-unused-expressions
  .commandDir('../lib/commands')
  .recommendCommands()
  .demandCommand(1, 'You need at least one command before moving on')
  .help()
  .argv
<|endoftext|>


<commit_before>'use strict';

var name = 'Johnny';
if(localStorage.userName) {
  name = JSON.parse(localStorage.userName);
}

var duckMessages = inspMessages; // Located in messages.js

var times = {};

if (localStorage.times) { // old user
  times = JSON.parse(localStorage.times);
} else { // new user
  times = {
    'userName': name,
    'goal': {},
    'unsolved': {}
  };
}

var minutes = 15;
var seconds = 0;
var timer;

document.getElementById('timer').textContent = minutes + ':' + ('0' + seconds).slice(-2);
document.getElementById('done_button').disabled = true;
document.getElementById('done_button').style.opacity = 0.5;
document.getElementById('duck_message').textContent = 'Hello ' + name + '!';

// Get this info from localStorage in the future
var messageInterval = 1;
var intervalHolder = messageInterval;
var theDuck = new Duck(duckMessages);

//when user enters info and presses start, goal changes
function showGoal() {
  console.log('showing goal');
  var userGoal = document.getElementById('userGoalInput').value;
  var divEl = document.getElementById('theGoalOutPut');
  var pEl = document.createElement('p');
  pEl.id = 'userGoal';
  pEl.textContent = userGoal;
  divEl.appendChild(pEl);

  var elem = document.getElementById('goalForm');
  elem.parentNode.removeChild(elem);

}

// Duck Constructor
function Duck(messages) {
  this.messages = messages;
  this.previous = -5; // Previous message index
  this.displayMessage = function() {
    // Display a message to user
    var rando = randomNumber(0, this.messages.length);
    while(this.previous === rando) {
      rando = randomNumber(0, this.messages.length);
      console.log('pew');
    }
    document.getElementById('duck_message').textContent = this.messages[rando];
    this.previous = rando;
  };
}

// Generates a random number used to index the messages for the duck
function randomNumber(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

// Stop the clock
function handleStop() {
  document.getElementById('done_button').disabled = true;
  document.getElementById('done_button').style.opacity = 0.5;
  document.getElementById('start_button').disabled = false;
  document.getElementById('start_button').style.opacity = 1;
  timer = clearInterval(timer);
  var jqPrompt = {
    state0: {
      title: 'Name',
      html:'Solution: <input type="text" name="solution" value="">
',
      buttons: { Solved: 1 },
      focus: 'input[name="solution"]',
      submit:function(e,v,m,f){
        console.log(f);
        e.preventDefault();
        $.prompt.close();

        // store in array
        times.goal[document.getElementById('userGoal').textContent] = f.solution;
        localStorage.times = JSON.stringify(times);
        window.location.href = 'summary.html';
      }
    }
  };
  $.prompt(jqPrompt);
}

// Reset timer to 15 minutes, stop the clock
function handleReset() {
  minutes = 15;
  seconds = 0;
  messageInterval = intervalHolder;
  timer = clearInterval(timer);
  document.getElementById('timer').textContent = minutes + ':' + ('0' + seconds).slice(-2);
  document.getElementById('done_button').disabled = true;
  document.getElementById('done_button').style.opacity = 0.5;
  document.getElementById('start_button').disabled = false;
  document.getElementById('start_button').style.opacity = 1;
}

// Start event handler
function handleStart() {
  document.getElementById('start_button').disabled = true;
  document.getElementById('start_button').style.opacity = 0.5;
  document.getElementById('done_button').disabled = false;
  document.getElementById('done_button').style.opacity = 1;
  showGoal();
  timer = setInterval(function() {
    seconds--;
    // 1 minute has has passed
    if (seconds === -1) {
      minutes--;
      seconds = 59;
      if (messageInterval === 0) {
        // Send message to duck
        theDuck.displayMessage();
        messageInterval = intervalHolder + 1;
      }
      messageInterval--;
    }
    // Time expired
    if (minutes < 0) {
      clearInterval(timer);
      document.getElementById('timer').innerHTML = 'EXPIRED';
      var jqPrompt = {
        state0: {
          title: 'Name',
          html:'Comment: <input type="text" name="comment" value="">
',
          buttons: { Comment: 1 },
          focus: 'input[name="comment"]',
          submit:function(e,v,m,f){
            console.log(f);
            e.preventDefault();
            $.prompt.close();

            // store in array
            times.unsolved[document.getElementById('userGoal').textContent] = f.comment;
            localStorage.times = JSON.stringify(times);
            window.location.href = 'summary.html';
          }
        }
      };
      $.prompt(jqPrompt);

      // Send info to summary page
    } else {
      document.getElementById('timer').textContent = minutes + ':' + ('0' + seconds).slice(-2);
    }
  }, 1000);
}

document.getElementById('start_button').addEventListener('click', handleStart);
document.getElementById('done_button').addEventListener('click', handleStop);
document.getElementById('reset_button').addEventListener('click', handleReset);
document.getElementById('test').addEventListener('click', function() {minutes = -1;});

//----------->
//--------------Cheat Sheet Globals-------------->
var section = document.getElementById('cheat_sheet');

//------------Cheat sheet Object----------------->
var cheatSheet = {
  referenceError: function (){
    clear();
    var h1 = document.createElement('h1');
    h1.textContent = 'ReferenceError';
    section.appendChild(h1);
    var h2 = document.createElement('h2');
    h2.textContent = 'VARIABLE DOES NOT EXIST';
    section.appendChild(h2);
    var p = document.createElement('p');
    p.textContent = 'This is caused by a variable that is not declared or is out of scope.';
    section.appendChild(p);
    var secH2 = document.createElement('h2');
    secH2.textContent = 'VARIABLE IS UNDECLARED';
    section.appendChild(secH2);
    var h3 = document.createElement('h3');
    h3.textContent = 'var width = 12;';
    section.appendChild(h3);
    var secH3 = document.createElement('h3');
    secH3.textContent = 'var area = width * height;';
    section.appendChild(secH3);
    var h4 = document.createElement('h2');
    h4.textContent = 'RefrenceError: Can\'t find variable: height';
    section.appendChild(h4);
    var namedTitle = document.createElement('h2');
    namedTitle.textContent = 'NAMED FUNCTION IS UNDEFINED';
    section.appendChild(namedTitle);
    var namedCode = document.createElement('h3');
    namedCode.textContent = 'document.write(randomFunction());';
    section.appendChild(namedCode);
    var namedError = document.createElement('h2');
    namedError.textContent = 'RefrenceError: Can\'t find varfiable: randomFunction';
    section.appendChild(namedError);
    console.log('RefrenceError cheat printed...');
  },
  //+++++++++++++++++++++ syntaxError +++++++++++++++++++>
  syntaxError: function (){
    clear();
    var mainTitle = document.createElement('h1');
    mainTitle.textContent = 'SyntaxError';
    section.appendChild(mainTitle);
    var mainSub = document.createElement('h2');
    mainSub.textContent = 'SYNTAX IS NOT CORRECT';
    section.appendChild(mainSub);
    var description = document.createElement('p');
    description.textContent = 'This is caused by incorrect use of the rules of the language. It is often the result of a simple typo.';
    section.appendChild(description);
//--->
    var mismatch = document.createElement('h2');
    mismatch.textContent = 'MISMATCH OR UNCLOSED QUOTES';
    var mismatchExp = document.createElement('h3');
    mismatchExp.textContent = 'document.write(\"Howdy\')';
    section.appendChild(mismatchExp);
    var mismatchError = document.createElement('h2');
    mismatchError.textContent = 'SyntaxErro: Unexpected EOF';
    section.appendChild(mismatchError);
//--->
    var missBracket = document.createElement('h2');
    missBracket.textContent = 'MISSING CLOSING BRACKET';
    section.appendChild(missBracket);
    var missBrackCode = document.createElement('h3');
    missBrackCode.textContent = 'documnet.getElementById(\'page\'';
    section.appendChild(missBrackCode);
    var missError = document.createElement('h2');
    missError.textContent = 'SyntaxError: Expected token \')\'';
    section.appendChild(missError);
//--->
    var missinComma = document.createElement('h2');
    missinComma.textContent = 'MISSING COMMA IN ARRAY';
    section.appendChild(missinComma);
    var missinCommaTip = document.createElement('p');
    missinCommaTip.textContent = 'Would be same for missing ] at the end';
    section.appendChild(missinCommaTip);
    var missinCommaCode = document.createElement('h3');
    missinCommaCode.textContent = 'var list = [\'Item 1\', \'Itme 2\' \'Item 3\'];';
    section.appendChild(missinCommaCode);
    var missinCommaError = document.createElement('h2');
    missinCommaError.textContent = 'SyntaxError: Expected token \']\'';
    section.appendChild(missinCommaError);
//--->
    var malfTitle = document.createElement('h2');
    malfTitle.textContent = 'MALFORMED PROPERTY NAME';
    section.appendChild(malfTitle);
    var malfTip = document.createElement('p');
    malfTip.textContent = 'It has a pace but is not surrounded by quote marks';
    section.appendChild(malfTip);
    var malfCode = document.createElement('h3');
    malfCode.textContent = 'user = {first name: \"Ben\", lastName: \"Lee\"};';
    section.appendChild(malfCode);
    var malfError = document.createElement('h2');
    malfError.textContent = 'SyntaxError: Expected an identifier but found \'name\' instead';
    section.appendChild(malfError); console.log('SyntaxError is printing!');
  },
  //+++++++++++ URIError +++++++++++++++++++>
  uriError : function() {
    clear();
    var uriErrorTitle = document.createElement('h1');
    uriErrorTitle.textContent = 'URIError';
    section.appendChild(uriErrorTitle);
    var uriDescription = document.createElement('p');
    uriDescription.textContent = 'If these characters are not escaped in URIs, they will cause an error: / ? & # : ;';
    section.appendChild(uriDescription);
//--->
    var characterEscape = document.createElement('h2');
    characterEscape.textContent = 'CHARACTERS ARE NOT ESCAPED';
    section.appendChild(characterEscape);
    var characterCode = document.createElement('h3');
    characterCode.textContent = 'decodeURI(\'http://bbc.com/news.php?a=1\')  \"?\"';
    section.appendChild(characterCode);
    var characterError = document.createElement('h2');
    characterError.textContent = 'URIError: URI error';
    section.appendChild(characterError);
    console.log('URIError is printing!');
  },
  //------------ TypeError ------------------->
  typeError: function() {
    clear();
    var typeErrorTitle = document.createElement('h1');
    typeErrorTitle.textContent = 'TypeError';
    section.appendChild(typeErrorTitle);
    var typeSub = document.createElement('h2');
    typeSub.textContent = 'VALUE IS UNEXPECTED DATA TYPE';
    section.appendChild(typeSub);
    var typeDescription = document.createElement('p');
    typeDescription.textContent = 'This is often caused by trying to use an object or method that does not exist.';
    section.appendChild(typeDescription);
//--->
    var incorCase = document.createElement('h2');
    incorCase.textContent = 'INCORRECT CASE FOR document OBJECT';
    section.appendChild(incorCase);
    var incorCaseCode = document.createElement('h3');
    incorCaseCode.textContent = 'Document.write(\'Oops!\');' + ' \"D\"<-';
    section.appendChild(incorCaseCode);
    var incorCaseError = document.createElement('h2');
    incorCaseError.textContent = 'TypeError: \'undifined\' is fnot a function (evaluating \'Document.write(\'Oops!\')\')';
    section.appendChild(incorCaseError);
//--->
    var incorCaseWrite = document.createElement('h2');
    incorCaseWrite.textContent = 'INCORRECT CASE FOR write() METHOD';section.appendChild(incorCaseWrite);
    var incorCaseCodeWrite = document.createElement('h3');
    incorCaseCodeWrite.textContent = 'document.Write(\'Oops!\');' + ' \"W\"<-';
    section.appendChild(incorCaseCodeWrite);
    var incorCaseErrorWrite = document.createElement('h2');
    incorCaseErrorWrite.textContent = 'TypeError: \'undifined\' is fnot a function (evaluating \'document.Write(\'Oops!\')\')';
    section.appendChild(incorCaseErrorWrite);
//--->
    var method = document.createElement('h2');
    method.textContent = 'METHOD DOES NOT EXIST';
    section.appendChild(method);
    var methodCode1 = document.createElement('h3');
    methodCode1.textContent = 'var box = {}; ' + ' // Creat empty object';
    section.appendChild(methodCode1);
    var methodCode2 = document.createElement('h3');
    methodCode2.textContent = 'box.getArea ' + ' // Try to access getArea()';
    section.appendChild(methodCode2);
    var methodError = document.createElement('h2');
    methodError.textContent = 'TypeError: \'undefind\' is not a function (evaluating \'box.getArea()\')';
    section.appendChild(methodError);
//--->
    var dom = document.createElement('h2');
    dom.textContent = 'DOM NODE DOES NOT EXIST';
    section.appendChild(dom);
    var domCode1 = document.createElement('h3');
    domCode1.textContent = 'var el = document.getElementById(\'z\'); ' + ' \"z\" <-';
    section.appendChild(domCode1);
    var domCode2 = document.createElement('h3');
    domCode2.textContent = 'el.innerHTML = \'Mango\'';
    section.appendChild(domCode2);
    var domError = document.createElement('h2');
    domError.textContent = 'TypeError: \'null\' is not an object (evaluating \'el.innerHTML = \'Mango\')';
    section.appendChild(domError);
  }

};
//------------Clear Section----------------->
function clear(){
  document.getElementById('cheat_sheet').innerHTML = '';
}
//-------------Event Listener---------------->
submit.addEventListener('click',cheatSheet.uriError);
<commit_msg>Range Error done<commit_after>'use strict';

var name = 'Johnny';
if(localStorage.userName) {
  name = JSON.parse(localStorage.userName);
}

var duckMessages = inspMessages; // Located in messages.js

var times = {};

if (localStorage.times) { // old user
  times = JSON.parse(localStorage.times);
} else { // new user
  times = {
    'userName': name,
    'goal': {},
    'unsolved': {}
  };
}

var minutes = 15;
var seconds = 0;
var timer;

document.getElementById('timer').textContent = minutes + ':' + ('0' + seconds).slice(-2);
document.getElementById('done_button').disabled = true;
document.getElementById('done_button').style.opacity = 0.5;
document.getElementById('duck_message').textContent = 'Hello ' + name + '!';

// Get this info from localStorage in the future
var messageInterval = 1;
var intervalHolder = messageInterval;
var theDuck = new Duck(duckMessages);

//when user enters info and presses start, goal changes
function showGoal() {
  console.log('showing goal');
  var userGoal = document.getElementById('userGoalInput').value;
  var divEl = document.getElementById('theGoalOutPut');
  var pEl = document.createElement('p');
  pEl.id = 'userGoal';
  pEl.textContent = userGoal;
  divEl.appendChild(pEl);

  var elem = document.getElementById('goalForm');
  elem.parentNode.removeChild(elem);

}

// Duck Constructor
function Duck(messages) {
  this.messages = messages;
  this.previous = -5; // Previous message index
  this.displayMessage = function() {
    // Display a message to user
    var rando = randomNumber(0, this.messages.length);
    while(this.previous === rando) {
      rando = randomNumber(0, this.messages.length);
      console.log('pew');
    }
    document.getElementById('duck_message').textContent = this.messages[rando];
    this.previous = rando;
  };
}

// Generates a random number used to index the messages for the duck
function randomNumber(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

// Stop the clock
function handleStop() {
  document.getElementById('done_button').disabled = true;
  document.getElementById('done_button').style.opacity = 0.5;
  document.getElementById('start_button').disabled = false;
  document.getElementById('start_button').style.opacity = 1;
  timer = clearInterval(timer);
  var jqPrompt = {
    state0: {
      title: 'Name',
      html:'Solution: <input type="text" name="solution" value="">
',
      buttons: { Solved: 1 },
      focus: 'input[name="solution"]',
      submit:function(e,v,m,f){
        console.log(f);
        e.preventDefault();
        $.prompt.close();

        // store in array
        times.goal[document.getElementById('userGoal').textContent] = f.solution;
        localStorage.times = JSON.stringify(times);
        window.location.href = 'summary.html';
      }
    }
  };
  $.prompt(jqPrompt);
}

// Reset timer to 15 minutes, stop the clock
function handleReset() {
  minutes = 15;
  seconds = 0;
  messageInterval = intervalHolder;
  timer = clearInterval(timer);
  document.getElementById('timer').textContent = minutes + ':' + ('0' + seconds).slice(-2);
  document.getElementById('done_button').disabled = true;
  document.getElementById('done_button').style.opacity = 0.5;
  document.getElementById('start_button').disabled = false;
  document.getElementById('start_button').style.opacity = 1;
}

// Start event handler
function handleStart() {
  document.getElementById('start_button').disabled = true;
  document.getElementById('start_button').style.opacity = 0.5;
  document.getElementById('done_button').disabled = false;
  document.getElementById('done_button').style.opacity = 1;
  showGoal();
  timer = setInterval(function() {
    seconds--;
    // 1 minute has has passed
    if (seconds === -1) {
      minutes--;
      seconds = 59;
      if (messageInterval === 0) {
        // Send message to duck
        theDuck.displayMessage();
        messageInterval = intervalHolder + 1;
      }
      messageInterval--;
    }
    // Time expired
    if (minutes < 0) {
      clearInterval(timer);
      document.getElementById('timer').innerHTML = 'EXPIRED';
      var jqPrompt = {
        state0: {
          title: 'Name',
          html:'Comment: <input type="text" name="comment" value="">
',
          buttons: { Comment: 1 },
          focus: 'input[name="comment"]',
          submit:function(e,v,m,f){
            console.log(f);
            e.preventDefault();
            $.prompt.close();

            // store in array
            times.unsolved[document.getElementById('userGoal').textContent] = f.comment;
            localStorage.times = JSON.stringify(times);
            window.location.href = 'summary.html';
          }
        }
      };
      $.prompt(jqPrompt);

      // Send info to summary page
    } else {
      document.getElementById('timer').textContent = minutes + ':' + ('0' + seconds).slice(-2);
    }
  }, 1000);
}

document.getElementById('start_button').addEventListener('click', handleStart);
document.getElementById('done_button').addEventListener('click', handleStop);
document.getElementById('reset_button').addEventListener('click', handleReset);
document.getElementById('test').addEventListener('click', function() {minutes = -1;});

//----------->
//--------------Cheat Sheet Globals-------------->
var section = document.getElementById('cheat_sheet');

//------------Cheat sheet Object----------------->
var cheatSheet = {
  referenceError: function (){
    clear();
    var h1 = document.createElement('h1');
    h1.textContent = 'ReferenceError';
    section.appendChild(h1);
    var h2 = document.createElement('h2');
    h2.textContent = 'VARIABLE DOES NOT EXIST';
    section.appendChild(h2);
    var p = document.createElement('p');
    p.textContent = 'This is caused by a variable that is not declared or is out of scope.';
    section.appendChild(p);
    var secH2 = document.createElement('h2');
    secH2.textContent = 'VARIABLE IS UNDECLARED';
    section.appendChild(secH2);
    var h3 = document.createElement('h3');
    h3.textContent = 'var width = 12;';
    section.appendChild(h3);
    var secH3 = document.createElement('h3');
    secH3.textContent = 'var area = width * height;';
    section.appendChild(secH3);
    var h4 = document.createElement('h2');
    h4.textContent = 'RefrenceError: Can\'t find variable: height';
    section.appendChild(h4);
    var namedTitle = document.createElement('h2');
    namedTitle.textContent = 'NAMED FUNCTION IS UNDEFINED';
    section.appendChild(namedTitle);
    var namedCode = document.createElement('h3');
    namedCode.textContent = 'document.write(randomFunction());';
    section.appendChild(namedCode);
    var namedError = document.createElement('h2');
    namedError.textContent = 'RefrenceError: Can\'t find varfiable: randomFunction';
    section.appendChild(namedError);
    console.log('RefrenceError cheat printed...');
  },
  //+++++++++++++++++++++ syntaxError +++++++++++++++++++>
  syntaxError: function (){
    clear();
    var mainTitle = document.createElement('h1');
    mainTitle.textContent = 'SyntaxError';
    section.appendChild(mainTitle);
    var mainSub = document.createElement('h2');
    mainSub.textContent = 'SYNTAX IS NOT CORRECT';
    section.appendChild(mainSub);
    var description = document.createElement('p');
    description.textContent = 'This is caused by incorrect use of the rules of the language. It is often the result of a simple typo.';
    section.appendChild(description);
//--->
    var mismatch = document.createElement('h2');
    mismatch.textContent = 'MISMATCH OR UNCLOSED QUOTES';
    var mismatchExp = document.createElement('h3');
    mismatchExp.textContent = 'document.write(\"Howdy\')';
    section.appendChild(mismatchExp);
    var mismatchError = document.createElement('h2');
    mismatchError.textContent = 'SyntaxErro: Unexpected EOF';
    section.appendChild(mismatchError);
//--->
    var missBracket = document.createElement('h2');
    missBracket.textContent = 'MISSING CLOSING BRACKET';
    section.appendChild(missBracket);
    var missBrackCode = document.createElement('h3');
    missBrackCode.textContent = 'documnet.getElementById(\'page\'';
    section.appendChild(missBrackCode);
    var missError = document.createElement('h2');
    missError.textContent = 'SyntaxError: Expected token \')\'';
    section.appendChild(missError);
//--->
    var missinComma = document.createElement('h2');
    missinComma.textContent = 'MISSING COMMA IN ARRAY';
    section.appendChild(missinComma);
    var missinCommaTip = document.createElement('p');
    missinCommaTip.textContent = 'Would be same for missing ] at the end';
    section.appendChild(missinCommaTip);
    var missinCommaCode = document.createElement('h3');
    missinCommaCode.textContent = 'var list = [\'Item 1\', \'Itme 2\' \'Item 3\'];';
    section.appendChild(missinCommaCode);
    var missinCommaError = document.createElement('h2');
    missinCommaError.textContent = 'SyntaxError: Expected token \']\'';
    section.appendChild(missinCommaError);
//--->
    var malfTitle = document.createElement('h2');
    malfTitle.textContent = 'MALFORMED PROPERTY NAME';
    section.appendChild(malfTitle);
    var malfTip = document.createElement('p');
    malfTip.textContent = 'It has a pace but is not surrounded by quote marks';
    section.appendChild(malfTip);
    var malfCode = document.createElement('h3');
    malfCode.textContent = 'user = {first name: \"Ben\", lastName: \"Lee\"};';
    section.appendChild(malfCode);
    var malfError = document.createElement('h2');
    malfError.textContent = 'SyntaxError: Expected an identifier but found \'name\' instead';
    section.appendChild(malfError); console.log('SyntaxError is printing!');
  },
  //+++++++++++ URIError +++++++++++++++++++>
  uriError : function() {
    clear();
    var uriErrorTitle = document.createElement('h1');
    uriErrorTitle.textContent = 'URIError';
    section.appendChild(uriErrorTitle);
    var uriDescription = document.createElement('p');
    uriDescription.textContent = 'If these characters are not escaped in URIs, they will cause an error: / ? & # : ;';
    section.appendChild(uriDescription);
//--->
    var characterEscape = document.createElement('h2');
    characterEscape.textContent = 'CHARACTERS ARE NOT ESCAPED';
    section.appendChild(characterEscape);
    var characterCode = document.createElement('h3');
    characterCode.textContent = 'decodeURI(\'http://bbc.com/news.php?a=1\')  \"?\"';
    section.appendChild(characterCode);
    var characterError = document.createElement('h2');
    characterError.textContent = 'URIError: URI error';
    section.appendChild(characterError);
    console.log('URIError is printing!');
  },
  //------------ TypeError ------------------->
  typeError: function() {
    clear();
    var typeErrorTitle = document.createElement('h1');
    typeErrorTitle.textContent = 'TypeError';
    section.appendChild(typeErrorTitle);
    var typeSub = document.createElement('h2');
    typeSub.textContent = 'VALUE IS UNEXPECTED DATA TYPE';
    section.appendChild(typeSub);
    var typeDescription = document.createElement('p');
    typeDescription.textContent = 'This is often caused by trying to use an object or method that does not exist.';
    section.appendChild(typeDescription);
//--->
    var incorCase = document.createElement('h2');
    incorCase.textContent = 'INCORRECT CASE FOR document OBJECT';
    section.appendChild(incorCase);
    var incorCaseCode = document.createElement('h3');
    incorCaseCode.textContent = 'Document.write(\'Oops!\');' + ' \"D\"<-';
    section.appendChild(incorCaseCode);
    var incorCaseError = document.createElement('h2');
    incorCaseError.textContent = 'TypeError: \'undifined\' is fnot a function (evaluating \'Document.write(\'Oops!\')\')';
    section.appendChild(incorCaseError);
//--->
    var incorCaseWrite = document.createElement('h2');
    incorCaseWrite.textContent = 'INCORRECT CASE FOR write() METHOD';section.appendChild(incorCaseWrite);
    var incorCaseCodeWrite = document.createElement('h3');
    incorCaseCodeWrite.textContent = 'document.Write(\'Oops!\');' + ' \"W\"<-';
    section.appendChild(incorCaseCodeWrite);
    var incorCaseErrorWrite = document.createElement('h2');
    incorCaseErrorWrite.textContent = 'TypeError: \'undifined\' is fnot a function (evaluating \'document.Write(\'Oops!\')\')';
    section.appendChild(incorCaseErrorWrite);
//--->
    var method = document.createElement('h2');
    method.textContent = 'METHOD DOES NOT EXIST';
    section.appendChild(method);
    var methodCode1 = document.createElement('h3');
    methodCode1.textContent = 'var box = {}; ' + ' // Creat empty object';
    section.appendChild(methodCode1);
    var methodCode2 = document.createElement('h3');
    methodCode2.textContent = 'box.getArea ' + ' // Try to access getArea()';
    section.appendChild(methodCode2);
    var methodError = document.createElement('h2');
    methodError.textContent = 'TypeError: \'undefind\' is not a function (evaluating \'box.getArea()\')';
    section.appendChild(methodError);
//--->
    var dom = document.createElement('h2');
    dom.textContent = 'DOM NODE DOES NOT EXIST';
    section.appendChild(dom);
    var domCode1 = document.createElement('h3');
    domCode1.textContent = 'var el = document.getElementById(\'z\'); ' + ' \"z\" <-';
    section.appendChild(domCode1);
    var domCode2 = document.createElement('h3');
    domCode2.textContent = 'el.innerHTML = \'Mango\'';
    section.appendChild(domCode2);
    var domError = document.createElement('h2');
    domError.textContent = 'TypeError: \'null\' is not an object (evaluating \'el.innerHTML = \'Mango\')';
    section.appendChild(domError);
  },
  //----------- Range Error ----------------->
  rangeError: function(){
    clear();
    var rangeErrorTitle = document.createElement('h1');
    rangeErrorTitle.textContent = 'RangeError';
    section.appendChild(rangeErrorTitle);
    var rangeSub = document.createElement('h2');
    rangeSub.textContent = 'NUMBER OUTSIDE OF RANGE';
    section.appendChild(rangeSub);
    var rangeDescription = document.createElement('p');
    rangeDescription.textContent = 'If you can call a function using numbers outside of its accepted range';
    section.appendChild(rangeDescription);
//--->
    var cannotCreateArray = document.createElement('h2');
    cannotCreateArray.textContent = 'CANNOT CREATE ARRAY WITH -1 ITEMS';
    section.appendChild(cannotCreateArray);
    var cannotCode = document.createElement('h3');
    cannotCode.textContent = 'var anArray = new Array(-1);';
    section.appendChild(cannotCode);
    var cannotError = document.createElement('h2');
    cannotError.textContent = 'RangeError: Array size is not a small enough positive integer';
    section.appendChild(cannotError);
//--->
    var number = document.createElement('h2');
    number.textContent = 'NUMBER OF DIGITS AFTER DECIMAL IN tofixed() CAN ONLY BE 0-20';
    section.appendChild(number);
    var numberCode1 = document.createElement('h3');
    numberCode1.textContent = 'var price = 9.99;';
    section.appendChild(numberCode1);
    var numberCode2 = document.createElement('h3');
    numberCode2.textContent = 'price.toFixed(21); ' + ' \"21\"<-';
    section.appendChild(numberCode2);
    var numberError = document.createElement('h2');
    numberError.textContent = 'RangeError: toFixed() argument must be between 0 and 20';
    section.appendChild(numberError);
//--->
    var numberOf = document.createElement('h2');
    numberOf.textContent = 'NUMBER OF DIGITS IN toPrecion() CAN';
    section.appendChild(numberOf);
    var numberOfCode1 = document.createElement('h3');
    numberOfCode1.textContent = 'num = 2.3456';
    section.appendChild(numberOfCode1);
    var numberOfCode2 = document.createElement('h3');
    numberOfCode2.textContent = 'num.toPrecision(22); ' + ' \"22\"<-';
    section.appendChild(numberOfCode2);
    var numberOfError = document.createElement('h2');
    numberOfError.textContent = 'RangeError: toPrecision() argument must be between 0 and 21';
    section.appendChild(numberOfError);
  }

};
//------------Clear Section----------------->
function clear(){
  document.getElementById('cheat_sheet').innerHTML = '';
}
//-------------Event Listener---------------->
submit.addEventListener('click',cheatSheet.uriError);
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const Liftoff = require('liftoff');
const argv = require('minimist')(process.argv.slice(2));
const chalk = require('chalk');

const gueCli = new Liftoff({
  name: 'gue',
  processTitle: 'gue',
  moduleName: 'gue',
  configName: 'guefile',
});

gueCli.launch({
  cwd: argv.cwd,
  configPath: argv.myappfile,
  require: argv.require,
  completion: argv.completion
}, invoke);

function invoke(env) {
  require(env.configPath);
  const gueInst = require(env.modulePath);
  const actions = argv._;
  const actionList = actions.length ? actions : ['default'];
  const availableTasks = gueInst.taskList();

  if (!env.configPath) {
    gueInst.log(chalk.red('No gulpfile found'));
    process.exit(1);
  }

  // add node_modules/.bin to the path.
  // this should be relative to the project root
  // if liftoff is working correctly.  :)
  process.env.PATH = env.configBase + '/node_modules/.bin:' +
    process.env.PATH;

  if (argv.l) {
    gueInst.log(availableTasks.join('\n'));
    process.exit(0);
  }

  //
  // Setup orcestrator event listeners
  //

  // Log task start
  gueInst.on('task_start', (event) => {
    gueInst.log('started', event.task, 'normal');
  });

  // Log task stop and task duration
  gueInst.on('task_stop', (event) => {
    gueInst.log('finished in', event.task, 'normal', event.duration);
  });

  // Print stderr and the task finish notification on error
  gueInst.on('task_err', (event)=> {
    gueInst.log(event.err.stderr, event.task, 'error');
    gueInst.log('finished in', event.task, 'normal', event.duration);
  });

  // If there was an error in any of the tasks set the exit code
  gueInst.on('err', (event) => {
    gueInst.exitCode = 1;
  });

  // setup process event listener so we can
  // exit with the right code
  process.once('exit', (code) => {
    if (gueInst.exitCode === 1) {
      process.exit(1);
    }
  });

  // Now lets make do stuff
  gueInst.start(actionList);
}
//
<commit_msg>Change dir to the project root before running<commit_after>#!/usr/bin/env node

'use strict';

const Liftoff = require('liftoff');
const argv = require('minimist')(process.argv.slice(2));
const chalk = require('chalk');

const gueCli = new Liftoff({
  name: 'gue',
  processTitle: 'gue',
  moduleName: 'gue',
  configName: 'guefile',
});

gueCli.launch({
  cwd: argv.cwd,
  configPath: argv.myappfile,
  require: argv.require,
  completion: argv.completion
}, invoke);

function invoke(env) {
  require(env.configPath);
  const gueInst = require(env.modulePath);
  const actions = argv._;
  const actionList = actions.length ? actions : ['default'];
  const availableTasks = gueInst.taskList();

  if (!env.configPath) {
    gueInst.log(chalk.red('No gulpfile found'));
    process.exit(1);
  }

  // add node_modules/.bin to the path.
  // this should be relative to the project root
  // if liftoff is working correctly.  :)
  process.env.PATH = env.configBase + '/node_modules/.bin:' +
    process.env.PATH;

  // Change directory to configBase to make sure everything
  // is relative to the project root
  // Fixes issue #4
  process.chdir(env.configBase);

  if (argv.l) {
    gueInst.log(availableTasks.join('\n'));
    process.exit(0);
  }

  //
  // Setup orcestrator event listeners
  //

  // Log task start
  gueInst.on('task_start', (event) => {
    gueInst.log('started', event.task, 'normal');
  });

  // Log task stop and task duration
  gueInst.on('task_stop', (event) => {
    gueInst.log('finished in', event.task, 'normal', event.duration);
  });

  // Print stderr and the task finish notification on error
  gueInst.on('task_err', (event)=> {
    gueInst.log(event.err.stderr, event.task, 'error');
    gueInst.log('finished in', event.task, 'normal', event.duration);
  });

  // If there was an error in any of the tasks set the exit code
  gueInst.on('err', (event) => {
    gueInst.exitCode = 1;
  });

  // setup process event listener so we can
  // exit with the right code
  process.once('exit', (code) => {
    if (gueInst.exitCode === 1) {
      process.exit(1);
    }
  });

  // Now lets make do stuff
  gueInst.start(actionList);
}
//
<|endoftext|>


<commit_before>// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var common = require('./common.js');
var nodes = require('./nodes.js');
var pexprs = require('./pexprs.js');

// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------

pexprs.PExpr.prototype.check = common.abstract;

pexprs.anything.check = function(vals) {
  return 1;
};

pexprs.end.check = function(vals) {
  return (vals[0] instanceof nodes.ValueNode && vals[0].value === undefined) && 1;
};

pexprs.Prim.prototype.check = function(vals) {
  return (vals[0] instanceof nodes.ValueNode && vals[0].value === this.obj) && 1;
};

pexprs.RegExpPrim.prototype.check = function(vals) {
  // TODO: more efficient "total match checker" than the use of .replace here
  return (vals[0] instanceof nodes.ValueNode
	  && typeof vals[0].value === 'string'
	  && vals[0].value.replace(this.obj, '') === '') && 1;
};

pexprs.Alt.prototype.check = function(vals) {
  for (var i = 0; i < this.terms.length; i++) {
    var result = this.terms[i].check(vals[0]);
    if (result !== false) {
      return result;
    }
  }
  return false;
};

pexprs.Seq.prototype.check = function(vals) {
  var pos = 0;
  for (var i = 0; i < this.factors.length; i++) {
    var result = this.factors[i].check(vals.slice(pos));
    if (result === false) {
      return result;
    }
    pos += result;
  }
  return pos;
};

pexprs.Many.prototype.check = function(vals) {
  var i;
  var arity = this.getArity();
  if (arity === 0) {
    // TODO: make this a static check w/ a nice error message, then remove the dynamic check.
    // cf. pexprs-eval.js for Many
    throw 'fix me!';
  }

  var columns = vals.slice(0, arity);
  if (columns.length !== arity) {
    return false;
  }
  var rowcount = columns[0].length;
  for (i = 1; i < arity; i++) {
    if (columns[i].length !== rowcount) {
      return false;
    }
  }

  for (i = 0; i < rowcount; i++) {
    var row = []
    for (var j = 0; j < arity; j++) {
      row.push(columns[j][i]);
    }
    var result = this.expr.check(row);
    if (result !== arity) {
      return result;
    }
  }

  return arity;
};

pexprs.Opt.prototype.check = function(vals) {
  var i;
  var arity = this.getArity();
  var allUndefined = true;
  for (i = 0; i < arity; i++) {
    if (vals[i] !== undefined) {
      allUndefined = false;
      break;
    }
  }

  if (allUndefined) {
    return arity;
  } else {
    return this.expr.check(vals);
  }
};

pexprs.Not.prototype.check = function(vals) {
  return 0;
};

pexprs.Lookahead.prototype.check = function(vals) {
  return this.expr.check(vals);
};

pexprs.Listy.prototype.check = function(vals) {
  return this.expr.check(vals);
};

pexprs.Obj.prototype.check = function(vals) {
  var i;
  var fixedArity = this.getArity();
  if (this.isLenient) {
    fixedArity--;
  }

  var pos = 0;
  for (var i = 0; i < fixedArity; i++) {
    var result = this.properties[i].pattern.check(vals.slice(pos));
    if (result === false) {
      return result;
    }
    pos += result;
  }

  if (this.isLenient) {
    if (!(typeof vals[pos] === 'object' && vals !== null) ) {
      return false;
    }
    pos++;
  }

  return pos;
};

pexprs.Apply.prototype.check = function(vals) {
  if (!(vals[0] instanceof nodes.RuleNode
	&& vals[0].grammar === this.grammar
	&& vals[0].ctorName === this.ruleName)) {
    return false;
  }

  var result = this.grammar.ruleDict[this.ruleName].check(vals[0].args);
  if (result !== vals[0].args.length) {
    return false;
  }

  return 1;
};

<commit_msg>Initial sketches of changes from code review<commit_after>// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var common = require('./common.js');
var nodes = require('./nodes.js');
var pexprs = require('./pexprs.js');

// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------

// TODO: make check :: [val] -> boolean, since the number will be getArity() always otherwise

pexprs.PExpr.prototype.check = common.abstract;

pexprs.anything.check = function(vals) {
  return vals.length >= 1 && 1;
};

pexprs.end.check = function(vals) {
  return (vals[0] instanceof nodes.ValueNode && vals[0].value === undefined) && 1;
};

pexprs.Prim.prototype.check = function(vals) {
  return (vals[0] instanceof nodes.ValueNode && vals[0].value === this.obj) && 1;
};

pexprs.RegExpPrim.prototype.check = function(vals) {
  // TODO: more efficient "total match checker" than the use of .replace here
  return (vals[0] instanceof nodes.ValueNode
	  && typeof vals[0].value === 'string'
	  && vals[0].value.replace(this.obj, '') === '') && 1;
};

pexprs.Alt.prototype.check = function(vals) {
  for (var i = 0; i < this.terms.length; i++) {
    var result = this.terms[i].check(vals);
    if (result !== false) {
      return result;
    }
  }
  return false;
};

pexprs.Seq.prototype.check = function(vals) {
  var pos = 0;
  for (var i = 0; i < this.factors.length; i++) {
    var result = this.factors[i].check(vals.slice(pos));
    if (result === false) {
      return result;
    }
    pos += result;
  }
  return pos;
};

pexprs.Many.prototype.check = function(vals) {
  var arity = this.getArity();
  if (arity === 0) {
    // TODO: make this a static check w/ a nice error message, then remove the dynamic check.
    // cf. pexprs-eval.js for Many
    throw 'fix me!';
  }

  var columns = vals.slice(0, arity);
  if (columns.length !== arity) {
    return false;
  }
  var rowcount = columns[0].length;
  var i;
  for (i = 1; i < arity; i++) {
    if (columns[i].length !== rowcount) {
      return false;
    }
  }

  for (i = 0; i < rowcount; i++) {
    var row = []
    for (var j = 0; j < arity; j++) {
      row.push(columns[j][i]);
    }
    var result = this.expr.check(row);
    if (result !== arity) {
      return false;
    }
  }

  return arity;
};

pexprs.Opt.prototype.check = function(vals) {
  var arity = this.getArity();
  var allUndefined = true;
  for (var i = 0; i < arity; i++) {
    if (vals[i] !== undefined) {
      allUndefined = false;
      break;
    }
  }

  if (allUndefined) {
    return arity;
  } else {
    return this.expr.check(vals);
  }
};

pexprs.Not.prototype.check = function(vals) {
  return 0;
};

pexprs.Lookahead.prototype.check = function(vals) {
  return this.expr.check(vals);
};

pexprs.Listy.prototype.check = function(vals) {
  return this.expr.check(vals);
};

pexprs.Obj.prototype.check = function(vals) {
  var i;
  var fixedArity = this.getArity();
  if (this.isLenient) {
    fixedArity--;
  }

  var pos = 0;
  for (var i = 0; i < fixedArity; i++) {
    var result = this.properties[i].pattern.check(vals.slice(pos));
    if (result === false) {
      return result;
    }
    pos += result;
  }

  if (this.isLenient) {
    if (!(typeof vals[pos] === 'object' && vals[pos])) {
      return false;
    }
    pos++;
  }

  return pos;
};

pexprs.Apply.prototype.check = function(vals) {
  if (!(vals[0] instanceof nodes.RuleNode
	&& vals[0].grammar === this.grammar
	&& vals[0].ctorName === this.ruleName)) {
    return false;
  }

  // TODO: think about *not* doing the following checks, i.e., trusting that the rule
  // was correctly constructed.
  var result = this.grammar.ruleDict[this.ruleName].check(vals[0].args);
  if (result !== vals[0].args.length) {
    return false;
  }

  return 1;
};

<|endoftext|>


<commit_before>export default class Counter {

  constructor(opts) {
    this.start = 0;
    this.end = 10;

    this.duration = 2000;

    this.selector = opts.selector;
  }

  tick(currentTime) {
    if(!this.timeStart) this.timeStart = currentTime;
    this.timeElapsed = currentTime - this.timeStart;

    this.next = this.ease(this.timeElapsed, this.start, this.end - this.start, this.duration);
    this.next = Math.round(this.next);

    this.selector.textContent = this.next;

    if (this.next < this.end)
      requestAnimationFrame((time)=> this.tick(time))
  }

  run() {
    requestAnimationFrame(this.tick.bind(this));
  }

  // t: current time, b: begInnIng value, c: change In value, d: duration
  ease(t, b, c, d) {
    return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
  }
}
<commit_msg>finish refactor. added callback option<commit_after>export default class Counter {

  constructor(opts) {
    this.start = opts.start;
    this.end = opts.end;
    this.selector = opts.selector;
    this.done = opts.done;
    this.duration = opts.duration || 2000;
  }

  run() {
    requestAnimationFrame(this._tick.bind(this));
  }

  _tick(currentTime) {
    if(!this.timeStart) this.timeStart = currentTime;

    this.timeElapsed = currentTime - this.timeStart;
    this.next = this._ease(this.timeElapsed, this.start, this.end - this.start, this.duration);
    this.selector.textContent = Math.round(this.next);

    if (this.next < this.end)
      return requestAnimationFrame(this._tick.bind(this));

    return this.done();
  }

  _ease(t, b, c, d) {
    return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
  }
}
<|endoftext|>


<commit_before>var games = [
    "SuperSeaSerpentSimulator",
    "RationsPlease"
];

var GenerateFromJason = function(data)
{
	console.log(data);
};

var GenerateContent = function(game)
{
	console.log("Generating content for " + game);
	$.getJSON("data/" + game + ".json", null, GenerateFromJason);
	//console.log("Loading " + game);
    //$("#modals").append($("<div>").load("modals/" + game + ".html"));
};

$(document).ready(function(){
	for (var i = games.length - 1; i >= 0; i--) {
		var game = games[i];
		GenerateContent(game);
	}
});<commit_msg>json test 4<commit_after>var games = [
    "SuperSeaSerpentSimulator",
    "RationsPlease"
];

var portfolioItemTemplate = "templates/portfolioItemTemplate.html";
var modalTemplate = "templates/modalTemplate.html";

var GeneratePortfolioItem = function(data)
{
	var portfolioItem = $("<div>").load(portfolioItemTemplate);
	console.log(portfolioItem);

	$("#portfolio-items").append(portfolioItem);
};

var GenerateModal = function(data)
{
	var modal = $.load(modalTemplate);
	console.log(modal);

	$("#modals").append(modal);
};

var GenerateFromJson = function(data)
{
	console.log(data);
	GeneratePortfolioItem(data);
	GenerateModal(data);
};

var GenerateContent = function(game)
{
	console.log("Generating content for " + game);
	$.getJSON("data/" + game + ".json", null, GenerateFromJson);
};

$(document).ready(function(){
	for (var i = games.length - 1; i >= 0; i--) {
		var game = games[i];
		GenerateContent(game);
	}
});<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Copyright 2016 Netsend.
 *
 * This file is part of PersDB.
 *
 * PersDB is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * PersDB is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with PersDB. If not, see <https://www.gnu.org/licenses/>.
 */

'use strict';

var fs = require('fs');

var async = require('async');
var hjson = require('hjson');
var level = require('level-packager')(require('leveldown'));
var program = require('commander');

var doDiff = require('../lib/diff');
var MergeTree = require('../lib/merge_tree');
var noop = require('../lib/noop');

program
  .version('0.0.2')
  .usage('[-f config] [-n]')
  .description('print graph of the given database')
  .option('-f, --config <config>', 'hjson config file with database path')
  .option('-s, --show', 'show complete objects')
  .option('-p, --patch', 'show patch compared to previous version')
  .option('    --pe <perspective>', 'print only this perspective')
  .option('-a  --all', 'print all perspectives')
  .option('-n, --number <number>', 'number of latest versions to show, defaults to 10, 0 means unlimited')
  .parse(process.argv);

var config = {};
var configFile = program.config;

if (configFile) {
  config = hjson.parse(fs.readFileSync(configFile, 'utf8'));
}

if (program.number === '0') {
  program.number = Infinity;
} else {
  program.number = Number(program.number) || 10;
}

// format merge tree stats
function fmtStats(stats) {
  var result = '';
  Object.keys(stats).forEach(function(pe) {
    result += pe + ' heads:\t' + stats[pe].heads.count + '\n';

    if (stats[pe].heads.conflict) {
      result += '  conflict:\t' + stats[pe].heads.conflict + '\n';
    }

    if (stats[pe].heads.deleted) {
      result += '  deleted:\t' + stats[pe].heads.deleted + '\n';
    }
  });

  return result;
}

// shows new values of added and changed attributes
function fmtPatch(patch, newItem) {
  var result = {};
  Object.keys(patch).forEach(function(key) {
    if (patch[key] !== '-') {
      result[key] = newItem[key];
    }
  });
  return JSON.stringify(result);
}

function fmtItem(item, parents) {
  parents = parents || [];

  var out = '';
  if (program.show) {
    // print tree
    if (parents.length) {
      out += '\u250f ';
    } else {
      out += '\u257a ';
    }
    out += ' ' + JSON.stringify(item);
    if (parents.length) {
      out += '\n';
    }

    var i = 0;
    parents.forEach(function(p) {
      i++;
      if (i === parents.length) {
        out += '\u2517\u2501 ';
      } else {
        out += '\u2523\u2501 ';
      }
      var diff = doDiff(item.b || {}, p.b || {});
      out += ' ' + p.h.id + ' ' + p.h.v + ' diff: ' + JSON.stringify(diff) + ' ' + fmtPatch(diff, item.b);
      if (i !== parents.length) {
        out += '\n';
      }
    });
  } else {
    out += item.h.id;
    out += ' ' + item.h.v;
    if (item.h.hasOwnProperty('d') && item.h.d) {
      out += ' d';
    } else {
      out += ' .';
    }
    if (item.h.hasOwnProperty('c') && item.h.c) {
      out += ' c';
    } else {
      out += ' .';
    }
    out += ' ' + (item.h.pe || 'local');
    if (item.h.hasOwnProperty('i')) {
      out += ' (' + item.h.i + ')';
    }
    out += ' ' + JSON.stringify(item.h.pa);
    if (program.patch && parents.length) {
      parents.forEach(function(p) {
        var diff = doDiff(item.b || {}, p.b || {});
        if (parents.length > 1) {
          out += ' ' + p.h.v;
        }
        out += ' diff: ' + JSON.stringify(diff) + ' ' + fmtPatch(diff, item.b);
      });
    }
  }
  return out;
}

function printTree(mt, tree, cb) {
  var counter = 0;
  console.log('%s:', tree.name);
  tree.iterateInsertionOrder({ reverse: true }, function(item, cb2) {
    counter++;

    if (!program.patch || !item.h.pa.length) {
      console.log(fmtItem(item));

      cb2(null, counter < program.number);
      return;
    }

    var parents = [];
    async.eachSeries(item.h.pa, function(pa, cb3) {
      mt.getByVersion(pa, function(err, p) {
        if (err) { cb3(err); return; }
        if (!p) {
          var error = new Error('parent not found');
          cb3(error);
          return;
        }

        parents.push(p);
        cb3();
      });
    }, function(err) {
      if (err) { cb2(err); return; }

      console.log(fmtItem(item, parents));

      cb2(null, counter < program.number);
    });
  }, cb);
}

function run(db, cfg, cb) {
  cfg = cfg || {};
  cfg.log = {
    err: noop,
    notice: noop,
    info: noop,
    debug: noop,
    debug2: noop
  };
  var mt = new MergeTree(db, cfg);

  mt.stats(function(err, stats) {
    if (err) { cb(err); return; }
    console.log(fmtStats(stats));

    var remoteTrees = mt.getRemoteTrees();

    if (program.all) {
      async.eachSeries(Object.keys(remoteTrees), function(name, cb2) {
        printTree(mt, remoteTrees[name], cb2);
      }, function(err) {
        if (err) { cb(err); return; }
        printTree(mt, mt.getStageTree(), function(err) {
          if (err) { cb(err); return; }
          printTree(mt, mt.getLocalTree(), function(err) {
            if (err) { cb(err); return; }
            cb();
          });
        });
      });
    } else {
      // print one tree, default to the local tree
      var tree, pe = program.pe || 'local';

      if (remoteTrees[pe]) {
        tree = remoteTrees[pe];
      } else if (pe === 'stage') {
        tree = mt.getStageTree();
      } else if (pe === 'local' || pe === mt._local.name) {
        tree = mt.getLocalTree();
      } else {
        cb(new Error('unknown perspective'));
        return;
      }

      printTree(mt, tree, cb);
    }
  });
}

if (config.dbs && config.dbs.length) {
  async.eachSeries(config.dbs, function(dbCfg, cb) {
    var chroot = dbCfg.chroot || '/var/persdb';
    var data = dbCfg.data || 'data';

    if (dbCfg.perspectives) {
      dbCfg.perspectives = dbCfg.perspectives.map(function(peCfg) {
        return peCfg.name;
      });
    }
    // open database
    level(chroot + '/' + data, { keyEncoding: 'binary', valueEncoding: 'binary' }, function(err, db) {
      if (err) { cb(err); return; }
      run(db, dbCfg, function(err) {
        db.close();
        if (err) { cb(err); return; }
      });
    });
  }, function(err) {
    if (err) { console.error(err); process.exit(2); }
  });
} else {
  // open database
  var newRoot = config.chroot || '/var/persdb';

  var path = config.path || '/data';
  // ensure leading slash
  if (path[0] !== '/') {
    path = '/' + path;
  }

  console.log(newRoot, path);

  level(newRoot + path, { keyEncoding: 'binary', valueEncoding: 'binary' }, function(err, db) {
    if (err) { throw err; }
    run(db, {}, function(err) {
      db.close();
      if (err) { console.error(err); process.exit(2); }
    });
  });
}
<commit_msg>bin/log.js: documentation<commit_after>#!/usr/bin/env node

/**
 * Copyright 2016 Netsend.
 *
 * This file is part of PersDB.
 *
 * PersDB is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * PersDB is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with PersDB. If not, see <https://www.gnu.org/licenses/>.
 */

'use strict';

var fs = require('fs');

var async = require('async');
var hjson = require('hjson');
var level = require('level-packager')(require('leveldown'));
var program = require('commander');

var doDiff = require('../lib/diff');
var MergeTree = require('../lib/merge_tree');
var noop = require('../lib/noop');

program
  .version('0.0.2')
  .usage('[-f config] [-n]')
  .description('print graph of the given database')
  .option('-f, --config <config>', 'hjson config file with database path')
  .option('-s, --show', 'show complete objects')
  .option('-p, --patch', 'show patch compared to previous version')
  .option('    --pe <perspective>', 'print only this perspective')
  .option('-a  --all', 'print all perspectives')
  .option('-n, --number <number>', 'number of heads to show, defaults to 10, 0 means unlimited')
  .parse(process.argv);

var config = {};
var configFile = program.config;

if (configFile) {
  config = hjson.parse(fs.readFileSync(configFile, 'utf8'));
}

if (program.number === '0') {
  program.number = Infinity;
} else {
  program.number = Number(program.number) || 10;
}

// format merge tree stats
function fmtStats(stats) {
  var result = '';
  Object.keys(stats).forEach(function(pe) {
    result += pe + ' heads:\t' + stats[pe].heads.count + '\n';

    if (stats[pe].heads.conflict) {
      result += '  conflict:\t' + stats[pe].heads.conflict + '\n';
    }

    if (stats[pe].heads.deleted) {
      result += '  deleted:\t' + stats[pe].heads.deleted + '\n';
    }
  });

  return result;
}

// shows new values of added and changed attributes
function fmtPatch(patch, newItem) {
  var result = {};
  Object.keys(patch).forEach(function(key) {
    if (patch[key] !== '-') {
      result[key] = newItem[key];
    }
  });
  return JSON.stringify(result);
}

function fmtItem(item, parents) {
  parents = parents || [];

  var out = '';
  if (program.show) {
    // print tree
    if (parents.length) {
      out += '\u250f ';
    } else {
      out += '\u257a ';
    }
    out += ' ' + JSON.stringify(item);
    if (parents.length) {
      out += '\n';
    }

    var i = 0;
    parents.forEach(function(p) {
      i++;
      if (i === parents.length) {
        out += '\u2517\u2501 ';
      } else {
        out += '\u2523\u2501 ';
      }
      var diff = doDiff(item.b || {}, p.b || {});
      out += ' ' + p.h.id + ' ' + p.h.v + ' diff: ' + JSON.stringify(diff) + ' ' + fmtPatch(diff, item.b);
      if (i !== parents.length) {
        out += '\n';
      }
    });
  } else {
    out += item.h.id;
    out += ' ' + item.h.v;
    if (item.h.hasOwnProperty('d') && item.h.d) {
      out += ' d';
    } else {
      out += ' .';
    }
    if (item.h.hasOwnProperty('c') && item.h.c) {
      out += ' c';
    } else {
      out += ' .';
    }
    out += ' ' + (item.h.pe || 'local');
    if (item.h.hasOwnProperty('i')) {
      out += ' (' + item.h.i + ')';
    }
    out += ' ' + JSON.stringify(item.h.pa);
    if (program.patch && parents.length) {
      parents.forEach(function(p) {
        var diff = doDiff(item.b || {}, p.b || {});
        if (parents.length > 1) {
          out += ' ' + p.h.v;
        }
        out += ' diff: ' + JSON.stringify(diff) + ' ' + fmtPatch(diff, item.b);
      });
    }
  }
  return out;
}

function printTree(mt, tree, cb) {
  var counter = 0;
  console.log('%s:', tree.name);
  tree.iterateInsertionOrder({ reverse: true }, function(item, cb2) {
    counter++;

    if (!program.patch || !item.h.pa.length) {
      console.log(fmtItem(item));

      cb2(null, counter < program.number);
      return;
    }

    var parents = [];
    async.eachSeries(item.h.pa, function(pa, cb3) {
      mt.getByVersion(pa, function(err, p) {
        if (err) { cb3(err); return; }
        if (!p) {
          var error = new Error('parent not found');
          cb3(error);
          return;
        }

        parents.push(p);
        cb3();
      });
    }, function(err) {
      if (err) { cb2(err); return; }

      console.log(fmtItem(item, parents));

      cb2(null, counter < program.number);
    });
  }, cb);
}

function run(db, cfg, cb) {
  cfg = cfg || {};
  cfg.log = {
    err: noop,
    notice: noop,
    info: noop,
    debug: noop,
    debug2: noop
  };
  var mt = new MergeTree(db, cfg);

  mt.stats(function(err, stats) {
    if (err) { cb(err); return; }
    console.log(fmtStats(stats));

    var remoteTrees = mt.getRemoteTrees();

    if (program.all) {
      async.eachSeries(Object.keys(remoteTrees), function(name, cb2) {
        printTree(mt, remoteTrees[name], cb2);
      }, function(err) {
        if (err) { cb(err); return; }
        printTree(mt, mt.getStageTree(), function(err) {
          if (err) { cb(err); return; }
          printTree(mt, mt.getLocalTree(), function(err) {
            if (err) { cb(err); return; }
            cb();
          });
        });
      });
    } else {
      // print one tree, default to the local tree
      var tree, pe = program.pe || 'local';

      if (remoteTrees[pe]) {
        tree = remoteTrees[pe];
      } else if (pe === 'stage') {
        tree = mt.getStageTree();
      } else if (pe === 'local' || pe === mt._local.name) {
        tree = mt.getLocalTree();
      } else {
        cb(new Error('unknown perspective'));
        return;
      }

      printTree(mt, tree, cb);
    }
  });
}

if (config.dbs && config.dbs.length) {
  async.eachSeries(config.dbs, function(dbCfg, cb) {
    var chroot = dbCfg.chroot || '/var/persdb';
    var data = dbCfg.data || 'data';

    if (dbCfg.perspectives) {
      dbCfg.perspectives = dbCfg.perspectives.map(function(peCfg) {
        return peCfg.name;
      });
    }
    // open database
    level(chroot + '/' + data, { keyEncoding: 'binary', valueEncoding: 'binary' }, function(err, db) {
      if (err) { cb(err); return; }
      run(db, dbCfg, function(err) {
        db.close();
        if (err) { cb(err); return; }
      });
    });
  }, function(err) {
    if (err) { console.error(err); process.exit(2); }
  });
} else {
  // open database
  var newRoot = config.chroot || '/var/persdb';

  var path = config.path || '/data';
  // ensure leading slash
  if (path[0] !== '/') {
    path = '/' + path;
  }

  console.log(newRoot, path);

  level(newRoot + path, { keyEncoding: 'binary', valueEncoding: 'binary' }, function(err, db) {
    if (err) { throw err; }
    run(db, {}, function(err) {
      db.close();
      if (err) { console.error(err); process.exit(2); }
    });
  });
}
<|endoftext|>