<commit_before>/*jslint white: true, browser: true, plusplus: true, vars: true, nomen: true, bitwise: true*/
/*global jQuery: false, $: false, data_graft: false*/

/* Copyright 2010-2011, Carlos Guerreiro
 * Licensed under the MIT license */

"use strict";

var data_input = {
  1 : [
    'graft',
    'graft',
    'data'
  ],
  2 : [
    'graft',
    'graft',
    'data'
  ],
  3 : [
    {a: 'graft', b: 'data'},
    {a: 'graft', b: 'data'},
    {a: 'graft', b: 'other'}
  ],
  4 : [
    {inside: {a: 'data'}},
    {inside: {a: 'data'}},
    {inside: {a: 'other'}}
  ],
  5 : [
    {b: 'outside', inside: {a: 'inside'}},
    {b: 'other', inside: {a: 'inside'}},
    {b: 'outside', inside: {a: 'other'}}
  ],
  6 : [
    [1, 2, 3],
    [1, 2, 3]
  ],
  7 : [
    {'a':1, 'b':2, 'c':3},
    {'a':1, 'b':22, 'c':3},
    {'a':1, 'd':3}
  ],
  8 : [
    {'a':1, 'b':2, 'c':3},
    {'a':1, 'b':22, 'c':3},
    {'aa':11, 'b':2, 'c':3}
  ],
  9 : [
    {
      'a':{'x':'ax', 'y':'ay', 'z':'az'},
      'b':{'x':'bx', 'y':'by', 'z':'bz'},
      'c':{'x':'cx', 'y':'cy', 'z':'cz'},
    },
    {
      'a':{'x':'ax2', 'y':'ay', 'z':'az'},
      'b':{'x':'bx', 'y':'by', 'z':'bz'},
      'c':{'x':'cx', 'y':'cy', 'z':'cz2'},
    },
    {
      'a':{'x':'ax', 'y':'ay', 'z':'az'},
      'c':{'x':'cx', 'y':'cy', 'z':'cz'},
      'd':{'x':'dx', 'y':'dy', 'z':'dz'}
    }
  ],
  10 : [
    {'a':1, 'b':2, 'c':3},
    {}
  ],
  11 : [
    {},
    {'a':1, 'b':2, 'c':3}
  ],
  12: [
    {name:'Tom'},
    {name:'Tom', location: {city: 'NYC', country: 'USA'}}
  ],
  13: [
    {name:'Tom', location: {city: 'NYC', country: 'USA'}},
    {name:'Tom'}
  ],
  14: [
    {'fb':'facebook.png','tw':'twitter.png'},
    {'fb':'facebook.png','tw':'twitter_large.png'},
    {'fb':'facebook.png','tw':'twitter.png', 'ca': 'identica.png'}
  ],
  15: [
    {'a':'outside', 'sub': {'a':'inside'}},
    {'a':'outside', 'sub': {'a':'inside'}},
    {'sub': {'a':'inside'}}
  ],
  16: [
    {'a':'outside', 'sub': {'a':'inside'}},
    {'a':'outside', 'sub': {'a':'inside'}},
    {'sub': {'a':'inside'}}
  ],
  17: [
    {'a':'x'},
    {'a':null},
    {}
  ],
  18: [
    {'link': 'http://perceptiveconstructs.com'},
    {'link': null},
    {}
  ],
  19: [
    {},
    {'link': 'http://perceptiveconstructs.com'},
    {'link':  undefined}
  ],
  20: [
    {'link': 'http://perceptiveconstructs.com'},
    {},
    {'link': 'http://www.perceptiveconstructs.com'}
  ],
  21 : [
    [1, 2, 3],
    [1, 2, 3]
  ],
  22: [
    {},
    {a:1, b:2},
  ]
};

function allAttributesIn(al, e) {
  var excludedAttributeNames = {'id':true};
  var i, eav;
  for(i = 0; i < al.length; ++i) {
    if(excludedAttributeNames[al[i].name] === undefined) {
      eav = e.getAttribute(al[i].name);
      if(eav !== al[i].value) {
        return false;
      }
    }
  }
  return true;
}

function trimmedString(s) {
  return s.replace(/^\s+|\s+$/g,"");
}

function accumText(ci) {
  var t = '';
  while(ci.i < ci.e.childNodes.length && ci.e.childNodes[ci.i].nodeType === 3) {
    t = t + ci.e.childNodes[ci.i].nodeValue;
    ci.i = ci.i + 1;
  }
  return trimmedString(t);
}

function onlyWhitespaceLeft(ci) {
  var e, s;
  while(ci.i < ci.e.childNodes.length) {
    e = ci.e.childNodes[ci.i];
    if(e.nodeType !== 3) {
      return false;
    }
    s =  trimmedString(e.nodeValue);
    if(s !== '') {
      return false;
    }
    ci.i = ci.i + 1;
  }
  return true;
}

function compareDOM(e1, e2) {
  if(e1.nodeType !== e2.nodeType) {
    return false;
  }

  if(e1.tagName !== e2.tagName) {
    return false;
  }

  if(e1.nodeValue !== e2.nodeValue) {
    return false;
  }

  if(e1.attributes !== undefined && e1.attributes !== null) {
    if(!allAttributesIn(e1.attributes, e2)) {
      return false;
    }
    if(!allAttributesIn(e2.attributes, e1)) {
      return false;
    }
  }

  var ci1 = {e: e1, i:0};
  var ci2 = {e: e2, i:0};
  var t1, t2;

  while(ci1.i < ci1.e.childNodes.length &&
        ci2.i < ci2.e.childNodes.length) {
    t1 = accumText(ci1);
    t2 = accumText(ci2);
    if(t1 !== t2) {
      return false;
    }

    if(ci1.i < ci1.e.childNodes.length) {
      if(ci2.i < ci2.e.childNodes.length) {
        if(!compareDOM(e1.childNodes[ci1.i], e2.childNodes[ci2.i])) {
          return false;
        }
        ci1.i = ci1.i + 1;
        ci2.i = ci2.i + 1;
      } else {
        return false;
      }
    } else {
      if(ci2.i < ci2.e.childNodes.length) {
        return false;
      }
    }
  }

  if(!onlyWhitespaceLeft(ci1)) {
    return false;
  }
  if(!onlyWhitespaceLeft(ci2)) {
    return false;
  }

  return true;
}

jQuery(document).ready(function() {

  var env = {
    '_all_': {
      postUpdateText: function(e, f) {
        $(e).addClass('updated');
        f();
      },
      postInsertSequence: function(e, f) {
        $(e).addClass('added');
        f();
      },
      postInsertIf: function(e, f) {
        $(e).addClass('added');
        f();
      },
      postInsertElse: function(e, f) {
        $(e).addClass('added');
        f();
      },
      postUpdateAttribute: function(e, f, attr) {
        $(e).addClass('updated-'+ attr);
        f();
      },
      postAddAttribute: function(e, f, attr) {
        $(e).addClass('added-'+ attr);
        f();
      },
      postRemoveAttribute: function(e, f, attr) {
        $(e).addClass('removed-'+ attr);
        f();
      }
    }
  };

  $.each(data_input, function(i, input) {

    var j, graft;

    var t = $('#tpl_'+ i)[0];

    var html = '
'+ i+ '	';

    for(j = 0; j < input.length; ++j) {
      html += '		';
    }
    html += '</tr';

    $('#output').append(html);

    var matched = true;

    for(j = 0; j < input.length; ++j) {
      graft = data_graft.germ(input[0], t, env);
      $('#output_'+ i+ '_'+ j).append(graft.output);
      $('#show_expected_'+ i+ '_'+ j).append($('#expected_'+ i+ '_'+ j));

      if(j > 0) {
        graft.update(input[j]);
      }

      matched = matched && compareDOM(graft.output, $('#expected_'+ i+ '_'+ j)[0]);
    }
    $('#id_'+ i).addClass(matched ? 'OK' : 'failed');
  });
});
<commit_msg>made suitable for execution in node.js jsdom environment, checking result only after handler completion<commit_after>/*jslint white: true, browser: true, plusplus: true, vars: true, nomen: true, bitwise: true*/
/*global jQuery: false, $: false, data_graft: false*/

/* Copyright 2010-2011, Carlos Guerreiro
 * Licensed under the MIT license */

"use strict";

var data_input = {
  1 : [
    'graft',
    'graft',
    'data'
  ],
  2 : [
    'graft',
    'graft',
    'data'
  ],
  3 : [
    {a: 'graft', b: 'data'},
    {a: 'graft', b: 'data'},
    {a: 'graft', b: 'other'}
  ],
  4 : [
    {inside: {a: 'data'}},
    {inside: {a: 'data'}},
    {inside: {a: 'other'}}
  ],
  5 : [
    {b: 'outside', inside: {a: 'inside'}},
    {b: 'other', inside: {a: 'inside'}},
    {b: 'outside', inside: {a: 'other'}}
  ],
  6 : [
    [1, 2, 3],
    [1, 2, 3]
  ],
  7 : [
    {'a':1, 'b':2, 'c':3},
    {'a':1, 'b':22, 'c':3},
    {'a':1, 'd':3}
  ],
  8 : [
    {'a':1, 'b':2, 'c':3},
    {'a':1, 'b':22, 'c':3},
    {'aa':11, 'b':2, 'c':3}
  ],
  9 : [
    {
      'a':{'x':'ax', 'y':'ay', 'z':'az'},
      'b':{'x':'bx', 'y':'by', 'z':'bz'},
      'c':{'x':'cx', 'y':'cy', 'z':'cz'},
    },
    {
      'a':{'x':'ax2', 'y':'ay', 'z':'az'},
      'b':{'x':'bx', 'y':'by', 'z':'bz'},
      'c':{'x':'cx', 'y':'cy', 'z':'cz2'},
    },
    {
      'a':{'x':'ax', 'y':'ay', 'z':'az'},
      'c':{'x':'cx', 'y':'cy', 'z':'cz'},
      'd':{'x':'dx', 'y':'dy', 'z':'dz'}
    }
  ],
  10 : [
    {'a':1, 'b':2, 'c':3},
    {}
  ],
  11 : [
    {},
    {'a':1, 'b':2, 'c':3}
  ],
  12: [
    {name:'Tom'},
    {name:'Tom', location: {city: 'NYC', country: 'USA'}}
  ],
  13: [
    {name:'Tom', location: {city: 'NYC', country: 'USA'}},
    {name:'Tom'}
  ],
  14: [
    {'fb':'facebook.png','tw':'twitter.png'},
    {'fb':'facebook.png','tw':'twitter_large.png'},
    {'fb':'facebook.png','tw':'twitter.png', 'ca': 'identica.png'}
  ],
  15: [
    {'a':'outside', 'sub': {'a':'inside'}},
    {'a':'outside', 'sub': {'a':'inside'}},
    {'sub': {'a':'inside'}}
  ],
  16: [
    {'a':'outside', 'sub': {'a':'inside'}},
    {'a':'outside', 'sub': {'a':'inside'}},
    {'sub': {'a':'inside'}}
  ],
  17: [
    {'a':'x'},
    {'a':null},
    {}
  ],
  18: [
    {'link': 'http://perceptiveconstructs.com'},
    {'link': null},
    {}
  ],
  19: [
    {},
    {'link': 'http://perceptiveconstructs.com'},
    {'link':  undefined}
  ],
  20: [
    {'link': 'http://perceptiveconstructs.com'},
    {},
    {'link': 'http://www.perceptiveconstructs.com'}
  ],
  21 : [
    [1, 2, 3],
    [1, 2, 3]
  ],
  22: [
    {},
    {a:1, b:2},
  ]
};

function allAttributesIn(al, e) {
  var excludedAttributeNames = {'id':true};
  var i, eav;
  for(i = 0; i < al.length; ++i) {
    if(excludedAttributeNames[al[i].name] === undefined) {
      eav = e.getAttribute(al[i].name);
      if(eav !== al[i].value) {
        return false;
      }
    }
  }
  return true;
}

function trimmedString(s) {
  return s.replace(/^\s+|\s+$/g,"");
}

function accumText(ci) {
  var t = '';
  while(ci.i < ci.e.childNodes.length && ci.e.childNodes[ci.i].nodeType === 3) {
    t = t + ci.e.childNodes[ci.i].nodeValue;
    ci.i = ci.i + 1;
  }
  return trimmedString(t);
}

function onlyWhitespaceLeft(ci) {
  var e, s;
  while(ci.i < ci.e.childNodes.length) {
    e = ci.e.childNodes[ci.i];
    if(e.nodeType !== 3) {
      return false;
    }
    s =  trimmedString(e.nodeValue);
    if(s !== '') {
      return false;
    }
    ci.i = ci.i + 1;
  }
  return true;
}

function compareDOM(e1, e2) {
  if(e1.nodeType !== e2.nodeType) {
    return false;
  }

  if(e1.tagName !== e2.tagName) {
    return false;
  }

  if(e1.nodeValue !== e2.nodeValue) {
    return false;
  }

  if(e1.attributes !== undefined && e1.attributes !== null) {
    if(!allAttributesIn(e1.attributes, e2)) {
      return false;
    }
    if(!allAttributesIn(e2.attributes, e1)) {
      return false;
    }
  }

  var ci1 = {e: e1, i:0};
  var ci2 = {e: e2, i:0};
  var t1, t2;

  while(ci1.i < ci1.e.childNodes.length &&
        ci2.i < ci2.e.childNodes.length) {
    t1 = accumText(ci1);
    t2 = accumText(ci2);
    if(t1 !== t2) {
      return false;
    }

    if(ci1.i < ci1.e.childNodes.length) {
      if(ci2.i < ci2.e.childNodes.length) {
        if(!compareDOM(e1.childNodes[ci1.i], e2.childNodes[ci2.i])) {
          return false;
        }
        ci1.i = ci1.i + 1;
        ci2.i = ci2.i + 1;
      } else {
        return false;
      }
    } else {
      if(ci2.i < ci2.e.childNodes.length) {
        return false;
      }
    }
  }

  if(!onlyWhitespaceLeft(ci1)) {
    return false;
  }
  if(!onlyWhitespaceLeft(ci2)) {
    return false;
  }

  return true;
}

function test(cb) {
  var errors = [];

  function checkPart(graft, i, j) {
    var expected, comp;
    expected = $('#expected_'+ i+ '_'+ j)[0];
    comp = compareDOM(graft.output, expected);
    if(!comp) {
      errors.push([i, j, graft.output, expected]);
    }
    return comp;
  }

  var env = {
    '_all_': {
      postUpdateText: function(e, f) {
        $(e).addClass('updated');
        f();
      },
      postInsertSequence: function(e, f) {
        $(e).addClass('added');
        f();
      },
      postInsertIf: function(e, f) {
        $(e).addClass('added');
        f();
      },
      postInsertElse: function(e, f) {
        $(e).addClass('added');
        f();
      },
      postUpdateAttribute: function(e, f, attr) {
        $(e).addClass('updated-'+ attr);
        f();
      },
      postAddAttribute: function(e, f, attr) {
        $(e).addClass('added-'+ attr);
        f();
      },
      postRemoveAttribute: function(e, f, attr) {
        $(e).addClass('removed-'+ attr);
        f();
      }
    }
  };

  var remCases = 0;
  $.each(data_input, function() { ++remCases; });

  $.each(data_input, function(i, input) {

    var j, graft;

    var t = $('#tpl_'+ i)[0];

    var html = '
'+ i+ '	';

    for(j = 0; j < input.length; ++j) {
      html += '		';
    }
    html += '
 0) {
        graft.update(part, function() {
          matched = matched && checkPart(graft, i, j);
          --remInCase;
          if(remInCase === 0) {
            $('#id_'+ i).addClass(matched ? 'OK' : 'failed');
            --remCases;
            if(remCases === 0) {
              if(cb) {
                cb(errors);
              }
            }
          }
        });
      } else {
        matched = matched && checkPart(graft, i, j);
      }
    });
  });
}

jQuery(document).ready(function() {
  test();
});
<|endoftext|>


<commit_before>/* jshint esversion: 6 */
'use strict';

var testSauceLabs = require('test-saucelabs');

// https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities
var platforms = [/*{
	browserName: 'internet explorer',
	platform: 'Windows 7',
	version: '9'
}, {
	browserName: 'internet explorer',
	platform: 'Windows 8',
	version: '10.0'
}, {
	browserName: 'internet explorer',
	platform: 'Windows 10',
	version: '11.0'
},*/ {
	browserName: 'safari',
	platform: 'OS X 10.12',
	version: 'latest'
}, {
	browserName: 'MicrosoftEdge',
	platform: 'Windows 10'
}, {
	browserName: 'firefox',
	platform: 'Windows 10',
	version: 'latest'
}, {
	browserName: 'googlechrome',
	platform: 'Windows 10',
	version: 'latest'
}, {
	browserName: 'Safari',
	'appium-version': '1.7.1',
	platformName: 'iOS',
	platformVersion: '11.0',
	deviceName: 'iPhone 8 Simulator'
}];

var url = 'http://canjs.test:3000/test/index.html?hidepassed';

testSauceLabs({
	urls: [{ name: "canjs", url : url }],
	platforms: platforms,
	zeroAssertionsPass: false
});
<commit_msg>Skip tests in Edge (for now)<commit_after>/* jshint esversion: 6 */
'use strict';

var testSauceLabs = require('test-saucelabs');

// https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities
var platforms = [/*{
	browserName: 'internet explorer',
	platform: 'Windows 7',
	version: '9'
}, {
	browserName: 'internet explorer',
	platform: 'Windows 8',
	version: '10.0'
}, {
	browserName: 'internet explorer',
	platform: 'Windows 10',
	version: '11.0'
}, {
	browserName: 'MicrosoftEdge',
	platform: 'Windows 10'
},*/ {
	browserName: 'safari',
	platform: 'OS X 10.12',
	version: 'latest'
}, {
	browserName: 'firefox',
	platform: 'Windows 10',
	version: 'latest'
}, {
	browserName: 'googlechrome',
	platform: 'Windows 10',
	version: 'latest'
}, {
	browserName: 'Safari',
	'appium-version': '1.7.1',
	platformName: 'iOS',
	platformVersion: '11.0',
	deviceName: 'iPhone 8 Simulator'
}];

var url = 'http://canjs.test:3000/test/index.html?hidepassed';

testSauceLabs({
	urls: [{ name: "canjs", url : url }],
	platforms: platforms,
	zeroAssertionsPass: false
});
<|endoftext|>


<commit_before>/**
 * LMLJS Framework
 * Copyright (c) 2014 http://lmlphp.com All rights reserved.
 * Licensed ( http://mit-license.org/ )
 * Author: leiminglin <leiminglin@126.com>
 *
 * A lovely javascript framework.
 *
 * $id: $
 *
 */
!function(a,b,c){function d(a){return a={},a.queue=[],a.running=0,a.promise=function(){a.queue.length?(a.running=1,a.queue.shift()()):a.running=0},a.then=function(b){a.queue.push(b)},a.front=function(b){a.queue.unshift(b)},a}function h(){function c(c){b.push(c),a.onresize=function(){for(var a in b)b[a]()}}var b=[];return c}function i(c){function f(c,d,e,f){e=b.createElement("script"),f=b.getElementsByTagName("script")[0],e.async=1,e.src=c;try{f.parentNode.insertBefore(e,f),a.addEventListener?e.addEventListener("load",d,!1):a.attachEvent?e.onreadystatechange=function(){this.readyState.match(/loaded|complete/i)&&d()}:e.onload=function(){d()}}catch(a){d()}}function h(a,b,d,e){function f(e,g){e=a.shift(),g=a.shift(),a.unshift(g),i(e,function(){g?(f(),c[g].callback.running||i.start(g)):b()},d)}e=a[0],f()}function i(a,b,g,j){function k(){function d(){f(a,function(){c[a].loaded=1,b(),i.start(a)})}g=g+""=="1"?1:0,g?d():c[a].start||c[a].loaded?(b(),i.start(a)):d(),c[a].start=1}return"object"==typeof a&&a instanceof Array?h(a,b):(b=b||function(){e.promise()},c[a]?c[a].callback.then(k):(j=d(),j.then(k),c[a]={loaded:0,start:0,callback:j}),void(c[a].callback.running||i.start(a)))}return c={},i.competeLoad=function(a,b,c,d,e,f){for(e=0,f=a.length;e<f;e++)i(a.shift(),function(){return b.flag?c():(b(),void(b.flag=1))},d)},i.start=function(a,b){if(g.onload)if(a)c[a].callback.promise();else for(b in c)c[b].callback.promise()},i}function k(c){var f,g,d=c.offsetTop,e=c.offsetParent;if(null==e&&c.parentNode)for(f=c.parentNode;null==e&&(e=f.offsetParent,f=f.parentNode););for(;e;)d+=e.offsetTop+e.clientTop,e=e.offsetParent;return"number"==typeof a.pageYOffset?g=a.pageYOffset:(docElement=b.compatMode&&"CSS1Compat"===b.compatMode?b.documentElement:b.body,g=docElement.scrollTop),d-g}function l(){return b.compatMode&&"BackCompat"==b.compatMode&&b.body?{width:b.body.clientWidth,height:b.body.clientHeight}:{width:b.documentElement.clientWidth,height:b.documentElement.clientHeight}}function m(a,c){c=b.createElement("style"),c.type="text/css",c.styleSheet?c.styleSheet.cssText=a:c.innerHTML=a,b.getElementsByTagName("head")[0].appendChild(c)}var e=d(),f=i(),g={};g.registerOnResize=h(),e.then(function(){function p(){if(m>=h.length)return void(a.addEventListener?b.removeEventListener("scroll",p,!1):a.attachEvent&&a.detachEvent(event,p));for(c=0,j=h.length;c<j;c++)h[c].getAttribute("src")||(n=k(h[c]),o=h[c].getAttribute("height")||0,n>=-o&&n<i.height&&(f=h[c].getAttribute("osrc"))&&(h[c].setAttribute("src",f),h[c].onerror=function(){(f=this.getAttribute("osrc-bak"))&&(this.setAttribute("src",f),this.onerror=null)},h[c].onload=function(){m++}))}var c,f,n,o,h=b.getElementsByTagName("IMG"),i=l(),m=0;g.registerOnResize(function(){i=l()}),a.addEventListener?b.addEventListener("scroll",p,!1):a.attachEvent&&a.attachEvent("onscroll",p),p();var q=1,r=function(){p(),q*=2,q>1e3&&(q=1e3),setTimeout(r,q)};setTimeout(r,q),e.promise()}),"function"!=typeof b.getElementsByClassName&&(b.getElementsByClassName=function(a){var f,g,a,c=b.getElementsByTagName("*"),d=new RegExp("\\b"+a+"\\b"),e=[];for(f=0,g=c.length;f<g;f++)a=c[f].className,d.test(a)&&e.push(c[f]);return e}),e.then(function(a,c){for(a=b.getElementsByClassName("lazyCss"),c=0;c<a.length;c++)m(a[c].value||a[c].innerHTML);e.promise()}),e.then(function(){var c,d,a=b.getElementsByClassName("lazyHtml");for(c=0;c<a.length;c++)"TEXTAREA"==a[c].tagName&&(d=b.createElement("DIV"),d.innerHTML=a[c].value,a[c].parentNode.insertBefore(d,a[c]));e.promise()});var n=function(){};"function"==typeof a.onload&&(n=a.onload),g.deferred=e,g.createDeferred=d,g.loadJs=f,g.onload=0,g.run=function(){g.onload||(g.onload=1,e.promise(),f.start(),n())},a.lml=g,a.onload=g.run}(window,document);
<commit_msg>compress<commit_after>/**
 * LMLJS Framework
 * Copyright (c) 2014 http://lmlphp.com All rights reserved.
 * Licensed ( http://mit-license.org/ )
 * Author: leiminglin <leiminglin@126.com>
 *
 * A lovely javascript framework.
 *
 * $id: $
 *
 */
!function(a,b,c){function d(a){return a={},a.queue=[],a.running=0,a.promise=function(){a.queue.length?(a.running=1,a.queue.shift()()):a.running=0},a.then=function(b){a.queue.push(b)},a.front=function(b){a.queue.unshift(b)},a}function h(){function c(c){b.push(c),a.onresize=function(){for(var a in b)b[a]()}}var b=[];return c}function i(c){function f(c,d,e,f){e=b.createElement("script"),f=b.getElementsByTagName("script")[0],e.async=1,e.src=c;try{f.parentNode.insertBefore(e,f),a.addEventListener?e.addEventListener("load",d,!1):a.attachEvent?e.onreadystatechange=function(){this.readyState.match(/loaded|complete/i)&&d()}:e.onload=function(){d()}}catch(a){d()}}function h(a,b,d,e){function f(e,g){e=a.shift(),g=a.shift(),a.unshift(g),i(e,function(){g?(f(),c[g].callback.running||i.start(g)):b()},d)}e=a[0],f()}function i(a,b,g,j){function k(){function d(){f(a,function(){c[a].loaded=1,b(),i.start(a)})}g=g+""=="1"?1:0,g?d():c[a].start||c[a].loaded?(b(),i.start(a)):d(),c[a].start=1}return"object"==typeof a&&a instanceof Array?h(a,b):(b=b||function(){e.promise()},c[a]?c[a].callback.then(k):(j=d(),j.then(k),c[a]={loaded:0,start:0,callback:j}),void(c[a].callback.running||i.start(a)))}return c={},i.competeLoad=function(a,b,c,d,e,f){for(e=0,f=a.length;e<f;e++)i(a.shift(),function(){return b.flag?c():(b(),void(b.flag=1))},d)},i.start=function(a,b){if(g.onload)if(a)c[a].callback.promise();else for(b in c)c[b].callback.promise()},i}function k(c){var f,g,d=c.offsetTop,e=c.offsetParent;if(null==e&&c.parentNode)for(f=c.parentNode;null==e&&(e=f.offsetParent,f=f.parentNode););for(;e;)d+=e.offsetTop+e.clientTop,e=e.offsetParent;return"number"==typeof a.pageYOffset?g=a.pageYOffset:(docElement=b.compatMode&&"CSS1Compat"===b.compatMode?b.documentElement:b.body,g=docElement.scrollTop),d-g}function l(){return b.compatMode&&"BackCompat"==b.compatMode&&b.body?{width:b.body.clientWidth,height:b.body.clientHeight}:{width:b.documentElement.clientWidth,height:b.documentElement.clientHeight}}function m(a,c){c=b.createElement("style"),c.type="text/css",c.styleSheet?c.styleSheet.cssText=a:c.innerHTML=a,b.getElementsByTagName("head")[0].appendChild(c)}function n(c,d,e,f){e=b.createElement("link"),f=b.getElementsByTagName("script")[0],d=d||function(){},e.rel="stylesheet",e.type="text/css",e.href=c;try{f.parentNode.insertBefore(e,f),a.addEventListener?e.addEventListener("load",d,!1):a.attachEvent?e.onreadystatechange=function(){this.readyState.match(/loaded|complete/i)&&d()}:e.onload=function(){d()}}catch(a){d()}}var e=d(),f=i(),g={};g.registerOnResize=h(),e.then(function(){function p(){if(m>=h.length)return void(a.addEventListener?b.removeEventListener("scroll",p,!1):a.attachEvent&&a.detachEvent(event,p));for(c=0,j=h.length;c<j;c++)h[c].getAttribute("src")||(n=k(h[c]),o=h[c].getAttribute("height")||0,n>=-o&&n<i.height&&(f=h[c].getAttribute("osrc"))&&(h[c].setAttribute("src",f),h[c].onerror=function(){(f=this.getAttribute("osrc-bak"))&&(this.setAttribute("src",f),this.onerror=null)},h[c].onload=function(){m++}))}var c,f,n,o,h=b.getElementsByTagName("IMG"),i=l(),m=0;g.registerOnResize(function(){i=l()}),a.addEventListener?b.addEventListener("scroll",p,!1):a.attachEvent&&a.attachEvent("onscroll",p),p();var q=1,r=function(){p(),q*=2,q>1e3&&(q=1e3),setTimeout(r,q)};setTimeout(r,q),e.promise()}),"function"!=typeof b.getElementsByClassName&&(b.getElementsByClassName=function(a){var f,g,a,c=b.getElementsByTagName("*"),d=new RegExp("\\b"+a+"\\b"),e=[];for(f=0,g=c.length;f<g;f++)a=c[f].className,d.test(a)&&e.push(c[f]);return e}),e.then(function(a,c){for(a=b.getElementsByClassName("lazyCss"),c=0;c<a.length;c++)m(a[c].value||a[c].innerHTML);e.promise()}),e.then(function(){var c,d,a=b.getElementsByClassName("lazyHtml");for(c=0;c<a.length;c++)"TEXTAREA"==a[c].tagName&&(d=b.createElement("DIV"),d.innerHTML=a[c].value,a[c].parentNode.insertBefore(d,a[c]));e.promise()});var o=function(){};"function"==typeof a.onload&&(o=a.onload),g.deferred=e,g.createDeferred=d,g.loadJs=f,g.loadCss=n,g.onload=0,g.run=function(){g.onload||(g.onload=1,e.promise(),f.start(),o())},a.lml=g,a.onload=g.run}(window,document);
<|endoftext|>


<commit_before>/*
 * uiRotate 0.1.0
 * http://github.com/cyan92128505/AngularRoulette
 *
 * Licensed under the MIT license
 */
(function (angular) {
    return angular.module('ui.rotate', [])
.service('uiRotateSupported', function () {
    var supportedCSS;
    var styles = document.getElementsByTagName("head")[0].style;
    var toCheck = "transformProperty WebkitTransform OTransform msTransform MozTransform".split(" "); //MozTransform <- firefox works slower with css!!!
    for (var a = 0; a < toCheck.length; a++) {
        if (styles[toCheck[a]] !== undefined) {
            supportedCSS = toCheck[a];
        }
    }

    var IE = eval('"v"=="\v"');

    return {
        IE: IE,
        supportedCSS: supportedCSS
    };
})
.service('uiRotateWilq32', ['uiRotateSupported', function (uiRotateSupported) {
            // Library agnostic interface
            var IE = uiRotateSupported.IE;
            var supportedCSS = uiRotateSupported.supportedCSS;
            var Wilq32 = {};

            Wilq32.PhotoEffect = (function () {

                if (supportedCSS) {
                    return function (img, parameters) {
                        img.Wilq32 = {
                            PhotoEffect: this
                        };

                        this._img = this._rootObj = this._eventObj = img;
                        this._handleRotation(parameters);
                    }
                } else if (IE) {
                    return function (img, parameters) {
                        // Make sure that class and id are also copied - just in case you would like to refeer to an newly created object
                        this._img = img;

                        this._rootObj = document.createElement('span');
                        this._rootObj.style.display = "inline-block";
                        this._rootObj.Wilq32 = {
                            PhotoEffect: this
                        };
                        img.parentNode.insertBefore(this._rootObj, img);
                        this._Loader(parameters);
                    }
                } else {
                    return function (img, parameters) {
                        // Just for now... Dont do anything if CSS3 is not supported
                        this._rootObj = img;
                    }
                }
            })();

            Wilq32.PhotoEffect.prototype = {
                _setupParameters: function (parameters) {
                    this._parameters = this._parameters || {};
                    if (typeof this._angle !== "number") {
                        this._angle = 0;
                    }
                    if (typeof parameters.angle === "number") {
                        this._angle = parameters.angle;
                    }
                    this._parameters.animateTo = (typeof parameters.animateTo === "number") ? (parameters.animateTo) : (this._angle);

                    this._parameters.step = parameters.step || this._parameters.step || null;
                    this._parameters.easing = parameters.easing || this._parameters.easing || function (x, t, b, c, d) {
                        return -c * ((t = t / d - 1) * t * t * t - 1) + b;
                    }
                    this._parameters.duration = parameters.duration || this._parameters.duration || 1000;
                    this._parameters.callback = parameters.callback || this._parameters.callback || function () {};
                    if (parameters.bind && parameters.bind != this._parameters.bind) {
                        this._BindEvents(parameters.bind);
                    }
                },

                _handleRotation: function (parameters) {
                    this._setupParameters(parameters);
                    if (this._angle == this._parameters.animateTo) {
                        this._rotate(this._angle);
                    } else {
                        this._animateStart();
                    }
                },

                _BindEvents: function (events) {
                    if (events && this._eventObj) {
                        // Unbinding previous Events
                        if (this._parameters.bind) {
                            var oldEvents = this._parameters.bind;
                            for (var a in oldEvents) {
                                if (oldEvents.hasOwnProperty(a)) {
                                    angular.element(this._eventObj).off(a, oldEvents[a]);
                                }
                            }
                        }

                        this._parameters.bind = events;
                        for (var a in events) {
                            if (events.hasOwnProperty(a)) {
                                angular.element(this._eventObj).on(a, events[a]);
                            }

                        }
                    }
                },

                _Loader: function (parameters) {
                    var width = this._img.width;
                    var height = this._img.height;
                    //this._img.parentNode.removeChild(this._img);
                    //this._rootObj.parentNode.removeChild(this._rootObj);

                    this._rootObj.appendChild(this._img);

                    this._rootObj.style.width = this._img.offsetWidth;
                    this._rootObj.style.height = this._img.offsetHeight;

                    this._img.style.position = "absolute";

                    this._rootObj = this._img;
                    this._rootObj.Wilq32 = {
                        PhotoEffect: this
                    }

                    this._rootObj.style.filter += "progid:DXImageTransform.Microsoft.Matrix(M11=1,M12=1,M21=1,M22=1,sizingMethod='auto expand')";

                    this._eventObj = this._rootObj;
                    this._handleRotation(parameters);
                },

                _animateStart: function () {
                    if (this._timer) {
                        clearTimeout(this._timer);
                    }
                    this._animateStartTime = +new Date;
                    this._animateStartAngle = this._angle;
                    this._animate();
                },

                _animate: function () {
                    var actualTime = +new Date;
                    var checkEnd = actualTime - this._animateStartTime > this._parameters.duration;

                    // TODO: Bug for animatedGif for static rotation ? (to test)
                    if (checkEnd && !this._parameters.animatedGif) {
                        clearTimeout(this._timer);
                    } else {
                        if (this._canvas || this._vimage || this._img) {
                            var angle = this._parameters.easing(0, actualTime - this._animateStartTime, this._animateStartAngle, this._parameters.animateTo - this._animateStartAngle, this._parameters.duration);
                            this._rotate((~~(angle * 10)) / 10);
                        }
                        if (this._parameters.step) {
                            this._parameters.step(this._angle);
                        }
                        var self = this;
                        this._timer = setTimeout(function () {
                                self._animate.call(self);
                            }, 10);
                    }

                    // To fix Bug that prevents using recursive function in callback I moved this function to back
                    if (this._parameters.callback && checkEnd) {
                        this._angle = this._parameters.animateTo;
                        this._rotate(this._angle);
                        this._parameters.callback.call(this._rootObj);
                    }
                },

                _rotate: (function () {
                    var rad = Math.PI / 180;
                    if (IE) {
                        return function (angle) {
                            this._angle = angle;
                            //this._container.style.rotation=(angle%360)+"deg";
                            var _rad = angle * rad;
                            costheta = Math.cos(_rad);
                            sintheta = Math.sin(_rad);
                            var fil = this._rootObj.filters.item("DXImageTransform.Microsoft.Matrix");
                            fil.M11 = costheta;
                            fil.M12 = -sintheta;
                            fil.M21 = sintheta;
                            fil.M22 = costheta;

                            this._rootObj.style.marginLeft =  - (this._rootObj.offsetWidth - this._rootObj.clientWidth) / 2 + "px";
                            this._rootObj.style.marginTop =  - (this._rootObj.offsetHeight - this._rootObj.clientHeight) / 2 + "px";
                        }
                    } else if (supportedCSS) {
                        return function (angle) {
                            this._angle = angle;
                            this._img.style[supportedCSS] = "rotate(" + (angle % 360) + "deg)";
                        }
                    }

                })()
            };

            return Wilq32;
        }
    ])
.service('uiRotateCore', ['uiRotateWilq32', function (uiRotateWilq32) {
            return function (_rootElement) {
                var Wilq32 = uiRotateWilq32;
                var rootElement = angular.element(_rootElement);
                return {
                    rotate: function (parameters) {
                        if (rootElement.length === 0 || typeof parameters == "undefined") {
                            return;
                        }
                        if (typeof parameters == "number") {
                            parameters = {
                                angle: parameters
                            };
                        }
                        var returned = [];
                        for (var i = 0, i0 = rootElement.length; i < i0; i++) {
                            if (!rootElement[i].Wilq32 || !rootElement[i].Wilq32.PhotoEffect) {

                                var paramClone = angular.copy(parameters);
                                var newRotObject = new Wilq32.PhotoEffect(rootElement[i], paramClone)._rootObj;

                                returned.push(rootElement[i](newRotObject));
                            } else {
                                rootElement[i].Wilq32.PhotoEffect._handleRotation(parameters);
                            }
                        }
                        return returned;
                    },
                    getRotateAngle: function () {
                        var ret = [];
                        for (var i = 0, i0 = rootElement.length; i < i0; i++) {
                            if (rootElement[i].Wilq32 && rootElement[i].Wilq32.PhotoEffect) {
                                ret[i] = rootElement[i].Wilq32.PhotoEffect._angle;
                            }
                        }
                        return ret;
                    },
                    stopRotate: function () {
                        for (var i = 0, i0 = rootElement.length; i < i0; i++) {
                            if (rootElement[i].Wilq32 && rootElement[i].Wilq32.PhotoEffect) {
                                clearTimeout(rootElement[i].Wilq32.PhotoEffect._timer);
                            }
                        }
                    }
                }
            }
        }
    ]);

})(angular)
<commit_msg>Fixed return no element<commit_after>/*
 * uiRotate 0.1.0
 * http://github.com/cyan92128505/AngularRoulette
 *
 * Licensed under the MIT license
 */
(function (angular) {
    return angular.module('ui.rotate', [])
.service('uiRotateSupported', function () {
    var supportedCSS;
    var styles = document.getElementsByTagName("head")[0].style;
    var toCheck = "transformProperty WebkitTransform OTransform msTransform MozTransform".split(" "); //MozTransform <- firefox works slower with css!!!
    for (var a = 0; a < toCheck.length; a++) {
        if (styles[toCheck[a]] !== undefined) {
            supportedCSS = toCheck[a];
        }
    }

    var IE = eval('"v"=="\v"');

    return {
        IE: IE,
        supportedCSS: supportedCSS
    };
})
.service('uiRotateWilq32', ['uiRotateSupported', function (uiRotateSupported) {
    // Library agnostic interface
    var IE = uiRotateSupported.IE;
    var supportedCSS = uiRotateSupported.supportedCSS;
    var Wilq32 = {};

    Wilq32.PhotoEffect = (function () {

        if (supportedCSS) {
            return function (img, parameters) {
                img.Wilq32 = {
                    PhotoEffect: this
                };

                this._img = this._rootObj = this._eventObj = img;
                this._handleRotation(parameters);
            }
        } else if (IE) {
            return function (img, parameters) {
                // Make sure that class and id are also copied - just in case you would like to refeer to an newly created object
                this._img = img;

                this._rootObj = document.createElement('span');
                this._rootObj.style.display = "inline-block";
                this._rootObj.Wilq32 = {
                    PhotoEffect: this
                };
                img.parentNode.insertBefore(this._rootObj, img);
                this._Loader(parameters);
            }
        } else {
            return function (img, parameters) {
                // Just for now... Dont do anything if CSS3 is not supported
                this._rootObj = img;
            }
        }
    })();

    Wilq32.PhotoEffect.prototype = {
        _setupParameters: function (parameters) {
            this._parameters = this._parameters || {};
            if (typeof this._angle !== "number") {
                this._angle = 0;
            }
            if (typeof parameters.angle === "number") {
                this._angle = parameters.angle;
            }
            this._parameters.animateTo = (typeof parameters.animateTo === "number") ? (parameters.animateTo) : (this._angle);

            this._parameters.step = parameters.step || this._parameters.step || null;
            this._parameters.easing = parameters.easing || this._parameters.easing || function (x, t, b, c, d) {
                return -c * ((t = t / d - 1) * t * t * t - 1) + b;
            }
            this._parameters.duration = parameters.duration || this._parameters.duration || 1000;
            this._parameters.callback = parameters.callback || this._parameters.callback || function () { };
            if (parameters.bind && parameters.bind != this._parameters.bind) {
                this._BindEvents(parameters.bind);
            }
        },

        _handleRotation: function (parameters) {
            this._setupParameters(parameters);
            if (this._angle == this._parameters.animateTo) {
                this._rotate(this._angle);
            } else {
                this._animateStart();
            }
        },

        _BindEvents: function (events) {
            if (events && this._eventObj) {
                // Unbinding previous Events
                if (this._parameters.bind) {
                    var oldEvents = this._parameters.bind;
                    for (var a in oldEvents) {
                        if (oldEvents.hasOwnProperty(a)) {
                            angular.element(this._eventObj).off(a, oldEvents[a]);
                        }
                    }
                }

                this._parameters.bind = events;
                for (var a in events) {
                    if (events.hasOwnProperty(a)) {
                        angular.element(this._eventObj).on(a, events[a]);
                    }

                }
            }
        },

        _Loader: function (parameters) {
            var width = this._img.width;
            var height = this._img.height;
            //this._img.parentNode.removeChild(this._img);
            //this._rootObj.parentNode.removeChild(this._rootObj);

            this._rootObj.appendChild(this._img);

            this._rootObj.style.width = this._img.offsetWidth;
            this._rootObj.style.height = this._img.offsetHeight;

            this._img.style.position = "absolute";

            this._rootObj = this._img;
            this._rootObj.Wilq32 = {
                PhotoEffect: this
            }

            this._rootObj.style.filter += "progid:DXImageTransform.Microsoft.Matrix(M11=1,M12=1,M21=1,M22=1,sizingMethod='auto expand')";

            this._eventObj = this._rootObj;
            this._handleRotation(parameters);
        },

        _animateStart: function () {
            if (this._timer) {
                clearTimeout(this._timer);
            }
            this._animateStartTime = +new Date;
            this._animateStartAngle = this._angle;
            this._animate();
        },

        _animate: function () {
            var actualTime = +new Date;
            var checkEnd = actualTime - this._animateStartTime > this._parameters.duration;

            // TODO: Bug for animatedGif for static rotation ? (to test)
            if (checkEnd && !this._parameters.animatedGif) {
                clearTimeout(this._timer);
            } else {
                if (this._canvas || this._vimage || this._img) {
                    var angle = this._parameters.easing(0, actualTime - this._animateStartTime, this._animateStartAngle, this._parameters.animateTo - this._animateStartAngle, this._parameters.duration);
                    this._rotate((~~(angle * 10)) / 10);
                }
                if (this._parameters.step) {
                    this._parameters.step(this._angle);
                }
                var self = this;
                this._timer = setTimeout(function () {
                    self._animate.call(self);
                }, 10);
            }

            // To fix Bug that prevents using recursive function in callback I moved this function to back
            if (this._parameters.callback && checkEnd) {
                this._angle = this._parameters.animateTo;
                this._rotate(this._angle);
                this._parameters.callback.call(this._rootObj);
            }
        },

        _rotate: (function () {
            var rad = Math.PI / 180;
            if (IE) {
                return function (angle) {
                    this._angle = angle;
                    //this._container.style.rotation=(angle%360)+"deg";
                    var _rad = angle * rad;
                    costheta = Math.cos(_rad);
                    sintheta = Math.sin(_rad);
                    var fil = this._rootObj.filters.item("DXImageTransform.Microsoft.Matrix");
                    fil.M11 = costheta;
                    fil.M12 = -sintheta;
                    fil.M21 = sintheta;
                    fil.M22 = costheta;

                    this._rootObj.style.marginLeft = -(this._rootObj.offsetWidth - this._rootObj.clientWidth) / 2 + "px";
                    this._rootObj.style.marginTop = -(this._rootObj.offsetHeight - this._rootObj.clientHeight) / 2 + "px";
                }
            } else if (supportedCSS) {
                return function (angle) {
                    this._angle = angle;
                    this._img.style[supportedCSS] = "rotate(" + (angle % 360) + "deg)";
                }
            }

        })()
    };

    return Wilq32;
}
])
.service('uiRotateCore', ['uiRotateWilq32', function (uiRotateWilq32) {
    return function (_rootElement) {
        var Wilq32 = uiRotateWilq32;
        var rootElement = angular.element(_rootElement);
        return {
            rotate: function (parameters) {
                if (rootElement.length === 0 || typeof parameters == "undefined") {
                    return;
                }
                if (typeof parameters == "number") {
                    parameters = {
                        angle: parameters
                    };
                }
                var returned = [];
                for (var i = 0, i0 = rootElement.length; i < i0; i++) {
                    if (!rootElement[i].Wilq32 || !rootElement[i].Wilq32.PhotoEffect) {

                        var paramClone = angular.copy(parameters);
                        var newRotObject = new Wilq32.PhotoEffect(rootElement[i], paramClone)._rootObj;
                        returned.push(newRotObject);
                    } else {
                        rootElement[i].Wilq32.PhotoEffect._handleRotation(parameters);
                    }
                }
                return returned;
            },
            getRotateAngle: function () {
                var ret = [];
                for (var i = 0, i0 = rootElement.length; i < i0; i++) {
                    if (rootElement[i].Wilq32 && rootElement[i].Wilq32.PhotoEffect) {
                        ret[i] = rootElement[i].Wilq32.PhotoEffect._angle;
                    }
                }
                return ret;
            },
            stopRotate: function () {
                for (var i = 0, i0 = rootElement.length; i < i0; i++) {
                    if (rootElement[i].Wilq32 && rootElement[i].Wilq32.PhotoEffect) {
                        clearTimeout(rootElement[i].Wilq32.PhotoEffect._timer);
                    }
                }
            }
        }
    }
}
]);

})(angular)
<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import MatrixClientPeg from './MatrixClientPeg';
import MultiInviter from '../../../utils/MultiInviter';

const emailRegex = /^\S+@\S+\.\S+$/;

export function getAddressType(inputText) {
    const isEmailAddress = /^\S+@\S+\.\S+$/.test(inputText);
    const isMatrixId = inputText[0] === '@' && inputText.indexOf(":") > 0;

    // sanity check the input for user IDs
    if (isEmailAddress) {
        return 'email';
    } else if (isMatrixId) {
        return 'mx';
    } else {
        return null;
    }
}

export function inviteToRoom(roomId, addr) {
    const addrType = getAddressType(addr);

    if (addrType == 'email') {
        return MatrixClientPeg.get().inviteByEmail(roomId, addr);
    } else if (addrType == 'mx') {
        return MatrixClientPeg.get().invite(roomId, addr);
    } else {
        throw new Error('Unsupported address');
    }
}

/**
 * Invites multiple addresses to a room
 * Simpler interface to utils/MultiInviter but with
 * no option to cancel.
 *
 * @param {roomId} The ID of the room to invite to
 * @param {array} Array of strings of addresses to invite. May be matrix IDs or 3pids.
 * @returns Promise
 */
export function inviteMultipleToRoom(roomId, addrs) {
    this.inviter = new MultiInviter(roomId);
    return inviter.invite(addrs);
}

export function isValidAddress(addr) {
    // Check if the addr is a valid type
    var addrType = this.getAddressType(addr);
    if (addrType === "mx") {
        let user = MatrixClientPeg.get().getUser(addr);
        if (user) {
            return true;
        } else {
            return false;
        }
    } else if (addrType === "email") {
        return true;
    } else {
        return false;
    }
}
<commit_msg>Correct path for MultiInviter<commit_after>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import MatrixClientPeg from './MatrixClientPeg';
import MultiInviter from './utils/MultiInviter';

const emailRegex = /^\S+@\S+\.\S+$/;

export function getAddressType(inputText) {
    const isEmailAddress = /^\S+@\S+\.\S+$/.test(inputText);
    const isMatrixId = inputText[0] === '@' && inputText.indexOf(":") > 0;

    // sanity check the input for user IDs
    if (isEmailAddress) {
        return 'email';
    } else if (isMatrixId) {
        return 'mx';
    } else {
        return null;
    }
}

export function inviteToRoom(roomId, addr) {
    const addrType = getAddressType(addr);

    if (addrType == 'email') {
        return MatrixClientPeg.get().inviteByEmail(roomId, addr);
    } else if (addrType == 'mx') {
        return MatrixClientPeg.get().invite(roomId, addr);
    } else {
        throw new Error('Unsupported address');
    }
}

/**
 * Invites multiple addresses to a room
 * Simpler interface to utils/MultiInviter but with
 * no option to cancel.
 *
 * @param {roomId} The ID of the room to invite to
 * @param {array} Array of strings of addresses to invite. May be matrix IDs or 3pids.
 * @returns Promise
 */
export function inviteMultipleToRoom(roomId, addrs) {
    this.inviter = new MultiInviter(roomId);
    return inviter.invite(addrs);
}

export function isValidAddress(addr) {
    // Check if the addr is a valid type
    var addrType = this.getAddressType(addr);
    if (addrType === "mx") {
        let user = MatrixClientPeg.get().getUser(addr);
        if (user) {
            return true;
        } else {
            return false;
        }
    } else if (addrType === "email") {
        return true;
    } else {
        return false;
    }
}
<|endoftext|>


<commit_before>// legacy, what's left to modulify!

// vendor (remove globals in eslintrc as these are removed)
import './legacyVendor';

// app helpers, last to be removed
import './legacyHelpers';

// student profile page:
  // pure ui components:
import '../app/assets/javascripts/student_profile/help_bubble.js';
import '../app/assets/javascripts/student_profile/quad_converter.jsx';
import '../app/assets/javascripts/student_profile/risk_bubble.jsx';
import '../app/assets/javascripts/student_profile/service_color.jsx';
import '../app/assets/javascripts/student_profile/provided_by_educator_dropdown.jsx';
import '../app/assets/javascripts/student_profile/profile_chart_settings.jsx';
import '../app/assets/javascripts/student_profile/educator.jsx';
import '../app/assets/javascripts/student_profile/datepicker.jsx';
import '../app/assets/javascripts/student_profile/highcharts_wrapper.jsx';
import '../app/assets/javascripts/student_profile/bar_chart_sparkline.jsx';
import '../app/assets/javascripts/student_profile/sparkline.jsx';
import '../app/assets/javascripts/student_profile/scales.jsx';
import '../app/assets/javascripts/student_profile/academic_summary.jsx';
import '../app/assets/javascripts/student_profile/take_notes.jsx';
import '../app/assets/javascripts/student_profile/editable_text_component.jsx';
import '../app/assets/javascripts/student_profile/note_card.jsx';
import '../app/assets/javascripts/student_profile/notes_list.jsx';
import '../app/assets/javascripts/student_profile/services_list.jsx';
import '../app/assets/javascripts/student_profile/record_service.jsx';
import '../app/assets/javascripts/student_profile/summary_list.jsx';
import '../app/assets/javascripts/student_profile/profile_chart.jsx';
import '../app/assets/javascripts/student_profile/profile_bar_chart.jsx';
import '../app/assets/javascripts/student_profile/modal_small_icon.jsx';
import '../app/assets/javascripts/student_profile/student_profile_header.jsx';
import '../app/assets/javascripts/student_profile/student_sections_roster.jsx';
import '../app/assets/javascripts/student_profile/pdf/student_profile_pdf.js';

  // details:
import '../app/assets/javascripts/student_profile/services_details.jsx';
import '../app/assets/javascripts/student_profile/notes_details.js';
import '../app/assets/javascripts/student_profile/profile_details.jsx';
import '../app/assets/javascripts/student_profile/attendance_details.jsx';
import '../app/assets/javascripts/student_profile/ela_details.jsx';
import '../app/assets/javascripts/student_profile/math_details.jsx';

  // page:
import '../app/assets/javascripts/student_profile/student_profile_page.jsx';
  // (unordered)
import '../app/assets/javascripts/student_profile/api.js';
import '../app/assets/javascripts/student_profile/page_container.jsx';
import '../app/assets/javascripts/student_profile/parse_query_string.jsx';

// bulk services:
import '../app/assets/javascripts/service_uploads/service_type_dropdown.jsx';

// all the rest, unordered
import '../app/assets/javascripts/section/section_header.jsx';
import '../app/assets/javascripts/section/section_page.jsx';
import '../app/assets/javascripts/service_uploads/new_service_upload.jsx';
import '../app/assets/javascripts/service_uploads/service_upload_detail.jsx';
import '../app/assets/javascripts/service_uploads/service_uploads_page.jsx';

<commit_msg>Remove Api.js from legacy JS file since it's moduleified<commit_after>// legacy, what's left to modulify!

// vendor (remove globals in eslintrc as these are removed)
import './legacyVendor';

// app helpers, last to be removed
import './legacyHelpers';

// student profile page:
  // pure ui components:
import '../app/assets/javascripts/student_profile/help_bubble.js';
import '../app/assets/javascripts/student_profile/quad_converter.jsx';
import '../app/assets/javascripts/student_profile/risk_bubble.jsx';
import '../app/assets/javascripts/student_profile/service_color.jsx';
import '../app/assets/javascripts/student_profile/provided_by_educator_dropdown.jsx';
import '../app/assets/javascripts/student_profile/profile_chart_settings.jsx';
import '../app/assets/javascripts/student_profile/educator.jsx';
import '../app/assets/javascripts/student_profile/datepicker.jsx';
import '../app/assets/javascripts/student_profile/highcharts_wrapper.jsx';
import '../app/assets/javascripts/student_profile/bar_chart_sparkline.jsx';
import '../app/assets/javascripts/student_profile/sparkline.jsx';
import '../app/assets/javascripts/student_profile/scales.jsx';
import '../app/assets/javascripts/student_profile/academic_summary.jsx';
import '../app/assets/javascripts/student_profile/take_notes.jsx';
import '../app/assets/javascripts/student_profile/editable_text_component.jsx';
import '../app/assets/javascripts/student_profile/note_card.jsx';
import '../app/assets/javascripts/student_profile/notes_list.jsx';
import '../app/assets/javascripts/student_profile/services_list.jsx';
import '../app/assets/javascripts/student_profile/record_service.jsx';
import '../app/assets/javascripts/student_profile/summary_list.jsx';
import '../app/assets/javascripts/student_profile/profile_chart.jsx';
import '../app/assets/javascripts/student_profile/profile_bar_chart.jsx';
import '../app/assets/javascripts/student_profile/modal_small_icon.jsx';
import '../app/assets/javascripts/student_profile/student_profile_header.jsx';
import '../app/assets/javascripts/student_profile/student_sections_roster.jsx';
import '../app/assets/javascripts/student_profile/pdf/student_profile_pdf.js';

  // details:
import '../app/assets/javascripts/student_profile/services_details.jsx';
import '../app/assets/javascripts/student_profile/notes_details.js';
import '../app/assets/javascripts/student_profile/profile_details.jsx';
import '../app/assets/javascripts/student_profile/attendance_details.jsx';
import '../app/assets/javascripts/student_profile/ela_details.jsx';
import '../app/assets/javascripts/student_profile/math_details.jsx';

  // page:
import '../app/assets/javascripts/student_profile/student_profile_page.jsx';
  // (unordered)
import '../app/assets/javascripts/student_profile/page_container.jsx';
import '../app/assets/javascripts/student_profile/parse_query_string.jsx';

// bulk services:
import '../app/assets/javascripts/service_uploads/service_type_dropdown.jsx';

// all the rest, unordered
import '../app/assets/javascripts/section/section_header.jsx';
import '../app/assets/javascripts/section/section_page.jsx';
import '../app/assets/javascripts/service_uploads/new_service_upload.jsx';
import '../app/assets/javascripts/service_uploads/service_upload_detail.jsx';
import '../app/assets/javascripts/service_uploads/service_uploads_page.jsx';

<|endoftext|>


<commit_before>'use strict'
/* eslint-env node, mocha */

const expect = require('chai').expect
const sinon = require('sinon')
const WhosHiring = require('../lib/whoshiring')
const HNSearch = require('hacker-news-api')

describe('WhosHiring', function () {
  // -------------------------------------------------------------
  // Fixtures
  // -------------------------------------------------------------

  const mockObjectID = 123
  const mockTitle = 'title text'
  const searchTerms = 'search terms'

  // Fake story result
  //
  const mockStorySearch = Promise.resolve({
    hits: [{
      objectID: mockObjectID,
      title: mockTitle
    }]
  })

  // Fake matches result
  //
  const mockMatches = [
    { comment_text: 'first comment' },
    { comment_text: 'second comment' },
    { comment_text: 'third comment' }
  ]

  const mockMatchesSearch = Promise.resolve({
    hits: mockMatches
  })

  // -------------------------------------------------------------
  // Sinon sandbox setup/teardown
  // -------------------------------------------------------------

  const sinonbox = sinon.sandbox.create({
    useFakeTimers: false,
    useFakeServer: false
  })

  // Before each test, stub and spy HNSearch methods
  //
  // Spies and Stubs notes:
  //   HNSearch.searchAsync is stubbed to provide
  //   the fixtures defined above
  //
  //   WhosHiring.url is spied
  //   WhosHiring.title is spied
  //
  beforeEach(function () {
    const searchAsync = sinonbox
      .stub(HNSearch, 'searchAsync')
      .returns(mockStorySearch)

    searchAsync
      .withArgs(searchTerms)
      .returns(mockMatchesSearch)

    sinonbox.spy(WhosHiring, 'url')
    sinonbox.spy(WhosHiring, 'title')
  })

  afterEach(function () {
    sinonbox.restore()
    WhosHiring.resetStoryCache()
  })

  // -------------------------------------------------------------
  // Tests
  // -------------------------------------------------------------

  describe('WhosHiring.url()', function () {
    it('should only call searchAsync once', function () {
      return Promise
        .resolve()
        .then(WhosHiring.url)
        .then(WhosHiring.url)
        .then(WhosHiring.url)
        .then((url) => {
          sinon.assert.calledThrice(WhosHiring.url)
          sinon.assert.calledOnce(HNSearch.searchAsync)
        })
    })

    it('should return a url with the mockObjectID', function () {
      return WhosHiring
        .url()
        .then((url) => {
          expect(url).to.match(new RegExp(`${mockObjectID}`))
        })
    })
  })

  describe('WhosHiring.title()', function () {
    it('should only call searchAsync once', function () {
      return Promise
        .resolve()
        .then(WhosHiring.title)
        .then(WhosHiring.title)
        .then(WhosHiring.title)
        .then((url) => {
          sinon.assert.calledThrice(WhosHiring.title)
          sinon.assert.calledOnce(HNSearch.searchAsync)
        })
    })

    it('should return a title with the mockTitle', function () {
      return WhosHiring
        .title()
        .then((title) => {
          expect(title).to.equal(mockTitle)
        })
    })
  })

  describe('WhosHiring.matches(terms)', function () {
    it('should return all matches ', function () {
      return WhosHiring
        .matches(searchTerms)
        .then((results) => {
          expect(results.length).to.equal(mockMatches.length)
        })
    })

    it('should return matches as strings', function () {
      return WhosHiring
        .matches(searchTerms)
        .then((results) => {
          results.forEach((result) => {
            expect(result).to.be.a('string')
          })
        })
    })

    it('should return matches from fixture', function () {
      const expected = mockMatches.map((m) => m.comment_text)

      return WhosHiring
        .matches(searchTerms)
        .then((results) => {
          expect(results).to.deep.equal(expected)
        })
    })
  })
})
<commit_msg>Rename sinonbox sandbox in whoshiring test<commit_after>'use strict'
/* eslint-env node, mocha */

const expect = require('chai').expect
const sinon = require('sinon')
const WhosHiring = require('../lib/whoshiring')
const HNSearch = require('hacker-news-api')

describe('WhosHiring', function () {
  // -------------------------------------------------------------
  // Fixtures
  // -------------------------------------------------------------

  const mockObjectID = 123
  const mockTitle = 'title text'
  const searchTerms = 'search terms'

  // Fake story result
  //
  const mockStorySearch = Promise.resolve({
    hits: [{
      objectID: mockObjectID,
      title: mockTitle
    }]
  })

  // Fake matches result
  //
  const mockMatches = [
    { comment_text: 'first comment' },
    { comment_text: 'second comment' },
    { comment_text: 'third comment' }
  ]

  const mockMatchesSearch = Promise.resolve({
    hits: mockMatches
  })

  // -------------------------------------------------------------
  // Sinon sandbox setup/teardown
  // -------------------------------------------------------------

  const sandbox = sinon.sandbox.create({
    useFakeTimers: false,
    useFakeServer: false
  })

  // Before each test, stub and spy HNSearch methods
  //
  // Spies and Stubs notes:
  //   HNSearch.searchAsync is stubbed to provide
  //   the fixtures defined above
  //
  //   WhosHiring.url is spied
  //   WhosHiring.title is spied
  //
  beforeEach(function () {
    const searchAsync = sandbox
      .stub(HNSearch, 'searchAsync')
      .returns(mockStorySearch)

    searchAsync
      .withArgs(searchTerms)
      .returns(mockMatchesSearch)

    sandbox.spy(WhosHiring, 'url')
    sandbox.spy(WhosHiring, 'title')
  })

  afterEach(function () {
    sandbox.restore()
    WhosHiring.resetStoryCache()
  })

  // -------------------------------------------------------------
  // Tests
  // -------------------------------------------------------------

  describe('WhosHiring.url()', function () {
    it('should only call searchAsync once', function () {
      return Promise
        .resolve()
        .then(WhosHiring.url)
        .then(WhosHiring.url)
        .then(WhosHiring.url)
        .then((url) => {
          sinon.assert.calledThrice(WhosHiring.url)
          sinon.assert.calledOnce(HNSearch.searchAsync)
        })
    })

    it('should return a url with the mockObjectID', function () {
      return WhosHiring
        .url()
        .then((url) => {
          expect(url).to.match(new RegExp(`${mockObjectID}`))
        })
    })
  })

  describe('WhosHiring.title()', function () {
    it('should only call searchAsync once', function () {
      return Promise
        .resolve()
        .then(WhosHiring.title)
        .then(WhosHiring.title)
        .then(WhosHiring.title)
        .then((url) => {
          sinon.assert.calledThrice(WhosHiring.title)
          sinon.assert.calledOnce(HNSearch.searchAsync)
        })
    })

    it('should return a title with the mockTitle', function () {
      return WhosHiring
        .title()
        .then((title) => {
          expect(title).to.equal(mockTitle)
        })
    })
  })

  describe('WhosHiring.matches(terms)', function () {
    it('should return all matches ', function () {
      return WhosHiring
        .matches(searchTerms)
        .then((results) => {
          expect(results.length).to.equal(mockMatches.length)
        })
    })

    it('should return matches as strings', function () {
      return WhosHiring
        .matches(searchTerms)
        .then((results) => {
          results.forEach((result) => {
            expect(result).to.be.a('string')
          })
        })
    })

    it('should return matches from fixture', function () {
      const expected = mockMatches.map((m) => m.comment_text)

      return WhosHiring
        .matches(searchTerms)
        .then((results) => {
          expect(results).to.deep.equal(expected)
        })
    })
  })
})
<|endoftext|>


<commit_before>//const newUser = require('./new_user.js');
const patronGroup = require('./patron_group.js');
const newPermissionSet = require('./new_permission_set.js');
const newProxy = require('./new_proxy.js');

module.exports.test = function meh(uitestctx) {
  patronGroup.test(uitestctx);
  // newUser.test(uitestctx);
  newPermissionSet.test(uitestctx);
  newProxy.test(uitestctx);
};
<commit_msg>Lint: whitespace<commit_after>// const newUser = require('./new_user.js');
const patronGroup = require('./patron_group.js');
const newPermissionSet = require('./new_permission_set.js');
const newProxy = require('./new_proxy.js');

module.exports.test = function meh(uitestctx) {
  patronGroup.test(uitestctx);
  // newUser.test(uitestctx);
  newPermissionSet.test(uitestctx);
  newProxy.test(uitestctx);
};
<|endoftext|>


<commit_before>import axios from 'axios'

// When running in development/hot mode we load the renderer js code via webpack dev server, and it is from there that
// we ultimately initate requests to these remote resources. The end result is that the electron browser window makes a
// request to localhost (to webpack dev server), which in turn makes a request to the remote resource. If the remote
// resource in question has a restrictive `Access-Control-Allow-Origin` header, this may cause the electron browser
// window to not allow loading the remote content.
//
// See https://enable-cors.org/
//
// In order to mitigate the CORS issue, we instead access these remote resources through a local proxy that we have
// defined on the webpack dev server.
const scheme =
  (process && process.env.HOT) || (window.env && window.env.HOT) ? '/proxy/' : 'https://'

export function requestTicker(id) {
  const BASE_URL = `${scheme}api.coinbase.com/v2/exchange-rates?currency=${id}`
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response => response.data)
}

export function requestTickers(ids) {
  return axios.all(ids.map(id => requestTicker(id))).then(
    axios.spread((btcTicker, ltcTicker) => ({
      btcTicker: btcTicker.data.rates,
      ltcTicker: ltcTicker.data.rates,
    }))
  )
}

export function requestSuggestedNodes() {
  const BASE_URL = `${scheme}zap.jackmallers.com/api/v1/suggested-peers`
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response => response.data)
}

export function requestFees() {
  const BASE_URL = 'https://bitcoinfees.earn.com/api/v1/fees/recommended'
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response => response.data)
}
<commit_msg>refactor: add requestNodeScores api method<commit_after>import axios from 'axios'
import { mainLog } from '@zap/utils/log'

// When running in development/hot mode we load the renderer js code via webpack dev server, and it is from there that
// we ultimately initate requests to these remote resources. The end result is that the electron browser window makes a
// request to localhost (to webpack dev server), which in turn makes a request to the remote resource. If the remote
// resource in question has a restrictive `Access-Control-Allow-Origin` header, this may cause the electron browser
// window to not allow loading the remote content.
//
// See https://enable-cors.org/
//
// In order to mitigate the CORS issue, we instead access these remote resources through a local proxy that we have
// defined on the webpack dev server.
const scheme =
  (process && process.env.HOT) || (window.env && window.env.HOT) ? '/proxy/' : 'https://'

export function requestTicker(id) {
  const BASE_URL = `${scheme}api.coinbase.com/v2/exchange-rates?currency=${id}`
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response => response.data)
}

export function requestTickers(ids) {
  return axios.all(ids.map(id => requestTicker(id))).then(
    axios.spread((btcTicker, ltcTicker) => ({
      btcTicker: btcTicker.data.rates,
      ltcTicker: ltcTicker.data.rates,
    }))
  )
}

export function requestSuggestedNodes() {
  const BASE_URL = `${scheme}zap.jackmallers.com/api/v1/suggested-peers`
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response => response.data)
}

export function requestNodeScores(chain, network) {
  const chainMap = {
    bitcoin: 'btc',
    litecoin: 'ltc',
  }
  const networkMap = {
    mainnet: '',
    testnet: 'testnet',
  }
  const code = chainMap[chain]
  const suffix = networkMap[network]
  const chainCode = `${code}${suffix}`
  const BASE_URL = `https://nodes.lightning.computer/availability/v1/${chainCode}.json`
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response =>
    response.data.scores.reduce((map, { public_key, score }) => {
      if (typeof public_key !== 'string' || !Number.isInteger(score)) {
        mainLog.warn('Invalid node score format!')
        return map
      }
      map[public_key] = score / 100000000.0
      return map
    }, {})
  )
}

export function requestFees() {
  const BASE_URL = 'https://bitcoinfees.earn.com/api/v1/fees/recommended'
  return axios({
    method: 'get',
    url: BASE_URL,
  }).then(response => response.data)
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2016 Satoshi Nakajima (https://github.com/snakajima)
// License: The MIT License
//

function load(swipe, prevState) {
  const str = JSON.stringify(swipe, undefined, 2);
  console.log(str);
  const pages = swipe.pages.map((page) => {
    if (page.elements) {
      return page.elements.reduce((ret, element)=>{
        var value = {};
        if (element.to) {
          console.log('load:element=', JSON.stringify(element.to));
          if (element.to.translate) {
            value.translate = element.to.translate;
          }
          if (element.to.opacity) {
            value.opacity = element.to.opacity;
          }
          if (element.to.rotate) {
            value.rotate = element.to.rotate;
          }
          if (element.to.scale) {
            value.scale = element.to.scale;
          }
        }
        ret[element.id] = value;
        return ret;
      }, {});
    }
    return {}
  });
  var state = {
    selection:{ids:new Set()},
    pageIndex:0,
    preview:false,
    dimension:{ width:swipe.dimension[0] || 320, height:swipe.dimension[1] || 320 },
    elements:swipe.templates.pages.s0.elements,
    pages:pages
  };
  return state;
}

module.exports = { load };
<commit_msg>load with rotate and scale<commit_after>//
// Copyright (c) 2016 Satoshi Nakajima (https://github.com/snakajima)
// License: The MIT License
//

function load(swipe, prevState) {
  const str = JSON.stringify(swipe, undefined, 2);
  console.log(str);
  const sceneElements = swipe.templates.pages.s0.elements;
  const elementMap = sceneElements.reduce((map, element)=>{
    map[element.id] = element;
    return map;
  }, {});
  const pages = swipe.pages.map((page) => {
    if (page.elements) {
      return page.elements.reduce((ret, element)=>{
        var value = {};
        const sceneElement = elementMap[element.id];
        console.log("load.map", sceneElement);
        if (element.to) {
          console.log('load:element=', JSON.stringify(element.to));
          if (element.to.translate) {
            value.translate = element.to.translate;
          }
          if (element.to.opacity) {
            value.opacity = element.to.opacity;
          }
          if (element.to.rotate) {
            value.rotate = element.to.rotate;
            if (sceneElement.rotate) {
              value.rotate -= sceneElement.rotate;
            }
          }
          if (element.to.scale) {
            value.scale = element.to.scale;
            if (sceneElement.scale) {
              value.scale[0] /= sceneElement.scale[0];
              value.scale[1] /= sceneElement.scale[1];
            }
          }
        }
        ret[element.id] = value;
        return ret;
      }, {});
    }
    return {}
  });
  var state = {
    selection:{ids:new Set()},
    pageIndex:0,
    preview:false,
    dimension:{ width:swipe.dimension[0] || 320, height:swipe.dimension[1] || 320 },
    elements:sceneElements,
    pages:pages
  };
  return state;
}

module.exports = { load };
<|endoftext|>


<commit_before>// Domino settings:
domino.settings({
  verbose: true,
  strict: true
});

function mod(property, d) {
  domino.module.call(this);
  var self = this;

  // The following array will store a new copy of the property value everytime
  // the property is updated.
  this.historic = [];

  this.triggers.properties[property.id] = function(event) {
    console.log(this, event);
    self.historic.push(this.get(property.id));
  }

  this.dispatch = function(value, event) {
    var a = d.getEvents(property.id),
        o = {};

    console.log(event, a[0]);
    o[property.id] = value;
    this.dispatchEvent(event || a[0], o);
  }
}

function init(properties) {
  var m = {},
      d = new domino({
            properties: properties
          });

  // We initialize a module for each property:
  for (var k in properties)
    m[properties[k].id] = d.addModule(mod, [properties[k]]);

  // We return the instance and the modules:
  return {
    d: d,
    m: m
  };
}

// Properties:
module('Properties management');
test('test 1', function() {
  var o = init([{ id: 's', type: 'string', value: 'abc', triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we simply update the value:
  o.m.s.dispatch('def');
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], 'def', 'The string property has been successfully updated!');
});
test('test 2', function() {
  var o = init([{ id: 's', type: 'string', value: 'abc', triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with a different value, and we want to check that domino has triggered:
  o.m.s.dispatch('def');
  deepEqual(o.m.s.historic.length, 2, 'Updating the string property with a new value effectively triggers the events.');
});
test('test 3', function() {
  var o = init([{ id: 's', type: 'string', value: 'abc', triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with the same value, and we want to check that domino does not trigger:
  o.m.s.dispatch('abc');
  deepEqual(o.m.s.historic.length, 1, 'Updating the string property with the same value does not trigger the events.');
});
test('test 4', function() {
  var o = init([{ id: 's', type: {a: 'number', b: '?number'}, value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we simply update the value:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], {a: 2, b: 1}, 'The complex property ("deeply atomic") has been successfully updated!');
});
test('test 5', function() {
  var o = init([{ id: 's', type: {a: 'number', b: '?number'}, value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with a different value, and we want to check that domino has triggered:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic.length, 2, 'Updating the complex property ("deeply atomic") with a new value effectively triggers the events.');
});
test('test 6', function() {
  var o = init([{ id: 's', type: {a: 'number', b: '?number'}, value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with the same value, and we want to check that domino does not trigger:
  o.m.s.dispatch({a: 1});
  deepEqual(o.m.s.historic.length, 1, 'Updating the complex property ("deeply atomic") with the same value does not trigger the events.');
});
test('test 7', function() {
  var o = init([{ id: 's', type: 'object', value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we simply update the value:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], {a: 2, b: 1}, 'The object property has been successfully updated!');
});
test('test 8', function() {
  var o = init([{ id: 's', type: 'object', value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with a different value, and we want to check that domino has triggered:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic.length, 2, 'Updating the object property with a new value effectively triggers the events.');
});
test('test 9', function() {
  var o = init([{ id: 's', type: 'object', value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with the same value, and we want to check that domino triggers anyway ('object' typed):
  o.m.s.dispatch({a: 1});
  deepEqual(o.m.s.historic.length, 2, 'Updating the object property with the same value actually triggers the events.');
});<commit_msg>added Setter overridding unit test<commit_after>// Domino settings:
domino.settings({
  verbose: true,
  strict: true
});

function mod(property, d) {
  domino.module.call(this);
  var self = this;

  // The following array will store a new copy of the property value everytime
  // the property is updated.
  this.historic = [];

  this.triggers.properties[property.id] = function(event) {
    console.log(this, event);
    self.historic.push(this.get(property.id));
  }

  this.dispatch = function(value, event) {
    var a = d.getEvents(property.id),
        o = {};

    console.log(event, a[0]);
    o[property.id] = value;
    this.dispatchEvent(event || a[0], o);
  }
}

function init(properties) {
  var m = {},
      d = new domino({
            properties: properties
          });

  // We initialize a module for each property:
  for (var k in properties)
    m[properties[k].id] = d.addModule(mod, [properties[k]]);

  // We return the instance and the modules:
  return {
    d: d,
    m: m
  };
}

// Properties:
module('Properties management');
test('test 1', function() {
  var o = init([{ id: 's', type: 'string', value: 'abc', triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we simply update the value:
  o.m.s.dispatch('def');
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], 'def', 'The string property has been successfully updated!');
});
test('test 2', function() {
  var o = init([{ id: 's', type: 'string', value: 'abc', triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with a different value, and we want to check that domino has triggered:
  o.m.s.dispatch('def');
  deepEqual(o.m.s.historic.length, 2, 'Updating the string property with a new value effectively triggers the events.');
});
test('test 3', function() {
  var o = init([{ id: 's', type: 'string', value: 'abc', triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with the same value, and we want to check that domino does not trigger:
  o.m.s.dispatch('abc');
  deepEqual(o.m.s.historic.length, 1, 'Updating the string property with the same value does not trigger the events.');
});
test('test 4', function() {
  var o = init([{ id: 's', type: {a: 'number', b: '?number'}, value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we simply update the value:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], {a: 2, b: 1}, 'The complex property ("deeply atomic") has been successfully updated!');
});
test('test 5', function() {
  var o = init([{ id: 's', type: {a: 'number', b: '?number'}, value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with a different value, and we want to check that domino has triggered:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic.length, 2, 'Updating the complex property ("deeply atomic") with a new value effectively triggers the events.');
});
test('test 6', function() {
  var o = init([{ id: 's', type: {a: 'number', b: '?number'}, value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with the same value, and we want to check that domino does not trigger:
  o.m.s.dispatch({a: 1});
  deepEqual(o.m.s.historic.length, 1, 'Updating the complex property ("deeply atomic") with the same value does not trigger the events.');
});
test('test 7', function() {
  var o = init([{ id: 's', type: 'object', value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we simply update the value:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], {a: 2, b: 1}, 'The object property has been successfully updated!');
});
test('test 8', function() {
  var o = init([{ id: 's', type: 'object', value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with a different value, and we want to check that domino has triggered:
  o.m.s.dispatch({a: 2, b: 1});
  deepEqual(o.m.s.historic.length, 2, 'Updating the object property with a new value effectively triggers the events.');
});
test('test 9', function() {
  var o = init([{ id: 's', type: 'object', value: {a: 1}, triggers: 'updateS', dispatch: 'sUpdated'}]);

  // Here we update the property, but with the same value, and we want to check that domino triggers anyway ('object' typed):
  o.m.s.dispatch({a: 1});
  deepEqual(o.m.s.historic.length, 2, 'Updating the object property with the same value actually triggers the events.');
});
test('test 10', function() {
  var o = init([{
    id: 's',
    type: 'string',
    value: '',
    triggers: 'updateS',
    dispatch: 'sUpdated',
    setter: function(v) {
      this.s = v.toLowerCase();
    }
  }]);

  o.m.s.dispatch('AbCdE');
  deepEqual(o.m.s.historic[o.m.s.historic.length-1], 'abcde', 'Setters overriding works well.');
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var nodes = require('../../lib/nodes')
  , should = require('should');

module.exports = {
  'test default': function(){
    nodes.null.clone().should.equal(nodes.null);
  },

  'test Color': function(){
    var node = new nodes.Color(255,50,0,1)
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.r.should.equal(255);
    clone.g.should.equal(50);
    clone.b.should.equal(0);
    clone.a.should.equal(1);
  },

  'test HSLA': function(){
    var node = new nodes.HSLA(100, 50, 12, 1)
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.h.should.equal(100);
    clone.s.should.equal(50);
    clone.l.should.equal(12);
    clone.a.should.equal(1);
  },

  'test String': function(){
    var node = new nodes.String('wahoo')
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.val.should.equal('wahoo');
  },

  'test Expression': function(){
    var node = new nodes.Expression(true)
      , a = new nodes.Unit(15)
      , b = new nodes.Unit(20);

    node.push(a);
    node.push(b);

    var clone = node.clone();
    clone.should.not.equal(node);
    clone.nodes[0].should.not.equal(a);
    clone.nodes[1].should.not.equal(b);
    clone.nodes[0].val.should.equal(15);
    clone.nodes[1].val.should.equal(20);
  },

  'test Params': function(){
    var node = new nodes.Params
      , a = new nodes.Unit(15)
      , b = new nodes.Unit(20);

    node.push(a);
    node.push(b);

    var clone = node.clone();
    clone.should.not.equal(node);
    clone.nodes[0].should.not.equal(a);
    clone.nodes[1].should.not.equal(b);
    clone.nodes[0].val.should.equal(15);
    clone.nodes[1].val.should.equal(20);
  }
};<commit_msg>Added Ident#clone() tests<commit_after>
/**
 * Module dependencies.
 */

var nodes = require('../../lib/nodes')
  , should = require('should');

module.exports = {
  'test default': function(){
    nodes.null.clone().should.equal(nodes.null);
  },

  'test Color': function(){
    var node = new nodes.Color(255,50,0,1)
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.r.should.equal(255);
    clone.g.should.equal(50);
    clone.b.should.equal(0);
    clone.a.should.equal(1);
  },

  'test HSLA': function(){
    var node = new nodes.HSLA(100, 50, 12, 1)
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.h.should.equal(100);
    clone.s.should.equal(50);
    clone.l.should.equal(12);
    clone.a.should.equal(1);
  },

  'test String': function(){
    var node = new nodes.String('wahoo')
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.val.should.equal('wahoo');
  },

  'test Expression': function(){
    var node = new nodes.Expression(true)
      , a = new nodes.Unit(15)
      , b = new nodes.Unit(20);

    node.push(a);
    node.push(b);

    var clone = node.clone();
    clone.should.not.equal(node);
    clone.nodes[0].should.not.equal(a);
    clone.nodes[1].should.not.equal(b);
    clone.nodes[0].val.should.equal(15);
    clone.nodes[1].val.should.equal(20);
  },

  'test Ident': function(){
    var n = new nodes.Unit(50)
      , node = new nodes.Ident('n', n)
      , clone = node.clone();

    clone.should.not.equal(node);
    clone.val.should.not.equal(n);
    clone.val.val.should.equal(50);
  },

  'test Params': function(){
    var node = new nodes.Params
      , a = new nodes.Unit(15)
      , b = new nodes.Unit(20);

    node.push(a);
    node.push(b);

    var clone = node.clone();
    clone.should.not.equal(node);
    clone.nodes[0].should.not.equal(a);
    clone.nodes[1].should.not.equal(b);
    clone.nodes[0].val.should.equal(15);
    clone.nodes[1].val.should.equal(20);
  }
};<|endoftext|>


<commit_before>$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var items = $(".card");
    //show only those matching user input:
      items.filter(function() {
          var is_show = $(this).text().toLowerCase().indexOf(value) > -1
          if (!is_show) {
              $(this).parent().css('display', 'none')
          } else {
              $(this).parent().css('display', 'block')
          }
    });
  });
});
console.log('Point of Sale JavaScript loaded');<commit_msg>CO-3519 - fix<commit_after>$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var items = $(".card");
    //show only those matching user input:
      items.filter(function() {
          var is_show = $(this).text().toLowerCase().indexOf(value) > -1
          if (!is_show) {
              $(this).parent().css('display', 'none')
          } else {
              $(this).parent().css('display', 'block')
          }
    });
  });
});<|endoftext|>


<commit_before>/*jslint white: true*/
/*global module */
module.exports = function (config) {
    'use strict';
    config.set({
        basePath: '../../',
        frameworks: ['jasmine', 'requirejs', 'es6-shim'],
        client: {
            jasmine: {
                failFast: false,
                DEFAULT_TIMEOUT_INTERVAL: 20000
            }
        },
        plugins: [
            'karma-jasmine',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-phantomjs-launcher',
            'karma-requirejs',
            'karma-coverage',
            'karma-mocha-reporter',
            'karma-es6-shim'
        ],
        preprocessors: {
            'kbase-extension/static/kbase/js/*/!(api)/**/*.js': ['coverage'],
            'kbase-extension/static/kbase/js/api/!(*[Cc]lient*|Catalog|KBaseFeatureValues|NarrativeJobServiceWrapper|NewWorkspace)*.js': ['coverage'],
            'kbase-extension/static/kbase/js/api/RestAPIClient.js': ['coverage']
        },
        files: [
            'kbase-extension/static/narrative_paths.js',
            {pattern: 'test/unit/spec/**/*.js', included: false},
            // {pattern: 'test/unit/spec/appWidgets/input/newObjectInputSpec.js', included: false},
            // {pattern: 'test/unit/spec/common/validate-Spec.js', included: false},
            {pattern: 'node_modules/string.prototype.startswith/startswith.js', included: true},
            {pattern: 'node_modules/string.prototype.endswith/endswith.js', included: true},
            {pattern: 'node_modules/jasmine-ajax/lib/mock-ajax.js', included: true},
            {pattern: 'kbase-extension/static/ext_components/kbase-ui-plugin-catalog/src/plugin/modules/data/categories.yml', included: false, served: true},
            {pattern: 'kbase-extension/static/**/*.css', included: false, served: true},
            {pattern: 'kbase-extension/static/kbase/templates/**/*.html', included: false, served: true},
            {pattern: 'kbase-extension/static/kbase/config/**/*.json', included: false, served: true},
            {pattern: 'kbase-extension/static/kbase/config/**/*.yaml', included: false, served: true},
            {pattern: 'kbase-extension/static/**/*.js', included: false, served: true},
            {pattern: 'kbase-extension/static/**/*.gif', included: false, served: true},
            {pattern: 'test/unit/testConfig.json', included: false, served: true, nocache: true},
            {pattern: 'test/*.tok', included: false, served: true, nocache: true},
            {pattern: 'test/data/**/*', included: false, served: true},
            'test/unit/testUtil.js',
            'test/unit/test-main.js'
        ],
        exclude: [
            'kbase-extension/static/buildTools/*.js',
            'kbase-extension/static/ext_components/**/test/**/*.js',
            'kbase-extension/static/kbase/js/patched-components/**/*'
        ],
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['mocha', 'coverage'],
        coverageReporter: {
            type: 'html',
            dir: 'js-coverage/',
            reporters: [{
                type: 'html',
                subdir: 'html'
            }, {
                type: 'lcov',
                subdir: 'lcov'
            }],
            includeAllSources: true
        },
        // web server port
        port: 9876,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,
        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['ChromeHeadless'], //['PhantomJS', 'Firefox', 'ChromeHeadless'],
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        // phantomjsLauncher: {
        //     options: {
        //         settings: {
        //             webSecurityEnabled: false
        //         }
        //     }
        // },
        browserNoActivityTimeout: 30000,
        singleRun: true,
        proxies: {
            '/narrative/static/': '/base/kbase-extension/static/',
            '/narrative/static/base': 'http://localhost:32323/narrative/static/base',
            '/narrative/static/notebook': 'http://localhost:32323/narrative/static/notebook',
            '/narrative/static/components': 'http://localhost:32323/narrative/static/components',
            '/narrative/static/services': 'http://localhost:32323/narrative/static/services',
            '/narrative/static/bidi': 'http://localhost:32323/narrative/static/bidi',
            '/static/kbase/config': '/base/kbase-extension/static/kbase/config',
            '/test/': '/base/test/'
        },
        client: {
          requireJsShowNoTimestampsError: '^(?!.*(^/narrative/static/))',
          clearContext: false
        },
        concurrency: Infinity

    });
};
<commit_msg>add new karma changes to manage api coverage better<commit_after>/*jslint white: true*/
/*global module */
module.exports = function (config) {
    'use strict';
    config.set({
        basePath: '../../',
        frameworks: ['jasmine', 'requirejs', 'es6-shim'],
        client: {
            jasmine: {
                failFast: false,
                DEFAULT_TIMEOUT_INTERVAL: 20000
            }
        },
        plugins: [
            'karma-jasmine',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-phantomjs-launcher',
            'karma-requirejs',
            'karma-coverage',
            'karma-mocha-reporter',
            'karma-es6-shim'
        ],
        preprocessors: {
            'kbase-extension/static/kbase/js/**/!(api)/*.js': ['coverage'],
            'kbase-extension/static/kbase/js/api/!(*[Cc]lient*|Catalog|KBaseFeatureValues|NarrativeJobServiceWrapper|NewWorkspace)*.js': ['coverage'],
            'kbase-extension/static/kbase/js/api/RestAPIClient.js': ['coverage']
        },
        files: [
            'kbase-extension/static/narrative_paths.js',
            {pattern: 'test/unit/spec/**/*.js', included: false},
            // {pattern: 'test/unit/spec/appWidgets/input/taxonomyRefInputSpec.js', included: false},
            // {pattern: 'test/unit/spec/common/validate-Spec.js', included: false},
            {pattern: 'node_modules/string.prototype.startswith/startswith.js', included: true},
            {pattern: 'node_modules/string.prototype.endswith/endswith.js', included: true},
            {pattern: 'node_modules/jasmine-ajax/lib/mock-ajax.js', included: true},
            {pattern: 'kbase-extension/static/ext_components/kbase-ui-plugin-catalog/src/plugin/modules/data/categories.yml', included: false, served: true},
            {pattern: 'kbase-extension/static/**/*.css', included: false, served: true},
            {pattern: 'kbase-extension/static/kbase/templates/**/*.html', included: false, served: true},
            {pattern: 'kbase-extension/static/kbase/config/**/*.json', included: false, served: true},
            {pattern: 'kbase-extension/static/kbase/config/**/*.yaml', included: false, served: true},
            {pattern: 'kbase-extension/static/**/*.js', included: false, served: true},
            {pattern: 'kbase-extension/static/**/*.gif', included: false, served: true},
            {pattern: 'test/unit/testConfig.json', included: false, served: true, nocache: true},
            {pattern: 'test/*.tok', included: false, served: true, nocache: true},
            {pattern: 'test/data/**/*', included: false, served: true},
            'test/unit/testUtil.js',
            'test/unit/test-main.js'
        ],
        exclude: [
            'kbase-extension/static/buildTools/*.js',
            'kbase-extension/static/ext_components/**/test/**/*.js',
            'kbase-extension/static/kbase/js/patched-components/**/*'
        ],
        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['mocha', 'coverage'],
        coverageReporter: {
            type: 'html',
            dir: 'js-coverage/',
            reporters: [{
                type: 'html',
                subdir: 'html'
            }, {
                type: 'lcov',
                subdir: 'lcov'
            }],
            includeAllSources: true
        },
        // web server port
        port: 9876,
        // enable / disable colors in the output (reporters and logs)
        colors: true,
        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,
        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['ChromeHeadless'], //['PhantomJS', 'Firefox', 'ChromeHeadless'],
        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        // phantomjsLauncher: {
        //     options: {
        //         settings: {
        //             webSecurityEnabled: false
        //         }
        //     }
        // },
        browserNoActivityTimeout: 30000,
        singleRun: true,
        proxies: {
            '/narrative/static/': '/base/kbase-extension/static/',
            '/narrative/static/base': 'http://localhost:32323/narrative/static/base',
            '/narrative/static/notebook': 'http://localhost:32323/narrative/static/notebook',
            '/narrative/static/components': 'http://localhost:32323/narrative/static/components',
            '/narrative/static/services': 'http://localhost:32323/narrative/static/services',
            '/narrative/static/bidi': 'http://localhost:32323/narrative/static/bidi',
            '/static/kbase/config': '/base/kbase-extension/static/kbase/config',
            '/test/': '/base/test/'
        },
        client: {
          requireJsShowNoTimestampsError: '^(?!.*(^/narrative/static/))',
          clearContext: false
        },
        concurrency: Infinity

    });
};
<|endoftext|>