<commit_before>'use strict';

describe('Bellows E2E Page Traversal', function () {
  // Better way to import all files from directory, might want node module like require-all?
  var activityPage        = require('../pages/activityPage.js');
  var changePasswordPage  = require('../pages/changePasswordPage.js');
  var forgotPasswordPage  = require('../pages/forgotPasswordPage.js');
  var loginPage           = require('../pages/loginPage.js');
  var projectSettingsPage = require('../pages/projectSettingsPage.js');
  var projectsPage        = require('../pages/projectsPage.js');
  var resetPasswordPage   = require('../pages/resetPasswordPage.js');
  var signupPage          = require('../pages/signupPage.js');
  var siteAdminPage       = require('../pages/siteAdminPage.js');
  var userProfilePage     = require('../pages/userProfilePage.js');
  var constants           = require('../../testConstants.json');

  it('Explore signup page' , function () {
    signupPage.get();
    signupPage.emailInput.clear();
    signupPage.nameInput.clear();
    signupPage.passwordInput.clear();
    signupPage.captcha.blueSquareButton.click();
    signupPage.captcha.yellowCircleButton.click();
    signupPage.captcha.redTriangleButton.click();
  });

  it('Explore forgot password page', function () {
    forgotPasswordPage.get();
    forgotPasswordPage.usernameInput.clear();
    forgotPasswordPage.submitButton.click();
  });

  it('Explore reset password page', function () {
    resetPasswordPage.get(constants.resetPasswordKey);
    resetPasswordPage.passwordInput.clear();
    resetPasswordPage.confirmPasswordInput.clear();
    resetPasswordPage.resetButton.click();
  });

  it('Explore login page', function () {
    loginPage.get();
    loginPage.loginAsAdmin();
  });

  it('Explore change password page', function () {
    changePasswordPage.get();
    changePasswordPage.password.clear();
    changePasswordPage.confirm.clear();
    changePasswordPage.submitButton.click();
  });

  it('Explore activity page', function () {
    activityPage.get();
    activityPage.activitiesList.count();
  });

  it('Explore project page', function () {
    projectsPage.get();
    projectsPage.projectsList.count();
    projectsPage.projectNames.count();
    projectsPage.projectTypes.count();
    projectsPage.createBtn.click();
  });

  // TODO Not sure if we want to test project settings since they seem quite different in lf and sf
  xit('Explore project settings page', function () {
    projectSettingsPage.get(constants.testProjectName);
    projectSettingsPage.noticeList.count();
    projectSettingsPage.tabDivs.count();
    projectSettingsPage.tabs.project.click();
    projectSettingsPage.tabs.remove.click();
  });

  it('Explore site admin page', function() {
    siteAdminPage.get();
    siteAdminPage.tabs.archivedProjects.click();
    siteAdminPage.tabs.archivedProjects.republishButton.click();
    siteAdminPage.tabs.archivedProjects.deleteButton.click();
    siteAdminPage.tabs.archivedProjects.projectsList.count();
  });

  it('Explore user profile page', function () {
    userProfilePage.get();
    userProfilePage.activitiesList.count();
    userProfilePage.tabs.aboutMe.click();
    userProfilePage.tabs.myAccount.click();
  });

  // TODO this seems to be a lf specific view
  xit('Explore user management page', function() {
    userManagementPage.get();
    // TODO click on things
  });
});
<commit_msg>Modfied bellowsTraversal spec<commit_after>'use strict';

describe('Bellows E2E Page Traversal', function () {
  // Better way to import all files from directory, might want node module like require-all?
  var activityPage        = require('../pages/activityPage.js');
  var changePasswordPage  = require('../pages/changePasswordPage.js');
  var forgotPasswordPage  = require('../pages/forgotPasswordPage.js');
  var loginPage           = require('../pages/loginPage.js');
  var projectSettingsPage = require('../pages/projectSettingsPage.js');
  var projectsPage        = require('../pages/projectsPage.js');
  var resetPasswordPage   = require('../pages/resetPasswordPage.js');
  var signupPage          = require('../pages/signupPage.js');
  var siteAdminPage       = require('../pages/siteAdminPage.js');
  var userProfilePage     = require('../pages/userProfilePage.js');
  var constants           = require('../../testConstants.json');

  it('Explore signup page' , function () {
    signupPage.get();
    signupPage.emailInput.clear();
    signupPage.nameInput.clear();
    signupPage.passwordInput.clear();
    signupPage.captcha.blueSquareButton.click();
    signupPage.captcha.yellowCircleButton.click();
    signupPage.captcha.redTriangleButton.click();
  });

  it('Explore forgot password page', function () {
    forgotPasswordPage.get();
    forgotPasswordPage.usernameInput.clear();
    forgotPasswordPage.submitButton.click();
  });

  it('Explore reset password page', function () {
    resetPasswordPage.get(constants.resetPasswordKey);
    resetPasswordPage.passwordInput.clear();
    resetPasswordPage.confirmPasswordInput.clear();
    resetPasswordPage.resetButton.click();
  });

  it('Explore login page', function () {
    loginPage.get();
    loginPage.loginAsAdmin();
  });

  it('Explore change password page', function () {
    changePasswordPage.get();
    changePasswordPage.password.clear();
    changePasswordPage.confirm.clear();
    changePasswordPage.submitButton.click();
  });

  it('Explore activity page', function () {
    activityPage.get();
    activityPage.activitiesList.count();
  });

  it('Explore project page', function () {
    projectsPage.get();
    projectsPage.projectsList.count();
    projectsPage.projectNames.count();
    projectsPage.projectTypes.count();
    projectsPage.createBtn.click();
  });

  // TODO Not sure if we want to test project settings since they seem quite different in lf and sf
  xit('Explore project settings page', function () {
    projectSettingsPage.get(constants.testProjectName);
    projectSettingsPage.noticeList.count();
    projectSettingsPage.tabDivs.count();
    projectSettingsPage.tabs.project.click();
    projectSettingsPage.tabs.remove.click();
  });

  it('Explore site admin page', function() {
    siteAdminPage.get();
    siteAdminPage.tabs.archivedProjects.click();
    siteAdminPage.archivedProjectsTab.republishButton.click();
    siteAdminPage.archivedProjectsTab.deleteButton.click();
    siteAdminPage.archivedProjectsTab.projectsList.count();
  });

  it('Explore user profile page', function () {
    userProfilePage.get();
    userProfilePage.activitiesList.count();
    userProfilePage.tabs.aboutMe.click();
    userProfilePage.tabs.myAccount.click();
  });

  // TODO this seems to be a lf specific view
  xit('Explore user management page', function() {
    userManagementPage.get();
    // TODO click on things
  });
});
<|endoftext|>


<commit_before>
exports.parse = require('./lib/parse');
exports.stringify = require('./lib/stringify');

exports.Reader = require('./lib/reader');
exports.Writer = require('./lib/writer');

exports.Client = require('./lib/client');
<commit_msg>index: add some comments<commit_after>
/**
 * Parse and stringify metadata Buffers to/from formatted Objects.
 */

exports.parse = require('./lib/parse');
exports.stringify = require('./lib/stringify');

/**
 * Low level transformation classes.
 */

exports.Reader = require('./lib/reader');
exports.Writer = require('./lib/writer');

/**
 * Icecast HTTP client interface. Aims to map directly 1-1 the "http" module's
 * client interface.
 */

exports.Client = require('./lib/client');
<|endoftext|>


<commit_before>
var https = require('https');
var http = require('http');
var fs = require('fs');

var express = require('express');
var detect = require('./lib/detect');
var argv = require('optimist')
  .boolean('s')
  .alias('s', 'secure')
  .describe('s', 'Start an HTTPS server.')
  .alias('p', 'port')
  .describe('p', 'Port to run server on.')
  .default('p', 3000)
  .describe('secure-port', 'Port to run secure server on.')
  .default('secure-port', 443)
  .argv;

var app = express();

app.configure(function () {
  app.use( express.static(__dirname + '/public') );
  app.use( express.compress() );
});

app.get('/detect/features', function (req, res) {
  detect.features(req.query.url, function (err, features) {
    res.jsonp({ error : err || false, features : features || {} });
  });
});

if (argv.secure) {
  var options = {
    key : fs.readFileSync('./ssl/key.pem').toString(),
    ca: [fs.readFileSync('./ssl/ca.primary').toString(), fs.readFileSync('./ssl/ca.secondary').toString()],
    cert : fs.readFileSync('./ssl/cert.pem').toString()
  };

  require('https').createServer(options, app).listen(argv['secure-port'], function () {
    console.log('secure server listening on port', argv['secure-port']);
  });
}

http.createServer(app).listen(argv.port);
console.log('server listening on port', argv.port);
<commit_msg>I guess order makes a difference.<commit_after>
var https = require('https');
var http = require('http');
var fs = require('fs');

var express = require('express');
var detect = require('./lib/detect');
var argv = require('optimist')
  .boolean('s')
  .alias('s', 'secure')
  .describe('s', 'Start an HTTPS server.')
  .alias('p', 'port')
  .describe('p', 'Port to run server on.')
  .default('p', 3000)
  .describe('secure-port', 'Port to run secure server on.')
  .default('secure-port', 443)
  .argv;

var app = express();

app.configure(function () {
  app.use( express.compress() );
  app.use( express.static(__dirname + '/public') );
});

app.get('/detect/features', function (req, res) {
  detect.features(req.query.url, function (err, features) {
    res.jsonp({ error : err || false, features : features || {} });
  });
});

if (argv.secure) {
  var options = {
    key : fs.readFileSync('./ssl/key.pem').toString(),
    ca: [fs.readFileSync('./ssl/ca.primary').toString(), fs.readFileSync('./ssl/ca.secondary').toString()],
    cert : fs.readFileSync('./ssl/cert.pem').toString()
  };

  require('https').createServer(options, app).listen(argv['secure-port'], function () {
    console.log('secure server listening on port', argv['secure-port']);
  });
}

http.createServer(app).listen(argv.port);
console.log('server listening on port', argv.port);
<|endoftext|>


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

var Connection = require('../../../lib/connection.js');
var defaultOptions = require('../../../lib/client-options.js').defaultOptions();
var types = require('../../../lib/types');
var utils = require('../../../lib/utils.js');
var requests = require('../../../lib/requests.js');
var helper = require('../../test-helper.js');
var vit = helper.vit;

describe('Connection', function () {
  this.timeout(120000);
  describe('#open()', function () {
    before(helper.ccmHelper.start(1));
    after(helper.ccmHelper.remove);
    it('should open', function (done) {
      var localCon = newInstance();
      localCon.open(function (err) {
        assert.ifError(err);
        assert.ok(localCon.connected && !localCon.connecting, 'Must be status connected');
        localCon.close(done);
      });
    });
    it('should use the max supported protocol version', function (done) {
      var localCon = newInstance(null, null);
      localCon.open(function (err) {
        assert.ifError(err);
        assert.strictEqual(localCon.protocolVersion, getProtocolVersion());
        assert.strictEqual(localCon.checkingVersion, true);
        localCon.close(done);
      });
    });
    vit('2.0', 'should limit the max protocol version based on the protocolOptions', function (done) {
      var options = utils.extend({}, defaultOptions);
      options.protocolOptions.maxVersion =  getProtocolVersion() - 1;
      var localCon = newInstance(null, null, options);
      localCon.open(function (err) {
        assert.ifError(err);
        assert.strictEqual(localCon.protocolVersion, options.protocolOptions.maxVersion);
        assert.strictEqual(localCon.checkingVersion, true);
        localCon.close(done);
      });
    });
    it('should open with all the protocol versions supported', function (done) {
      var maxProtocolVersionSupported = getProtocolVersion();
      var protocolVersion = 0;
      async.whilst(function condition() {
        return (++protocolVersion) <= maxProtocolVersionSupported;
      }, function iterator (next) {
        var localCon = newInstance(null, protocolVersion);
        localCon.open(function (err) {
          assert.ifError(err);
          assert.ok(localCon.connected && !localCon.connecting, 'Must be status connected');
          localCon.close(next);
        });
      }, done);
      for (var i = 1; i <= maxProtocolVersionSupported; i++) {
      }
    });
    it('should fail when the host does not exits', function (done) {
      var localCon = newInstance('1.1.1.1');
      localCon.open(function (err) {
        assert.ok(err, 'Must return a connection error');
        assert.ok(!localCon.connected && !localCon.connecting);
        localCon.close(done);
      });
    });
    it('should fail when the host exists but port closed', function (done) {
      var localCon = newInstance('127.0.0.1:8090');
      localCon.open(function (err) {
        assert.ok(err, 'Must return a connection error');
        assert.ok(!localCon.connected && !localCon.connecting);
        localCon.close(done);
      });
    });
    it('should set the timeout for the hearbeat', function (done) {
      var options = utils.extend({}, defaultOptions);
      options.pooling.heartBeatInterval = 200;
      var c = newInstance(null, undefined, options);
      var sendCounter = 0;
      c.open(function (err) {
        assert.ifError(err);
        assert.ok(c.idleTimeout);
        var originalSend = c.sendStream;
        c.sendStream = function() {
          sendCounter++;
          originalSend.apply(c, Array.prototype.slice.call(arguments));
        };
      });
      setTimeout(function () {
        //wait for requests to take place
        //at least 3 requests
        assert.ok(sendCounter > 2, 'sendCounter ' + sendCounter);
        done();
      }, 1000)
    });
  });
  describe('#open with ssl', function () {
    before(helper.ccmHelper.start(1, {ssl: true}));
    after(helper.ccmHelper.remove);
    it('should open to a ssl enabled host', function (done) {
      var localCon = newInstance();
      localCon.options.sslOptions = {};
      localCon.open(function (err) {
        assert.ifError(err);
        assert.ok(localCon.connected && !localCon.connecting, 'Must be status connected');
        localCon.sendStream(getRequest('SELECT * FROM system.schema_keyspaces'), null, function (err, result) {
          assert.ifError(err);
          assert.ok(result);
          assert.ok(result.rows.length);
          localCon.close(done);
        });
      });
    });
  });
  describe('#changeKeyspace()', function () {
    before(helper.ccmHelper.start(1));
    after(helper.ccmHelper.remove);
    it('should change active keyspace', function (done) {
      var localCon = newInstance();
      var keyspace = helper.getRandomName();
      async.series([
        localCon.open.bind(localCon),
        function creating(next) {
          var query = 'CREATE KEYSPACE ' + keyspace + ' WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : 1};';
          localCon.sendStream(getRequest(query), {}, next);
        },
        function changing(next) {
          localCon.changeKeyspace(keyspace, next);
        },
        function asserting(next) {
          assert.strictEqual(localCon.keyspace, keyspace);
          next();
        }
      ], done);
    });
    it('should be case sensitive', function (done) {
      var localCon = newInstance();
      var keyspace = helper.getRandomName().toUpperCase();
      assert.notStrictEqual(keyspace, keyspace.toLowerCase());
      async.series([
        localCon.open.bind(localCon),
        function creating(next) {
          var query = 'CREATE KEYSPACE "' + keyspace + '" WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : 1};';
          localCon.sendStream(getRequest(query), {}, next);
        },
        function changing(next) {
          localCon.changeKeyspace(keyspace, next);
        },
        function asserting(next) {
          assert.strictEqual(localCon.keyspace, keyspace);
          next();
        }
      ], done);
    });
  });
  describe('#execute()', function () {
    before(helper.ccmHelper.start(1));
    after(helper.ccmHelper.remove);
    it('should queue pending if there is not an available stream id', function (done) {
      var connection = newInstance();
      var maxRequests = connection.protocolVersion < 3 ? 128 : Math.pow(2, 15);
      async.series([
        connection.open.bind(connection),
        function asserting(seriesNext) {
          async.times(maxRequests + 10, function (n, next) {
            var request = getRequest('SELECT * FROM system.schema_keyspaces');
            connection.sendStream(request, null, next);
          }, seriesNext);
        }
      ], done);
    });
    it('should callback the pending queue if the connection is there is a socket error', function (done) {
      var connection = newInstance();
      var maxRequests = connection.protocolVersion < 3 ? 128 : Math.pow(2, 15);
      var killed = false;
      async.series([
        connection.open.bind(connection),
        function asserting(seriesNext) {
          async.times(maxRequests + 10, function (n, next) {
            if (n === maxRequests + 9) {
              connection.netClient.destroy();
              killed = true;
              return next();
            }
            var request = getRequest('SELECT key FROM system.local');
            connection.sendStream(request, null, function (err) {
              if (killed && err) {
                assert.ok(err.isServerUnhealthy);
                err = null;
              }
              next(err);
            });
          }, seriesNext);
        }
      ], done);
    });
  });
});

/** @returns {Connection} */
function newInstance(address, protocolVersion, options){
  if (!address) {
    address = helper.baseOptions.contactPoints[0];
  }
  if (typeof protocolVersion === 'undefined') {
    protocolVersion = getProtocolVersion();
  }
  //var logEmitter = function (name, type) { if (type === 'verbose') { return; } console.log.apply(console, arguments);};
  options = utils.extend({logEmitter: helper.noop}, options || defaultOptions);
  return new Connection(address + ':' + options.protocolOptions.port, protocolVersion, options);
}

function getRequest(query) {
  return new requests.QueryRequest(query, null, null);
}

/**
 * Gets the max supported protocol version for the current Cassandra version
 * @returns {number}
 */
function getProtocolVersion() {
  //expected protocol version
  if (helper.getCassandraVersion().indexOf('2.0.') === 0) {
    return 2;
  }
  if (helper.getCassandraVersion().indexOf('1.') === 0) {
    return 1;
  }
  return 3;
}<commit_msg>Update getProtocolVersion() to account for v4.<commit_after>var assert = require('assert');
var util = require('util');
var async = require('async');

var Connection = require('../../../lib/connection.js');
var defaultOptions = require('../../../lib/client-options.js').defaultOptions();
var types = require('../../../lib/types');
var utils = require('../../../lib/utils.js');
var requests = require('../../../lib/requests.js');
var helper = require('../../test-helper.js');
var vit = helper.vit;

describe('Connection', function () {
  this.timeout(120000);
  describe('#open()', function () {
    before(helper.ccmHelper.start(1));
    after(helper.ccmHelper.remove);
    it('should open', function (done) {
      var localCon = newInstance();
      localCon.open(function (err) {
        assert.ifError(err);
        assert.ok(localCon.connected && !localCon.connecting, 'Must be status connected');
        localCon.close(done);
      });
    });
    it('should use the max supported protocol version', function (done) {
      var localCon = newInstance(null, null);
      localCon.open(function (err) {
        assert.ifError(err);
        assert.strictEqual(localCon.protocolVersion, getProtocolVersion());
        assert.strictEqual(localCon.checkingVersion, true);
        localCon.close(done);
      });
    });
    vit('2.0', 'should limit the max protocol version based on the protocolOptions', function (done) {
      var options = utils.extend({}, defaultOptions);
      options.protocolOptions.maxVersion =  getProtocolVersion() - 1;
      var localCon = newInstance(null, null, options);
      localCon.open(function (err) {
        assert.ifError(err);
        assert.strictEqual(localCon.protocolVersion, options.protocolOptions.maxVersion);
        assert.strictEqual(localCon.checkingVersion, true);
        localCon.close(done);
      });
    });
    it('should open with all the protocol versions supported', function (done) {
      var maxProtocolVersionSupported = getProtocolVersion();
      var protocolVersion = 0;
      async.whilst(function condition() {
        return (++protocolVersion) <= maxProtocolVersionSupported;
      }, function iterator (next) {
        var localCon = newInstance(null, protocolVersion);
        localCon.open(function (err) {
          assert.ifError(err);
          assert.ok(localCon.connected && !localCon.connecting, 'Must be status connected');
          localCon.close(next);
        });
      }, done);
      for (var i = 1; i <= maxProtocolVersionSupported; i++) {
      }
    });
    it('should fail when the host does not exits', function (done) {
      var localCon = newInstance('1.1.1.1');
      localCon.open(function (err) {
        assert.ok(err, 'Must return a connection error');
        assert.ok(!localCon.connected && !localCon.connecting);
        localCon.close(done);
      });
    });
    it('should fail when the host exists but port closed', function (done) {
      var localCon = newInstance('127.0.0.1:8090');
      localCon.open(function (err) {
        assert.ok(err, 'Must return a connection error');
        assert.ok(!localCon.connected && !localCon.connecting);
        localCon.close(done);
      });
    });
    it('should set the timeout for the hearbeat', function (done) {
      var options = utils.extend({}, defaultOptions);
      options.pooling.heartBeatInterval = 200;
      var c = newInstance(null, undefined, options);
      var sendCounter = 0;
      c.open(function (err) {
        assert.ifError(err);
        assert.ok(c.idleTimeout);
        var originalSend = c.sendStream;
        c.sendStream = function() {
          sendCounter++;
          originalSend.apply(c, Array.prototype.slice.call(arguments));
        };
      });
      setTimeout(function () {
        //wait for requests to take place
        //at least 3 requests
        assert.ok(sendCounter > 2, 'sendCounter ' + sendCounter);
        done();
      }, 1000)
    });
  });
  describe('#open with ssl', function () {
    before(helper.ccmHelper.start(1, {ssl: true}));
    after(helper.ccmHelper.remove);
    it('should open to a ssl enabled host', function (done) {
      var localCon = newInstance();
      localCon.options.sslOptions = {};
      localCon.open(function (err) {
        assert.ifError(err);
        assert.ok(localCon.connected && !localCon.connecting, 'Must be status connected');
        localCon.sendStream(getRequest('SELECT * FROM system.schema_keyspaces'), null, function (err, result) {
          assert.ifError(err);
          assert.ok(result);
          assert.ok(result.rows.length);
          localCon.close(done);
        });
      });
    });
  });
  describe('#changeKeyspace()', function () {
    before(helper.ccmHelper.start(1));
    after(helper.ccmHelper.remove);
    it('should change active keyspace', function (done) {
      var localCon = newInstance();
      var keyspace = helper.getRandomName();
      async.series([
        localCon.open.bind(localCon),
        function creating(next) {
          var query = 'CREATE KEYSPACE ' + keyspace + ' WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : 1};';
          localCon.sendStream(getRequest(query), {}, next);
        },
        function changing(next) {
          localCon.changeKeyspace(keyspace, next);
        },
        function asserting(next) {
          assert.strictEqual(localCon.keyspace, keyspace);
          next();
        }
      ], done);
    });
    it('should be case sensitive', function (done) {
      var localCon = newInstance();
      var keyspace = helper.getRandomName().toUpperCase();
      assert.notStrictEqual(keyspace, keyspace.toLowerCase());
      async.series([
        localCon.open.bind(localCon),
        function creating(next) {
          var query = 'CREATE KEYSPACE "' + keyspace + '" WITH replication = {\'class\': \'SimpleStrategy\', \'replication_factor\' : 1};';
          localCon.sendStream(getRequest(query), {}, next);
        },
        function changing(next) {
          localCon.changeKeyspace(keyspace, next);
        },
        function asserting(next) {
          assert.strictEqual(localCon.keyspace, keyspace);
          next();
        }
      ], done);
    });
  });
  describe('#execute()', function () {
    before(helper.ccmHelper.start(1));
    after(helper.ccmHelper.remove);
    it('should queue pending if there is not an available stream id', function (done) {
      var connection = newInstance();
      var maxRequests = connection.protocolVersion < 3 ? 128 : Math.pow(2, 15);
      async.series([
        connection.open.bind(connection),
        function asserting(seriesNext) {
          async.times(maxRequests + 10, function (n, next) {
            var request = getRequest('SELECT * FROM system.schema_keyspaces');
            connection.sendStream(request, null, next);
          }, seriesNext);
        }
      ], done);
    });
    it('should callback the pending queue if the connection is there is a socket error', function (done) {
      var connection = newInstance();
      var maxRequests = connection.protocolVersion < 3 ? 128 : Math.pow(2, 15);
      var killed = false;
      async.series([
        connection.open.bind(connection),
        function asserting(seriesNext) {
          async.times(maxRequests + 10, function (n, next) {
            if (n === maxRequests + 9) {
              connection.netClient.destroy();
              killed = true;
              return next();
            }
            var request = getRequest('SELECT key FROM system.local');
            connection.sendStream(request, null, function (err) {
              if (killed && err) {
                assert.ok(err.isServerUnhealthy);
                err = null;
              }
              next(err);
            });
          }, seriesNext);
        }
      ], done);
    });
  });
});

/** @returns {Connection} */
function newInstance(address, protocolVersion, options){
  if (!address) {
    address = helper.baseOptions.contactPoints[0];
  }
  if (typeof protocolVersion === 'undefined') {
    protocolVersion = getProtocolVersion();
  }
  //var logEmitter = function (name, type) { if (type === 'verbose') { return; } console.log.apply(console, arguments);};
  options = utils.extend({logEmitter: helper.noop}, options || defaultOptions);
  return new Connection(address + ':' + options.protocolOptions.port, protocolVersion, options);
}

function getRequest(query) {
  return new requests.QueryRequest(query, null, null);
}

/**
 * Gets the max supported protocol version for the current Cassandra version
 * @returns {number}
 */
function getProtocolVersion() {
  //expected protocol version
  if (helper.getCassandraVersion().indexOf('2.1.') === 0) {
    return 3;
  }
  if (helper.getCassandraVersion().indexOf('2.0.') === 0) {
    return 2;
  }
  if (helper.getCassandraVersion().indexOf('1.') === 0) {
    return 1;
  }
  return 4;
}<|endoftext|>


<commit_before>var atCss = require('basisjs-tools-ast').css;
var mime = require('mime');

function unsupportedLink(link){
  return (link[0].type != 'style' && link[0].type != 'style-block') ||
         link[1].type != 'Url';
};

(module.exports = function(flow){
  var fconsole = flow.console;
  var quota = flow.options.cssInlineImage;

  fconsole.log('Inline resources less ' + quota + ' bytes\n');

  for (var i = flow.files.queue.length - 1, file; file = flow.files.queue[i]; i--)
  {
    if (file.type == 'image')
    {
      fconsole.start(file.relpath);

      if (file.content.length > quota)
      {
        fconsole.endl('[skip] Too big (' + file.content.length + ' bytes)');
        continue;
      }

      if (file.linkBack.some(unsupportedLink))
      {
        fconsole.endl('[skip] Has non-css or not url() references');
        continue;
      }

      //
      // inline
      //

      var fileBase64Content = new Buffer(file.content, 'binary').toString('base64');
      var mimeType = mime.lookup(file.relpath);

      // replace refences
      fconsole.start('Replace references in css');
      for (var j = 0; j < file.linkBack.length; j++)
      {
        var cssToken = file.linkBack[j][1];

        // remove link from resource links
        flow.resLinks.some(function(link, idx){
          if (link.token === cssToken)
          {
            flow.resLinks.splice(idx, 1);
            return true;
          }
        });

        // replace reference to dataURI
        fconsole.log(file.linkBack[j][0].relpath);
        atCss.Url('data:' + mimeType + ';base64,' + fileBase64Content, cssToken);
      }
      fconsole.end();

      // remove from output
      fconsole.log('Remove file from output');
      flow.files.remove(file);

      // end
      fconsole.endl();
    }
  }

}).handlerName = '[res] Inline to base64';

module.exports.skip = function(flow){
  var quota = flow.options.cssInlineImage;

  if (isNaN(quota) || quota <= 0)
    return 'Use option --css-inline-image to set max size of image to be inlined';
};
<commit_msg>fixed mime usage that crashed a build<commit_after>var atCss = require('basisjs-tools-ast').css;
var mime = require('mime');

function unsupportedLink(link){
  return (link[0].type != 'style' && link[0].type != 'style-block') ||
         link[1].type != 'Url';
};

(module.exports = function(flow){
  var fconsole = flow.console;
  var quota = flow.options.cssInlineImage;

  fconsole.log('Inline resources less ' + quota + ' bytes\n');

  for (var i = flow.files.queue.length - 1, file; file = flow.files.queue[i]; i--)
  {
    if (file.type == 'image')
    {
      fconsole.start(file.relpath);

      if (file.content.length > quota)
      {
        fconsole.endl('[skip] Too big (' + file.content.length + ' bytes)');
        continue;
      }

      if (file.linkBack.some(unsupportedLink))
      {
        fconsole.endl('[skip] Has non-css or not url() references');
        continue;
      }

      //
      // inline
      //

      var fileBase64Content = new Buffer(file.content, 'binary').toString('base64');
      var mimeType = mime.getType(file.relpath);

      // replace refences
      fconsole.start('Replace references in css');
      for (var j = 0; j < file.linkBack.length; j++)
      {
        var cssToken = file.linkBack[j][1];

        // remove link from resource links
        flow.resLinks.some(function(link, idx){
          if (link.token === cssToken)
          {
            flow.resLinks.splice(idx, 1);
            return true;
          }
        });

        // replace reference to dataURI
        fconsole.log(file.linkBack[j][0].relpath);
        atCss.Url('data:' + mimeType + ';base64,' + fileBase64Content, cssToken);
      }
      fconsole.end();

      // remove from output
      fconsole.log('Remove file from output');
      flow.files.remove(file);

      // end
      fconsole.endl();
    }
  }

}).handlerName = '[res] Inline to base64';

module.exports.skip = function(flow){
  var quota = flow.options.cssInlineImage;

  if (isNaN(quota) || quota <= 0)
    return 'Use option --css-inline-image to set max size of image to be inlined';
};
<|endoftext|>


<commit_before>define([
    'jquery',
    "underscore",
    'moment',
    'date_filter',
    'slider_filter',
    'text_filter'
], function ($, _, moment, date_filter, slider_filter, text_filter) {
  "use strict";

  var dependencies_loaded = false;
  var grids_to_initialize = []

  var QGrid = function (grid_elem_selector, data_frame, column_types) {
    this.grid_elem_selector = grid_elem_selector;
    this.grid_elem = $(this.grid_elem_selector)
    this.data_frame = data_frame;

    this.row_data = [];
    this.columns = [];
    this.filters = {};
    this.filter_list = [];
    this.sort_field = "id";
    this.sort_ascending = true;

    this.python_types = {
      Character: "text",
      Float: "number",
      Complex: "number",
      Datetime: "date",
      Integer: "number",
      UnsignedInteger: "number"
    };

    var self = this;

    if (column_types.length > 0) {
      for (var i = 0; i < column_types.length; i++){
        var cur_column = column_types[i];

        if (!cur_column.type){
          cur_column.type = "text";
        }else{
          cur_column.type = this.python_types[cur_column.type];
        }

        if (i === 0){
          this.sort_field = cur_column.field;
        }

        cur_column = {
          name: cur_column.field,
          field: cur_column.field,
          id: cur_column.field,
          type: cur_column.type,
          formatter: this["format_" + cur_column.type],
          sortable: true,
          resizable: true
        };

        var filter_generator = this["create_" + cur_column.type + "_filter"];
        if (filter_generator){
          var cur_filter = filter_generator(cur_column.field);
          $(cur_filter).on("filter_changed", $.proxy(this.handle_filter_changed, this))
          this.filters[cur_column.id] = cur_filter;
          this.filter_list.push(cur_filter);
        }

        this.columns.push(cur_column);
      }
    }

    var row_count = 0;
    _.each(this.data_frame, function (cur_row, key, list) {
      cur_row.id = "row" + row_count;
      row_count++;
      this.row_data.push(cur_row);
      this.filter_list.forEach(function(cur_filter){
        cur_filter.handle_row_data(cur_row);
      }, this);
    }, this);
  }

  QGrid.prototype.initialize_slick_grid = function (options) {
    this.data_view = new Slick.Data.DataView({
      inlineFilters: false,
      enableTextSelectionOnCells: true
    })

    this.data_view.beginUpdate();
    var sort_comparer = this.get_sort_comparer(this.sort_field, this.sort_ascending)
    this.data_view.sort(sort_comparer, this.sort_ascending);
    this.data_view.setItems(this.row_data);
    this.data_view.setFilter($.proxy(this.include_row, this));
    this.data_view.endUpdate();

    var max_height = options.rowHeight * 15;
    var grid_height = max_height;
    // totalRowHeight is how tall the grid would have to be to fit all of the rows in the dataframe.
    // The '+ 1' accounts for the height of the column header.
    var total_row_height = (this.row_data.length + 1) * options.rowHeight + 1;
    if (total_row_height <= max_height){
      grid_height = total_row_height;
      this.grid_elem.addClass('hide-scrollbar');
    }
    this.grid_elem.height(grid_height);

    if (this.columns.length < 5){
      this.grid_elem.width(this.columns.length * 200);
    }

    this.slick_grid = new Slick.Grid(this.grid_elem_selector, this.data_view, this.columns, options);
    this.slick_grid.setSelectionModel(new Slick.RowSelectionModel())
    this.update_sort_indicators();
    this.slick_grid.render();

    this.slick_grid.onSort.subscribe($.proxy(this.handle_sort_changed, this));
    this.slick_grid.onHeaderCellRendered.subscribe($.proxy(this.handle_header_cell_rendered, this))

    // Force the grid to re-render the column headers so the onHeaderCellRendered event is triggered.
    this.slick_grid.setColumns(this.slick_grid.getColumns());

    var self = this;
    this.data_view.onRowCountChanged.subscribe(function(e, args){
      self.slick_grid.updateRowCount();
      self.slick_grid.render();
    });

    this.data_view.onRowsChanged.subscribe(function(e, args){
      self.slick_grid.invalidateRows(args.rows)
      self.slick_grid.render()
    });

    $(window).resize(function(){
      self.slick_grid.resizeCanvas();
    });
  }

  QGrid.prototype.handle_filter_changed = function(e, exclude_this_filter){
    var show_clear_filter_button = false;
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      var filter_button = cur_filter.column_header_elem.find(".filter-button");
      if (cur_filter.is_active()){
        show_clear_filter_button = true;
        filter_button.addClass("filter-active");
      }
      else {
        filter_button.removeClass("filter-active");
      }
    }
//    if (show_clear_filter_button){
//      this.tab_elem.find(".clear-filters").show();
//    }
//    else {
//      this.tab_elem.find(".clear-filters").hide();
//    }

    this.apply_filters(exclude_this_filter ? e.target : null)
  }

  QGrid.prototype.apply_filters = function(excluded_filter){
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if ((cur_filter instanceof slider_filter.SliderFilter)  && cur_filter != excluded_filter){
        cur_filter.reset_min_max();
      }
    }
    this.data_view.refresh();
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if ((cur_filter instanceof slider_filter.SliderFilter) && cur_filter != excluded_filter){
        cur_filter.handle_filtering_done();
      }
    }
  }

  QGrid.prototype.include_row = function(item, args){
    item.include = true;
    item.excluded_by = {};
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if (!cur_filter.include_item(item)){
        item.include = false;
        item.excluded_by[cur_filter.field] = true;
      }
    }

    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if (cur_filter instanceof slider_filter.SliderFilter){
        cur_filter.update_min_max(item);
      }
    }

    return item.include;
  }

  QGrid.prototype.handle_sort_changed = function(e, args){
    this.sort_field = args.sortCol.field;
    this.sort_ascending = args.sortAsc;

    var sort_comparer = this.get_sort_comparer(this.sort_field, this.sort_ascending);
    this.data_view.sort(sort_comparer, this.sort_ascending);
  }

  QGrid.prototype.update_sort_indicators = function(){
    this.slick_grid.setSortColumns([ {columnId: this.sort_field, sortAsc: this.sort_ascending} ]);
  }

  QGrid.prototype.get_sort_comparer = function(field, ascending){
    return function(x, y){
      var x_value = x[field];
      var y_value = y[field];

      return (x_value > y_value) ? 1 : -1;
    }
  }

  QGrid.prototype.handle_header_cell_rendered = function(e, args){
    var cur_filter = this.filters[args.column.id];
    if (cur_filter){
      $.proxy(cur_filter.render_filter_button($(args.node), this.slick_grid), cur_filter);
    }
  }

  QGrid.prototype.format_date = function(row, cell, value, columnDef, dataContext){
    var date = new Date(value);
    return moment(date).format("YYYY-MM-DD");
  }

  QGrid.prototype.format_string = function(row, cell, value, columnDef, dataContext){
    return value;
  }

  QGrid.prototype.format_number = function(row, cell, value, columnDef, dataContext){
    return value;
  }

  QGrid.prototype.create_date_filter = function(field){
    return new date_filter.DateFilter(field);
  }

  QGrid.prototype.create_number_filter = function(field){
    return new slider_filter.SliderFilter(field);
  }

  QGrid.prototype.create_text_filter = function(field){
    return new text_filter.TextFilter(field);
  }

//
//  QGrid.prototype.create_ticker_filter = function(field){
//    return new quanto.SecurityFilter(@$tab_elem, field);
//  }
//
//  QGrid.prototype.format_money = function(row, cell, value, columnDef, dataContext){
//    if (!value.value)
//      return "- -";
//    else
//      return "#{quanto.safe_to_money(value)}";
//  }

//  QGrid.prototype.format_total = function(totals, columnDef){
//    val = totals.sum.value ? totals.sum[columnDef.field] : null;
//    if (val.value)
//      return "total:#{quanto.safe_to_money(val)}";
//    return "- -";
//  }

  return { "QGrid": QGrid };

});
<commit_msg>Update qgrid.js<commit_after>define([
    'jquery',
    "underscore",
    'moment',
    'date_filter',
    'slider_filter',
    'text_filter'
], function ($, _, moment, date_filter, slider_filter, text_filter) {
  "use strict";

  var dependencies_loaded = false;
  var grids_to_initialize = []

  var QGrid = function (grid_elem_selector, data_frame, column_types) {
    this.grid_elem_selector = grid_elem_selector;
    this.grid_elem = $(this.grid_elem_selector)
    this.data_frame = data_frame;

    this.row_data = [];
    this.columns = [];
    this.filters = {};
    this.filter_list = [];
    this.sort_field = "id";
    this.sort_ascending = true;

    this.python_types = {
      Character: "text",
      Float: "number",
      Complex: "number",
      Datetime: "date",
      Integer: "number",
      UnsignedInteger: "number"
    };

    var self = this;

    if (column_types.length > 0) {
      for (var i = 0; i < column_types.length; i++){
        var cur_column = column_types[i];

        if (!cur_column.type){
          cur_column.type = "text";
        }else{
          cur_column.type = this.python_types[cur_column.type];
        }

        if (i === 0){
          this.sort_field = cur_column.field;
        }

        cur_column = {
          name: cur_column.field,
          field: cur_column.field,
          id: cur_column.field,
          type: cur_column.type,
          formatter: this["format_" + cur_column.type],
          sortable: true,
          resizable: true
        };

        var filter_generator = this["create_" + cur_column.type + "_filter"];
        if (filter_generator){
          var cur_filter = filter_generator(cur_column.field);
          $(cur_filter).on("filter_changed", $.proxy(this.handle_filter_changed, this))
          this.filters[cur_column.id] = cur_filter;
          this.filter_list.push(cur_filter);
        }

        this.columns.push(cur_column);
      }
    }

    var row_count = 0;
    _.each(this.data_frame, function (cur_row, key, list) {
      cur_row.slick_grid_id = "row" + row_count;
      row_count++;
      this.row_data.push(cur_row);
      this.filter_list.forEach(function(cur_filter){
        cur_filter.handle_row_data(cur_row);
      }, this);
    }, this);
  }

  QGrid.prototype.initialize_slick_grid = function (options) {
    this.data_view = new Slick.Data.DataView({
      inlineFilters: false,
      enableTextSelectionOnCells: true
    })

    this.data_view.beginUpdate();
    var sort_comparer = this.get_sort_comparer(this.sort_field, this.sort_ascending)
    this.data_view.sort(sort_comparer, this.sort_ascending);
    this.data_view.setItems(this.row_data, 'slick_grid_id');
    this.data_view.setFilter($.proxy(this.include_row, this));
    this.data_view.endUpdate();

    var max_height = options.rowHeight * 15;
    var grid_height = max_height;
    // totalRowHeight is how tall the grid would have to be to fit all of the rows in the dataframe.
    // The '+ 1' accounts for the height of the column header.
    var total_row_height = (this.row_data.length + 1) * options.rowHeight + 1;
    if (total_row_height <= max_height){
      grid_height = total_row_height;
      this.grid_elem.addClass('hide-scrollbar');
    }
    this.grid_elem.height(grid_height);

    if (this.columns.length < 5){
      this.grid_elem.width(this.columns.length * 200);
    }

    this.slick_grid = new Slick.Grid(this.grid_elem_selector, this.data_view, this.columns, options);
    this.slick_grid.setSelectionModel(new Slick.RowSelectionModel())
    this.update_sort_indicators();
    this.slick_grid.render();

    this.slick_grid.onSort.subscribe($.proxy(this.handle_sort_changed, this));
    this.slick_grid.onHeaderCellRendered.subscribe($.proxy(this.handle_header_cell_rendered, this))

    // Force the grid to re-render the column headers so the onHeaderCellRendered event is triggered.
    this.slick_grid.setColumns(this.slick_grid.getColumns());

    var self = this;
    this.data_view.onRowCountChanged.subscribe(function(e, args){
      self.slick_grid.updateRowCount();
      self.slick_grid.render();
    });

    this.data_view.onRowsChanged.subscribe(function(e, args){
      self.slick_grid.invalidateRows(args.rows)
      self.slick_grid.render()
    });

    $(window).resize(function(){
      self.slick_grid.resizeCanvas();
    });
  }

  QGrid.prototype.handle_filter_changed = function(e, exclude_this_filter){
    var show_clear_filter_button = false;
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      var filter_button = cur_filter.column_header_elem.find(".filter-button");
      if (cur_filter.is_active()){
        show_clear_filter_button = true;
        filter_button.addClass("filter-active");
      }
      else {
        filter_button.removeClass("filter-active");
      }
    }
//    if (show_clear_filter_button){
//      this.tab_elem.find(".clear-filters").show();
//    }
//    else {
//      this.tab_elem.find(".clear-filters").hide();
//    }

    this.apply_filters(exclude_this_filter ? e.target : null)
  }

  QGrid.prototype.apply_filters = function(excluded_filter){
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if ((cur_filter instanceof slider_filter.SliderFilter)  && cur_filter != excluded_filter){
        cur_filter.reset_min_max();
      }
    }
    this.data_view.refresh();
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if ((cur_filter instanceof slider_filter.SliderFilter) && cur_filter != excluded_filter){
        cur_filter.handle_filtering_done();
      }
    }
  }

  QGrid.prototype.include_row = function(item, args){
    item.include = true;
    item.excluded_by = {};
    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if (!cur_filter.include_item(item)){
        item.include = false;
        item.excluded_by[cur_filter.field] = true;
      }
    }

    for (var i=0; i < this.filter_list.length; i++){
      var cur_filter = this.filter_list[i];
      if (cur_filter instanceof slider_filter.SliderFilter){
        cur_filter.update_min_max(item);
      }
    }

    return item.include;
  }

  QGrid.prototype.handle_sort_changed = function(e, args){
    this.sort_field = args.sortCol.field;
    this.sort_ascending = args.sortAsc;

    var sort_comparer = this.get_sort_comparer(this.sort_field, this.sort_ascending);
    this.data_view.sort(sort_comparer, this.sort_ascending);
  }

  QGrid.prototype.update_sort_indicators = function(){
    this.slick_grid.setSortColumns([ {columnId: this.sort_field, sortAsc: this.sort_ascending} ]);
  }

  QGrid.prototype.get_sort_comparer = function(field, ascending){
    return function(x, y){
      var x_value = x[field];
      var y_value = y[field];

      return (x_value > y_value) ? 1 : -1;
    }
  }

  QGrid.prototype.handle_header_cell_rendered = function(e, args){
    var cur_filter = this.filters[args.column.id];
    if (cur_filter){
      $.proxy(cur_filter.render_filter_button($(args.node), this.slick_grid), cur_filter);
    }
  }

  QGrid.prototype.format_date = function(row, cell, value, columnDef, dataContext){
    var date = new Date(value);
    return moment(date).format("YYYY-MM-DD");
  }

  QGrid.prototype.format_string = function(row, cell, value, columnDef, dataContext){
    return value;
  }

  QGrid.prototype.format_number = function(row, cell, value, columnDef, dataContext){
    return value;
  }

  QGrid.prototype.create_date_filter = function(field){
    return new date_filter.DateFilter(field);
  }

  QGrid.prototype.create_number_filter = function(field){
    return new slider_filter.SliderFilter(field);
  }

  QGrid.prototype.create_text_filter = function(field){
    return new text_filter.TextFilter(field);
  }

//
//  QGrid.prototype.create_ticker_filter = function(field){
//    return new quanto.SecurityFilter(@$tab_elem, field);
//  }
//
//  QGrid.prototype.format_money = function(row, cell, value, columnDef, dataContext){
//    if (!value.value)
//      return "- -";
//    else
//      return "#{quanto.safe_to_money(value)}";
//  }

//  QGrid.prototype.format_total = function(totals, columnDef){
//    val = totals.sum.value ? totals.sum[columnDef.field] : null;
//    if (val.value)
//      return "total:#{quanto.safe_to_money(val)}";
//    return "- -";
//  }

  return { "QGrid": QGrid };

});
<|endoftext|>


<commit_before>(function(global) {
  "use strict;"

  var VdomBuilder = function VdomBuilder(component, formName) {
    this.component = component;
    this.formName = formName;
    this.h = virtualDom.h;
    this.elements = [];
  };

  $.extend(VdomBuilder.prototype, {
    markup: function(callback) {
      var root = this.component.root, formName, builder, attributes;

      if (typeof callback !== 'function')
        throw new Error("The first agument must be a function.");
      if (callback.length === 0)
        throw new Error("Callback requires an argument.");
      if (root.tagName == 'form') formName = root.attributes.name;
      builder = new VdomBuilder(this.component, formName);
      callback.call(this.component, builder);

      attributes = {};
      for (var i = 0, len = root.attributes.length; i < len; i++)
        attributes[root.attributes[i].nodeName] = root.attributes[i].value;
      return this.h(root.tagName, attributes, builder.elements);
    },
    elem: function(tagName) {
      var args, options, content, callback, builder;

      args = Array.prototype.slice.call(arguments, 1);
      content = extractContent(args);
      options = extractOptions(args);
      callback = extractCallback(args);

      if (callback) {
        builder = new VdomBuilder(this.component, this.formName);
        if (callback.length === 0) { throw new Error("Callback requires an argument.") }
        callback.call(this.component, builder);
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, builder.elements));
      }
      else {
        content = content || '';
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, content));
      }
      return this;
    },
    text: function(content) {
      this.elements.push(content);
      return this;
    },
    space: function() {
      this.elements.push(' ');
      return this;
    },
    form: function(options, callback) {
      var name, builder, attributes;

      if (callback.length === 0) { throw new Error("Callback requires an argument.") }
      name = options.name || '';
      builder = new VdomBuilder(this.component, name);
      callback.call(this.component, builder);
      options = options || {};
      if (options.onsubmit === undefined) {
        options.onsubmit = function(e) { return false };
      }
      attributes = generateAttributes(options);
      this.elements.push(this.h('form', attributes, builder.elements));
      return this;
    },
    labelFor: function(id, content, options) {
      options = options || {};
      options.htmlFor = id;
      this.element('label', content, options)
      return this;
    },
    input: function(options) {
      var form, name, value;

      options = options || {};
      name = options.name;
      value = options.value;
      if (value === undefined && name !== undefined && this.formName !== undefined)
        options.value = this.component.getValue(this.formName + '.' + name);
      attributes = generateAttributes(options);
      this.elements.push(this.h('input', attributes));
      return this;
    },
    hiddenField: function(name, options) {
      options = options || {};
      options.type = 'hidden';
      options.name = name;
      this.input(options);
      return this;
    },
    textField: function(name, options) {
      options = options || {};
      options.type = 'text';
      options.name = name;
      this.input(options);
      return this;
    },
    textarea: function(name, options) {
      var value = this.component.getValue(this.formName + '.' + name);
      options.name = name;
      this.element('textarea', value, options);
      return this;
    },
    checkBox: function(attrName, options) {
      var checked = this.component.getValue(this.formName + '.' + attrName);

      options = options || {};
      options.type = 'checkbox';
      if (attrName) options.name = attrName;
      if (checked) options.checked = 'checked';
      if (!options.value) options.value = '1';
      this.input($.extend({}, options, { type: 'hidden', value: '0' }));
      this.input(options);
      return this;
    },
    radioButton: function(attrName, options) {
      var value = this.component.getValue(this.formName + '.' + attrName);

      options = options || {};
      options.type = 'radio';
      if (attrName) options.name = attrName;
      if (options.value === value) options.checked = 'checked';
      this.input(options);
      return this;
    },
    faIcon: function(iconName) {
      this.i('', { class: 'fa fa-' + iconName});
      return this;
    }
  });

  function extractContent(args) {
    if (typeof args[0] === 'string') return args[0];
  }

  function extractOptions(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'object') return args[i];
  }

  function extractCallback(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'function') return args[i];
  }

  function generateAttributes(options) {
    options = options || {};
    if ('visible' in options && !options['visible']) {
      options['style'] = options['style'] || {};
      options['style']['display'] = 'none';
    }
    if ('class' in options) {
      options['className'] = options['class'];
      delete options['class'];
    }
    if ('for' in options) {
      options['htmlFor'] = options['for'];
      delete options['for'];
    }
    if (typeof options['className'] === 'object') {
      var names = []
      for (var name in options['className']) {
        if (options['className'][name]) {
          names.push(name)
        }
      }
      if (names.length) {
        options['className'] = names.join(' ')
      }
      else {
        delete options['className'];
      }
    }
    return options;
  }

  var normalElementNames = [
    'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
    'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code',
    'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div',
    'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'html',
    'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark',
    'menu', 'menuitem', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup',
    'option', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's',
    'samp', 'script', 'section', 'select', 'small', 'span', 'strong', 'style',
    'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot',
    'th', 'thead', 'time', 'title', 'tr', 'u', 'ul', 'var', 'video' ];

  for (var i = 0; i < normalElementNames.length; i++) {
    var tagName = normalElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("arg1", "arg2",
      "this.elem('" + tagName + "', arg1, arg2); return this");
  }

  var voidElementNames = [
    'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'keygen',
    'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'
  ]

  for (var i = 0; i < voidElementNames.length; i++) {
    var tagName = voidElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("options",
      "this.elem('" + tagName + "', options); return this");
  }

  if (!global.CapeJS) {
    var CapeJS = {};
    if ("process" in global) module.exports = CapeJS;
    global.CapeJS = CapeJS;
  }
  global.CapeJS.VdomBuilder = VdomBuilder;

})((this || 0).self || global);
<commit_msg>Bug fix: replace element with elem<commit_after>(function(global) {
  "use strict;"

  var VdomBuilder = function VdomBuilder(component, formName) {
    this.component = component;
    this.formName = formName;
    this.h = virtualDom.h;
    this.elements = [];
  };

  $.extend(VdomBuilder.prototype, {
    markup: function(callback) {
      var root = this.component.root, formName, builder, attributes;

      if (typeof callback !== 'function')
        throw new Error("The first agument must be a function.");
      if (callback.length === 0)
        throw new Error("Callback requires an argument.");
      if (root.tagName == 'form') formName = root.attributes.name;
      builder = new VdomBuilder(this.component, formName);
      callback.call(this.component, builder);

      attributes = {};
      for (var i = 0, len = root.attributes.length; i < len; i++)
        attributes[root.attributes[i].nodeName] = root.attributes[i].value;
      return this.h(root.tagName, attributes, builder.elements);
    },
    elem: function(tagName) {
      var args, options, content, callback, builder;

      args = Array.prototype.slice.call(arguments, 1);
      content = extractContent(args);
      options = extractOptions(args);
      callback = extractCallback(args);

      if (callback) {
        builder = new VdomBuilder(this.component, this.formName);
        if (callback.length === 0) { throw new Error("Callback requires an argument.") }
        callback.call(this.component, builder);
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, builder.elements));
      }
      else {
        content = content || '';
        attributes = generateAttributes(options);
        this.elements.push(this.h(tagName, attributes, content));
      }
      return this;
    },
    text: function(content) {
      this.elements.push(content);
      return this;
    },
    space: function() {
      this.elements.push(' ');
      return this;
    },
    form: function(options, callback) {
      var name, builder, attributes;

      if (callback.length === 0) { throw new Error("Callback requires an argument.") }
      name = options.name || '';
      builder = new VdomBuilder(this.component, name);
      callback.call(this.component, builder);
      options = options || {};
      if (options.onsubmit === undefined) {
        options.onsubmit = function(e) { return false };
      }
      attributes = generateAttributes(options);
      this.elements.push(this.h('form', attributes, builder.elements));
      return this;
    },
    labelFor: function(id, content, options) {
      options = options || {};
      options.htmlFor = id;
      this.elem('label', content, options)
      return this;
    },
    input: function(options) {
      var form, name, value;

      options = options || {};
      name = options.name;
      value = options.value;
      if (value === undefined && name !== undefined && this.formName !== undefined)
        options.value = this.component.getValue(this.formName + '.' + name);
      attributes = generateAttributes(options);
      this.elements.push(this.h('input', attributes));
      return this;
    },
    hiddenField: function(name, options) {
      options = options || {};
      options.type = 'hidden';
      options.name = name;
      this.input(options);
      return this;
    },
    textField: function(name, options) {
      options = options || {};
      options.type = 'text';
      options.name = name;
      this.input(options);
      return this;
    },
    textarea: function(name, options) {
      var value = this.component.getValue(this.formName + '.' + name);
      options.name = name;
      this.elem('textarea', value, options);
      return this;
    },
    checkBox: function(attrName, options) {
      var checked = this.component.getValue(this.formName + '.' + attrName);

      options = options || {};
      options.type = 'checkbox';
      if (attrName) options.name = attrName;
      if (checked) options.checked = 'checked';
      if (!options.value) options.value = '1';
      this.input($.extend({}, options, { type: 'hidden', value: '0' }));
      this.input(options);
      return this;
    },
    radioButton: function(attrName, options) {
      var value = this.component.getValue(this.formName + '.' + attrName);

      options = options || {};
      options.type = 'radio';
      if (attrName) options.name = attrName;
      if (options.value === value) options.checked = 'checked';
      this.input(options);
      return this;
    },
    faIcon: function(iconName) {
      this.i('', { class: 'fa fa-' + iconName});
      return this;
    }
  });

  function extractContent(args) {
    if (typeof args[0] === 'string') return args[0];
  }

  function extractOptions(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'object') return args[i];
  }

  function extractCallback(args) {
    for (var i = 0; i < args.length; i++)
      if (typeof args[i] === 'function') return args[i];
  }

  function generateAttributes(options) {
    options = options || {};
    if ('visible' in options && !options['visible']) {
      options['style'] = options['style'] || {};
      options['style']['display'] = 'none';
    }
    if ('class' in options) {
      options['className'] = options['class'];
      delete options['class'];
    }
    if ('for' in options) {
      options['htmlFor'] = options['for'];
      delete options['for'];
    }
    if (typeof options['className'] === 'object') {
      var names = []
      for (var name in options['className']) {
        if (options['className'][name]) {
          names.push(name)
        }
      }
      if (names.length) {
        options['className'] = names.join(' ')
      }
      else {
        delete options['className'];
      }
    }
    return options;
  }

  var normalElementNames = [
    'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo',
    'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code',
    'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div',
    'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'html',
    'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark',
    'menu', 'menuitem', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup',
    'option', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's',
    'samp', 'script', 'section', 'select', 'small', 'span', 'strong', 'style',
    'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot',
    'th', 'thead', 'time', 'title', 'tr', 'u', 'ul', 'var', 'video' ];

  for (var i = 0; i < normalElementNames.length; i++) {
    var tagName = normalElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("arg1", "arg2",
      "this.elem('" + tagName + "', arg1, arg2); return this");
  }

  var voidElementNames = [
    'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'keygen',
    'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'
  ]

  for (var i = 0; i < voidElementNames.length; i++) {
    var tagName = voidElementNames[i];
    VdomBuilder.prototype[tagName] = new Function("options",
      "this.elem('" + tagName + "', options); return this");
  }

  if (!global.CapeJS) {
    var CapeJS = {};
    if ("process" in global) module.exports = CapeJS;
    global.CapeJS = CapeJS;
  }
  global.CapeJS.VdomBuilder = VdomBuilder;

})((this || 0).self || global);
<|endoftext|>


<commit_before>FLOW.MonitoringDataTableView = FLOW.View.extend({
  showingDetailsDialog: false,
  cursorStart: null,

  pageNumber: function(){
	return FLOW.router.surveyedLocaleController.get('pageNumber');
  }.property('FLOW.router.surveyedLocaleController.pageNumber'),

  showDetailsDialog: function (evt) {
	FLOW.surveyInstanceControl.set('content', FLOW.store.findQuery(FLOW.SurveyInstance, {
		surveyedLocaleId: evt.context.get('keyId')
	}));
    this.toggleProperty('showingDetailsDialog');
  },

  showApprovalStatusColumn: function () {
      return FLOW.Env.enableDataApproval;
  }.property(),

  closeDetailsDialog: function () {
    this.toggleProperty('showingDetailsDialog');
  },

  showSurveyInstanceDetails: function (evt) {
    FLOW.questionAnswerControl.doQuestionAnswerQuery(evt.context.get('keyId'));
    $('.si_details').hide();
    $('tr[data-flow-id="si_details_' + evt.context.get('keyId') + '"]').show();
  },

  findSurveyedLocale: function (evt) {
	  var ident = this.get('identifier'),
	      displayName = this.get('displayName'),
	      sgId = FLOW.selectedControl.get('selectedSurveyGroup'),
	      cursorType = FLOW.metaControl.get('cursorType'),
        criteria = {};

	  if (ident) {
		  criteria.identifier = ident;
	  }

	  if (displayName) {
		  criteria.displayName = displayName;
	  }

	  if (sgId) {
		  criteria.surveyGroupId = sgId.get('keyId');
	  }

	  if (this.get('cursorStart')) {
		criteria.since = this.get('cursorStart');
	  }
      FLOW.router.surveyedLocaleController.populate(criteria);
      if(Ember.empty(FLOW.router.userListController.get('content'))) {
          FLOW.router.userListController.set('content', FLOW.User.find());
      }
  },

  doNextPage: function () {
	var cursorArray, cursorStart;
	cursorArray = FLOW.router.surveyedLocaleController.get('sinceArray');
	cursorStart = cursorArray.length > 0 ? cursorArray[cursorArray.length - 1] : null;
	this.set('cursorStart', cursorStart);
    this.findSurveyedLocale();
    FLOW.router.surveyedLocaleController.set('pageNumber', FLOW.router.surveyedLocaleController.get('pageNumber') + 1);
  },

  doPrevPage: function () {
	var cursorArray, cursorStart;
	cursorArray = FLOW.router.surveyedLocaleController.get('sinceArray');
	cursorStart = cursorArray.length - 3 > -1 ? cursorArray[cursorArray.length - 3] : null;
	this.set('cursorStart', cursorStart);
    this.findSurveyedLocale();
    FLOW.router.surveyedLocaleController.set('pageNumber', FLOW.router.surveyedLocaleController.get('pageNumber') - 1);
  },

  hasNextPage: function () {
    return FLOW.metaControl.get('numSLLoaded') == 20;
  }.property('FLOW.metaControl.numSLLoaded'),

  hasPrevPage: function () {
    return FLOW.router.surveyedLocaleController.get('pageNumber');
  }.property('FLOW.router.surveyedLocaleController.pageNumber'),
});

/**
 * View of each row/data point in the monitoring data tab
 */
FLOW.DataPointView = FLOW.View.extend({
    templateName: 'navData/monitoring-data-row',

    approvalStatus: [{label: Ember.String.loc('_pending'), value: 'PENDING'}, { label: Ember.String.loc('_approved'), value: 'APPROVED' },{ label: Ember.String.loc('_rejected'), value: 'REJECTED'}],

    showDataApprovalBlock: false,

    showSurveyedLocaleDeleteButton: function() {
        return FLOW.router.surveyedLocaleController.get('userCanDelete');
    }.property(),

    showApprovalStatusColumn: function () {
        return this.get('parentView').get('showApprovalStatusColumn');
    }.property(),

    dataPointApprovals: function () {
        var approvals = FLOW.router.dataPointApprovalController.get('content');
        if(!approvals) {
            return;
        }

        var surveyedLocaleId = this.content && this.content.get('keyId');
        return approvals.filterProperty('surveyedLocaleId', surveyedLocaleId);
    }.property('FLOW.router.dataPointApprovalController.content.@each'),

    /*
     * get the next approval step id
     */
    nextApprovalStepId: function () {
        return this.get('nextApprovalStep') && this.get('nextApprovalStep').get('keyId');
    }.property('this.nextApprovalStep'),

    /*
     * Derive the next approval step (in ordered approvals)
     */
    nextApprovalStep: function () {
        var approvals = this.get('dataPointApprovals');
        var steps = FLOW.router.approvalStepsController.get('arrangedContent');
        var lastApprovedStepOrder = -1;

        approvals.forEach(function (approval) {
            var step = steps.filterProperty('keyId',
                                approval.get('approvalStepId')).get('firstObject');
            if (approval.get('status') === 'APPROVED' &&
                    step && (step.get('order') > lastApprovedStepOrder)) {
                lastApprovedStepOrder = step.get('order');
            }
        });

        var nextStep = steps.filterProperty('order', ++lastApprovedStepOrder).get('firstObject');
        return nextStep;

    // NOTE: below we observe the '@each.approvalDate' in order to be
    // sure that we only recalculate the next step whenever the approval
    //  has been correctly updated on the server side
    }.property('this.dataPointApprovals.@each.approvalDate'),

    /*
     * return true if there are any of the approvals rejected in this set
     */
    hasRejectedApproval: function () {
        var approvals = this.get('dataPointApprovals');
        return !Ember.empty(approvals.filterProperty('status', 'REJECTED'));
    }.property('this.dataPointApprovals'),

    loadDataPointApprovalObserver: function () {
        if(!this.get('showDataApprovalBlock')) {
            return; // do nothing when hiding approval block
        }

        var dataPoint = this.get('content');
        if (dataPoint) {
            FLOW.router.dataPointApprovalController.loadBySurveyedLocaleId(dataPoint.get('keyId'));
        }
    }.observes('this.showDataApprovalBlock'),

    toggleShowDataApprovalBlock: function () {
        this.toggleProperty('showDataApprovalBlock');
    },
});

/**
 * View to render the status of a data point in the approval
 * status cell of each data point / row
 */
FLOW.DataPointApprovalStatusView = FLOW.View.extend({
    content: null,

    latestApprovalStepTitle: function () {
        var nextStepId = this.get('parentView').get('nextApprovalStepId');
        var stepsController = FLOW.router.get('approvalStepsController');
        var step = stepsController.filterProperty('keyId', nextStepId).get('firstObject');
        return step && step.get('title');
    }.property('this.parentView.nextApprovalStepId'),
});

/**
 * The data approval view for each approval step of a data point
 */
FLOW.DataPointApprovalView = FLOW.View.extend({
    step: null,

    dataPoint: null,

    dataPointApproval: function () {
        var approvals = this.get('parentView').get('dataPointApprovals');
        var defaultApproval = Ember.Object.create({ status: null, comment: null});

        if(Ember.empty(approvals)) {
            return defaultApproval;
        }

        var stepId = this.step && this.step.get('keyId');
        var approval = approvals.filterProperty('approvalStepId', stepId).get('firstObject');

        return approval || defaultApproval;
    }.property('this.parentView.dataPointApprovals'),

    isApprovedStep: function () {
        var dataPointApproval = this.get('dataPointApproval');
        return dataPointApproval && dataPointApproval.get('keyId');
    }.property('this.dataPointApproval'),

    /*
     * Enable the approval fields based on whether or not approval steps
     * should be executed in order
     */
    showApprovalFields: function () {
        if(this.get('parentView').get('hasRejectedApproval')) {
            return false;
        }

        var approvalGroup = FLOW.router.approvalGroupController.get('content');
        if(approvalGroup && approvalGroup.get('ordered')) {
            var nextStepId = this.get('parentView').get('nextApprovalStepId');
            if (nextStepId) {
                return this.step.get('keyId') === nextStepId;
            } else {
                return false;
            }
        } else {
            // this is for unordered approval steps. show fields for
            // all steps so that its possible to approve any step
            return true;
        }
    }.property('this.parentView.nextApprovalStep'),

    /*
     *  Submit data approval properties to controller
     */
    submitDataPointApproval: function (event) {

        var dataPointApproval = this.get('dataPointApproval');
        if(dataPointApproval.get('keyId')) {
            FLOW.router.dataPointApprovalController.update(dataPointApproval);
        } else {
            dataPointApproval.surveyedLocaleId = this.get('dataPoint').get('keyId');
            dataPointApproval.approvalStepId = this.get('step').get('keyId');
            dataPointApproval.approverUserName = null;

            FLOW.router.dataPointApprovalController.add(dataPointApproval);
        }
    },
});<commit_msg>[#1774] Take into account the current user id when enabling submitting approval<commit_after>FLOW.MonitoringDataTableView = FLOW.View.extend({
  showingDetailsDialog: false,
  cursorStart: null,

  pageNumber: function(){
	return FLOW.router.surveyedLocaleController.get('pageNumber');
  }.property('FLOW.router.surveyedLocaleController.pageNumber'),

  showDetailsDialog: function (evt) {
	FLOW.surveyInstanceControl.set('content', FLOW.store.findQuery(FLOW.SurveyInstance, {
		surveyedLocaleId: evt.context.get('keyId')
	}));
    this.toggleProperty('showingDetailsDialog');
  },

  showApprovalStatusColumn: function () {
      return FLOW.Env.enableDataApproval;
  }.property(),

  closeDetailsDialog: function () {
    this.toggleProperty('showingDetailsDialog');
  },

  showSurveyInstanceDetails: function (evt) {
    FLOW.questionAnswerControl.doQuestionAnswerQuery(evt.context.get('keyId'));
    $('.si_details').hide();
    $('tr[data-flow-id="si_details_' + evt.context.get('keyId') + '"]').show();
  },

  findSurveyedLocale: function (evt) {
	  var ident = this.get('identifier'),
	      displayName = this.get('displayName'),
	      sgId = FLOW.selectedControl.get('selectedSurveyGroup'),
	      cursorType = FLOW.metaControl.get('cursorType'),
        criteria = {};

	  if (ident) {
		  criteria.identifier = ident;
	  }

	  if (displayName) {
		  criteria.displayName = displayName;
	  }

	  if (sgId) {
		  criteria.surveyGroupId = sgId.get('keyId');
	  }

	  if (this.get('cursorStart')) {
		criteria.since = this.get('cursorStart');
	  }
      FLOW.router.surveyedLocaleController.populate(criteria);
      if(Ember.empty(FLOW.router.userListController.get('content'))) {
          FLOW.router.userListController.set('content', FLOW.User.find());
      }
  },

  doNextPage: function () {
	var cursorArray, cursorStart;
	cursorArray = FLOW.router.surveyedLocaleController.get('sinceArray');
	cursorStart = cursorArray.length > 0 ? cursorArray[cursorArray.length - 1] : null;
	this.set('cursorStart', cursorStart);
    this.findSurveyedLocale();
    FLOW.router.surveyedLocaleController.set('pageNumber', FLOW.router.surveyedLocaleController.get('pageNumber') + 1);
  },

  doPrevPage: function () {
	var cursorArray, cursorStart;
	cursorArray = FLOW.router.surveyedLocaleController.get('sinceArray');
	cursorStart = cursorArray.length - 3 > -1 ? cursorArray[cursorArray.length - 3] : null;
	this.set('cursorStart', cursorStart);
    this.findSurveyedLocale();
    FLOW.router.surveyedLocaleController.set('pageNumber', FLOW.router.surveyedLocaleController.get('pageNumber') - 1);
  },

  hasNextPage: function () {
    return FLOW.metaControl.get('numSLLoaded') == 20;
  }.property('FLOW.metaControl.numSLLoaded'),

  hasPrevPage: function () {
    return FLOW.router.surveyedLocaleController.get('pageNumber');
  }.property('FLOW.router.surveyedLocaleController.pageNumber'),
});

/**
 * View of each row/data point in the monitoring data tab
 */
FLOW.DataPointView = FLOW.View.extend({
    templateName: 'navData/monitoring-data-row',

    approvalStatus: [{label: Ember.String.loc('_pending'), value: 'PENDING'}, { label: Ember.String.loc('_approved'), value: 'APPROVED' },{ label: Ember.String.loc('_rejected'), value: 'REJECTED'}],

    showDataApprovalBlock: false,

    showSurveyedLocaleDeleteButton: function() {
        return FLOW.router.surveyedLocaleController.get('userCanDelete');
    }.property(),

    showApprovalStatusColumn: function () {
        return this.get('parentView').get('showApprovalStatusColumn');
    }.property(),

    dataPointApprovals: function () {
        var approvals = FLOW.router.dataPointApprovalController.get('content');
        if(!approvals) {
            return;
        }

        var surveyedLocaleId = this.content && this.content.get('keyId');
        return approvals.filterProperty('surveyedLocaleId', surveyedLocaleId);
    }.property('FLOW.router.dataPointApprovalController.content.@each'),

    /*
     * get the next approval step id
     */
    nextApprovalStepId: function () {
        return this.get('nextApprovalStep') && this.get('nextApprovalStep').get('keyId');
    }.property('this.nextApprovalStep'),

    /*
     * Derive the next approval step (in ordered approvals)
     */
    nextApprovalStep: function () {
        var approvals = this.get('dataPointApprovals');
        var steps = FLOW.router.approvalStepsController.get('arrangedContent');
        var lastApprovedStepOrder = -1;

        approvals.forEach(function (approval) {
            var step = steps.filterProperty('keyId',
                                approval.get('approvalStepId')).get('firstObject');
            if (approval.get('status') === 'APPROVED' &&
                    step && (step.get('order') > lastApprovedStepOrder)) {
                lastApprovedStepOrder = step.get('order');
            }
        });

        var nextStep = steps.filterProperty('order', ++lastApprovedStepOrder).get('firstObject');
        return nextStep;

    // NOTE: below we observe the '@each.approvalDate' in order to be
    // sure that we only recalculate the next step whenever the approval
    //  has been correctly updated on the server side
    }.property('this.dataPointApprovals.@each.approvalDate'),

    /*
     * return true if there are any of the approvals rejected in this set
     */
    hasRejectedApproval: function () {
        var approvals = this.get('dataPointApprovals');
        return !Ember.empty(approvals.filterProperty('status', 'REJECTED'));
    }.property('this.dataPointApprovals'),

    loadDataPointApprovalObserver: function () {
        if(!this.get('showDataApprovalBlock')) {
            return; // do nothing when hiding approval block
        }

        var dataPoint = this.get('content');
        if (dataPoint) {
            FLOW.router.dataPointApprovalController.loadBySurveyedLocaleId(dataPoint.get('keyId'));
        }
    }.observes('this.showDataApprovalBlock'),

    toggleShowDataApprovalBlock: function () {
        this.toggleProperty('showDataApprovalBlock');
    },
});

/**
 * View to render the status of a data point in the approval
 * status cell of each data point / row
 */
FLOW.DataPointApprovalStatusView = FLOW.View.extend({
    content: null,

    latestApprovalStepTitle: function () {
        var nextStepId = this.get('parentView').get('nextApprovalStepId');
        var stepsController = FLOW.router.get('approvalStepsController');
        var step = stepsController.filterProperty('keyId', nextStepId).get('firstObject');
        return step && step.get('title');
    }.property('this.parentView.nextApprovalStepId'),
});

/**
 * The data approval view for each approval step of a data point
 */
FLOW.DataPointApprovalView = FLOW.View.extend({
    step: null,

    dataPoint: null,

    dataPointApproval: function () {
        var approvals = this.get('parentView').get('dataPointApprovals');
        var defaultApproval = Ember.Object.create({ status: null, comment: null});

        if(Ember.empty(approvals)) {
            return defaultApproval;
        }

        var stepId = this.step && this.step.get('keyId');
        var approval = approvals.filterProperty('approvalStepId', stepId).get('firstObject');

        return approval || defaultApproval;
    }.property('this.parentView.dataPointApprovals'),

    isApprovedStep: function () {
        var dataPointApproval = this.get('dataPointApproval');
        return dataPointApproval && dataPointApproval.get('keyId');
    }.property('this.dataPointApproval'),

    /*
     * return the current user's id
     */
    currentUserId: function () {
        var step = this.get('step');
        var currentUserEmail = FLOW.currentUser.get('email');
        var userList = FLOW.router.userListController.get('content');
        var currentUser = userList &&
                            userList.filterProperty('emailAddress', currentUserEmail).get('firstObject');
        return currentUser && currentUser.get('keyId');
    }.property(),

    /*
     * Enable the approval fields based on whether or not approval steps
     * should be executed in order
     */
    showApprovalFields: function () {
        if(this.get('parentView').get('hasRejectedApproval')) {
            return false;
        }

        var approvalGroup = FLOW.router.approvalGroupController.get('content');
        var currentUserId = this.get('currentUserId');
        if(approvalGroup && approvalGroup.get('ordered')) {
            var nextStep = this.get('parentView').get('nextApprovalStep');
            if (nextStep) {
                return this.step.get('keyId') === nextStep.get('keyId') &&
                        nextStep.get('approverUserList').contains(currentUserId);
            } else {
                return false;
            }
        } else {
            // this is for unordered approval steps. show fields for
            // all steps so that its possible to approve any step
            return true;
        }
    }.property('this.parentView.nextApprovalStep'),

    /*
     *  Submit data approval properties to controller
     */
    submitDataPointApproval: function (event) {

        var dataPointApproval = this.get('dataPointApproval');
        if(dataPointApproval.get('keyId')) {
            FLOW.router.dataPointApprovalController.update(dataPointApproval);
        } else {
            dataPointApproval.surveyedLocaleId = this.get('dataPoint').get('keyId');
            dataPointApproval.approvalStepId = this.get('step').get('keyId');
            dataPointApproval.approverUserName = null;

            FLOW.router.dataPointApprovalController.add(dataPointApproval);
        }
    },
});<|endoftext|>


<commit_before>// Load in our dependencies
// DEV: By using an internal require here, we have verified that we support internal requires
var assert = require('assert');
// DEV: By using a `node_modules` require here, we have verified that we support external requires
void require('js-string-escape');
// DEV: By using a `./` require here, we have verified that we support relative requires
// DEV: We are resolving relative to `node_modules/karma/static/context.html` so lots of `../`
var submodule = require('../../../test/integration-test/test-files/submodule');

// Start our tests
describe('All `<script src=` Node.js integrations', function () {
  it('function as expected', function () {
    // Example: /home/todd/github/karma-electron/node_modules/karma/static/context.html
    assert(/karma[\/\\]static[\/\\]context\.html$/.test(__filename),
      'Expected "' + __filename + '" to end with "karma/static/context.html"');
    // Example: /home/todd/github/karma-electron/node_modules/karma/static
    assert(/karma[\/\\]static$/.test(__dirname),
      'Expected "' + __dirname + '" to end with "karma/static"');
  });
});

describe('module for `<script src=` based Node.js integrations', function () {
  describe('in the top level', function () {
    // DEV: Determined exepctations via `../reference`
    it('identify as the page itself', function () {
      // Example: /home/todd/github/karma-electron/node_modules/karma/static/context.html
      assert(/karma[\/\\]static[\/\\]context\.html$/.test(module.filename),
        'Expected "' + module.filename + '" to end with "karma/static/context.html"');
      assert.strictEqual(typeof module.exports, 'object');
      assert.strictEqual(module.id, 'electron/js2c/renderer_init');
      assert.strictEqual(submodule.loaded, true);
      // DEV: While iterating on #54, we noticed Electron@15 changed from `module.parent` to `module.__proto__.parent`
      //   This is caused by Node.js@16 upgrade which changed behavior, https://github.com/electron/electron/releases/tag/v15.0.0
      assert.strictEqual(module.hasOwnProperty('parent'), false);
      assert.strictEqual(module.__proto__.hasOwnProperty('parent'), true);
      assert.strictEqual(module.parent, undefined);
    });
  });

  describe('in a child module', function () {
    // DEV: Determined exepctations via `../reference`
    it('identify as a standalone module', function () {
      assert(/test[\/\\]integration-test[\/\\]test-files[\/\\]submodule\.js$/.test(submodule.filename),
        'Expected "' + submodule.filename + '" to end with "test/integration-test/test-files/submodule.js"');
      // Verify `hello` property of `module.exports`
      assert.strictEqual(submodule.exports.hello, 'world');
      assert(/test[\/\\]integration-test[\/\\]test-files[\/\\]submodule\.js$/.test(submodule.id),
        'Expected "' + submodule.id + '" to end with "test/integration-test/test-files/submodule.js"');
      assert.strictEqual(submodule.loaded, true);
      assert.strictEqual(submodule.parent, module);

      // Verify exported values
      assert.strictEqual(submodule.hello, 'world');
      // Example: /home/todd/github/karma-electron/test/integration-test/node-test.js
      assert(/test[\/\\]integration-test[\/\\]test-files[\/\\]submodule\.js$/.test(submodule.filename),
        'Expected "' + submodule.filename + '" to end with "test/integration-test/test-files/submodule.js"');
      // Example: /home/todd/github/karma-electron/test/integration-test
      assert(/test[\/\\]integration-test[\/\\]test-files$/.test(submodule.dirname),
        'Expected "' + submodule.dirname + '" to end with "test/integration-test/test-files"');
    });

    it('has same window context as parent', function () {
      assert.strictEqual(submodule.before, window.before);
    });
  });
});
<commit_msg>Fixed up lint error<commit_after>// Load in our dependencies
// DEV: By using an internal require here, we have verified that we support internal requires
var assert = require('assert');
// DEV: By using a `node_modules` require here, we have verified that we support external requires
void require('js-string-escape');
// DEV: By using a `./` require here, we have verified that we support relative requires
// DEV: We are resolving relative to `node_modules/karma/static/context.html` so lots of `../`
var submodule = require('../../../test/integration-test/test-files/submodule');

// Start our tests
describe('All `<script src=` Node.js integrations', function () {
  it('function as expected', function () {
    // Example: /home/todd/github/karma-electron/node_modules/karma/static/context.html
    assert(/karma[\/\\]static[\/\\]context\.html$/.test(__filename),
      'Expected "' + __filename + '" to end with "karma/static/context.html"');
    // Example: /home/todd/github/karma-electron/node_modules/karma/static
    assert(/karma[\/\\]static$/.test(__dirname),
      'Expected "' + __dirname + '" to end with "karma/static"');
  });
});

describe('module for `<script src=` based Node.js integrations', function () {
  describe('in the top level', function () {
    // DEV: Determined exepctations via `../reference`
    it('identify as the page itself', function () {
      // Example: /home/todd/github/karma-electron/node_modules/karma/static/context.html
      assert(/karma[\/\\]static[\/\\]context\.html$/.test(module.filename),
        'Expected "' + module.filename + '" to end with "karma/static/context.html"');
      assert.strictEqual(typeof module.exports, 'object');
      assert.strictEqual(module.id, 'electron/js2c/renderer_init');
      assert.strictEqual(submodule.loaded, true);
      // DEV: While iterating on #54, we noticed Electron@15 changed from `module.parent` to `module.__proto__.parent`
      //   This is caused by Node.js@16 upgrade which changed behavior, https://github.com/electron/electron/releases/tag/v15.0.0
      // DEV: `Object.getPrototypeOf` is the more formal call for `__proto__`
      assert.strictEqual(module.hasOwnProperty('parent'), false);
      assert.strictEqual(Object.getPrototypeOf(module).hasOwnProperty('parent'), true);
      assert.strictEqual(module.parent, undefined);
    });
  });

  describe('in a child module', function () {
    // DEV: Determined exepctations via `../reference`
    it('identify as a standalone module', function () {
      assert(/test[\/\\]integration-test[\/\\]test-files[\/\\]submodule\.js$/.test(submodule.filename),
        'Expected "' + submodule.filename + '" to end with "test/integration-test/test-files/submodule.js"');
      // Verify `hello` property of `module.exports`
      assert.strictEqual(submodule.exports.hello, 'world');
      assert(/test[\/\\]integration-test[\/\\]test-files[\/\\]submodule\.js$/.test(submodule.id),
        'Expected "' + submodule.id + '" to end with "test/integration-test/test-files/submodule.js"');
      assert.strictEqual(submodule.loaded, true);
      assert.strictEqual(submodule.parent, module);

      // Verify exported values
      assert.strictEqual(submodule.hello, 'world');
      // Example: /home/todd/github/karma-electron/test/integration-test/node-test.js
      assert(/test[\/\\]integration-test[\/\\]test-files[\/\\]submodule\.js$/.test(submodule.filename),
        'Expected "' + submodule.filename + '" to end with "test/integration-test/test-files/submodule.js"');
      // Example: /home/todd/github/karma-electron/test/integration-test
      assert(/test[\/\\]integration-test[\/\\]test-files$/.test(submodule.dirname),
        'Expected "' + submodule.dirname + '" to end with "test/integration-test/test-files"');
    });

    it('has same window context as parent', function () {
      assert.strictEqual(submodule.before, window.before);
    });
  });
});
<|endoftext|>