<commit_before>/*exported e, ajax*/
function Toggler(rootEl) {
  var toggler = this;
  var togglerBtnAttribute = '[data-o-toggler-button]';
	var togglerTargetAttribute = '[data-o-toggler-target]';

  function handleToggle() {
    toggler.isOpen = !toggler.isOpen;

    if (toggler.isOpen) {
      toggler.button.setAttribute('aria-expanded', 'true');
      toggler.target.setAttribute('aria-hidden', 'false');
    } else {
      toggler.button.setAttribute('aria-expanded', 'false');
      toggler.target.setAttribute('aria-hidden', 'true');
    }
  }

  function handleEsc(e) {
    if (toggler.isOpen && e.keyCode === 27) {
        handleToggle();
    }
  }

  function handleClick(e) {
    if (toggler.isOpen && !rootEl.contains(e.target)) {
      handleToggle();
    }
  }

  function init() {
    if (!rootEl) {
      rootEl = document.body;
    }

    var btnEl = rootEl.querySelector(togglerBtnAttribute);
    var targetEl = rootEl.querySelector(togglerTargetAttribute);

    if (!btnEl) { return; }

    toggler.rootEl = rootEl;
    toggler.button = btnEl;
    toggler.target = targetEl;
    toggler.isOpen = false;

    toggler.button.addEventListener('click', handleToggle);
    document.body.addEventListener('click', handleClick);
    document.body.addEventListener('keydown', handleEsc);
  }

  init();
}

function Nav(rootEl) {
	var config = {navClassName: 'o-nav'};
	var oNav = this;

	function init() {
		if (!rootEl) {
			rootEl = document.body;
		}
		var rootDelegate = new Delegate(rootEl);

		oNav.delegate = rootDelegate;
		oNav.rootEl = rootEl;
	}

	function selected() {
		var selectAttribute = '.nav-section-head.mobile';
		var selectableEls = oNav.rootEl.querySelectorAll(selectAttribute);

		oNav.delegate.on('click', selectAttribute, function (e, selectable) {
			for (var i = 0; i < selectableEls.length; i++) {
				selectableEls[i].setAttribute('aria-selected', 'false');
			}
			selectable.setAttribute('aria-selected', 'true');
		});
	}

	function preventScroll() {
		var navToggle = oNav.rootEl.querySelector('[data-o-nav-togglable]');
		var navOpenClass = config.navClassName + '--open';

		if (navToggle) {
			navToggle.addEventListener('click', function() {
				document.documentElement.classList.toggle(navOpenClass);
				document.body.classList.toggle(navOpenClass);
			});
		}
	}

	function toggle() {
		var toggleAttribute = '[data-o-nav-togglable]';

		oNav.delegate.on('click', toggleAttribute, function (e, togglerEl) {
			var togglerElState = togglerEl.getAttribute('aria-pressed');

			if (togglerElState === 'true') {
				togglerEl.setAttribute('aria-pressed', 'false');
			} else if (togglerElState === 'false' || !togglerElState) {
				togglerEl.setAttribute('aria-pressed', 'true');
			}
		});
	}

	init();
	preventScroll();
	toggle();
	selected();
}

function searchRedirect(formEl) {
	if (typeof formEl === 'string') {
		formEl = document.querySelector(formEl);
	}
	if (!formEl) {
		return;
	}
	var searchEl = formEl.querySelector('.search-input');

	var baseUrl = window.location.protocol + '//' + window.location.hostname + '/archiver/';

	var pattern = /^(20\d{2})[-\s\/](0[1-9]|1[012])[-\s\/](0[1-9]|[12][0-9]|3[01])$/;

	formEl.addEventListener('submit', function(e) {
		var searchValue = searchEl.value;
		var matchedValue = searchValue.match(pattern);

		if (matchedValue) {
			e.preventDefault();
			var archiveDate = matchedValue.slice(1).join('-');
			console.log(archiveDate);

			window.location.assign(baseUrl + archiveDate);
		}
	});
}

searchRedirect('#search-form');

// callback(error, data)
var ajax = {
	getData: function (url, callback) {
	  var xhr = new XMLHttpRequest();

	  xhr.onreadystatechange = function() {
	    if (xhr.readyState === 4) {
	      if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
	        // var type = xhr.getResponseHeader('Content-Type');
	        // if (type.indexOf('html') !== -1 || xhr.responseXML) {
	        // 	console.log('HTML or XML');
	        //   callback(null, xhr.responseXML);
	        // } else if (type === 'application/json') {
	        //   callback(null, JSON.parse(xhr.responseText));
	        // } else {
	        	// console.log('text');
	          callback(null, xhr.responseText);
	        // }
	      } else {
	        //console.log('Request was unsuccessful: ' + xhr.status);
	        callback(xhr.status);
	      }

	    } else {
	      //console.log('readyState: ' + xhr.readyState);
	    }
	  };

	  xhr.open('GET', url);
	  // xhr.responseType = 'document';
	  xhr.send(null);
	}
};

// Find .nav-sections which are not the currently loaded page and thus have no .nav-items.level-2
function getEmptyNavSections(container) {
	var navSectionClassname = '.nav-section';

	var navSectionEls = container.querySelectorAll(navSectionClassname);
	var navSectionsObj = {};

	for (var i = 0, len = navSectionEls.length; i < len; i++) {
		var navSectionEl = navSectionEls[i];

		var selected = navSectionEl.getAttribute('aria-selected');
		var navSectionName = navSectionEl.getAttribute('data-section');

		if ((!selected) && navSectionName) {
			navSectionsObj[navSectionName] = navSectionEl;
		}
	}
	return navSectionsObj;
}

function zipObject(objA, objB) {
	for (var k in objA) {
		if (objA.hasOwnProperty(k) && k in objB) {
			//console.log(k);
			//console.log(objA[k]);
			objA[k].appendChild(objB[k]);
		}
	}
}

var navEl = document.querySelector('.o-nav');
new Nav(navEl);
if (navEl) {
	var searchEl = navEl.querySelector('.o-nav__search');
	new Toggler(searchEl);
}

function stringToDOM(str) {
	var tmpEl = document.createElement('ol');
	tmpEl.innerHTML = str;
	var elCollection = {};
	var navSectionEls = tmpEl.querySelectorAll('.nav-section');

// In IE8, `tmpEl.querySelectorAll('.nav-section')`does not work.
// This might be that `querySelector` is not live.
// If it does not work, fallback to `getElementsByTagName`,
// and manually iterate elements and filter by classname.

	if (navSectionEls.length > 0) {
		for (var k = 0, len = navSectionEls.length; k< len; k++) {

			var navSectionEl = navSectionEls[k];

			var navSectionName = navSectionEl.getAttribute('data-section');
			var navItemsEl = navSectionEl.querySelector('.nav-items');

			elCollection[navSectionName] = navItemsEl;
		}
	} else {
		var liEls = tmpEl.getElementsByTagName('li');

		for (var i = 0; i < liEls.length; i++) {
			var liEl = liEls[i];
			if (liEl.className.search(/nav-section/) > -1) {
				var sectionName = liEl.getAttribute('data-section');
				var olEls = liEl.getElementsByTagName('ol');
				for(var j = 0; j < olEls.length; j++) {
					var olEl = olEls[j];
					if (olEl.className.search(/nav-items/) !== -1) {
						var navItems = olEl;
						elCollection[sectionName] = navItems;
					}
				}
			}
		}
	}
	return elCollection;
}

var emptyNavSections = getEmptyNavSections(navEl);

ajax.getData('/m/corp/ajax-nav.html?hhhh', function(error, data) {
	if (error) {return error;}
	var parsedDOM = stringToDOM(data);
	zipObject(emptyNavSections, parsedDOM);
});<commit_msg>fix bugs in the navigation<commit_after>/*exported e, ajax*/
function Toggler(rootEl) {
  var toggler = this;
  var togglerBtnAttribute = '[data-o-toggler-button]';
	var togglerTargetAttribute = '[data-o-toggler-target]';

  function handleToggle() {
    toggler.isOpen = !toggler.isOpen;

    if (toggler.isOpen) {
      toggler.button.setAttribute('aria-expanded', 'true');
      toggler.target.setAttribute('aria-hidden', 'false');
    } else {
      toggler.button.setAttribute('aria-expanded', 'false');
      toggler.target.setAttribute('aria-hidden', 'true');
    }
  }

  function handleEsc(e) {
    if (toggler.isOpen && e.keyCode === 27) {
        handleToggle();
    }
  }

  function handleClick(e) {
    if (toggler.isOpen && !rootEl.contains(e.target)) {
      handleToggle();
    }
  }

  function init() {
    if (!rootEl) {
      rootEl = document.body;
    }

    var btnEl = rootEl.querySelector(togglerBtnAttribute);
    var targetEl = rootEl.querySelector(togglerTargetAttribute);

    if (!btnEl) { return; }

    toggler.rootEl = rootEl;
    toggler.button = btnEl;
    toggler.target = targetEl;
    toggler.isOpen = false;

    toggler.button.addEventListener('click', handleToggle);
    document.body.addEventListener('click', handleClick);
    document.body.addEventListener('keydown', handleEsc);
  }

  init();
}

function Nav(rootEl) {
	var config = {navClassName: 'o-nav'};
	var oNav = this;

	function init() {
		if (!rootEl) {
			rootEl = document.body;
		}
		var rootDelegate = new Delegate(rootEl);

		oNav.delegate = rootDelegate;
		oNav.rootEl = rootEl;
	}

	function selected() {
		var selectAttribute = '.nav-section-head.mobile';
		var selectableEls = oNav.rootEl.querySelectorAll(selectAttribute);

		oNav.delegate.on('click', selectAttribute, function (e, selectable) {
			for (var i = 0; i < selectableEls.length; i++) {
				selectableEls[i].setAttribute('aria-selected', 'false');
			}
			selectable.setAttribute('aria-selected', 'true');
		});
	}

	function preventScroll() {
		var navToggle = oNav.rootEl.querySelector('[data-o-nav-togglable]');
		var navOpenClass = config.navClassName + '--open';

		if (navToggle) {
			navToggle.addEventListener('click', function() {
				document.documentElement.classList.toggle(navOpenClass);
				document.body.classList.toggle(navOpenClass);
			});
		}
	}

	function toggle() {
		var toggleAttribute = '[data-o-nav-togglable]';

		oNav.delegate.on('click', toggleAttribute, function (e, togglerEl) {
			var togglerElState = togglerEl.getAttribute('aria-pressed');

			if (togglerElState === 'true') {
				togglerEl.setAttribute('aria-pressed', 'false');
			} else if (togglerElState === 'false' || !togglerElState) {
				togglerEl.setAttribute('aria-pressed', 'true');
			}
		});
	}

	init();
	preventScroll();
	toggle();
	selected();
}

function searchRedirect(formEl) {
	if (typeof formEl === 'string') {
		formEl = document.querySelector(formEl);
	}
	if (!formEl) {
		return;
	}
	var searchEl = formEl.querySelector('.search-input');

	var baseUrl = window.location.protocol + '//' + window.location.hostname + '/archiver/';

	var pattern = /^(20\d{2})[-\s\/](0[1-9]|1[012])[-\s\/](0[1-9]|[12][0-9]|3[01])$/;

	formEl.addEventListener('submit', function(e) {
		var searchValue = searchEl.value;
		var matchedValue = searchValue.match(pattern);

		if (matchedValue) {
			e.preventDefault();
			var archiveDate = matchedValue.slice(1).join('-');
			console.log(archiveDate);

			window.location.assign(baseUrl + archiveDate);
		}
	});
}

// Find .nav-sections which are not the currently loaded page and thus have no .nav-items.level-2
function getEmptyNavSections(container) {
	var navSectionClassname = '.nav-section';

	var navSectionEls = container.querySelectorAll(navSectionClassname);
	var navSectionsObj = {};

	for (var i = 0, len = navSectionEls.length; i < len; i++) {
		var navSectionEl = navSectionEls[i];

		var selected = navSectionEl.getAttribute('aria-selected');
		var navSectionName = navSectionEl.getAttribute('data-section');

		if ((!selected) && navSectionName) {
			navSectionsObj[navSectionName] = navSectionEl;
		}
	}
	return navSectionsObj;
}

function zipObject(objA, objB) {
	for (var k in objA) {
		if (objA.hasOwnProperty(k) && k in objB) {
			//console.log(k);
			//console.log(objA[k]);
			objA[k].appendChild(objB[k]);
		}
	}
}

function stringToDOM(str) {
	var tmpEl = document.createElement('ol');
	tmpEl.innerHTML = str;
	var elCollection = {};
	var navSectionEls = tmpEl.querySelectorAll('.nav-section');

// In IE8, `tmpEl.querySelectorAll('.nav-section')`does not work.
// This might be that `querySelector` is not live.
// If it does not work, fallback to `getElementsByTagName`,
// and manually iterate elements and filter by classname.

	if (navSectionEls.length > 0) {
		for (var k = 0, len = navSectionEls.length; k< len; k++) {
			var navSectionEl = navSectionEls[k];
			var navSectionName = navSectionEl.getAttribute('data-section');
			var navItemsEl = navSectionEl.querySelector('.nav-items');
			elCollection[navSectionName] = navItemsEl;
		}
	} else {
		var liEls = tmpEl.getElementsByTagName('li');

		for (var i = 0; i < liEls.length; i++) {
			var liEl = liEls[i];
			if (liEl.className.search(/nav-section/) > -1) {
				var sectionName = liEl.getAttribute('data-section');
				var olEls = liEl.getElementsByTagName('ol');
				for(var j = 0; j < olEls.length; j++) {
					var olEl = olEls[j];
					if (olEl.className.search(/nav-items/) !== -1) {
						var navItems = olEl;
						elCollection[sectionName] = navItems;
					}
				}
			}
		}
	}
	return elCollection;
}

var navEl = document.querySelector('.o-nav');
// MARK: If the page does not have navigation element, no need to do anything
if (navEl) {
	searchRedirect('#search-form');
	// callback(error, data)
	var ajax = {
		getData: function (url, callback) {
		  var xhr = new XMLHttpRequest();
		  xhr.onreadystatechange = function() {
		    if (xhr.readyState === 4) {
		      if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
		        // var type = xhr.getResponseHeader('Content-Type');
		        // if (type.indexOf('html') !== -1 || xhr.responseXML) {
		        // 	console.log('HTML or XML');
		        //   callback(null, xhr.responseXML);
		        // } else if (type === 'application/json') {
		        //   callback(null, JSON.parse(xhr.responseText));
		        // } else {
		        	// console.log('text');
		          callback(null, xhr.responseText);
		        // }
		      } else {
		        //console.log('Request was unsuccessful: ' + xhr.status);
		        callback(xhr.status);
		      }

		    } else {
		      //console.log('readyState: ' + xhr.readyState);
		    }
		  };

		  xhr.open('GET', url);
		  // xhr.responseType = 'document';
		  xhr.send(null);
		}
	};
	new Nav(navEl);
	var searchEl = navEl.querySelector('.o-nav__search');
	new Toggler(searchEl);
	var emptyNavSections = getEmptyNavSections(navEl);
	ajax.getData('/m/corp/ajax-nav.html?hhhh', function(error, data) {
		if (error) {return error;}
		var parsedDOM = stringToDOM(data);
		zipObject(emptyNavSections, parsedDOM);
	});
}<|endoftext|>


<commit_before>/*global chrome, $ */
'use strict';

var TourabuEx = TourabuEx || {};

/*
 Applies the config value read from the local storage in a popup.html at startup.
 Store the config values to local storage when form in the popup.html changed.
 Use config.get in config.js to access config values.
 config.jsはストレージの変更を監視する
 */
(function () {
    var storage = TourabuEx.storage,
        setting = document.querySelector('#setting'),
        DEFAULT_SETTING = function () {
            return {
                'setting': {
                    'notification': {}
                }
            };
        };

    function initialize() {
        storage.get('setting', function (s) {
            // 通知関係
            var notification = s.notification,
                k, i, l, os;

            // 保存されてた設定を反映
            for (k in notification) {
                if (notification.hasOwnProperty(k)) {
                    document.querySelector('#' + k).value = notification[k];
                }
            }

        });
    }

    window.addEventListener('load', initialize);

    setting.addEventListener('change', function (e) {
        var selects = document.querySelectorAll('#notification select'),
            s = DEFAULT_SETTING(),
            i, l = selects.length;

        for (i = 0; i < l; i++) {
            s.setting.notification[selects[i].id] = selects[i].value;
        }

        storage.set(s);
    });

    document.querySelector('#screenshot').addEventListener('click', function () {
        console.log('shot');
        chrome.runtime.sendMessage({type: 'capture/start'});
    });

    // screen shot hogehoge
    $('#screenshot').hide();

    chrome.runtime.sendMessage({type: 'popup/show'});

    chrome.runtime.onMessage.addListener(function(mes, sender) {
        if (mes.type === 'content/load') {
            $('#screenshot').show();
        }

        if (mes.type === 'capture/enable') {
            $('#screenshot').show();
        }
    });

    // widget mode
    $('#start-widget').click(function () {
        chrome.runtime.sendMessage({type: 'start/widget'});
    });
}());
<commit_msg>Change structure of setting object<commit_after>/*global chrome, $ */
'use strict';

var TourabuEx = TourabuEx || {};

/*
 Applies the config value read from the local storage in a popup.html at startup.
 Store the config values to local storage when form in the popup.html changed.
 Use config.get in config.js to access config values.
 config.jsはストレージの変更を監視する
 */
(function () {
    var storage = TourabuEx.storage,
        setting = document.querySelector('#setting'),
        DEFAULT_SETTING = function () {
            return {
                'setting': {
                 }
            };
        };

    function initialize() {
        storage.get('setting', function (s) {
            // 通知関係
            var k, i, l, os;

            // 保存されてた設定を反映
            for (k in s) {
                if (s.hasOwnProperty(k)) {
                    document.querySelector('#' + k).value = s[k];
                }
            }

        });
    }

    window.addEventListener('load', initialize);

    setting.addEventListener('change', function (e) {
        var selects = document.querySelectorAll('#notification select'),
            s = DEFAULT_SETTING(),
            i, l = selects.length;

        for (i = 0; i < l; i++) {
            s.setting[selects[i].id] = selects[i].value;
        }

        storage.set(s);
    });

    document.querySelector('#screenshot').addEventListener('click', function () {
        console.log('shot');
        chrome.runtime.sendMessage({type: 'capture/start'});
    });

    // screen shot hogehoge
    $('#screenshot').hide();

    chrome.runtime.sendMessage({type: 'popup/show'});

    chrome.runtime.onMessage.addListener(function(mes, sender) {
        if (mes.type === 'content/load') {
            $('#screenshot').show();
        }

        if (mes.type === 'capture/enable') {
            $('#screenshot').show();
        }
    });

    // widget mode
    $('#start-widget').click(function () {
        chrome.runtime.sendMessage({type: 'start/widget'});
    });
}());
<|endoftext|>


<commit_before>// Truth table functions and view
'use strict';

var m = require('mithril');
var _ = require('underscore');
var classNames = require('classnames');

var Table = {};

// Iterate through all possible true/false values for the given collection of
// variables
Table.forEachRow = function (variables, callback) {
  var currentVarValues = {};
  variables.forEach(function (variable) {
    // Variable values should be initialized to true because they will be
    // inverted before the callback is called for the first table row, making
    // the first permutation of variable values all false
    currentVarValues[variable.name] = true;
  });
  // If n corresponds to the number of variables, then there will always be 2^n
  // rows in the truth table (excluding the table head, of course)
  return _.times(Math.pow(2, variables.length), function (rowIndex) {
    variables.forEach(function (variable, varIndex) {
      // Alternate current variable values as needed
      if (rowIndex % Math.pow(2, variables.length - varIndex - 1) === 0) {
        currentVarValues[variable.name] = !currentVarValues[variable.name];
      }
    });
    return callback(currentVarValues);
  });
};

// Get the string value of the given boolean for display in the truth table
Table.getBoolStr = function (boolean) {
  if (boolean === true) {
    return 'T';
  } else if (boolean === false) {
    return 'F';
  } else {
    // Display U for null/undefined values
    return 'U';
  }
};

Table.Component = {};

Table.Component.controller = function () {
  return {
    getExpressionIndex: function (expressionElem) {
      var currentElem = expressionElem.parentNode.parentNode;
      var expressionIndex = -1;
      do {
        currentElem = currentElem.previousElementSibling;
        expressionIndex += 1;
      } while (currentElem !== null && currentElem.classList.contains('expression'));
      return expressionIndex;
    },
    updateExpressionString: function (ctrl, app, event) {
      var expression = app.expressions.get(ctrl.getExpressionIndex(event.target));
      expression.string = event.target.value;
      app.save();
    },
    addExpression: function (ctrl, app, event) {
      var expressionIndex = ctrl.getExpressionIndex(event.target);
      var expression = app.expressions.get(expressionIndex);
      app.expressions.insert(expressionIndex + 1, {
        string: expression.string
      });
      // Redraw the view to ensire the new expression element exists
      m.redraw();
      event.target
        .parentNode
        .parentNode
        .nextElementSibling
        .querySelector('input').focus();
      app.save();
    },
    removeExpression: function (ctrl, app, event) {
      app.expressions.remove(ctrl.getExpressionIndex(event.target));
      app.save();
    },
    handleControls: function (ctrl, app, event) {
      if (event.target.classList.contains('control-add')) {
        ctrl.addExpression(ctrl, app, event);
      } else if (event.target.classList.contains('control-remove')) {
        ctrl.removeExpression(ctrl, app, event);
      }
    }
  };
};

Table.Component.view = function (ctrl, app) {
  var nonEmptyVariables = app.variables.filter(function (variable) {
    return variable.name !== '';
  });
  // A cache to store expressions which are known to be invalid (so as to avoid
  // re-evaluating them later)
  var invalidExpressionCache = {};
  return m('table#truth-table', [
    m('thead', m('tr', {
      onclick: _.partial(ctrl.handleControls, ctrl, app),
      oninput: _.partial(ctrl.updateExpressionString, ctrl, app)
    }, [
      nonEmptyVariables.map(function (variable) {
        return m('th.variable', variable.name);
      }),
      app.expressions.map(function (expression) {
        return m('th.expression', m('div.has-controls', [
          m('div.control.control-add'),
          app.expressions.length > 1 ? m('div.control.control-remove') : null,
          m('input', {
            type: 'text',
            size: Math.max(1, expression.string.length),
            value: expression.string,
            autocapitalize: 'off',
            autocomplete: 'off',
            autocorrect: 'off',
            spellcheck: false
          })
        ]));
      })
    ])
  ),
  m('tbody', Table.forEachRow(nonEmptyVariables, function (varValues) {
    return m('tr', [
      nonEmptyVariables.map(function(variable) {
        var varValue = varValues[variable.name];
        return m('td', {
          class: classNames(
            {true: varValue === true},
            {false: varValue === false}
          )
        },
        Table.getBoolStr(varValue));
      }),
      app.expressions.map(function(expression) {
        var exprValue;
        // Don't re-evaluate expression if it is known to be invalid
        if (expression.string in invalidExpressionCache) {
          exprValue = null;
        } else {
          exprValue = expression.evaluate(varValues);
          if (exprValue === null) {
            // The value stored with the key in the cache doesn't really matter;
            // the cache itself functions more as a set than a dictionary
            invalidExpressionCache[expression.string] = true;
          }
        }
        return m('td', {
          class: classNames(
            {true: exprValue === true},
            {false: exprValue === false}
          )
        }, Table.getBoolStr(exprValue));
      })
    ]);
  }))
]);
};

module.exports = Table;
<commit_msg>Use '?' instead of 'U' for undefined table values<commit_after>// Truth table functions and view
'use strict';

var m = require('mithril');
var _ = require('underscore');
var classNames = require('classnames');

var Table = {};

// Iterate through all possible true/false values for the given collection of
// variables
Table.forEachRow = function (variables, callback) {
  var currentVarValues = {};
  variables.forEach(function (variable) {
    // Variable values should be initialized to true because they will be
    // inverted before the callback is called for the first table row, making
    // the first permutation of variable values all false
    currentVarValues[variable.name] = true;
  });
  // If n corresponds to the number of variables, then there will always be 2^n
  // rows in the truth table (excluding the table head, of course)
  return _.times(Math.pow(2, variables.length), function (rowIndex) {
    variables.forEach(function (variable, varIndex) {
      // Alternate current variable values as needed
      if (rowIndex % Math.pow(2, variables.length - varIndex - 1) === 0) {
        currentVarValues[variable.name] = !currentVarValues[variable.name];
      }
    });
    return callback(currentVarValues);
  });
};

// Get the string value of the given boolean for display in the truth table
Table.getBoolStr = function (boolean) {
  if (boolean === true) {
    return 'T';
  } else if (boolean === false) {
    return 'F';
  } else {
    return '?';
  }
};

Table.Component = {};

Table.Component.controller = function () {
  return {
    getExpressionIndex: function (expressionElem) {
      var currentElem = expressionElem.parentNode.parentNode;
      var expressionIndex = -1;
      do {
        currentElem = currentElem.previousElementSibling;
        expressionIndex += 1;
      } while (currentElem !== null && currentElem.classList.contains('expression'));
      return expressionIndex;
    },
    updateExpressionString: function (ctrl, app, event) {
      var expression = app.expressions.get(ctrl.getExpressionIndex(event.target));
      expression.string = event.target.value;
      app.save();
    },
    addExpression: function (ctrl, app, event) {
      var expressionIndex = ctrl.getExpressionIndex(event.target);
      var expression = app.expressions.get(expressionIndex);
      app.expressions.insert(expressionIndex + 1, {
        string: expression.string
      });
      // Redraw the view to ensire the new expression element exists
      m.redraw();
      event.target
        .parentNode
        .parentNode
        .nextElementSibling
        .querySelector('input').focus();
      app.save();
    },
    removeExpression: function (ctrl, app, event) {
      app.expressions.remove(ctrl.getExpressionIndex(event.target));
      app.save();
    },
    handleControls: function (ctrl, app, event) {
      if (event.target.classList.contains('control-add')) {
        ctrl.addExpression(ctrl, app, event);
      } else if (event.target.classList.contains('control-remove')) {
        ctrl.removeExpression(ctrl, app, event);
      }
    }
  };
};

Table.Component.view = function (ctrl, app) {
  var nonEmptyVariables = app.variables.filter(function (variable) {
    return variable.name !== '';
  });
  // A cache to store expressions which are known to be invalid (so as to avoid
  // re-evaluating them later)
  var invalidExpressionCache = {};
  return m('table#truth-table', [
    m('thead', m('tr', {
      onclick: _.partial(ctrl.handleControls, ctrl, app),
      oninput: _.partial(ctrl.updateExpressionString, ctrl, app)
    }, [
      nonEmptyVariables.map(function (variable) {
        return m('th.variable', variable.name);
      }),
      app.expressions.map(function (expression) {
        return m('th.expression', m('div.has-controls', [
          m('div.control.control-add'),
          app.expressions.length > 1 ? m('div.control.control-remove') : null,
          m('input', {
            type: 'text',
            size: Math.max(1, expression.string.length),
            value: expression.string,
            autocapitalize: 'off',
            autocomplete: 'off',
            autocorrect: 'off',
            spellcheck: false
          })
        ]));
      })
    ])
  ),
  m('tbody', Table.forEachRow(nonEmptyVariables, function (varValues) {
    return m('tr', [
      nonEmptyVariables.map(function(variable) {
        var varValue = varValues[variable.name];
        return m('td', {
          class: classNames(
            {true: varValue === true},
            {false: varValue === false}
          )
        },
        Table.getBoolStr(varValue));
      }),
      app.expressions.map(function(expression) {
        var exprValue;
        // Don't re-evaluate expression if it is known to be invalid
        if (expression.string in invalidExpressionCache) {
          exprValue = null;
        } else {
          exprValue = expression.evaluate(varValues);
          if (exprValue === null) {
            // The value stored with the key in the cache doesn't really matter;
            // the cache itself functions more as a set than a dictionary
            invalidExpressionCache[expression.string] = true;
          }
        }
        return m('td', {
          class: classNames(
            {true: exprValue === true},
            {false: exprValue === false}
          )
        }, Table.getBoolStr(exprValue));
      })
    ]);
  }))
]);
};

module.exports = Table;
<|endoftext|>


<commit_before>import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

const {
    inject,
    computed
} = Ember;

export default AjaxService.extend({
    auth: inject.service(),

    contentType: 'application/json; charset=utf-8',

    trustedHosts: [
        /outlook.office.com/,
        /graph.microsoft.com/,
        /online.lync.com/
    ],

    headers: computed('auth.msftAccessToken', function () {
        let headers = {};
        const token = this.get('auth.msftAccessToken');
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
        }
        return headers;
    })
});
<commit_msg>Add purecloud hosts as trusted<commit_after>import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

const {
    inject,
    computed
} = Ember;

export default AjaxService.extend({
    auth: inject.service(),

    contentType: 'application/json; charset=utf-8',

    trustedHosts: [
        /outlook.office.com/,
        /graph.microsoft.com/,
        /online.lync.com/,
        /api.(?:inindca|mypurecloud).(?:com|jp).?(?:ie|au)?/
    ],

    headers: computed('auth.msftAccessToken', function () {
        let headers = {};
        const token = this.get('auth.msftAccessToken');
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
        }
        return headers;
    })
});
<|endoftext|>


<commit_before>var NavFrame = function(location, content) {
  var self = this;
  var excerptSize = 2;
  var items = location.split('#L-');
  this.lineNumber = (items.length>1)?parseInt(items[1]):0;
  this.location = location.replace(/.*?\/file\//, "");
  this.content = content;
  function getLines(text, linenum, size) {
    if (linenum === 0) {
      // don't interested in a specific line
      return "";
    }
    text = text.substring(28, text.length-13);
    var lines = text.split('\n');
    var windowSize = 1+2*size;
    var lineStart = linenum - size;
    lineStart = Math.min(lines.length - windowSize, lineStart);
    lineStart = Math.max(0, lineStart);
    var segment =  lines.slice(lineStart, lineStart + windowSize).join('\n');
    return segment.replace(/foo/g, "excerpt");
  };
  this.excerpt = getLines(content, this.lineNumber, excerptSize);
  this.scrollTop = 0;
};

var PSBViewModel = function() {
  var self = this;
  var EMPTYFRAME = new NavFrame("", "");
  this.navStack = ko.observableArray();
  this.currentFrame = ko.observable(EMPTYFRAME);
  this.searchResults = ko.observableArray();
  this.searchTerm = ko.observable('');

  this.pushFrame = function(navFrame) {
    self.navStack.push(navFrame);
    self.currentFrame(navFrame);
    showNavFramePane();
  };

  this.clearAddNewFrame = function(url, file_content) {
    self.navStack.splice(0);
    self.addNewFrame(url, file_content);
  };

  this.addNewFrame = function(url, file_content) {
    var newFrame = new NavFrame(url, file_content);
    self.pushFrame(newFrame);
  };

  // make sure the #nav-stack tab is shown. This could be a custom-binding,
  // but no one has implemented it, so for now, we just manipulate the DOM
  // directly.
  // TODO: Create a knockout custome binding for bootstrap tab
  function showNavFramePane() {
    $('#nav-stack-btn').tab('show');
  };

  this.scrollToBottom = function(domNode, i, data) {
    domNode.scrollIntoView();
  };

  this.showFrame = function(navFrame) {
    self.currentFrame(navFrame);
  };

  this.deleteFrame = function(value) {
    var idx = self.navStack.indexOf(value);
    if (idx != -1) {
      self.navStack.splice(idx);
    }
    if (idx > 0) {
      self.currentFrame(self.navStack()[idx-1]);
    } else {
      self.currentFrame(EMPTYFRAME);
    }
  };
};

(function setup() {
  $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    options.async = true;
  });
  // populate the project directory tree
  $.get('/file/', function(data) {
    $('#directory-content').jstree({
      "types" : {
        "default" : {
          "icon" : "glyphicon glyphicon-folder-close"
        },
        "file" : {
          "icon" : "glyphicon glyphicon-file"
        }
      },
      "plugins" : [ "types" ],
      'core' : {
        'data' : data
      }
    }).on('loaded.jstree', function() {
      $('#directory-content').jstree('open_node', '#root');
    });
  });
  $('#directory-content').on('select_node.jstree', function(event, data) {
      if (data.node.type === 'file') {
        var url = data.node.a_attr.href;
        $.get(url, function(file_content) {
          psbViewModel.clearAddNewFrame(url, file_content);
        });
      }
    });
  $("#nav-stack").on("click", ".nav-frame", function(e) {
    var target = e.target;
    psbViewModel.showFrame(ko.dataFor(target));
  });
})();

var psbViewModel = new PSBViewModel();

ko.applyBindings(psbViewModel);
<commit_msg>In project tree, clicking directory node will expand/collapse the node.<commit_after>var NavFrame = function(location, content) {
  var self = this;
  var excerptSize = 2;
  var items = location.split('#L-');
  this.lineNumber = (items.length>1)?parseInt(items[1]):0;
  this.location = location.replace(/.*?\/file\//, "");
  this.content = content;
  function getLines(text, linenum, size) {
    if (linenum === 0) {
      // don't interested in a specific line
      return "";
    }
    text = text.substring(28, text.length-13);
    var lines = text.split('\n');
    var windowSize = 1+2*size;
    var lineStart = linenum - size;
    lineStart = Math.min(lines.length - windowSize, lineStart);
    lineStart = Math.max(0, lineStart);
    var segment =  lines.slice(lineStart, lineStart + windowSize).join('\n');
    return segment.replace(/foo/g, "excerpt");
  };
  this.excerpt = getLines(content, this.lineNumber, excerptSize);
  this.scrollTop = 0;
};

var PSBViewModel = function() {
  var self = this;
  var EMPTYFRAME = new NavFrame("", "");
  this.navStack = ko.observableArray();
  this.currentFrame = ko.observable(EMPTYFRAME);
  this.searchResults = ko.observableArray();
  this.searchTerm = ko.observable('');

  this.pushFrame = function(navFrame) {
    self.navStack.push(navFrame);
    self.currentFrame(navFrame);
    showNavFramePane();
  };

  this.clearAddNewFrame = function(url, file_content) {
    self.navStack.splice(0);
    self.addNewFrame(url, file_content);
  };

  this.addNewFrame = function(url, file_content) {
    var newFrame = new NavFrame(url, file_content);
    self.pushFrame(newFrame);
  };

  // make sure the #nav-stack tab is shown. This could be a custom-binding,
  // but no one has implemented it, so for now, we just manipulate the DOM
  // directly.
  // TODO: Create a knockout custome binding for bootstrap tab
  function showNavFramePane() {
    $('#nav-stack-btn').tab('show');
  };

  this.scrollToBottom = function(domNode, i, data) {
    domNode.scrollIntoView();
  };

  this.showFrame = function(navFrame) {
    self.currentFrame(navFrame);
  };

  this.deleteFrame = function(value) {
    var idx = self.navStack.indexOf(value);
    if (idx != -1) {
      self.navStack.splice(idx);
    }
    if (idx > 0) {
      self.currentFrame(self.navStack()[idx-1]);
    } else {
      self.currentFrame(EMPTYFRAME);
    }
  };
};

(function setup() {
  $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    options.async = true;
  });
  // populate the project directory tree
  $.get('/file/', function(data) {
    $('#directory-content').jstree({
      "types" : {
        "default" : {
          "icon" : "glyphicon glyphicon-folder-close"
        },
        "file" : {
          "icon" : "glyphicon glyphicon-file"
        }
      },
      "plugins" : [ "types" ],
      'core' : {
        'data' : data
      }
    }).on('loaded.jstree', function() {
      $('#directory-content').jstree('open_node', '#root');
    });
  });
  $('#directory-content').on('select_node.jstree', function(event, data) {
      if (data.node.type === 'file') {
        var url = data.node.a_attr.href;
        $.get(url, function(file_content) {
          psbViewModel.clearAddNewFrame(url, file_content);
        });
      } else {
        data.instance.toggle_node(data.node);
      }
    });
  $("#nav-stack").on("click", ".nav-frame", function(e) {
    var target = e.target;
    psbViewModel.showFrame(ko.dataFor(target));
  });
})();

var psbViewModel = new PSBViewModel();

ko.applyBindings(psbViewModel);
<|endoftext|>


<commit_before>module("Double click protection", {
  setup: function(){
    this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>');

    $('#qunit-fixture').append(this.$form);
  }
});

test('clicking submit input disables the button', function() {
  GOVUK.doubleClickProtection();

  var $submit_tag = this.$form.find('input[type=submit]');
  ok(!$submit_tag.prop('disabled'));

  this.$form.on('submit', function (e) {
    e.preventDefault();
    ok($submit_tag.prop('disabled'));
  });

  $submit_tag.click();
});

test('clicking submit input creates a hidden input with the same name and value', function() {
  GOVUK.doubleClickProtection();

  var $submit_tag = this.$form.find('input[type=submit]');

  this.$form.on('submit', function (e) {
    e.preventDefault();
    equal($.find('form input[type=hidden][name=input_name][value=Save]').length, 1);
  });

  $submit_tag.click();
});
<commit_msg>Don't double-load the double click protection<commit_after>module("Double click protection", {
  setup: function(){
    this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>');

    $('#qunit-fixture').append(this.$form);
  }
});

test('clicking submit input disables the button', function() {
  var $submit_tag = this.$form.find('input[type=submit]');
  ok(!$submit_tag.prop('disabled'));

  this.$form.on('submit', function (e) {
    e.preventDefault();
    ok($submit_tag.prop('disabled'));
  });

  $submit_tag.click();
});

test('clicking submit input creates a hidden input with the same name and value', function() {
  var $submit_tag = this.$form.find('input[type=submit]');

  this.$form.on('submit', function (e) {
    e.preventDefault();
    equal($.find('form input[type=hidden][name=input_name][value=Save]').length, 1);
  });

  $submit_tag.click();
});
<|endoftext|>


<commit_before>'use strict';

describe('MwListCollectionFilter', function() {
  var MwListCollectionFilter;

  beforeEach(module('mwCollection'));

  beforeEach(module(function($provide) {
    var LocalForage = {
      getItem: function(identifier) {
        return {
          then: function() {
            return null;
          }
        };
      }
    };
    $provide.value('LocalForage', LocalForage);

    function MCAPFilterHolder() {};
    MCAPFilterHolder.prototype.get = function fn() {
    };
    $provide.value('MCAPFilterHolder', MCAPFilterHolder);

    function MCAPFilterHolders(irrelevant, type) {
      this.type = type;
    };
    $provide.value('MCAPFilterHolders', MCAPFilterHolders);
  }));

  beforeEach(inject(function(_MwListCollectionFilter_) {
    MwListCollectionFilter = _MwListCollectionFilter_;
  }));

  describe('fetching applied filters', function() {
    it('returns null if no applied filter is in localstorage', function() {
      var appliedFilter = new MwListCollectionFilter('foo').fetchAppliedFilter();

      expect(appliedFilter).toBe(null);
    });
  });

});<commit_msg>MDM-7712: return filter in localstorage if present<commit_after>'use strict';

describe('MwListCollectionFilter', function() {
  var MwListCollectionFilter,
    filterInLocalStorage;

  beforeEach(module('mwCollection'));

  beforeEach(module(function($provide) {
    var LocalForage = {
      getItem: function(identifier) {
        return {
          then: function() {
            return filterInLocalStorage;
          }
        };
      }
    };
    $provide.value('LocalForage', LocalForage);

    function MCAPFilterHolder() {};
    MCAPFilterHolder.prototype.get = function fn() {
    };
    $provide.value('MCAPFilterHolder', MCAPFilterHolder);

    function MCAPFilterHolders(irrelevant, type) {
      this.type = type;
    };
    $provide.value('MCAPFilterHolders', MCAPFilterHolders);
  }));

  beforeEach(inject(function(_MwListCollectionFilter_) {
    MwListCollectionFilter = _MwListCollectionFilter_;
  }));

  describe('fetching applied filters', function() {
    it('returns null if no applied filter is in localstorage', function() {
      filterInLocalStorage = null;

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).toBeNull();
    });

    it('returns filter in localstorage if present', function() {
      filterInLocalStorage = '{"content":"IRRELEVANT"}';

      var appliedFilter = new MwListCollectionFilter('IRRELEVANT').fetchAppliedFilter();

      expect(appliedFilter).not.toBeNull();
    });
  });

});<|endoftext|>


<commit_before>module.exports = function () {
    var path = require('path'),
        basePath = path.resolve('.'),
        TodoPage = require('../../po/todoPage.po'),
        page,
        configuration = {
            afterAdd: 'afterAdd',
            afterArchive: 'afterArchive',
            afterCheck: 'afterCheck'
        };

    this.setDefaultTimeout(60 * 1000);

    this.Given(/^I have todos$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'initial');
        ngApimock.addMockModule();

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^I have new todo$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'initial');
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-post.json'), 'success');
        ngApimock.addMockModule();

        browser.get('/');
        callback();
    });

    this.Given(/^I have completed todos that has not been archived yet$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'afterAdd');
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-delete.json'), 'success');
        ngApimock.addMockModule();

        browser.get('/');
        callback();
    });

    this.Given(/^I have completed a todo$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'afterArchive');
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-put.json'), 'success');
        ngApimock.addMockModule();

        browser.get('/');
        callback();
    });

    this.Given(/^an error occurred while fetching the todos$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'oops');
        ngApimock.addMockModule();

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^an error occurred while adding a todo$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'initial');
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-post.json'), 'oops');
        ngApimock.addMockModule();

        configuration.afterAdd = 'initial';

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^an error occurred while archiving a todo$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'initial');
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-delete.json'), 'oops');
        ngApimock.addMockModule();

        configuration.afterArchive = 'initial';

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^an error occurred while completing a todo$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), 'initial');
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-put.json'), 'oops');
        ngApimock.addMockModule();

        configuration.afterCheck = 'initial';

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.When(/^I add the todo$/, function (callback) {

        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), configuration.afterAdd);
        page.actions.add('another todo').then(function () {
            callback();
        });
    });

    this.When(/^I archive the todos$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), configuration.afterArchive);
        page.actions.archive().then(function () {
            callback();
        });
    });

    this.When(/^I check the todo as completed$/, function (callback) {
        ngApimock.selectScenario(require(basePath + '/test/mocks/api-todos-all.json'), configuration.afterCheck);
        page.todos.get(2).check().then(function () {
            callback();
        });
    });

    this.Then(/^the total number of todos is (.*)$/, function (numberOfTodos, callback) {
        expect(page.information.total).to.eventually.equal(numberOfTodos).and.notify(callback);
    });

    this.Then(/^the total number of remaining uncompleted todos is (.*)$/, function (numberOfUncompletedTodos, callback) {
        expect(page.information.remaining).to.eventually.equal(numberOfUncompletedTodos).and.notify(callback);
    });

    this.Then(/^the total number of completed but unarchived todos is (\d+)$/, function (numberOfUnarchivedTodos, callback) {
        page.information.total.then(function (total) {
            page.information.remaining.then(function (remaining) {
                expect((total - remaining)).to.equal(parseInt(numberOfUnarchivedTodos));
                callback();
            });
        });
    });

    this.Then(/^todo (.*) with description (.*) should be present$/, function (index, description, callback) {
        expect(page.todos.get(index).description).to.eventually.equal(description).and.notify(callback);
    });

    this.Then(/^todo (.*) should be marked as completed (.*)$/, function (index, completed, callback) {
        expect(page.todos.get(index).isChecked()).to.eventually.be.equal(completed === 'true').and.notify(callback);
    });
};<commit_msg>get mockdata once.<commit_after>module.exports = function () {
    var path = require('path'),
        basePath = path.resolve('.'),
        TodoPage = require('../../po/todoPage.po'),
        page,
        configuration = {
            afterAdd: 'afterAdd',
            afterArchive: 'afterArchive',
            afterCheck: 'afterCheck'
        };

    this.setDefaultTimeout(60 * 1000);

    var mockData = {
        todos: require(basePath + '/test/mocks/api-todos-all.json'),
        addTodo: require(basePath + '/test/mocks/api-todos-post.json'),
        updateTodo: require(basePath + '/test/mocks/api-todos-put.json'),
        deleteTodo: require(basePath + '/test/mocks/api-todos-delete.json')
    };

    this.Given(/^I have todos$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'initial');
        ngApimock.addMockModule();

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^I have new todo$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'initial');
        ngApimock.selectScenario(mockData.addTodo, 'success');
        ngApimock.addMockModule();

        browser.get('/');
        callback();
    });

    this.Given(/^I have completed todos that has not been archived yet$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'afterAdd');
        ngApimock.selectScenario(mockData.deleteTodo, 'success');
        ngApimock.addMockModule();

        browser.get('/');
        callback();
    });

    this.Given(/^I have completed a todo$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'afterArchive');
        ngApimock.selectScenario(mockData.updateTodo, 'success');
        ngApimock.addMockModule();

        browser.get('/');
        callback();
    });

    this.Given(/^an error occurred while fetching the todos$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'oops');
        ngApimock.addMockModule();

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^an error occurred while adding a todo$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'initial');
        ngApimock.selectScenario(mockData.addTodo, 'oops');
        ngApimock.addMockModule();

        configuration.afterAdd = 'initial';

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^an error occurred while archiving a todo$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'initial');
        ngApimock.selectScenario(mockData.deleteTodo, 'oops');
        ngApimock.addMockModule();

        configuration.afterArchive = 'initial';

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.Given(/^an error occurred while completing a todo$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, 'initial');
        ngApimock.selectScenario(mockData.updateTodo, 'oops');
        ngApimock.addMockModule();

        configuration.afterCheck = 'initial';

        browser.get('/');
        page = new TodoPage(element(by.id('todo')));
        callback();
    });

    this.When(/^I add the todo$/, function (callback) {

        ngApimock.selectScenario(mockData.todos, configuration.afterAdd);
        page.actions.add('another todo').then(function () {
            callback();
        });
    });

    this.When(/^I archive the todos$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, configuration.afterArchive);
        page.actions.archive().then(function () {
            callback();
        });
    });

    this.When(/^I check the todo as completed$/, function (callback) {
        ngApimock.selectScenario(mockData.todos, configuration.afterCheck);
        page.todos.get(2).check().then(function () {
            callback();
        });
    });

    this.Then(/^the total number of todos is (.*)$/, function (numberOfTodos, callback) {
        expect(page.information.total).to.eventually.equal(numberOfTodos).and.notify(callback);
    });

    this.Then(/^the total number of remaining uncompleted todos is (.*)$/, function (numberOfUncompletedTodos, callback) {
        expect(page.information.remaining).to.eventually.equal(numberOfUncompletedTodos).and.notify(callback);
    });

    this.Then(/^the total number of completed but unarchived todos is (\d+)$/, function (numberOfUnarchivedTodos, callback) {
        page.information.total.then(function (total) {
            page.information.remaining.then(function (remaining) {
                expect((total - remaining)).to.equal(parseInt(numberOfUnarchivedTodos));
                callback();
            });
        });
    });

    this.Then(/^todo (.*) with description (.*) should be present$/, function (index, description, callback) {
        expect(page.todos.get(index).description).to.eventually.equal(description).and.notify(callback);
    });

    this.Then(/^todo (.*) should be marked as completed (.*)$/, function (index, completed, callback) {
        expect(page.todos.get(index).isChecked()).to.eventually.be.equal(completed === 'true').and.notify(callback);
    });
};<|endoftext|>


<commit_before>var assert = require( 'assert' );

module.exports = {
	description: 'disallows non-top-level exports',
	error: function ( err ) {
		assert.ok( false, 'TODO: pick an error message' );
	}
};
<commit_msg>fix test<commit_after>var path = require( 'path' );
var assert = require( 'assert' );

module.exports = {
	description: 'disallows non-top-level exports',
	error: function ( err ) {
		assert.equal( err.file, path.resolve( __dirname, 'main.js' ) );
		assert.deepEqual( err.loc, { line: 2, column: 2 });
		assert.ok( /may only appear at the top level/.test( err.message ) );
	}
};
<|endoftext|>


<commit_before>'use strict';

describe('', function () {

    var moduleUnderTest, httpProvider;
    var dependencies = [];

    var hasModule = function (module) {
        return dependencies.indexOf(module) >= 0;
    };

    beforeEach(module('coreGamesIonicUi.config', function($httpProvider) {
        console.log('init');
        httpProvider = $httpProvider;
    }));

    beforeEach(function () {
        // Get module
        moduleUnderTest = angular.module('coreGamesIonicUi');
        dependencies = moduleUnderTest.requires;
        inject();
    });

    it('should enable credentials', function() {
        expect(httpProvider.defaults.withCredentials).toEqual(true);
    });

    it('should load outside dependencies', function () {
        expect(hasModule('coreGamesUi')).toBeTruthy();
        expect(hasModule('ngCordova')).toBeTruthy();
        expect(hasModule('ionic')).toBeTruthy();
    });

    it('should load config module', function () {
        expect(hasModule('coreGamesIonicUi.config')).toBeTruthy();
    });

    it('should load interceptors module', function () {
        expect(hasModule('coreGamesIonicUi.interceptors')).toBeTruthy();
    });

    it('should load controllers module', function () {
        expect(hasModule('coreGamesIonicUi.controllers')).toBeTruthy();
    });

    it('should load services module', function () {
        expect(hasModule('coreGamesIonicUi.services')).toBeTruthy();
    });

});<commit_msg>more registration tests<commit_after>'use strict';

describe('', function () {

    var moduleUnderTest, httpProvider;
    var dependencies = [];

    var hasModule = function (module) {
        return dependencies.indexOf(module) >= 0;
    };

    beforeEach(module('coreGamesIonicUi.config', function($httpProvider) {
        httpProvider = $httpProvider;
    }));

    beforeEach(function () {
        // Get module
        moduleUnderTest = angular.module('coreGamesIonicUi');
        dependencies = moduleUnderTest.requires;
        inject();
    });

    it('should enable credentials', function() {
        expect(httpProvider.defaults.withCredentials).toEqual(true);
    });

    it('should load outside dependencies', function () {
        expect(hasModule('coreGamesUi')).toBeTruthy();
        expect(hasModule('ngCordova')).toBeTruthy();
        expect(hasModule('ionic')).toBeTruthy();
    });

    it('should load config module', function () {
        expect(hasModule('coreGamesIonicUi.config')).toBeTruthy();
    });

    it('should load interceptors module', function () {
        expect(hasModule('coreGamesIonicUi.interceptors')).toBeTruthy();
    });

    it('should load controllers module', function () {
        expect(hasModule('coreGamesIonicUi.controllers')).toBeTruthy();
    });

    it('should load services module', function () {
        expect(hasModule('coreGamesIonicUi.services')).toBeTruthy();
    });

});<|endoftext|>


<commit_before>const sql = require('sql-bricks-postgres');

function getLatestRpcSpecId() {
    return sql.select('id')
        .from('rpc_spec')
        .orderBy('created_ts DESC')
        .limit(1);
}

function permissionRelationsNoModules(isProduction, hideDeleted = false) {
    let base = sql.select('child_permission_name, parent_permission_name, false::BOOLEAN AS is_custom')
        .from('permission_relations')
        .innerJoin('permissions', {
            'permissions.name': 'permission_relations.child_permission_name'
        })
        .where(
            sql.notEq('type', 'MODULE')
        );

    // retrieve root custom vehicle data items applicable only to the production status/environment
    let customVehicleDataProduction = sql.select('vcvd.name AS child_permission_name, t.parent_permission_name, true::BOOLEAN AS is_custom')
        .from('view_custom_vehicle_data vcvd')
        .crossJoin(sql(`(VALUES ('GetVehicleData'), ('OnVehicleData'), ('SubscribeVehicleData'), ('UnsubscribeVehicleData')) AS t(parent_permission_name)`))
        .where({
            'vcvd.status': 'PRODUCTION',
            'vcvd.is_deleted': false, // production always hides deleted items
            'vcvd.parent_id': null
        });

    // this query gets the most recent custom vehicle data items, regardless of status/environment
    const customVehicleDataGroup = sql.select('max(id) AS id', 'name', 'parent_id')
        .from('view_custom_vehicle_data')
        .where({
            'parent_id': null
        })
        .groupBy('name, parent_id');

    // retrieve root custom vehicle data items applicable to the staging status/environment
    let customVehicleDataStaging = sql.select('vcvd.name AS child_permission_name, t.parent_permission_name, true::BOOLEAN AS is_custom')
        .from('(' + customVehicleDataGroup + ') cvdg')
        .join('view_custom_vehicle_data vcvd', {
            'vcvd.id': 'cvdg.id'
        })
        .crossJoin(sql(`(VALUES ('GetVehicleData'), ('OnVehicleData'), ('SubscribeVehicleData'), ('UnsubscribeVehicleData')) AS t(parent_permission_name)`));

    // hiding deleted applies to staging
    if (hideDeleted) {
        customVehicleDataStaging.where({
            'vcvd.is_deleted': false
        });
    } else {
        customVehicleDataStaging.where(
            sql.or({
                'vcvd.is_deleted': false,
                'vcvd.status': 'STAGING'
            })
        );
    }

    return base.union(isProduction ? customVehicleDataProduction : customVehicleDataStaging)
        .orderBy('is_custom ASC')
        .toString();
}

const rpcs = sql.select('*')
    .from('permissions')
    .where({
        type: 'RPC'
    })
    .toString();

const hmiLevels = sql.select('hmi_level_enum AS id')
    .from('hmi_levels')
    .innerJoin('hmi_level_conversion', {
        'hmi_levels.id': 'hmi_level_conversion.hmi_level_text'
    })
    .toString();

const getGroupNamesStaging = sql.select('property_name')
    .from('(' + getFuncGroupStatus(false) + ') fgi')
    .toString();

function getFuncGroupId (id) {
    return sql.select('*').from('function_group_info')
        .where({
            id: id
        })
        .orderBy('LOWER(function_group_info.property_name)')
        .toString();
}

function getFuncGroupHmiLevelsId (id) {
    return sql.select('function_group_id', 'permission_name', 'hmi_level')
        .from('function_group_hmi_levels')
        .where({
            function_group_id: id
        })
        .toString();
}

let funcGroupParamOr = function() {
    return sql.or(
        // is a native Vehicle Data param
        sql.exists(
            sql.select()
            .from('rpc_spec_param rsp')
            .join('rpc_spec_type rst', {
                'rst.id': 'rsp.rpc_spec_type_id'
            })
            .where({
                'rst.rpc_spec_id': getLatestRpcSpecId(),
                'rst.element_type': 'FUNCTION',
                'rst.name': sql('fgp.rpc_name'),
                'rsp.name': sql('fgp.parameter')
            })
            .where(
                sql.in('rst.message_type', [
                    'response',
                    'notification'
                ])
            )
        ),
        // is a custom vehicle data param in the given environment
        sql.exists(
            sql.select()
            .from('view_custom_vehicle_data vcvd')
            .where({
                'vcvd.parent_id': null,
                'vcvd.is_deleted': false,
                'vcvd.name': sql('fgp.parameter')
            })
            .where(
                sql.or(
                    {
                        'vcvd.status': 'PRODUCTION'
                    },
                    {
                        'vcvd.status': sql('CASE WHEN fgi.status=\'STAGING\' THEN \'STAGING\'::edit_status ELSE \'PRODUCTION\'::edit_status END')
                    }
                )
            )
        )
    );
}

function getFuncGroupParametersId (id) {
    let query = sql.select('fgp.function_group_id', 'fgp.rpc_name', 'fgp.parameter')
        .from('function_group_parameters fgp')
        .join('function_group_info fgi', {
            'fgi.id': 'fgp.function_group_id'
        })
        .where(
            sql.and(
                {
                    'fgp.function_group_id': id
                },
                funcGroupParamOr()
            )
        )
        .toString();

    return query.toString();
}

function getFuncGroupStatus (isProduction, hideDeleted = false) {
    const funcGroupsProduction = sql.select('*')
        .from('view_function_group_info')
        .where({
            status: 'PRODUCTION',
            'is_deleted': false
        })
        .orderBy('LOWER(view_function_group_info.property_name)');

    const funcGroupsGroup = sql.select('max(id) AS id', 'property_name')
        .from('view_function_group_info')
        .groupBy('property_name');

    let funcGroupsStaging = sql.select('view_function_group_info.*')
        .from('(' + funcGroupsGroup + ') vfgi')
        .innerJoin('view_function_group_info', {
            'view_function_group_info.id': 'vfgi.id'
        });

        if (hideDeleted) {
            funcGroupsStaging.where(
                {
                    'is_deleted': false
                }
            );
        }
        else {
            funcGroupsStaging.where(
                sql.or({
                    'is_deleted': false,
                    'status': 'STAGING'
                })
            );
        }

        funcGroupsStaging = funcGroupsStaging.orderBy('LOWER(view_function_group_info.property_name)');

    if (isProduction) {
        //filter out so only production entries exist
        return funcGroupsProduction;
    }
    else {
        //filter out based on highest id
        return funcGroupsStaging;
    }
}

function getFuncGroupHmiLevelsStatus (isProduction, hideDeleted = false) {
    return sql.select('function_group_id', 'permission_name', 'hmi_level')
        .select(
            '(' + sql.select('COUNT(pr.parent_permission_name)')
                .from('permission_relations pr')
                .join('permissions p', {
                    'p.name': 'pr.child_permission_name'
                })
                .where({
                    'pr.parent_permission_name': sql('function_group_hmi_levels.permission_name'),
                    'p.type': 'PARAMETER'
                })
                .toString()
            + ') AS possible_parameter_count'
        )
        .from('(' + getFuncGroupStatus(isProduction, hideDeleted) + ') fgi')
        .innerJoin('function_group_hmi_levels', {
            'fgi.id': 'function_group_hmi_levels.function_group_id'
        })
        .toString();
}

function getFuncGroupParametersStatus (isProduction, hideDeleted = false) {
    return sql.select('fgp.function_group_id', 'fgp.rpc_name', 'fgp.parameter')
        .from('(' + getFuncGroupStatus(isProduction, hideDeleted) + ') fgiv')
        .join('function_group_info fgi', {
            'fgi.id': 'fgiv.id'
        })
        .join('function_group_parameters fgp', {
            'fgiv.id': 'fgp.function_group_id'
        })
        .where(
            funcGroupParamOr()
        )
        .toString();
}

function getFuncGroupsByIdsStagingFilter (ids) {
    return sql.select('*')
        .from('function_group_info')
        .where(
            sql.and(
                sql.in('id', ids),
                {
                    status: 'STAGING'
                }
            )
        )
        .toString()
}

function getFuncGroupHmiLevelsByIdsStagingFilter (ids) {
    return sql.select('function_group_hmi_levels.*')
        .from('function_group_hmi_levels')
        .innerJoin('function_group_info', {
            'function_group_info.id': 'function_group_hmi_levels.function_group_id'
        })
        .where(
            sql.and(
                sql.in('id', ids),
                {
                    status: 'STAGING'
                }
            )
        )
        .toString();
}

function getFuncGroupParametersByIdsStagingFilter (ids) {
    return sql.select('fgp.*')
        .from('function_group_parameters fgp')
        .innerJoin('function_group_info fgi', {
            'fgi.id': 'fgp.function_group_id'
        })
        .where(
            sql.and(
                sql.in('id', ids),
                {
                    'fgi.status': 'STAGING'
                },
                funcGroupParamOr()
            )
        )
        .toString();
}

module.exports = {
    rpcs: rpcs,
    hmiLevels: hmiLevels,
    permissionRelationsNoModules: permissionRelationsNoModules,
    getGroupNamesStaging: getGroupNamesStaging,
    getFuncGroup: {
        base: {
            idFilter: getFuncGroupId,
            statusFilter: getFuncGroupStatus,
            ids: getFuncGroupsByIdsStagingFilter
        },
        hmiLevels: {
            idFilter: getFuncGroupHmiLevelsId,
            statusFilter: getFuncGroupHmiLevelsStatus,
            ids: getFuncGroupHmiLevelsByIdsStagingFilter
        },
        parameters: {
            idFilter: getFuncGroupParametersId,
            statusFilter: getFuncGroupParametersStatus,
            ids: getFuncGroupParametersByIdsStagingFilter
        }
    }
}

<commit_msg>+ comment for behavioral clarity<commit_after>const sql = require('sql-bricks-postgres');

function getLatestRpcSpecId() {
    return sql.select('id')
        .from('rpc_spec')
        .orderBy('created_ts DESC')
        .limit(1);
}

function permissionRelationsNoModules(isProduction, hideDeleted = false) {
    let base = sql.select('child_permission_name, parent_permission_name, false::BOOLEAN AS is_custom')
        .from('permission_relations')
        .innerJoin('permissions', {
            'permissions.name': 'permission_relations.child_permission_name'
        })
        .where(
            sql.notEq('type', 'MODULE')
        );

    // retrieve root custom vehicle data items applicable only to the production status/environment
    let customVehicleDataProduction = sql.select('vcvd.name AS child_permission_name, t.parent_permission_name, true::BOOLEAN AS is_custom')
        .from('view_custom_vehicle_data vcvd')
        .crossJoin(sql(`(VALUES ('GetVehicleData'), ('OnVehicleData'), ('SubscribeVehicleData'), ('UnsubscribeVehicleData')) AS t(parent_permission_name)`))
        .where({
            'vcvd.status': 'PRODUCTION',
            'vcvd.is_deleted': false, // production always hides deleted items
            'vcvd.parent_id': null
        });

    // this query gets the most recent custom vehicle data items, regardless of status/environment
    const customVehicleDataGroup = sql.select('max(id) AS id', 'name', 'parent_id')
        .from('view_custom_vehicle_data')
        .where({
            'parent_id': null
        })
        .groupBy('name, parent_id');

    // retrieve root custom vehicle data items applicable to the staging status/environment
    let customVehicleDataStaging = sql.select('vcvd.name AS child_permission_name, t.parent_permission_name, true::BOOLEAN AS is_custom')
        .from('(' + customVehicleDataGroup + ') cvdg')
        .join('view_custom_vehicle_data vcvd', {
            'vcvd.id': 'cvdg.id'
        })
        .crossJoin(sql(`(VALUES ('GetVehicleData'), ('OnVehicleData'), ('SubscribeVehicleData'), ('UnsubscribeVehicleData')) AS t(parent_permission_name)`));

    // hiding deleted applies to staging
    if (hideDeleted) {
        customVehicleDataStaging.where({
            'vcvd.is_deleted': false
        });
    } else {
        customVehicleDataStaging.where(
            sql.or({
                'vcvd.is_deleted': false,
                'vcvd.status': 'STAGING'
            })
        );
    }

    return base.union(isProduction ? customVehicleDataProduction : customVehicleDataStaging)
        .orderBy('is_custom ASC')
        .toString();
}

const rpcs = sql.select('*')
    .from('permissions')
    .where({
        type: 'RPC'
    })
    .toString();

const hmiLevels = sql.select('hmi_level_enum AS id')
    .from('hmi_levels')
    .innerJoin('hmi_level_conversion', {
        'hmi_levels.id': 'hmi_level_conversion.hmi_level_text'
    })
    .toString();

const getGroupNamesStaging = sql.select('property_name')
    .from('(' + getFuncGroupStatus(false) + ') fgi')
    .toString();

function getFuncGroupId (id) {
    return sql.select('*').from('function_group_info')
        .where({
            id: id
        })
        .orderBy('LOWER(function_group_info.property_name)')
        .toString();
}

function getFuncGroupHmiLevelsId (id) {
    return sql.select('function_group_id', 'permission_name', 'hmi_level')
        .from('function_group_hmi_levels')
        .where({
            function_group_id: id
        })
        .toString();
}

let funcGroupParamOr = function() {
    return sql.or(
        // is a native Vehicle Data param
        sql.exists(
            sql.select()
            .from('rpc_spec_param rsp')
            .join('rpc_spec_type rst', {
                'rst.id': 'rsp.rpc_spec_type_id'
            })
            .where({
                'rst.rpc_spec_id': getLatestRpcSpecId(),
                'rst.element_type': 'FUNCTION',
                'rst.name': sql('fgp.rpc_name'),
                'rsp.name': sql('fgp.parameter')
            })
            .where(
                sql.in('rst.message_type', [
                    'response',
                    'notification'
                ])
            )
        ),
        // is a custom vehicle data param in the given environment
        sql.exists(
            sql.select()
            .from('view_custom_vehicle_data vcvd')
            .where({
                'vcvd.parent_id': null,
                'vcvd.is_deleted': false,
                'vcvd.name': sql('fgp.parameter')
            })
            .where(
                sql.or(
                    // always get PRODUCTION records if they are the most recent version
                    {
                        'vcvd.status': 'PRODUCTION'
                    },
                    // if the function group we're in context of is in STAGING, then allow STAGING custom vehicle data
                    // otherwise restrict the custom vehicle data to PRODUCTION records
                    {
                        'vcvd.status': sql('CASE WHEN fgi.status=\'STAGING\' THEN \'STAGING\'::edit_status ELSE \'PRODUCTION\'::edit_status END')
                    }
                )
            )
        )
    );
}

function getFuncGroupParametersId (id) {
    let query = sql.select('fgp.function_group_id', 'fgp.rpc_name', 'fgp.parameter')
        .from('function_group_parameters fgp')
        .join('function_group_info fgi', {
            'fgi.id': 'fgp.function_group_id'
        })
        .where(
            sql.and(
                {
                    'fgp.function_group_id': id
                },
                funcGroupParamOr()
            )
        )
        .toString();

    return query.toString();
}

function getFuncGroupStatus (isProduction, hideDeleted = false) {
    const funcGroupsProduction = sql.select('*')
        .from('view_function_group_info')
        .where({
            status: 'PRODUCTION',
            'is_deleted': false
        })
        .orderBy('LOWER(view_function_group_info.property_name)');

    const funcGroupsGroup = sql.select('max(id) AS id', 'property_name')
        .from('view_function_group_info')
        .groupBy('property_name');

    let funcGroupsStaging = sql.select('view_function_group_info.*')
        .from('(' + funcGroupsGroup + ') vfgi')
        .innerJoin('view_function_group_info', {
            'view_function_group_info.id': 'vfgi.id'
        });

        if (hideDeleted) {
            funcGroupsStaging.where(
                {
                    'is_deleted': false
                }
            );
        }
        else {
            funcGroupsStaging.where(
                sql.or({
                    'is_deleted': false,
                    'status': 'STAGING'
                })
            );
        }

        funcGroupsStaging = funcGroupsStaging.orderBy('LOWER(view_function_group_info.property_name)');

    if (isProduction) {
        //filter out so only production entries exist
        return funcGroupsProduction;
    }
    else {
        //filter out based on highest id
        return funcGroupsStaging;
    }
}

function getFuncGroupHmiLevelsStatus (isProduction, hideDeleted = false) {
    return sql.select('function_group_id', 'permission_name', 'hmi_level')
        .select(
            '(' + sql.select('COUNT(pr.parent_permission_name)')
                .from('permission_relations pr')
                .join('permissions p', {
                    'p.name': 'pr.child_permission_name'
                })
                .where({
                    'pr.parent_permission_name': sql('function_group_hmi_levels.permission_name'),
                    'p.type': 'PARAMETER'
                })
                .toString()
            + ') AS possible_parameter_count'
        )
        .from('(' + getFuncGroupStatus(isProduction, hideDeleted) + ') fgi')
        .innerJoin('function_group_hmi_levels', {
            'fgi.id': 'function_group_hmi_levels.function_group_id'
        })
        .toString();
}

function getFuncGroupParametersStatus (isProduction, hideDeleted = false) {
    return sql.select('fgp.function_group_id', 'fgp.rpc_name', 'fgp.parameter')
        .from('(' + getFuncGroupStatus(isProduction, hideDeleted) + ') fgiv')
        .join('function_group_info fgi', {
            'fgi.id': 'fgiv.id'
        })
        .join('function_group_parameters fgp', {
            'fgiv.id': 'fgp.function_group_id'
        })
        .where(
            funcGroupParamOr()
        )
        .toString();
}

function getFuncGroupsByIdsStagingFilter (ids) {
    return sql.select('*')
        .from('function_group_info')
        .where(
            sql.and(
                sql.in('id', ids),
                {
                    status: 'STAGING'
                }
            )
        )
        .toString()
}

function getFuncGroupHmiLevelsByIdsStagingFilter (ids) {
    return sql.select('function_group_hmi_levels.*')
        .from('function_group_hmi_levels')
        .innerJoin('function_group_info', {
            'function_group_info.id': 'function_group_hmi_levels.function_group_id'
        })
        .where(
            sql.and(
                sql.in('id', ids),
                {
                    status: 'STAGING'
                }
            )
        )
        .toString();
}

function getFuncGroupParametersByIdsStagingFilter (ids) {
    return sql.select('fgp.*')
        .from('function_group_parameters fgp')
        .innerJoin('function_group_info fgi', {
            'fgi.id': 'fgp.function_group_id'
        })
        .where(
            sql.and(
                sql.in('id', ids),
                {
                    'fgi.status': 'STAGING'
                },
                funcGroupParamOr()
            )
        )
        .toString();
}

module.exports = {
    rpcs: rpcs,
    hmiLevels: hmiLevels,
    permissionRelationsNoModules: permissionRelationsNoModules,
    getGroupNamesStaging: getGroupNamesStaging,
    getFuncGroup: {
        base: {
            idFilter: getFuncGroupId,
            statusFilter: getFuncGroupStatus,
            ids: getFuncGroupsByIdsStagingFilter
        },
        hmiLevels: {
            idFilter: getFuncGroupHmiLevelsId,
            statusFilter: getFuncGroupHmiLevelsStatus,
            ids: getFuncGroupHmiLevelsByIdsStagingFilter
        },
        parameters: {
            idFilter: getFuncGroupParametersId,
            statusFilter: getFuncGroupParametersStatus,
            ids: getFuncGroupParametersByIdsStagingFilter
        }
    }
}

<|endoftext|>


<commit_before>'use strict';

// Detect Firefox's API feature
var isFirefox = typeof InstallTrigger !== 'undefined';

var requestHonCode = function(event, link) {
  // Prevent Duckduckgo onclick redirect
  event.stopPropagation();

  var domain = honcode.getDomainFromUrl(link);
  var layerId = 'layer' + event.target.id;
  var $logoId =  $(event.target);

  var popUp = '
' +
    '
' + domain + '
' +
    '
' +
    '
' + chrome.i18n.getMessage('ShowCertificate') + '
' +
    '
' +
    '' +
    '
' +
    '
' + chrome.i18n.getMessage('HonCodeCertified') +
    '

' +
    '
' +
    '
' + chrome.i18n.getMessage('HonPrinciples') + '

' +
    '
' + chrome.i18n.getMessage('Authority') + '
' +
    '
' + chrome.i18n.getMessage('Complementarity') + '
' +
    '
' + chrome.i18n.getMessage('PrivacyPolicy') + '
' +
    '
' + chrome.i18n.getMessage('Attribution') + '
' +
    '
' + chrome.i18n.getMessage('Justifiability') + '
' +
    '
' + chrome.i18n.getMessage('Transparency') + '
' +
    '
' + chrome.i18n.getMessage('FinancialDisclosure') + '
' +
    '
' + chrome.i18n.getMessage('AdvertisingPolicy') + '
' +
    '

' +
    '
';
  $('body').append(popUp);

  var $layerId =  $('#' + layerId);
  var borderX = 10;
  if (event.pageX + 290 > document.body.getBoundingClientRect().right) {
    borderX = event.pageX + 300 - document.body.getBoundingClientRect().right;
  }

  $layerId.css('left', event.pageX - borderX);
  $layerId.css('top', event.pageY - 10);
  honcode.contentHONcodeStatus($layerId.find('.honTrust'), link);

  var timeoutId;
  var hideTimeoutId;
  // Add honLogo eventListener
  $logoId.hover(function() {
    if (!timeoutId) {
      timeoutId = window.setTimeout(function() {
        timeoutId = null;
        $layerId.show();
      }, 200);
    }
  }, function() {
    if (timeoutId) {
      window.clearTimeout(timeoutId);
      timeoutId = null;
    }
  });

  $layerId.hover(function() {
    if (hideTimeoutId) {
      window.clearTimeout(hideTimeoutId);
      hideTimeoutId = null;
    }
  }, function() {
    if (!hideTimeoutId) {
      hideTimeoutId = window.setTimeout(function() {
        hideTimeoutId = null;
        $layerId.hide();
      }, 200);
    }
  });
  $layerId.show();
};

var updateLinks = function() {
  var deferred = new $.Deferred();

  // Get links
  var links = [];
  var hrefSelector = '';
  var timeToWait = 1;
  var honCodeRequested = 0;
  var honLogoSize = 'honcode-logo-tall';
  // Match Google
  if (window.location.host.indexOf('google') > -1) {
    hrefSelector = 'h3.r>a';
  }
  // Match Yahoo
  else if (window.location.host.indexOf('yahoo') > -1) {
    hrefSelector = '#web div.compTitle h3.title>a';
    timeToWait = 1000;
  }
  // Match Bing
  else if (window.location.host.indexOf('bing') > -1) {
    hrefSelector = 'li.b_algo h2>a';
  }
  // Match DuckDuckGo
  else if (window.location.host.indexOf('duckduckgo') > -1) {
    hrefSelector = 'h2.result__title>a.result__a';
    timeToWait = 1000;
    $('head').unbind('DOMSubtreeModified',updateLinks);
    $('head').bind('DOMSubtreeModified', updateLinks);
  }
  // Match Wikipedia
  else if (!isFirefox && window.location.host.indexOf('wikipedia') > -1) {
    hrefSelector = 'a.external.text';
    honLogoSize = 'honcode-logo-wide';
  }
  // Match MedlinePlus
  else if (!isFirefox && window.location.host.indexOf('medlineplus') > -1) {
    hrefSelector = '.bulletlist a';
    honLogoSize = 'honcode-logo-wide';
  }
  setTimeout(function() {
    var nodeList = document.querySelectorAll(hrefSelector);
    for (var i = 0; i < nodeList.length; ++i) {
      links[i] = nodeList[i].href;
    }
    links.forEach(function(link, index) {
      var honLogo = $(nodeList.item(index)).parent();

      var logoId = 'honLogo_' + index;

      var honCodeLogo = '

';

      if (honLogo.children('.certificateLink').length === 0) {
        // Normalize Search Engine parents' behaviors
        honLogo.parent().css('overflow','visible');
        honLogo.parent().css('position','relative');
        honLogo.prepend(honCodeLogo);
        honcode.contentHONcodeStatus(
          honLogo.children('.certificateLink'), link);

        // Add onClick listener
        $('#' + logoId).one('click', function(e) {
          requestHonCode(e, link);
        });
      }

      honCodeRequested++;
      if (honCodeRequested === links.length) {
        deferred.resolve();
      }
    });
  }, timeToWait);

  return deferred.promise();
};

updateLinks().done(function() {});
<commit_msg>fix selector to ignore ads<commit_after>'use strict';

// Detect Firefox's API feature
var isFirefox = typeof InstallTrigger !== 'undefined';

var requestHonCode = function(event, link) {
  // Prevent Duckduckgo onclick redirect
  event.stopPropagation();

  var domain = honcode.getDomainFromUrl(link);
  var layerId = 'layer' + event.target.id;
  var $logoId =  $(event.target);

  var popUp = '
' +
    '
' + domain + '
' +
    '
' +
    '
' + chrome.i18n.getMessage('ShowCertificate') + '
' +
    '
' +
    '' +
    '
' +
    '
' + chrome.i18n.getMessage('HonCodeCertified') +
    '

' +
    '
' +
    '
' + chrome.i18n.getMessage('HonPrinciples') + '

' +
    '
' + chrome.i18n.getMessage('Authority') + '
' +
    '
' + chrome.i18n.getMessage('Complementarity') + '
' +
    '
' + chrome.i18n.getMessage('PrivacyPolicy') + '
' +
    '
' + chrome.i18n.getMessage('Attribution') + '
' +
    '
' + chrome.i18n.getMessage('Justifiability') + '
' +
    '
' + chrome.i18n.getMessage('Transparency') + '
' +
    '
' + chrome.i18n.getMessage('FinancialDisclosure') + '
' +
    '
' + chrome.i18n.getMessage('AdvertisingPolicy') + '
' +
    '

' +
    '
';
  $('body').append(popUp);

  var $layerId =  $('#' + layerId);
  var borderX = 10;
  if (event.pageX + 290 > document.body.getBoundingClientRect().right) {
    borderX = event.pageX + 300 - document.body.getBoundingClientRect().right;
  }

  $layerId.css('left', event.pageX - borderX);
  $layerId.css('top', event.pageY - 10);
  honcode.contentHONcodeStatus($layerId.find('.honTrust'), link);

  var timeoutId;
  var hideTimeoutId;
  // Add honLogo eventListener
  $logoId.hover(function() {
    if (!timeoutId) {
      timeoutId = window.setTimeout(function() {
        timeoutId = null;
        $layerId.show();
      }, 200);
    }
  }, function() {
    if (timeoutId) {
      window.clearTimeout(timeoutId);
      timeoutId = null;
    }
  });

  $layerId.hover(function() {
    if (hideTimeoutId) {
      window.clearTimeout(hideTimeoutId);
      hideTimeoutId = null;
    }
  }, function() {
    if (!hideTimeoutId) {
      hideTimeoutId = window.setTimeout(function() {
        hideTimeoutId = null;
        $layerId.hide();
      }, 200);
    }
  });
  $layerId.show();
};

var updateLinks = function() {
  var deferred = new $.Deferred();

  // Get links
  var links = [];
  var hrefSelector = '';
  var timeToWait = 1;
  var honCodeRequested = 0;
  var honLogoSize = 'honcode-logo-tall';
  // Match Google
  if (window.location.host.indexOf('google') > -1) {
    hrefSelector = 'h3.r>a';
  }
  // Match Yahoo
  else if (window.location.host.indexOf('yahoo') > -1) {
    hrefSelector = '#web div.compTitle h3.title>a';
    timeToWait = 1000;
  }
  // Match Bing
  else if (window.location.host.indexOf('bing') > -1) {
    hrefSelector = 'li.b_algo h2>a';
  }
  // Match DuckDuckGo
  else if (window.location.host.indexOf('duckduckgo') > -1) {
    hrefSelector = '#links h2.result__title>a.result__a';
    timeToWait = 1000;
    $('head').unbind('DOMSubtreeModified',updateLinks);
    $('head').bind('DOMSubtreeModified', updateLinks);
  }
  // Match Wikipedia
  else if (!isFirefox && window.location.host.indexOf('wikipedia') > -1) {
    hrefSelector = 'a.external.text';
    honLogoSize = 'honcode-logo-wide';
  }
  // Match MedlinePlus
  else if (!isFirefox && window.location.host.indexOf('medlineplus') > -1) {
    hrefSelector = '.bulletlist a';
    honLogoSize = 'honcode-logo-wide';
  }
  setTimeout(function() {
    var nodeList = document.querySelectorAll(hrefSelector);
    for (var i = 0; i < nodeList.length; ++i) {
      links[i] = nodeList[i].href;
    }
    links.forEach(function(link, index) {
      var honLogo = $(nodeList.item(index)).parent();

      var logoId = 'honLogo_' + index;

      var honCodeLogo = '

';

      if (honLogo.children('.certificateLink').length === 0) {
        // Normalize Search Engine parents' behaviors
        honLogo.parent().css('overflow','visible');
        honLogo.parent().css('position','relative');
        honLogo.prepend(honCodeLogo);
        honcode.contentHONcodeStatus(
          honLogo.children('.certificateLink'), link);

        // Add onClick listener
        $('#' + logoId).one('click', function(e) {
          requestHonCode(e, link);
        });
      }

      honCodeRequested++;
      if (honCodeRequested === links.length) {
        deferred.resolve();
      }
    });
  }, timeToWait);

  return deferred.promise();
};

updateLinks().done(function() {});
<|endoftext|>


<commit_before>angular.module('bdSearch', [])
  .controller('SearchCtrl', function (
    $scope,
    $location,
    G,
    Restangular
  ) {
    'use strict';

    $scope.g = G;
    var keyword = $location.search().kw || $scope.g.searchKeyword;
    var type = $location.search().t || $scope.g.searchType;

    if ($scope.g.searchKeyword !== keyword) {
      $scope.g.searchKeyword = keyword;
    }

    if (!$scope.g.searchType) {
      $scope.g.searchType = 'character';
    } else if ($scope.g.searchType !== type) {
      $scope.g.searchType = type;
    }

    if (angular.isDefined(keyword)) {
      Restangular.all('search').getList({
        kw: keyword,
        t: type
      }).then(function (data) {
        $scope.objects = data;
      });
    }

    $scope.getResult = function () {
      $location.path('/').search({kw: $scope.g.searchKeyword, t: $scope.g.searchType});
    };
  })

  .factory('searchUtils', function () {
    'use strict';

    var service = {
      select: {
        prev: function (cur, lists) {
          var prev;

          cur.removeClass('list-cur');
          prev = cur.prev();
          if (!prev.length) {
            prev = lists.last();
          }
          return prev.addClass('list-cur');
        },

        next: function (cur, lists) {
          var next;

          cur.removeClass('list-cur');
          next = cur.next();
          if (!next.length) {
            next = lists.first();
          }

          return next.addClass('list-cur');
        },

        choose: function (cur) {
          var object;

          cur.removeClass('list-cur');
          object = {
            name: cur.text(),
            id: cur.attr('object-id')
          };

          return object;
        }
      }
    };

    return service;
  })

  .directive('bdSearch', function (
    $timeout,
    Restangular
  ) {
    'use strict';

    return {
      scope: false,
      restrict: 'A',
      require: 'ngModel',
      link: function ($scope, $element, $attrs, $ctrl) {
        var delayRequest;
        $scope.searchFlag = true;

        $element.on('keydown', function (e) {
          $scope.searchFlag = true;
        });

        $scope.$watch(function () {
          return $ctrl.$modelValue;
        }, function (modelValue) {
          $timeout.cancel(delayRequest);

          if (modelValue && $scope.searchFlag) {
            delayRequest = $timeout(function () {
              Restangular.all('search').getList({
                  kw: modelValue,
                  t: $attrs.bdSearchType
                })
                .then(function (data) {
                  $scope.results = data;
                  if (data.length > 0) {
                    $scope.isListShow = true;
                  } else {
                    $scope.isListShow = false;
                  }
                });
            }, 500);
          }
        });
      }
    };
  })

  .directive('bdSelectSearching', function (
    searchUtils
  ) {
    'use strict';

    return {
      link: function ($scope, $element, $attrs) {
        var keyCode = {
          up: 38,
          down: 40,
          enter: 13,
          tab: 9
        };
        var ul = $element.next();

        $element.on('keydown', function (e) {
          var lists = ul.find('li');
          var cur = ul.children('.list-cur');

          if ($scope.isListShow) {
            switch (e.keyCode) {
            case keyCode.up:
              e.originalEvent.preventDefault();
              searchUtils.select.prev(cur, lists);
              break;

            case keyCode.down:
              e.originalEvent.preventDefault();
              searchUtils.select.next(cur, lists);
              break;

            case keyCode.tab:
            case keyCode.enter:
              e.originalEvent.preventDefault();
              var resultObject = searchUtils.select.choose(cur, lists);

              $scope.$emit('resultSelect', resultObject);

              break;
            }
          }
        });
      }
    };
  })

  .directive('bdAutoComplete', function () {
    'use strict';

    return {
      require: 'ngModel',
      link: function ($scope, $element, $attrs, $ctrl) {
        $scope.$on('resultSelect', function (event, resultObject) {
          $scope.$apply(function () {
            switch ($attrs.bdAutoComplete) {

            case 'id':
              var id = resultObject.id;
              $ctrl.$setViewValue(id);
              $element.val(id);
              break;

            case 'name':
              var name = resultObject.name;
              $ctrl.$setViewValue(name);
              $element.val(name);
              break;
            }

            $scope.searchFlag = false;
            $scope.isListShow = false;
          });
        });
      }
    };
  });
<commit_msg>fix: disabled auto search when update something<commit_after>angular.module('bdSearch', [])
  .controller('SearchCtrl', function (
    $scope,
    $location,
    G,
    Restangular
  ) {
    'use strict';

    $scope.g = G;
    var keyword = $location.search().kw || $scope.g.searchKeyword;
    var type = $location.search().t || $scope.g.searchType;

    if ($scope.g.searchKeyword !== keyword) {
      $scope.g.searchKeyword = keyword;
    }

    if (!$scope.g.searchType) {
      $scope.g.searchType = 'character';
    } else if ($scope.g.searchType !== type) {
      $scope.g.searchType = type;
    }

    if (angular.isDefined(keyword)) {
      Restangular.all('search').getList({
        kw: keyword,
        t: type
      }).then(function (data) {
        $scope.objects = data;
      });
    }

    $scope.getResult = function () {
      $location.path('/').search({kw: $scope.g.searchKeyword, t: $scope.g.searchType});
    };
  })

  .factory('searchUtils', function () {
    'use strict';

    var service = {
      select: {
        prev: function (cur, lists) {
          var prev;

          cur.removeClass('list-cur');
          prev = cur.prev();
          if (!prev.length) {
            prev = lists.last();
          }
          return prev.addClass('list-cur');
        },

        next: function (cur, lists) {
          var next;

          cur.removeClass('list-cur');
          next = cur.next();
          if (!next.length) {
            next = lists.first();
          }

          return next.addClass('list-cur');
        },

        choose: function (cur) {
          var object;

          cur.removeClass('list-cur');
          object = {
            name: cur.text(),
            id: cur.attr('object-id')
          };

          return object;
        }
      }
    };

    return service;
  })

  .directive('bdSearch', function (
    $timeout,
    Restangular
  ) {
    'use strict';

    return {
      scope: false,
      restrict: 'A',
      require: 'ngModel',
      link: function ($scope, $element, $attrs, $ctrl) {
        var delayRequest;
        $scope.searchFlag = false;

        $element.on('keydown', function (e) {
          $scope.searchFlag = true;
        });

        $scope.$watch(function () {
          return $ctrl.$modelValue;
        }, function (modelValue) {
          $timeout.cancel(delayRequest);

          if (modelValue && $scope.searchFlag) {
            delayRequest = $timeout(function () {
              Restangular.all('search').getList({
                  kw: modelValue,
                  t: $attrs.bdSearchType
                })
                .then(function (data) {
                  $scope.results = data;
                  if (data.length > 0) {
                    $scope.isListShow = true;
                  } else {
                    $scope.isListShow = false;
                  }
                });
            }, 500);
          }
        });
      }
    };
  })

  .directive('bdSelectSearching', function (
    searchUtils
  ) {
    'use strict';

    return {
      link: function ($scope, $element, $attrs) {
        var keyCode = {
          up: 38,
          down: 40,
          enter: 13,
          tab: 9
        };
        var ul = $element.next();

        $element.on('keydown', function (e) {
          var lists = ul.find('li');
          var cur = ul.children('.list-cur');

          if ($scope.isListShow) {
            switch (e.keyCode) {
            case keyCode.up:
              e.originalEvent.preventDefault();
              searchUtils.select.prev(cur, lists);
              break;

            case keyCode.down:
              e.originalEvent.preventDefault();
              searchUtils.select.next(cur, lists);
              break;

            case keyCode.tab:
            case keyCode.enter:
              e.originalEvent.preventDefault();
              var resultObject = searchUtils.select.choose(cur, lists);

              $scope.$emit('resultSelect', resultObject);

              break;
            }
          }
        });
      }
    };
  })

  .directive('bdAutoComplete', function () {
    'use strict';

    return {
      require: 'ngModel',
      link: function ($scope, $element, $attrs, $ctrl) {
        $scope.$on('resultSelect', function (event, resultObject) {
          $scope.$apply(function () {
            switch ($attrs.bdAutoComplete) {

            case 'id':
              var id = resultObject.id;
              $ctrl.$setViewValue(id);
              $element.val(id);
              break;

            case 'name':
              var name = resultObject.name;
              $ctrl.$setViewValue(name);
              $element.val(name);
              break;
            }

            $scope.searchFlag = false;
            $scope.isListShow = false;
          });
        });
      }
    };
  });
<|endoftext|>


<commit_before>'use strict';

module.exports = ['$q', '$log', '$http', emailService];

function emailService($q, $log, $http){
  $log.debug('emailService');

  let service = {};
  let url = `${__API_URL__}contact`;

  service.sendMail = function(form){
    console.log('url = ', url);
    return $http({
      method: 'POST',
      url: url,
      data: JSON.stringify(form)
      // config: config
    }).then(function successCallback(response) {
      $log.debug('email send -- ',response, 'response status -- '+ response.data.responseCode);
    }, function errorCallback(response) {
      $log.debug('error occured -- ', response);
    });
  };

  return service;
}
<commit_msg>C:/Program Files/Git/ route fix<commit_after>'use strict';

module.exports = ['$q', '$log', '$http', emailService];

function emailService($q, $log, $http){
  $log.debug('emailService');

  let service = {};
  let url = `${__API_URL__}/contact`;

  service.sendMail = function(form){
    console.log('url = ', url);
    return $http({
      method: 'POST',
      url: url,
      data: JSON.stringify(form)
      // config: config
    }).then(function successCallback(response) {
      $log.debug('email send -- ',response, 'response status -- '+ response.data.responseCode);
    }, function errorCallback(response) {
      $log.debug('error occured -- ', response);
    });
  };

  return service;
}
<|endoftext|>