<commit_before>Helpers = initHelpers(window, document);

function initHelpers(w, d, undefined) {
  "use strict";
  var useCustomCss = false;
  var extended = extensions();

  var helperObj = {
    report: reportHTML,
    useJQ: loadJQ,
    useCSS: setCustomCss,
    log2Screen: log2Screen,
    initSO: SOInit,
    printDirect: printDirect,
    logClear: screenClear,
    partial: Partial
  };

  function setCustomCss(yn) {
    useCustomCss = yn;
    if (useCustomCss) {
     loadCSS();
    } else {
     unloadCSS();
    }
  }

  function loadJQ(callback) {
      if (w.jQuery) {
        return callback && callback instanceof Function ? callback() : true;
      }

      var jqel  = createElementWithProps('script', {src: 'http://code.jquery.com/jquery-2.1.1.min.js', id: 'jqloaded'});

      d.querySelector('head').appendChild(jqel);

      if (callback && callback instanceof Function)
          jqel.addEventListener('load', callback);

      return void(0);
  }

  function loadCSS() {
    if (d.querySelector('#HelperCSS')) {
      return true;
    }
    var css = createElementWithProps(
                    'link',
                    { href: 'https://rawgit.com/KooiInc/Helpers/master/Helpers.css',
                      type: 'text/css',
                      rel: 'stylesheet',
                      id: 'HelperCSS' }
              );
    return d.querySelector('head').appendChild (css);
  }

  function unloadCSS() {
   var css = document.querySelector('#HelperCSS');
   void (css && document.querySelector('head').removeChild(css));
  }

   // a few usefull augments/polyfills
  function extensions() {
        if (extended) {
          return true;
        }
        // remove double values from an array
        function noDoubles(arr) {
          arr = arr || this;
          return arr.filter(function(val) {
           return !this[val] ? ((this[val] = true), true) : false;
          }, {});
        }

        function stringformat() {
                var args = args2Array(arguments);
                return this.replace(/(\{\d+\})/g, function(a){
                    return args[+(a.substr(1,a.length-2))||0];
                });
        };

        // determine value frequencies in an array
        function frequencies(arr) {
          var mapped = {sum: 0};
          (arr || this).map(function (a){
              if (!(a in this)) { this[a] = 1; }
              else { this[a] += 1; }
              this.sum += 1;
              return a; }, mapped
          );
          return mapped;
        }

        String.Format = function(){
            var args = args2Array(arguments);
            return stringformat.apply(args[0],args.slice(1));
        };

        String.prototype.format = function () {
          return stringformat.apply(this,arguments);
        }

        String.prototype.repeat = function(n){
            var s = this, r = '';
            while(n--) {
                r += s;
            }
            return r;
        };

        // run functions sequentially
        Function.prototype.andThen = function () {
         var args = args2Array(arguments)
            ,next = args.slice(1);
         this();
         return args[0] && next.length
                 ? args[0].andThen.apply(args[0], next)
                 : args.length == 1  ? args[0]()
                 : true;
        };

        Function.prototype.partial = Function.prototype.partial || function () {
             var stored_args = [].slice.call(arguments)
                ,fn = this;
            return function () {
                return fn.apply(null, stored_args.concat([].slice.call(arguments)));
             };
        };

        Function.prototype.partialx = function(){
            var fn = this, args = Array.prototype.slice.call(arguments);
            return function(){
              var arg = 0;
              for ( var i = 0; i < args.length && arg < arguments.length; i++ )
                if ( args[i] === undefined || args[i] === null)
                  args[i] = arguments[arg++];
              return fn.apply(this, args);
            };
        };

        // is character @ [atpos] upperCase?
        boolean:String.prototype.charIsUpper = function (atpos){
          var chr = this.charAt(atpos);
          return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
        };

        String.prototype.firstUp = function () {
          return this.slice(0,1).toUpperCase()+this.slice(1).toLowerCase();
        }

        String.prototype.isValidEmail = function() {
          // should be sufficient
          return  /^[\w._-]{1,}[+]?[\w._-]{0,}@[\w.-]+\.[a-zA-Z]{2,6}$/.test(this);
        }

        Array.prototype.toRE = function (){
          try { return RegExp.apply(null, this); }
          catch(e) { return /.*/; }
        }

        Array.toRE = function(arr) {
          return ([].toRE.call(arr));
        }

        String.prototype.reCleanup = function(encodeHTML){
          var str = encodeHTML ? this.replace(/[\u0080-\u024F]/g, function(a) {return '&#'+a.charCodeAt(0)+';';}) : this;
          return str.replace(/[?*|.+$\/]|\\/g, function(c) {return c==='\\' ? '' : '\\\\'+c;});
        }

        String.concat = function(joinchar){
          joinchar = joinchar || '';
          return args2Array(arguments).join(joinchar);
        }

        // MDN Array filter polyfill
        if (!Array.prototype.filter) {
          Array.prototype.filter = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun != "function")
              throw new TypeError();

            var res = [];
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)  {
                var val = t[i];
                if (fun.call(thisArg, val, i, t))
                  res.push(val);
              }
            }

            return res;
          };
        }

        // MDN Array map polyfill
        if (!Array.prototype.map) {
          Array.prototype.map = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun !== "function")
              throw new TypeError();

            var res = new Array(len);
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)
                res[i] = fun.call(thisArg, t[i], i, t);
            }

            return res;
        };
       }

       Array.prototype.uniquify = noDoubles;

       Array.prototype.frequencies = Array.prototype.frequencies || frequencies;

       Array.prototype.each = Array.prototype.each || function (fn,rewrite) {
          for (var i = 0; i < this.length; i++) {
           if (rewrite){
             this[i] = fn(this[i]);
           } else {
            fn(this[i]);
           }
          }
          return this;
       };

       // statics
       Object.print = function (obj, space) {
            space = space || '  ';
            return '
'+JSON.stringify(obj, null, space)+'
';
       }

       Object.format = function (obj, space) {
            space = space || '  ';
            return '
'+JSON.stringify(obj, null, space)+'
';
       }

       Object.isOneOf = isOfType;

       extended = true;
       return extended;
  }

  // SO specials
  function SOInit() {
    extensions();
    setCustomCss(true);
    loadJQ( jqcallback );

    function jqcallback() {
       $(document).on('mouseover', '.solink',  setSOLink);
       $(document).on('click', '[data-link]', clicklink);
    };
  }

  function setSOLink(e) {
      if ($(this).attr('data-link')) { return true; }

      $.ajax(
          {
              url: 'http://www.nicon.nl/node/stackx/questionx',
              data: {qid: $('.solink').first().attr('data-linkid')},
              method: 'post',
              success: SOcb
          }
      );

      function SOcb(data) {
          var resp = data.items && data.items[0] || data
          ,linkelement = $('.solink').first()
          ,linktip = linkelement.find('.linkhover').first()
          ;
          linktip.html(
              'Click logo to view the related question:

' + resp.title + '

' +
              'Asked by
'+ resp.owner.display_name + '
; '+
              'rep ' + resp.owner.reputation +'; question views: '+resp.view_count
          );
          linkelement.attr('data-link', resp.link);
      }

      return true;
  }

  // firefox needs a link added to the DOM, Chrome, IE don't
  function clicklink(e) {
      e.stopPropagation(); //just this link
      var linkurl = this.getAttribute('data-link')
         ,xlink = document.querySelector('a[href="'+linkurl+'"]') ||
                  function() {
                      var _link = createElementWithProps(
                                    'a', { href: linkurl, target:'_blank', style: { display: 'none' } }
                                  );
                      document.body.appendChild(_link);
                      return _link; }();
      xlink.click();
  }

  // Reporting
  // 1. simple
  function reportHTML() {
    var report = document.querySelector('#result') ||
        function() {
          var r = createElementWithProps( 'div', {id: 'result'} );
          document.querySelector('body').appendChild(r);
          return r;
        }();
    var entry = createElementWithProps('p');
    entry.innerHTML = args2Array(arguments).join('');
    report.appendChild(entry);

    if (useCustomCss) {
      var to = function () { entry.className = 'fadeIn'; };
      var dummy = setTimeout(to, 100);
    }
  }

  // 2. with parameter object usage
  function log2Screen() {
      var result = document.querySelector('#result') ||
                   function () {
                       var r = createElementWithProps('div', {id: 'result'});
                       document.body.appendChild(r);
                       return r; }()
         ,args = args2Array(arguments)
         ,lastarg = args.slice(-1)[0]
         ,optkeys = /clear|clrscr|direct|opts|useopts|continuous/i
         ,opts = Object.isOneOf(lastarg, Object) && Object.keys(lastarg).filter(function(v){return optkeys.test(v);}).length
                 ? lastarg.opts instanceof Object ? lastarg.opts : lastarg
                 : {empty: 1};
      void(!opts.empty && (args = args.slice(0,-1)));

      if (opts.clrscr) {
          return result.innerHTML = '';
      }

      if (opts.clear) {
          result.innerHTML = '';
      }

      if (opts.continuous) {
          return result.innerHTML += args.join('').replace(/\n/g,'
');
      }

      var p = createElementWithProps('p');
      p.innerHTML = args.join('').replace(/\n/g,'
');
      result.appendChild(p);
      return opts.direct ? (p.className = 'fadeIn')
                         : setTimeout(function () { p.className = 'fadeIn'; }, +opts.timed*1000 || 0);
  }

  function printDirect() {
    return log2Screen.apply( null, args2Array(arguments).concat({direct:true}) );
  }

  function screenClear() {
      var res = d.querySelector('#result');
      return  res && (res.innerHTML = '') || true;
  }

  // utilities
  function createElementWithProps(elType, props) {
    var el = d.createElement(elType);
    if (props && isOfType(props, Object)) {
      for (var l in props) {
        if (!props.hasOwnProperty(l)) continue;
        if (/style/i.test(l)) {
          for (var ll in props[l]) {
            if (!props[l].hasOwnProperty(ll)) continue;
            el.style[ll] = props[l][ll];
          }
        } else {
          el[l] = props[l];
        }
      }
    }
    return el;
  }

  function args2Array(args){
    var arr = [];
    while (arr.length < args.length) { arr.push(args[arr.length]); }
    return arr;
  }

  // see: http://codereview.stackexchange.com/questions/23317/istypeobj-gettypeobj-v0/23329#23329
  function isOfType(obj) {
    if (!obj) { return false; }
    var test = arguments.length ? args2Array(arguments).slice(1) : null
       ,self = obj.constructor;
    return test ? !!(test.filter(function(a){return a === self}).length)
           : (self.constructor.name ||
              (String(self).match ( /^function\s*([^\s(]+)/im)
                || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
  };

  function Partial (fn) {
    this.initial = [].slice.call(arguments,1);
    this.fnp = function () {
                 return fn.partialx.apply(fn, this.initial);
                };
    if (!Partial.prototype.x) {
      Partial.prototype.x = function () {
        return this.fnp().apply(null, [].slice.call(arguments));
      };
    }
  };

  return helperObj
}
<commit_msg>Partial: cleaner param names<commit_after>Helpers = initHelpers(window, document);

function initHelpers(w, d, undefined) {
  "use strict";
  var useCustomCss = false;
  var extended = extensions();

  var helperObj = {
    report: reportHTML,
    useJQ: loadJQ,
    useCSS: setCustomCss,
    log2Screen: log2Screen,
    initSO: SOInit,
    printDirect: printDirect,
    logClear: screenClear,
    Partial: Partial
  };

  function setCustomCss(yn) {
    useCustomCss = yn;
    if (useCustomCss) {
     loadCSS();
    } else {
     unloadCSS();
    }
  }

  function loadJQ(callback) {
      if (w.jQuery) {
        return callback && callback instanceof Function ? callback() : true;
      }

      var jqel  = createElementWithProps('script', {src: 'http://code.jquery.com/jquery-2.1.1.min.js', id: 'jqloaded'});

      d.querySelector('head').appendChild(jqel);

      if (callback && callback instanceof Function)
          jqel.addEventListener('load', callback);

      return void(0);
  }

  function loadCSS() {
    if (d.querySelector('#HelperCSS')) {
      return true;
    }
    var css = createElementWithProps(
                    'link',
                    { href: 'https://rawgit.com/KooiInc/Helpers/master/Helpers.css',
                      type: 'text/css',
                      rel: 'stylesheet',
                      id: 'HelperCSS' }
              );
    return d.querySelector('head').appendChild (css);
  }

  function unloadCSS() {
   var css = document.querySelector('#HelperCSS');
   void (css && document.querySelector('head').removeChild(css));
  }

   // a few usefull augments/polyfills
  function extensions() {
        if (extended) {
          return true;
        }
        // remove double values from an array
        function noDoubles(arr) {
          arr = arr || this;
          return arr.filter(function(val) {
           return !this[val] ? ((this[val] = true), true) : false;
          }, {});
        }

        function stringformat() {
                var args = args2Array(arguments);
                return this.replace(/(\{\d+\})/g, function(a){
                    return args[+(a.substr(1,a.length-2))||0];
                });
        };

        // determine value frequencies in an array
        function frequencies(arr) {
          var mapped = {sum: 0};
          (arr || this).map(function (a){
              if (!(a in this)) { this[a] = 1; }
              else { this[a] += 1; }
              this.sum += 1;
              return a; }, mapped
          );
          return mapped;
        }

        String.Format = function(){
            var args = args2Array(arguments);
            return stringformat.apply(args[0],args.slice(1));
        };

        String.prototype.format = function () {
          return stringformat.apply(this,arguments);
        }

        String.prototype.repeat = function(n){
            var s = this, r = '';
            while(n--) {
                r += s;
            }
            return r;
        };

        // run functions sequentially
        Function.prototype.andThen = function () {
         var args = args2Array(arguments)
            ,next = args.slice(1);
         this();
         return args[0] && next.length
                 ? args[0].andThen.apply(args[0], next)
                 : args.length == 1  ? args[0]()
                 : true;
        };

        Function.prototype.partial = Function.prototype.partial || function () {
             var stored_args = [].slice.call(arguments)
                ,fn = this;
            return function () {
                return fn.apply(null, stored_args.concat([].slice.call(arguments)));
             };
        };

        Function.prototype.partialx = function(){
            var fn = this, args = Array.prototype.slice.call(arguments);
            return function(){
              var arg = 0;
              for ( var i = 0; i < args.length && arg < arguments.length; i++ )
                if ( args[i] === undefined || args[i] === null)
                  args[i] = arguments[arg++];
              return fn.apply(this, args);
            };
        };

        // is character @ [atpos] upperCase?
        boolean:String.prototype.charIsUpper = function (atpos){
          var chr = this.charAt(atpos);
          return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
        };

        String.prototype.firstUp = function () {
          return this.slice(0,1).toUpperCase()+this.slice(1).toLowerCase();
        }

        String.prototype.isValidEmail = function() {
          // should be sufficient
          return  /^[\w._-]{1,}[+]?[\w._-]{0,}@[\w.-]+\.[a-zA-Z]{2,6}$/.test(this);
        }

        Array.prototype.toRE = function (){
          try { return RegExp.apply(null, this); }
          catch(e) { return /.*/; }
        }

        Array.toRE = function(arr) {
          return ([].toRE.call(arr));
        }

        String.prototype.reCleanup = function(encodeHTML){
          var str = encodeHTML ? this.replace(/[\u0080-\u024F]/g, function(a) {return '&#'+a.charCodeAt(0)+';';}) : this;
          return str.replace(/[?*|.+$\/]|\\/g, function(c) {return c==='\\' ? '' : '\\\\'+c;});
        }

        String.concat = function(joinchar){
          joinchar = joinchar || '';
          return args2Array(arguments).join(joinchar);
        }

        // MDN Array filter polyfill
        if (!Array.prototype.filter) {
          Array.prototype.filter = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun != "function")
              throw new TypeError();

            var res = [];
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)  {
                var val = t[i];
                if (fun.call(thisArg, val, i, t))
                  res.push(val);
              }
            }

            return res;
          };
        }

        // MDN Array map polyfill
        if (!Array.prototype.map) {
          Array.prototype.map = function(fun)
          {
            if (this === void 0 || this === null)
              throw new TypeError();

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fun !== "function")
              throw new TypeError();

            var res = new Array(len);
            var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
            for (var i = 0; i < len; i++) {
              if (i in t)
                res[i] = fun.call(thisArg, t[i], i, t);
            }

            return res;
        };
       }

       Array.prototype.uniquify = noDoubles;

       Array.prototype.frequencies = Array.prototype.frequencies || frequencies;

       Array.prototype.each = Array.prototype.each || function (fn,rewrite) {
          for (var i = 0; i < this.length; i++) {
           if (rewrite){
             this[i] = fn(this[i]);
           } else {
            fn(this[i]);
           }
          }
          return this;
       };

       // statics
       Object.print = function (obj, space) {
            space = space || '  ';
            return '
'+JSON.stringify(obj, null, space)+'
';
       }

       Object.format = function (obj, space) {
            space = space || '  ';
            return '
'+JSON.stringify(obj, null, space)+'
';
       }

       Object.isOneOf = isOfType;

       extended = true;
       return extended;
  }

  // SO specials
  function SOInit() {
    extensions();
    setCustomCss(true);
    loadJQ( jqcallback );

    function jqcallback() {
       $(document).on('mouseover', '.solink',  setSOLink);
       $(document).on('click', '[data-link]', clicklink);
    };
  }

  function setSOLink(e) {
      if ($(this).attr('data-link')) { return true; }

      $.ajax(
          {
              url: 'http://www.nicon.nl/node/stackx/questionx',
              data: {qid: $('.solink').first().attr('data-linkid')},
              method: 'post',
              success: SOcb
          }
      );

      function SOcb(data) {
          var resp = data.items && data.items[0] || data
          ,linkelement = $('.solink').first()
          ,linktip = linkelement.find('.linkhover').first()
          ;
          linktip.html(
              'Click logo to view the related question:

' + resp.title + '

' +
              'Asked by
'+ resp.owner.display_name + '
; '+
              'rep ' + resp.owner.reputation +'; question views: '+resp.view_count
          );
          linkelement.attr('data-link', resp.link);
      }

      return true;
  }

  // firefox needs a link added to the DOM, Chrome, IE don't
  function clicklink(e) {
      e.stopPropagation(); //just this link
      var linkurl = this.getAttribute('data-link')
         ,xlink = document.querySelector('a[href="'+linkurl+'"]') ||
                  function() {
                      var _link = createElementWithProps(
                                    'a', { href: linkurl, target:'_blank', style: { display: 'none' } }
                                  );
                      document.body.appendChild(_link);
                      return _link; }();
      xlink.click();
  }

  // Reporting
  // 1. simple
  function reportHTML() {
    var report = document.querySelector('#result') ||
        function() {
          var r = createElementWithProps( 'div', {id: 'result'} );
          document.querySelector('body').appendChild(r);
          return r;
        }();
    var entry = createElementWithProps('p');
    entry.innerHTML = args2Array(arguments).join('');
    report.appendChild(entry);

    if (useCustomCss) {
      var to = function () { entry.className = 'fadeIn'; };
      var dummy = setTimeout(to, 100);
    }
  }

  // 2. with parameter object usage
  function log2Screen() {
      var result = document.querySelector('#result') ||
                   function () {
                       var r = createElementWithProps('div', {id: 'result'});
                       document.body.appendChild(r);
                       return r; }()
         ,args = args2Array(arguments)
         ,lastarg = args.slice(-1)[0]
         ,optkeys = /clear|clrscr|direct|opts|useopts|continuous/i
         ,opts = Object.isOneOf(lastarg, Object) && Object.keys(lastarg).filter(function(v){return optkeys.test(v);}).length
                 ? lastarg.opts instanceof Object ? lastarg.opts : lastarg
                 : {empty: 1};
      void(!opts.empty && (args = args.slice(0,-1)));

      if (opts.clrscr) {
          return result.innerHTML = '';
      }

      if (opts.clear) {
          result.innerHTML = '';
      }

      if (opts.continuous) {
          return result.innerHTML += args.join('').replace(/\n/g,'
');
      }

      var p = createElementWithProps('p');
      p.innerHTML = args.join('').replace(/\n/g,'
');
      result.appendChild(p);
      return opts.direct ? (p.className = 'fadeIn')
                         : setTimeout(function () { p.className = 'fadeIn'; }, +opts.timed*1000 || 0);
  }

  function printDirect() {
    return log2Screen.apply( null, args2Array(arguments).concat({direct:true}) );
  }

  function screenClear() {
      var res = d.querySelector('#result');
      return  res && (res.innerHTML = '') || true;
  }

  // utilities
  function createElementWithProps(elType, props) {
    var el = d.createElement(elType);
    if (props && isOfType(props, Object)) {
      for (var l in props) {
        if (!props.hasOwnProperty(l)) continue;
        if (/style/i.test(l)) {
          for (var ll in props[l]) {
            if (!props[l].hasOwnProperty(ll)) continue;
            el.style[ll] = props[l][ll];
          }
        } else {
          el[l] = props[l];
        }
      }
    }
    return el;
  }

  function args2Array(args, sliceAt){
    var arr = [];
    while (arr.length < args.length) { arr.push(args[arr.length]); }
    return sliceAt ? arr.slice(sliceAt) : arr;
  }

  // see: http://codereview.stackexchange.com/questions/23317/istypeobj-gettypeobj-v0/23329#23329
  function isOfType(obj) {
    if (!obj) { return false; }
    var test = arguments.length ? args2Array(arguments).slice(1) : null
       ,self = obj.constructor;
    return test ? !!(test.filter(function(a){return a === self}).length)
           : (self.constructor.name ||
              (String(self).match ( /^function\s*([^\s(]+)/im)
                || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
  };

  function Partial (func) {
    this.initial = funcp(arguments, 1);
    this.funcp = function () {
                 return func.partialx.apply(func, this.initial);
                };
    if (!Partial.prototype.x) {
      Partial.prototype.x = function () {
        return this.funcp().apply(null, args2Array(arguments));
      };
    }
  };

  return helperObj
}
<|endoftext|>


<commit_before>/*k-means clustering*/
var Kmeans=(function namespace(){
    function init(k,data,attributes,initMethod){
        config=Object.assign({
            k:k,
            data:data,
            attributes:attributes,
            groups:[],
            initMethod:initMethod||0,
            oldCentroid:[],
        },config);
        config.groups.length=k;
        for(var i=0;i<k;i++){
            config.groups[i]=[];
        }
    }
    /*PublicMethod*/
    init.prototype.initialize=function(centroid){
        if(config.initMethod==init.initOption.Assign){
            config.centroid=centroid;
        }else if(config.initMethod==init.initOption.Forgy){
            config.centroid=[];
            var arr=config.data.slice();
            while(config.centroid.length!=config.k){
                var i=Math.floor(Math.random()*arr.length);
                if(!config.centroid.includes(i)){
                    config.centroid.push(i);
                    arr.splice(arr.indexOf(i),1);
                }
            }
        }else if(config.initMethod==init.initOption.RandomPartition){
            config.centroid=[];
            for(var i=0;i<config.data.length;i++){
                config.groups[Math.floor(Math.random()*config.k)].push(i);
            }
            init.prototype.update();
        }
    };
    init.prototype.assignment=function(){
        //reset groups
        for(var i=0;i<config.k;i++){
            config.groups[i].length=0;
        }
        //assignment
        for(var i=0;i<config.data.length;i++){
            var min=Infinity;
            var minj=-1;
            for(var j=0;j<config.k;j++){
                var d=getDistance(config.data[i],config.data[config.centroid[j]]);
                if(d<min){
                    min=d;
                    minj=j;
                }
            }
            config.groups[minj].push(i);
        }
    };
    init.prototype.update=function(){
        //reset centroid
        config.oldCentroid=config.centroid.slice();
        config.centroid.length=0;
        config.centroid.length=config.k;
        //each group
        for(var i=0;i<config.k;i++){
            var mean={};
            //each attribute
            for(var j=0;j<config.attributes.length;j++){
                var sum=0;
                for(var m=0;m<config.groups[i].length;m++){
                    sum+=config.data[config.groups[i][m]][config.attributes[j]];
                }
                sum/=config.attributes.length;
                mean[config.attributes[j]]=sum;
            }
            //get centroid
            var min=Infinity;
            var minj=-1;
            for(var j=0;j<config.data.length;j++){
                var d=getDistance(mean,config.data[j]);
                if(d<min&&!config.centroid.includes(j)){
                    min=d;
                    minj=j;
                }
            }
            config.centroid[i]=minj;
        }
    };
    init.prototype.finish=function(){
        for(var i=0;i<config.k;i++){
            if(!config.oldCentroid.includes(config.centroid[i])){
                return false;
            }
        }
        return true;
    };
    init.prototype.getGroups=function(){
        return config.groups;
    };
    init.prototype.do=function(centroid){
        init.prototype.initialize(centroid);
        while(!init.prototype.finish()){
            init.prototype.assignment();
            init.prototype.update();
        }
        return init.prototype.getGroups();
    };
    /*PrivateMethod*/
    function getDistance(a,b){
        var sum=0;
        for(var i=0;i<config.attributes.length;i++){
            sum+=Math.pow(a[config.attributes[i]]-b[config.attributes[i]],2);
        }
        return sum;
    }
    /*PublicAttribute*/
    init.initOption={
        Assign:0,
        Forgy:1,
        RandomPartition:2,
    };
    /*PrivateAttribute*/
    var config={
        k:0,
        data:[],
        attributes:[],
        groups:[],
        oldCentroid:[],
        centroid:[],
        initMethod:-1,
    };
    return init;
}());<commit_msg>update k-means initOption<commit_after>/*k-means clustering*/
var Kmeans=(function namespace(){
    function init(k,data,attributes,initMethod){
        config=Object.assign({
            k:k,
            data:data,
            attributes:attributes,
            groups:[],
            initMethod:initMethod||0,
            oldCentroid:[],
        },config);
        config.groups.length=k;
        for(var i=0;i<k;i++){
            config.groups[i]=[];
        }
    }
    /*PublicMethod*/
    init.prototype.initialize=function(centroid){
        if(config.initMethod==init.initOption.Assign){
            config.centroid=centroid;
        }else if(config.initMethod==init.initOption.Forgy){
            config.centroid=[];
            var arr=config.data.slice();
            while(config.centroid.length!=config.k){
                var i=Math.floor(Math.random()*arr.length);
                if(!config.centroid.includes(i)){
                    config.centroid.push(i);
                    arr.splice(arr.indexOf(i),1);
                }
            }
        }else if(config.initMethod==init.initOption.RandomPartition){
            config.centroid=[];
            for(var i=0;i<config.data.length;i++){
                config.groups[Math.floor(Math.random()*config.k)].push(i);
            }
            init.prototype.update();
        }
    };
    init.prototype.assignment=function(){
        //reset groups
        for(var i=0;i<config.k;i++){
            config.groups[i].length=0;
        }
        //assignment
        for(var i=0;i<config.data.length;i++){
            var min=Infinity;
            var minj=-1;
            for(var j=0;j<config.k;j++){
                var d=getDistance(config.data[i],config.data[config.centroid[j]]);
                if(d<min){
                    min=d;
                    minj=j;
                }
            }
            config.groups[minj].push(i);
        }
    };
    init.prototype.update=function(){
        //reset centroid
        config.oldCentroid=config.centroid.slice();
        config.centroid.length=0;
        config.centroid.length=config.k;
        //each group
        for(var i=0;i<config.k;i++){
            var mean={};
            //each attribute
            for(var j=0;j<config.attributes.length;j++){
                var sum=0;
                for(var m=0;m<config.groups[i].length;m++){
                    sum+=config.data[config.groups[i][m]][config.attributes[j]];
                }
                sum/=config.attributes.length;
                mean[config.attributes[j]]=sum;
            }
            //get centroid
            var min=Infinity;
            var minj=-1;
            for(var j=0;j<config.data.length;j++){
                var d=getDistance(mean,config.data[j]);
                if(d<min&&!config.centroid.includes(j)){
                    min=d;
                    minj=j;
                }
            }
            config.centroid[i]=minj;
        }
    };
    init.prototype.finish=function(){
        for(var i=0;i<config.k;i++){
            if(!config.oldCentroid.includes(config.centroid[i])){
                return false;
            }
        }
        return true;
    };
    init.prototype.getGroups=function(){
        return config.groups;
    };
    init.prototype.do=function(centroid){
        init.prototype.initialize(centroid);
        while(!init.prototype.finish()){
            init.prototype.assignment();
            init.prototype.update();
        }
        return init.prototype.getGroups();
    };
    /*PrivateMethod*/
    function getDistance(a,b){
        var sum=0;
        for(var i=0;i<config.attributes.length;i++){
            sum+=Math.pow(a[config.attributes[i]]-b[config.attributes[i]],2);
        }
        return sum;
    }
    /*PublicAttribute*/
    init.initOption={
        Assign:"Assign",
        Forgy:"Forgy",
        RandomPartition:"RandomPartition",
    };
    /*PrivateAttribute*/
    var config={
        k:0,
        data:[],
        attributes:[],
        groups:[],
        oldCentroid:[],
        centroid:[],
        initMethod:-1,
    };
    return init;
}());<|endoftext|>


<commit_before>var promise = require("deferred");
var Etcd = require("node-etcd");
var logger = require("winston");
var path = require("path");

function VccStore () {
	this.connected = false;
}

VccStore.prototype.connect = function (host, port) {
	var conn = "http://"+host+":"+port;
	logger.debug("kvstore is connecting to", conn);
	this.etcd = new Etcd(conn, {timeout: 5000});
	this.connected = true;
}

VccStore.prototype.set = function (key, value, ttl) {
	var deferred = promise();
	if (!this.connected) {
		deferred.reject("not connected");
	}
	// set the key optionally with ttl
	logger.debug("key set:", key, value, ttl);
	var options = {};
	if (ttl) {
		options.ttl = ttl;
	}
	// call the etcd function
	this.etcd.set(key, value, options, function (err, res) {
		if (err) {
			deferred.reject(err);
		} else {
			deferred.resolve();
		}
	});
	// return promise
	return deferred.promise();
}

VccStore.prototype.get = function (key, recursive, recursive_with_vals) {
	var deferred = promise();
	var me = this;
	if (!this.connected) {
		deferred.reject("not connected");
	}
	logger.debug("key get:", key, recursive);
	var options = {};
	if (recursive) {
		options.recursive = true;
	}
	// call the etcd function
	this.etcd.get(key, function (err, res) {
		if (err) {
			deferred.reject(err);
		} else {
			// check the response
			if (res.node) {
				if (recursive) {
					if (res.node.nodes) {
						// convert a list of objects into the required format
						// only show the base name of the full path
						if (recursive_with_vals) {
							// we need an object with {key: value}
							var listresult = res.node.nodes.reduce(function (r, i) {
								if (!i.dir) {
									r[path.basename(i.key)] = i.value;
								}
								return r;
							}, {});
						} else {
							// we just need list of keys
							var listresult = res.node.nodes.reduce(function (r, i) {
								r.push(path.basename(i.key));
								return r;
							}, []);
						}
						deferred.resolve(listresult);
					} else {
						deferred.reject("recursive, expecting nodes but didn't get any");
					}
				} else {
					if (res.node.dir) {
						deferred.reject(res.node.key + " is a directory");
					} else if (res.node.value) {
						deferred.resolve(res.node.value);
					} else {
						deferred.reject("no value in response");
					}
				}
			} else {
				deferred.reject("no node in response");
			}
		}
	});
	// return promise
	return deferred.promise();
}

VccStore.prototype.watch = function (key) {
	var deferred = promise();
	if (!this.connected) {
		deferred.reject("not connected");
	}
	// returns an event emitter on change
	logger.debug("key watch:", key);
	deferred.resolve(this.etcd.watcher(key));
	// return promise
	return deferred.promise();
}

VccStore.prototype.list = function (key, with_vals) {
	// call the get function with recursive option
	// with_vals allows us to get the values when listing in the same call
	return this.get(key, true, with_vals);
}

VccStore.prototype.register = function (key, value, ttl) {
	// this is the only function that does not return a promise
	// because there is no obvious resolution
	if (!this.connected) {
		throw "kvstore is not connected";
	}
	logger.debug("key register:", key, value, ttl, "refresh in", (ttl*1000)-10000, "ms");
	var me = this;
	this.set(key, value, ttl);
	setTimeout(function() {
		me.register(key, value, ttl);
	}, (ttl*1000)-10000);
}

module.exports = VccStore;<commit_msg>register function returns promise, resolve after first set<commit_after>var promise = require("deferred");
var Etcd = require("node-etcd");
var logger = require("winston");
var path = require("path");

function VccStore () {
	this.connected = false;
}

VccStore.prototype.connect = function (host, port) {
	var conn = "http://"+host+":"+port;
	logger.debug("kvstore is connecting to", conn);
	this.etcd = new Etcd(conn, {timeout: 5000});
	this.connected = true;
}

VccStore.prototype.set = function (key, value, ttl) {
	var deferred = promise();
	if (!this.connected) {
		deferred.reject("not connected");
	}
	// set the key optionally with ttl
	logger.debug("key set:", key, value, ttl);
	var options = {};
	if (ttl) {
		options.ttl = ttl;
	}
	// call the etcd function
	this.etcd.set(key, value, options, function (err, res) {
		if (err) {
			deferred.reject(err);
		} else {
			deferred.resolve();
		}
	});
	// return promise
	return deferred.promise();
}

VccStore.prototype.get = function (key, recursive, recursive_with_vals) {
	var deferred = promise();
	var me = this;
	if (!this.connected) {
		deferred.reject("not connected");
	}
	logger.debug("key get:", key, recursive);
	var options = {};
	if (recursive) {
		options.recursive = true;
	}
	// call the etcd function
	this.etcd.get(key, function (err, res) {
		if (err) {
			deferred.reject(err);
		} else {
			// check the response
			if (res.node) {
				if (recursive) {
					if (res.node.nodes) {
						// convert a list of objects into the required format
						// only show the base name of the full path
						if (recursive_with_vals) {
							// we need an object with {key: value}
							var listresult = res.node.nodes.reduce(function (r, i) {
								if (!i.dir) {
									r[path.basename(i.key)] = i.value;
								}
								return r;
							}, {});
						} else {
							// we just need list of keys
							var listresult = res.node.nodes.reduce(function (r, i) {
								r.push(path.basename(i.key));
								return r;
							}, []);
						}
						deferred.resolve(listresult);
					} else {
						deferred.reject("recursive, expecting nodes but didn't get any");
					}
				} else {
					if (res.node.dir) {
						deferred.reject(res.node.key + " is a directory");
					} else if (res.node.value) {
						deferred.resolve(res.node.value);
					} else {
						deferred.reject("no value in response");
					}
				}
			} else {
				deferred.reject("no node in response");
			}
		}
	});
	// return promise
	return deferred.promise();
}

VccStore.prototype.watch = function (key) {
	var deferred = promise();
	if (!this.connected) {
		deferred.reject("not connected");
	}
	// returns an event emitter on change
	logger.debug("key watch:", key);
	deferred.resolve(this.etcd.watcher(key));
	// return promise
	return deferred.promise();
}

VccStore.prototype.list = function (key, with_vals) {
	// call the get function with recursive option
	// with_vals allows us to get the values when listing in the same call
	return this.get(key, true, with_vals);
}

VccStore.prototype.register = function (key, value, ttl) {
	var deferred = promise();
	// this promise resolves after the first set is complete
	if (!this.connected) {
		deferred.reject("kvstore is not connected");
	}
	logger.debug("key register:", key, value, ttl, "refresh in", (ttl*1000)-10000, "ms");
	var me = this;
	this.set(key, value, ttl).then(function () {
		// success, now register a timeout
		setTimeout(function() {
			me.register(key, value, ttl);
		}, (ttl*1000)-10000);
		// resolve the promise
		deferred.resolve();
	}, function (err) {
		deferred.reject(err);
	});
	return deferred.promise();
}

module.exports = VccStore;<|endoftext|>


<commit_before>OC.L10N.register(
    'audioplayer',
    {
        'Welcome to' : 'Vítejte v aplikaci',
        'Audio Player' : 'Přehrávač Hudby',
        'Add new tracks to library' : 'Přidat nové skladby do playlistu',
        'Scan for new audio files' : 'Vyhledat nové skladby',
        'New or updated audio files available' : 'Jsou dostupné nové nebo aktualizované skladby',
        'Help' : 'Nápověda',
        'Sort playlist' : 'Setřídit playlist',
        'Rename playlist' : 'Přejmenovat playlist',
        'Delete playlist' : 'Smazat playlist',
        'Add new tracks to playlist by drag and drop' : 'Přetažením přidáte nové skladby do playlistu.',
        'No playlist selected!' : 'Není vybrán žádný playlist!',
        'Sort modus active' : 'Řazení aktivní',
        'Playlist successfully deleted!' : 'Playlist byl úspěšně odstraněn!',
        'Start scanning…' : 'Začít vyhledávat…',
        'Scanning finished! New Audios found!' : 'Vyhledávání dokončeno! Byly nalezeny nové skladby!',
        'Yes' : 'Ano',
        'No' : 'Ne',
        'Error' : 'Chyba',
        'Are you sure?' : 'Jste si jistí?',
        'Disc' : 'Disk',
        'Track' : 'Skladba',
        'File' : 'Soubor',
        'Title' : 'Titul',
        'Subtitle' : 'Podtitul',
        'Artist' : 'Interpret',
        'Album Artist' : 'Interpret alba',
        'Year' : 'Rok',
        'Album' : 'Album',
        'Albums' : 'Alba',
        'Composer' : 'Skladatel',
        'Metadata' : 'Metadata',
        'Edit metadata' : 'Upravit metadata',
        'ID3 Editor' : 'Editor ID3',
        'No ID3 editor installed' : 'Není nainstalovaný žádný editor ID3',
        'Playlists' : 'Playlisty',
        'No playlist entry' : 'Nenachází se v žádném playlistu',
        'Lyrics' : 'Text',
        'No lyrics found' : 'Žádný text nebyl nalezen',
        'Reading data' : 'Probíhá čtení dat',
        'No data' : 'Žádná data',
        'Remove' : 'Odstranit',
        'Options' : 'Možnosti',
        'MIME type' : 'Typ MIME',
        'MIME type not supported by browser' : 'Typ MIME není podporován prohlížečem',
        'Missing permission to edit metadata of track!' : 'Nedostatečné oprávnění pro úpravu metadat!',
        'Existing Albums' : 'Album již existuje',
        'New Album' : 'Nové album',
        'Genre' : 'Žánr',
        'Add as Album Cover' : 'Přidat jako obálku alba',
        'of' : 'z',
        'Total' : 'Celkem',
        'Select from cloud' : 'Vybrat z cloudu',
        'Edit' : 'Upravit',
        'Delete' : 'Smazat',
        'Settings' : 'Nastavení',
        'Select a single folder with audio files' : 'Vyberte jednu složku s audiosoubory',
        'Invalid path!' : 'Neplatná cesta!',
        'saved' : 'uloženo',
        'Reset library' : 'Obnovit knihovnu',
        'Start resetting library…' : 'Začít s obnovou knihovny...',
        'Resetting finished!' : 'Obnova dokončena!',
        'All library entries will be deleted!' : 'Všechny záznamy v knihovně budou smazány!',
        'Close' : 'Zavřít',
        'Play' : 'Hrát',
        'Save' : 'Uložit',
        'Existing Artists' : 'Existující interpreti',
        'New Artist' : 'Nový interpret',
        'Existing Genres' : 'Existující žánry',
            'New Genre': 'Nový žánr',
            'Selected': 'Vybráno',
            'Selected Album': 'Vybrané album',
            'Selected Artist': 'Vybraný interpret',
            'Selected Album Artist': 'Vybraný interpret alba',
            'Selected Composer': 'Vybraný skladatel',
            'Selected Folder': 'Vybraná složka',
            'Selected Genre': 'Vybraný žánr',
            'Selected Playlist': 'Vybraný playlist',
            'Selected Year': 'Vybraný rok',
            'Length': 'Délka',
            'loading': 'loading'
    },
    '');<commit_msg>Update Czech localization - .js variant (#545)<commit_after>OC.L10N.register(
    'audioplayer',
    {
        'Welcome to' : 'Vítejte v aplikaci',
        'Audio Player' : 'Přehrávač Hudby',
        'Add new tracks to library' : 'Přidat nové skladby do knihovny',
        'Scan for new audio files' : 'Vyhledat nové skladby',
        'New or updated audio files available' : 'Jsou k dispozici nové nebo aktualizované skladby',
        'Help' : 'Nápověda',
        'Sort playlist' : 'Setřídit seznam k přehrávání',
        'Rename playlist' : 'Přejmenovat seznam k přehrávání',
        'Delete playlist' : 'Smazat seznam k přehrávání',
        'Add new tracks to playlist by drag and drop' : 'Nové skladby do seznam k přehrávání přidáte jejich přetažením.',
        'No playlist selected!' : 'Není vybrán žádný seznam k přehrávání!',
        'Sort modus active' : 'Řazení aktivní',
        'Playlist successfully deleted!' : 'Seznam k přehrávání úspěšně odstraněn!',
        'Start scanning…' : 'Začít vyhledávat…',
        'Scanning finished! New Audios found!' : 'Vyhledávání dokončeno! Byly nalezeny nové skladby!',
        'Yes' : 'Ano',
        'No' : 'Ne',
        'Error' : 'Chyba',
        'Are you sure?' : 'Opravdu to chcete?',
        'Disc' : 'Disk',
        'Track' : 'Skladba',
        'File' : 'Soubor',
        'Title' : 'Titul',
        'Subtitle' : 'Podtitul',
        'Artist' : 'Interpret',
        'Album Artist' : 'Interpret alba',
        'Year' : 'Rok',
        'Album' : 'Album',
        'Albums' : 'Alba',
        'Composer' : 'Skladatel',
        'Metadata' : 'Metadata',
        'Edit metadata' : 'Upravit metadata',
        'ID3 Editor' : 'Editor ID3',
        'No ID3 editor installed' : 'Není nainstalovaný žádný editor ID3',
        'Playlists' : 'Seznamy k přehrávání',
        'No playlist entry' : 'Nenachází se v žádném seznamu k přehrávání',
        'Lyrics' : 'Text',
        'No lyrics found' : 'Nebyly nalezeny žádné texty',
        'Reading data' : 'Probíhá čtení dat',
        'No data' : 'Žádná data',
        'Remove' : 'Odstranit',
        'Options' : 'Možnosti',
        'MIME type' : 'Typ MIME',
        'MIME type not supported by browser' : 'Typ MIME není podporován prohlížečem',
        'Missing permission to edit metadata of track!' : 'Nedostatečné oprávnění pro úpravu metadat!',
        'Existing Albums' : 'Album už existuje',
        'New Album' : 'Nové album',
        'Genre' : 'Žánr',
        'Add as Album Cover' : 'Přidat jako obálku alba',
        'of' : 'z',
        'Total' : 'Celkem',
        'Select from cloud' : 'Vybrat z cloudu',
        'Edit' : 'Upravit',
        'Delete' : 'Smazat',
        'Settings' : 'Nastavení',
        'Select a single folder with audio files' : 'Vyberte jednu složku s audiosoubory',
        'Invalid path!' : 'Neplatný popis umístění!',
        'saved' : 'uloženo',
        'Reset library' : 'Vytvořit knihovnu odznovu',
        'Start resetting library…' : 'Začít s opětovným vytvářením knihovny…',
        'Resetting finished!' : 'Znovuvytvoření dokončeno!',
        'All library entries will be deleted!' : 'Všechny záznamy v knihovně budou smazány!',
        'Close' : 'Zavřít',
        'Play' : 'Přehrát',
        'Save' : 'Uložit',
        'Existing Artists' : 'Existující interpreti',
        'New Artist' : 'Nový interpret',
        'Existing Genres' : 'Existující žánry',
            'New Genre': 'Nový žánr',
            'Selected': 'Vybráno',
            'Selected Album': 'Vybrané album',
            'Selected Artist': 'Vybraný interpret',
            'Selected Album Artist': 'Vybraný interpret alba',
            'Selected Composer': 'Vybraný skladatel',
            'Selected Folder': 'Vybraná složka',
            'Selected Genre': 'Vybraný žánr',
            'Selected Playlist': 'Vybraný playlist',
            'Selected Year': 'Vybraný rok',
            'Length': 'Délka',
            'loading': 'načítání'
    },
    '');
<|endoftext|>


<commit_before>import Ember from 'ember';

import OSFAgnosticAuthRouteMixin from 'ember-osf/mixins/osf-agnostic-auth-route';
import AnalyticsMixin from '../mixins/analytics-mixin';

export default Ember.Route.extend(AnalyticsMixin, OSFAgnosticAuthRouteMixin, {
    i18n: Ember.inject.service(),
    afterModel: function() {
        const availableLocales = this.get('i18n.locales').toArray();
        let locale;

        // Works in Chrome and Firefox (editable in settings)
        if (navigator.languages && navigator.languages.length) {
            for (let lang of navigator.languages) {
                if (availableLocales.contains(lang)) {
                    locale = lang;
                    break;
                }
            }
        }
        // Backup for Safari (uses system settings)
        else if (navigator.language && availableLocales.contains(navigator.language)) {
            locale = navigator.language;
        }

        if (locale)
            this.set('i18n.locale', navigator.language);
    }
});
<commit_msg>Fix setting locale to the proper variable<commit_after>import Ember from 'ember';

import OSFAgnosticAuthRouteMixin from 'ember-osf/mixins/osf-agnostic-auth-route';
import AnalyticsMixin from '../mixins/analytics-mixin';

export default Ember.Route.extend(AnalyticsMixin, OSFAgnosticAuthRouteMixin, {
    i18n: Ember.inject.service(),
    afterModel: function() {
        const availableLocales = this.get('i18n.locales').toArray();
        let locale;

        // Works in Chrome and Firefox (editable in settings)
        if (navigator.languages && navigator.languages.length) {
            for (let lang of navigator.languages) {
                if (availableLocales.contains(lang)) {
                    locale = lang;
                    break;
                }
            }
        }
        // Backup for Safari (uses system settings)
        else if (navigator.language && availableLocales.contains(navigator.language)) {
            locale = navigator.language;
        }

        if (locale)
            this.set('i18n.locale', locale);
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';

import OSFAgnosticAuthRouteMixin from 'ember-osf/mixins/osf-agnostic-auth-route';
import AnalyticsMixin from '../mixins/analytics-mixin';

export default Ember.Route.extend(AnalyticsMixin, OSFAgnosticAuthRouteMixin, {
    i18n: Ember.inject.service(),
    afterModel: function() {
        const availableLocales = this.get('i18n.locales').toArray();
        let locale;

        console.log(availableLocales);

        // Works in Chrome and Firefox (editable in settings)
        if (navigator.languages && navigator.languages.length) {
            for (let lang of navigator.languages) {
                if (availableLocales.contains(lang)) {
                    locale = lang;
                    break;
                }
            }
        }
        // Backup for Safari (uses system settings)
        else if (navigator.language && availableLocales.contains(navigator.language)) {
            locale = navigator.language;
        }

        if (locale)
            this.set('i18n.locale', navigator.language);
    }
});
<commit_msg>Remove console.log statement<commit_after>import Ember from 'ember';

import OSFAgnosticAuthRouteMixin from 'ember-osf/mixins/osf-agnostic-auth-route';
import AnalyticsMixin from '../mixins/analytics-mixin';

export default Ember.Route.extend(AnalyticsMixin, OSFAgnosticAuthRouteMixin, {
    i18n: Ember.inject.service(),
    afterModel: function() {
        const availableLocales = this.get('i18n.locales').toArray();
        let locale;

        // Works in Chrome and Firefox (editable in settings)
        if (navigator.languages && navigator.languages.length) {
            for (let lang of navigator.languages) {
                if (availableLocales.contains(lang)) {
                    locale = lang;
                    break;
                }
            }
        }
        // Backup for Safari (uses system settings)
        else if (navigator.language && availableLocales.contains(navigator.language)) {
            locale = navigator.language;
        }

        if (locale)
            this.set('i18n.locale', navigator.language);
    }
});
<|endoftext|>


<commit_before>var express = require('express'),
    bot = require('../bot'),
    githubApi = require('../github'),
    config = require('../../config'),
    debug = require('debug')('reviewbot:pullrequest'),
    router = express.Router();

  /**
   * POST /pullrequest: Process incoming GitHub payload
   */
   router.post('/:reviewsNeeded', _handlePREvent);
   router.post('/', _handlePREvent);

  function _handlePREvent (req, res) {
    var eventName = req.get("X-GitHub-Event");
    if(req.params.reviewsNeeded) {
      console.log("reviewsNeeded passed as param: " + req.params.reviewsNeeded);
    } else {
      console.log("No reviewsNeeded passed, using default from config: " + config.reviewsNeeded);
    }
    // see if the reviewsNeeded was passed as param to the callback
    if(req.params.reviewsNeeded && !isNaN(parseInt(req.params.reviewsNeeded,0)) && parseInt(req.params.reviewsNeeded, 0) > 0 ) {
      config.reviewsNeeded = parseInt(req.params.reviewsNeeded, 0);
    }

    // ensure we only handle events we know how to handle
    if( config.pullRequestEvents.indexOf(eventName) < 0 ) {
      console.log('POST Request received, but this is not the event I am looking for.');
      return debug('POST Request received, but this is not the event I am looking for.');
    }

    if (!req.body) {
      console.log('POST Request received, but no body!');
      return debug('POST Request received, but no body!');
    }
    if (!req.body.repository) {
      console.log('POST Request received, but no repo found.');
      return debug('POST Request received, but no repo found.');
    }
    var repo = req.body.repository.name;
    // Check if it's a simple PR action
    if (req.body.pull_request && req.body.pull_request.number) {

      if ( req.body.pull_request.state && config.pullRequestsStatus.indexOf(req.body.pull_request.state) < 0 ) {
        console.log("POST Request received, but the PR is in a state that I do not care about (" + req.body.pull_request.state + ").");
        return debug("POST Request received, but the PR is in a state that I do not care about (" + req.body.pull_request.state + ").");
      }

      bot.checkForLabel(req.body.pull_request.number, repo, req.body.pull_request, processPullRequest);
      return _respond(res, 'Processing PR ' + req.body.pull_request.number);
    }

    // Check if it's an issue action (comment, for instance)
    if (req.body.issue && req.body.issue.pull_request) {
        githubApi.pullrequests.get(req.body.issue.number, repo, function (pullRequests) {
            if (!pullRequests || pullRequests.length < 0) {
              console.log('Error: Tried to process single pull request, but failed');
              return debug('Error: Tried to process single pull request, but failed');
            }
            var pr0 = pullRequests[0];
            if ( pr0.state && config.pullRequestsStatus.indexOf(pr0.state) < 0 ) {
              console.log("POST Request received, but the PR is in a state that I do not care about (" + pr0.state + ").");
              return debug("POST Request received, but the PR is in a state that I do not care about (" + pr0.state + ").");
            }
            bot.checkForLabel(pr0.number, repo, pr0, processPullRequest);
        });
        return _respond(res, 'Processing PR as Issue' + req.body.issue.number);
    }
  }

/**
 * Respond using a given Express res object
 * @param {Object} res - Express res object
 * @param {string|string[]} message - Either a message or an array filled with messages
 */
function _respond(res, message) {
    if (res && message) {
        if (message.isArray) {
            return res.json({messages: JSON.stringify(message)});
        } else {
            res.json({message: message});
        }
    }
}

/**
 * Process Pull Request
 * @param {string[]} labelResult - Result as generated by bot.checkForLabels;
 * @param {Object} pr - PR currently handled
 */
function processPullRequest(labelResult, pr) {
    // Check if PR is already labeled as 'reviewed', in which case we stop here
    if (labelResult.labeledReviewed) {
        return debug('PR ' + pr.number + ' already marked as "reviewed", stopping');
    }

    // Check if we're supposed to skip this one
    if (labelResult.labeledExclude) {
        return debug('PR ' + pr.number + ' labeled to be exlcuded from the bot, stopping');
    }
    console.log("processPullRequest");
    // Check for filenameFilter
     bot.checkForFiles(pr.number, pr.head.repo.name, function (isFilenameMatched) {
        if (!isFilenameMatched) {
            console.log('PR ' + pr.number + ' does not match filenameFilter, stopping')
            return debug('PR ' + pr.number + ' does not match filenameFilter, stopping');
        }
        console.log("checkForApprovalComments:::")
        // Let's get all our comments and check them for approval
        bot.checkForApprovalComments(pr.number, pr.head.repo.name, pr, function (approved) {
            var labels, output = [];

            // Check for instructions comment and post if not present
            bot.postInstructionsComment(pr.number, pr.head.repo.name);

            // Stop if we already marked it as 'needs-review' and it does need more reviews
            if (labelResult.labeledNeedsReview && !approved) {
              console.log('PR ' + pr.number + ' already marked as "needs-review", stopping');
              return debug('PR ' + pr.number + ' already marked as "needs-review", stopping');
            }

            labels = labelResult.labels.map(function (label) {
                return label.name;
            });

            // Update the labels
            output.push('Updating labels for PR ' + pr.number);
            bot.updateLabels(pr.number, pr.head.repo.name, approved, labels);

            // If we're supposed to merge, merge
            if (approved && config.mergeOnReview) {
                output.push('Merging on review set to true, PR approved, merging');
                bot.merge(pr.number);
            }
        });
    });
}

module.exports = router;
<commit_msg>fixed #18 - check if the webhook action is 'assigned' when the PR is created, if it is, ignore the action so the bot doesnt spam the PR<commit_after>var express = require('express'),
    bot = require('../bot'),
    githubApi = require('../github'),
    config = require('../../config'),
    debug = require('debug')('reviewbot:pullrequest'),
    router = express.Router();

  /**
   * POST /pullrequest: Process incoming GitHub payload
   */
   router.post('/:reviewsNeeded', _handlePREvent);
   router.post('/', _handlePREvent);

  function _handlePREvent (req, res) {
    var eventName = req.get("X-GitHub-Event");
    if(req.params.reviewsNeeded) {
      console.log("reviewsNeeded passed as param: " + req.params.reviewsNeeded);
    } else {
      console.log("No reviewsNeeded passed, using default from config: " + config.reviewsNeeded);
    }
    // see if the reviewsNeeded was passed as param to the callback
    if(req.params.reviewsNeeded && !isNaN(parseInt(req.params.reviewsNeeded,0)) && parseInt(req.params.reviewsNeeded, 0) > 0 ) {
      config.reviewsNeeded = parseInt(req.params.reviewsNeeded, 0);
    }

    // ensure we only handle events we know how to handle
    if( config.pullRequestEvents.indexOf(eventName) < 0 ) {
      console.log('POST Request received, but this is not the event I am looking for.');
      return debug('POST Request received, but this is not the event I am looking for.');
    }

		// assigned causes the bot to spam the instructions comment.
		if(req.body.action && req.body.action === "assigned") {
			console.log('POST Request received, but "' + req.body.action + '" is not an action I am looking for.');
      return debug('POST Request received, but "' + req.body.action + '" is not an action I am looking for.');
		}

    if (!req.body) {
      console.log('POST Request received, but no body!');
      return debug('POST Request received, but no body!');
    }
    if (!req.body.repository) {
      console.log('POST Request received, but no repo found.');
      return debug('POST Request received, but no repo found.');
    }

    var repo = req.body.repository.name;
    // Check if it's a simple PR action
    if (req.body.pull_request && req.body.pull_request.number) {

      if ( req.body.pull_request.state && config.pullRequestsStatus.indexOf(req.body.pull_request.state) < 0 ) {
        console.log("POST Request received, but the PR is in a state that I do not care about (" + req.body.pull_request.state + ").");
        return debug("POST Request received, but the PR is in a state that I do not care about (" + req.body.pull_request.state + ").");
      }

      bot.checkForLabel(req.body.pull_request.number, repo, req.body.pull_request, processPullRequest);
      return _respond(res, 'Processing PR ' + req.body.pull_request.number);
    }

    // Check if it's an issue action (comment, for instance)
    if (req.body.issue && req.body.issue.pull_request) {
        githubApi.pullrequests.get(req.body.issue.number, repo, function (pullRequests) {
            if (!pullRequests || pullRequests.length < 0) {
              console.log('Error: Tried to process single pull request, but failed');
              return debug('Error: Tried to process single pull request, but failed');
            }
            var pr0 = pullRequests[0];
            if ( pr0.state && config.pullRequestsStatus.indexOf(pr0.state) < 0 ) {
              console.log("POST Request received, but the PR is in a state that I do not care about (" + pr0.state + ").");
              return debug("POST Request received, but the PR is in a state that I do not care about (" + pr0.state + ").");
            }
            bot.checkForLabel(pr0.number, repo, pr0, processPullRequest);
        });
        return _respond(res, 'Processing PR as Issue' + req.body.issue.number);
    }
  }

/**
 * Respond using a given Express res object
 * @param {Object} res - Express res object
 * @param {string|string[]} message - Either a message or an array filled with messages
 */
function _respond(res, message) {
    if (res && message) {
        if (message.isArray) {
            return res.json({messages: JSON.stringify(message)});
        } else {
            res.json({message: message});
        }
    }
}

/**
 * Process Pull Request
 * @param {string[]} labelResult - Result as generated by bot.checkForLabels;
 * @param {Object} pr - PR currently handled
 */
function processPullRequest(labelResult, pr) {
    // Check if PR is already labeled as 'reviewed', in which case we stop here
    if (labelResult.labeledReviewed) {
        return debug('PR ' + pr.number + ' already marked as "reviewed", stopping');
    }

    // Check if we're supposed to skip this one
    if (labelResult.labeledExclude) {
        return debug('PR ' + pr.number + ' labeled to be exlcuded from the bot, stopping');
    }
    console.log("processPullRequest");
    // Check for filenameFilter
     bot.checkForFiles(pr.number, pr.head.repo.name, function (isFilenameMatched) {
        if (!isFilenameMatched) {
            console.log('PR ' + pr.number + ' does not match filenameFilter, stopping')
            return debug('PR ' + pr.number + ' does not match filenameFilter, stopping');
        }
        console.log("checkForApprovalComments:::")
        // Let's get all our comments and check them for approval
        bot.checkForApprovalComments(pr.number, pr.head.repo.name, pr, function (approved) {
            var labels, output = [];

            // Check for instructions comment and post if not present
            bot.postInstructionsComment(pr.number, pr.head.repo.name);

            // Stop if we already marked it as 'needs-review' and it does need more reviews
            if (labelResult.labeledNeedsReview && !approved) {
              console.log('PR ' + pr.number + ' already marked as "needs-review", stopping');
              return debug('PR ' + pr.number + ' already marked as "needs-review", stopping');
            }

            labels = labelResult.labels.map(function (label) {
                return label.name;
            });

            // Update the labels
            output.push('Updating labels for PR ' + pr.number);
            bot.updateLabels(pr.number, pr.head.repo.name, approved, labels);

            // If we're supposed to merge, merge
            if (approved && config.mergeOnReview) {
                output.push('Merging on review set to true, PR approved, merging');
                bot.merge(pr.number);
            }
        });
    });
}

module.exports = router;
<|endoftext|>


<commit_before>import cloneDeep from 'lodash/cloneDeep';
export default {
    name: 'u-form',
    props: {
        model: Object,
        rules: Object,
        layout: { type: String, default: 'block' },
        labelSize: { type: String, default: 'normal' },
    },
    data() {
        return {
            // @TODO: Optimize
            state: '',
            itemVMs: [],
            comparedModel: null,
        };
    },
    created() {
        this.$on('add-item-vm', (itemVM) => {
            itemVM.parentVM = this;
            this.itemVMs.push(itemVM);
        });
        this.$on('remove-item-vm', (itemVM) => {
            itemVM.parentVM = undefined;
            this.itemVMs.splice(this.itemVMs.indexOf(itemVM), 1);
        });
        this.$on('validate-item-vm', () => {
            this.state = this.getState();
            this.$emit('validate', {
                valid: this.state === 'success',
            });
        });
    },
    watch: {
        model: {
            handler(val) {
                if (this.comparedModel) {
                    // @TODO: 考虑到 @change 事件是基于子组件的 @change 事件的，所以 @modify 命名分开
                    this.$emit('modify', {
                        modified: this.deepCompare(val, this.comparedModel),
                    });
                }
            },
            deep: true,
        },
    },
    methods: {
        validate(silent = false) {
            return Promise.all(this.itemVMs.map((itemVM) => itemVM.validate('submit', silent)
                .catch((errors) => errors)
            )).then((results) => {
                if (results.some((result) => !!result))
                    throw new Error(results);
            });
        },
        validateItem(name, trigger = 'submit', silent = false) {
            const itemVM = this.itemVMs.find((itemVM) => itemVM.name === name);
            if (!itemVM)
                return;
            itemVM.validate(trigger, silent);
        },
        getState() {
            const STATE_LEVEL = {
                '': 4,
                focus: 3,
                validating: 2,
                error: 1,
                success: 0,
            };

            let state = 'success';
            this.itemVMs.forEach((itemVM) => {
                if (itemVM.currentRules && STATE_LEVEL[itemVM.state] > STATE_LEVEL[state])
                    state = itemVM.state;
            });

            return state;
        },
        record() {
            this.comparedModel = cloneDeep(this.model);
        },
        deepCompare(o = {}, compare) {
            if (!compare)
                return false;
            if (typeof o === 'object' && o !== null) {
                if (Array.isArray(o))
                    return o.length !== compare.length || o.some((m, i) => this.deepCompare(m, compare[i]));
                else
                    return Object.keys(o).some((key) => this.deepCompare(o[key], compare[key]));
            } else
                return o !== compare;
        },
    },
};
<commit_msg>:bug: <u-form>validate错误抛出errors<commit_after>import cloneDeep from 'lodash/cloneDeep';
export default {
    name: 'u-form',
    props: {
        model: Object,
        rules: Object,
        layout: { type: String, default: 'block' },
        labelSize: { type: String, default: 'normal' },
    },
    data() {
        return {
            // @TODO: Optimize
            state: '',
            itemVMs: [],
            comparedModel: null,
        };
    },
    created() {
        this.$on('add-item-vm', (itemVM) => {
            itemVM.parentVM = this;
            this.itemVMs.push(itemVM);
        });
        this.$on('remove-item-vm', (itemVM) => {
            itemVM.parentVM = undefined;
            this.itemVMs.splice(this.itemVMs.indexOf(itemVM), 1);
        });
        this.$on('validate-item-vm', () => {
            this.state = this.getState();
            this.$emit('validate', {
                valid: this.state === 'success',
            });
        });
    },
    watch: {
        model: {
            handler(val) {
                if (this.comparedModel) {
                    // @TODO: 考虑到 @change 事件是基于子组件的 @change 事件的，所以 @modify 命名分开
                    this.$emit('modify', {
                        modified: this.deepCompare(val, this.comparedModel),
                    });
                }
            },
            deep: true,
        },
    },
    methods: {
        validate(silent = false) {
            return Promise.all(this.itemVMs.map((itemVM) => itemVM.validate('submit', silent)
                .catch((errors) => errors)
            )).then((results) => {
                if (results.some((result) => !!result))
                    throw results;
            });
        },
        validateItem(name, trigger = 'submit', silent = false) {
            const itemVM = this.itemVMs.find((itemVM) => itemVM.name === name);
            if (!itemVM)
                return;
            itemVM.validate(trigger, silent);
        },
        getState() {
            const STATE_LEVEL = {
                '': 4,
                focus: 3,
                validating: 2,
                error: 1,
                success: 0,
            };

            let state = 'success';
            this.itemVMs.forEach((itemVM) => {
                if (itemVM.currentRules && STATE_LEVEL[itemVM.state] > STATE_LEVEL[state])
                    state = itemVM.state;
            });

            return state;
        },
        record() {
            this.comparedModel = cloneDeep(this.model);
        },
        deepCompare(o = {}, compare) {
            if (!compare)
                return false;
            if (typeof o === 'object' && o !== null) {
                if (Array.isArray(o))
                    return o.length !== compare.length || o.some((m, i) => this.deepCompare(m, compare[i]));
                else
                    return Object.keys(o).some((key) => this.deepCompare(o[key], compare[key]));
            } else
                return o !== compare;
        },
    },
};
<|endoftext|>


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

    let btnMakeSimpleCallStack = document.getElementById('btnMakeSimpleCallStack');

    function makeTheFisrtCall() {
        printSomeMessage();
    }

    function printSomeMessage() {
        var message = getFullname('Hello', 'Stack');

        console.log(message);
    }

    function getFullname(name, lastName) {
        return `${ name } ${ lastName }!`;
    }

    btnMakeSimpleCallStack.addEventListener('click', makeTheFisrtCall);
})();
<commit_msg>Added debugger in call stack example<commit_after>(() => {
    'use strict';

    let btnMakeSimpleCallStack = document.getElementById('btnMakeSimpleCallStack');

    function makeTheFisrtCall() {
        debugger;

        printSomeMessage();
    }

    function printSomeMessage() {
        var message = getFullname('Hello', 'Stack');

        console.log(message);
    }

    function getFullname(name, lastName) {
        return `${ name } ${ lastName }!`;
    }

    btnMakeSimpleCallStack.addEventListener('click', makeTheFisrtCall);
})();
<|endoftext|>


<commit_before>goog.provide('recoil.ui.widgets.PopupWidget');

goog.require('goog.dom');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.ui.Container');
goog.require('goog.ui.Popup');
goog.require('recoil.ui.ComponentWidgetHelper');
goog.require('recoil.ui.WidgetScope');

/**
 *
 * @template T
 * @param {!recoil.ui.WidgetScope} scope
 * @implements {recoil.ui.Widget}
 * @constructor
 */
recoil.ui.widgets.PopupWidget = function(scope) {
    this.scope_ = scope;
    this.popupContainer_ = goog.dom.createDom('div');
    this.displayContainer_ = goog.dom.createDom(
        'div',
        {'class' : 'goog-inline-block goog-menu-button-caption', tabindex: 0});
    this.buttonContainer_ = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button-dropdown'});
    this.displayAndButtonContainer_ = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button'});
    var outerBox = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button-outer-box'});
    var innerBox = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button-inner-box'});

    goog.dom.append(this.displayAndButtonContainer_, outerBox);
    goog.dom.append(outerBox, innerBox);
    goog.dom.append(innerBox, this.displayContainer_);
    goog.dom.append(innerBox, this.buttonContainer_);

    this.container_ = new goog.ui.Component();
    var toControl = recoil.ui.ComponentWidgetHelper.elementToNoFocusControl;

//    this.container_.addClassName("goog-inline-block");

    this.container_.addChild(toControl(this.displayAndButtonContainer_), true);
    this.container_.addChild(toControl(this.popupContainer_), true);
    this.popup_ = new goog.ui.Popup(this.popupContainer_);

    goog.dom.setProperties(this.popupContainer_, {class: 'recoil-popup'});

    this.popup_.setVisible(false);
    var me = this;
    var doPopup = function() {
        me.popup_.setVisible(false);
        me.popup_.setPinnedCorner(goog.positioning.Corner.TOP_LEFT); // button corner
        me.popup_.setMargin(new goog.math.Box(0, 0, 0, 0));
        me.popup_.setPosition(new goog.positioning.AnchoredViewportPosition(me.displayAndButtonContainer_,
        goog.positioning.Corner.BOTTOM_LEFT));

        me.popup_.setVisible(true);

    };
    this.displayAndButtonContainer_.onmousedown = doPopup;

    goog.events.listen(this.displayAndButtonContainer_
, goog.events.EventType.KEYDOWN,
                       function(e) {
                               console.log(e.keyCode);
                           if (e.keyCode === goog.events.KeyCodes.SPACE) {
                               if (me.popup_.isVisible()) {
                                   me.popup_.setVisible(false);
                               }
                               else {
                                   doPopup();
                               }
                           }
                           else if (e.keyCode === goog.events.KeyCodes.ESC) {
                               me.popup_.setVisible(false);
                           }

                       });
    goog.events.listen(this.popup_.getElement(), goog.events.EventType.BLUR, function(e) {
        console.log('bluring popup');
    });

    this.popup_.setHideOnEscape(true);
    this.popup_.setAutoHide(true);
    this.helper_ = new recoil.ui.ComponentWidgetHelper(scope, this.container_, this, this.updateState_);
};

/**
 */
recoil.ui.widgets.PopupWidget.options = recoil.frp.Util.Options('popupWidget', 'displayWidget');

/**
 * @param {!recoil.frp.Behaviour<!recoil.ui.Widget>|!recoil.ui.Widget} popupWidget the widget that will be displayed in the popup
 * @param {!recoil.frp.Behaviour<!recoil.ui.Widget>|!recoil.ui.Widget} displayWidget the widget that will be displayed normally (no popup required
 * @suppress {missingProperties}
 */

recoil.ui.widgets.PopupWidget.prototype.attach = function(popupWidget, displayWidget)  {
    recoil.ui.widgets.PopupWidget.options.displayWidget(displayWidget).popupWidget(popupWidget).attach(this);
};

/**
 * see recoil.ui.widgets.PopupWidget.options fro valid options
 * @param {!Object|!recoil.frp.Behaviour<Object>} options
 * @suppress {missingProperties}
 */
recoil.ui.widgets.PopupWidget.prototype.attachStruct = function(options) {
    var frp = this.helper_.getFrp();
    var bound = recoil.ui.widgets.PopupWidget.options.bind(frp, options);

    this.displayWidgetB = bound.displayWidget();
    this.popupWidgetB = bound.popupWidget();

    this.helper_.attach(this.popupWidgetB, this.displayWidgetB);

};

/**
 * @private
 * @param {!Element} container where the component goes
 * @param {goog.ui.Component} current the currently renderd component
 * @param {goog.ui.Component} newComponent the component we want to render
 * @return {goog.ui.Component} the new Component
 */
recoil.ui.widgets.PopupWidget.prototype.replaceComponent_ = function(container, current, newComponent) {
    if (current !== newComponent) {
        goog.dom.removeChildren(container);
        newComponent.render(container);
    }
    return newComponent;
};
/**
 *
 * @param {recoil.ui.WidgetHelper} helper
 * @private
 */
recoil.ui.widgets.PopupWidget.prototype.updateState_ = function(helper) {
    if (helper.isGood()) {
        this.displayComponent_ = this.replaceComponent_(this.displayContainer_, this.displayComponent_, this.displayWidgetB.get().getComponent());
        this.popupComponent_ = this.replaceComponent_(this.popupContainer_, this.popupComponent_, this.popupWidgetB.get().getComponent());
    }
    else {
    }
};

/**
 * @return {!goog.ui.Component}
 */
recoil.ui.widgets.PopupWidget.prototype.getComponent = function() {
    return this.container_;
};

/**
 * all widgets should not allow themselves to be flatterned
 *
 * @type {!Object}
 */

recoil.ui.widgets.PopupWidget.prototype.flatten = recoil.frp.struct.NO_FLATTEN;
<commit_msg>put focus on popup widget<commit_after>goog.provide('recoil.ui.widgets.PopupWidget');

goog.require('goog.dom');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.ui.Container');
goog.require('goog.ui.Popup');
goog.require('recoil.ui.ComponentWidgetHelper');
goog.require('recoil.ui.WidgetScope');

/**
 *
 * @template T
 * @param {!recoil.ui.WidgetScope} scope
 * @implements {recoil.ui.Widget}
 * @constructor
 */
recoil.ui.widgets.PopupWidget = function(scope) {
    this.scope_ = scope;
    this.popupContainer_ = goog.dom.createDom('div');
    this.displayContainer_ = goog.dom.createDom(
        'div',
        {'class' : 'goog-inline-block goog-menu-button-caption', tabindex: 0});
    this.buttonContainer_ = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button-dropdown'});
    this.displayAndButtonContainer_ = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button'});
    var outerBox = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button-outer-box'});
    var innerBox = goog.dom.createDom('div', {'class' : 'goog-inline-block goog-menu-button-inner-box'});

    goog.dom.append(this.displayAndButtonContainer_, outerBox);
    goog.dom.append(outerBox, innerBox);
    goog.dom.append(innerBox, this.displayContainer_);
    goog.dom.append(innerBox, this.buttonContainer_);

    this.container_ = new goog.ui.Component();
    var toControl = recoil.ui.ComponentWidgetHelper.elementToNoFocusControl;

//    this.container_.addClassName("goog-inline-block");

    var buttonControl = recoil.ui.ComponentWidgetHelper.elementToControl(this.displayAndButtonContainer_);
    this.container_.addChild(buttonControl, true);
    this.container_.addChild(toControl(this.popupContainer_), true);
    this.popup_ = new goog.ui.Popup(this.popupContainer_);
    goog.dom.setProperties(this.popupContainer_, {class: 'recoil-popup'});

    this.popup_.setVisible(false);
    var me = this;
    var doPopup = function() {
        me.popup_.setVisible(false);
        me.popup_.setPinnedCorner(goog.positioning.Corner.TOP_LEFT); // button corner
        me.popup_.setMargin(new goog.math.Box(0, 0, 0, 0));
        me.popup_.setPosition(new goog.positioning.AnchoredViewportPosition(me.displayAndButtonContainer_,
        goog.positioning.Corner.BOTTOM_LEFT));

        me.popup_.setVisible(true);

    };
    this.displayAndButtonContainer_.onmousedown = doPopup;

    goog.events.listen(this.displayAndButtonContainer_
, goog.events.EventType.KEYDOWN,
                       function(e) {
                               console.log(e.keyCode);
                           if (e.keyCode === goog.events.KeyCodes.SPACE) {
                               if (me.popup_.isVisible()) {
                                   me.popup_.setVisible(false);
                               }
                               else {
                                   doPopup();
                               }
                           }
                           else if (e.keyCode === goog.events.KeyCodes.ESC) {
                               me.popup_.setVisible(false);
                           }

                       });
    goog.events.listen(this.popup_.getElement(), goog.events.EventType.BLUR, function(e) {
        console.log('bluring popup');
    });

    this.popup_.setHideOnEscape(true);
    this.popup_.setAutoHide(true);
    this.helper_ = new recoil.ui.ComponentWidgetHelper(scope, this.container_, this, this.updateState_);
};

/**
 */
recoil.ui.widgets.PopupWidget.options = recoil.frp.Util.Options('popupWidget', 'displayWidget');

/**
 * @param {!recoil.frp.Behaviour<!recoil.ui.Widget>|!recoil.ui.Widget} popupWidget the widget that will be displayed in the popup
 * @param {!recoil.frp.Behaviour<!recoil.ui.Widget>|!recoil.ui.Widget} displayWidget the widget that will be displayed normally (no popup required
 * @suppress {missingProperties}
 */

recoil.ui.widgets.PopupWidget.prototype.attach = function(popupWidget, displayWidget)  {
    recoil.ui.widgets.PopupWidget.options.displayWidget(displayWidget).popupWidget(popupWidget).attach(this);
};

/**
 * see recoil.ui.widgets.PopupWidget.options fro valid options
 * @param {!Object|!recoil.frp.Behaviour<Object>} options
 * @suppress {missingProperties}
 */
recoil.ui.widgets.PopupWidget.prototype.attachStruct = function(options) {
    var frp = this.helper_.getFrp();
    var bound = recoil.ui.widgets.PopupWidget.options.bind(frp, options);

    this.displayWidgetB = bound.displayWidget();
    this.popupWidgetB = bound.popupWidget();

    this.helper_.attach(this.popupWidgetB, this.displayWidgetB);

};

/**
 * @private
 * @param {!Element} container where the component goes
 * @param {goog.ui.Component} current the currently renderd component
 * @param {goog.ui.Component} newComponent the component we want to render
 * @return {goog.ui.Component} the new Component
 */
recoil.ui.widgets.PopupWidget.prototype.replaceComponent_ = function(container, current, newComponent) {
    if (current !== newComponent) {
        goog.dom.removeChildren(container);
        newComponent.render(container);
    }
    return newComponent;
};
/**
 *
 * @param {recoil.ui.WidgetHelper} helper
 * @private
 */
recoil.ui.widgets.PopupWidget.prototype.updateState_ = function(helper) {
    if (helper.isGood()) {
        this.displayComponent_ = this.replaceComponent_(this.displayContainer_, this.displayComponent_, this.displayWidgetB.get().getComponent());
        this.popupComponent_ = this.replaceComponent_(this.popupContainer_, this.popupComponent_, this.popupWidgetB.get().getComponent());
    }
    else {
    }
};

/**
 * @return {!goog.ui.Component}
 */
recoil.ui.widgets.PopupWidget.prototype.getComponent = function() {
    return this.container_;
};

/**
 * all widgets should not allow themselves to be flatterned
 *
 * @type {!Object}
 */

recoil.ui.widgets.PopupWidget.prototype.flatten = recoil.frp.struct.NO_FLATTEN;
<|endoftext|>


<commit_before>const PanelsActionCreator = require('../actions/panels-action-creator');

PATTERN_LEVELS = [
  // level 0 sequence
  [
    // sequence step = {stripId: {panelId: active}}
    // All other panels and strips will be turned inactive
    {'0': {'3': true}},
    {'0': {'4': true}},
    {'0': {'5': true}},
  ],
  // level 1 sequence
  [
    {'1': {'3': true}},
    {'1': {'5': true}},
    {'1': {'4': true}},
  ],
  // level 2 sequence
  [
    {'2': {'3': true}},
    {'2': {'5': true}},
    {'2': {'4': true}},
    {'2': {'6': true}},
  ],
];

const TARGET_PANEL_INTENSITY = 100;
const PANEL_OFF_INTENSITY = 0;
const SEQUENCE_ANIMATION_FRAME_DELAY = 500;

const ANIMATION_NONE = false;

export default class SimonGameLogic {
  static ANIMATION_SUCCESS = "success";

  // These are automatically added to the sculpture store
  static trackedProperties = {
    level: 0,
    levelPosition: 0
  };

  constructor(store) {
    this.store = store;
  }

  get data() {
    return this.store.data.get('simon');
  }

  get _lights() {
    return this.store.data.get('lights');
  }

  start() {
    this._playCurrentSequence();
  }

  handleActionPayload(payload) {
    const actionHandlers = {
      [PanelsActionCreator.PANEL_PRESSED]: this._actionPanelPressed.bind(this),
    };

    const actionHandler = actionHandlers[payload.actionType];
    if (actionHandler) {
      actionHandler(payload);
    }
  }

  _actionPanelPressed(payload) {
    let {stripId, panelId, pressed} = payload;
  }

  _playCurrentSequence() {
    const level = this.data.get('level');
    const currentSequence = PATTERN_LEVELS[level];

    this._playSequence(currentSequence);
  }

  _playSequence(sequence) {
    let frameIndex = -1;
    const playNextFrame = () => {
      frameIndex += 1;

      const frame = sequence[frame];
    };

    playNextFrame();
  }
}
<commit_msg>Fixed syntax error in simon game logic<commit_after>const PanelsActionCreator = require('../actions/panels-action-creator');

const PATTERN_LEVELS = [
  // level 0 sequence
  [
    // sequence step = {stripId: {panelId: active}}
    // All other panels and strips will be turned inactive
    {'0': {'3': true}},
    {'0': {'4': true}},
    {'0': {'5': true}},
  ],
  // level 1 sequence
  [
    {'1': {'3': true}},
    {'1': {'5': true}},
    {'1': {'4': true}},
  ],
  // level 2 sequence
  [
    {'2': {'3': true}},
    {'2': {'5': true}},
    {'2': {'4': true}},
    {'2': {'6': true}},
  ],
];

const TARGET_PANEL_INTENSITY = 100;
const PANEL_OFF_INTENSITY = 0;
const SEQUENCE_ANIMATION_FRAME_DELAY = 500;

const ANIMATION_NONE = false;

export default class SimonGameLogic {
  static ANIMATION_SUCCESS = "success";

  // These are automatically added to the sculpture store
  static trackedProperties = {
    level: 0,
    levelPosition: 0
  };

  constructor(store) {
    this.store = store;
  }

  get data() {
    return this.store.data.get('simon');
  }

  get _lights() {
    return this.store.data.get('lights');
  }

  start() {
    this._playCurrentSequence();
  }

  handleActionPayload(payload) {
    const actionHandlers = {
      [PanelsActionCreator.PANEL_PRESSED]: this._actionPanelPressed.bind(this),
    };

    const actionHandler = actionHandlers[payload.actionType];
    if (actionHandler) {
      actionHandler(payload);
    }
  }

  _actionPanelPressed(payload) {
    let {stripId, panelId, pressed} = payload;
  }

  _playCurrentSequence() {
    const level = this.data.get('level');
    const currentSequence = PATTERN_LEVELS[level];

    this._playSequence(currentSequence);
  }

  _playSequence(sequence) {
    let frameIndex = -1;
    const playNextFrame = () => {
      frameIndex += 1;

      const frame = sequence[frame];
    };

    playNextFrame();
  }
}
<|endoftext|>


<commit_before>
// class Impetus
function Impetus()
{
    this.sounds = [];
}
// function getSound(String url):ImpetusSound
Impetus.prototype.getSound = function(url)
{
    for(var i = 0; i < this.sounds.length; ++i)
    {
        if(sounds[i].url === url)
        {
            return sounds[i];
        }
    }

    var s = new ImpetusSound(url);

    this.sounds.push(s);

    return s;
};

// class ImpetusSound
function ImpetusSound(url)
{
    this.url = url; // :String
}
// function playNew():ImpetusChannel
ImpetusSound.prototype.playNew = function()
{
};
// function stopAll():void
ImpetusSound.prototype.stopAll = function()
{
};

// class ImpetusChannel
function ImpetusChannel()
{
}
// function play():void
ImpetusChannel.prototype.play = function()
{
};
// function stop():void
ImpetusChannel.prototype.stop = function()
{
};
// function setPos(int pos):void
ImpetusChannel.prototype.setPos = function(pos)
{
};
// function getPos():int
ImpetusChannel.prototype.getPos = function()
{
};
<commit_msg>Implement ImpetusSound::playNew() & stopAll()<commit_after>
// class Impetus
function Impetus()
{
    this.sounds = []; // :Array<ImpetusSound>
}
// function getSound(String url):ImpetusSound
Impetus.prototype.getSound = function(url)
{
    for(var i = 0; i < this.sounds.length; ++i)
    {
        if(sounds[i].url === url)
        {
            return sounds[i];
        }
    }

    var s = new ImpetusSound(url);

    this.sounds.push(s);

    return s;
};

// class ImpetusSound
function ImpetusSound(url)
{
    this.url = url; // :String

    this.channels =[]; // :Array<ImpetusChannel>
}
// function playNew():ImpetusChannel
ImpetusSound.prototype.playNew = function()
{
    var c = new ImpetusChannel();

    this.channels.push(c);

    return c;
};
// function stopAll():void
ImpetusSound.prototype.stopAll = function()
{
    for(var i = 0; i < this.channels.length; ++i)
    {
        channels[i].stop();
    }
};

// class ImpetusChannel
function ImpetusChannel()
{
}
// function play():void
ImpetusChannel.prototype.play = function()
{
};
// function stop():void
ImpetusChannel.prototype.stop = function()
{
};
// function setPos(int pos):void
ImpetusChannel.prototype.setPos = function(pos)
{
};
// function getPos():int
ImpetusChannel.prototype.getPos = function()
{
};
<|endoftext|>