<commit_before>var Popup = (function(my){

  var bg = chrome.extension.getBackgroundPage();
  var linkedinData = {};
  var settings = {};

  my.init = function() {
    window.addEventListener('load', showPopup, false);
  };

  function showPopup() {
    updateSettings();
    updateLinkedinData();
    renderContent();
  }

  function updateLinkedinData() {
    linkedinData = bg.App.linkedinData;
  }

  function updateSettings() {
    settings.apiKey = localStorage['apiKey'] || '';
  }

  function renderContent() {
    var result = my.template( $.extend({}, linkedinData, settings) );
    document.body.innerHTML = result.content;
    // attach event listeners
    for (var i = result.eventHandlers.length - 1; i >= 0; i--) {
      var f = result.eventHandlers[i];
      if (typeof f === 'function') f();
    };
  }

  // ========================================= Template
  my.template = function(data) {
    var content = '

',
        inputs = ['firstname', 'lastname', 'domain'];

    content += '

';
    content += '
<form id="submitName">';
    for (var i = 0, len = inputs.length; i < len; i++) {
      var id = inputs[i];
      content += '
<input id="' + id + '" value="' + (data[id] ? data[id] : '') + '" placeholder="' + id + '"/>
';
    }
    content += '<input type="button" class="btn btn-success" id="submitMake" value="Submit">';
    content += '</form>	';
    content += '<form id="submitEmail">';
    content += '
<input id="email" placeholder="email"/>
';
    content += '<button class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '

';

    content += '

';

    var eventHandlers = [];
    eventHandlers.push(

      function() {
        var showResult = function(msg, className, delay) {
          var $result = $('#result');
          $result.removeClass();
          if (className) $result.addClass(className);
          $result.html(msg).show();
          if (delay) {
            setTimeout(function(){
              $result.hide();
            }, delay);
          }
        }

        var showLoader = function() {
          showResult('

');
        }

        var checkAPI = function() {
          if (!data.apiKey) {
            showResult('
Please add your Toofr API key.

Find it by logging into Toofr. You will see your API key in the footer of every page. Right click on the Chrome extention to get to your Options page where you add your API key.
', 'alert alert-info', false);
            return false;
          }
          return true;
        }

        var sendRequest = function(url, processResponse) {
          $.ajax({
            url: url,
            method: 'POST',
            beforeSend: showLoader,
            dataType: 'json'
          }).done( function(response){
            var result = processResponse(response);
            showResult( result.content, result.type );
          }).fail( function(){
            showResult('Network error', 'alert alert-info', 2000);
          });
        }

        var processMakeResponse = function(json) {
            first = Object.keys(json)[0];
            confidence = json[first].confidence;
            email = json[first].email;
            type = 'alert alert-success';
            content = '';
            content += '
email: ' + email + '
';
            content += '
confidence: ' + confidence + '
';
            content += '
';
            content += '

';
          return {type: type, content: content};
        }

        var processEmailResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else {
            var confidence = json.confidence, email = json.email;
            content = '
email: ' + email + '
';
            content += '
Confidence:' + confidence + '
';
            content += '
';
            content += '

';
            type = 'alert alert-success';
            if (!confidence) type = 'alert alert-danger';
          }
          return {type: type, content: content};
        }

        var checkResponseErrors = function(json) {
          if (!json.confidence) return "Bad response";
          else if (json.error) return json.error;
          else return false;
        }

        $('#submitMake').click( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'https://www.toofr.com:443/api/v1/guess_email.json' +
              '?key=' + data.apiKey +
              '&company_name=' + $('#domain').val() +
              '&first_name=' + $('#firstname').val() +
              '&last_name=' + $('#lastname').val();
              console.log(url);
          sendRequest(url, processMakeResponse);
        });

        $('#submitEmail').submit( function(e){
          e.preventDefault();
          if (!checkAPI) return;
          var url = 'https://www.toofr.com:443/api/v1/test_email.json' +
              '?key=' + data.apiKey +
              '&email=' + $('#email').val();
          sendRequest(url, processEmailResponse);
        });

      });

    return {content: content, eventHandlers: eventHandlers};
  }

  return my;

})(Popup || {});

Popup.init();
<commit_msg>finished<commit_after>var Popup = (function(my){

  var bg = chrome.extension.getBackgroundPage();
  var linkedinData = {};
  var settings = {};

  my.init = function() {
    window.addEventListener('load', showPopup, false);
  };

  function showPopup() {
    updateSettings();
    updateLinkedinData();
    renderContent();
  }

  function updateLinkedinData() {
    linkedinData = bg.App.linkedinData;
  }

  function updateSettings() {
    settings.apiKey = localStorage['apiKey'] || '';
  }

  function renderContent() {
    var result = my.template( $.extend({}, linkedinData, settings) );
    document.body.innerHTML = result.content;
    // attach event listeners
    for (var i = result.eventHandlers.length - 1; i >= 0; i--) {
      var f = result.eventHandlers[i];
      if (typeof f === 'function') f();
    };
  }

  // ========================================= Template
  my.template = function(data) {
    var content = '

',
        inputs = ['firstname', 'lastname', 'domain'];

    content += '

';
    content += '
<form id="submitName">';
    for (var i = 0, len = inputs.length; i < len; i++) {
      var id = inputs[i];
      content += '
<input id="' + id + '" value="' + (data[id] ? data[id] : '') + '" placeholder="' + id + '"/>
';
    }
    content += '<input type="button" class="btn btn-success" id="submitMake" value="Submit">';
    content += '</form>	';
    content += '<form id="submitEmail">';
    content += '
<input id="email" placeholder="email"/>
';
    content += '<button class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '

';

    content += '

';

    var eventHandlers = [];
    eventHandlers.push(

      function() {
        var showResult = function(msg, className, delay) {
          var $result = $('#result');
          $result.removeClass();
          if (className) $result.addClass(className);
          $result.html(msg).show();
          if (delay) {
            setTimeout(function(){
              $result.hide();
            }, delay);
          }
        }

        var showLoader = function() {
          showResult('

');
        }

        var checkAPI = function() {
          if (!data.apiKey) {
            showResult('
Please add your Toofr API key.

Find it by logging into Toofr. You will see your API key in the footer of every page. Right click on the Chrome extention to get to your Options page where you add your API key.
', 'alert alert-info', false);
            return false;
          }
          return true;
        }

        var sendRequest = function(url, processResponse) {
          $.ajax({
            url: url,
            method: 'POST',
            beforeSend: showLoader,
            dataType: 'json'
          }).done( function(response){
            var result = processResponse(response);
            showResult( result.content, result.type );
          }).fail( function(){
            showResult('Network error', 'alert alert-info', 2000);
          });
        }

        var processMakeResponse = function(json) {
            first = Object.keys(json)[0];
            confidence = json[first].confidence;
            email = json[first].email;
            type = 'alert alert-success';
            content = '';
            content += '
email: ' + email + '
';
            content += '
confidence: ' + confidence + '
';
            content += '
';
            content += '

';
          return {type: type, content: content};
        }

        var processEmailResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else {
            var confidence = json.confidence, email = json.email;
            content = '
Confidence:' + confidence + '
';
            content += '
';
            content += '

';
            type = 'alert alert-success';
            if (!confidence) type = 'alert alert-danger';
          }
          return {type: type, content: content};
        }

        var checkResponseErrors = function(json) {
          if (!json.confidence) return "Bad response";
          else if (json.error) return json.error;
          else return false;
        }

        $('#submitMake').click( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'https://www.toofr.com:443/api/v1/guess_email.json' +
              '?key=' + data.apiKey +
              '&company_name=' + $('#domain').val() +
              '&first_name=' + $('#firstname').val() +
              '&last_name=' + $('#lastname').val();
              console.log(url);
          sendRequest(url, processMakeResponse);
        });

        $('#submitEmail').submit( function(e){
          e.preventDefault();
          if (!checkAPI) return;
          var url = 'https://www.toofr.com:443/api/v1/test_email.json' +
              '?key=' + data.apiKey +
              '&email=' + $('#email').val();
          sendRequest(url, processEmailResponse);
        });

      });

    return {content: content, eventHandlers: eventHandlers};
  }

  return my;

})(Popup || {});

Popup.init();
<|endoftext|>


<commit_before>if (arguments.length != 1) {
  print('usage: d8 wasm.js -- <filename>');
  quit(0);
}

var data = read(arguments[0]);
var buffer = new ArrayBuffer(data.length);
var u8a = new Uint8Array(buffer);
for (var i = 0; i < data.length; ++i) {
  u8a[i] = data.charCodeAt(i);
}
var module = WASM.instantiateModule(buffer, {});
print(module.main());
<commit_msg>use d8's readbuffer(), not read() to read file<commit_after>if (arguments.length != 1) {
  print('usage: d8 wasm.js -- <filename>');
  quit(0);
}

var buffer = readbuffer(arguments[0]);
var module = WASM.instantiateModule(buffer, {});
print(module.main());
<|endoftext|>


<commit_before>window.ModuleList = [
  ['Top Five','SSYT 2.0','v1.0.x'],
  ['Newest Member Today','SSYT 2.0','v1.0'],
  ['Topic Preview','SSYT 2.0','v1.0.x']
];
<commit_msg>Update release.js<commit_after>window.ModuleList = [
  ['Top Five','SSYT 2.0','25.01.2017','v1.0.x'],
  ['Newest Member Today','SSYT 2.0','25.01.2017','v1.0'],
  ['Topic Preview','SSYT 2.0','N/A','v1.0.x']
];
<|endoftext|>


<commit_before><commit_msg>Update ogario.v4.js<commit_after><|endoftext|>


<commit_before>/*global describe, it, before, beforeEach, after, afterEach */
var path = require('path');
var util = require('util');
var generator = require('yeoman-generator');
var helpers = require(path.join(path.dirname(require.resolve('yeoman-generator')), 'lib/test/helpers'));
var assert = require('assert');
var env = generator();

var insightStub = {
  track: function () {}
};

var yoyo = require('../yoyo');
var yo = function () {
  env.run('yo', {
    insight: insightStub
  });
};
env.register(path.join(__dirname, '../yoyo'), 'yo');

function Phoenix() {
  generator.Base.apply(this, arguments);
}
util.inherits(Phoenix, generator.Base);
env.registerStub(Phoenix, 'phoenix:app');

describe('yo yo', function () {
  afterEach(helpers.restore);

  it.skip('should find generators', function (cb) {
    helpers.stub(yoyo.prototype, 'findGenerators', cb);

    yo();
  });

  it.skip('should send the user to the home screen', function (cb) {
    helpers.stub(yoyo.prototype, 'home', cb);

    yo();
  });

  describe('home', function () {
    describe('prompts', function () {
      var choices = {
        generators: [],
        methods: []
      };

      before(function () {
        yoyo.prototype.pkgs = {
          phoenix: {
            version: '0.0.0',
            appGenerator: true,
            namespace: 'phoenix:app'
          }
        };
        helpers.stub(yoyo.prototype, 'findGenerators');
        helpers.stub(yoyo.prototype, 'prompt', function (prompts) {
          prompts[0].choices.forEach(function (choice) {
            if (choice.value && choice.value.method) {
              if (choice.value.method === '_initGenerator') {
                choices.generators.push(choice.value.args);
              } else {
                choices.methods.push(choice.value.method);
              }
            }
          });
        });

        yo();
      });

      it('should display installed generators', function () {
        assert.equal(choices.generators.length, 1);
        assert.ok(choices.generators.indexOf('phoenix:app') > -1);
      });

      it('should allow an option to exit', function () {
        assert.ok(choices.methods.indexOf('_noop') > -1);
      });
    });
  });

  describe('updateGenerators', function () {
    var pkgs = yoyo.prototype.pkgs;
    var updatedGenerators = [];
    var choices = [];
    var sentHome = false;

    beforeEach(function () {
      yoyo.prototype.pkgs = [{
        name: 'generator-unicorn'
      }, {
        name: 'generator-phoenix'
      }];

      yoyo.prototype.insight = insightStub;

      helpers.stub(yoyo.prototype, 'spawnCommand', function spawnCommand(cmd, args) {
        if (args) {
          updatedGenerators.push(args[args.length - 1]);
        }

        return {
          on: function (event, cb) {
            if (event === 'exit') {
              return cb();
            } else {
              return spawnCommand();
            }
          }
        };
      });

      helpers.stub(yoyo.prototype, 'home', function (opts) {
        sentHome = true;
      });

      helpers.stub(yoyo.prototype, 'prompt', function (prompts) {
        prompts[0].choices.forEach(function (choice) {
          choices.push(choice);
        });
        yoyo.prototype._updateGenerators(choices.map(function (choice) { return choice.name; }));
      });

      yoyo.prototype._promptToUpdateGenerators();
    });

    after(function () {
      yoyo.prototype.pkgs = pkgs;
    });

    it('should globally update selected generators', function () {
      assert.ok(updatedGenerators.indexOf('generator-unicorn') > -1);
      assert.ok(updatedGenerators.indexOf('generator-phoenix') > -1);
    });

    it('should return the user to the home screen', function () {
      assert.ok(sentHome);
    });
  });

  describe('initGenerator', function () {
    it('should .run() desired generator', function (done) {
      var fakeGenerator = 'generator-phoenix';

      helpers.stub(yoyo.prototype.env = {}, 'run', function (generator, done) {
        assert.equal(generator, fakeGenerator);
        done();
      });

      yoyo.prototype._initGenerator(fakeGenerator, done);
    });
  });

  describe('installGenerator', function () {
    describe('argument supplied', function () {
      var installedGenerator;
      var fakeGenerator = 'generator-phoenix';
      var options;

      before(function () {
        helpers.stub(yoyo.prototype, 'home', function (opts) {
          options = opts;
        });

        helpers.stub(yoyo.prototype, 'spawnCommand', function spawnCommand(cmd, args) {
          if (args) {
            installedGenerator = args[args.length - 1];
          }

          return {
            on: function (event, cb) {
              if (event === 'exit') {
                return cb();
              } else {
                return spawnCommand();
              }
            }
          };
        });

        yoyo.prototype._installGenerator(fakeGenerator);
      });

      it('should install a generator', function () {
        assert.equal(installedGenerator, fakeGenerator);
      });

      it('should send the user home with `refresh: true`', function () {
        assert.equal(options.refresh, true);
      });
    });

    describe('no argument supplied', function () {
      var prompted = false;
      var searchNpmCalled = false;

      before(function () {
        helpers.stub(yoyo.prototype, 'home');

        helpers.stub(yoyo.prototype, '_searchNpm', function () {
          searchNpmCalled = true;
        });

        helpers.stub(yoyo.prototype, 'prompt', function (prompts, callback) {
          prompted = true;
          callback();
        });

        yoyo.prototype._installGenerator();
      });

      it('should prompt for a search term if argument wasn\'t supplied', function () {
        assert.ok(prompted);
      });

      it('should search npm with the search term', function () {
        assert.ok(searchNpmCalled);
      });
    });
  });

  describe('findAllNpmGenerators', function () {
    var requestedUrl;
    var npmGeneratorsExpected = {
      'generator-phoenix': {
        adorable: true
      }
    };
    var searchTermExpected = 'phoenix';
    var searchTermActual;

    before(function () {
      helpers.stub(yoyo.prototype, 'request', function (url, cb) {
        requestedUrl = url;
        cb(null, null, JSON.stringify(npmGeneratorsExpected));
      });

      yo();
      yoyo.prototype._findAllNpmGenerators(searchTermExpected, function (term) {
        searchTermActual = term;
      });
    });

    it('should make request for the registry', function () {
      assert.ok(requestedUrl.indexOf('isaacs.iriscouch.com') > -1);
    });

    it('should parse and store the response as JSON', function () {
      assert.equal(JSON.stringify(yoyo.prototype.npmGenerators), JSON.stringify(npmGeneratorsExpected));
    });

    it('should return searched term to callback', function () {
      assert.equal(searchTermActual, searchTermExpected);
    });
  });

  describe('searchNpm', function () {
    var pkgs = yoyo.prototype.pkgs;
    var npmGenerators = yoyo.prototype.npmGenerators;

    var choices = [];

    var fakeResponse = {
      rows: [{
        key: [ null, 'generator-unicorn' ]
      }, {
        key: [ null, 'generator-phoenix' ]
      }, {
        key: [ null, 'generator-unicorn-sparkles' ]
      }]
    };

    beforeEach(function () {
      // Pretend we have generator-unicorn installed. I mean, why wouldn't we?
      yoyo.prototype.pkgs = { 'generator-unicorn': 'awesome' };

      yoyo.prototype.npmGenerators = fakeResponse;

      helpers.stub(yoyo.prototype, 'prompt', function (prompts, cb) {
        choices = [];
        prompts[0].choices.forEach(function (choice) {
          choices.push(choice.value);
        });
      });
    });

    after(function () {
      yoyo.prototype.npmGenerators = npmGenerators;
      yoyo.prototype.pkgs = pkgs;
    });

    it('should call `_findAllNpmGenerators` if it hasn\'t before', function () {
      var npmGenerators = yoyo.prototype.npmGenerators;
      yoyo.prototype.npmGenerators = null;

      var called = false;
      helpers.stub(yoyo.prototype, '_findAllNpmGenerators', function () {
        called = true;
      });

      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(called);
      yoyo.prototype.npmGenerators = npmGenerators;
    });

    it('should prompt user with generators that match the term', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'generator'
      });

      assert.ok(choices.indexOf('generator-phoenix') > -1);
      assert.ok(choices.indexOf('generator-unicorn-sparkles') > -1);
    });

    it('should not show already installed generators', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(choices.indexOf('generator-unicorn') === -1);
      assert.ok(choices.indexOf('generator-unicorn-sparkles') > -1);
    });

    it('should allow the user to search again', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(choices.indexOf('_installGenerator') > -1);
    });

    it('should allow the user to return home', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(choices.indexOf('home') > -1);
    });
  });

  describe('findHelp', function () {
    var choices;

    before(function () {
      helpers.stub(yoyo.prototype, 'prompt', function (prompts, callback) {
        choices = prompts[0].choices;
      });

      yoyo.prototype._findHelp();
    });

    it('should only allow URLs and existing methods', function () {
      choices.forEach(function (choice) {
        if (choice.value.method) {
          assert.ok(yoyo.prototype._.isFunction(yoyo.prototype[choice.value.method]));
        } else {
          assert.ok(choice.value.match(/^https*:\/\//));
        }
      });
    });
  });
});
<commit_msg>Fix async tests<commit_after>/*global describe, it, before, beforeEach, after, afterEach */
var path = require('path');
var util = require('util');
var generator = require('yeoman-generator');
var helpers = require(path.join(path.dirname(require.resolve('yeoman-generator')), 'lib/test/helpers'));
var assert = require('assert');
var env = generator();

var insightStub = {
  track: function () {}
};

var yoyo = require('../yoyo');
var yo = function () {
  env.run('yo', {
    insight: insightStub
  });
};
env.registerStub(yoyo, 'yo');

function Phoenix() {
  generator.Base.apply(this, arguments);
}
util.inherits(Phoenix, generator.Base);
env.registerStub(Phoenix, 'phoenix:app');

describe('yo yo', function () {
  afterEach(helpers.restore);

  it.skip('should find generators', function (cb) {
    helpers.stub(yoyo.prototype, 'findGenerators', cb);

    yo();
  });

  it.skip('should send the user to the home screen', function (cb) {
    helpers.stub(yoyo.prototype, 'home', cb);

    yo();
  });

  describe('home', function () {
    describe('prompts', function () {
      var choices = {
        generators: [],
        methods: []
      };

      before(function (cb) {
        yoyo.prototype.pkgs = {
          phoenix: {
            version: '0.0.0',
            appGenerator: true,
            namespace: 'phoenix:app'
          }
        };
        helpers.stub(yoyo.prototype, 'findGenerators');
        helpers.stub(yoyo.prototype, 'prompt', function (prompts) {
          prompts[0].choices.forEach(function (choice) {
            if (choice.value && choice.value.method) {
              if (choice.value.method === '_initGenerator') {
                choices.generators.push(choice.value.args);
              } else {
                choices.methods.push(choice.value.method);
              }
            }
          });
          cb();
        });

        yo();
      });

      it('should display installed generators', function () {
        assert.equal(choices.generators.length, 1);
        assert.ok(choices.generators.indexOf('phoenix:app') > -1);
      });

      it('should allow an option to exit', function () {
        assert.ok(choices.methods.indexOf('_noop') > -1);
      });
    });
  });

  describe('updateGenerators', function () {
    var pkgs = yoyo.prototype.pkgs;
    var updatedGenerators = [];
    var choices = [];
    var sentHome = false;

    beforeEach(function () {
      yoyo.prototype.pkgs = [{
        name: 'generator-unicorn'
      }, {
        name: 'generator-phoenix'
      }];

      yoyo.prototype.insight = insightStub;

      helpers.stub(yoyo.prototype, 'spawnCommand', function spawnCommand(cmd, args) {
        if (args) {
          updatedGenerators.push(args[args.length - 1]);
        }

        return {
          on: function (event, cb) {
            if (event === 'exit') {
              return cb();
            } else {
              return spawnCommand();
            }
          }
        };
      });

      helpers.stub(yoyo.prototype, 'home', function (opts) {
        sentHome = true;
      });

      helpers.stub(yoyo.prototype, 'prompt', function (prompts) {
        prompts[0].choices.forEach(function (choice) {
          choices.push(choice);
        });
        yoyo.prototype._updateGenerators(choices.map(function (choice) { return choice.name; }));
      });

      yoyo.prototype._promptToUpdateGenerators();
    });

    after(function () {
      yoyo.prototype.pkgs = pkgs;
    });

    it('should globally update selected generators', function () {
      assert.ok(updatedGenerators.indexOf('generator-unicorn') > -1);
      assert.ok(updatedGenerators.indexOf('generator-phoenix') > -1);
    });

    it('should return the user to the home screen', function () {
      assert.ok(sentHome);
    });
  });

  describe('initGenerator', function () {
    it('should .run() desired generator', function (done) {
      var fakeGenerator = 'generator-phoenix';

      helpers.stub(yoyo.prototype.env = {}, 'run', function (generator, done) {
        assert.equal(generator, fakeGenerator);
        done();
      });

      yoyo.prototype._initGenerator(fakeGenerator, done);
    });
  });

  describe('installGenerator', function () {
    describe('argument supplied', function () {
      var installedGenerator;
      var fakeGenerator = 'generator-phoenix';
      var options;

      before(function () {
        helpers.stub(yoyo.prototype, 'home', function (opts) {
          options = opts;
        });

        helpers.stub(yoyo.prototype, 'spawnCommand', function spawnCommand(cmd, args) {
          if (args) {
            installedGenerator = args[args.length - 1];
          }

          return {
            on: function (event, cb) {
              if (event === 'exit') {
                return cb();
              } else {
                return spawnCommand();
              }
            }
          };
        });

        yoyo.prototype._installGenerator(fakeGenerator);
      });

      it('should install a generator', function () {
        assert.equal(installedGenerator, fakeGenerator);
      });

      it('should send the user home with `refresh: true`', function () {
        assert.equal(options.refresh, true);
      });
    });

    describe('no argument supplied', function () {
      var prompted = false;
      var searchNpmCalled = false;

      before(function () {
        helpers.stub(yoyo.prototype, 'home');

        helpers.stub(yoyo.prototype, '_searchNpm', function () {
          searchNpmCalled = true;
        });

        helpers.stub(yoyo.prototype, 'prompt', function (prompts, callback) {
          prompted = true;
          callback();
        });

        yoyo.prototype._installGenerator();
      });

      it('should prompt for a search term if argument wasn\'t supplied', function () {
        assert.ok(prompted);
      });

      it('should search npm with the search term', function () {
        assert.ok(searchNpmCalled);
      });
    });
  });

  describe('findAllNpmGenerators', function () {
    var requestedUrl;
    var npmGeneratorsExpected = {
      'generator-phoenix': {
        adorable: true
      }
    };
    var searchTermExpected = 'phoenix';
    var searchTermActual;

    before(function () {
      helpers.stub(yoyo.prototype, 'request', function (url, cb) {
        requestedUrl = url;
        cb(null, null, JSON.stringify(npmGeneratorsExpected));
      });

      yo();
      yoyo.prototype._findAllNpmGenerators(searchTermExpected, function (term) {
        searchTermActual = term;
      });
    });

    it('should make request for the registry', function () {
      assert.ok(requestedUrl.indexOf('isaacs.iriscouch.com') > -1);
    });

    it('should parse and store the response as JSON', function () {
      assert.equal(JSON.stringify(yoyo.prototype.npmGenerators), JSON.stringify(npmGeneratorsExpected));
    });

    it('should return searched term to callback', function () {
      assert.equal(searchTermActual, searchTermExpected);
    });
  });

  describe('searchNpm', function () {
    var pkgs = yoyo.prototype.pkgs;
    var npmGenerators = yoyo.prototype.npmGenerators;

    var choices = [];

    var fakeResponse = {
      rows: [{
        key: [ null, 'generator-unicorn' ]
      }, {
        key: [ null, 'generator-phoenix' ]
      }, {
        key: [ null, 'generator-unicorn-sparkles' ]
      }]
    };

    beforeEach(function () {
      // Pretend we have generator-unicorn installed. I mean, why wouldn't we?
      yoyo.prototype.pkgs = { 'generator-unicorn': 'awesome' };

      yoyo.prototype.npmGenerators = fakeResponse;

      helpers.stub(yoyo.prototype, 'prompt', function (prompts, cb) {
        choices = [];
        prompts[0].choices.forEach(function (choice) {
          choices.push(choice.value);
        });
      });
    });

    after(function () {
      yoyo.prototype.npmGenerators = npmGenerators;
      yoyo.prototype.pkgs = pkgs;
    });

    it('should call `_findAllNpmGenerators` if it hasn\'t before', function () {
      var npmGenerators = yoyo.prototype.npmGenerators;
      yoyo.prototype.npmGenerators = null;

      var called = false;
      helpers.stub(yoyo.prototype, '_findAllNpmGenerators', function () {
        called = true;
      });

      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(called);
      yoyo.prototype.npmGenerators = npmGenerators;
    });

    it('should prompt user with generators that match the term', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'generator'
      });

      assert.ok(choices.indexOf('generator-phoenix') > -1);
      assert.ok(choices.indexOf('generator-unicorn-sparkles') > -1);
    });

    it('should not show already installed generators', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(choices.indexOf('generator-unicorn') === -1);
      assert.ok(choices.indexOf('generator-unicorn-sparkles') > -1);
    });

    it('should allow the user to search again', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(choices.indexOf('_installGenerator') > -1);
    });

    it('should allow the user to return home', function () {
      yoyo.prototype._searchNpm({
        searchTerm: 'unicorn'
      });

      assert.ok(choices.indexOf('home') > -1);
    });
  });

  describe('findHelp', function () {
    var choices;

    before(function () {
      helpers.stub(yoyo.prototype, 'prompt', function (prompts, callback) {
        choices = prompts[0].choices;
      });

      yoyo.prototype._findHelp();
    });

    it('should only allow URLs and existing methods', function () {
      choices.forEach(function (choice) {
        if (choice.value.method) {
          assert.ok(yoyo.prototype._.isFunction(yoyo.prototype[choice.value.method]));
        } else {
          assert.ok(choice.value.match(/^https*:\/\//));
        }
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var OnlineSVM = require( './../lib' );
var x1;
var x2;
var y;
var i;

// Create model:
var model = new OnlineSVM({
	'lambda': 1e-4,
	'loss': 'leastSquares',
	'intercept': true
});

// Data comes in...
for ( i = 0; i < 100000; i++ ) {
	x1 = Math.random();
	x2 = Math.random();
	y = 3.0 * x1 + -3.0 * x2 + 2.0;
	model.update( y, [ x1, x2 ] );
}

// Extract model coefficients:
console.log( model.coefs );

// Predict new observations:
console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.1] ), 0.9, 0.1 );
console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.1,0.9] ), 0.1, 0.9 );
console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.9] ), 0.9, 0.9 );
<commit_msg>Update module name in example code<commit_after>'use strict';

var OnlineSGDRegression = require( './../lib' );
var x1;
var x2;
var y;
var i;

// Create model:
var model = new OnlineSGDRegression({
	'lambda': 1e-4,
	'loss': 'leastSquares',
	'intercept': true
});

// Data comes in...
for ( i = 0; i < 100000; i++ ) {
	x1 = Math.random();
	x2 = Math.random();
	y = 3.0 * x1 + -3.0 * x2 + 2.0;
	model.update( y, [ x1, x2 ] );
}

// Extract model coefficients:
console.log( model.coefs );

// Predict new observations:
console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.1] ), 0.9, 0.1 );
console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.1,0.9] ), 0.1, 0.9 );
console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.9] ), 0.9, 0.9 );
<|endoftext|>


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

    var removeSpace = (/\s*/g),
        trimSpace = (/^\s*|\s*$/g),
        splitSpace = (/\s+/);
    // generate a short, numeric hash of a string
    function okhash(x) {
        if (!x || !x.length) return 0;
        for (var i = 0, h = 0; i < x.length; i++) {
            h = ((h << 5) - h) + x.charCodeAt(i) | 0;
        } return h;
    }
    // all Y children of X
    function get(x, y) { return x.getElementsByTagName(y); }
    function attr(x, y) { return x.getAttribute(y); }
    function attrf(x, y) { return parseFloat(attr(x, y)); }
    // one Y child of X, if any, otherwise null
    function get1(x, y) { var n = get(x, y); return n.length ? n[0] : null; }
    // https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize
    function norm(el) { if (el.normalize) { el.normalize(); } return el; }
    // cast array x into numbers
    function numarray(x) {
        for (var j = 0, o = []; j < x.length; j++) o[j] = parseFloat(x[j]);
        return o;
    }
    function clean(x) {
        var o = {};
        for (var i in x) if (x[i]) o[i] = x[i];
        return o;
    }
    // get the content of a text node, if any
    function nodeVal(x) { if (x) {norm(x);} return x && x.firstChild && x.firstChild.nodeValue; }
    // get one coordinate from a coordinate array, if any
    function coord1(v) { return numarray(v.replace(removeSpace, '').split(',')); }
    // get all coordinates from a coordinate array as [[],[]]
    function coord(v) {
        var coords = v.replace(trimSpace, '').split(splitSpace),
            o = [];
        for (var i = 0; i < coords.length; i++) {
            o.push(coord1(coords[i]));
        }
        return o;
    }
    function coordPair(x) { return [attrf(x, 'lon'), attrf(x, 'lat')]; }

    // create a new feature collection parent object
    function fc() {
        return {
            type: 'FeatureCollection',
            features: []
        };
    }

    var serializer;
    if (typeof XMLSerializer !== 'undefined') {
        serializer = new XMLSerializer();
    } else if (typeof require !== 'undefined') {
        serializer = new (require('xmldom').XMLSerializer)();
    }
    function xml2str(str) { return serializer.serializeToString(str); }

    var t = {
        kml: function(doc, o) {
            o = o || {};

            var gj = fc(),
                // styleindex keeps track of hashed styles in order to match features
                styleIndex = {},
                // atomic geospatial types supported by KML - MultiGeometry is
                // handled separately
                geotypes = ['Polygon', 'LineString', 'Point', 'Track'],
                // all root placemarks in the file
                placemarks = get(doc, 'Placemark'),
                styles = get(doc, 'Style');

            for (var k = 0; k < styles.length; k++) {
                styleIndex['#' + attr(styles[k], 'id')] = okhash(xml2str(styles[k])).toString(16);
            }
            for (var j = 0; j < placemarks.length; j++) {
                gj.features = gj.features.concat(getPlacemark(placemarks[j]));
            }
            function gxCoord(v) { return numarray(v.split(' ')); }
            function gxCoords(root) {
                var elems = get(root, 'coord', 'gx'), coords = [];
                for (var i = 0; i < elems.length; i++) coords.push(gxCoord(nodeVal(elems[i])));
                return coords;
            }
            function getGeometry(root) {
                var geomNode, geomNodes, i, j, k, geoms = [];
                if (get1(root, 'MultiGeometry')) return getGeometry(get1(root, 'MultiGeometry'));
                if (get1(root, 'MultiTrack')) return getGeometry(get1(root, 'MultiTrack'));
                for (i = 0; i < geotypes.length; i++) {
                    geomNodes = get(root, geotypes[i]);
                    if (geomNodes) {
                        for (j = 0; j < geomNodes.length; j++) {
                            geomNode = geomNodes[j];
                            if (geotypes[i] == 'Point') {
                                geoms.push({
                                    type: 'Point',
                                    coordinates: coord1(nodeVal(get1(geomNode, 'coordinates')))
                                });
                            } else if (geotypes[i] == 'LineString') {
                                geoms.push({
                                    type: 'LineString',
                                    coordinates: coord(nodeVal(get1(geomNode, 'coordinates')))
                                });
                            } else if (geotypes[i] == 'Polygon') {
                                var rings = get(geomNode, 'LinearRing'),
                                    coords = [];
                                for (k = 0; k < rings.length; k++) {
                                    coords.push(coord(nodeVal(get1(rings[k], 'coordinates'))));
                                }
                                geoms.push({
                                    type: 'Polygon',
                                    coordinates: coords
                                });
                            } else if (geotypes[i] == 'Track') {
                                geoms.push({
                                    type: 'LineString',
                                    coordinates: gxCoords(geomNode)
                                });
                            }
                        }
                    }
                }
                return geoms;
            }
            function getPlacemark(root) {
                var geoms = getGeometry(root), i, properties = {},
                    name = nodeVal(get1(root, 'name')),
                    styleUrl = nodeVal(get1(root, 'styleUrl')),
                    description = nodeVal(get1(root, 'description')),
                    extendedData = get1(root, 'ExtendedData');

                if (!geoms.length) return [];
                if (name) properties.name = name;
                if (styleUrl && styleIndex[styleUrl]) {
                    properties.styleUrl = styleUrl;
                    properties.styleHash = styleIndex[styleUrl];
                }
                if (description) properties.description = description;
                if (extendedData) {
                    var datas = get(extendedData, 'Data'),
                        simpleDatas = get(extendedData, 'SimpleData');

                    for (i = 0; i < datas.length; i++) {
                        properties[datas[i].getAttribute('name')] = nodeVal(get1(datas[i], 'value'));
                    }
                    for (i = 0; i < simpleDatas.length; i++) {
                        properties[simpleDatas[i].getAttribute('name')] = nodeVal(simpleDatas[i]);
                    }
                }
                return [{
                    type: 'Feature',
                    geometry: (geoms.length === 1) ? geoms[0] : {
                        type: 'GeometryCollection',
                        geometries: geoms
                    },
                    properties: properties
                }];
            }
            return gj;
        },
        gpx: function(doc, o) {
            var i,
                tracks = get(doc, 'trk'),
                routes = get(doc, 'rte'),
                waypoints = get(doc, 'wpt'),
                // a feature collection
                gj = fc();
            for (i = 0; i < tracks.length; i++) {
                gj.features.push(getLinestring(tracks[i], 'trkpt'));
            }
            for (i = 0; i < routes.length; i++) {
                gj.features.push(getLinestring(routes[i], 'rtept'));
            }
            for (i = 0; i < waypoints.length; i++) {
                gj.features.push(getPoint(waypoints[i]));
            }
            function getLinestring(node, pointname) {
                var j, pts = get(node, pointname), line = [];
                for (j = 0; j < pts.length; j++) {
                    line.push(coordPair(pts[j]));
                }
                return {
                    type: 'Feature',
                    properties: getProperties(node),
                    geometry: {
                        type: 'LineString',
                        coordinates: line
                    }
                };
            }
            function getPoint(node) {
                var prop = getProperties(node);
                prop.ele = nodeVal(get1(node, 'ele'));
                prop.sym = nodeVal(get1(node, 'sym'));
                return {
                    type: 'Feature',
                    properties: prop,
                    geometry: {
                        type: 'Point',
                        coordinates: coordPair(node)
                    }
                };
            }
            function getProperties(node) {
                var meta = ['name', 'desc', 'author', 'copyright', 'link',
                            'time', 'keywords'],
                    prop = {},
                    k;
                for (k = 0; k < meta.length; k++) {
                    prop[meta[k]] = nodeVal(get1(node, meta[k]));
                }
                return clean(prop);
            }
            return gj;
        }
    };
    return t;
})();

if (typeof module !== 'undefined') module.exports = toGeoJSON;
<commit_msg>togeojson.js: Fix bug with parsing google KML files"<commit_after>toGeoJSON = (function() {
    'use strict';

    var removeSpace = (/\s*/g),
        trimSpace = (/^\s*|\s*$/g),
        splitSpace = (/\s+/);
    // generate a short, numeric hash of a string
    function okhash(x) {
        if (!x || !x.length) return 0;
        for (var i = 0, h = 0; i < x.length; i++) {
            h = ((h << 5) - h) + x.charCodeAt(i) | 0;
        } return h;
    }
    // all Y children of X
    function get(x, y) { return x.getElementsByTagName(y); }
    function attr(x, y) { return x.getAttribute(y); }
    function attrf(x, y) { return parseFloat(attr(x, y)); }
    // one Y child of X, if any, otherwise null
    function get1(x, y) { var n = get(x, y); return n.length ? n[0] : null; }
    // https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize
    function norm(el) { if (el.normalize) { el.normalize(); } return el; }
    // cast array x into numbers
    function numarray(x) {
        for (var j = 0, o = []; j < x.length; j++) o[j] = parseFloat(x[j]);
        return o;
    }
    function clean(x) {
        var o = {};
        for (var i in x) if (x[i]) o[i] = x[i];
        return o;
    }
    // get the content of a text node, if any
    function nodeVal(x) { if (x) {norm(x);} return x && x.firstChild && x.firstChild.nodeValue; }
    // get one coordinate from a coordinate array, if any
    function coord1(v) { return numarray(v.replace(removeSpace, '').split(',')); }
    // get all coordinates from a coordinate array as [[],[]]
    function coord(v) {
        var coords = v.replace(trimSpace, '').split(splitSpace),
            o = [];
        for (var i = 0; i < coords.length; i++) {
            o.push(coord1(coords[i]));
        }
        return o;
    }
    function coordPair(x) { return [attrf(x, 'lon'), attrf(x, 'lat')]; }

    // create a new feature collection parent object
    function fc() {
        return {
            type: 'FeatureCollection',
            features: []
        };
    }

    var serializer;
    if (typeof XMLSerializer !== 'undefined') {
        serializer = new XMLSerializer();
    } else if (typeof require !== 'undefined') {
        serializer = new (require('xmldom').XMLSerializer)();
    }
    function xml2str(str) { return serializer.serializeToString(str); }

    var t = {
        kml: function(doc, o) {
            o = o || {};

            var gj = fc(),
                // styleindex keeps track of hashed styles in order to match features
                styleIndex = {},
                // atomic geospatial types supported by KML - MultiGeometry is
                // handled separately
                geotypes = ['Polygon', 'LineString', 'Point', 'Track'],
                // all root placemarks in the file
                placemarks = get(doc, 'Placemark'),
                styles = get(doc, 'Style');

            for (var k = 0; k < styles.length; k++) {
                styleIndex['#' + attr(styles[k], 'id')] = okhash(xml2str(styles[k])).toString(16);
            }
            for (var j = 0; j < placemarks.length; j++) {
                gj.features = gj.features.concat(getPlacemark(placemarks[j]));
            }
            function gxCoord(v) { return numarray(v.split(' ')); }
            function gxCoords(root) {
                var elems = get(root, 'coord', 'gx'), coords = [];
                for (var i = 0; i < elems.length; i++) coords.push(gxCoord(nodeVal(elems[i])));
                return coords;
            }
            function getGeometry(root) {
                var geomNode, geomNodes, i, j, k, geoms = [];
                if (get1(root, 'MultiGeometry')) return getGeometry(get1(root, 'MultiGeometry'));
                if (get1(root, 'MultiTrack')) return getGeometry(get1(root, 'MultiTrack'));
                for (i = 0; i < geotypes.length; i++) {
                    geomNodes = get(root, geotypes[i]);
                    if (geomNodes) {
                        for (j = 0; j < geomNodes.length; j++) {
                            geomNode = geomNodes[j];
                            if (geotypes[i] == 'Point') {
                                if(nodeVal(get1(geomNode, 'coordinates')) === null)
                                    continue;
                                geoms.push({
                                    type: 'Point',
                                    coordinates: coord1(nodeVal(get1(geomNode, 'coordinates')))
                                });
                            } else if (geotypes[i] == 'LineString') {
                                geoms.push({
                                    type: 'LineString',
                                    coordinates: coord(nodeVal(get1(geomNode, 'coordinates')))
                                });
                            } else if (geotypes[i] == 'Polygon') {
                                var rings = get(geomNode, 'LinearRing'),
                                    coords = [];
                                for (k = 0; k < rings.length; k++) {
                                    coords.push(coord(nodeVal(get1(rings[k], 'coordinates'))));
                                }
                                geoms.push({
                                    type: 'Polygon',
                                    coordinates: coords
                                });
                            } else if (geotypes[i] == 'Track') {
                                geoms.push({
                                    type: 'LineString',
                                    coordinates: gxCoords(geomNode)
                                });
                            }
                        }
                    }
                }
                return geoms;
            }
            function getPlacemark(root) {
                var geoms = getGeometry(root), i, properties = {},
                    name = nodeVal(get1(root, 'name')),
                    styleUrl = nodeVal(get1(root, 'styleUrl')),
                    description = nodeVal(get1(root, 'description')),
                    extendedData = get1(root, 'ExtendedData');

                if (!geoms.length) return [];
                if (name) properties.name = name;
                if (styleUrl && styleIndex[styleUrl]) {
                    properties.styleUrl = styleUrl;
                    properties.styleHash = styleIndex[styleUrl];
                }
                if (description) properties.description = description;
                if (extendedData) {
                    var datas = get(extendedData, 'Data'),
                        simpleDatas = get(extendedData, 'SimpleData');

                    for (i = 0; i < datas.length; i++) {
                        properties[datas[i].getAttribute('name')] = nodeVal(get1(datas[i], 'value'));
                    }
                    for (i = 0; i < simpleDatas.length; i++) {
                        properties[simpleDatas[i].getAttribute('name')] = nodeVal(simpleDatas[i]);
                    }
                }
                return [{
                    type: 'Feature',
                    geometry: (geoms.length === 1) ? geoms[0] : {
                        type: 'GeometryCollection',
                        geometries: geoms
                    },
                    properties: properties
                }];
            }
            return gj;
        },
        gpx: function(doc, o) {
            var i,
                tracks = get(doc, 'trk'),
                routes = get(doc, 'rte'),
                waypoints = get(doc, 'wpt'),
                // a feature collection
                gj = fc();
            for (i = 0; i < tracks.length; i++) {
                gj.features.push(getLinestring(tracks[i], 'trkpt'));
            }
            for (i = 0; i < routes.length; i++) {
                gj.features.push(getLinestring(routes[i], 'rtept'));
            }
            for (i = 0; i < waypoints.length; i++) {
                gj.features.push(getPoint(waypoints[i]));
            }
            function getLinestring(node, pointname) {
                var j, pts = get(node, pointname), line = [];
                for (j = 0; j < pts.length; j++) {
                    line.push(coordPair(pts[j]));
                }
                return {
                    type: 'Feature',
                    properties: getProperties(node),
                    geometry: {
                        type: 'LineString',
                        coordinates: line
                    }
                };
            }
            function getPoint(node) {
                var prop = getProperties(node);
                prop.ele = nodeVal(get1(node, 'ele'));
                prop.sym = nodeVal(get1(node, 'sym'));
                return {
                    type: 'Feature',
                    properties: prop,
                    geometry: {
                        type: 'Point',
                        coordinates: coordPair(node)
                    }
                };
            }
            function getProperties(node) {
                var meta = ['name', 'desc', 'author', 'copyright', 'link',
                            'time', 'keywords'],
                    prop = {},
                    k;
                for (k = 0; k < meta.length; k++) {
                    prop[meta[k]] = nodeVal(get1(node, meta[k]));
                }
                return clean(prop);
            }
            return gj;
        }
    };
    return t;
})();

if (typeof module !== 'undefined') module.exports = toGeoJSON;
<|endoftext|>


<commit_before>window.testmator = (function () {
  'use strict';

  // Backbone like extend function.
  var extend = function (protoProps, staticProps) {
    var parent = this;
    var child = function () {
      return parent.apply(this, arguments);
    };

    // Inherit static properties.
    _.extend(child, parent, staticProps);

    var Surrogate = function () {
      this.constructor = child;
    };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate();

    // Inherit prototype properties.
    if (protoProps) {
      _.extend(child.prototype, protoProps);
    }

    return child;
  };

  var PageObject = function (options) {
    var el = (options && options.el) || options;
    if (_.isFunction(el)) {
      el = el();
    }
    // '#hoge' -> $('#hoge')
    if (_.isString(el)) {
      el = $(el);
    }
    // view = new Backbone.View({el: '#hoge'});
    // el = view.el
    if (el && el.el) {
      el = el.el;
    }

    this.$el = (el instanceof $) ? el : $(el);
    this.el = this.$el[0];

    this.parent = options && options.parent;
  };

  _.extend(PageObject, {
    extend: extend
  });

  _.extend(PageObject.prototype, {
    $: function () {
      return this.$el.find.apply(this.$el, arguments);
    },
    click: function () {
      this.$.apply(this, arguments).trigger('click');
    },
    switchParent: function () {
      return this.parent;
    }
  });

  return _.extend({}, {
    PageObject: PageObject
  });
})();
<commit_msg>Add Automator object.<commit_after>window.testmator = (function () {
  'use strict';

  // Backbone like extend function.
  var extend = function (protoProps, staticProps) {
    var parent = this;
    var child = function () {
      return parent.apply(this, arguments);
    };

    // Inherit static properties.
    _.extend(child, parent, staticProps);

    var Surrogate = function () {
      this.constructor = child;
    };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate();

    // Inherit prototype properties.
    if (protoProps) {
      _.extend(child.prototype, protoProps);
    }

    return child;
  };

  var PageObject = function (options) {
    var el = (options && options.el) || options;
    if (_.isFunction(el)) {
      el = el();
    }
    // '#hoge' -> $('#hoge')
    if (_.isString(el)) {
      el = $(el);
    }
    // view = new Backbone.View({el: '#hoge'});
    // el = view.el
    if (el && el.el) {
      el = el.el;
    }

    this.$el = (el instanceof $) ? el : $(el);
    this.el = this.$el[0];

    this.parent = options && options.parent;
  };

  _.extend(PageObject, {
    extend: extend
  });

  _.extend(PageObject.prototype, {
    $: function () {
      return this.$el.find.apply(this.$el, arguments);
    },
    click: function () {
      this.$.apply(this, arguments).trigger('click');
    },
    switchParent: function () {
      return this.parent;
    }
  });

  // Convert from Promise to Automator object.
  var convertToAutomator = function (promise, page) {
    var then = function (filter) {
      return promise.then(filter);
    };

    var wrapFilter = function (filter) {
      return function (target) {
        var result = filter(target);

        return (result && result.action && promise) || result || page;
      };
    };

    var toAutomator = function (filter) {
      return convertToAutomator(then(wrapFilter(filter)), page);
    };

    return {
      action: function (filter) {
        return toAutomator(filter);
      },
      scope: function (filter) {
        return toAutomator(filter);
      },
      test: function (filter) {
        return toAutomator(filter);
      },
      done: _.bind(promise.done, promise)
    };
  };

  // Convert Automator object.
  var automator = function (page) {
    var promise = $.Deferred().resolve(page).promise();

    return convertToAutomator(promise, page);
  };

  var testmator = automator;

  return _.extend(testmator, {
    PageObject: PageObject,
    automator: automator
  });
})();
<|endoftext|>


<commit_before>import * as React from "react";
import { Navigation } from "./Navigation";

/**
 * Main Navigation Component
 */
export const Header = () => {
  const TITLE = "LLVM Build View";

  return (

      <Wrapper>
        {TITLE}
      </Wrapper>
      <Navigation/>

  );
}
<commit_msg>Wrap Navigation, Add className to header element<commit_after>import * as React from "react";
import { Navigation } from "./Navigation";

/**
 * Main Navigation Component
 */
export const Header = () => {
  const TITLE = "LLVM Build View";

  return (

      <Wrapper>
        {TITLE}
      </Wrapper>
      <Wrapper>
        <Navigation/>
      </Wrapper>

  );
}
<|endoftext|>


<commit_before>// eslint-disable-next-line ember/no-observers
import { observer } from '@ember/object';
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import prerelease from 'semver/functions/prerelease';

import ajax from '../../utils/ajax';

export default Route.extend({
  session: service(),

  flashMessages: service(),

  // eslint-disable-next-line ember/no-observers
  refreshAfterLogin: observer('session.isLoggedIn', function () {
    this.refresh();
  }),

  async model(params) {
    const requestedVersion = params.version_num === 'all' ? '' : params.version_num;
    const crate = this.modelFor('crate');
    const controller = this.controllerFor(this.routeName);
    const maxVersion = crate.get('max_version');

    const isUnstableVersion = version => !!prerelease(version);

    const fetchCrateDocumentation = () => {
      if (!crate.get('documentation') || crate.get('documentation').substr(0, 16) === 'https://docs.rs/') {
        let crateName = crate.get('name');
        let crateVersion = params.version_num;
        ajax(`https://docs.rs/crate/${crateName}/${crateVersion}/builds.json`, { mode: 'cors' }).then(r => {
          if (r.length > 0 && r[0].build_status === true) {
            crate.set('documentation', `https://docs.rs/${crateName}/${crateVersion}/`);
          }
        });
      }
    };

    // Fallback to the crate's last stable version
    // If `max_version` is `0.0.0` then all versions have been yanked
    if (!requestedVersion && maxVersion !== '0.0.0') {
      if (isUnstableVersion(maxVersion)) {
        crate
          .get('versions')
          .then(versions => {
            const latestStableVersion = versions.find(version => {
              // Find the latest version that is stable AND not-yanked.
              if (!isUnstableVersion(version.get('num')) && !version.get('yanked')) {
                return version;
              }
            });

            if (latestStableVersion == null) {
              // Cannot find any version that is stable AND not-yanked.
              // The fact that "maxVersion" itself cannot be found means that
              // we have to fall back to the latest one that is unstable....
              const latestUnyankedVersion = versions.find(version => {
                // Find the latest version that is stable AND not-yanked.
                if (!version.get('yanked')) {
                  return version;
                }
              });

              if (latestStableVersion == null) {
                // There's not even any unyanked version...
                params.version_num = maxVersion;
              } else {
                params.version_num = latestUnyankedVersion;
              }
            } else {
              params.version_num = latestStableVersion.get('num');
            }
          })
          .then(fetchCrateDocumentation);
      } else {
        params.version_num = maxVersion;
        fetchCrateDocumentation();
      }
    } else {
      fetchCrateDocumentation();
    }

    controller.set('crate', crate);
    controller.set('requestedVersion', requestedVersion);

    // Find version model
    let versions = await crate.get('versions');

    const version = versions.find(version => version.get('num') === params.version_num);
    if (params.version_num && !version) {
      this.flashMessages.queue(`Version '${params.version_num}' of crate '${crate.get('name')}' does not exist`);
    }

    return version || versions.find(version => version.get('num') === maxVersion) || versions.objectAt(0);
  },

  setupController(controller) {
    this._super(...arguments);
    controller.loadReadmeTask.perform();
  },

  serialize(model) {
    let version_num = model.get('num');
    return { version_num };
  },
});
<commit_msg>crate.version: Remove obsolete `refreshAfterLogin` observer<commit_after>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import prerelease from 'semver/functions/prerelease';

import ajax from '../../utils/ajax';

export default Route.extend({
  flashMessages: service(),

  async model(params) {
    const requestedVersion = params.version_num === 'all' ? '' : params.version_num;
    const crate = this.modelFor('crate');
    const controller = this.controllerFor(this.routeName);
    const maxVersion = crate.get('max_version');

    const isUnstableVersion = version => !!prerelease(version);

    const fetchCrateDocumentation = () => {
      if (!crate.get('documentation') || crate.get('documentation').substr(0, 16) === 'https://docs.rs/') {
        let crateName = crate.get('name');
        let crateVersion = params.version_num;
        ajax(`https://docs.rs/crate/${crateName}/${crateVersion}/builds.json`, { mode: 'cors' }).then(r => {
          if (r.length > 0 && r[0].build_status === true) {
            crate.set('documentation', `https://docs.rs/${crateName}/${crateVersion}/`);
          }
        });
      }
    };

    // Fallback to the crate's last stable version
    // If `max_version` is `0.0.0` then all versions have been yanked
    if (!requestedVersion && maxVersion !== '0.0.0') {
      if (isUnstableVersion(maxVersion)) {
        crate
          .get('versions')
          .then(versions => {
            const latestStableVersion = versions.find(version => {
              // Find the latest version that is stable AND not-yanked.
              if (!isUnstableVersion(version.get('num')) && !version.get('yanked')) {
                return version;
              }
            });

            if (latestStableVersion == null) {
              // Cannot find any version that is stable AND not-yanked.
              // The fact that "maxVersion" itself cannot be found means that
              // we have to fall back to the latest one that is unstable....
              const latestUnyankedVersion = versions.find(version => {
                // Find the latest version that is stable AND not-yanked.
                if (!version.get('yanked')) {
                  return version;
                }
              });

              if (latestStableVersion == null) {
                // There's not even any unyanked version...
                params.version_num = maxVersion;
              } else {
                params.version_num = latestUnyankedVersion;
              }
            } else {
              params.version_num = latestStableVersion.get('num');
            }
          })
          .then(fetchCrateDocumentation);
      } else {
        params.version_num = maxVersion;
        fetchCrateDocumentation();
      }
    } else {
      fetchCrateDocumentation();
    }

    controller.set('crate', crate);
    controller.set('requestedVersion', requestedVersion);

    // Find version model
    let versions = await crate.get('versions');

    const version = versions.find(version => version.get('num') === params.version_num);
    if (params.version_num && !version) {
      this.flashMessages.queue(`Version '${params.version_num}' of crate '${crate.get('name')}' does not exist`);
    }

    return version || versions.find(version => version.get('num') === maxVersion) || versions.objectAt(0);
  },

  setupController(controller) {
    this._super(...arguments);
    controller.loadReadmeTask.perform();
  },

  serialize(model) {
    let version_num = model.get('num');
    return { version_num };
  },
});
<|endoftext|>


<commit_before>/*
    GNOME Shell extensions repository
    Copyright (C) 2011-2012  Jasper St. Pierre <jstpierre@mecheye.net>
    Copyright (C) 2016-2017  Yuri Konotopov <ykonotopov@gnome.org>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 */

define(['jquery', 'messages', 'dbus!_', 'extensionUtils', 'templates', 'paginator', 'switch'],
	function ($, messages, dbusProxy, extensionUtils, templates) {
		"use strict";

		var ExtensionState = extensionUtils.ExtensionState;

		$.fn.buildShellVersionsInfo = function () {
			return this.each(function () {
				var $table = $(this);
				var $tbody = $table.find('tbody');
				var $extension = $table.parents('.extension');

				$tbody.children().remove();

				var svm = $extension.data('svm');
				for (var version in svm)
				{
					if (!svm.hasOwnProperty(version))
					{
						continue;
					}

					var vpk = extensionUtils.grabProperExtensionVersion(svm, version);
					var $tr = $('<tr>').appendTo($tbody);
					$('<td>').append($('<code>').text(version)).appendTo($tr);
					$('<td>').text(vpk.version).appendTo($tr);
				}
			});
		};

		// While technically we shouldn't have mismatched API versions,
		// the plugin doesn't check whether the Shell matches, so if someone
		// is running with an old Shell version but a newer plugin, error out.
		if (dbusProxy.IsDummy)
		{
			// We don't have a proper DBus proxy -- it's probably an old
			// version of GNOME3 or the Shell.
			messages.addError(templates.get('messages/dummy_proxy')());

			$.fn.addExtensionSwitch = function () {
				// Don't show our switches -- CSS styles define a clickable
				// area even with no content.
				return this.find('.switch').hide();
			};

			$.fn.addLocalExtensions = function () {
				return this.append(templates.get('messages/cannot_list_local')());
			};

			$.fn.fillInErrors = function () {
				var $textarea = this.find('textarea[name=error]');
				var $hidden = this.find('input:hidden[name=has_errors]');
				$textarea.text(templates.get('messages/cannot_list_errors')()).addClass('no-errors').attr('disabled', 'disabled');
				$hidden.val('');
				return this;
			};

			$.fn.grayOutIfOutOfDate = function () {
				return this;
			};

			return;
		}

		// uuid => elem
		var elems = {};

		function extensionStateChanged(uuid, newState) {
			if (elems[uuid] !== undefined)
			{
				elems[uuid].trigger('state-changed', newState);
			}
		}

		function extensionTypeChanged(uuid, newType) {
			if (elems[uuid] !== undefined)
			{
				if(elems[uuid].data('type') != newType)
				{
					elems[uuid].trigger('type-changed', newState);
				}
			}
		}

		dbusProxy.extensionStateChangedHandler = extensionStateChanged;

		dbusProxy.shellRestartHandler = function () {
			dbusProxy.ListExtensions().then(function (extensions) {
				$.each(extensions, function () {
					extensionStateChanged(this.uuid, this.state);
					extensionTypeChanged(this.uuid, this.type);
				});
			});
		};

		function addExtensionSwitch(uuid, $elem, meta) {
			var $switch = $elem.find('.switch');
			var _state;
			if (meta && meta.state)
			{
				_state = meta.state;
			}
			else
			{
				_state = ExtensionState.UNINSTALLED;
			}

			$elem.find('.configure-button').on('click', function () {
				dbusProxy.LaunchExtensionPrefs(uuid);
			});

			$elem.find('.upgrade-button').on('click', function () {
				function installExtension() {
					dbusProxy.InstallExtension(uuid).then(function (result) {
						if (result === 'cancelled')
						{
							// WELP. We can't really do anything except leave the
							// thing uninstalled.
							$switch.switchify('activate', false);
						}
						// GNOME Shell bug https://bugzilla.gnome.org/show_bug.cgi?id=777544
						else if (['s', 'successful'].indexOf(result) != -1)
						{
							// It should always became "per user" extension if installed from repository.
							$elem.trigger('type-changed', extensionUtils.ExtensionType.PER_USER);
						}
					});
				}

				$elem.removeClass('upgradable');
				if($elem.data('type') == extensionUtils.ExtensionType.PER_USER)
				{
					dbusProxy.UninstallExtension(uuid).then(function (result) {
						// If we weren't able to uninstall the extension, don't
						// do anything more.
						if (!result)
						{
							return;
						}

						installExtension();
					});
				}
				else
				{
					installExtension();
				}
			});

			$elem.find('.uninstall-button').on('click', function () {
				dbusProxy.UninstallExtension(uuid).then(function (result) {
					if (result)
					{
						$elem.fadeOut({queue: false}).slideUp({queue: false});
						messages.addInfo(templates.get('extensions/uninstall')(meta));
					}
				});
			});

			if ([ExtensionState.UNINSTALLED, ExtensionState.DOWNLOADING].indexOf(_state) == -1)
			{
				$elem.addClass('installed');
			}

			if(meta.type == extensionUtils.ExtensionType.SYSTEM)
			{
				$elem.addClass('system');
			}

			$elem.data({
				'elem': $elem,
				'state': _state,
				'type': meta.type
			});

			$switch.data('elem', $elem);
			$switch.switchify();

			var svm = meta.shell_version_map || $elem.data('svm');
			var latest = extensionUtils.grabProperExtensionVersion(svm, dbusProxy.ShellVersion);
			if (_state !== ExtensionState.UNINSTALLED && latest !== null &&
				(!meta.version || latest.version > meta.version || _state === ExtensionState.OUT_OF_DATE))
			{
				$elem.addClass('upgradable');
			}

			function sendPopularity(action) {
				$.ajax({
					url: '/ajax/adjust-popularity/',
					type: 'POST',
					data: {
						uuid: uuid,
						action: action
					}
				});
			}

			// When the user flips the switch...
			$switch.on('changed', function (e, newValue) {
				var oldState = $elem.data('state');
				if (newValue)
				{
					if (oldState == ExtensionState.UNINSTALLED)
					{
						// If the extension is uninstalled and we
						// flick the switch on, install.
						dbusProxy.InstallExtension(uuid).then(function (result) {
							if (result === 'succeeded')
							{
								sendPopularity('enable');
							}
							else if (result === 'cancelled')
							{
								$switch.switchify('activate', false);
							}
						});
					}
					else if (oldState == ExtensionState.DISABLED ||
						oldState == ExtensionState.INITIALIZED)
					{
						dbusProxy.EnableExtension(uuid);
						sendPopularity('enable');
					}
				}
				else
				{
					if (oldState == ExtensionState.ENABLED)
					{
						dbusProxy.DisableExtension(uuid);
						sendPopularity('disable');
					}
				}
			});

			// When the extension changes state...
			$elem.on('state-changed', function (e, newState) {
				$elem.data('state', newState);

				var hasPrefs = !!(meta.hasPrefs && newState !== ExtensionState.OUT_OF_DATE);
				$elem.toggleClass('configurable', hasPrefs);

				if (newState == ExtensionState.DISABLED ||
					newState == ExtensionState.INITIALIZED ||
					newState == ExtensionState.UNINSTALLED)
				{
					$switch.switchify('activate', false);
				}
				else if (newState == ExtensionState.ENABLED)
				{
					$switch.switchify('activate', true);
					$elem.removeClass('out-of-date');
				}
				else if (newState == ExtensionState.ERROR)
				{
					$switch.switchify('customize', "ERROR", 'error');
				}
				else if (newState == ExtensionState.OUT_OF_DATE)
				{
					$elem.addClass('out-of-date');
					$switch.switchify('customize', "OUTDATED", 'outdated');
				}
			});

			$elem.on('type-changed', function (e, newType) {
				if(newType == extensionUtils.ExtensionType.SYSTEM)
				{
					$elem.addClass('system');
				}
				else
				{
					$elem.removeClass('system');
				}

				$elem.data('type', newType);
			});

			$elem.trigger('state-changed', _state);
			elems[uuid] = $elem;
		}

		$.fn.addLocalExtensions = function () {
			return this.each(function () {
				var $container = $(this);
				dbusProxy.ListExtensions().then(function (extensions) {
					if (extensions && !$.isEmptyObject(extensions))
					{
						var extensionValues = [];
						for (var uuid in extensions)
						{
							extensionValues.push(extensions[uuid]);
						}

						extensionValues.sort(function (a, b) {
							if (a.name === undefined)
							{
								return 0;
							}

							if (b.name === undefined)
							{
								return 0;
							}

							return a.name.localeCompare(b.name);
						});

						extensionValues.forEach(function (extension) {
							var uuid = extension.uuid;

							// Give us a dummy element that we'll replace when
							// rendering below, to keep renderExtension simple.
							var $elem = $('<a>');

							function renderExtension() {
								if (extension.type == extensionUtils.ExtensionType.SYSTEM)
								{
									extension.system = true;
								}

								if (extension.description)
								{
									extension.first_line_of_description = extension.description.split('\n')[0];
								}

								$elem = $(templates.get('extensions/info')(extension)).replaceAll($elem);

								addExtensionSwitch(uuid, $elem, extension);
							}

							$.ajax({
								url: "/ajax/detail/",
								dataType: "json",
								data: {
									uuid: extension.uuid,
									version: extension.version
								},
								type: "GET",
							}).done(function (result) {
								$.extend(extension, result);
								renderExtension();
							}).fail(function (error) {
								// Had an error looking up the data for the
								// extension -- that's OK, just render it anyway.
								renderExtension();
							});

							$container.append($elem);
						});
					}
					else
					{
						$container.append("You don't have any extensions installed.");
					}
				})
			});
		};

		$.fn.fillInErrors = function () {
			return this.each(function () {
				var $form = $(this);
				var uuid = $form.data('uuid');
				var $textarea = $form.find('textarea');
				dbusProxy.GetExtensionInfo(uuid).then(function (meta) {
					dbusProxy.GetErrors($form.data('uuid')).then(function (errors) {
						var context = {
							sv: dbusProxy.ShellVersion,
							ev: (meta && meta.version) ? meta.version : null,
							errors: errors
						};

						$textarea.text(templates.get('extensions/error_report_template')(context));
					});
				});
			});
		};

		$.fn.addExtensionSwitch = function () {
			return this.each(function () {
				var $extension = $(this);
				var uuid = $extension.data('uuid');

				$extension.on('out-of-date', function () {
					var svm = $extension.data('svm');
					var nhvOperation = extensionUtils.findNextHighestVersion(svm, dbusProxy.ShellVersion);
					if (nhvOperation.operation === 'upgrade' &&
						nhvOperation.stability === 'stable')
					{
						messages.addError("This extension is incompatible with your version of GNOME. Please upgrade to GNOME " + nhvOperation.version);
					}
					else if (nhvOperation.operation === 'upgrade' &&
						nhvOperation.stability === 'unstable')
					{
						messages.addError("This extension is incompatible with your version of GNOME. This extension supports the GNOME unstable release, " + nhvOperation.version);
					}
					else if (nhvOperation.operation === 'downgrade')
					{
						messages.addError("This extension is incompatible with your version of GNOME.");
					}
				});

				dbusProxy.GetExtensionInfo(uuid).then(function (meta) {
					addExtensionSwitch(uuid, $extension, meta);
				});
			});
		};

		$.fn.grayOutIfOutOfDate = function () {
			return this.each(function () {
				var $elem = $(this);
				var svm = $elem.data('svm');
				if (!svm)
				{
					return;
				}

				var vpk = extensionUtils.grabProperExtensionVersion(svm, dbusProxy.ShellVersion);
				if (vpk === null)
				{
					$elem.addClass('out-of-date');
				}
			});
		};
	}
);
<commit_msg>extensions: try to disable system extension prior to upgrade.<commit_after>/*
    GNOME Shell extensions repository
    Copyright (C) 2011-2012  Jasper St. Pierre <jstpierre@mecheye.net>
    Copyright (C) 2016-2017  Yuri Konotopov <ykonotopov@gnome.org>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 */

define(['jquery', 'messages', 'dbus!_', 'extensionUtils', 'templates', 'paginator', 'switch'],
	function ($, messages, dbusProxy, extensionUtils, templates) {
		"use strict";

		var ExtensionState = extensionUtils.ExtensionState;

		$.fn.buildShellVersionsInfo = function () {
			return this.each(function () {
				var $table = $(this);
				var $tbody = $table.find('tbody');
				var $extension = $table.parents('.extension');

				$tbody.children().remove();

				var svm = $extension.data('svm');
				for (var version in svm)
				{
					if (!svm.hasOwnProperty(version))
					{
						continue;
					}

					var vpk = extensionUtils.grabProperExtensionVersion(svm, version);
					var $tr = $('<tr>').appendTo($tbody);
					$('<td>').append($('<code>').text(version)).appendTo($tr);
					$('<td>').text(vpk.version).appendTo($tr);
				}
			});
		};

		// While technically we shouldn't have mismatched API versions,
		// the plugin doesn't check whether the Shell matches, so if someone
		// is running with an old Shell version but a newer plugin, error out.
		if (dbusProxy.IsDummy)
		{
			// We don't have a proper DBus proxy -- it's probably an old
			// version of GNOME3 or the Shell.
			messages.addError(templates.get('messages/dummy_proxy')());

			$.fn.addExtensionSwitch = function () {
				// Don't show our switches -- CSS styles define a clickable
				// area even with no content.
				return this.find('.switch').hide();
			};

			$.fn.addLocalExtensions = function () {
				return this.append(templates.get('messages/cannot_list_local')());
			};

			$.fn.fillInErrors = function () {
				var $textarea = this.find('textarea[name=error]');
				var $hidden = this.find('input:hidden[name=has_errors]');
				$textarea.text(templates.get('messages/cannot_list_errors')()).addClass('no-errors').attr('disabled', 'disabled');
				$hidden.val('');
				return this;
			};

			$.fn.grayOutIfOutOfDate = function () {
				return this;
			};

			return;
		}

		// uuid => elem
		var elems = {};

		function extensionStateChanged(uuid, newState) {
			if (elems[uuid] !== undefined)
			{
				elems[uuid].trigger('state-changed', newState);
			}
		}

		function extensionTypeChanged(uuid, newType) {
			if (elems[uuid] !== undefined)
			{
				if(elems[uuid].data('type') != newType)
				{
					elems[uuid].trigger('type-changed', newState);
				}
			}
		}

		dbusProxy.extensionStateChangedHandler = extensionStateChanged;

		dbusProxy.shellRestartHandler = function () {
			dbusProxy.ListExtensions().then(function (extensions) {
				$.each(extensions, function () {
					extensionStateChanged(this.uuid, this.state);
					extensionTypeChanged(this.uuid, this.type);
				});
			});
		};

		function addExtensionSwitch(uuid, $elem, meta) {
			var $switch = $elem.find('.switch');
			var _state;
			if (meta && meta.state)
			{
				_state = meta.state;
			}
			else
			{
				_state = ExtensionState.UNINSTALLED;
			}

			$elem.find('.configure-button').on('click', function () {
				dbusProxy.LaunchExtensionPrefs(uuid);
			});

			$elem.find('.upgrade-button').on('click', function () {
				function installExtension() {
					dbusProxy.InstallExtension(uuid).then(function (result) {
						if (result === 'cancelled')
						{
							// WELP. We can't really do anything except leave the
							// thing uninstalled.
							$switch.switchify('activate', false);
						}
						// GNOME Shell bug https://bugzilla.gnome.org/show_bug.cgi?id=777544
						else if (['s', 'successful'].indexOf(result) != -1)
						{
							// It should always became "per user" extension if installed from repository.
							$elem.trigger('type-changed', extensionUtils.ExtensionType.PER_USER);
						}
					});
				}

				$elem.removeClass('upgradable');
				if($elem.data('type') == extensionUtils.ExtensionType.PER_USER)
				{
					dbusProxy.UninstallExtension(uuid).then(function (result) {
						// If we weren't able to uninstall the extension, don't
						// do anything more.
						if (!result)
						{
							return;
						}

						installExtension();
					});
				}
				else
				{
					dbusProxy.DisableExtension(uuid).then(function (result) {
						// Install extension if we were able to disable it first
						if(result)
						{
							installExtension();
						}
					});
				}
			});

			$elem.find('.uninstall-button').on('click', function () {
				dbusProxy.UninstallExtension(uuid).then(function (result) {
					if (result)
					{
						$elem.fadeOut({queue: false}).slideUp({queue: false});
						messages.addInfo(templates.get('extensions/uninstall')(meta));
					}
				});
			});

			if ([ExtensionState.UNINSTALLED, ExtensionState.DOWNLOADING].indexOf(_state) == -1)
			{
				$elem.addClass('installed');
			}

			if(meta.type == extensionUtils.ExtensionType.SYSTEM)
			{
				$elem.addClass('system');
			}

			$elem.data({
				'elem': $elem,
				'state': _state,
				'type': meta.type
			});

			$switch.data('elem', $elem);
			$switch.switchify();

			var svm = meta.shell_version_map || $elem.data('svm');
			var latest = extensionUtils.grabProperExtensionVersion(svm, dbusProxy.ShellVersion);
			if (_state !== ExtensionState.UNINSTALLED && latest !== null &&
				(!meta.version || latest.version > meta.version || _state === ExtensionState.OUT_OF_DATE))
			{
				$elem.addClass('upgradable');
			}

			function sendPopularity(action) {
				$.ajax({
					url: '/ajax/adjust-popularity/',
					type: 'POST',
					data: {
						uuid: uuid,
						action: action
					}
				});
			}

			// When the user flips the switch...
			$switch.on('changed', function (e, newValue) {
				var oldState = $elem.data('state');
				if (newValue)
				{
					if (oldState == ExtensionState.UNINSTALLED)
					{
						// If the extension is uninstalled and we
						// flick the switch on, install.
						dbusProxy.InstallExtension(uuid).then(function (result) {
							if (result === 'succeeded')
							{
								sendPopularity('enable');
							}
							else if (result === 'cancelled')
							{
								$switch.switchify('activate', false);
							}
						});
					}
					else if (oldState == ExtensionState.DISABLED ||
						oldState == ExtensionState.INITIALIZED)
					{
						dbusProxy.EnableExtension(uuid);
						sendPopularity('enable');
					}
				}
				else
				{
					if (oldState == ExtensionState.ENABLED)
					{
						dbusProxy.DisableExtension(uuid);
						sendPopularity('disable');
					}
				}
			});

			// When the extension changes state...
			$elem.on('state-changed', function (e, newState) {
				$elem.data('state', newState);

				var hasPrefs = !!(meta.hasPrefs && newState !== ExtensionState.OUT_OF_DATE);
				$elem.toggleClass('configurable', hasPrefs);

				if (newState == ExtensionState.DISABLED ||
					newState == ExtensionState.INITIALIZED ||
					newState == ExtensionState.UNINSTALLED)
				{
					$switch.switchify('activate', false);
				}
				else if (newState == ExtensionState.ENABLED)
				{
					$switch.switchify('activate', true);
					$elem.removeClass('out-of-date');
				}
				else if (newState == ExtensionState.ERROR)
				{
					$switch.switchify('customize', "ERROR", 'error');
				}
				else if (newState == ExtensionState.OUT_OF_DATE)
				{
					$elem.addClass('out-of-date');
					$switch.switchify('customize', "OUTDATED", 'outdated');
				}
			});

			$elem.on('type-changed', function (e, newType) {
				if(newType == extensionUtils.ExtensionType.SYSTEM)
				{
					$elem.addClass('system');
				}
				else
				{
					$elem.removeClass('system');
				}

				$elem.data('type', newType);
			});

			$elem.trigger('state-changed', _state);
			elems[uuid] = $elem;
		}

		$.fn.addLocalExtensions = function () {
			return this.each(function () {
				var $container = $(this);
				dbusProxy.ListExtensions().then(function (extensions) {
					if (extensions && !$.isEmptyObject(extensions))
					{
						var extensionValues = [];
						for (var uuid in extensions)
						{
							extensionValues.push(extensions[uuid]);
						}

						extensionValues.sort(function (a, b) {
							if (a.name === undefined)
							{
								return 0;
							}

							if (b.name === undefined)
							{
								return 0;
							}

							return a.name.localeCompare(b.name);
						});

						extensionValues.forEach(function (extension) {
							var uuid = extension.uuid;

							// Give us a dummy element that we'll replace when
							// rendering below, to keep renderExtension simple.
							var $elem = $('<a>');

							function renderExtension() {
								if (extension.type == extensionUtils.ExtensionType.SYSTEM)
								{
									extension.system = true;
								}

								if (extension.description)
								{
									extension.first_line_of_description = extension.description.split('\n')[0];
								}

								$elem = $(templates.get('extensions/info')(extension)).replaceAll($elem);

								addExtensionSwitch(uuid, $elem, extension);
							}

							$.ajax({
								url: "/ajax/detail/",
								dataType: "json",
								data: {
									uuid: extension.uuid,
									version: extension.version
								},
								type: "GET",
							}).done(function (result) {
								$.extend(extension, result);
								renderExtension();
							}).fail(function (error) {
								// Had an error looking up the data for the
								// extension -- that's OK, just render it anyway.
								renderExtension();
							});

							$container.append($elem);
						});
					}
					else
					{
						$container.append("You don't have any extensions installed.");
					}
				})
			});
		};

		$.fn.fillInErrors = function () {
			return this.each(function () {
				var $form = $(this);
				var uuid = $form.data('uuid');
				var $textarea = $form.find('textarea');
				dbusProxy.GetExtensionInfo(uuid).then(function (meta) {
					dbusProxy.GetErrors($form.data('uuid')).then(function (errors) {
						var context = {
							sv: dbusProxy.ShellVersion,
							ev: (meta && meta.version) ? meta.version : null,
							errors: errors
						};

						$textarea.text(templates.get('extensions/error_report_template')(context));
					});
				});
			});
		};

		$.fn.addExtensionSwitch = function () {
			return this.each(function () {
				var $extension = $(this);
				var uuid = $extension.data('uuid');

				$extension.on('out-of-date', function () {
					var svm = $extension.data('svm');
					var nhvOperation = extensionUtils.findNextHighestVersion(svm, dbusProxy.ShellVersion);
					if (nhvOperation.operation === 'upgrade' &&
						nhvOperation.stability === 'stable')
					{
						messages.addError("This extension is incompatible with your version of GNOME. Please upgrade to GNOME " + nhvOperation.version);
					}
					else if (nhvOperation.operation === 'upgrade' &&
						nhvOperation.stability === 'unstable')
					{
						messages.addError("This extension is incompatible with your version of GNOME. This extension supports the GNOME unstable release, " + nhvOperation.version);
					}
					else if (nhvOperation.operation === 'downgrade')
					{
						messages.addError("This extension is incompatible with your version of GNOME.");
					}
				});

				dbusProxy.GetExtensionInfo(uuid).then(function (meta) {
					addExtensionSwitch(uuid, $extension, meta);
				});
			});
		};

		$.fn.grayOutIfOutOfDate = function () {
			return this.each(function () {
				var $elem = $(this);
				var svm = $elem.data('svm');
				if (!svm)
				{
					return;
				}

				var vpk = extensionUtils.grabProperExtensionVersion(svm, dbusProxy.ShellVersion);
				if (vpk === null)
				{
					$elem.addClass('out-of-date');
				}
			});
		};
	}
);
<|endoftext|>


<commit_before>/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovi.es>"],
        licenses:["MIT"], //TODO: Licenses

        init:function () {
            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                // e.target matches the elem from above
                lastEvent = e;
                //TODO populate TemplateDOM
            }, false);
            return templateLayout;
        },

        getLastEvent:function () {
            return lastEvent;
        }
    };

    var lastEvent = null;

    wef.plugins.register("templateLayout", templateLayout);
})();<commit_msg>Move StyleDeclaration outside main function<commit_after>/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovi.es>"],
        licenses:["MIT"], //TODO: Licenses

        init:function () {
            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                //console.log(e.data.selectorText, e.data.declaration);
                lastEvent = e;
                //TODO populate TemplateDOM

            }, false);
            return templateLayout;
        },

        getLastEvent:function () {
            return lastEvent;
        }
    };

    var lastEvent = null;

    wef.plugins.register("templateLayout", templateLayout);
})();<|endoftext|>