<commit_before>const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { initCommuneFields, initCommuneFormat } = require('./lib/communeHelpers');
const { initDepartementFields } = require('./lib/departementHelpers');
const { initRegionFields } = require('./lib/regionHelpers');
const { formatOne } = require('./lib/helpers');
const dbCommunes = require('./lib/communes').getIndexedDb();
const dbDepartements = require('./lib/departements').getIndexedDb();
const dbRegions = require('./lib/regions').getIndexedDb();
const { pick } = require('lodash');

const app = express();
app.use(cors());
app.use(morgan('dev'));

/* Communes */
app.get('/communes', initCommuneFields, initCommuneFormat, function (req, res) {
  let result;

  const query = pick(req.query, 'code', 'codePostal', 'nom');
  if (req.query.lat && req.query.lon) {
    const lat = parseFloat(req.query.lat);
    const lon = parseFloat(req.query.lon);
    if (Number.isFinite(lat)
      && lat >= -90
      && lat <= 90
      && Number.isFinite(lon)
      && lon >= -180
      && lon <= 180
    ) {
      query.lat = lat;
      query.lon = lon;
    }
  }
  if (query.nom) req.fields.add('_score');

  if (Object.keys(query).length === 0) {
    return res.sendStatus(400);
  }

  result = dbCommunes.search(query);

  if (req.outputFormat === 'geojson') {
    res.send({
      type: 'FeatureCollection',
      features: result.map(commune => formatOne(req, commune)),
    });
  } else {
    res.send(result.map(commune => formatOne(req, commune)));
  }
});

app.get('/communes/:code', initCommuneFields, initCommuneFormat, function (req, res) {
  let commune = dbCommunes.queryByCode(req.params.code)[0];
  if (!commune) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, commune));
  }
});

/* Départements */
app.get('/departements', initDepartementFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbDepartements
      .search(query)
      .map(departement => formatOne(req, departement))
  );
});

app.get('/departements/:code', initDepartementFields, function (req, res) {
  let departement = dbDepartements.queryByCode(req.params.code)[0];
  if (!departement) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, departement));
  }
});

app.get('/departements/:code/communes',  initCommuneFields, initCommuneFormat, function (req, res) {
  let communes = dbCommunes.queryByDep(req.params.code);
  if (!communes.length) {
    res.sendStatus(404);
  } else {
    if (req.outputFormat === 'geojson') {
      res.send({
        type: 'FeatureCollection',
        features: communes.map(commune => formatOne(req, commune)),
      });
    } else {
      res.send(communes.map(commune => formatOne(req, commune)));
    }
  }
});

/* Régions */
app.get('/regions', initRegionFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbRegions
      .search(query)
      .map(departement => formatOne(req, departement))
  );
});

app.get('/regions/:code', initRegionFields, function (req, res) {
  let departement = dbRegions.queryByCode(req.params.code)[0];
  if (!departement) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, departement));
  }
});

/* Definition */
app.get('/definition.yml', function (req, res) {
  res.sendFile(__dirname + '/definition.yml');
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  /* eslint no-console: 0 */
  console.log('Start listening on port %d', port);
});

module.exports = app;
<commit_msg>Fix arrays handling in server<commit_after>const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { initCommuneFields, initCommuneFormat } = require('./lib/communeHelpers');
const { initDepartementFields } = require('./lib/departementHelpers');
const { initRegionFields } = require('./lib/regionHelpers');
const { formatOne } = require('./lib/helpers');
const dbCommunes = require('./lib/communes').getIndexedDb();
const dbDepartements = require('./lib/departements').getIndexedDb();
const dbRegions = require('./lib/regions').getIndexedDb();
const { pick } = require('lodash');

const app = express();
app.use(cors());
app.use(morgan('dev'));

/* Communes */
app.get('/communes', initCommuneFields, initCommuneFormat, function (req, res) {
  let result;

  const query = pick(req.query, 'code', 'codePostal', 'nom');
  if (req.query.lat && req.query.lon) {
    const lat = parseFloat(req.query.lat);
    const lon = parseFloat(req.query.lon);
    if (Number.isFinite(lat)
      && lat >= -90
      && lat <= 90
      && Number.isFinite(lon)
      && lon >= -180
      && lon <= 180
    ) {
      query.lat = lat;
      query.lon = lon;
    }
  }
  if (query.nom) req.fields.add('_score');

  if (Object.keys(query).length === 0) {
    return res.sendStatus(400);
  }

  result = dbCommunes.search(query);

  if (req.outputFormat === 'geojson') {
    res.send({
      type: 'FeatureCollection',
      features: result.map(commune => formatOne(req, commune)),
    });
  } else {
    res.send(result.map(commune => formatOne(req, commune)));
  }
});

app.get('/communes/:code', initCommuneFields, initCommuneFormat, function (req, res) {
  const communes = dbCommunes.queryByCode(req.params.code);
  if (communes.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, communes[0]));
  }
});

/* Départements */
app.get('/departements', initDepartementFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbDepartements
      .search(query)
      .map(departement => formatOne(req, departement))
  );
});

app.get('/departements/:code', initDepartementFields, function (req, res) {
  const departements = dbDepartements.queryByCode(req.params.code);
  if (departements.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, departements[0]));
  }
});

app.get('/departements/:code/communes',  initCommuneFields, initCommuneFormat, function (req, res) {
  const departements = dbDepartements.queryByCode(req.params.code);
  if (departements.length === 0) {
    res.sendStatus(404);
  } else {
    const communes = dbCommunes.queryByDep(req.params.code);
    if (req.outputFormat === 'geojson') {
      res.send({
        type: 'FeatureCollection',
        features: communes.map(commune => formatOne(req, commune)),
      });
    } else {
      res.send(communes.map(commune => formatOne(req, commune)));
    }
  }
});

/* Régions */
app.get('/regions', initRegionFields, function (req, res) {
  const query = pick(req.query, 'code', 'nom', 'codeRegion');

  if (query.nom) req.fields.add('_score');

  res.send(
    dbRegions
      .search(query)
      .map(region => formatOne(req, region))
  );
});

app.get('/regions/:code', initRegionFields, function (req, res) {
  const regions = dbRegions.queryByCode(req.params.code);
  if (regions.length === 0) {
    res.sendStatus(404);
  } else {
    res.send(formatOne(req, regions[0]));
  }
});

/* Definition */
app.get('/definition.yml', function (req, res) {
  res.sendFile(__dirname + '/definition.yml');
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  /* eslint no-console: 0 */
  console.log('Start listening on port %d', port);
});

module.exports = app;
<|endoftext|>


<commit_before>/* SHA512 for JavaScript
 *
 * The MIT License (MIT)
 * Copyright (c) 2016 Leonardone @ NEETSDKASU
 */

function SHA512JS() {

	function Int64() {

		var SIZE = 9;
		var LEN = 8;
		var BITLEN = 16;
		var MASK = 0xFFFF;

		this.valueOf = function(n) {
			// n: Number(Integer)
			var i, v = new Array(SIZE);
			for (i = 0; i < SIZE; i++) {
				v[i] = n & MASK;
				n >>= BITLEN;
			}
			return v;
		};

		this.parse = function(s) {
			// s: Hex String
			var i, v = new Array(SIZE), j;
			i = 0;
			for (j = s.length - 4; j >= 0 && i < LEN; j -= 4) {
				v[i] = parseInt('0x' + s.substring(j, j + 4));
				i++;
			}
			if (j > -4 && i < LEN) {
				v[i] = parseInt('0x' + s.substring(0, j + 4));
				i++;
			}
			for (; i < SIZE; i++) {
				v[i] = 0;
			}
			return v;
		};

		this.add = function(v1, v2) {
			var i, v = new Array(SIZE), t = 0;
			for (i = 0; i < LEN; i++) {
				t += v1[i] + v2[i];
				v[i] = t & MASK;
				t >>= BITLEN;
			}
			v[LEN] = 0;
			return v;
		};

		this.bwXor = function(v1, v2) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] ^ v2[i];
			}
			v[LEN] = 0;
			return v;
		};

		this.bwAnd = function(v1, v2) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] & v2[i];
			}
			v[LEN] = 0;
			return v;
		};

		this.bwOr  = function(v1, v2) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] | v2[i];
			}
			v[LEN] = 0;
			return v;
		};

		this.bwNot = function(v1) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] ^ MASK;
			}
			v[LEN] = 0;
			return v;
		};

		this.shiftR = function(v1, s) {
			var i, v = new Array(SIZE), k, m, p;
			k = (s & 63) >> 4; // div BITLEN(16)
			for (i = 0; i + k < LEN; i++) {
				v[i] = v1[i + k];
			}
			s &= MASK;
			m = (1 << s) - 1; // mask
			p = BITLEN - s;   // shiftL
			for (i = 0; i < LEN; i++) {
				v[i] >>= s;
				v[i] |= (v[i + 1] & m) << p;
			}
			return v;
		};

		this.rotateR = function(v1, r) {
			var i, v = new Array(SIZE), k, m, p;
			k = (r & 63) >> 4; // div BITLEN(16)
			for (i = 0; i < LEN; i++) {
				v[i] = v1[(i + k) & 7]; // % LEN(8)
			}
			r &= MASK;
			m = (1 << r) - 1;  // mask
			p = BITLEN - r;    // shiftL
			v[LEN] = v[0] & m; // lowest bits
			for (i = 0; i < LEN; i++) {
				v[i] >>= r;
				v[i] |= (v[i + 1] & m) << p;
			}
			v[LEN] = 0;
			return v;
		};

		this.toHex = function(v) {
			var i, c, s = '';
			for (i = LEN - 1; i >= 0; i--) {
				c = v[i].toString(16);
				while (c.length < 4) { c = '0' + c; } // 4 hex-characters at BITLEN(16)
				s += c;
			}
			return s;
		};
	}

	this.getInt64 = function() { return new Int64(); };

}
<commit_msg>特に意味はないが、Int64をインスタンスに変えてみた。<commit_after>/* SHA512 for JavaScript
 *
 * The MIT License (MIT)
 * Copyright (c) 2016 Leonardone @ NEETSDKASU
 */

function SHA512JS() {

	var Int64 = new function() {

		var SIZE = 9;
		var LEN = 8;
		var BITLEN = 16;
		var MASK = 0xFFFF;

		this.valueOf = function(n) {
			// n: Number(Integer)
			var i, v = new Array(SIZE);
			for (i = 0; i < SIZE; i++) {
				v[i] = n & MASK;
				n >>= BITLEN;
			}
			return v;
		};

		this.parse = function(s) {
			// s: Hex String
			var i, v = new Array(SIZE), j;
			i = 0;
			for (j = s.length - 4; j >= 0 && i < LEN; j -= 4) {
				v[i] = parseInt('0x' + s.substring(j, j + 4));
				i++;
			}
			if (j > -4 && i < LEN) {
				v[i] = parseInt('0x' + s.substring(0, j + 4));
				i++;
			}
			for (; i < SIZE; i++) {
				v[i] = 0;
			}
			return v;
		};

		this.add = function(v1, v2) {
			var i, v = new Array(SIZE), t = 0;
			for (i = 0; i < LEN; i++) {
				t += v1[i] + v2[i];
				v[i] = t & MASK;
				t >>= BITLEN;
			}
			v[LEN] = 0;
			return v;
		};

		this.bwXor = function(v1, v2) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] ^ v2[i];
			}
			v[LEN] = 0;
			return v;
		};

		this.bwAnd = function(v1, v2) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] & v2[i];
			}
			v[LEN] = 0;
			return v;
		};

		this.bwOr  = function(v1, v2) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] | v2[i];
			}
			v[LEN] = 0;
			return v;
		};

		this.bwNot = function(v1) {
			var i, v = new Array(SIZE);
			for (i = 0; i < LEN; i++) {
				v[i] = v1[i] ^ MASK;
			}
			v[LEN] = 0;
			return v;
		};

		this.shiftR = function(v1, s) {
			var i, v = new Array(SIZE), k, m, p;
			k = (s & 63) >> 4; // div BITLEN(16)
			for (i = 0; i + k < LEN; i++) {
				v[i] = v1[i + k];
			}
			s &= MASK;
			m = (1 << s) - 1; // mask
			p = BITLEN - s;   // shiftL
			for (i = 0; i < LEN; i++) {
				v[i] >>= s;
				v[i] |= (v[i + 1] & m) << p;
			}
			return v;
		};

		this.rotateR = function(v1, r) {
			var i, v = new Array(SIZE), k, m, p;
			k = (r & 63) >> 4; // div BITLEN(16)
			for (i = 0; i < LEN; i++) {
				v[i] = v1[(i + k) & 7]; // % LEN(8)
			}
			r &= MASK;
			m = (1 << r) - 1;  // mask
			p = BITLEN - r;    // shiftL
			v[LEN] = v[0] & m; // lowest bits
			for (i = 0; i < LEN; i++) {
				v[i] >>= r;
				v[i] |= (v[i + 1] & m) << p;
			}
			v[LEN] = 0;
			return v;
		};

		this.toHex = function(v) {
			var i, c, s = '';
			for (i = LEN - 1; i >= 0; i--) {
				c = v[i].toString(16);
				while (c.length < 4) { c = '0' + c; } // 4 hex-characters at BITLEN(16)
				s += c;
			}
			return s;
		};
	};

	this.getInt64 = function() { return Int64; };

}
<|endoftext|>


<commit_before>/**
 * @class  	Sharer
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

var Util = require('T/util');

var globalCallback = null; // Handle all callbacks

function onSocialComplete(e) {
	if (!_.isFunction(globalCallback)) return;

	e.type = 'complete';
	if (e.activityName) e.platform = e.activityName;
	globalCallback(e);
}

function onSocialCancel(e) {
	if (!_.isFunction(globalCallback)) return;

	e.type = 'cancelled';
	if (e.activityName) e.platform = e.activityName;
	globalCallback(e);
}

function parseArgs(args) {
	if (!_.isObject(args)) return {};
	args = _.clone(args);

	if (args.image != null) {
		if (_.isObject(args.image)) {
			if (args.image.resolve) {
				args.imageBlob = args.image;
				args.image = args.imageBlob.resolve();
			} else if (args.image.nativePath) {
				args.imageBlob = args.image;
				args.image = args.imageBlob.nativePath;
			} else {
				delete args.image;
			}
		} else if (_.isString(args.image) && args.image.indexOf('://') !== -1) {
			args.imageUrl = args.image;
		}
	}

	if (args.link != null) {
		args.url = args.link;
		delete args.link;
	}

	if (args.removeIcons === 'ALL') args.removeIcons = 'print,sms,copy,contact,camera,readinglist';

	if (args.text != null && args.url != null) {
		args.fullText = args.text + ' (' + args.url + ')';
	} else if (args.text != null) {
		args.fullText = args.text;
	} else if (args.url != null) {
		args.fullText = args.url;
	}

	if (_.isFunction(args.callback)) {
		globalCallback = args.callback;
		delete args.callback;
	}

	return args;
}

/**
 * @method facebook
 * Share on Facebook
 * @param {Object} args
 */
exports.facebook = function(args) {
	args = parseArgs(args);

	// Native iOS dialog
	if (args.useApp !== true
		&& false === /https?\:\/\/(www\.)?facebook\.com/.test(args.url) // iOS share dialog doesn't share Facebook links
	 	&& dkNappSocial !== null && dkNappSocial.isFacebookSupported()
	) {
		dkNappSocial.facebook({
			text: args.text,
			image: args.image,
			url: args.url
		});
		return true;
	}

	if (FB != null && _.isFunction(FB.share) /*&& _.isFunction(FB.getCanPresentShareDialog()) && FB.getCanPresentShareDialog() === true*/) {
		FB.share({ url: args.url });
		return true;
	}

	// Fallback
	Ti.Platform.openURL('https://www.facebook.com/dialog/share' + Util.buildQuery({
		app_id: Ti.App.Properties.getString('ti.facebook.appid'),
		display: 'touch',
		redirect_uri: Ti.App.url,
		href: args.url
	}));
};

/**
 * @method twitter
 * Share on Twitter
 * @param {Object} args
 */
exports.twitter = function(args) {
	args = parseArgs(args);

	// Native iOS Dialog
	if (args.useApp !== true
		&& dkNappSocial !== null && dkNappSocial.isTwitterSupported()
	) {
		dkNappSocial.twitter({
			text: args.text,
			image: args.image,
			url: args.url
		});
		return true;
	}

	// var tweetbotIOSURL = 'tweetbot://post' + Util.buildQuery({ text: args.fullText });
	// if (OS_IOS && Ti.Platform.canOpenURL(tweetbotIOSURL)) {
	// 	Ti.Platform.openURL(tweetbotIOSURL);
	// 	return true;
	// }

	var nativeIOSURL = 'twitter://post' + Util.buildQuery({ message: args.fullText });
	if (OS_IOS && Ti.Platform.canOpenURL(nativeIOSURL)) {
		Ti.Platform.openURL(nativeIOSURL);
		return true;
	}

	Ti.Platform.openURL('http://www.twitter.com/intent/tweet' + Util.buildQuery({
		 text: args.text,
		 url: args.url
	}));
};

/**
 * @method email
 * Share via Mail
 * @param {Object} args
 */
exports.email = function(args) {
	args = parseArgs(args);

	var $dialog = Ti.UI.createEmailDialog({
		subject: args.subject || args.title,
		messageBody: args.fullText,
	});

	if (args.imageBlob != null) $dialog.addAttachment(args.imageBlob);

	$dialog.addEventListener('complete', function(e) {
		if (e.result !== this.CANCELLED) {
			onSocialComplete({
				success: (e.result === this.SENT),
				platform: 'email'
			});
		} else {
			onSocialCancel({
				success: false,
				platform: 'email'
			});
		}
	});

	$dialog.open();
};

/**
 * @method googleplus
 * Share on Google Plus
 * @param {Object} args
 */
exports.googleplus = function(args) {
	args = parseArgs(args);

	Ti.Platform.openURL('https://plus.google.com/share' + Util.buildQuery({
		url: args.url
	}));
};

/**
 * @method whatsapp
 * Share via Whatsapp
 * @param {Object} args
 */
exports.whatsapp = function(args) {
	args = parseArgs(args);

	// Native protocol binding
	if (OS_IOS) {
		Util.openURL('whatsapp://send?text=' + args.fullText, function() {
			require('T/dialog').confirmYes(L('app_not_installed', 'App not installed'), String.format(L('app_install_question', 'Do you want to install %s?'), 'Whatsapp'), function() {
				Util.openInStore('310633997');
			}, L('install_app', 'Install app'));
		});

		return true;
	}

	// Android Intent using package
	if (OS_ANDROID) {
		try {
			var intent = Ti.Android.createIntent({
				action: Ti.Android.ACTION_SEND,
				type: 'text/plain',
				packageName: 'com.whatsapp'
			});
			intent.putExtra(Ti.Android.EXTRA_TEXT, args.fullText);
			Ti.Android.currentActivity.startActivity(intent, L('Share'));
		} catch (err) {
			require('T/dialog').confirmYes(L('app_not_installed', 'App not installed'), String.format(L('app_install_question', 'Do you want to install %s?'), 'Whatsapp'), function() {
				Util.openInStore('com.whatsapp');
			}, L('install_app', 'Install app'));
		}

		return true;
	}
};

/**
 * @method message
 * Share via Messages
 * @param {Object} args
 */
exports.message = function(args) {
	args = parseArgs(args);

	// iOS Native modal
	if (OS_IOS && benCodingSMS !== null) {
		var $dialog = benCodingSMS.createSMSDialog({ messageBody: args.fullText });
		$dialog.addEventListener('completed', function(){ onSocialComplete({ success: true, platform: 'messages' }); });
		$dialog.addEventListener('cancelled', function(){ onSocialCancel({ success: false, platform: 'messages' }); });
		$dialog.addEventListener('errored', function(){ onSocialComplete({ success: false, platform: 'messages' }); });
		$dialog.open({ animated: true });

		return true;
	}

	// Android Native
	if (OS_ANDROID) {
		var intent = Ti.Android.createIntent({
			action: Ti.Android.ACTION_VIEW,
			type: 'vnd.android-dir/mms-sms',
		});
		intent.putExtra('sms_body', args.fullText);
		Ti.Android.currentActivity.startActivity(intent, L('Share'));

		return true;
	}
};
exports.sms = exports.message;

/**
 * @method activity
 * Share using iOS ActivityPopover or Android Intents
 * @param {Object} args
 */
exports.activity = function(args) {
	args = parseArgs(args);

	// iOS Activity native
	if (OS_IOS && dkNappSocial !== null) {
		dkNappSocial[ Util.isIPad() ? 'activityPopover' : 'activityView' ]({
			text: args.text,
			title: args.title,
			image: args.image,
			removeIcons: args.removeIcons,
			view: args.view,
			url: args.url
		}, args.customIcons || []);

		return true;
	}

	// Android intents
	if (OS_ANDROID) {
		var intent = Ti.Android.createIntent({ action: Ti.Android.ACTION_SEND });
		if (args.fullText) intent.putExtra(Ti.Android.EXTRA_TEXT, args.fullText);
		if (args.title) intent.putExtra(Ti.Android.EXTRA_TITLE, args.title);
		if (args.image) intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);

		Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, L('Share')));

		return true;
	}
};

/*
Init
*/

// Load modules

var FB = Util.requireOrNull('T/facebook');

if (OS_IOS) {

	var dkNappSocial = Util.requireOrNull('dk.napp.social');
	var benCodingSMS = Util.requireOrNull('bencoding.sms');

	if (benCodingSMS != null) {
		dkNappSocial.addEventListener('complete', onSocialComplete);
		dkNappSocial.addEventListener('cancelled', onSocialCancel);
	}

}
<commit_msg>Share fix null<commit_after>/**
 * @class  	Sharer
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

var Util = require('T/util');

var globalCallback = null; // Handle all callbacks

function onSocialComplete(e) {
	if (!_.isFunction(globalCallback)) return;

	e.type = 'complete';
	if (e.activityName) e.platform = e.activityName;
	globalCallback(e);
}

function onSocialCancel(e) {
	if (!_.isFunction(globalCallback)) return;

	e.type = 'cancelled';
	if (e.activityName) e.platform = e.activityName;
	globalCallback(e);
}

function parseArgs(args) {
	if (!_.isObject(args)) return {};
	args = _.clone(args);

	if (args.image != null) {
		if (_.isObject(args.image)) {
			if (args.image.resolve) {
				args.imageBlob = args.image;
				args.image = args.imageBlob.resolve();
			} else if (args.image.nativePath) {
				args.imageBlob = args.image;
				args.image = args.imageBlob.nativePath;
			} else {
				delete args.image;
			}
		} else if (_.isString(args.image) && args.image.indexOf('://') !== -1) {
			args.imageUrl = args.image;
		}
	}

	if (args.link != null) {
		args.url = args.link;
		delete args.link;
	}

	if (args.removeIcons === 'ALL') args.removeIcons = 'print,sms,copy,contact,camera,readinglist';

	if (args.text != null && args.url != null) {
		args.fullText = args.text + ' (' + args.url + ')';
	} else if (args.text != null) {
		args.fullText = args.text;
	} else if (args.url != null) {
		args.fullText = args.url;
	}

	if (_.isFunction(args.callback)) {
		globalCallback = args.callback;
		delete args.callback;
	}

	return args;
}

/**
 * @method facebook
 * Share on Facebook
 * @param {Object} args
 */
exports.facebook = function(args) {
	args = parseArgs(args);

	// Native iOS dialog
	if (args.useApp !== true
		&& false === /https?\:\/\/(www\.)?facebook\.com/.test(args.url) // iOS share dialog doesn't share Facebook links
	 	&& dkNappSocial != null && dkNappSocial.isFacebookSupported()
	) {
		dkNappSocial.facebook({
			text: args.text,
			image: args.image,
			url: args.url
		});
		return true;
	}

	if (FB != null && _.isFunction(FB.share) /*&& _.isFunction(FB.getCanPresentShareDialog()) && FB.getCanPresentShareDialog() === true*/) {
		FB.share({ url: args.url });
		return true;
	}

	// Fallback
	Ti.Platform.openURL('https://www.facebook.com/dialog/share' + Util.buildQuery({
		app_id: Ti.App.Properties.getString('ti.facebook.appid'),
		display: 'touch',
		redirect_uri: Ti.App.url,
		href: args.url
	}));
};

/**
 * @method twitter
 * Share on Twitter
 * @param {Object} args
 */
exports.twitter = function(args) {
	args = parseArgs(args);

	// Native iOS Dialog
	if (args.useApp !== true
		&& dkNappSocial != null && dkNappSocial.isTwitterSupported()
	) {
		dkNappSocial.twitter({
			text: args.text,
			image: args.image,
			url: args.url
		});
		return true;
	}

	// var tweetbotIOSURL = 'tweetbot://post' + Util.buildQuery({ text: args.fullText });
	// if (OS_IOS && Ti.Platform.canOpenURL(tweetbotIOSURL)) {
	// 	Ti.Platform.openURL(tweetbotIOSURL);
	// 	return true;
	// }

	var nativeIOSURL = 'twitter://post' + Util.buildQuery({ message: args.fullText });
	if (OS_IOS && Ti.Platform.canOpenURL(nativeIOSURL)) {
		Ti.Platform.openURL(nativeIOSURL);
		return true;
	}

	Ti.Platform.openURL('http://www.twitter.com/intent/tweet' + Util.buildQuery({
		 text: args.text,
		 url: args.url
	}));
};

/**
 * @method email
 * Share via Mail
 * @param {Object} args
 */
exports.email = function(args) {
	args = parseArgs(args);

	var $dialog = Ti.UI.createEmailDialog({
		subject: args.subject || args.title,
		messageBody: args.fullText,
	});

	if (args.imageBlob != null) $dialog.addAttachment(args.imageBlob);

	$dialog.addEventListener('complete', function(e) {
		if (e.result !== this.CANCELLED) {
			onSocialComplete({
				success: (e.result === this.SENT),
				platform: 'email'
			});
		} else {
			onSocialCancel({
				success: false,
				platform: 'email'
			});
		}
	});

	$dialog.open();
};

/**
 * @method googleplus
 * Share on Google Plus
 * @param {Object} args
 */
exports.googleplus = function(args) {
	args = parseArgs(args);

	Ti.Platform.openURL('https://plus.google.com/share' + Util.buildQuery({
		url: args.url
	}));
};

/**
 * @method whatsapp
 * Share via Whatsapp
 * @param {Object} args
 */
exports.whatsapp = function(args) {
	args = parseArgs(args);

	// Native protocol binding
	if (OS_IOS) {
		Util.openURL('whatsapp://send?text=' + args.fullText, function() {
			require('T/dialog').confirmYes(L('app_not_installed', 'App not installed'), String.format(L('app_install_question', 'Do you want to install %s?'), 'Whatsapp'), function() {
				Util.openInStore('310633997');
			}, L('install_app', 'Install app'));
		});

		return true;
	}

	// Android Intent using package
	if (OS_ANDROID) {
		try {
			var intent = Ti.Android.createIntent({
				action: Ti.Android.ACTION_SEND,
				type: 'text/plain',
				packageName: 'com.whatsapp'
			});
			intent.putExtra(Ti.Android.EXTRA_TEXT, args.fullText);
			Ti.Android.currentActivity.startActivity(intent, L('Share'));
		} catch (err) {
			require('T/dialog').confirmYes(L('app_not_installed', 'App not installed'), String.format(L('app_install_question', 'Do you want to install %s?'), 'Whatsapp'), function() {
				Util.openInStore('com.whatsapp');
			}, L('install_app', 'Install app'));
		}

		return true;
	}
};

/**
 * @method message
 * Share via Messages
 * @param {Object} args
 */
exports.message = function(args) {
	args = parseArgs(args);

	// iOS Native modal
	if (OS_IOS && benCodingSMS !== null) {
		var $dialog = benCodingSMS.createSMSDialog({ messageBody: args.fullText });
		$dialog.addEventListener('completed', function(){ onSocialComplete({ success: true, platform: 'messages' }); });
		$dialog.addEventListener('cancelled', function(){ onSocialCancel({ success: false, platform: 'messages' }); });
		$dialog.addEventListener('errored', function(){ onSocialComplete({ success: false, platform: 'messages' }); });
		$dialog.open({ animated: true });

		return true;
	}

	// Android Native
	if (OS_ANDROID) {
		var intent = Ti.Android.createIntent({
			action: Ti.Android.ACTION_VIEW,
			type: 'vnd.android-dir/mms-sms',
		});
		intent.putExtra('sms_body', args.fullText);
		Ti.Android.currentActivity.startActivity(intent, L('Share'));

		return true;
	}
};
exports.sms = exports.message;

/**
 * @method activity
 * Share using iOS ActivityPopover or Android Intents
 * @param {Object} args
 */
exports.activity = function(args) {
	args = parseArgs(args);

	// iOS Activity native
	if (OS_IOS && dkNappSocial != null) {
		dkNappSocial[ Util.isIPad() ? 'activityPopover' : 'activityView' ]({
			text: args.text,
			title: args.title,
			image: args.image,
			removeIcons: args.removeIcons,
			view: args.view,
			url: args.url
		}, args.customIcons || []);

		return true;
	}

	// Android intents
	if (OS_ANDROID) {
		var intent = Ti.Android.createIntent({ action: Ti.Android.ACTION_SEND });
		if (args.fullText) intent.putExtra(Ti.Android.EXTRA_TEXT, args.fullText);
		if (args.title) intent.putExtra(Ti.Android.EXTRA_TITLE, args.title);
		if (args.image) intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);

		Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, L('Share')));

		return true;
	}
};

/*
Init
*/

// Load modules

var FB = Util.requireOrNull('T/facebook');

if (OS_IOS) {

	var dkNappSocial = Util.requireOrNull('dk.napp.social');
	var benCodingSMS = Util.requireOrNull('bencoding.sms');

	if (benCodingSMS != null) {
		dkNappSocial.addEventListener('complete', onSocialComplete);
		dkNappSocial.addEventListener('cancelled', onSocialCancel);
	}

}
<|endoftext|>


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

'use strict';

var program = require('commander');
var shp = require('./lib/shp');
var errorText = ''

program
  .version('1.0.0')
	.option('-s, --shapefile <s>', 'Shapefile')
	.option('-h, --host <h>', 'ElasticSearch host')
	.option('-p ,--port <p>', 'ElasticSearch port', parseInt)
  .parse(process.argv);

if(!program.shapefile || !program.shapefile.match(/\.shp$/i)){
  errorText += 'Invalid shapefile.\n';
}

if(!program.host){
  errorText += 'Must provide an elasticsearch host';
}

if(!program.port || program.port < -1 || program.port > 65536){
  errorText += 'Must provide a port number between 0 and 65535';
}

if (errorText) return usage(errorText);

return shp.read(program.shapefile, program.host, program.port);

function usage(error) {
  console.log(error);
  console.log('usage: ./shp2es -s <shapefile> -h <ElasticSearch host> -p <ElasticSearch port>');
}
<commit_msg>Cleaner printing<commit_after>#!/usr/bin/env node

'use strict';

var program = require('commander');
var shp = require('./lib/shp');
var errorText = ''

program
  .version('1.0.0')
	.option('-s, --shapefile <s>', 'Shapefile')
	.option('-h, --host <h>', 'ElasticSearch host')
	.option('-p ,--port <p>', 'ElasticSearch port', parseInt)
  .parse(process.argv);

if(!program.shapefile || !program.shapefile.match(/\.shp$/i)){
  errorText += 'Invalid shapefile.\n';
}

if(!program.host){
  errorText += 'Must provide an elasticsearch host.\n';
}

if(!program.port || program.port < -1 || program.port > 65536){
  errorText += 'Must provide a port number between 0 and 65535.\n';
}

if (errorText) return usage(errorText);

return shp.read(program.shapefile, program.host, program.port);

function usage(error) {
  console.log(error);
  console.log('usage: ./shp2es -s <shapefile> -h <ElasticSearch host> -p <ElasticSearch port>');
}
<|endoftext|>


<commit_before>function setup() {
  COLOR_1 = color("#233237"); // gunmetal
  COLOR_2 = color("#984b43"); // rusty red
  WHITE = color("#ffffff");

  createCanvas(windowWidth, windowHeight)
  noStroke();
  textAlign(CENTER, CENTER);
  textSize(96);

  score_1 = 0;
  score_2 = 0;
}

function draw() {
  // score_1 background
  fill(COLOR_1);
  if (height > width) {
    rect(0, 0, width, 0.5 * height);
  } else {
    rect(0, 0, 0.5 * width, height);
  }
  // score_2 background
  fill(COLOR_2);
  if (height > width) {
    rect(0, 0.5 * height, width, 0.5 * height);
  } else {
    rect(0.5 * width, 0, 0.5 * width, height);
  }

  // scores
  fill(WHITE);
  if (height > width) {
    text(score_1.toString(), 0.5 * width, 0.25 * height);
    text(score_2.toString(), 0.5 * width, 0.75 * height);
  } else {
    text(score_1.toString(), 0.25 * width, 0.5 * height);
    text(score_2.toString(), 0.75 * width, 0.5 * height);
  }
}

function mousePressed() {
  var score_1_clicked = (height > width) ? (mouseY < 0.5 * height) : (mouseX < 0.5 * width);

  if (score_1_clicked) {
    ++score_1;
  } else {
    ++score_2;
  }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}<commit_msg>add reset button; add digit scaling<commit_after>function setup() {
  COLOR_1 = color("#233237"); // gunmetal
  COLOR_2 = color("#984b43"); // rusty red
  RESET_SYMBOL = "↻";

  createCanvas(windowWidth, windowHeight)
  noStroke();
  textAlign(CENTER, CENTER);
  textSize(96);

  score_1 = 0;
  score_2 = 0;
  reset_button_diameter = 0;
}

function draw() {
  // score_1 background
  fill(COLOR_1);
  if (height > width) {
    rect(0, 0, width, 0.5 * height);
  } else {
    rect(0, 0, 0.5 * width, height);
  }
  // score_2 background
  fill(COLOR_2);
  if (height > width) {
    rect(0, 0.5 * height, width, 0.5 * height);
  } else {
    rect(0.5 * width, 0, 0.5 * width, height);
  }

  // scores
  fill(255);
  textSize(0.375 * min(width, height));
  if (height > width) {
    text(score_1.toString(), 0.5 * width, 0.25 * height);
    text(score_2.toString(), 0.5 * width, 0.75 * height);
  } else {
    text(score_1.toString(), 0.25 * width, 0.5 * height);
    text(score_2.toString(), 0.75 * width, 0.5 * height);
  }

  // reset button
  textSize(0.0625 * max(width, height));
  reset_button_diameter = 1.25 * textWidth(RESET_SYMBOL);
  fill(255);
  ellipse(0.5 * width, 0.5 * height, reset_button_diameter);
  fill(0);
  text(RESET_SYMBOL, 0.5 * width, 0.5 * height)
}

function mousePressed() {
  if (dist(mouseX, mouseY, 0.5 * width, 0.5 * height) < 0.5 * reset_button_diameter) {
    // reset button clicked
    score_1 = 0;
    score_2 = 0;
  } else {
    var score_1_clicked = (height > width) ? (mouseY < 0.5 * height) : (mouseX < 0.5 * width);

    if (score_1_clicked) {
      ++score_1;
    } else {
      ++score_2;
    }
  }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}
<|endoftext|>


<commit_before>function setup() {

}

function draw() {

}
<commit_msg>Created basic canvas<commit_after>function setup() {
  createCanvas(windowWidht,windowHeight);
}

function draw() {
  background(0);
}
<|endoftext|>


<commit_before>var p5 = p5.prototype;
var level = 0;
var active = true
var activeE = false
var lives = 3
var missBase = 50
var pMiss = 0
var eMiss = 0
var lastTime = Date.now()
var contributers = ['Daft Podunk',
  'Willard',
  'Hugh Morris',
  'Fwiller',
  'Dasyayi',
  'Steven',
  'Wott',
  'Vince Delicious',
  'A giant potato',
  'Fabian',
  'Cameron Cisco',
  'Gabisver',
  'Fouton',
  'Dezzy',
  'Mitch',
  'E Van',
  'The Dabsmith',
  'Ninnyz'
]

var ling = [
  'al', 'ie', 't', 'ev', 'ic', 'oc', 'so', "k'", 'dal', 'dek', 'der', 'div', 'scov', 'leni', 'leb', 'si', 'to', 'my', 'lobo', 'lin', 'fin', 'son', 's', 'ar', 'er', 'ir', 'or', 'ur', 't', 'p', 's', 'd', 'ba', 'be', 'bi', 'bo', 'bu', 'st', 'ev', 'en', 'qa', 'qe', 'qi', 'qo', 'qu', 'ga', 'ell', 'se', 'ka', 'ris', 'sa', 'zim', 'da', 'de', 'di', 'do', 'du', 'hit', 'dez', 'ler', 'ey', 'ra', 're', 'ri', 'ro', 'ru', 'an', 'wa', 'we', 'wi', 'wo', 'wu', 'wy', 'et', 'han', 'ash', 'esh', 'ish',
  'osh', 'ush', 'ane', 'ca', 'ce', 'ci', 'co', 'cu', 'fa', 'fe', 'fi', 'fo', 'fu', 'ga', 'ge', 'gi', 'go', 'gu'
]

setTimeout(function() {
  activeE = true
}, 4000);

function save() {
  var sav1 = JSON.stringify(player.weapon)
  sav1 = btoa(sav1)
  saveDoc.value = sav1
}

function load() {
  var sav = saveDoc.value
  sav = atob(sav)
  player.weapon = JSON.parse(sav)
}

var weapons = []

for (var i = 0; i < 90; i++) {
  weapons.push(new Weapon())
}

var saveDoc = document.getElementById('name')
var loadS = document.getElementById("load")
var saveW = document.getElementById("save")
var game = document.getElementById("game")
var main = document.getElementById('main')
var output = document.getElementById('output')
var attackbtn = document.getElementById("attackBtn")
var enemyDoc = document.getElementById("mainEnemy")
var spawnButton = document.getElementById("newEnemy")
var loot = document.getElementById('Loot')
$(document).ready(function() {
  $(game).hide()
  $(game).slideDown(500)
})
attackbtn.addEventListener("click", attackP)
loot.addEventListener("click", lootEnemy)
spawnButton.addEventListener("click", nextE)
saveW.addEventListener("click", save)
loadS.addEventListener("click", load)
// generate player and enemies
var player = new human()
var enemy = new Enemy()
// make starter sword
player.weapon.name = "Explorer's old rusty sword"
player.weapon.type = "'s starter"
player.weapon.speed = 700
player.weapon.damage = 8
player.weapon.di = 3
player.weapon.accuracy = 40
//buildpage
enemyDoc.innerHTML = makeHtml(enemy)
main.innerHTML = makeHtml(player)
//

//clocks
var gameClock = setInterval(function() {
  if (player.health <= 0 && lives > 0) {
    lives--
    player.health = player.maxHealth
    activeE = false
    active = true
    output.innerHTML = ("
You have been revived to continue your journey! " + lives + " revives remaining!
" + output.innerHTML)
    setTimeout(function() {
      activeE = true
    }, 1000);
  }
  if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
    enemyDoc.innerHTML = makeHtml(enemy)
    main.innerHTML = makeHtml(player)
  }
  if (enemy.health > 0) {
    $(".hideme").hide()
  } else {
    $(".hideme").slideDown(200)
  }
  if ((Date.now() - lastTime) > 400) {
    for (var i = 0; i < ((Date.now() - lastTime) / 100); i++) {
      if (player.health > 0) {
        player.regen()
      }
    }
    if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
      enemyDoc.innerHTML = makeHtml(enemy)
      main.innerHTML = makeHtml(player)
    }
  }
  lastTime = Date.now();
}, 100);

function selfTest(x, y) {
  return x + y
}

// (function($) {
//   $.fn.nodoubletapzoom = function() {
//       $(this).bind('touchstart', function preventZoom(e) {
//         var t2 = e.timeStamp
//           , t1 = $(this).data('lastTouch') || t2
//           , dt = t2 - t1
//           , fingers = e.originalEvent.touches.length;
//         $(this).data('lastTouch', t2);
//         if (!dt || dt > 500 || fingers > 1) return; // not double-tap
//         e.preventDefault(); // double tap - prevent the zoom
//         // also synthesize click events we just swallowed up
//         $(this).trigger('click').trigger('click');
//       });
//   };
// })(jQuery);
var clock = setInterval(function() {
  if (player.health > 0) {
    player.regen()
    if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
      enemyDoc.innerHTML = makeHtml(enemy)
      main.innerHTML = makeHtml(player)
    }
  }
}, 200);

var enemyClock = setInterval(function() {
  if (enemy.health > 0) {
    enemy.regen()
    if (activeE) {
      setTimeout(function() {
        attackE()
        setTimeout(function() {
          activeE = true
          eMiss = 0
        }, eMiss);
      }, (1000) - enemy.weapon.speed);
    }
    activeE = false
    if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
      enemyDoc.innerHTML = makeHtml(enemy)
      main.innerHTML = makeHtml(player)
    }
  }
  if (player.weapon === undefined) {
    weapons.push(new Weapon())
    player.weapon = weapons[0]
  }
}, 400);

//
//Display
function makeHtml(char) {
  if (char.health <= 0) {
    char.health = 0
  }
  var tmp = ""
  tmp += ("

" + char.name + " at Level: " + level + "
")
  tmp += ("
")
  tmp += ("
" + (+(char.health / char.maxHealth).toFixed(4) * 100).toFixed(2) + "% health. " + char.health.toFixed(1) + " /" + char.maxHealth.toFixed(0) + " points
")
  tmp += ("
 Wielding " + char.weapon.name + " :
Level " + char.weapon.level + "
speed: " + (char.weapon.speed / 10).toFixed(0) + "
")
  tmp += ("
Accuracy: " + (char.weapon.accuracy).toFixed(1) + "
")
  if (char.weapon.di >= 2) {

    tmp += ("
 rolling " + char.weapon.di + " D" + char.weapon.damage + "s
")
  } else {
    tmp += ("
 rolling " + char.weapon.di + " D" + char.weapon.damage + "
")
  }
  tmp += ("
" + (char.stamina).toFixed(1) + " stamina

")
  return tmp
}
main.innerHTML = makeHtml(player)
//
//Generate Names
function makeName(t) {
  var len = Math.round(p5.random(2, 10))
  var name = ""
  for (var i = 0; name.length < len; i++) {
    name += p5.random(ling)
  }
  name = name.toLowerCase()
  var fl = name.charAt(0)
  fl = fl.toUpperCase()
  name = name.slice(1)
  name = fl + name
  if (p5.random(0, 100) < 40 && t != 'weapon') {
    name = p5.random(contributers)
  }
  return name
}
// Players attack
function attackP() {
  if (active == true) {
    if (player.stamina <= 1) {
      if (player.stamina <= 0) {
        player.stamina = 0
      }
      main.innerHTML = makeHtml(player)
      output.innerHTML = ("
You cannot attack now: Not enough stamina

" + output.innerHTML)

    } else if (player.health == 0 || enemy.health == 0) {
      main.innerHTML = makeHtml(player)

    } else {
      var dam = player.attack()
      if (dam == 0) {
        enemyDoc.innerHTML = makeHtml(enemy)
        main.innerHTML = makeHtml(player)
        output.innerHTML = ("
 You've missed!

" + output.innerHTML)
        pMiss = 1000
      } else {
        enemy.health -= dam
        enemyDoc.innerHTML = makeHtml(enemy)
        main.innerHTML = makeHtml(player)
        output.innerHTML = ("
 Attacked for: " + dam + "

" + output.innerHTML)
      }
    }
    active = false
    setTimeout(function() {
      setTimeout(function() {
        active = true
        pMiss = 0
      }, pMiss);
    }, (1000) - player.weapon.speed);
  }
}

//Enemies attack
function attackE() {
  var dam = enemy.attack()
  if (enemy.stamina < 1 && player.health !== 0 && enemy.health > 0) {
    if (enemy.stamina < 0) {
      enemy.stamina = 0
    }
    enemyDoc.innerHTML = makeHtml(enemy)

  } else if (player.health == 0 || enemy.health == 0) {
    enemyDoc.innerHTML = makeHtml(enemy)
  } else if (dam == 0) {
    enemy.stamina = +(enemy.stamina - 1).toFixed(2);
    enemyDoc.innerHTML = makeHtml(enemy)
    output.innerHTML = ("
Enemy missed! Strike now while they recover!
" + output.innerHTML)
    eMiss = 1000
  } else {
    player.health -= dam
    enemy.stamina = +(enemy.stamina - 1).toFixed(2);
    enemyDoc.innerHTML = makeHtml(enemy)
    output.innerHTML = ("
 Took " + dam + " Damage! You are at " + player.health.toFixed(0) + " health.

" + output.innerHTML)
  }
}
//On next level
function nextE() {
  if (active == true) {
    for (var i = 0; i < 10; i++) {
      weapons.push(new Weapon())
    }
    if (weapons.length > 500) {
      while (weapons.length > 500) {
        weapons.shift()
      }
    }
    main.innerHTML = makeHtml(player)
    enemyDoc.innerHTML = makeHtml(enemy)
    player.levelUp()
    enemy = new Enemy()
    level += 1
    active = false
    setTimeout(function() {
      active = true
    }, 100);
  }
}

function lootEnemy() {
  var tmp = player.weapon
  player.weapon = enemy.weapon
  enemy.weapon = tmp
}
<commit_msg>halved missrate<commit_after>var p5 = p5.prototype;
var level = 0;
var active = true
var activeE = false
var lives = 3
var missBase = 100
var pMiss = 0
var eMiss = 0
var lastTime = Date.now()
var contributers = ['Daft Podunk',
  'Willard',
  'Hugh Morris',
  'Fwiller',
  'Dasyayi',
  'Steven',
  'Wott',
  'Vince Delicious',
  'A giant potato',
  'Fabian',
  'Cameron Cisco',
  'Gabisver',
  'Fouton',
  'Dezzy',
  'Mitch',
  'E Van',
  'The Dabsmith',
  'Ninnyz'
]

var ling = [
  'al', 'ie', 't', 'ev', 'ic', 'oc', 'so', "k'", 'dal', 'dek', 'der', 'div', 'scov', 'leni', 'leb', 'si', 'to', 'my', 'lobo', 'lin', 'fin', 'son', 's', 'ar', 'er', 'ir', 'or', 'ur', 't', 'p', 's', 'd', 'ba', 'be', 'bi', 'bo', 'bu', 'st', 'ev', 'en', 'qa', 'qe', 'qi', 'qo', 'qu', 'ga', 'ell', 'se', 'ka', 'ris', 'sa', 'zim', 'da', 'de', 'di', 'do', 'du', 'hit', 'dez', 'ler', 'ey', 'ra', 're', 'ri', 'ro', 'ru', 'an', 'wa', 'we', 'wi', 'wo', 'wu', 'wy', 'et', 'han', 'ash', 'esh', 'ish',
  'osh', 'ush', 'ane', 'ca', 'ce', 'ci', 'co', 'cu', 'fa', 'fe', 'fi', 'fo', 'fu', 'ga', 'ge', 'gi', 'go', 'gu'
]

setTimeout(function() {
  activeE = true
}, 4000);

function save() {
  var sav1 = JSON.stringify(player.weapon)
  sav1 = btoa(sav1)
  saveDoc.value = sav1
}

function load() {
  var sav = saveDoc.value
  sav = atob(sav)
  player.weapon = JSON.parse(sav)
}

var weapons = []

for (var i = 0; i < 90; i++) {
  weapons.push(new Weapon())
}

var saveDoc = document.getElementById('name')
var loadS = document.getElementById("load")
var saveW = document.getElementById("save")
var game = document.getElementById("game")
var main = document.getElementById('main')
var output = document.getElementById('output')
var attackbtn = document.getElementById("attackBtn")
var enemyDoc = document.getElementById("mainEnemy")
var spawnButton = document.getElementById("newEnemy")
var loot = document.getElementById('Loot')
$(document).ready(function() {
  $(game).hide()
  $(game).slideDown(500)
})
attackbtn.addEventListener("click", attackP)
loot.addEventListener("click", lootEnemy)
spawnButton.addEventListener("click", nextE)
saveW.addEventListener("click", save)
loadS.addEventListener("click", load)
// generate player and enemies
var player = new human()
var enemy = new Enemy()
// make starter sword
player.weapon.name = "Explorer's old rusty sword"
player.weapon.type = "'s starter"
player.weapon.speed = 700
player.weapon.damage = 8
player.weapon.di = 3
player.weapon.accuracy = 40
//buildpage
enemyDoc.innerHTML = makeHtml(enemy)
main.innerHTML = makeHtml(player)
//

//clocks
var gameClock = setInterval(function() {
  if (player.health <= 0 && lives > 0) {
    lives--
    player.health = player.maxHealth
    activeE = false
    active = true
    output.innerHTML = ("
You have been revived to continue your journey! " + lives + " revives remaining!
" + output.innerHTML)
    setTimeout(function() {
      activeE = true
    }, 1000);
  }
  if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
    enemyDoc.innerHTML = makeHtml(enemy)
    main.innerHTML = makeHtml(player)
  }
  if (enemy.health > 0) {
    $(".hideme").hide()
  } else {
    $(".hideme").slideDown(200)
  }
  if ((Date.now() - lastTime) > 400) {
    for (var i = 0; i < ((Date.now() - lastTime) / 100); i++) {
      if (player.health > 0) {
        player.regen()
      }
    }
    if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
      enemyDoc.innerHTML = makeHtml(enemy)
      main.innerHTML = makeHtml(player)
    }
  }
  lastTime = Date.now();
}, 100);

function selfTest(x, y) {
  return x + y
}

// (function($) {
//   $.fn.nodoubletapzoom = function() {
//       $(this).bind('touchstart', function preventZoom(e) {
//         var t2 = e.timeStamp
//           , t1 = $(this).data('lastTouch') || t2
//           , dt = t2 - t1
//           , fingers = e.originalEvent.touches.length;
//         $(this).data('lastTouch', t2);
//         if (!dt || dt > 500 || fingers > 1) return; // not double-tap
//         e.preventDefault(); // double tap - prevent the zoom
//         // also synthesize click events we just swallowed up
//         $(this).trigger('click').trigger('click');
//       });
//   };
// })(jQuery);
var clock = setInterval(function() {
  if (player.health > 0) {
    player.regen()
    if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
      enemyDoc.innerHTML = makeHtml(enemy)
      main.innerHTML = makeHtml(player)
    }
  }
}, 200);

var enemyClock = setInterval(function() {
  if (enemy.health > 0) {
    enemy.regen()
    if (activeE) {
      setTimeout(function() {
        attackE()
        setTimeout(function() {
          activeE = true
          eMiss = 0
        }, eMiss);
      }, (1000) - enemy.weapon.speed);
    }
    activeE = false
    if (enemyDoc.innerHTML != makeHtml(enemy) || main.innerHTML != makeHtml(player)) {
      enemyDoc.innerHTML = makeHtml(enemy)
      main.innerHTML = makeHtml(player)
    }
  }
  if (player.weapon === undefined) {
    weapons.push(new Weapon())
    player.weapon = weapons[0]
  }
}, 400);

//
//Display
function makeHtml(char) {
  if (char.health <= 0) {
    char.health = 0
  }
  var tmp = ""
  tmp += ("

" + char.name + " at Level: " + level + "
")
  tmp += ("
")
  tmp += ("
" + (+(char.health / char.maxHealth).toFixed(4) * 100).toFixed(2) + "% health. " + char.health.toFixed(1) + " /" + char.maxHealth.toFixed(0) + " points
")
  tmp += ("
 Wielding " + char.weapon.name + " :
Level " + char.weapon.level + "
speed: " + (char.weapon.speed / 10).toFixed(0) + "
")
  tmp += ("
Accuracy: " + (char.weapon.accuracy).toFixed(1) + "
")
  if (char.weapon.di >= 2) {

    tmp += ("
 rolling " + char.weapon.di + " D" + char.weapon.damage + "s
")
  } else {
    tmp += ("
 rolling " + char.weapon.di + " D" + char.weapon.damage + "
")
  }
  tmp += ("
" + (char.stamina).toFixed(1) + " stamina

")
  return tmp
}
main.innerHTML = makeHtml(player)
//
//Generate Names
function makeName(t) {
  var len = Math.round(p5.random(2, 10))
  var name = ""
  for (var i = 0; name.length < len; i++) {
    name += p5.random(ling)
  }
  name = name.toLowerCase()
  var fl = name.charAt(0)
  fl = fl.toUpperCase()
  name = name.slice(1)
  name = fl + name
  if (p5.random(0, 100) < 40 && t != 'weapon') {
    name = p5.random(contributers)
  }
  return name
}
// Players attack
function attackP() {
  if (active == true) {
    if (player.stamina <= 1) {
      if (player.stamina <= 0) {
        player.stamina = 0
      }
      main.innerHTML = makeHtml(player)
      output.innerHTML = ("
You cannot attack now: Not enough stamina

" + output.innerHTML)

    } else if (player.health == 0 || enemy.health == 0) {
      main.innerHTML = makeHtml(player)

    } else {
      var dam = player.attack()
      if (dam == 0) {
        enemyDoc.innerHTML = makeHtml(enemy)
        main.innerHTML = makeHtml(player)
        output.innerHTML = ("
 You've missed!

" + output.innerHTML)
        pMiss = 1000
      } else {
        enemy.health -= dam
        enemyDoc.innerHTML = makeHtml(enemy)
        main.innerHTML = makeHtml(player)
        output.innerHTML = ("
 Attacked for: " + dam + "

" + output.innerHTML)
      }
    }
    active = false
    setTimeout(function() {
      setTimeout(function() {
        active = true
        pMiss = 0
      }, pMiss);
    }, (1000) - player.weapon.speed);
  }
}

//Enemies attack
function attackE() {
  var dam = enemy.attack()
  if (enemy.stamina < 1 && player.health !== 0 && enemy.health > 0) {
    if (enemy.stamina < 0) {
      enemy.stamina = 0
    }
    enemyDoc.innerHTML = makeHtml(enemy)

  } else if (player.health == 0 || enemy.health == 0) {
    enemyDoc.innerHTML = makeHtml(enemy)
  } else if (dam == 0) {
    enemy.stamina = +(enemy.stamina - 1).toFixed(2);
    enemyDoc.innerHTML = makeHtml(enemy)
    output.innerHTML = ("
Enemy missed! Strike now while they recover!
" + output.innerHTML)
    eMiss = 1000
  } else {
    player.health -= dam
    enemy.stamina = +(enemy.stamina - 1).toFixed(2);
    enemyDoc.innerHTML = makeHtml(enemy)
    output.innerHTML = ("
 Took " + dam + " Damage! You are at " + player.health.toFixed(0) + " health.

" + output.innerHTML)
  }
}
//On next level
function nextE() {
  if (active == true) {
    for (var i = 0; i < 10; i++) {
      weapons.push(new Weapon())
    }
    if (weapons.length > 500) {
      while (weapons.length > 500) {
        weapons.shift()
      }
    }
    main.innerHTML = makeHtml(player)
    enemyDoc.innerHTML = makeHtml(enemy)
    player.levelUp()
    enemy = new Enemy()
    level += 1
    active = false
    setTimeout(function() {
      active = true
    }, 100);
  }
}

function lootEnemy() {
  var tmp = player.weapon
  player.weapon = enemy.weapon
  enemy.weapon = tmp
}
<|endoftext|>


<commit_before>let gridSize = 32
let grid

function setup() {
  makeGrid()
  createCanvas(512, 512)
  drawGrid()
}

function makeGrid() {
  grid = new Array(32)
  for (var i = 0; i < grid.length; i++) {
    grid[i] = new Array(32)
  }
}

function drawGrid() {
  tileSize = floor(width / gridSize)

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid.length; j++) {
      fill(random(51, 200))
      stroke(0)
      x = map(i, 0, 32, 0, 512)
      y = map(j, 0, 32, 0, 512)
      rect(x, y, tileSize, tileSize)
    }
  }
}

function draw() {

}
<commit_msg>Redesign makeGrid() and drawGrid()<commit_after>let gridSize = 32
let grid

function setup() {
  grid = makeGrid(32, 32)
  createCanvas(512, 512)
  drawGrid()
}

function makeGrid(x, y) {
  let g = new Array(x)
  for (var i = 0; i < g.length; i++) {
    g[i] = new Array(y)
  }

  return g
}

function drawGrid() {
  tileSize = floor(width / gridSize)

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid.length; j++) {
      if (grid[x][y] === undefined) {
        fill(51)
        stroke(0)
      }
      x = map(i, 0, 32, 0, 512)
      y = map(j, 0, 32, 0, 512)
      rect(x, y, tileSize, tileSize)
    }
  }
}
<|endoftext|>


<commit_before>$(document).on('ready', function () {
  var hasDuplicates = function (array) {
    // debugger
    var sortedValues = array.sort();
    for(var i = 1; i < sortedValues.length; i++) {
      if(sortedValues[i] && (sortedValues[i] === sortedValues[i-1])) {
        return true;
      }
    }
    return false;
  }

  var generateMatrix = function () {
    var rows = $('tr');
    var matrix = _.map(rows, function (row, rowIndex) {
      var cells = $(row).find('td');
      return _.map(cells, function (cell, cellIndex) {
        var value = $(cell).find('input').val();
        var set = value ? true : false;
        return {
          rowIndex: rowIndex,
          cellIndex: cellIndex,
          set: set,
          value: value
        }
      })
    });
    return matrix;
  }

  var hasRowConflictAt = function (rowIndex, matrix) {
    var row = matrix[rowIndex];
    var values = _.map(row, function (cell) {
      return (cell.value === "") ? undefined : +cell.value;
    });
    return hasDuplicates(values);
  }

  var hasRowConflicts = function (matrix) {
    for(var i = 0; i < matrix.length; i++) {
      if(hasRowConflictAt(i, matrix)) {
        return true;
      }
    }
    return false;
  }

  var hasColConflictAt = function (colIndex, matrix) {
    var colValues = _.map(matrix, function (row) {
      return +row[colIndex].value;
    });
    return hasDuplicates(colValues);
  }

  var hasColConflicts = function (matrix) {
    for(var i = 0; i < matrix.length; i++) {
      if(hasColConflictAt(i, matrix)) {
        return true;
      }
    }
    return false;
  }

  // rowGroup describes a grouping of rows as 1, 2, or 3, to describe the first, second, or third three rows, respectively
  // colGroup describes a grouping of cols as 1, 2, or 3, to describe the first, second, or third three cols, respectively
  // a group is therefore described in terms of a rowGroup and a colGroup, such as (2,2) for the center group

  var hasGroupConflictAt = function (rowGroup, colGroup, matrix) {
    var groups = {
      1: [0,3],
      2: [3,6],
      3: [6,9]
    }
    var rowGroupCoordinates = groups[rowGroup];
    var colGroupCoordinates = groups[colGroup];
    var group = [].slice.apply(matrix, rowGroupCoordinates).map(function (row) {
      return [].slice.apply(row, colGroupCoordinates);
    });
    var groupValues = _.flatten(group).map(function (cell) {
      return +cell.value;
    });
    var sortedValues = groupValues.sort();
    return hasDuplicates(sortedValues);
  }

  var hasGroupConflicts = function (matrix) {
    for(var rowGroupIndex = 1; rowGroupIndex < 4; rowGroupIndex++) {
      for(var colGroupIndex = 1; colGroupIndex < 4; colGroupIndex++) {
        if(hasGroupConflictAt(rowGroupIndex, colGroupIndex, matrix)) {
          return true;
        }
      }
    }
    return false;
  }

  $('.solve')
    .on('click', function (e) {
      e.preventDefault();
      var matrix = generateMatrix();
      var hasConflicts = function () {
        return hasRowConflicts(matrix) || hasColConflicts(matrix) || hasGroupConflicts(matrix);
      }
      var setValue = function(rowIndex, colIndex, value) {
        matrix[rowIndex][colIndex].value = value;
      }

      var removeValue = function(rowIndex, colIndex) {
        matrix[rowIndex][colIndex].value = 0;
      }

      var inner = function (rowIndex, colIndex, value) {
        var cell = matrix[rowIndex][colIndex];
        if(cell.set) { // if the cell has been pre-set...
          return inner(rowIndex, ++colIndex, 1); // move to the next column
        } else if (!cell.set) { // otherwise...
          setValue(rowIndex, colIndex, value); // set the specified input
          var conflict = hasConflicts(); // check for conflicts
          if(conflict) { // if there is a conflict ...
            removeValue(rowIndex, colIndex) // remove the value...
            if(value < 9) { // if the attempted input is less than 9...
              return inner(rowIndex, colIndex, ++value); // try again with a higher value
            } else { // otherwise
              return false; // conflict is unavoidable using numbers 1-9 - go back down the line and change the values that came before
            }
          } else if (!conflict) { // if there is no conflict with the newly set value
            var nextColumn = colIndex < 8;
            var nextRow = rowIndex < 8;
            if(nextColumn) {
              return inner(rowIndex, ++colIndex, 1); // move on to the next column
            } else if (nextRow) {
              return inner(++rowIndex, 0, 1);
            } else if (!nextColumn && !nextRow) {
              return matrix;
            }
          }
        }
      }
      var result = inner(0,0,1);
      console.log(result);
      debugger
    }); // end on click

  $('.clear')
    .on('click', function (e) {
      e.preventDefault();
      $('input').val('');
    });

  $('.tr1').find('.td1 input').focus();

}); // end on ready

<commit_msg>started pulling recursive calls out into variables to test paths, rather than simply returning the recursive calls.<commit_after>$(document).on('ready', function () {
  var hasDuplicates = function (array) {
    // debugger
    var sortedValues = array.sort();
    for(var i = 1; i < sortedValues.length; i++) {
      if(sortedValues[i] && (sortedValues[i] === sortedValues[i-1])) {
        return true;
      }
    }
    return false;
  }

  var generateMatrix = function () {
    var rows = $('tr');
    var matrix = _.map(rows, function (row, rowIndex) {
      var cells = $(row).find('td');
      return _.map(cells, function (cell, cellIndex) {
        var value = $(cell).find('input').val();
        var set = value ? true : false;
        return {
          rowIndex: rowIndex,
          cellIndex: cellIndex,
          set: set,
          value: value
        }
      })
    });
    return matrix;
  }

  var hasRowConflictAt = function (rowIndex, matrix) {
    var row = matrix[rowIndex];
    var values = _.map(row, function (cell) {
      return (cell.value === "") ? undefined : +cell.value;
    });
    return hasDuplicates(values);
  }

  var hasRowConflicts = function (matrix) {
    for(var i = 0; i < matrix.length; i++) {
      if(hasRowConflictAt(i, matrix)) {
        return true;
      }
    }
    return false;
  }

  var hasColConflictAt = function (colIndex, matrix) {
    var colValues = _.map(matrix, function (row) {
      return +row[colIndex].value;
    });
    return hasDuplicates(colValues);
  }

  var hasColConflicts = function (matrix) {
    for(var i = 0; i < matrix.length; i++) {
      if(hasColConflictAt(i, matrix)) {
        return true;
      }
    }
    return false;
  }

  // rowGroup describes a grouping of rows as 1, 2, or 3, to describe the first, second, or third three rows, respectively
  // colGroup describes a grouping of cols as 1, 2, or 3, to describe the first, second, or third three cols, respectively
  // a group is therefore described in terms of a rowGroup and a colGroup, such as (2,2) for the center group

  var hasGroupConflictAt = function (rowGroup, colGroup, matrix) {
    var groups = {
      1: [0,3],
      2: [3,6],
      3: [6,9]
    }
    var rowGroupCoordinates = groups[rowGroup];
    var colGroupCoordinates = groups[colGroup];
    var group = [].slice.apply(matrix, rowGroupCoordinates).map(function (row) {
      return [].slice.apply(row, colGroupCoordinates);
    });
    var groupValues = _.flatten(group).map(function (cell) {
      return +cell.value;
    });
    var sortedValues = groupValues.sort();
    return hasDuplicates(sortedValues);
  }

  var hasGroupConflicts = function (matrix) {
    for(var rowGroupIndex = 1; rowGroupIndex < 4; rowGroupIndex++) {
      for(var colGroupIndex = 1; colGroupIndex < 4; colGroupIndex++) {
        if(hasGroupConflictAt(rowGroupIndex, colGroupIndex, matrix)) {
          return true;
        }
      }
    }
    return false;
  }

  $('.solve')
    .on('click', function (e) {
      e.preventDefault();

      var matrix = generateMatrix();
      var hasConflicts = function () {
        return hasRowConflicts(matrix) || hasColConflicts(matrix) || hasGroupConflicts(matrix);
      }
      var setValue = function(rowIndex, colIndex, value) {
        matrix[rowIndex][colIndex].value = value;
      }
      var removeValue = function(rowIndex, colIndex) {
        matrix[rowIndex][colIndex].value = 0;
      }
      var mapValues = function () {
        return matrix.map(function (row) {
          return row.map(function (cell) {
            return cell.value;
          });
        });
      }
      console.log('mapValues right before declaration', mapValues)

      var inner = function (rowIndex, colIndex, value) {
        var cell = matrix[rowIndex][colIndex];
        console.log('rowIndex', rowIndex, 'colIndex', colIndex, 'value', value);
        console.log('mapValues inner', mapValues);
        console.log(removeValue)
        if(cell.set) { // if the cell has been pre-set...
          return inner(rowIndex, ++colIndex, 1); // move to the next column
        } else if (!cell.set) { // otherwise...
          setValue(rowIndex, colIndex, value); // set the specified input
          var conflict = hasConflicts(); // check for conflicts
          if(conflict) { // if there is a conflict ...
            removeValue(rowIndex, colIndex) // remove the value...
            if(value < 9) { // if the attempted input is less than 9...
              var possibleSoFar = inner(rowIndex, colIndex, ++value); // try again with a higher value
              if possibleSoFar {
                return possibleSoFar;
              } else {
                return inner(rowIndex, ++colIndex, )
              }
            } else { // otherwise
              return false; // conflict is unavoidable using numbers 1-9 - go back down the line and change the values that came before
            }
          } else if (!conflict) { // if there is no conflict with the newly set value
            var nextColumn = colIndex < 8; // see if there is a next column
            var nextRow = rowIndex < 8; // see if there is a new row
            if(nextColumn) { // if there is a new column....
              var nextColWorks = inner(rowIndex, ++colIndex, 1); // move on to the next column and check to see if it provides a solution
              if(nextColWorks) { // if it provides a solution
                return nextColWorks; // return the solution
              } else { // otherwise
                console.log('nextCol didnt work:','rowIndex', rowIndex, 'colIndex', colIndex, 'value', value);
                debugger
                var nextValWorks = inner(rowIndex, colIndex, ++value); // stay in this column and increment the value
                if(nextValWorks) {
                  return nextValWorks;
                } else {
                  console.log('nextVal didnt work:','rowIndex', rowIndex, 'colIndex', colIndex, 'value', value);
                  debugger
                  return false;
                }
              }
            } else if (nextRow) { // if there is no next column, see if there is a next row
              console.log('nextRow', rowIndex+1);
              return inner(++rowIndex, 0, 1); // if so, move on to the next row
            } else if (!nextColumn && !nextRow) { // if we are on the last cell of the last row
              return 'no next column or row'
              // return matrix; // we have found a solution matrix, so we'll return it
            }
          }
        }
      }
      console.log('mapValues right after declaration', mapValues)

      var result = inner(0,0,1);
      console.log(result);
    }); // end on click

  $('.clear')
    .on('click', function (e) {
      e.preventDefault();
      $('input').val('');
    });

  $('.tr1').find('.td1 input').focus();

}); // end on ready

<|endoftext|>


<commit_before>class DB {

    constructor(idb, idbKey, settings, isWebWorker) {
        this.db = idb;
        this.idbKey = idbKey;
        this.settings = settings;
        this.isWebWorker = isWebWorker || false;
    }

    /**
     * Initializes database connection with indexedDB
     *
     * @returns {Promise}
     */
    connect() {
        let db = this;
        return new Promise((resolve, reject) => {

            if(db.isWebWorker){
                db.createWorkerHandler(resolve, reject);
            }else{
                db.createNormalHandler(resolve, reject);
            }
        });
    }

    /**
     * Destroys/Deletes the databaase
     * @param dbName
     */
    destroy(dbName) {
        console.info('database ' + dbName + ' deleted');
        this.db.deleteDatabase(dbName);
    }

    /**
     * Creates connection in web worker space and if web worker fails
     * then creates normal database connection instance
     * @param resolve
     * @param reject
     */
    createWorkerHandler (resolve, reject) {
        let db = this;
        try{
            let worker = new window.Worker('/indexeddb/src/worker.js');
            let models = {};
            let timestamp = Date.now();

            worker.postMessage({
                detail : JSON.stringify(db.settings),
                action : 'initialize',
                timestamp : timestamp
            });

            worker.onmessage = function (e) {
                if(e.data.action === 'initialize' && e.data.timestamp === timestamp) {
                    if (e.data.detail === true) {
                        db.settings.migrations.forEach((schema) => {
                            Object.defineProperty(models, schema.name, {
                                get() {
                                    return new WorkerModelHandler(schema.name, worker, window);
                                }
                            });
                        });
                        resolve(models);
                    } else {
                        db.createNormalHandler(resolve, reject);
                    }
                }
            }

        }catch (e) {
            reject(e);
        }

    }

    /**
     * Creates normal database instance and models
     * @param resolve
     * @param reject
     */
    createNormalHandler (resolve, reject) {
        let db = this;

        let request = this.db.open(this.settings.dbName, this.settings.dbVersion);

        request.onupgradeneeded = function (e) {
            let mig = new Migration(e.target.result, e.target.transaction, db.settings.migrations);
            mig.run();
        };

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

        request.onsuccess = function (e) {
            let models = {};

            db.settings.migrations.forEach((schema) => {
                let primary = schema.primary || 'id';
                Object.defineProperty(models, schema.name, {
                    get() {
                        return new Model(e.target.result, db.idbKey, schema.name, primary);
                    }
                });
            });

            resolve(models);
        };
    }
}<commit_msg>change flag name to hanlde usage of web worker<commit_after>class DB {

    constructor(idb, idbKey, settings, useWebWorker) {
        this.db = idb;
        this.idbKey = idbKey;
        this.settings = settings;
        this.useWebWorker = useWebWorker || false;
        this.isWebWorker = false;
    }

    /**
     * Initializes database connection with indexedDB
     *
     * @returns {Promise}
     */
    connect() {
        let db = this;
        return new Promise((resolve, reject) => {

            if(db.useWebWorker){
                db.createWorkerHandler(resolve, reject);
            }else{
                db.createNormalHandler(resolve, reject);
            }
        });
    }

    /**
     * Destroys/Deletes the databaase
     * @param dbName
     */
    destroy(dbName) {
        console.info('database ' + dbName + ' deleted');
        this.db.deleteDatabase(dbName);
    }

    /**
     * Creates connection in web worker space and if web worker fails
     * then creates normal database connection instance
     * @param resolve
     * @param reject
     */
    createWorkerHandler (resolve, reject) {
        let db = this;
        try{
            let worker = new window.Worker('/indexeddb/src/worker.js');
            let models = {};
            let timestamp = Date.now();

            worker.postMessage({
                detail : JSON.stringify(db.settings),
                action : 'initialize',
                timestamp : timestamp
            });

            worker.onmessage = function (e) {
                if(e.data.action === 'initialize' && e.data.timestamp === timestamp) {
                    if (e.data.detail === true) {
                        db.settings.migrations.forEach((schema) => {
                            Object.defineProperty(models, schema.name, {
                                get() {
                                    return new WorkerModelHandler(schema.name, worker, window);
                                }
                            });
                        });

                        db.isWebWorker = true;
                        resolve(models);
                    } else {
                        db.createNormalHandler(resolve, reject);
                    }
                }
            }

        }catch (e) {
            reject(e);
        }

    }

    /**
     * Creates normal database instance and models
     * @param resolve
     * @param reject
     */
    createNormalHandler (resolve, reject) {
        let db = this;

        let request = this.db.open(this.settings.dbName, this.settings.dbVersion);

        request.onupgradeneeded = function (e) {
            let mig = new Migration(e.target.result, e.target.transaction, db.settings.migrations);
            mig.run();
        };

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

        request.onsuccess = function (e) {
            let models = {};

            db.settings.migrations.forEach((schema) => {
                let primary = schema.primary || 'id';
                Object.defineProperty(models, schema.name, {
                    get() {
                        return new Model(e.target.result, db.idbKey, schema.name, primary);
                    }
                });
            });

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


<commit_before>/**
 * noscript MVC framework
 * @namespace
 */
var ns = {};

if (typeof window === 'undefined') {
    module.exports = ns;
}

/**
 * @const
 * @type {Boolean}
 */
ns.IS_TOUCH = Boolean(window['Modernizr'] && Modernizr.touch && window['$'] && $.mobile);

/**
 * FIXME: зачем оно тут?
    Do not clone functions, only data.
    @param {!Object} dest
    @param {!Object} src
    @return {!Object}
*/
ns.extendRecursive = function(dest, src) {
    for (var key in src) {
        var value = src[key];

        if (value instanceof Array) {
            var ar = dest[key] = [];
            for (var j = 0, m = value.length; j < m; j++) {
                var item = value[j];
                ar[j] = (typeof item === 'object') ? ns.extendRecursive( {}, item ) : item;
            }

        } else if (typeof value === 'object') {
            dest[key] = ns.extendRecursive( {}, value );

        } else {
            dest[key] = value;

        }
    }

    return dest;
};

ns.todo = function() {
    throw new Error('Unimplemented');
};

/**
 * Parse query string to object.
 * @param {String} s Query string
 * @returns {Object}
 */
ns.parseQuery = function(s) {
    var o = {};

    s.split('&').forEach(function(chunk) {
        var p = chunk.split('=');
        var name = p[0];
        if (name) {
            var value = p[1];

            // &c=
            if (typeof value === 'undefined') {
                value = '';

            } else {
                try {
                    value = decodeURIComponent(value);
                } catch (e) {
                    value = '';
                    ns.log.info('ns.parseQuery.invalid-param', {
                        query: s,
                        chunk: chunk
                    });
                }
            }

            o[name] = value;
        }
    });

    return o;
};

/**
 * Performs json templating.
 * @param {*} json
 * @param {String} mode
 * @param {String} [module='main']
 * @returns {Element}
 */
ns.tmpl = function(json, mode, module) {
    var result = yr.run(module || 'main', json, mode);
    return ns.html2node(result);
};

/**
 * Производит первоначальную инициализацию noscript.
 */
ns.init = function() {
    ns.action.init();
    ns.router.init();

    ns.history.adapt();
    ns.initMainView();
};

/**
 * Инициализирует корневой View.
 */
ns.initMainView = function() {
    var mainView = ns.View.create('app');
    mainView._setNode(document.getElementById('app'));
    mainView.invalidate();

    /**
     * Корневой View.
     * @type {ns.View}
     */
    ns.MAIN_VIEW = mainView;
};

/**
 * Создает транзакцию (cb) и блокирует вызов ns.page.go
 * @param {Function} cb
 */
ns.transaction = function(cb) {
    // останавливаем ns.page.go
    ns.page._stop = true;
    cb();

    // запускаем ns.page.go
    ns.page._stop = false;
    ns.page.go(ns.page._lastUrl);
};

if (window['mocha']) {

    /**
     * Clean internal data after tests
     */
    ns.clean = function() {
        ns.layout.undefine();
        ns.View.undefine();
        ns.Model.undefine();
        ns.request.clean();
    };
}
<commit_msg>history.adapt вызываем последним<commit_after>/**
 * noscript MVC framework
 * @namespace
 */
var ns = {};

if (typeof window === 'undefined') {
    module.exports = ns;
}

/**
 * @const
 * @type {Boolean}
 */
ns.IS_TOUCH = Boolean(window['Modernizr'] && Modernizr.touch && window['$'] && $.mobile);

/**
 * FIXME: зачем оно тут?
    Do not clone functions, only data.
    @param {!Object} dest
    @param {!Object} src
    @return {!Object}
*/
ns.extendRecursive = function(dest, src) {
    for (var key in src) {
        var value = src[key];

        if (value instanceof Array) {
            var ar = dest[key] = [];
            for (var j = 0, m = value.length; j < m; j++) {
                var item = value[j];
                ar[j] = (typeof item === 'object') ? ns.extendRecursive( {}, item ) : item;
            }

        } else if (typeof value === 'object') {
            dest[key] = ns.extendRecursive( {}, value );

        } else {
            dest[key] = value;

        }
    }

    return dest;
};

ns.todo = function() {
    throw new Error('Unimplemented');
};

/**
 * Parse query string to object.
 * @param {String} s Query string
 * @returns {Object}
 */
ns.parseQuery = function(s) {
    var o = {};

    s.split('&').forEach(function(chunk) {
        var p = chunk.split('=');
        var name = p[0];
        if (name) {
            var value = p[1];

            // &c=
            if (typeof value === 'undefined') {
                value = '';

            } else {
                try {
                    value = decodeURIComponent(value);
                } catch (e) {
                    value = '';
                    ns.log.info('ns.parseQuery.invalid-param', {
                        query: s,
                        chunk: chunk
                    });
                }
            }

            o[name] = value;
        }
    });

    return o;
};

/**
 * Performs json templating.
 * @param {*} json
 * @param {String} mode
 * @param {String} [module='main']
 * @returns {Element}
 */
ns.tmpl = function(json, mode, module) {
    var result = yr.run(module || 'main', json, mode);
    return ns.html2node(result);
};

/**
 * Производит первоначальную инициализацию noscript.
 */
ns.init = function() {
    ns.action.init();
    ns.router.init();
    ns.initMainView();

    ns.history.adapt();
};

/**
 * Инициализирует корневой View.
 */
ns.initMainView = function() {
    var mainView = ns.View.create('app');
    mainView._setNode(document.getElementById('app'));
    mainView.invalidate();

    /**
     * Корневой View.
     * @type {ns.View}
     */
    ns.MAIN_VIEW = mainView;
};

/**
 * Создает транзакцию (cb) и блокирует вызов ns.page.go
 * @param {Function} cb
 */
ns.transaction = function(cb) {
    // останавливаем ns.page.go
    ns.page._stop = true;
    cb();

    // запускаем ns.page.go
    ns.page._stop = false;
    ns.page.go(ns.page._lastUrl);
};

if (window['mocha']) {

    /**
     * Clean internal data after tests
     */
    ns.clean = function() {
        ns.layout.undefine();
        ns.View.undefine();
        ns.Model.undefine();
        ns.request.clean();
    };
}
<|endoftext|>


<commit_before>/**
 * "Converts" a date to a specific time zone
 *
 * Note: This is only for specific and controlled usage,
 * as the internal UTC time of the resulting object will be off.
 *
 * Example:
 *   let normalDate = new Date(); // d is a normal Date instance, with local timezone and correct utc representation
 *       tzDate = CronTZ(d, 'America/New_York') // d is a tainted Date instance, where getHours()
 *                                                 (for example) will return local time in new york, but getUTCHours()
 *                                                 will return something irrelevant.
 *
 * @param {date} date - Input date
 * @param {string} tzString - Timezone string in Europe/Stockholm format
 * @param {boolean} [reverse] - Reverse operation
 * @returns {date}
 */
function CronTZ(date, tzString, reverse) {
	if (reverse) {
		return CronFromTZ(date, tzString);
	} else {
		return new Date(date.toLocaleString("sv-SE", {timeZone: tzString}));
	}
}

/**
 * Reverse of CronTZ
 *
 * @param {date} date - Input (tainted) date
 * @param {string} tzString - Timezone string in Europe/Stockholm format
 * @returns {date}
 */
function CronFromTZ(sourceDate, tzString) {

	// Try using target offset
	const
		targetPlus = new Date(sourceDate.toLocaleString("sv-SE", {timeZone: tzString})),
		offset = sourceDate.getTime() - targetPlus.getTime();

	let testOffset = 0,
		iterations = 0,
		closestAfter = -Infinity;

	while (iterations++ < 2) {
		const
			testTarget = new Date(sourceDate.getTime() + offset - testOffset),
			test = new Date(testTarget.toLocaleString("sv-SE", {timeZone: tzString}));

		testOffset = test.getTime() - sourceDate.getTime();

		if (testOffset === 0) {
			return testTarget;
		} else {
			if (testOffset < 0 && testOffset > closestAfter) {
				closestAfter = testOffset;
			}
		}

	}

	return new Date(sourceDate.getTime() + offset - closestAfter);

}

export { CronTZ };
<commit_msg>Code cleanup<commit_after>/**
 * "Converts" a date to a specific time zone
 *
 * Note: This is only for specific and controlled usage,
 * as the internal UTC time of the resulting object will be off.
 *
 * Example:
 *   let normalDate = new Date(); // d is a normal Date instance, with local timezone and correct utc representation
 *       tzDate = CronTZ(d, 'America/New_York') // d is a tainted Date instance, where getHours()
 *                                                 (for example) will return local time in new york, but getUTCHours()
 *                                                 will return something irrelevant.
 *
 * @param {date} date - Input date
 * @param {string} tzString - Timezone string in Europe/Stockholm format
 * @param {boolean} [reverse] - Reverse operation
 * @returns {date}
 */
function CronTZ(date, tzString, reverse) {
	if (reverse) {
		return CronFromTZ(date, tzString);
	} else {
		return new Date(date.toLocaleString("sv-SE", {timeZone: tzString}));
	}
}

/**
 * Reverse of CronTZ
 *
 * @param {date} date - Input (tainted) date
 * @param {string} tzString - Timezone string in Europe/Stockholm format
 * @returns {date}
 */
function CronFromTZ(sourceDate, tzString) {

	// Calculate offset between local and target, this will be a "best guess"
	const
		targetPlus = new Date(sourceDate.toLocaleString("sv-SE", {timeZone: tzString})),
		bestGuessOffset = sourceDate.getTime() - targetPlus.getTime();

	let testOffset = 0,
		iterations = 0,
		closestAfter = -Infinity;

	while (iterations++ < 2) {

		const
			// Subtract best guess from target, creating a guessed local time
			guessedLocalTime = new Date(sourceDate.getTime() + bestGuessOffset - testOffset),

			// Add correct timezone offset to guessed local time
			test = new Date(guessedLocalTime.toLocaleString("sv-SE", {timeZone: tzString}));

		// If offset is 0, we made it, return correct local time
		testOffset = test.getTime() - sourceDate.getTime();
		if (testOffset === 0) {
			return guessedLocalTime;

		// If there is an offset, this usually mean that there is a DST switch locally between target and guessed local time
		} else {

			// Store best guess after actual time, to use if we cannot make a match at all
			if (testOffset < 0 && testOffset > closestAfter) {
				closestAfter = testOffset;
			}
		}

	}

	// If we made it here, it is impossible to create a local time that land at target time
	// after applying the timezone offset. This usually means that target is during a
	// DST switch (target is 00:00:00 when clock skips from 23:59:59 to 01:00:00).
	// In this case, use the point in time which yields the time closest to target after applying timezone offset
	// which in the previous example will be 01:00:00.
	return new Date(sourceDate.getTime() + bestGuessOffset - closestAfter);

}

export { CronTZ };
<|endoftext|>


<commit_before>window.addEventListener("load", function(e) {
  // initially setup the ui
  ui.resizeElements();
  ui.resizeDialogs();
  ui.bindButtons();
  ui.bindKeys();
  ui.bindScrollRequestList();
  ui.initContentSplitter();
  ui.enableSyntaxHighlighting();

  // attach resize event
  this.addEventListener("resize", ui.resizeElements);

  // initialize trace listener
  SAMLTrace.TraceWindow.init();
}, true);

ui = {
  resizeElements: function() {
    let reservedHeight =
        document.getElementById("header").clientHeight +
        document.getElementById("dragger").clientHeight +
        document.getElementById("request-info-tabbox").clientHeight +
        document.getElementById("statuspanel").clientHeight;

    let elementTop = document.getElementById("request-list");
    let elementBottom = document.getElementById("request-info-content");
    let controlHeightSum = elementTop.clientHeight + elementBottom.clientHeight;

    let remainingHeight = window.innerHeight - reservedHeight;
    let ratioTop = (elementTop.clientHeight / controlHeightSum) * remainingHeight;
    let ratioBottom = (elementBottom.clientHeight / controlHeightSum) * remainingHeight;

    const getPaddingHeight = element => {
      let style = window.getComputedStyle(element);
      return parseInt(style.paddingTop) + parseInt(style.paddingBottom);
    };

    elementTop.style.height = (ratioTop - getPaddingHeight(elementTop)) + "px";
    elementBottom.style.height = (ratioBottom - getPaddingHeight(elementBottom)) + "px";
  },

  toggleButtonState: function(button) {
    let isActive = button.classList.contains("active");
    let newState = !isActive;
    ui.setButtonState(button, newState)
    return newState;
  },

  setButtonState: function(button, newState) {
    newState ? button.classList.add("active") : button.classList.remove("active");
  },

  bindButtons: function() {
    document.getElementById("button-clear").addEventListener("click", () => {
      window.tracer.clearRequests();
    }, true);
    document.getElementById("button-pause").addEventListener("click", e => {
      let newState = ui.toggleButtonState(e.target);
      window.tracer.setPauseTracing(newState);
    }, true);
    document.getElementById("button-autoscroll").addEventListener("click", e => {
      let newState = ui.toggleButtonState(e.target);
      window.tracer.setAutoscroll(newState);
    }, true);
    document.getElementById("button-filter").addEventListener("click", e => {
      let newState = ui.toggleButtonState(e.target);
      window.tracer.setFilterResources(newState);
      let hidableRows = document.getElementsByClassName("list-row isRessource");
      if (newState) {
        Array.from(hidableRows).forEach(row => row.classList.remove("displayAnyway"));
      } else {
        Array.from(hidableRows).forEach(row => row.classList.add("displayAnyway"));
      }
    }, true);
    document.getElementById("button-export-list").addEventListener("click", () => {
      let exportDialog = document.getElementById("exportDialog");
      exportDialog.style.visibility = "visible";
      let isFlteringActive = document.getElementById("button-filter").classList.contains("active");
      let exportDialogContent = document.getElementById("exportDialogContent");
      exportDialogContent.contentWindow.ui.setupContent(window.tracer.requests, window.tracer.httpRequests, isFlteringActive);
    }, true);
    document.getElementById("button-import-list").addEventListener("click", () => {
      let importDialog = document.getElementById("importDialog");
      importDialog.style.visibility = "visible";
      let importDialogContent = document.getElementById("importDialogContent");
      importDialogContent.contentWindow.ui.setupContent();
    }, true);

    let modalCloseButtons = document.querySelectorAll(".modal-close");
    modalCloseButtons.forEach(button => button.addEventListener("click", ui.hideDialogs, true));
  },

  bindKeys: function() {
    const closeDialogs = e => {
      // close dialogs when ESC is pressed
      if (e.key === "Escape") {
        ui.hideDialogs();
      }
    };

    const selectRequestInfoContent = e => {
      // override CTRL+A to just select the request info content
      if ((e.ctrlKey || e.metaKey) && e.key === "a") {
        let element = document.getElementById("request-info-content");
        let range = document.createRange();
        range.selectNode(element);
        window.getSelection().addRange(range);
        e.preventDefault();
      }
    };

    const selectRowOnKeybeardEvent = e => {
      // select another request, when ArrowUp, ArrowDown, PageUp, PageDown, Home or End are pressed
      let requestList = document.getElementById("request-list");
      ScrollableList.selectRowOnKeybeardEvent(e, requestList, newElement => {
        window.tracer.selectItemInList(newElement, requestList);
        window.tracer.showRequest(newElement.requestItem);
        ui.highlightContent();
      });
    };

    const togglePauseTracing = e => {
      // pauses or resumes request tracing when the pause key is pressed
      if (e.key === "Pause") {
        let button = document.getElementById("button-pause");
        let newState = ui.toggleButtonState(button);
        window.tracer.setPauseTracing(newState);
      }
    };

    let iframes = document.querySelectorAll("iframe");
    iframes.forEach(iframe => iframe.contentWindow.document.addEventListener("keydown", closeDialogs));
    document.addEventListener("keydown", closeDialogs);
    document.addEventListener("keydown", selectRequestInfoContent);
    document.addEventListener("keydown", selectRowOnKeybeardEvent);
    document.addEventListener("keydown", togglePauseTracing);
  },

  bindScrollRequestList: function() {
    let requestList = document.getElementById("request-list");
    let autoScrollButton = document.getElementById("button-autoscroll");

    requestList.addEventListener("scroll", e => {
      let wasScrolledUp = requestList.scrollTop < requestList.scrollTopMax;
      let activateAutoscroll = !wasScrolledUp;

      ui.setButtonState(autoScrollButton, activateAutoscroll);
      window.tracer.setAutoscroll(activateAutoscroll);
    });
  },

  initContentSplitter: function() {
    let controlTop = document.getElementById("request-list");
    let controlBottom = document.getElementById("request-info-content");
    let dragger = document.getElementById("dragger");
    Splitter.setup(controlTop, controlBottom, dragger);
  },

  hideDialogs: () => {
    document.querySelectorAll(".modal").forEach(dialog => dialog.style.visibility = "hidden");
  },

  resizeDialogs: function() {
    let iframes = document.querySelectorAll("iframe");
    iframes.forEach(iframe => {
      iframe.width  = iframe.contentWindow.document.body.scrollWidth;
      iframe.height = iframe.contentWindow.document.body.scrollHeight;
    });
  },

  highlightContent: () => {
    const getSyntaxHighlightingClass = tab => {
      let tabName = tab ? tab.href.split('#')[1] : "n/a";
      if (tabName === "HTTP" || tabName === "Parameters") {
        return "HTTP";
      } else {
        return "XML";
      }
    };

    const removeSyntaxHighlightingClasses = block => {
      const syntaxHighlightingClasses = [ "HTTP", "XML" ];
      syntaxHighlightingClasses.forEach(c => block.classList.remove(c));
    };

    let content = document.querySelector("#request-info-content");
    removeSyntaxHighlightingClasses(content);

    let selectedTab = document.querySelector(".tab.selected");
    let syntaxHighlightingClass = getSyntaxHighlightingClass(selectedTab);
    content.classList.add(syntaxHighlightingClass);
    hljs.highlightBlock(content);
  },

  enableSyntaxHighlighting: function() {
    let tabBox = document.querySelector("#request-info-tabbox");
    tabBox.addEventListener("click", ui.highlightContent);

    let requestList = document.querySelector("#request-list");
    requestList.addEventListener("click", ui.highlightContent);
  }
}<commit_msg>The Autoscroll-button scrolls the request list down to the bottom, when re-activated.<commit_after>window.addEventListener("load", function(e) {
  // initially setup the ui
  ui.resizeElements();
  ui.resizeDialogs();
  ui.bindButtons();
  ui.bindKeys();
  ui.bindScrollRequestList();
  ui.initContentSplitter();
  ui.enableSyntaxHighlighting();

  // attach resize event
  this.addEventListener("resize", ui.resizeElements);

  // initialize trace listener
  SAMLTrace.TraceWindow.init();
}, true);

ui = {
  resizeElements: function() {
    let reservedHeight =
        document.getElementById("header").clientHeight +
        document.getElementById("dragger").clientHeight +
        document.getElementById("request-info-tabbox").clientHeight +
        document.getElementById("statuspanel").clientHeight;

    let elementTop = document.getElementById("request-list");
    let elementBottom = document.getElementById("request-info-content");
    let controlHeightSum = elementTop.clientHeight + elementBottom.clientHeight;

    let remainingHeight = window.innerHeight - reservedHeight;
    let ratioTop = (elementTop.clientHeight / controlHeightSum) * remainingHeight;
    let ratioBottom = (elementBottom.clientHeight / controlHeightSum) * remainingHeight;

    const getPaddingHeight = element => {
      let style = window.getComputedStyle(element);
      return parseInt(style.paddingTop) + parseInt(style.paddingBottom);
    };

    elementTop.style.height = (ratioTop - getPaddingHeight(elementTop)) + "px";
    elementBottom.style.height = (ratioBottom - getPaddingHeight(elementBottom)) + "px";
  },

  toggleButtonState: function(button) {
    let isActive = button.classList.contains("active");
    let newState = !isActive;
    ui.setButtonState(button, newState)
    return newState;
  },

  setButtonState: function(button, newState) {
    newState ? button.classList.add("active") : button.classList.remove("active");
  },

  bindButtons: function() {
    document.getElementById("button-clear").addEventListener("click", () => {
      window.tracer.clearRequests();
    }, true);
    document.getElementById("button-pause").addEventListener("click", e => {
      let newState = ui.toggleButtonState(e.target);
      window.tracer.setPauseTracing(newState);
    }, true);
    document.getElementById("button-autoscroll").addEventListener("click", e => {
      let newState = ui.toggleButtonState(e.target);
      window.tracer.setAutoscroll(newState);
      if (newState === true) {
        let requestList = document.getElementById("request-list");
        requestList.scrollTop = requestList.scrollTopMax;
      }
    }, true);
    document.getElementById("button-filter").addEventListener("click", e => {
      let newState = ui.toggleButtonState(e.target);
      window.tracer.setFilterResources(newState);
      let hidableRows = document.getElementsByClassName("list-row isRessource");
      if (newState) {
        Array.from(hidableRows).forEach(row => row.classList.remove("displayAnyway"));
      } else {
        Array.from(hidableRows).forEach(row => row.classList.add("displayAnyway"));
      }
    }, true);
    document.getElementById("button-export-list").addEventListener("click", () => {
      let exportDialog = document.getElementById("exportDialog");
      exportDialog.style.visibility = "visible";
      let isFlteringActive = document.getElementById("button-filter").classList.contains("active");
      let exportDialogContent = document.getElementById("exportDialogContent");
      exportDialogContent.contentWindow.ui.setupContent(window.tracer.requests, window.tracer.httpRequests, isFlteringActive);
    }, true);
    document.getElementById("button-import-list").addEventListener("click", () => {
      let importDialog = document.getElementById("importDialog");
      importDialog.style.visibility = "visible";
      let importDialogContent = document.getElementById("importDialogContent");
      importDialogContent.contentWindow.ui.setupContent();
    }, true);

    let modalCloseButtons = document.querySelectorAll(".modal-close");
    modalCloseButtons.forEach(button => button.addEventListener("click", ui.hideDialogs, true));
  },

  bindKeys: function() {
    const closeDialogs = e => {
      // close dialogs when ESC is pressed
      if (e.key === "Escape") {
        ui.hideDialogs();
      }
    };

    const selectRequestInfoContent = e => {
      // override CTRL+A to just select the request info content
      if ((e.ctrlKey || e.metaKey) && e.key === "a") {
        let element = document.getElementById("request-info-content");
        let range = document.createRange();
        range.selectNode(element);
        window.getSelection().addRange(range);
        e.preventDefault();
      }
    };

    const selectRowOnKeybeardEvent = e => {
      // select another request, when ArrowUp, ArrowDown, PageUp, PageDown, Home or End are pressed
      let requestList = document.getElementById("request-list");
      ScrollableList.selectRowOnKeybeardEvent(e, requestList, newElement => {
        window.tracer.selectItemInList(newElement, requestList);
        window.tracer.showRequest(newElement.requestItem);
        ui.highlightContent();
      });
    };

    const togglePauseTracing = e => {
      // pauses or resumes request tracing when the pause key is pressed
      if (e.key === "Pause") {
        let button = document.getElementById("button-pause");
        let newState = ui.toggleButtonState(button);
        window.tracer.setPauseTracing(newState);
      }
    };

    let iframes = document.querySelectorAll("iframe");
    iframes.forEach(iframe => iframe.contentWindow.document.addEventListener("keydown", closeDialogs));
    document.addEventListener("keydown", closeDialogs);
    document.addEventListener("keydown", selectRequestInfoContent);
    document.addEventListener("keydown", selectRowOnKeybeardEvent);
    document.addEventListener("keydown", togglePauseTracing);
  },

  bindScrollRequestList: function() {
    let requestList = document.getElementById("request-list");
    let autoScrollButton = document.getElementById("button-autoscroll");

    requestList.addEventListener("scroll", e => {
      let wasScrolledUp = requestList.scrollTop < requestList.scrollTopMax;
      let activateAutoscroll = !wasScrolledUp;

      ui.setButtonState(autoScrollButton, activateAutoscroll);
      window.tracer.setAutoscroll(activateAutoscroll);
    });
  },

  initContentSplitter: function() {
    let controlTop = document.getElementById("request-list");
    let controlBottom = document.getElementById("request-info-content");
    let dragger = document.getElementById("dragger");
    Splitter.setup(controlTop, controlBottom, dragger);
  },

  hideDialogs: () => {
    document.querySelectorAll(".modal").forEach(dialog => dialog.style.visibility = "hidden");
  },

  resizeDialogs: function() {
    let iframes = document.querySelectorAll("iframe");
    iframes.forEach(iframe => {
      iframe.width  = iframe.contentWindow.document.body.scrollWidth;
      iframe.height = iframe.contentWindow.document.body.scrollHeight;
    });
  },

  highlightContent: () => {
    const getSyntaxHighlightingClass = tab => {
      let tabName = tab ? tab.href.split('#')[1] : "n/a";
      if (tabName === "HTTP" || tabName === "Parameters") {
        return "HTTP";
      } else {
        return "XML";
      }
    };

    const removeSyntaxHighlightingClasses = block => {
      const syntaxHighlightingClasses = [ "HTTP", "XML" ];
      syntaxHighlightingClasses.forEach(c => block.classList.remove(c));
    };

    let content = document.querySelector("#request-info-content");
    removeSyntaxHighlightingClasses(content);

    let selectedTab = document.querySelector(".tab.selected");
    let syntaxHighlightingClass = getSyntaxHighlightingClass(selectedTab);
    content.classList.add(syntaxHighlightingClass);
    hljs.highlightBlock(content);
  },

  enableSyntaxHighlighting: function() {
    let tabBox = document.querySelector("#request-info-tabbox");
    tabBox.addEventListener("click", ui.highlightContent);

    let requestList = document.querySelector("#request-list");
    requestList.addEventListener("click", ui.highlightContent);
  }
}<|endoftext|>