<commit_before>/*
 * Browser Detection
 * � 2010 DevSlide Labs
 *
 * Visit us at: www.devslide.com/labs
 */

var notSupportedBrowsers = [{'os': 'Any', 'browser': 'MSIE', 'version': 8}];
var displayPoweredBy = false;
var noticeLang = 'professional';
var noticeLangCustom = null;
var supportedBrowsers = [];

var BrowserDetection = {
	init: function(){
		if(notSupportedBrowsers == null || notSupportedBrowsers.length < 1){
			notSupportedBrowsers = this.defaultNotSupportedBrowsers;
		}

		this.detectBrowser();
		this.detectOS();

		if(this.browser == '' || this.browser == 'Unknown' || this.os == '' ||
		   this.os == 'Unknown' || this.browserVersion == '' || this.browserVersion == 0)
		{
			return;
		}

		// Check if this is old browser
		var oldBrowser = false;
		for(var i = 0; i < notSupportedBrowsers.length; i++){
			if(notSupportedBrowsers[i].os == 'Any' || notSupportedBrowsers[i].os == this.os){
				if(notSupportedBrowsers[i].browser == 'Any' || notSupportedBrowsers[i].browser == this.browser){
					if(notSupportedBrowsers[i].version == "Any" || this.browserVersion <= parseFloat(notSupportedBrowsers[i].version)){
						oldBrowser = true;
						break;
					}
				}
			}
		}

		if(oldBrowser){
			this.displayNotice();
		}
	},

	getEl: function(id){ return window.document.getElementById(id); },
	getElSize: function(id){
		var el = this.getEl(id);
		if(el == null){ return null; }
		return { 'width': parseInt(el.offsetWidth), 'height': parseInt(el.offsetHeight) };
	},
	getWindowSize: function(){
		if(typeof window.innerWidth != 'undefined'){
			return {'width': parseInt(window.innerWidth), 'height': parseInt(window.innerHeight)};
		} else {
			if(window.document.documentElement.clientWidth != 0){
				return {'width': parseInt(window.document.documentElement.clientWidth), 'height': parseInt(window.document.documentElement.clientHeight)};
			} else {
				return {'width': parseInt(window.document.body.clientWidth), 'height': parseInt(window.document.body.clientHeight)};
			}
		}
	},
	positionNotice: function(){
		var noticeSize = this.getElSize('browser-detection');
		var windowSize = this.getWindowSize();
		var noticeEl = this.getEl('browser-detection');

		if(noticeEl == null || noticeSize == null || windowSize == null || !windowSize.width || !windowSize.height){ return; }
		noticeEl.style.left = (windowSize.width - noticeSize.width) / 2 + "px";

		noticeEl.style.top = "10px";
		this.noticeHeight = noticeSize.height;
	},

	displayNotice: function(){
		if(this.readCookie('bdnotice') == 1){
			return;
		}

		this.writeNoticeCode();
		this.positionNotice();

		var el = this;
		window.onresize = function(){ el.positionNotice(); };
		if(this.browser == "MSIE" && this.browserVersion < 7){
			window.onscroll = function(){ el.positionNotice(); };
		}

		this.getEl('browser-detection-close').onclick = function(){ el.remindMe(false); };
		this.getEl('browser-detection-remind-later').onclick = function(){ el.remindMe(false); };
		this.getEl('browser-detection-never-remind').onclick = function(){ el.remindMe(true); };
	},

	remindMe: function(never){
		this.writeCookie('bdnotice', 1, never == true ? 365 : 7);
		this.getEl('browser-detection').style.display = 'none';
		this.getEl('black_overlay').style.display = 'none';
	},

	writeCookie: function(name, value, days){
		var expiration = "";
		if(parseInt(days) > 0){
			var date = new Date();
			date.setTime(date.getTime() + parseInt(days) * 24 * 60 * 60 * 1000);
			expiration = '; expires=' + date.toGMTString();
		}

		document.cookie = name + '=' + value + expiration + '; path=/';
	},

	readCookie: function(name){
		if(!document.cookie){ return ''; }

		var searchName = name + '=';
		var data = document.cookie.split(';');

		for(var i = 0; i < data.length; i++){
			while(data[i].charAt(0) == ' '){
				data[i] = data[i].substring(1, data[i].length);
			}

			if(data[i].indexOf(searchName) == 0){
				return data[i].substring(searchName.length, data[i].length);
			}
		}

		return '';
	},

	writeNoticeCode: function(){
		var title = '';
		var notice = '';
		var selectBrowser = '';
		var remindMeLater = '';
		var neverRemindAgain = '';

		var browsersList = null;
		var code = '

Close';

		if(noticeLang == 'custom' && noticeLangCustom != null){
			title = noticeLangCustom.title;
			notice = noticeLangCustom.notice;
			selectBrowser = noticeLangCustom.selectBrowser;
			remindMeLater = noticeLangCustom.remindMeLater;
			neverRemindAgain = noticeLangCustom.neverRemindAgain;
		} else {
			var noticeTextObj = null;
			eval('noticeTextObj = this.noticeText.' + noticeLang + ';');

			if(!noticeTextObj){
				noticeTextObj = this.noticeText.professional;
			}

			title = noticeTextObj.title;
			notice = noticeTextObj.notice;
			selectBrowser = noticeTextObj.selectBrowser;
			remindMeLater = noticeTextObj.remindMeLater;
			neverRemindAgain = noticeTextObj.neverRemindAgain;
		}

		notice = notice.replace("\n", '

');
		notice = notice.replace("{browser_name}", (this.browser + " " + this.browserVersion));

		code += '
' + title + '

' + notice + '

' + selectBrowser + '
';

		if(supportedBrowsers.length > 0){
			browsersList = supportedBrowsers;
		} else {
			browsersList = this.supportedBrowsers;
		}

		code += '
';
		for(var i = 0; i < browsersList.length; i++){
			code += '
' + browsersList[i].name + '
';
		}
		code += '
';

		if(displayPoweredBy){
			code += '
Powered by DevSlide Labs
';
		}

		code += '
';
		code += '
<button id="browser-detection-remind-later" type="button">' + remindMeLater + '</button>
';
		code += '
<button id="browser-detection-never-remind" type="button">' + neverRemindAgain + '</button>
';
		code += '
';
		code += '
';
		window.document.body.innerHTML += code;
	},

	detectBrowser: function(){
		this.browser = '';
		this.browserVersion = 0;

		if(/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Opera';
		} else if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
			this.browser = 'MSIE';
		} else if(/Navigator[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Netscape';
		} else if(/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Chrome';
		} else if(/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Safari';
			/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
			this.browserVersion = new Number(RegExp.$1);
		} else if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Firefox';
		}

		if(this.browser == ''){
			this.browser = 'Unknown';
		} else if(this.browserVersion == 0) {
			this.browserVersion = parseFloat(new Number(RegExp.$1));
		}
	},

	// Detect operation system
	detectOS: function(){
		for(var i = 0; i < this.operatingSystems.length; i++){
			if(this.operatingSystems[i].searchString.indexOf(this.operatingSystems[i].subStr) != -1){
				this.os = this.operatingSystems[i].name;
				return;
			}
		}

		this.os = "Unknown";
	},

	//	Variables
	noticeHeight: 0,
	browser: '',
	os: '',
	browserVersion: '',
	supportedBrowsers: [
	       { 'cssClass': 'firefox', 'name': 'Mozilla Firefox', 'downloadUrl': 'http://www.getfirefox.com/' },
	       { 'cssClass': 'chrome', 'name': 'Google Chrome', 'downloadUrl': 'http://www.google.com/chrome/' },
	       { 'cssClass': 'msie', 'name': 'Internet Explorer', 'downloadUrl': 'http://www.getie.com/' },
	       { 'cssClass': 'opera', 'name': 'Opera', 'downloadUrl': 'http://www.opera.com/' },
	       { 'cssClass': 'safari', 'name': 'Apple Safari', 'downloadUrl': 'http://www.apple.com/safari/' }
	],
	operatingSystems: [
           { 'searchString': navigator.platform, 'name': 'Windows', 'subStr': 'Win' },
           { 'searchString': navigator.platform, 'name': 'Mac', 'subStr': 'Mac' },
           { 'searchString': navigator.platform, 'name': 'Linux', 'subStr': 'Linux' },
           { 'searchString': navigator.userAgent, 'name': 'iPhone', 'subStr': 'iPhone/iPod' }
	],
	defaultNotSupportedBrowsers: [{'os': 'Any', 'browser': 'MSIE', 'version': 6}],
	noticeText: {
    	   'professional': { "title": "Outdated Browser Detected", "notice": "iceScrum has detected that you are using an outdated browser. Using your current browser will prevent you from accessing features on iceScrum. An upgrade is not required, but is strongly recommend to improve your browsing experience on iceScrum.", "selectBrowser": "Use the links below to download a new browser or upgrade your existing browser.", "remindMeLater": "Remind me later", "neverRemindAgain": "No, don't remind me again" }
    }
};

window.onload = function(){
	BrowserDetection.init();
};<commit_msg>T556-0 Warning IE<commit_after>/*
 * Browser Detection
 * 2010 DevSlide Labs
 *
 * Visit us at: www.devslide.com/labs
 */

var notSupportedBrowsers = [{'os': 'Any', 'browser': 'MSIE', 'version': 8}];
var displayPoweredBy = false;
var noticeLang = 'professional';
var noticeLangCustom = null;
var supportedBrowsers = [];

var BrowserDetection = {
	init: function(){
		if(notSupportedBrowsers == null || notSupportedBrowsers.length < 1){
			notSupportedBrowsers = this.defaultNotSupportedBrowsers;
		}

		this.detectBrowser();
		this.detectOS();

		if(this.browser == '' || this.browser == 'Unknown' || this.os == '' ||
		   this.os == 'Unknown' || this.browserVersion == '' || this.browserVersion == 0)
		{
			return;
		}

		// Check if this is old browser
		var oldBrowser = false;
		for(var i = 0; i < notSupportedBrowsers.length; i++){
			if(notSupportedBrowsers[i].os == 'Any' || notSupportedBrowsers[i].os == this.os){
				if(notSupportedBrowsers[i].browser == 'Any' || notSupportedBrowsers[i].browser == this.browser){
					if(notSupportedBrowsers[i].version == "Any" || this.browserVersion <= parseFloat(notSupportedBrowsers[i].version)){
						oldBrowser = true;
						break;
					}
				}
			}
		}

		if(oldBrowser){
			this.displayNotice();
		}
	},

	getEl: function(id){ return window.document.getElementById(id); },
	getElSize: function(id){
		var el = this.getEl(id);
		if(el == null){ return null; }
		return { 'width': parseInt(el.offsetWidth), 'height': parseInt(el.offsetHeight) };
	},
	getWindowSize: function(){
		if(typeof window.innerWidth != 'undefined'){
			return {'width': parseInt(window.innerWidth), 'height': parseInt(window.innerHeight)};
		} else {
			if(window.document.documentElement.clientWidth != 0){
				return {'width': parseInt(window.document.documentElement.clientWidth), 'height': parseInt(window.document.documentElement.clientHeight)};
			} else {
				return {'width': parseInt(window.document.body.clientWidth), 'height': parseInt(window.document.body.clientHeight)};
			}
		}
	},
	positionNotice: function(){
		var noticeSize = this.getElSize('browser-detection');
		var windowSize = this.getWindowSize();
		var noticeEl = this.getEl('browser-detection');

		if(noticeEl == null || noticeSize == null || windowSize == null || !windowSize.width || !windowSize.height){ return; }
		noticeEl.style.left = (windowSize.width - noticeSize.width) / 2 + "px";

		noticeEl.style.top = "10px";
		this.noticeHeight = noticeSize.height;
	},

	displayNotice: function(){
		if(this.readCookie('bdnotice') == 1){
			return;
		}

		this.writeNoticeCode();
		this.positionNotice();

		var el = this;
		window.onresize = function(){ el.positionNotice(); };
		if(this.browser == "MSIE" && this.browserVersion < 7){
			window.onscroll = function(){ el.positionNotice(); };
		}

		this.getEl('browser-detection-close').onclick = function(){ el.remindMe(false); };
		this.getEl('browser-detection-remind-later').onclick = function(){ el.remindMe(false); };
		this.getEl('browser-detection-never-remind').onclick = function(){ el.remindMe(true); };
	},

	remindMe: function(never){
		this.writeCookie('bdnotice', 1, never == true ? 365 : 7);
		this.getEl('browser-detection').style.display = 'none';
		this.getEl('black_overlay').style.display = 'none';
	},

	writeCookie: function(name, value, days){
		var expiration = "";
		if(parseInt(days) > 0){
			var date = new Date();
			date.setTime(date.getTime() + parseInt(days) * 24 * 60 * 60 * 1000);
			expiration = '; expires=' + date.toGMTString();
		}

		document.cookie = name + '=' + value + expiration + '; path=/';
	},

	readCookie: function(name){
		if(!document.cookie){ return ''; }

		var searchName = name + '=';
		var data = document.cookie.split(';');

		for(var i = 0; i < data.length; i++){
			while(data[i].charAt(0) == ' '){
				data[i] = data[i].substring(1, data[i].length);
			}

			if(data[i].indexOf(searchName) == 0){
				return data[i].substring(searchName.length, data[i].length);
			}
		}

		return '';
	},

	writeNoticeCode: function(){
		var title = '';
		var notice = '';
		var selectBrowser = '';
		var remindMeLater = '';
		var neverRemindAgain = '';

		var browsersList = null;
		var code = '

Close';

		if(noticeLang == 'custom' && noticeLangCustom != null){
			title = noticeLangCustom.title;
			notice = noticeLangCustom.notice;
			selectBrowser = noticeLangCustom.selectBrowser;
			remindMeLater = noticeLangCustom.remindMeLater;
			neverRemindAgain = noticeLangCustom.neverRemindAgain;
		} else {
			var noticeTextObj = null;
			eval('noticeTextObj = this.noticeText.' + noticeLang + ';');

			if(!noticeTextObj){
				noticeTextObj = this.noticeText.professional;
			}

			title = noticeTextObj.title;
			notice = noticeTextObj.notice;
			selectBrowser = noticeTextObj.selectBrowser;
			remindMeLater = noticeTextObj.remindMeLater;
			neverRemindAgain = noticeTextObj.neverRemindAgain;
		}

		notice = notice.replace("\n", '

');
		notice = notice.replace("{browser_name}", (this.browser + " " + this.browserVersion));

		code += '
' + title + '

' + notice + '

' + selectBrowser + '
';

		if(supportedBrowsers.length > 0){
			browsersList = supportedBrowsers;
		} else {
			browsersList = this.supportedBrowsers;
		}

		code += '
';
		for(var i = 0; i < browsersList.length; i++){
			code += '
' + browsersList[i].name + '
';
		}
		code += '
';

		if(displayPoweredBy){
			code += '
Powered by DevSlide Labs
';
		}

		code += '
';
		code += '
<button id="browser-detection-remind-later" type="button">' + remindMeLater + '</button>
';
		code += '
<button id="browser-detection-never-remind" type="button">' + neverRemindAgain + '</button>
';
		code += '
';
		code += '
';
		window.document.body.innerHTML += code;
	},

	detectBrowser: function(){
		this.browser = '';
		this.browserVersion = 0;

		if(/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Opera';
		} else if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
			this.browser = 'MSIE';
		} else if(/Navigator[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Netscape';
		} else if(/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Chrome';
		} else if(/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Safari';
			/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
			this.browserVersion = new Number(RegExp.$1);
		} else if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
			this.browser = 'Firefox';
		}

		if(this.browser == ''){
			this.browser = 'Unknown';
		} else if(this.browserVersion == 0) {
			this.browserVersion = parseFloat(new Number(RegExp.$1));
		}
	},

	// Detect operation system
	detectOS: function(){
		for(var i = 0; i < this.operatingSystems.length; i++){
			if(this.operatingSystems[i].searchString.indexOf(this.operatingSystems[i].subStr) != -1){
				this.os = this.operatingSystems[i].name;
				return;
			}
		}

		this.os = "Unknown";
	},

	//	Variables
	noticeHeight: 0,
	browser: '',
	os: '',
	browserVersion: '',
	supportedBrowsers: [
	       { 'cssClass': 'firefox', 'name': 'Mozilla Firefox', 'downloadUrl': 'http://www.getfirefox.com/' },
	       { 'cssClass': 'chrome', 'name': 'Google Chrome', 'downloadUrl': 'http://www.google.com/chrome/' },
	       { 'cssClass': 'msie', 'name': 'Internet Explorer', 'downloadUrl': 'http://www.getie.com/' },
	       { 'cssClass': 'opera', 'name': 'Opera', 'downloadUrl': 'http://www.opera.com/' },
	       { 'cssClass': 'safari', 'name': 'Apple Safari', 'downloadUrl': 'http://www.apple.com/safari/' }
	],
	operatingSystems: [
           { 'searchString': navigator.platform, 'name': 'Windows', 'subStr': 'Win' },
           { 'searchString': navigator.platform, 'name': 'Mac', 'subStr': 'Mac' },
           { 'searchString': navigator.platform, 'name': 'Linux', 'subStr': 'Linux' },
           { 'searchString': navigator.userAgent, 'name': 'iPhone', 'subStr': 'iPhone/iPod' }
	],
	defaultNotSupportedBrowsers: [{'os': 'Any', 'browser': 'MSIE', 'version': 6}],
	noticeText: {
    	   'professional': { "title": "Outdated Browser Detected", "notice": "iceScrum has detected that you are using an outdated browser. Using your current browser will prevent you from accessing features on iceScrum. An upgrade is not required, but is strongly recommend to improve your browsing experience on iceScrum.", "selectBrowser": "Use the links below to download a new browser or upgrade your existing browser.", "remindMeLater": "Remind me later", "neverRemindAgain": "No, don't remind me again" }
    }
};

window.onload = function(){
	BrowserDetection.init();
};<|endoftext|>


<commit_before>const {createSauceLabsLauncher} = require('@web/test-runner-saucelabs');
const {compileJSPlugin} = require('./compile-js-plugin.js');

const sauceLabsLauncher = createSauceLabsLauncher(
  {
    user: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
  },
  {
    name: 'Polyfills tests',
    build: process.env.GITHUB_REF ?? 'local',
  }
);

// wct -s 'windows 10/microsoftedge@17' -s 'windows 10/microsoftedge@15' -s 'windows 8.1/internet explorer@11' -s 'macos 10.13/safari@12' -s 'macos 10.13/safari@11' -s 'os x 10.11/safari@10' -s 'os x 10.11/safari@9' -s 'Linux/chrome@41'

const defaultBrowsers = [
  sauceLabsLauncher({
    platformName: 'windows 10',
    browserName: 'microsoftedge',
    browserVersion: '17',
  }),
  sauceLabsLauncher({
    platformName: 'windows 10',
    browserName: 'microsoftedge',
    browserVersion: '15',
  }),
  sauceLabsLauncher({
    platformName: 'windows 8.1',
    browserName: 'internet explorer',
    browserVersion: '11',
  }),
  sauceLabsLauncher({
    platformName: 'macos 10.13',
    browserName: 'safari',
    browserVersion: '12',
  }),
  sauceLabsLauncher({
    platformName: 'macos 10.13',
    browserName: 'safari',
    browserVersion: '11',
  }),
  sauceLabsLauncher({
    platformName: 'os x 10.11',
    browserName: 'safari',
    browserVersion: '10',
  }),
  sauceLabsLauncher({
    platformName: 'os x 10.11',
    browserName: 'safari',
    browserVersion: '9',
  }),
  sauceLabsLauncher({
    platformName: 'Linux',
    browserName: 'chrome',
    browserVersion: '41',
  }),
];

const envBrowsers = process.env.BROWSERS?.split(',').map((product) => {
  const [platformName, rest] = product.split('/');
  const [browserName, browserVersion] = rest.split('@');
  return sauceLabsLauncher({
    platformName,
    browserName,
    browserVersion,
  });
});

const browsers = envBrowsers ?? defaultBrowsers;

module.exports = {
  files: [
    'packages/scoped-custom-element-registry/test/**/*.test.(js|html)',
    'packages/tests/custom-elements/wtr/**/*.test.(js|html)',
  ],
  nodeResolve: true,
  concurrency: 1,
  concurrentBrowsers: 1,
  browsers,
  plugins: [compileJSPlugin()],
};
<commit_msg>Remove the `scoped-custom-element-registry` polyfill tests from the Sauce tests.<commit_after>const {createSauceLabsLauncher} = require('@web/test-runner-saucelabs');
const {compileJSPlugin} = require('./compile-js-plugin.js');

const sauceLabsLauncher = createSauceLabsLauncher(
  {
    user: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
  },
  {
    name: 'Polyfills tests',
    build: process.env.GITHUB_REF ?? 'local',
  }
);

// wct -s 'windows 10/microsoftedge@17' -s 'windows 10/microsoftedge@15' -s 'windows 8.1/internet explorer@11' -s 'macos 10.13/safari@12' -s 'macos 10.13/safari@11' -s 'os x 10.11/safari@10' -s 'os x 10.11/safari@9' -s 'Linux/chrome@41'

const defaultBrowsers = [
  sauceLabsLauncher({
    platformName: 'windows 10',
    browserName: 'microsoftedge',
    browserVersion: '17',
  }),
  sauceLabsLauncher({
    platformName: 'windows 10',
    browserName: 'microsoftedge',
    browserVersion: '15',
  }),
  sauceLabsLauncher({
    platformName: 'windows 8.1',
    browserName: 'internet explorer',
    browserVersion: '11',
  }),
  sauceLabsLauncher({
    platformName: 'macos 10.13',
    browserName: 'safari',
    browserVersion: '12',
  }),
  sauceLabsLauncher({
    platformName: 'macos 10.13',
    browserName: 'safari',
    browserVersion: '11',
  }),
  sauceLabsLauncher({
    platformName: 'os x 10.11',
    browserName: 'safari',
    browserVersion: '10',
  }),
  sauceLabsLauncher({
    platformName: 'os x 10.11',
    browserName: 'safari',
    browserVersion: '9',
  }),
  sauceLabsLauncher({
    platformName: 'Linux',
    browserName: 'chrome',
    browserVersion: '41',
  }),
];

const envBrowsers = process.env.BROWSERS?.split(',').map((product) => {
  const [platformName, rest] = product.split('/');
  const [browserName, browserVersion] = rest.split('@');
  return sauceLabsLauncher({
    platformName,
    browserName,
    browserVersion,
  });
});

const browsers = envBrowsers ?? defaultBrowsers;

module.exports = {
  files: [
    //'packages/scoped-custom-element-registry/test/**/*.test.(js|html)',
    'packages/tests/custom-elements/wtr/**/*.test.(js|html)',
  ],
  nodeResolve: true,
  concurrency: 1,
  concurrentBrowsers: 1,
  browsers,
  plugins: [compileJSPlugin()],
};
<|endoftext|>


<commit_before>(function() {

var app = angular.module('optc');

var directives = { };

/*****************
 * UI directives *
 *****************/

directives.autoFocus = function($timeout) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function(){ element[0].focus(); });
		}
	};
};

directives.decorateSlot = function() {
    return {
        restrict: 'A',
        scope: { uid: '=', udata: '=' },
        link: function(scope, element, attrs) {
            var update = function() {
                var target = element[0];
                if (!scope.uid && !scope.udata) {
                    target.style.backgroundImage = null;
                    target.removeAttribute('title');
                } else {
                    target.style.backgroundImage = 'url(' + Utils.getThumbnailUrl(scope.uid) + ')';
                    if (attrs.decorateSlot.indexOf('notitle') == -1)
                        target.setAttribute('title', Utils.getThumbnailTitle(scope.udata || scope.uid));
                }
            };
            scope.$watch('uid',update);
            scope.$watch('udata',update);
        }
    };
};

directives.expandableDamage = function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.detailsVisible = false;
            element.click(function(e) {
                if (e.which != 1 || e.ctrlKey) return;
                element.toggleClass('details');
                if (!scope.detailsVisible) {
                    element[0].style.zIndex = 5;
                    setTimeout(function() { scope.detailsVisible = true; scope.$apply();
                    },500);
                } else {
                    scope.detailsVisible = false;
                    scope.$apply();
                    setTimeout(function() { element[0].style.zIndex = 4; },500);
                }
            });
        },
    };
};

directives.detailPane = function() {
    return {
        restrict: 'A',
        templateUrl: 'views/details.html',
        scope: true,
        link: function(scope, element, attrs) {
            var modifiers = [ 'Miss', 'Good', 'Great', 'Perfect' ];
            scope.modifyDamage = function(e,n) {
                if (e.which != 2 && (e.which != 1 || !e.ctrlKey)) return;
                var custom = $.extend([ ],scope.numbers[scope.type].hitModifiers);
                custom[n] = modifiers[(modifiers.indexOf(custom[n])+1)%4];
                scope.tdata.customHitModifiers = custom;
                e.preventDefault();
                e.stopPropagation();
                return false;
            };
        }
    };
};

directives.attachPicker = function() {
    return {
        restrict: 'A',
        scope: true,
        controller: function($scope, $state) { $scope.$state = $state; },
        link: function(scope, element, attrs) {
            element.click(function(e) {
                if (e.which != 1 || e.ctrlKey) return;
                if ($(e.target).parent().hasClass('slide') || Utils.isClickOnOrb(e,e.target)) return;
                scope.$state.go('.pick',{ slot: scope.slot });
            });
        }
    };
};

directives.defenseOnClick = function() {
    return {
        restrict: 'A',
        controller: function($scope, $state) { $scope.go = $state.go; },
        link: function(scope, element, attrs) {
            element.click(function(e) {
                if (e.which == 2 || (e.which == 1 && e.ctrlKey))
                    scope.go('.defense');
                else if (e.which == 1)
                    element.find('input').focus();
            });
        }
    };
};

directives.shipManager = function() {
    return {
        restrict: 'A',
        scope: true,
        controller: function($scope, $state) { $scope.go = $state.go; },
        link: function(scope, element, attrs) {
            var background = element.find('#ship-background')[0];
            background.style.width = Math.round(scope.data.ship.level * 10)  + '%';
            scope.level = scope.data.ship.level;
            element.click(function(e) {
                if (e.which == 2 || (e.which == 1 && e.ctrlKey))
                    scope.go('.ship');
            });
            var updateBackground = function(perc) {
                perc = Math.min(1,perc);
                background.style.width = Math.min(Math.round(perc * 100),100)  + '%';
                background.style.background =
                    'rgb(' + [ Math.floor(240-148*perc), Math.floor(173+11*perc), Math.floor(78+14*perc) ].join(',') + ')';
            };
            var mouseup = function(e) {
                $(document).off('mouseup');
                $(document).off('mousemove');
                scope.data.ship.level = scope.level;
                scope.$apply();
                updateBackground(scope.level / 10);
            };
            var mousemove = function(e) {
                var level = Math.max(1,Math.min(Math.round(e.clientX / 230 * 10),10));
                if (level == scope.data.ship.level) return;
                e.preventDefault();
                e.stopPropagation();
                scope.level = level;
                scope.$apply();
                updateBackground(e.clientX / 230);
            };
            element.mousedown(function(e) {
                if (e.which != 1 || e.ctrlKey) return;
                var level = Math.round(e.clientX / 230 * 10);
                $(document).mouseup(mouseup);
                $(document).mousemove(mousemove);
                scope.level = level;
                scope.$apply();
                updateBackground(e.clientX / 230);
            });
            updateBackground(scope.level / 10);
        }
    };
};

/************************
 * Component directives *
 ************************/

directives.mainController = function() {
    return {
        restrict: 'A',
        controller: 'MainCtrl'
    };
};

directives.sidebar = function() {
    return {
        restrict: 'E',
        templateUrl: 'views/sidebar.html',
        replace: true
    };
};

directives.cruncher = function() {
    return {
        restrict: 'E',
        controller: 'CruncherCtrl',
        templateUrl: 'views/results.html',
        replace: true
    };
};

directives.units = function() {
    return {
        restrict: 'E',
        templateUrl: 'views/units.html',
        replace: true,
    };
};

directives.slot = function() {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'views/fragments/slot.html',
        scope: true,
        link: function(scope, element, attrs) {
            scope.slot = element.index();
        }
    };
};

directives.hpBar = function() {
    return {
        rstrict: 'A',
        replace: true,
        template: '

' +
            '
{{ hp.current | number }} HP ({{ hp.perc || number }}%)

',
        link: function(scope, element, attrs) {
            scope.hp = { current: scope.data.hp.current, perc: scope.data.hp.perc };
            var slider = element.find('#hpSlider').noUiSlider({
                start: [ scope.data.hp.current ],
                range: { min: [ 1 ], max: [ scope.data.hp.max || 1 ] },
                connect: 'lower'
            });
            var update = function(event,value) {
                scope.hp.current = Math.floor(value);
                scope.hp.perc = Math.round(scope.hp.current / scope.data.hp.max * 10000) / 100;
                currentHP =scope.data.hp.current;
                if (event === null) slider.val(value);
                else if (event.type == 'change') {
                    scope.data.hp.current = scope.hp.current;
                    scope.data.hp.perc = scope.hp.perc;
                }
                if (!scope.$$phase) scope.$apply();
            };
            slider.on({ change: update, slide: update });
            scope.$watch('data.hp',function(hp) {
                slider.noUiSlider({ range: { min: [ 1 ], max: [ scope.data.hp.max || 1 ] } },true);
                var newHP = Math.floor(hp.perc * hp.max / 100);
                update(null,newHP);
            },true);
        }
    };
};

directives.levelLabel = function() {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        template: '
Lv. {{ data.team[slot].level }}<input ng-show="editorVisible" ng-model="level"></input>
',
        link: function(scope, element, attrs) {
            scope.level = scope.data.team[scope.slot].level;
            var input = element.find('input');
            element.click(function(e) {
                scope.level = '';
                if (e.which == 1 && !e.ctrlKey) {
                    if (scope.options.slidersEnabled) $('.unit').eq(scope.slot).addClass('slide');
                    else scope.editorVisible = true;
                } else if (e.which == 2 || (e.which == 1 && e.ctrlKey))
                    scope.data.team[scope.slot].level = scope.data.team[scope.slot].unit.maxLevel;
                scope.$apply();
                if (scope.editorVisible) input.focus();
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
            var update = function(e) {
                if (e.type == 'keyup' && e.which != 13) return;
                var level = parseInt(scope.level,10);
                scope.editorVisible = false;
                if (isNaN(level)) return;
                scope.data.team[scope.slot].level = Math.min(Math.max(1,level),scope.data.team[scope.slot].unit.maxLevel);
                scope.$apply();
            };
            input.focusout(update);
            input.keyup(update);
        }
    };
};

directives.levelSlider = function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<input disabled class="unitSlider"></input>',
        link: function(scope, element, attrs) {
            var currentValue = 0;
            var onRelease = function(value) {
                if (!value || value <= 0 || currentValue == value) return;
                currentValue = value;
                scope.data.team[scope.slot].level = value;
                scope.$apply();
            };
            var update = function(value) {
                if (!value || value <= 0 || currentValue == value) return;
                currentValue = Math.min(value,scope.data.team[scope.slot].unit ? scope.data.team[scope.slot].unit.maxLevel : 1);
                element.val(currentValue).trigger('change');
            };
            var updateMax = function(value) {
                if (!value) value = 1;
                element.trigger('configure',{ max: value });
                if (value < currentValue) update(value);
            };
            var slider = element.knob({
                width: 88,
                height: 88,
                angleOffset: -120,
                angleArc: 240,
                release: onRelease,
                min: 1,
                max: 99
            });
            scope.$watch('data.team[slot].unit.maxLevel',updateMax);
            scope.$watch('data.team[slot].level',update);
            element.parent().on('click touchend',function(e) {
                $('.unit').eq(scope.slot).removeClass('slide');
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
        }
    };
};

directives.unitOrb = function() {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        template: '

',
        link: function(scope, element, attrs) {
            scope.glow = function() {
                var unit = scope.tdata.team[scope.slot];
                if (unit.orb == 1) return 'none';
                if (unit.orb == 2) return scope.data.team[scope.slot].unit.type;
                return Utils.getOppositeType(scope.data.team[scope.slot].unit.type) + ' opposite';
            };
            var onMouseUp = function(e) {
                var unit = scope.data.team[scope.slot], tunit = scope.tdata.team[scope.slot];
                if (!$(e.target).hasClass('unitPortrait')) return;
                if (unit.unit === null || e.target.className == 'unitLevel') return;
                if (e.which == 2 || (e.which == 1 && (e.ctrlKey || Utils.isClickOnOrb(e,e.target)))) {
                    tunit.orb = (tunit.orb == 1 ? 2 : tunit.orb == 2 ? 0.5 : 1);
                    scope.glow();
                    scope.$apply();
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            };
            element.parent().parent().mouseup(onMouseUp);
        },
        controller: function($scope, $timeout) {
            $timeout(function() {
                if ($scope.tdata.team[$scope.slot].orb != 1)
                    $scope.$apply();
            });
        }
    };
};

directives.special = function() {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        template: '

{{data.team[slot].unit.name}}

',
        link: function(scope, element, attrs) {
            scope.slot = element.prevAll('.special').length;
            var isSelected = scope.tdata.team[scope.slot].special;
            var removeType = function() { ['STR','DEX','QCK','PSY','INT'].forEach(function(x) { element.removeClass(x); }); };
            scope.hasSpecial = false;
            scope.$watch('tdata.team[slot].special',function(enabled) {
                removeType();
                if (enabled) element.addClass(scope.data.team[scope.slot].unit.type);
                type = (scope.data.team[scope.slot].unit !== null ? scope.data.team[scope.slot].unit.type : null);
                isSelected = enabled;
            });
            scope.$watch('data.team[slot].unit',function(unit) {
                removeType();
                if (scope.tdata.team[scope.slot].special) element.addClass(unit.type);
                scope.hasSpecial = unit && specials.hasOwnProperty(unit.number+1);
            });
            element.click(function(e) {
                isSelected = !isSelected;
                scope.tdata.team[scope.slot].special = isSelected;
                scope.$apply();
            });
        }
    };
};

/****************************
 * Directive initialization *
 ****************************/

for (var key in directives)
    app.directive(key, directives[key]);

})();
<commit_msg>fixed ship level slider<commit_after>(function() {

var app = angular.module('optc');

var directives = { };

/*****************
 * UI directives *
 *****************/

directives.autoFocus = function($timeout) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function(){ element[0].focus(); });
		}
	};
};

directives.decorateSlot = function() {
    return {
        restrict: 'A',
        scope: { uid: '=', udata: '=' },
        link: function(scope, element, attrs) {
            var update = function() {
                var target = element[0];
                if (!scope.uid && !scope.udata) {
                    target.style.backgroundImage = null;
                    target.removeAttribute('title');
                } else {
                    target.style.backgroundImage = 'url(' + Utils.getThumbnailUrl(scope.uid) + ')';
                    if (attrs.decorateSlot.indexOf('notitle') == -1)
                        target.setAttribute('title', Utils.getThumbnailTitle(scope.udata || scope.uid));
                }
            };
            scope.$watch('uid',update);
            scope.$watch('udata',update);
        }
    };
};

directives.expandableDamage = function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.detailsVisible = false;
            element.click(function(e) {
                if (e.which != 1 || e.ctrlKey) return;
                element.toggleClass('details');
                if (!scope.detailsVisible) {
                    element[0].style.zIndex = 5;
                    setTimeout(function() { scope.detailsVisible = true; scope.$apply();
                    },500);
                } else {
                    scope.detailsVisible = false;
                    scope.$apply();
                    setTimeout(function() { element[0].style.zIndex = 4; },500);
                }
            });
        },
    };
};

directives.detailPane = function() {
    return {
        restrict: 'A',
        templateUrl: 'views/details.html',
        scope: true,
        link: function(scope, element, attrs) {
            var modifiers = [ 'Miss', 'Good', 'Great', 'Perfect' ];
            scope.modifyDamage = function(e,n) {
                if (e.which != 2 && (e.which != 1 || !e.ctrlKey)) return;
                var custom = $.extend([ ],scope.numbers[scope.type].hitModifiers);
                custom[n] = modifiers[(modifiers.indexOf(custom[n])+1)%4];
                scope.tdata.customHitModifiers = custom;
                e.preventDefault();
                e.stopPropagation();
                return false;
            };
        }
    };
};

directives.attachPicker = function() {
    return {
        restrict: 'A',
        scope: true,
        controller: function($scope, $state) { $scope.$state = $state; },
        link: function(scope, element, attrs) {
            element.click(function(e) {
                if (e.which != 1 || e.ctrlKey) return;
                if ($(e.target).parent().hasClass('slide') || Utils.isClickOnOrb(e,e.target)) return;
                scope.$state.go('.pick',{ slot: scope.slot });
            });
        }
    };
};

directives.defenseOnClick = function() {
    return {
        restrict: 'A',
        controller: function($scope, $state) { $scope.go = $state.go; },
        link: function(scope, element, attrs) {
            element.click(function(e) {
                if (e.which == 2 || (e.which == 1 && e.ctrlKey))
                    scope.go('.defense');
                else if (e.which == 1)
                    element.find('input').focus();
            });
        }
    };
};

directives.shipManager = function() {
    return {
        restrict: 'A',
        scope: true,
        controller: function($scope, $state) { $scope.go = $state.go; },
        link: function(scope, element, attrs) {
            var background = element.find('#ship-background')[0];
            background.style.width = Math.round(scope.data.ship.level * 10)  + '%';
            scope.level = scope.data.ship.level;
            element.click(function(e) {
                if (e.which == 2 || (e.which == 1 && e.ctrlKey))
                    scope.go('.ship');
            });
            var updateBackground = function(perc) {
                perc = Math.min(1,perc);
                background.style.width = Math.min(Math.round(perc * 100),100)  + '%';
                background.style.background =
                    'rgb(' + [ Math.floor(240-148*perc), Math.floor(173+11*perc), Math.floor(78+14*perc) ].join(',') + ')';
            };
            var mouseup = function(e) {
                $(document).off('mouseup');
                $(document).off('mousemove');
                scope.data.ship.level = scope.level;
                scope.$apply();
                updateBackground(scope.level / 10);
            };
            var mousemove = function(e) {
                var level = Math.max(1,Math.min(Math.round(e.clientX / 230 * 10),10));
                if (level == scope.data.ship.level) return;
                e.preventDefault();
                e.stopPropagation();
                scope.level = level;
                scope.$apply();
                updateBackground(e.clientX / 230);
            };
            element.mousedown(function(e) {
                if (e.which != 1 || e.ctrlKey) return;
                var level = Math.max(1,Math.round(e.clientX / 230 * 10));
                $(document).mouseup(mouseup);
                $(document).mousemove(mousemove);
                scope.level = level;
                scope.$apply();
                updateBackground(e.clientX / 230);
            });
            updateBackground(scope.level / 10);
        }
    };
};

/************************
 * Component directives *
 ************************/

directives.mainController = function() {
    return {
        restrict: 'A',
        controller: 'MainCtrl'
    };
};

directives.sidebar = function() {
    return {
        restrict: 'E',
        templateUrl: 'views/sidebar.html',
        replace: true
    };
};

directives.cruncher = function() {
    return {
        restrict: 'E',
        controller: 'CruncherCtrl',
        templateUrl: 'views/results.html',
        replace: true
    };
};

directives.units = function() {
    return {
        restrict: 'E',
        templateUrl: 'views/units.html',
        replace: true,
    };
};

directives.slot = function() {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'views/fragments/slot.html',
        scope: true,
        link: function(scope, element, attrs) {
            scope.slot = element.index();
        }
    };
};

directives.hpBar = function() {
    return {
        rstrict: 'A',
        replace: true,
        template: '

' +
            '
{{ hp.current | number }} HP ({{ hp.perc || number }}%)

',
        link: function(scope, element, attrs) {
            scope.hp = { current: scope.data.hp.current, perc: scope.data.hp.perc };
            var slider = element.find('#hpSlider').noUiSlider({
                start: [ scope.data.hp.current ],
                range: { min: [ 1 ], max: [ scope.data.hp.max || 1 ] },
                connect: 'lower'
            });
            var update = function(event,value) {
                scope.hp.current = Math.floor(value);
                scope.hp.perc = Math.round(scope.hp.current / scope.data.hp.max * 10000) / 100;
                currentHP =scope.data.hp.current;
                if (event === null) slider.val(value);
                else if (event.type == 'change') {
                    scope.data.hp.current = scope.hp.current;
                    scope.data.hp.perc = scope.hp.perc;
                }
                if (!scope.$$phase) scope.$apply();
            };
            slider.on({ change: update, slide: update });
            scope.$watch('data.hp',function(hp) {
                slider.noUiSlider({ range: { min: [ 1 ], max: [ scope.data.hp.max || 1 ] } },true);
                var newHP = Math.floor(hp.perc * hp.max / 100);
                update(null,newHP);
            },true);
        }
    };
};

directives.levelLabel = function() {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        template: '
Lv. {{ data.team[slot].level }}<input ng-show="editorVisible" ng-model="level"></input>
',
        link: function(scope, element, attrs) {
            scope.level = scope.data.team[scope.slot].level;
            var input = element.find('input');
            element.click(function(e) {
                scope.level = '';
                if (e.which == 1 && !e.ctrlKey) {
                    if (scope.options.slidersEnabled) $('.unit').eq(scope.slot).addClass('slide');
                    else scope.editorVisible = true;
                } else if (e.which == 2 || (e.which == 1 && e.ctrlKey))
                    scope.data.team[scope.slot].level = scope.data.team[scope.slot].unit.maxLevel;
                scope.$apply();
                if (scope.editorVisible) input.focus();
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
            var update = function(e) {
                if (e.type == 'keyup' && e.which != 13) return;
                var level = parseInt(scope.level,10);
                scope.editorVisible = false;
                if (isNaN(level)) return;
                scope.data.team[scope.slot].level = Math.min(Math.max(1,level),scope.data.team[scope.slot].unit.maxLevel);
                scope.$apply();
            };
            input.focusout(update);
            input.keyup(update);
        }
    };
};

directives.levelSlider = function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<input disabled class="unitSlider"></input>',
        link: function(scope, element, attrs) {
            var currentValue = 0;
            var onRelease = function(value) {
                if (!value || value <= 0 || currentValue == value) return;
                currentValue = value;
                scope.data.team[scope.slot].level = value;
                scope.$apply();
            };
            var update = function(value) {
                if (!value || value <= 0 || currentValue == value) return;
                currentValue = Math.min(value,scope.data.team[scope.slot].unit ? scope.data.team[scope.slot].unit.maxLevel : 1);
                element.val(currentValue).trigger('change');
            };
            var updateMax = function(value) {
                if (!value) value = 1;
                element.trigger('configure',{ max: value });
                if (value < currentValue) update(value);
            };
            var slider = element.knob({
                width: 88,
                height: 88,
                angleOffset: -120,
                angleArc: 240,
                release: onRelease,
                min: 1,
                max: 99
            });
            scope.$watch('data.team[slot].unit.maxLevel',updateMax);
            scope.$watch('data.team[slot].level',update);
            element.parent().on('click touchend',function(e) {
                $('.unit').eq(scope.slot).removeClass('slide');
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
        }
    };
};

directives.unitOrb = function() {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        template: '

',
        link: function(scope, element, attrs) {
            scope.glow = function() {
                var unit = scope.tdata.team[scope.slot];
                if (unit.orb == 1) return 'none';
                if (unit.orb == 2) return scope.data.team[scope.slot].unit.type;
                return Utils.getOppositeType(scope.data.team[scope.slot].unit.type) + ' opposite';
            };
            var onMouseUp = function(e) {
                var unit = scope.data.team[scope.slot], tunit = scope.tdata.team[scope.slot];
                if (!$(e.target).hasClass('unitPortrait')) return;
                if (unit.unit === null || e.target.className == 'unitLevel') return;
                if (e.which == 2 || (e.which == 1 && (e.ctrlKey || Utils.isClickOnOrb(e,e.target)))) {
                    tunit.orb = (tunit.orb == 1 ? 2 : tunit.orb == 2 ? 0.5 : 1);
                    scope.glow();
                    scope.$apply();
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            };
            element.parent().parent().mouseup(onMouseUp);
        },
        controller: function($scope, $timeout) {
            $timeout(function() {
                if ($scope.tdata.team[$scope.slot].orb != 1)
                    $scope.$apply();
            });
        }
    };
};

directives.special = function() {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        template: '

{{data.team[slot].unit.name}}

',
        link: function(scope, element, attrs) {
            scope.slot = element.prevAll('.special').length;
            var isSelected = scope.tdata.team[scope.slot].special;
            var removeType = function() { ['STR','DEX','QCK','PSY','INT'].forEach(function(x) { element.removeClass(x); }); };
            scope.hasSpecial = false;
            scope.$watch('tdata.team[slot].special',function(enabled) {
                removeType();
                if (enabled) element.addClass(scope.data.team[scope.slot].unit.type);
                type = (scope.data.team[scope.slot].unit !== null ? scope.data.team[scope.slot].unit.type : null);
                isSelected = enabled;
            });
            scope.$watch('data.team[slot].unit',function(unit) {
                removeType();
                if (scope.tdata.team[scope.slot].special) element.addClass(unit.type);
                scope.hasSpecial = unit && specials.hasOwnProperty(unit.number+1);
            });
            element.click(function(e) {
                isSelected = !isSelected;
                scope.tdata.team[scope.slot].special = isSelected;
                scope.$apply();
            });
        }
    };
};

/****************************
 * Directive initialization *
 ****************************/

for (var key in directives)
    app.directive(key, directives[key]);

})();
<|endoftext|>


<commit_before>function initOldVersionWarnings($, thisVersion, projectUrl) {
    var schemeLessUrl = projectUrl;
    if (projectUrl.startsWith("http://")) projectUrl = schemeLessUrl.substring(5);
    else if (projectUrl.startsWith("https://")) projectUrl = schemeLessUrl.substring(6);
    const url = schemeLessUrl + (schemeLessUrl.endsWith("\/") ? "" : "/") + "paradox.json";
    $.get(url, function (versionData) {
        const currentVersion = versionData.version;
        if (thisVersion !== currentVersion) {
            showVersionWarning(thisVersion, currentVersion, projectUrl);
        }
    });
}

function showVersionWarning(thisVersion, currentVersion, projectUrl) {
    $('#version-warning').prepend(
        '
' +
        '
This documentation regards version ' + thisVersion + ', ' +
        'however the current version is ' + currentVersion + '.
' +
        '
'
    );
}<commit_msg>Don't try to download without project.url<commit_after>function initOldVersionWarnings($, thisVersion, projectUrl) {
    if (projectUrl && projectUrl !== "") {
        var schemeLessUrl = projectUrl;
        if (projectUrl.startsWith("http://")) projectUrl = schemeLessUrl.substring(5);
        else if (projectUrl.startsWith("https://")) projectUrl = schemeLessUrl.substring(6);
        const url = schemeLessUrl + (schemeLessUrl.endsWith("\/") ? "" : "/") + "paradox.json";
        $.get(url, function (versionData) {
            const currentVersion = versionData.version;
            if (thisVersion !== currentVersion) {
                showVersionWarning(thisVersion, currentVersion, projectUrl);
            }
        });
    }
}

function showVersionWarning(thisVersion, currentVersion, projectUrl) {
    $('#version-warning').prepend(
        '
' +
        '
This documentation regards version ' + thisVersion + ', ' +
        'however the current version is ' + currentVersion + '.
' +
        '
'
    );
}<|endoftext|>


<commit_before>'use strict';

/* global THREE, threejsLessonUtils */

{
  threejsLessonUtils.addDiagrams({
    mergedCubes: {
      create() {
        const geometries = [];
        const width = 3;
        const height = 2;
        const depth = 2;
        for (let y = 0; y < height; ++y) {
          for (let z = 0; z < depth; ++z) {
            for (let x = 0; x < width; ++x) {
              const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
              geometry.applyMatrix((new THREE.Matrix4()).makeTranslation(x, y, z));
              geometries.push(geometry);
            }
          }
        }
        const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(geometries, false);
        const material = new THREE.MeshBasicMaterial({
          color: 'black',
          wireframe: true,
        });
        const mesh = new THREE.Mesh(mergedGeometry, material);
        mesh.position.set(
            0.5 - width / 2,
            0.5 - height / 2,
            0.5 - depth / 2);
        const base = new THREE.Object3D();
        base.add(mesh);
        base.scale.setScalar(3.5);
        return base;
      },
    },
    culledCubes: {
      create() {
        const geometry = new THREE.BoxBufferGeometry(3, 2, 2, 3, 2, 2);
        const material = new THREE.MeshBasicMaterial({
          color: 'black',
          wireframe: true,
        });
        const mesh = new THREE.Mesh(geometry, material);
        mesh.scale.setScalar(3.5);
        return mesh;
      },
    },
  });
}

<commit_msg>dark stuff<commit_after>'use strict';

/* global THREE, threejsLessonUtils */

{
  const darkMatcher = window.matchMedia('(prefers-color-scheme: dark)');
  const isDarkMode = darkMatcher.matches;

  const darkColors = {
    wire: '#DDD',
  };
  const lightColors = {
    wore: '#000',
  };
  const colors = isDarkMode ? darkColors : lightColors;

  threejsLessonUtils.addDiagrams({
    mergedCubes: {
      create() {
        const geometries = [];
        const width = 3;
        const height = 2;
        const depth = 2;
        for (let y = 0; y < height; ++y) {
          for (let z = 0; z < depth; ++z) {
            for (let x = 0; x < width; ++x) {
              const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
              geometry.applyMatrix((new THREE.Matrix4()).makeTranslation(x, y, z));
              geometries.push(geometry);
            }
          }
        }
        const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(geometries, false);
        const material = new THREE.MeshBasicMaterial({
          color: colors.wire,
          wireframe: true,
        });
        const mesh = new THREE.Mesh(mergedGeometry, material);
        mesh.position.set(
            0.5 - width / 2,
            0.5 - height / 2,
            0.5 - depth / 2);
        const base = new THREE.Object3D();
        base.add(mesh);
        base.scale.setScalar(3.5);
        return base;
      },
    },
    culledCubes: {
      create() {
        const geometry = new THREE.BoxBufferGeometry(3, 2, 2, 3, 2, 2);
        const material = new THREE.MeshBasicMaterial({
          color: colors.wire,
          wireframe: true,
        });
        const mesh = new THREE.Mesh(geometry, material);
        mesh.scale.setScalar(3.5);
        return mesh;
      },
    },
  });
}

<|endoftext|>


<commit_before>const parseFunction = require('parse-function');

class Command {
  constructor(commandFn) {
    const obj = parseFunction(commandFn);

    this.name = obj.name;
    this.commandFn = commandFn;
  }
}

class BasePlugin {
    /**
     * @param {Client} client The Discord Client that gets passed into this Plugin
     */
    constructor(client) {
      this.client = client;
      this.commandMapping = {};

      //this.client.on('message', this.callCommand);
    }

    /**
     *  Execute a command if one matches a command's regex pattern in the mapping
     */
    callCommand(message) {
      for (var command in this.commandMapping) {
        if message.content.match(command) {
          this.commandMapping[command](message);
          break;
        }
      }
    }

    /**
     * Register a command function.
     *
     * The function will be parsed and a regex pattern will be generated for it using the function name and params.
     * @param {Function} command The command to be added.
     */
    registerCommand(commandFn) {
      const command = Command(commandFn);

    }
}

module.exports = BasePlugin;<commit_msg>Missing parentheis<commit_after>const parseFunction = require('parse-function');

class Command {
  constructor(commandFn) {
    const obj = parseFunction(commandFn);

    this.name = obj.name;
    this.commandFn = commandFn;
  }
}

class BasePlugin {
    /**
     * @param {Client} client The Discord Client that gets passed into this Plugin
     */
    constructor(client) {
      this.client = client;
      this.commandMapping = {};

      //this.client.on('message', this.callCommand);
    }

    /**
     *  Execute a command if one matches a command's regex pattern in the mapping
     */
    callCommand(message) {
      for (var command in this.commandMapping) {
        if (message.content.match(command)) {
          this.commandMapping[command](message);
          break;
        }
      }
    }

    /**
     * Register a command function.
     *
     * The function will be parsed and a regex pattern will be generated for it using the function name and params.
     * @param {Function} command The command to be added.
     */
    registerCommand(commandFn) {
      const command = Command(commandFn);

    }
}

module.exports = BasePlugin;<|endoftext|>


<commit_before>'use strict';
const Database = require('../.');

describe('Statement#iterate()', function () {
	beforeEach(function () {
		this.db = new Database(util.next());
		this.db.pragma("journal_mode = WAL");
		this.db.prepare('CREATE TABLE entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)').run();
		this.db.prepare("INSERT INTO entries WITH RECURSIVE temp(a, b, c, d, e) AS (SELECT 'foo', 1, 3.14, x'dddddddd', NULL UNION ALL SELECT a, b + 1, c, d, e FROM temp LIMIT 10) SELECT * FROM temp").run();
	});
	afterEach(function () {
		this.db.close();
	});

	it('should throw an exception when used on a statement that returns no data', function () {
		let stmt = this.db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
		expect(stmt.reader).to.be.false;
		expect(() => stmt.iterate()).to.throw(TypeError);

		stmt = this.db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
		expect(stmt.reader).to.be.false;
		expect(() => stmt.iterate()).to.throw(TypeError);

		stmt = this.db.prepare("BEGIN TRANSACTION");
		expect(stmt.reader).to.be.false;
		expect(() => stmt.iterate()).to.throw(TypeError);

		this.db.prepare("INSERT INTO entries WITH RECURSIVE temp(a, b, c, d, e) AS (SELECT 'foo', 1, 3.14, x'dddddddd', NULL UNION ALL SELECT a, b + 1, c, d, e FROM temp LIMIT 10) SELECT * FROM temp").run();
	});
	it('should return an iterator over each matching row', function () {
		const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };

		let count = 0;
		let stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		expect(stmt.reader).to.be.true;

		const iterator = stmt.iterate();
		expect(iterator).to.not.be.null;
		expect(typeof iterator).to.equal('object');
		expect(iterator.next).to.be.a('function');
		expect(iterator.return).to.be.a('function');
		expect(iterator.throw).to.not.be.a('function');
		expect(iterator[Symbol.iterator]).to.be.a('function');
		expect(iterator[Symbol.iterator]()).to.equal(iterator);

		for (const data of iterator) {
			row.b = ++count;
			expect(data).to.deep.equal(row);
		}
		expect(count).to.equal(10);

		count = 0;
		stmt = this.db.prepare("SELECT * FROM entries WHERE b > 5 ORDER BY rowid");
		const iterator2 = stmt.iterate();
		expect(iterator).to.not.equal(iterator2);
		for (const data of iterator2) {
			row.b = ++count + 5;
			expect(data).to.deep.equal(row);
		}
		expect(count).to.equal(5);
	});
	it('should obey the current pluck and expand settings', function () {
		const shouldHave = (desiredData) => {
			let i = 0;
			for (const data of stmt.iterate()) {
				i += 1;
				if (typeof desiredData === 'object' && desiredData !== null) {
					if (typeof desiredData.entries === 'object' && desiredData.entries !== null) {
						desiredData.entries.b = i;
					} else {
						desiredData.b = i;
					}
				}
				expect(data).to.deep.equal(desiredData);
			}
			expect(i).to.equal(10);
		};
		const expanded = {
			entries: { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null },
			$: { c: 5.5 },
		};
		const row = { ...expanded.entries, ...expanded.$ };
		const plucked = expanded.entries.a;
		const stmt = this.db.prepare("SELECT *, 2 + 3.5 AS c FROM entries ORDER BY rowid");
		shouldHave(row);
		stmt.pluck(true);
		shouldHave(plucked);
		shouldHave(plucked);
		stmt.pluck(false);
		shouldHave(row);
		shouldHave(row);
		stmt.pluck();
		shouldHave(plucked);
		shouldHave(plucked);
		stmt.expand();
		shouldHave(expanded);
		shouldHave(expanded);
		stmt.expand(false);
		shouldHave(row);
		shouldHave(row);
		stmt.expand(true);
		shouldHave(expanded);
		shouldHave(expanded);
		stmt.pluck(true);
		shouldHave(plucked);
		shouldHave(plucked);
	});
	it('should not be able to invoke .pluck() while the database is busy', function () {
		const stmt1 = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		const stmt2 = this.db.prepare("SELECT * FROM entries ORDER BY rowid LIMIT 2");
		let i = 0;
		for (const data of stmt1.iterate()) {
			++i;
			expect(() => stmt1.pluck()).to.throw(TypeError);
			expect(() => stmt2.pluck()).to.throw(TypeError);
			expect(() => stmt1.pluck(false)).to.throw(TypeError);
			expect(() => stmt2.pluck(false)).to.throw(TypeError);
		}
		expect(i).to.equal(10);
	});
	it('should close the iterator when throwing in a for-of loop', function () {
		const err = new Error('foobar');
		const stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		const iterator = stmt.iterate();
		let count = 0;
		expect(() => {
			for (const row of iterator) { ++count; throw err; }
		}).to.throw(err);
		expect(count).to.equal(1);
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		for (const row of iterator) ++count;
		expect(count).to.equal(1);
		for (const row of stmt.iterate()) ++count;
		expect(count).to.equal(11);
	});
	it('should close the iterator when using break in a for-of loop', function () {
		const stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		const iterator = stmt.iterate();
		let count = 0;
		for (const row of iterator) { ++count; break; }
		expect(count).to.equal(1);
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		for (const row of iterator) ++count;
		expect(count).to.equal(1);
		for (const row of stmt.iterate()) ++count;
		expect(count).to.equal(11);
	});
	it('should return an empty iterator when no rows were found', function () {
		const stmt = this.db.prepare("SELECT * FROM entries WHERE b == 999");
		expect(stmt.iterate().next()).to.deep.equal({ value: undefined, done: true });
		for (const data of stmt.pluck().iterate()) {
			throw new Error('This callback should not have been invoked');
		}
	});
	it('should not allow other database operations to execute while open', function () {
		const stmt1 = this.db.prepare('SELECT * FROM entries ORDER BY rowid');
		const stmt2 = this.db.prepare('CREATE TABLE numbers (number INTEGER)');
		let count = 0;
		for (const row of this.db.prepare('SELECT * FROM entries ORDER BY rowid').iterate()) {
			++count;
			expect(() => this.db.close()).to.throw(TypeError);
			expect(() => this.db.pragma('cache_size')).to.throw(TypeError);
			expect(() => this.db.checkpoint()).to.throw(TypeError);
			expect(() => this.db.prepare('SELECT * FROM entries ORDER BY rowid')).to.throw(TypeError);
			expect(() => this.db.transaction(() => {})).to.throw(TypeError);
			expect(() => stmt1.get()).to.throw(TypeError);
			expect(() => stmt1.all()).to.throw(TypeError);
			expect(() => stmt1.iterate()).to.throw(TypeError);
			expect(() => stmt2.run()).to.throw(TypeError);
		}
		expect(count).to.equal(10);
	});
	it('should allow database operations after closing the iterator', function () {
		const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
		const stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		this.db.prepare('SELECT 555');
		const iterator = stmt.iterate();
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.next()).to.deep.equal({ value: row, done: false });
		row.b += 1;
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.next()).to.deep.equal({ value: row, done: false });
		row.b += 1;
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.next()).to.deep.equal({ value: row, done: false });
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.return()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
		expect(iterator.return()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
	});
	it('should accept bind parameters', function () {
		const shouldHave = (SQL, desiredData, args) => {
			let i = 0;
			const stmt = this.db.prepare(SQL);
			for (const data of stmt.iterate(...args)) {
				desiredData.b = ++i;
				expect(data).to.deep.equal(desiredData);
			}
			expect(i).to.equal(1);
		};

		const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
		const SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
		const SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';

		shouldHave(SQL1, row, ['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]);
		shouldHave(SQL1, row, [['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]]);
		shouldHave(SQL1, row, [['foo', 1], [3.14], Buffer.alloc(4).fill(0xdd), [,]]);
		shouldHave(SQL2, row, [{ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: undefined }]);

		for (const data of this.db.prepare(SQL2).iterate({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xaa), e: undefined })) {
			throw new Error('This callback should not have been invoked');
		}

		expect(() =>
			this.db.prepare(SQL2).iterate(row, () => {})
		).to.throw(TypeError);

		expect(() =>
			this.db.prepare(SQL2).iterate({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd) })
		).to.throw(RangeError);

		expect(() =>
			this.db.prepare(SQL1).iterate()
		).to.throw(RangeError);

		expect(() =>
			this.db.prepare(SQL2).iterate()
		).to.throw(TypeError);

		expect(() =>
			this.db.prepare(SQL2).iterate(row, {})
		).to.throw(TypeError);

		expect(() =>
			this.db.prepare(SQL2).iterate({})
		).to.throw(RangeError);

		this.db.prepare(SQL1).iterate('foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null).return();
		expect(() =>
			this.db.prepare(SQL1).iterate('foo', 1, new (function(){})(), Buffer.alloc(4).fill(0xdd), null)
		).to.throw(TypeError);
	});

	it("should read and write non-trivial numbers of rows", function () {
		this.timeout(5000);
		const runUntil = Date.now() + 1000
	  let i = 0;
		const r = .141592654
	  this.db.prepare('CREATE TABLE t (id INTEGER, b TEXT, c REAL)').run();
		const stmt = this.db.prepare("INSERT INTO t VALUES (?, ?, ?)");
		while(Date.now() < runUntil) {
			// Batched transactions of 100 inserts:
			this.db.transaction(() => {
				for(const start = i; i < start + 100 ; i++) {
					expect(stmt.run([i, String(i), i + r])).to.deep.equal({
						changes: 1,
						lastInsertRowid: i + 1
					});
				}
			})();
		}
		expect(i).to.be.gte(1000); // < expect ~50K and 200K on reasonable machines
	  const stmt1 = this.db.prepare("SELECT * FROM t ORDER BY id DESC");
	  for (const data of stmt1.iterate()) {
			i--
	    expect(data).to.deep.equal({
	      id: i,
	      b: String(i),
	      c: i + r
	    })
	  }
	  expect(i).to.equal(0)
	});
});
<commit_msg>adjust timeout and runtime based on a const<commit_after>'use strict';
const Database = require('../.');

describe('Statement#iterate()', function () {
	beforeEach(function () {
		this.db = new Database(util.next());
		this.db.pragma("journal_mode = WAL");
		this.db.prepare('CREATE TABLE entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)').run();
		this.db.prepare("INSERT INTO entries WITH RECURSIVE temp(a, b, c, d, e) AS (SELECT 'foo', 1, 3.14, x'dddddddd', NULL UNION ALL SELECT a, b + 1, c, d, e FROM temp LIMIT 10) SELECT * FROM temp").run();
	});
	afterEach(function () {
		this.db.close();
	});

	it('should throw an exception when used on a statement that returns no data', function () {
		let stmt = this.db.prepare("INSERT INTO entries VALUES ('foo', 1, 3.14, x'dddddddd', NULL)");
		expect(stmt.reader).to.be.false;
		expect(() => stmt.iterate()).to.throw(TypeError);

		stmt = this.db.prepare("CREATE TABLE IF NOT EXISTS entries (a TEXT, b INTEGER, c REAL, d BLOB, e TEXT)");
		expect(stmt.reader).to.be.false;
		expect(() => stmt.iterate()).to.throw(TypeError);

		stmt = this.db.prepare("BEGIN TRANSACTION");
		expect(stmt.reader).to.be.false;
		expect(() => stmt.iterate()).to.throw(TypeError);

		this.db.prepare("INSERT INTO entries WITH RECURSIVE temp(a, b, c, d, e) AS (SELECT 'foo', 1, 3.14, x'dddddddd', NULL UNION ALL SELECT a, b + 1, c, d, e FROM temp LIMIT 10) SELECT * FROM temp").run();
	});
	it('should return an iterator over each matching row', function () {
		const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };

		let count = 0;
		let stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		expect(stmt.reader).to.be.true;

		const iterator = stmt.iterate();
		expect(iterator).to.not.be.null;
		expect(typeof iterator).to.equal('object');
		expect(iterator.next).to.be.a('function');
		expect(iterator.return).to.be.a('function');
		expect(iterator.throw).to.not.be.a('function');
		expect(iterator[Symbol.iterator]).to.be.a('function');
		expect(iterator[Symbol.iterator]()).to.equal(iterator);

		for (const data of iterator) {
			row.b = ++count;
			expect(data).to.deep.equal(row);
		}
		expect(count).to.equal(10);

		count = 0;
		stmt = this.db.prepare("SELECT * FROM entries WHERE b > 5 ORDER BY rowid");
		const iterator2 = stmt.iterate();
		expect(iterator).to.not.equal(iterator2);
		for (const data of iterator2) {
			row.b = ++count + 5;
			expect(data).to.deep.equal(row);
		}
		expect(count).to.equal(5);
	});
	it('should obey the current pluck and expand settings', function () {
		const shouldHave = (desiredData) => {
			let i = 0;
			for (const data of stmt.iterate()) {
				i += 1;
				if (typeof desiredData === 'object' && desiredData !== null) {
					if (typeof desiredData.entries === 'object' && desiredData.entries !== null) {
						desiredData.entries.b = i;
					} else {
						desiredData.b = i;
					}
				}
				expect(data).to.deep.equal(desiredData);
			}
			expect(i).to.equal(10);
		};
		const expanded = {
			entries: { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null },
			$: { c: 5.5 },
		};
		const row = { ...expanded.entries, ...expanded.$ };
		const plucked = expanded.entries.a;
		const stmt = this.db.prepare("SELECT *, 2 + 3.5 AS c FROM entries ORDER BY rowid");
		shouldHave(row);
		stmt.pluck(true);
		shouldHave(plucked);
		shouldHave(plucked);
		stmt.pluck(false);
		shouldHave(row);
		shouldHave(row);
		stmt.pluck();
		shouldHave(plucked);
		shouldHave(plucked);
		stmt.expand();
		shouldHave(expanded);
		shouldHave(expanded);
		stmt.expand(false);
		shouldHave(row);
		shouldHave(row);
		stmt.expand(true);
		shouldHave(expanded);
		shouldHave(expanded);
		stmt.pluck(true);
		shouldHave(plucked);
		shouldHave(plucked);
	});
	it('should not be able to invoke .pluck() while the database is busy', function () {
		const stmt1 = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		const stmt2 = this.db.prepare("SELECT * FROM entries ORDER BY rowid LIMIT 2");
		let i = 0;
		for (const data of stmt1.iterate()) {
			++i;
			expect(() => stmt1.pluck()).to.throw(TypeError);
			expect(() => stmt2.pluck()).to.throw(TypeError);
			expect(() => stmt1.pluck(false)).to.throw(TypeError);
			expect(() => stmt2.pluck(false)).to.throw(TypeError);
		}
		expect(i).to.equal(10);
	});
	it('should close the iterator when throwing in a for-of loop', function () {
		const err = new Error('foobar');
		const stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		const iterator = stmt.iterate();
		let count = 0;
		expect(() => {
			for (const row of iterator) { ++count; throw err; }
		}).to.throw(err);
		expect(count).to.equal(1);
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		for (const row of iterator) ++count;
		expect(count).to.equal(1);
		for (const row of stmt.iterate()) ++count;
		expect(count).to.equal(11);
	});
	it('should close the iterator when using break in a for-of loop', function () {
		const stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		const iterator = stmt.iterate();
		let count = 0;
		for (const row of iterator) { ++count; break; }
		expect(count).to.equal(1);
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		for (const row of iterator) ++count;
		expect(count).to.equal(1);
		for (const row of stmt.iterate()) ++count;
		expect(count).to.equal(11);
	});
	it('should return an empty iterator when no rows were found', function () {
		const stmt = this.db.prepare("SELECT * FROM entries WHERE b == 999");
		expect(stmt.iterate().next()).to.deep.equal({ value: undefined, done: true });
		for (const data of stmt.pluck().iterate()) {
			throw new Error('This callback should not have been invoked');
		}
	});
	it('should not allow other database operations to execute while open', function () {
		const stmt1 = this.db.prepare('SELECT * FROM entries ORDER BY rowid');
		const stmt2 = this.db.prepare('CREATE TABLE numbers (number INTEGER)');
		let count = 0;
		for (const row of this.db.prepare('SELECT * FROM entries ORDER BY rowid').iterate()) {
			++count;
			expect(() => this.db.close()).to.throw(TypeError);
			expect(() => this.db.pragma('cache_size')).to.throw(TypeError);
			expect(() => this.db.checkpoint()).to.throw(TypeError);
			expect(() => this.db.prepare('SELECT * FROM entries ORDER BY rowid')).to.throw(TypeError);
			expect(() => this.db.transaction(() => {})).to.throw(TypeError);
			expect(() => stmt1.get()).to.throw(TypeError);
			expect(() => stmt1.all()).to.throw(TypeError);
			expect(() => stmt1.iterate()).to.throw(TypeError);
			expect(() => stmt2.run()).to.throw(TypeError);
		}
		expect(count).to.equal(10);
	});
	it('should allow database operations after closing the iterator', function () {
		const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
		const stmt = this.db.prepare("SELECT * FROM entries ORDER BY rowid");
		this.db.prepare('SELECT 555');
		const iterator = stmt.iterate();
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.next()).to.deep.equal({ value: row, done: false });
		row.b += 1;
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.next()).to.deep.equal({ value: row, done: false });
		row.b += 1;
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.next()).to.deep.equal({ value: row, done: false });
		expect(() => this.db.prepare('SELECT 555')).to.throw(TypeError);
		expect(iterator.return()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
		expect(iterator.return()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
		expect(iterator.next()).to.deep.equal({ value: undefined, done: true });
		this.db.prepare('SELECT 555');
	});
	it('should accept bind parameters', function () {
		const shouldHave = (SQL, desiredData, args) => {
			let i = 0;
			const stmt = this.db.prepare(SQL);
			for (const data of stmt.iterate(...args)) {
				desiredData.b = ++i;
				expect(data).to.deep.equal(desiredData);
			}
			expect(i).to.equal(1);
		};

		const row = { a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: null };
		const SQL1 = 'SELECT * FROM entries WHERE a=? AND b=? AND c=? AND d=? AND e IS ?';
		const SQL2 = 'SELECT * FROM entries WHERE a=@a AND b=@b AND c=@c AND d=@d AND e IS @e';

		shouldHave(SQL1, row, ['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]);
		shouldHave(SQL1, row, [['foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null]]);
		shouldHave(SQL1, row, [['foo', 1], [3.14], Buffer.alloc(4).fill(0xdd), [,]]);
		shouldHave(SQL2, row, [{ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd), e: undefined }]);

		for (const data of this.db.prepare(SQL2).iterate({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xaa), e: undefined })) {
			throw new Error('This callback should not have been invoked');
		}

		expect(() =>
			this.db.prepare(SQL2).iterate(row, () => {})
		).to.throw(TypeError);

		expect(() =>
			this.db.prepare(SQL2).iterate({ a: 'foo', b: 1, c: 3.14, d: Buffer.alloc(4).fill(0xdd) })
		).to.throw(RangeError);

		expect(() =>
			this.db.prepare(SQL1).iterate()
		).to.throw(RangeError);

		expect(() =>
			this.db.prepare(SQL2).iterate()
		).to.throw(TypeError);

		expect(() =>
			this.db.prepare(SQL2).iterate(row, {})
		).to.throw(TypeError);

		expect(() =>
			this.db.prepare(SQL2).iterate({})
		).to.throw(RangeError);

		this.db.prepare(SQL1).iterate('foo', 1, 3.14, Buffer.alloc(4).fill(0xdd), null).return();
		expect(() =>
			this.db.prepare(SQL1).iterate('foo', 1, new (function(){})(), Buffer.alloc(4).fill(0xdd), null)
		).to.throw(TypeError);
	});

	it.only("should read and write non-trivial numbers of rows", function () {
		const insertRuntime = 10000
		this.timeout(insertRuntime * 2.5);
		const runUntil = Date.now() + insertRuntime
	  let i = 0;
		const r = .141592654
	  this.db.prepare('CREATE TABLE t (id INTEGER, b TEXT, c REAL)').run();
		const stmt = this.db.prepare("INSERT INTO t VALUES (?, ?, ?)");
		while(Date.now() < runUntil) {
			// Batched transactions of 100 inserts:
			this.db.transaction(() => {
				for(const start = i; i < start + 100 ; i++) {
					expect(stmt.run([i, String(i), i + r])).to.deep.equal({
						changes: 1,
						lastInsertRowid: i + 1
					});
				}
			})();
		}
		expect(i).to.be.gte(1000); // < expect ~50K and 200K on reasonable machines
	  const stmt1 = this.db.prepare("SELECT * FROM t ORDER BY id DESC");
	  for (const data of stmt1.iterate()) {
			i--
	    expect(data).to.deep.equal({
	      id: i,
	      b: String(i),
	      c: i + r
	    })
	  }
	  expect(i).to.equal(0)
	});
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('app')
    .controller('SearchCtrl', SearchController);

  SearchController.$inject = ['$scope', 'findApi', 'utils'];

  function SearchController($scope, findApi, utils) {
    var vm = this;

    vm.url = sessionStorage.getItem('url') || null;
    vm.dataAPI = null;
    vm.fields = null;
    vm.errorData = {};
    vm.itemInit = {key:'', value:''};
    vm.itemsPost = [];

    $scope.$watch('vm.url', function() {
      vm.errorData.show = false;
      vm.errorData = {};
    });

    ////////

    vm.getData = function() {
      if(vm.url) {
        sessionStorage.setItem('url', vm.url);

        return findApi.getData(vm.url).then(function(data) {
          if (data.data.length > 0) {
            vm.dataAPI = data.data;
            vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
          }
          // show section
          vm.showResult = true;
        }, function(error) {
          vm.showResult = false;
          vm.errorData.method = error.config.method;
          vm.errorData.message = error.data.message || error.data;
          vm.errorData.status = error.status;
          vm.errorData.show = true;
        });
      }
    };

    vm.showPostForm = function() {

      if(vm.putForm) {
        vm.putForm = false;
      }

      if(vm.postForm) {
        vm.postForm = false;
      } else {
        vm.postForm = true;
      }
    };
    vm.hidePostForm = function() {
      if(vm.postForm) {
        vm.postForm = false;
      }
    };

    vm.showPutForm = function() {

      vm.url = utils.formatURL(vm.url);

      if(vm.postForm) {
        vm.postForm = false;
      }

      if(vm.putForm) {
        vm.putForm = false;
      } else {
        vm.putForm = true;
      }
    };
    vm.hidePutForm = function() {
      if(vm.putForm) {
        vm.putForm = false;
      }
    };

    vm.addItem = function() {
      if(vm.itemsPost.length === 0) {
        vm.itemsPost.push(vm.itemInit);
      }

      vm.itemsPost.push({
        key: '',
        value: ''
      });
    };

    vm.removeItem = function() {
      vm.itemsPost.pop();
    };

    vm.postData = function(obj) {
      var newObj = {};

      for(var i=0, size = vm.itemsPost.length; i < size; i++) {
          newObj[vm.itemsPost[i].key] = vm.itemsPost[i].value;
      }

      obj = obj || newObj;

      return findApi.postData(vm.url, obj).then(function(data) {
        if(vm.showResult) {
          return findApi.getData(vm.url).then(function(data) {
            vm.dataAPI = data.data;
            vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
          });
        }
      });

    };

    vm.deleteData = function(id, param) {
      var finalURL = null;

      vm.url = utils.formatURL(vm.url);
      finalURL = vm.url + id;

      vm.errorData = {};

      if(param === 'input') {
          finalURL = vm.url;
      }

      return findApi.deleteData(finalURL).then(function(data) {
        return findApi.getData(vm.url).then(function(data) {
          vm.dataAPI = data.data;
          vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
          vm.showAdd = vm.dataAPI.length ? true : false;
        });
      });
    };

    vm.putData = function(data) {
      var newObj = {};

      for(var i=0, size = vm.itemsPost.length; i < size; i++) {
          newObj[vm.itemsPost[i].key] = vm.itemsPost[i].value;
      }

      console.log(newObj);

      return findApi.updateData(vm.url, newObj).then(function(data) {
        vm.url = sessionStorage.getItem('url');
        return findApi.getData(vm.url).then(function(data) {
          vm.dataAPI = data.data;
          vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
        });
      });
    };

  }

}());
<commit_msg>refactor<commit_after>(function() {
  'use strict';

  angular
    .module('app')
    .controller('SearchCtrl', SearchController);

  SearchController.$inject = ['$scope', 'findApi', 'utils'];

  function SearchController($scope, findApi, utils) {
    var vm = this;

    vm.url = sessionStorage.getItem('url') || null;
    vm.dataAPI = null;
    vm.fields = null;
    vm.errorData = {};
    vm.itemInit = {key:'', value:''};
    vm.itemsPost = [];

    $scope.$watch('vm.url', function() {
      vm.errorData.show = false;
      vm.errorData = {};
    });

    ////////

    vm.getData = function() {
      if(vm.url) {
        sessionStorage.setItem('url', vm.url);

        return findApi.getData(vm.url).then(function(data) {
          if (data.data.length > 0) {
            vm.dataAPI = data.data;
            vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
          }
          // show section
          vm.showResult = true;
        }, function(error) {
          vm.showResult = false;
          vm.errorData.method = error.config.method;
          vm.errorData.message = error.data.message || error.data;
          vm.errorData.status = error.status;
          vm.errorData.show = true;
        });
      }
    };

    vm.showPostForm = function() {

      if(vm.putForm) {
        vm.putForm = false;
      }

      if(vm.postForm) {
        vm.postForm = false;
      } else {
        vm.postForm = true;
      }
    };
    vm.hidePostForm = function() {
      if(vm.postForm) {
        vm.postForm = false;
      }
    };

    vm.showPutForm = function() {

      vm.url = utils.formatURL(vm.url);

      if(vm.postForm) {
        vm.postForm = false;
      }

      if(vm.putForm) {
        vm.putForm = false;
      } else {
        vm.putForm = true;
      }
    };
    vm.hidePutForm = function() {
      if(vm.putForm) {
        vm.putForm = false;
      }
    };

    vm.addItem = function() {
      if(vm.itemsPost.length === 0) {
        vm.itemsPost.push(vm.itemInit);
      }

      vm.itemsPost.push({
        key: '',
        value: ''
      });
    };

    vm.removeItem = function() {
      vm.itemsPost.pop();
    };

    vm.postData = function() {
      var newObj = {};

      for(var i=0, size = vm.itemsPost.length; i < size; i++) {
          newObj[vm.itemsPost[i].key] = vm.itemsPost[i].value;
      }

      return findApi.postData(vm.url, newObj).then(function(data) {
        if(vm.showResult) {
          return findApi.getData(vm.url).then(function(data) {
            vm.dataAPI = data.data;
            vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
          });
        }
      });

    };

    vm.deleteData = function(id, param) {
      var finalURL = null;

      vm.url = utils.formatURL(vm.url);
      finalURL = vm.url + id;

      vm.errorData = {};

      if(param === 'input') {
          finalURL = vm.url;
      }

      return findApi.deleteData(finalURL).then(function(data) {
        return findApi.getData(vm.url).then(function(data) {
          vm.dataAPI = data.data;
          vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
          vm.showAdd = vm.dataAPI.length ? true : false;
        });
      });
    };

    vm.putData = function() {
      var newObj = {};

      for(var i=0, size = vm.itemsPost.length; i < size; i++) {
          newObj[vm.itemsPost[i].key] = vm.itemsPost[i].value;
      }

      return findApi.updateData(vm.url, newObj).then(function(data) {
        vm.url = sessionStorage.getItem('url');
        return findApi.getData(vm.url).then(function(data) {
          vm.dataAPI = data.data;
          vm.fields = data.data[0] ? Object.getOwnPropertyNames(data.data[0]) : null;
        });
      });
    };

  }

}());
<|endoftext|>


<commit_before>var React = require("react/addons");
var Cookies = require("js-cookie");

var BarChart = require("app/components/barChart");
var stubReactComponents = require("../../helpers/stubReactComponent");
var stubRouterContext = require("../../helpers/stubRouterContext");

var TestUtils = React.addons.TestUtils;
var findWithClass = TestUtils.findRenderedDOMComponentWithClass;
var findWithType = TestUtils.findRenderedComponentWithType;

describe("BarChart", function() {

  beforeEach(function() {
    this.sandbox = sinon.sandbox.create();
    this.Element = BarChart;
  });

  afterEach(function() {
    this.sandbox.restore();
    React.unmountComponentAtNode(document.body);
  });

  describe("render()", function() {

    it("renders with default props", function() {
      var comp = React.render(<this.Element />, document.body);
      expect(comp).to.be.ok;
    });

  });

});
<commit_msg>Unused imports<commit_after>var React = require("react/addons");

var BarChart = require("app/components/barChart");

describe("BarChart", function() {

  beforeEach(function() {
    this.sandbox = sinon.sandbox.create();
    this.Element = BarChart;
  });

  afterEach(function() {
    this.sandbox.restore();
    React.unmountComponentAtNode(document.body);
  });

  describe("render()", function() {

    it("renders with default props", function() {
      var comp = React.render(<this.Element />, document.body);
      expect(comp).to.be.ok;
    });

  });

});
<|endoftext|>