<commit_before>var http = require('http');
var https = require('https');
var parseUrl = require('url').parse;
var net = require('net');
var path = require('path');
var StringDecoder = require('string_decoder').StringDecoder;
require('should');
require('should-http');
var fs = require('fs');
var fse = require('fs-extra');
var startWhistle = require('../index');
var socks = require('socksv5');
var util = require('./util.test');
var config = require('./config.test');
var values = util.getValues();
var testList = fs.readdirSync(path.join(__dirname, './units')).map(function(name) {
  return require('./units/' + name);
});
//var start = 0;
//testList = testList.slice(start, start + 20);
var options = {
  key: fs.readFileSync(path.join(__dirname, 'assets/certs/root.key')),
  cert: fs.readFileSync(path.join(__dirname, 'assets/certs/root.crt'))
};
var count = 6;

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: config.wsPort });
//var WHISTLE_PATH = process.env.WHISTLE_PATH = __dirname;
//var PLUGINS_PATH = path.join(WHISTLE_PATH, '.whistle/node_modules');
//
//fse.removeSync(path.join(WHISTLE_PATH, '.whistle'));
//fse.copySync(path.join(__dirname, 'plugins'), PLUGINS_PATH);

wss.on('connection', function connection(ws) {
  var req = ws.upgradeReq;
  ws.on('message', function(msg) {
    ws.send(JSON.stringify({
      type: 'server',
      method: req.method,
      headers: req.headers,
      body: msg
    }, null, '\t'));
  });
});

http.createServer(function(req, res) {
  req.on('error', util.noop);
  res.on('error', util.noop);

  var body = '';
  var decoder = new StringDecoder('utf8');
  req.on('data', function(data) {
    body += decoder.write(data);
  });
  req.on('end', function() {
    body += decoder.end();
    res.end(JSON.stringify({
      type: 'server',
      url: req.url,
      method: req.method,
      headers: req.headers,
      body: body
    }, null, '\t'));
  });
}).listen(config.serverPort, startTest);

https.createServer(options, function(req, res) {
  res.end(JSON.stringify({
    headers: req.headers,
    body: 'test'
  }));
}).listen(config.httpsPort, startTest);

startWhistle({
  port: config.port,
  storage: 'test_',
  localUIHost: 'local.whistle.com',
  rules: fs.readFileSync(path.join(__dirname, 'rules.txt'), {encoding: 'utf8'}),
  values: values
}, startTest);

var socksServer = socks.createServer(function(info, accept, deny) {
  var socket;
  if (info.dstPort === 443) {
    if (socket = accept(true)) {
      var client = net.connect({
        host: '127.0.0.1',
        port: 5566
      }, function() {
        socket.pipe(client).pipe(socket);
      });
    }
    return;
  }
  if (socket = accept(true)) {
    var body = JSON.stringify({
      port: config.socksPort
    });
    socket.end([
      'HTTP/1.1 200 OK',
      'Connection: close',
      'Content-Type: text/plain;charset=utf8',
      'Content-Length: ' + Buffer.byteLength(body),
      '',
      body
    ].join('\r\n'));
  }
});

var authSocksServer = socks.createServer(function(info, accept, deny) {
  var socket;
  if (info.dstPort === 443) {
    if (socket = accept(true)) {
      var client = net.connect({
        host: '127.0.0.1',
        port: 5566
      }, function() {
        socket.pipe(client).pipe(socket);
      });
    }
    return;
  }
  if (socket = accept(true)) {
    var body = JSON.stringify({
      port: config.authSocksPort
    });
    socket.end([
      'HTTP/1.1 200 OK',
      'Connection: close',
      'Content-Type: text/plain;charset=utf8',
      'Content-Length: ' + Buffer.byteLength(body),
      '',
      body
    ].join('\r\n'));
  }
});

socksServer.useAuth(socks.auth.None());
authSocksServer.useAuth(socks.auth.UserPassword(function(user, password, cb) {
  cb(user == 'test' && password == 'hello1234');
}));

socksServer.listen(config.socksPort, startTest);
authSocksServer.listen(config.authSocksPort, startTest);

/**
 * 不用处理异常
 */
var server = http.createServer(function(req, res) {
  var fullUrl = /^http:/.test(req.url) ? req.url : 'http://' + req.headers.host + req.url;
  var options = parseUrl(fullUrl);
  delete options.hostname;
  options.host = '127.0.0.1';
  options.method = req.method;
  options.headers = req.headers;
  var client = http.request(options, function(_res) {
    _res.pipe(res);
  });
  req.pipe(client);
});

server.on('connect', function(req, socket) {
  var tunnelUrl = 'tunnel://' + (/^[^:\/]+:\d+$/.test(req.url) ? req.url : req.headers.host);
  var options = parseUrl(tunnelUrl);
  var client = net.connect({
    host: '127.0.0.1',
    port: options.port || 443
  }, function() {
    socket.pipe(client).pipe(socket);
    socket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: whistle/test\r\n\r\n');
  });
});

server.listen(config.proxyPort, startTest);

function startTest() {
  if (--count > 0) {
    return;
  }

  var done;
  function testAll() {
    if (done) {
      return;
    }
    done = true;
    testList.forEach(function(fn) {
      fn();
    });
  }

  (function getData() {
    util.request('http://local.whistlejs.com/cgi-bin/get-data', function() {
      testAll();
      setTimeout(getData, 5000);
    });
  })();
}

<commit_msg>test: plugins<commit_after>var http = require('http');
var https = require('https');
var parseUrl = require('url').parse;
var net = require('net');
var path = require('path');
var StringDecoder = require('string_decoder').StringDecoder;
require('should');
require('should-http');
var fs = require('fs');
var fse = require('fs-extra');
var startWhistle = require('../index');
var socks = require('socksv5');
var util = require('./util.test');
var config = require('./config.test');
var values = util.getValues();
var testList = fs.readdirSync(path.join(__dirname, './units')).map(function(name) {
  return require('./units/' + name);
});
var options = {
  key: fs.readFileSync(path.join(__dirname, 'assets/certs/root.key')),
  cert: fs.readFileSync(path.join(__dirname, 'assets/certs/root.crt'))
};
var count = 6;

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: config.wsPort });
var WHISTLE_PATH = process.env.WHISTLE_PATH = __dirname;
var PLUGINS_PATH = path.join(WHISTLE_PATH, '.whistle/node_modules');

fse.removeSync(path.join(WHISTLE_PATH, '.whistle'));
fse.copySync(path.join(__dirname, 'plugins'), PLUGINS_PATH);

wss.on('connection', function connection(ws) {
  var req = ws.upgradeReq;
  ws.on('message', function(msg) {
    ws.send(JSON.stringify({
      type: 'server',
      method: req.method,
      headers: req.headers,
      body: msg
    }, null, '\t'));
  });
});

http.createServer(function(req, res) {
  req.on('error', util.noop);
  res.on('error', util.noop);

  var body = '';
  var decoder = new StringDecoder('utf8');
  req.on('data', function(data) {
    body += decoder.write(data);
  });
  req.on('end', function() {
    body += decoder.end();
    res.end(JSON.stringify({
      type: 'server',
      url: req.url,
      method: req.method,
      headers: req.headers,
      body: body
    }, null, '\t'));
  });
}).listen(config.serverPort, startTest);

https.createServer(options, function(req, res) {
  res.end(JSON.stringify({
    headers: req.headers,
    body: 'test'
  }));
}).listen(config.httpsPort, startTest);

startWhistle({
  port: config.port,
  storage: 'test_',
  localUIHost: 'local.whistle.com',
  rules: fs.readFileSync(path.join(__dirname, 'rules.txt'), {encoding: 'utf8'}),
  values: values
}, startTest);

var socksServer = socks.createServer(function(info, accept, deny) {
  var socket;
  if (info.dstPort === 443) {
    if (socket = accept(true)) {
      var client = net.connect({
        host: '127.0.0.1',
        port: 5566
      }, function() {
        socket.pipe(client).pipe(socket);
      });
    }
    return;
  }
  if (socket = accept(true)) {
    var body = JSON.stringify({
      port: config.socksPort
    });
    socket.end([
      'HTTP/1.1 200 OK',
      'Connection: close',
      'Content-Type: text/plain;charset=utf8',
      'Content-Length: ' + Buffer.byteLength(body),
      '',
      body
    ].join('\r\n'));
  }
});

var authSocksServer = socks.createServer(function(info, accept, deny) {
  var socket;
  if (info.dstPort === 443) {
    if (socket = accept(true)) {
      var client = net.connect({
        host: '127.0.0.1',
        port: 5566
      }, function() {
        socket.pipe(client).pipe(socket);
      });
    }
    return;
  }
  if (socket = accept(true)) {
    var body = JSON.stringify({
      port: config.authSocksPort
    });
    socket.end([
      'HTTP/1.1 200 OK',
      'Connection: close',
      'Content-Type: text/plain;charset=utf8',
      'Content-Length: ' + Buffer.byteLength(body),
      '',
      body
    ].join('\r\n'));
  }
});

socksServer.useAuth(socks.auth.None());
authSocksServer.useAuth(socks.auth.UserPassword(function(user, password, cb) {
  cb(user == 'test' && password == 'hello1234');
}));

socksServer.listen(config.socksPort, startTest);
authSocksServer.listen(config.authSocksPort, startTest);

/**
 * 不用处理异常
 */
var server = http.createServer(function(req, res) {
  var fullUrl = /^http:/.test(req.url) ? req.url : 'http://' + req.headers.host + req.url;
  var options = parseUrl(fullUrl);
  delete options.hostname;
  options.host = '127.0.0.1';
  options.method = req.method;
  options.headers = req.headers;
  var client = http.request(options, function(_res) {
    _res.pipe(res);
  });
  req.pipe(client);
});

server.on('connect', function(req, socket) {
  var tunnelUrl = 'tunnel://' + (/^[^:\/]+:\d+$/.test(req.url) ? req.url : req.headers.host);
  var options = parseUrl(tunnelUrl);
  var client = net.connect({
    host: '127.0.0.1',
    port: options.port || 443
  }, function() {
    socket.pipe(client).pipe(socket);
    socket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: whistle/test\r\n\r\n');
  });
});

server.listen(config.proxyPort, startTest);

function startTest() {
  if (--count > 0) {
    return;
  }

  var done;
  function testAll() {
    if (done) {
      return;
    }
    done = true;
    testList.forEach(function(fn) {
      fn();
    });
  }

  (function getData() {
    util.request('http://local.whistlejs.com/cgi-bin/get-data', function() {
      testAll();
      setTimeout(getData, 5000);
    });
  })();
}

<|endoftext|>


<commit_before>'use strict';

var express    = require('express'),
    body_parser = require('body-parser');

// Globals
var PORT = 8080;

// Server
var server = module.exports.server = exports.server = express();

// form body parsing
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true}));

server.get('/', function(req, res) {
});

server.listen(PORT);
console.log('Running on http://localhost:' + PORT);

/* --- FUNCTIONS --- */
<commit_msg>responding on / with empty json object for now<commit_after>'use strict';

var express    = require('express'),
    body_parser = require('body-parser');

// Globals
var PORT = 8080;

// Server
var server = module.exports.server = exports.server = express();

// form body parsing
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true}));

server.get('/', function(req, res) {
    res.json({
    });
});

server.listen(PORT);
console.log('Running on http://localhost:' + PORT);

/* --- FUNCTIONS --- */
<|endoftext|>


<commit_before>// TODO: db schema

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var Event = mongoose.model('Event', new Schema({
	eventDate: [Date],
	//6 do we need a seperate key/val for time?
  eventToBook: String,
  roomName: String,
  eventAlert: Boolean
}));

//6 export this?<commit_msg>[update] edited schema<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var db = mongoose.connection;

mongoose.connect('mongodb://localhost/test');

var eventSchema = new Schema({
	eventDate: [Date],
  eventToBook: String,
  eventAlert: Boolean,
  eTime: '',
  roomName: String,
  eventTime: [Date]
});

module.exports = mongoose.model('Event', eventSchema);
<|endoftext|>


<commit_before>'use strict';

const noop = require('lodash/noop');

module.exports = (client) => {
  const me = {
    new: {
      newUrsis: [],
    },
    enroll: {},
    lookup: {},
  };

  me.new.fillForm = (done = noop) => client
    .setValue('input[name=FirstName]', 'testFirstName')
    .setValue('input[name=MiddleName]', 'testMiddleName')
    .setValue('input[name=LastName]', 'testLastName')
    .setValue('input[name=Suffix]', 'testSuffix')
    .setValue('input[name=BirthDate]', '10/10/2010')
    .click('#GenderF')
    .selectByVisibleText('select[name=ethnicity]', 'Unknown')
    .click('#racCat1')
    .click('#racCat2')
    .click('#racCat3')
    .click('#racCat4')
    .click('#racCat5')
    .setValue('input[name=Line1]', 'testAddressLine1')
    .setValue('input[name=Line2]', 'testAddressLine2')
    .setValue('input[name=City]', 'testCity')
    .selectByVisibleText('select[name=State]', 'AL - Alabama')
    .setValue('input[name=Zip]', 12345)
    .selectByVisibleText('select[name=Country]', 'United States')
    .setValue('#phone1_area_code', 123)
    .setValue('#phone2_area_code', 321)
    .setValue('#phone1_phone_num', 4567890)
    .setValue('#phone1_extension', 1111)
    .setValue('#phone2_extension', 2222)
    .setValue('#Notes', 'testNotes')
    .setValue('#email_address', 'testEmail@mrn.org')
    .selectByValue('#subject_tag_id', 1) // U.S. SSN
    .setValue('#value', 1112223333) // subject tag value
    .click('#context_site') // subject tag context === site
    .moveToObject('#study_id')
    .selectByValue('#study_id', 2319) // NITEST
    .alertDismiss((err) => {
      if (err) {
        /* eslint-disable no-console */
        console.warn('Study Enrollment limit OK - < 90% full');
        /* eslint-enable no-console */
      }
    })
    .waitForVis('#site_id', 8000)
    .moveToObject('#site_id')
    .selectByValue('#site_id', 7)
    .moveToObject('#first_name_at_birth', (err) => {
      if (err) { return; } // not an RDoC study
      return client // eslint-disable-line consistent-return
        .setValue('#first_name_at_birth', 'testFirstNameAtBirth')
        .setValue('#middle_name_at_birth', 'testMiddleNameAtBirth')
        .setValue('#last_name_at_birth', 'testLastNameAtBirth')
        .click('#physical_sex_at_birth_f')
        .setValue('#city_born_in', 'testCityBornIn');
    })
    .setValue('#consent_date', '02/22/2015')
    .click('[name=agreestosharedata]') // selects the first matched radio (Yes)
    .click('[name=agrees_to_future_studies]') // selects the first matched radio (Yes)
    .call(done);

  me.new.submit = (done = noop) => client
    .pause(1000)
    .scroll('#submit_new_subject')
    .click('#submit_new_subject')
    .waitForPaginationComplete()
    .pause(100)
    .isExisting('[value="Add >"]', (err, isExisting) => {
      if (!isExisting) {
        throw new Error('Submit new subject did not detect that it made it to the verify page.');
      }
    })
    .call(done);

  me.new.verify = (done = noop) => client
    .pause(200)
    .moveToObject('[value="Add >"]')
    .click('[value="Add >"]')
    .waitForPaginationComplete()
    .call(done);

  /* eslint-disable no-underscore-dangle */
  me.new._handleSubjectMatchesClick = (done = noop) => client
    .pause(200)
    .moveToObject('#verify_add_new_subject')
    .click('#verify_add_new_subject')
    .pause(10)
    .call(done);

  me.new.handleSubjectMatchesAddNew = (done = noop) => me.new._handleSubjectMatchesClick()
    .isVisible('#confirm_new_participant_modal', (err, isVisible) => {
      if (isVisible) {
            // test that you can close and reopen
        client
          .click('#confirm_new_subject_declined')
          .isVisible('#confirm_new_subject_declined', (err2, isVisible2) => {
            if (isVisible2) {
              throw new Error('#confirm_new_subject_declined should not be visible');
            }
          })
          .moveToObject('#verify_add_new_subject')
          .click('#verify_add_new_subject')
          .pause(50)
          .click('#confirm_new_subject_confirmed');
      }
    })
    .waitForPaginationComplete()
    .pause(200)
    .isExisting('#new_ursi', (err, isExisting) => {
      if (!isExisting) {
        throw new Error('Submit verify subject did not detect that it made it to new URSI page.');
      }
    })
    .getText('#new_ursi', (err, textParam) => {
      const text = (textParam || '').trim();

      if (!text || text.charAt(0) !== 'M') {
        throw new Error('Unable to retrieve new URSI value.');
      }

      me.new.newUrsis.push(text);
    })
    .call(done);
  /* eslint-enable no-underscore-dangle */

  me.new.handleSubjectMatchesExisting = () => {
    client
      .scroll(0, 0)
      .setValue('.coins-datatable-wrapper input[type=search]', 'testaddressline1')
      .click('//*[@id="datatable-container"]/tbody/tr[1]/td[8]/a')
      .pause(500);

    // Create/Re-use
    if (Date.now() % 2 === 0) {
      client.click('#page-container > div.boxBody > div > a:nth-child(2)');
    } else {
      client.click('#page-container > div.boxBody > div > a:nth-child(5)');
    }

    client.click('input[type=button][value=Continue]');
  };

  me.enroll.submitExisting = (done = noop) => client
    .pause(1000)
    .moveToObject('#enroll_subject_submit')
    .click('#enroll_subject_submit')
    .waitForPaginationComplete()
    // .scroll('.confirmMsg')
    .call(done);

  me.lookup.existing = (ursi, done = noop) => {
    if (!ursi) {
      throw new Error('subject.lookup.existing expects an ursi');
    }

    return client
      .pause(100)
      .setValue('input[name=ursi]', ursi)
      .click('[value="Continue >"]')
      .waitForPaginationComplete()
      .call(done);
  };

  return me;
};
<commit_msg>Move race and ethnicity inputs<commit_after>'use strict';

const noop = require('lodash/noop');

module.exports = (client) => {
  const me = {
    new: {
      newUrsis: [],
    },
    enroll: {},
    lookup: {},
  };

  me.new.fillForm = (done = noop) => client
    .setValue('input[name=FirstName]', 'testFirstName')
    .setValue('input[name=MiddleName]', 'testMiddleName')
    .setValue('input[name=LastName]', 'testLastName')
    .setValue('input[name=Suffix]', 'testSuffix')
    .setValue('input[name=BirthDate]', '10/10/2010')
    .click('#GenderF')
    .setValue('input[name=Line1]', 'testAddressLine1')
    .setValue('input[name=Line2]', 'testAddressLine2')
    .setValue('input[name=City]', 'testCity')
    .selectByVisibleText('select[name=State]', 'AL - Alabama')
    .setValue('input[name=Zip]', 12345)
    .selectByVisibleText('select[name=Country]', 'United States')
    .setValue('#phone1_area_code', 123)
    .setValue('#phone2_area_code', 321)
    .setValue('#phone1_phone_num', 4567890)
    .setValue('#phone1_extension', 1111)
    .setValue('#phone2_extension', 2222)
    .setValue('#Notes', 'testNotes')
    .setValue('#email_address', 'testEmail@mrn.org')
    .selectByValue('#subject_tag_id', 1) // U.S. SSN
    .setValue('#value', 1112223333) // subject tag value
    .click('#context_site') // subject tag context === site
    .moveToObject('#study_id')
    .selectByValue('#study_id', 2319) // NITEST
    .alertDismiss((err) => {
      if (err) {
        /* eslint-disable no-console */
        console.warn('Study Enrollment limit OK - < 90% full');
        /* eslint-enable no-console */
      }
    })
    .waitForVis('#site_id', 8000)
    .moveToObject('#site_id')
    .selectByValue('#site_id', 7)
    .selectByVisibleText('select[name=ethnicity]', 'Unknown')
    .click('#racCat1')
    .click('#racCat2')
    .click('#racCat3')
    .click('#racCat4')
    .click('#racCat5')
    .moveToObject('#first_name_at_birth', (err) => {
      if (err) { return; } // not an RDoC study
      return client // eslint-disable-line consistent-return
        .setValue('#first_name_at_birth', 'testFirstNameAtBirth')
        .setValue('#middle_name_at_birth', 'testMiddleNameAtBirth')
        .setValue('#last_name_at_birth', 'testLastNameAtBirth')
        .click('#physical_sex_at_birth_f')
        .setValue('#city_born_in', 'testCityBornIn');
    })
    .setValue('#consent_date', '02/22/2015')
    .click('[name=agreestosharedata]') // selects the first matched radio (Yes)
    .click('[name=agrees_to_future_studies]') // selects the first matched radio (Yes)
    .call(done);

  me.new.submit = (done = noop) => client
    .pause(1000)
    .scroll('#submit_new_subject')
    .click('#submit_new_subject')
    .waitForPaginationComplete()
    .pause(100)
    .isExisting('[value="Add >"]', (err, isExisting) => {
      if (!isExisting) {
        throw new Error('Submit new subject did not detect that it made it to the verify page.');
      }
    })
    .call(done);

  me.new.verify = (done = noop) => client
    .pause(200)
    .moveToObject('[value="Add >"]')
    .click('[value="Add >"]')
    .waitForPaginationComplete()
    .call(done);

  /* eslint-disable no-underscore-dangle */
  me.new._handleSubjectMatchesClick = (done = noop) => client
    .pause(200)
    .moveToObject('#verify_add_new_subject')
    .click('#verify_add_new_subject')
    .pause(10)
    .call(done);

  me.new.handleSubjectMatchesAddNew = (done = noop) => me.new._handleSubjectMatchesClick()
    .isVisible('#confirm_new_participant_modal', (err, isVisible) => {
      if (isVisible) {
            // test that you can close and reopen
        client
          .click('#confirm_new_subject_declined')
          .isVisible('#confirm_new_subject_declined', (err2, isVisible2) => {
            if (isVisible2) {
              throw new Error('#confirm_new_subject_declined should not be visible');
            }
          })
          .moveToObject('#verify_add_new_subject')
          .click('#verify_add_new_subject')
          .pause(50)
          .click('#confirm_new_subject_confirmed');
      }
    })
    .waitForPaginationComplete()
    .pause(200)
    .isExisting('#new_ursi', (err, isExisting) => {
      if (!isExisting) {
        throw new Error('Submit verify subject did not detect that it made it to new URSI page.');
      }
    })
    .getText('#new_ursi', (err, textParam) => {
      const text = (textParam || '').trim();

      if (!text || text.charAt(0) !== 'M') {
        throw new Error('Unable to retrieve new URSI value.');
      }

      me.new.newUrsis.push(text);
    })
    .call(done);
  /* eslint-enable no-underscore-dangle */

  me.new.handleSubjectMatchesExisting = () => {
    client
      .scroll(0, 0)
      .setValue('.coins-datatable-wrapper input[type=search]', 'testaddressline1')
      .click('//*[@id="datatable-container"]/tbody/tr[1]/td[8]/a')
      .pause(500);

    // Create/Re-use
    if (Date.now() % 2 === 0) {
      client.click('#page-container > div.boxBody > div > a:nth-child(2)');
    } else {
      client.click('#page-container > div.boxBody > div > a:nth-child(5)');
    }

    client.click('input[type=button][value=Continue]');
  };

  me.enroll.submitExisting = (done = noop) => client
    .pause(1000)
    .moveToObject('#enroll_subject_submit')
    .click('#enroll_subject_submit')
    .waitForPaginationComplete()
    // .scroll('.confirmMsg')
    .call(done);

  me.lookup.existing = (ursi, done = noop) => {
    if (!ursi) {
      throw new Error('subject.lookup.existing expects an ursi');
    }

    return client
      .pause(100)
      .setValue('input[name=ursi]', ursi)
      .click('[value="Continue >"]')
      .waitForPaginationComplete()
      .call(done);
  };

  return me;
};
<|endoftext|>


<commit_before>// Configuration check routine
var fs = require('fs');
const Configstore = require('configstore');
const pkg = require('./package.json');
const conf = new Configstore(pkg.name)

var unix_paths = ["/usr/bin/php", "/usr/sbin/php", "/etc/php", "/usr/lib/php", "/usr/share/php"]

$(function() {

  // Check OS
  checkWrite("Detecting system... ",0);
  var os;

  if (process.platform == "win32") {
    os = "win";
    checkWrite("Windows",1);
  }
  else if (process.platform == 'darwin') {
    os = "osx";
    checkWrite("Mac OSX",1);
  }
  else {
    os = "linux";
    checkWrite("Linux",1);
  }

  // Searching for PHP binary
  checkWrite("Trying to find PHP binary... ",0);
  switch (os) {
    case "osx":
    case "linux":
      checkPhpPath(unix_paths, 0);
      // @TODO Implement Windows
  }

});

function checkPhpPath(list, index) {
  if (list[index] == null) {
    phpNotFound();
  } else {
    fs.exists(list[index], function(exists) {
      if (exists) {
        phpFound(list[index]);
      } else {
        checkPhpPath(list, ++index);
      }
    });
  }
}

function phpFound(path) {
  checkWrite("Found! ("+path+")", 1);
  checkWrite("Storing data...", 0);
  conf.set("php_path", path);
  checkWrite("Done!",1);
  checkWrite("Starting app...");
  // Wait for 1.5 second, just in the first run
  setTimeout('window.location = "index.html"', 1500);
}

function phpNotFound() {
  // @TODO Implement
}

function checkWrite(text, br) {
  if (br)
    $("body").append(text + "
");
  else
    $("body").append(text);
}
<commit_msg>Added a message when it's not possible to find PHP binary<commit_after>// Configuration check routine
var fs = require('fs');
const Configstore = require('configstore');
const pkg = require('./package.json');
const conf = new Configstore(pkg.name)

var unix_paths = ["/usr/bin/php", "/usr/sbin/php", "/etc/php", "/usr/lib/php", "/usr/share/php"]

$(function() {

  // Check OS
  checkWrite("Detecting system... ",0);
  var os;

  if (process.platform == "win32") {
    os = "win";
    checkWrite("Windows",1);
  }
  else if (process.platform == 'darwin') {
    os = "osx";
    checkWrite("Mac OSX",1);
  }
  else {
    os = "linux";
    checkWrite("Linux",1);
  }

  // Searching for PHP binary
  checkWrite("Trying to find PHP binary... ",0);
  switch (os) {
    case "osx":
    case "linux":
      checkPhpPath(unix_paths, 0);
      // @TODO Implement Windows
  }

});

function checkPhpPath(list, index) {
  if (list[index] == null) {
    phpNotFound();
  } else {
    fs.exists(list[index], function(exists) {
      if (exists) {
        phpFound(list[index]);
      } else {
        checkPhpPath(list, ++index);
      }
    });
  }
}

function phpFound(path) {
  checkWrite("Found! ("+path+")", 1);
  checkWrite("Storing data...", 0);
  conf.set("php_path", path);
  checkWrite("Done!",1);
  checkWrite("Starting app...");
  // Wait for 1.5 second, just in the first run
  setTimeout('window.location = "index.html"', 1500);
}

function phpNotFound() {
  // @TODO Implement instructions and possibility to search for PHP binary
  checkWrite("Not found. Install PHP and try again.");
}

function checkWrite(text, br) {
  if (br)
    $("body").append(text + "
");
  else
    $("body").append(text);
}
<|endoftext|>


<commit_before>/* eslint no-underscore-dangle: 0 */
const test = require('ava').test;
const Promise = require('bluebird');
const mongoose = require('mongoose');

const stringColleciton = require('../');

mongoose.Promise = Promise;
const db = mongoose.createConnection('localhost');
const getModel = (schema) => {
  const collectionId = mongoose.Types.ObjectId().toString();
  const collectionName = `tmp${collectionId}`;

  return db.model(collectionName, schema);
};
const minimalValidate = (t, pathOption) => {
  t.is(pathOption.instance, 'Array');
  t.is(pathOption.caster.instance, 'String');
};

test.after.always('clean up tmp collection', () => {
  const dropCollection = collectionName => Promise.fromNode((callback) => {
    db.db.dropCollection(collectionName, callback);
  });

  return Promise.fromNode(callback => db.db.listCollections({ name: /^tmp/ }).toArray(callback))
    .map(collection => collection.name)
    .map(dropCollection);
});

test('fieldName: should exists target filed name', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const pathOption = schema.path('tags');

  t.truthy(pathOption);
  minimalValidate(t, pathOption);
  t.false(pathOption.caster.options.index);
});

test('fieldName: should index in caster field', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { isIndex: true });
  const pathOption = schema.path('tags');

  t.truthy(pathOption);
  t.true(pathOption.caster.options.index);
});

test('fieldName: should use input field name', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { fieldName: 't' });
  const pathOption = schema.path('t');

  minimalValidate(t, pathOption);
});

test('get: should success get collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  return model.create({ tags: ['t3'] })
    .then(doc => model.getTags({ _id: doc._id }))
    .then((tags) => {
      t.deepEqual(tags, ['t3']);
    });
});

test('get: should still get tags withou input', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  return model.create({ tags: ['t3'] })
    .then(() => model.getTags())
    .then(tags => t.deepEqual(tags, ['t3']));
});

test('add: should success add to collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['test'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.addTags({ _id: doc._id }, ['test2']);
    })
    .then(() => model.findById(bus.docId))
    .then(doc => t.deepEqual(doc.tags, ['test', 'test2']));
});

test('add: should success add to collection with unique opions', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { isUnique: false });
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.addTags({ _id: doc._id }, ['t1']);
    })
    .then(() => model.findById(bus.docId))
    .then(doc => t.deepEqual(doc.tags, ['t', 't1', 't1']));
});

test('add: should success add to collection with unique opions', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { isUnique: true });
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.addTags({ _id: doc._id }, ['t1']);
    })
    .then((doc) => {
      t.deepEqual(doc.tags, ['t', 't1']);

      return model.findById(bus.docId);
    })
    .then((doc) => {
      t.deepEqual(doc.tags, ['t', 't1']);
    });
});

test('add: should reject emtpy query error', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const promise = model.addTags();
  t.throws(promise, 'query should not be empty');
});

test('replace: should success replace original collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.replaceTags({ _id: doc._id }, ['t2']);
    })
    .then((doc) => {
      t.deepEqual(doc.tags, ['t2']);

      return model.findById(doc._id);
    })
    .then(doc => t.deepEqual(doc.tags, ['t2']));
});

test('replace: should reject emtpy query error', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const promise = model.replaceTags();
  t.throws(promise, 'query should not be empty');
});

test('batchReplace: should success batchReplace original collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.batchReplaceTags({ _id: doc._id }, ['t2']);
    })
    .then(({ nModified }) => {
      t.is(nModified, 1);

      return model.findById(bus.docId);
    })
    .then(doc => t.deepEqual(doc.tags, ['t2']));
});

test('batchReplace: should reject emtpy query error', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const promise = model.batchReplaceTags();
  t.throws(promise, 'query should not be empty');
});
<commit_msg>test(plugin): fix ava throws should use async/await<commit_after>/* eslint no-underscore-dangle: 0 */
const test = require('ava').test;
const Promise = require('bluebird');
const mongoose = require('mongoose');

const stringColleciton = require('../');

mongoose.Promise = Promise;
const db = mongoose.createConnection('localhost');
const getModel = (schema) => {
  const collectionId = mongoose.Types.ObjectId().toString();
  const collectionName = `tmp${collectionId}`;

  return db.model(collectionName, schema);
};
const minimalValidate = (t, pathOption) => {
  t.is(pathOption.instance, 'Array');
  t.is(pathOption.caster.instance, 'String');
};

test.after.always('clean up tmp collection', () => {
  const dropCollection = collectionName => Promise.fromNode((callback) => {
    db.db.dropCollection(collectionName, callback);
  });

  return Promise.fromNode(callback => db.db.listCollections({ name: /^tmp/ }).toArray(callback))
    .map(collection => collection.name)
    .map(dropCollection);
});

test('fieldName: should exists target filed name', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const pathOption = schema.path('tags');

  t.truthy(pathOption);
  minimalValidate(t, pathOption);
  t.false(pathOption.caster.options.index);
});

test('fieldName: should index in caster field', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { isIndex: true });
  const pathOption = schema.path('tags');

  t.truthy(pathOption);
  t.true(pathOption.caster.options.index);
});

test('fieldName: should use input field name', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { fieldName: 't' });
  const pathOption = schema.path('t');

  minimalValidate(t, pathOption);
});

test('get: should success get collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  return model.create({ tags: ['t3'] })
    .then(doc => model.getTags({ _id: doc._id }))
    .then((tags) => {
      t.deepEqual(tags, ['t3']);
    });
});

test('get: should still get tags withou input', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  return model.create({ tags: ['t3'] })
    .then(() => model.getTags())
    .then(tags => t.deepEqual(tags, ['t3']));
});

test('add: should success add to collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['test'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.addTags({ _id: doc._id }, ['test2']);
    })
    .then(() => model.findById(bus.docId))
    .then(doc => t.deepEqual(doc.tags, ['test', 'test2']));
});

test('add: should success add to collection with unique opions', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { isUnique: false });
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.addTags({ _id: doc._id }, ['t1']);
    })
    .then(() => model.findById(bus.docId))
    .then(doc => t.deepEqual(doc.tags, ['t', 't1', 't1']));
});

test('add: should success add to collection with unique opions', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton, { isUnique: true });
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.addTags({ _id: doc._id }, ['t1']);
    })
    .then((doc) => {
      t.deepEqual(doc.tags, ['t', 't1']);

      return model.findById(bus.docId);
    })
    .then((doc) => {
      t.deepEqual(doc.tags, ['t', 't1']);
    });
});

test('add: should reject emtpy query error', async (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const promise = model.addTags();
  await t.throws(promise, 'query should not be empty');
});

test('replace: should success replace original collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.replaceTags({ _id: doc._id }, ['t2']);
    })
    .then((doc) => {
      t.deepEqual(doc.tags, ['t2']);

      return model.findById(doc._id);
    })
    .then(doc => t.deepEqual(doc.tags, ['t2']));
});

test('replace: should reject emtpy query error', async (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const promise = model.replaceTags();
  await t.throws(promise, 'query should not be empty');
});

test('batchReplace: should success batchReplace original collection', (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const bus = {};
  return model.create({ tags: ['t', 't1'] })
    .then((doc) => {
      t.truthy(doc);
      bus.docId = doc._id;

      return model.batchReplaceTags({ _id: doc._id }, ['t2']);
    })
    .then(({ nModified }) => {
      t.is(nModified, 1);

      return model.findById(bus.docId);
    })
    .then(doc => t.deepEqual(doc.tags, ['t2']));
});

test('batchReplace: should reject emtpy query error', async (t) => {
  const schema = new mongoose.Schema();
  schema.plugin(stringColleciton);
  const model = getModel(schema);

  const promise = model.batchReplaceTags();
  await t.throws(promise, 'query should not be empty');
});
<|endoftext|>


<commit_before>// Show posts list (topic)
//
"use strict";

var _         = require('lodash');
var memoizee  = require('memoizee');

var forum_breadcrumbs = require('../../../lib/forum_breadcrumbs.js');

module.exports = function (N, apiPath) {
  N.validate(apiPath, {
    // topic id
    hid: {
      type: "integer",
      minimum: 1,
      required: true
    },
    section_hid: {
      type: "integer",
      minimum: 1,
    },
    page: {
      type: "integer",
      minimum: 1,
      'default': 1
    }
  });

  // shortcut
  var Section = N.models.forum.Section;

  // Just subcall forum.topic.list, that enchances `env`
  //
  N.wire.on(apiPath, function get_posts(env, callback) {
    env.extras.puncher.start('Fetch posts');

    N.wire.emit('server:forum.topic.list', env, function (err) {
      env.extras.puncher.stop();

      callback(err);
    });
  });

  // Fill head meta & topic info
  N.wire.after(apiPath, function fill_meta(env) {
    var t_params;
    var data = env.response.data;
    var topic = env.data.topic;

    if (env.session && env.session.hb) {
      topic.cache.real = topic.cache.hb;
    }

    // prepare page title
    data.head.title = topic.title;
    if (env.params.page > 1) {
      t_params = { title: topic.title, page: env.params.page };
      data.head.title = env.t('title_with_page', t_params);
    }
  });

  // Helper - cacheable bredcrumbs info fetch, to save DB request.
  // We can cache it, because cache size is limited by sections count.
  var fetchForumsBcInfo = memoizee(
    function (ids, callback) {
      Section
        .find({ _id: { $in: ids }})
        .select('id title')
        .sort({ 'level': 1 })
        .setOptions({ lean: true })
        .exec(function (err, parents) {
        callback(err, parents);
      });
    },
    {
      async: true,
      maxAge:     60000, // cache TTL = 60 seconds
      primitive:  true   // params keys are calculated as toStrins, ok for our case
    }
  );

  // build breadcrumbs
  N.wire.after(apiPath, function fill_topic_breadcrumbs(env, callback) {
    var section = env.data.section;
    var data = env.response.data;

    env.extras.puncher.start('Build breadcrumbs');

    fetchForumsBcInfo(section.parent_list, function (err, parents) {
      env.extras.puncher.stop();

      if (err) {
        callback(err);
        return;
      }

      var bc_list = parents.slice(); // clone result to keep cache safe
      bc_list.push(_.pick(section, ['id', 'title']));

      data.blocks = data.blocks || {};
      data.blocks.breadcrumbs = forum_breadcrumbs(env, bc_list);

      callback();
    });
  });
};
<commit_msg>fixed topic page breadcrumbs links<commit_after>// Show posts list (topic)
//
"use strict";

var _         = require('lodash');
var memoizee  = require('memoizee');

var forum_breadcrumbs = require('../../../lib/forum_breadcrumbs.js');

module.exports = function (N, apiPath) {
  N.validate(apiPath, {
    // topic id
    hid: {
      type: "integer",
      minimum: 1,
      required: true
    },
    section_hid: {
      type: "integer",
      minimum: 1,
    },
    page: {
      type: "integer",
      minimum: 1,
      'default': 1
    }
  });

  // shortcut
  var Section = N.models.forum.Section;

  // Just subcall forum.topic.list, that enchances `env`
  //
  N.wire.on(apiPath, function get_posts(env, callback) {
    env.extras.puncher.start('Fetch posts');

    N.wire.emit('server:forum.topic.list', env, function (err) {
      env.extras.puncher.stop();

      callback(err);
    });
  });

  // Fill head meta & topic info
  N.wire.after(apiPath, function fill_meta(env) {
    var t_params;
    var data = env.response.data;
    var topic = env.data.topic;

    if (env.session && env.session.hb) {
      topic.cache.real = topic.cache.hb;
    }

    // prepare page title
    data.head.title = topic.title;
    if (env.params.page > 1) {
      t_params = { title: topic.title, page: env.params.page };
      data.head.title = env.t('title_with_page', t_params);
    }
  });

  // Helper - cacheable bredcrumbs info fetch, to save DB request.
  // We can cache it, because cache size is limited by sections count.
  var fetchForumsBcInfo = memoizee(
    function (ids, callback) {
      Section
        .find({ _id: { $in: ids }})
        .select('hid title')
        .sort({ 'level': 1 })
        .setOptions({ lean: true })
        .exec(function (err, parents) {
        callback(err, parents);
      });
    },
    {
      async: true,
      maxAge:     60000, // cache TTL = 60 seconds
      primitive:  true   // params keys are calculated as toStrins, ok for our case
    }
  );

  // build breadcrumbs
  N.wire.after(apiPath, function fill_topic_breadcrumbs(env, callback) {
    var section = env.data.section;
    var data = env.response.data;

    env.extras.puncher.start('Build breadcrumbs');

    fetchForumsBcInfo(section.parent_list, function (err, parents) {
      env.extras.puncher.stop();

      if (err) {
        callback(err);
        return;
      }

      var bc_list = parents.slice(); // clone result to keep cache safe
      bc_list.push(_.pick(section, ['hid', 'title']));

      data.blocks = data.blocks || {};
      data.blocks.breadcrumbs = forum_breadcrumbs(env, bc_list);

      callback();
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

function click_button(){
    // Add clicks-per-click to clicks.
    document.getElementById('clicks').innerHTML =
      parseInt(document.getElementById('clicks').innerHTML)
      + Math.floor(parseInt(document.getElementById('clicks-per-click').innerHTML)
      * (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100));
}

function purchase(upgrade, cost, target, free){
    var clicks = parseInt(document.getElementById('clicks').innerHTML);
    free = free || false;

    if(!free
      && clicks < parseInt(document.getElementById('upgrade-' + upgrade + '-cost').innerHTML)){
        return;
    }

    if(!free){
        // If user can afford upgrade...
        //   ...subtract cost of upgrade from clicks...
        document.getElementById('clicks').innerHTML =
          clicks - parseInt(document.getElementById('upgrade-' + upgrade + '-cost').innerHTML);
    }

    // ...and increase upgrade...
    upgrades[upgrade]['level'] += 1;
    document.getElementById('upgrade-' + upgrade).innerHTML = upgrades[upgrade]['level'];

    // ...and update upgrade cost...
    upgrades[upgrade]['cost'] *= upgrades[upgrade]['multiplier'];
    document.getElementById('upgrade-' + upgrade + '-cost').innerHTML =
      upgrades[upgrade]['base'] + upgrades[upgrade]['cost'];

    // ...and increase target value, either clicks-per-click or clicks-per-second...
    document.getElementById(target).innerHTML = parseInt(document.getElementById(target).innerHTML)
      + (cost < 1 || cost > 4
        ? 1
        : cost
      );

    // ...and recalculate multiplied values.
    var multiplier = (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100);
    document.getElementById('clicks-per-click-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-click').innerHTML) * multiplier);
    document.getElementById('clicks-per-second-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-second').innerHTML) * multiplier);
}

function reset_score(){
    if(!window.confirm('Reset score?')){
        return;
    }

    var ids = {
      'clicks': 0,
      'clicks-multiplier': 100,
      'clicks-per-click': 1,
      'clicks-per-click-multiplied': 1,
      'clicks-per-second': 0,
      'clicks-per-second-multiplied': 0,
    };
    for(var id in ids){
        window.localStorage.removeItem('Click.htm-' + id);
        document.getElementById(id).innerHTML = ids[id];
    }

    for(id in upgrades){
        upgrades[id]['cost'] = 1;
        upgrades[id]['level'] = 0;
    }

    for(var id in upgrades){
        window.localStorage.removeItem('Click.htm-upgrade-' + id);

        document.getElementById('upgrade-' + id).innerHTML = upgrades[id]['level'];
        document.getElementById('upgrade-' + id + '-cost').innerHTML =
          upgrades[id]['base'] + upgrades[id]['cost'];
    }
}

function reset_settings(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    window.localStorage.removeItem('Click.htm-keybind-click');
    document.getElementById('keybind-click').value = 'C';

    for(var id in upgrades){
        window.localStorage.removeItem('Click.htm-keybind-' + id);
        document.getElementById('keybind-' + id).value = upgrades[id]['keybind'];
    }
}

function second(){
    if(parseInt(document.getElementById('clicks-per-second').innerHTML) > 0){
        document.getElementById('clicks').innerHTML =
          parseInt(document.getElementById('clicks').innerHTML)
        + Math.floor(parseInt(document.getElementById('clicks-per-second').innerHTML)
          * (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100));
    }

    // Setting the title to # of clicks makes idling easier.
    document.title = document.getElementById('clicks').innerHTML;

    // There is always another second.
    window.setTimeout(
      second,
      1000
    );
}

function settings_toggle(state){
    state = state == void 0
      ? document.getElementById('settings-button').value === '+'
      : state;
    var display = 'inline';

    if(state){
        document.getElementById('settings-button').value = '-';

    }else{
        display = 'none';
        document.getElementById('settings-button').value = '+';
    }

    for(var id in upgrades){
        document.getElementById('keybind-' + id).style.display = display;
    }
    document.getElementById('keybind-click').style.display = display;
    document.getElementById('settings-div').style.display = display;
}

var keyclick_ready = 1;
var upgrades = {
  'manual': {
    'base': 9,
    'cost': 1,
    'level': 0,
    'keybind': '1',
    'multiplier': 2,
    'type': 'per-click',
  },
  'script': {
    'base': 99,
    'cost': 1,
    'level': 0,
    'keybind': '2',
    'multiplier': 4,
    'type': 'per-second',
  },
  'employee': {
    'base': 249,
    'cost': 1,
    'level': 0,
    'keybind': '3',
    'multiplier': 8,
    'type': 'per-second',
  },
  'server': {
    'base': 499,
    'cost': 1,
    'level': 0,
    'keybind': '4',
    'multiplier': 16,
    'type': 'per-second',
  },
  'cluster': {
    'base': 999,
    'cost': 1,
    'level': 0,
    'keybind': '5',
    'multiplier': 32,
    'type': 'per-second',
  },
  'investor': {
    'base': 99,
    'cost': 1,
    'level': 0,
    'keybind': '6',
    'multiplier': 64,
    'type': 'multiplier',
  },
};

window.onbeforeunload = function(e){
    // Save clicks into window.localStorage.
    var clicks = parseInt(document.getElementById('clicks').innerHTML);
    if(clicks > 0){
        window.localStorage.setItem(
          'Click.htm-clicks',
          clicks
        );

    }else{
        window.localStorage.removeItem('Click.htm-clicks');
    }

    // Save upgrades into window.localStorage.
    for(var id in upgrades){
        // Save upgrade keybinds, if different from default.
        if(document.getElementById('keybind-' + id).value != upgrades[id]['keybind']){
            window.localStorage.setItem(
              'Click.htm-keybind-' + id,
              document.getElementById('keybind-' + id).value
            );

        }else{
            window.localStorage.removeItem('Click.htm-keybind-' + id);
        }

        // Only save level if greater than 0.
        if(upgrades[id]['level'] > 0){
            window.localStorage.setItem(
              'Click.htm-upgrade-' + id,
              upgrades[id]['level']
            );
        }

    }

    // Save click keybind, if different from default.
    if(document.getElementById('keybind-click').value != 'C'){
        window.localStorage.setItem(
          'Click.htm-keybind-click',
          document.getElementById('keybind-click').value
        );

    }else{
        window.localStorage.removeItem('Click.htm-keybind-click');
    }
};

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: show settings.
    if(key === 187){
        settings_toggle(true);
        return;

    // -: hide settings.
    }else if(key === 189){
        settings_toggle(false);
        return;
    }

    key = String.fromCharCode(key);

    if(key === document.getElementById('keybind-click').value){
        if(keyclick_ready > 0){
            keyclick_ready = 0;
            click_button();
        }

        return;
    }

    for(var id in upgrades){
        if(key != document.getElementById('keybind-' + id).value){
            continue;
        }

        purchase(
          id,
          upgrades[id]['cost'],
          'clicks-' + upgrades[id]['type']
        );
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === document.getElementById('keybind-click').value){
        keyclick_ready = 1;
    }
};

window.onload = function(){
    // Load values from window.localStorage, if they exist.
    document.getElementById('keybind-click').value =
      window.localStorage.getItem('Click.htm-keybind-click') === null
        ? 'C'
        : window.localStorage.getItem('Click.htm-keybind-click');

    var ids = {
      'clicks': 0,
      'clicks-multiplier': 100,
      'clicks-per-click': 1,
      'clicks-per-second': 0,
    };

    for(var id in ids){
        document.getElementById(id).innerHTML =
          window.localStorage.getItem('Click.htm-' + id) === null
            ? ids[id]
            : window.localStorage.getItem('Click.htm-' + id);
    }

    var multiplier = (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100);
    document.getElementById('clicks-per-click-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-click').innerHTML) * multiplier);
    document.getElementById('clicks-per-second-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-second').innerHTML) * multiplier);

    for(id in upgrades){
        var upgrade = id[0].toUpperCase() + id.substring(1);

        document.getElementById('upgrades').innerHTML +=
          '0'
          + ' <input onclick=purchase("'
            + id + '",'
            + upgrades[id]['cost'] + ',"'
            + 'clicks-' + upgrades[id]['type']
          + '") type=button value=' + upgrade + '>'
          + '<input class=keybind id=keybind-' + id + ' maxlength=1>'
          + ' ' + (upgrades[id]['base'] + upgrades[id]['cost']) +'
';
    }

    for(id in upgrades){
        document.getElementById('keybind-' + id).value =
          window.localStorage.getItem('Click.htm-keybind-' + id) === null
            ? upgrades[id]['keybind']
            : window.localStorage.getItem('Click.htm-keybind-' + id);

        var level = parseInt(window.localStorage.getItem('Click.htm-upgrade-' + id));
        level = isNaN(level)
          ? 0
          : level;
        while(level > 0){
            purchase(
              id,
              upgrades[id]['cost'],
              'clicks-' + upgrades[id]['type'],
              true
            );
            level -= 1;
        }
    }

    window.setTimeout(
      second,
      1000
    );
};
<commit_msg>fixed incorrect bonuses<commit_after>'use strict';

function click_button(){
    // Add clicks-per-click to clicks.
    document.getElementById('clicks').innerHTML =
      parseInt(document.getElementById('clicks').innerHTML)
      + Math.floor(parseInt(document.getElementById('clicks-per-click').innerHTML)
      * (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100));
}

function purchase(upgrade, cost, target, free){
    var clicks = parseInt(document.getElementById('clicks').innerHTML);
    free = free || false;

    if(!free
      && clicks < parseInt(document.getElementById('upgrade-' + upgrade + '-cost').innerHTML)){
        return;
    }

    if(!free){
        // If user can afford upgrade...
        //   ...subtract cost of upgrade from clicks...
        document.getElementById('clicks').innerHTML =
          clicks - parseInt(document.getElementById('upgrade-' + upgrade + '-cost').innerHTML);
    }

    // ...and increase upgrade...
    upgrades[upgrade]['level'] += 1;
    document.getElementById('upgrade-' + upgrade).innerHTML = upgrades[upgrade]['level'];

    // ...and update upgrade cost...
    upgrades[upgrade]['cost'] *= upgrades[upgrade]['multiplier'];
    document.getElementById('upgrade-' + upgrade + '-cost').innerHTML =
      upgrades[upgrade]['base'] + upgrades[upgrade]['cost'];

    // ...and increase target value, either clicks-per-click or clicks-per-second...
    document.getElementById(target).innerHTML = parseInt(document.getElementById(target).innerHTML)
      + upgrades[upgrade]['bonus'];

    // ...and recalculate multiplied values.
    var multiplier = (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100);
    document.getElementById('clicks-per-click-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-click').innerHTML) * multiplier);
    document.getElementById('clicks-per-second-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-second').innerHTML) * multiplier);
}

function reset_score(){
    if(!window.confirm('Reset score?')){
        return;
    }

    var ids = {
      'clicks': 0,
      'clicks-multiplier': 100,
      'clicks-per-click': 1,
      'clicks-per-click-multiplied': 1,
      'clicks-per-second': 0,
      'clicks-per-second-multiplied': 0,
    };
    for(var id in ids){
        window.localStorage.removeItem('Click.htm-' + id);
        document.getElementById(id).innerHTML = ids[id];
    }

    for(id in upgrades){
        upgrades[id]['cost'] = 1;
        upgrades[id]['level'] = 0;
    }

    for(var id in upgrades){
        window.localStorage.removeItem('Click.htm-upgrade-' + id);

        document.getElementById('upgrade-' + id).innerHTML = upgrades[id]['level'];
        document.getElementById('upgrade-' + id + '-cost').innerHTML =
          upgrades[id]['base'] + upgrades[id]['cost'];
    }
}

function reset_settings(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    window.localStorage.removeItem('Click.htm-keybind-click');
    document.getElementById('keybind-click').value = 'C';

    for(var id in upgrades){
        window.localStorage.removeItem('Click.htm-keybind-' + id);
        document.getElementById('keybind-' + id).value = upgrades[id]['keybind'];
    }
}

function second(){
    if(parseInt(document.getElementById('clicks-per-second').innerHTML) > 0){
        document.getElementById('clicks').innerHTML =
          parseInt(document.getElementById('clicks').innerHTML)
        + Math.floor(parseInt(document.getElementById('clicks-per-second').innerHTML)
          * (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100));
    }

    // Setting the title to # of clicks makes idling easier.
    document.title = document.getElementById('clicks').innerHTML;

    // There is always another second.
    window.setTimeout(
      second,
      1000
    );
}

function settings_toggle(state){
    state = state == void 0
      ? document.getElementById('settings-button').value === '+'
      : state;
    var display = 'inline';

    if(state){
        document.getElementById('settings-button').value = '-';

    }else{
        display = 'none';
        document.getElementById('settings-button').value = '+';
    }

    for(var id in upgrades){
        document.getElementById('keybind-' + id).style.display = display;
    }
    document.getElementById('keybind-click').style.display = display;
    document.getElementById('settings-div').style.display = display;
}

var keyclick_ready = 1;
var upgrades = {
  'manual': {
    'base': 9,
    'bonus': 1,
    'cost': 1,
    'level': 0,
    'keybind': '1',
    'multiplier': 2,
    'type': 'per-click',
  },
  'script': {
    'base': 99,
    'bonus': 1,
    'cost': 1,
    'level': 0,
    'keybind': '2',
    'multiplier': 4,
    'type': 'per-second',
  },
  'employee': {
    'base': 249,
    'bonus': 2,
    'cost': 1,
    'level': 0,
    'keybind': '3',
    'multiplier': 8,
    'type': 'per-second',
  },
  'server': {
    'base': 499,
    'bonus': 3,
    'cost': 1,
    'level': 0,
    'keybind': '4',
    'multiplier': 16,
    'type': 'per-second',
  },
  'cluster': {
    'base': 999,
    'bonus': 4,
    'cost': 1,
    'level': 0,
    'keybind': '5',
    'multiplier': 32,
    'type': 'per-second',
  },
  'investor': {
    'base': 99,
    'bonus': 1,
    'cost': 1,
    'level': 0,
    'keybind': '6',
    'multiplier': 64,
    'type': 'multiplier',
  },
};

window.onbeforeunload = function(e){
    // Save clicks into window.localStorage.
    var clicks = parseInt(document.getElementById('clicks').innerHTML);
    if(clicks > 0){
        window.localStorage.setItem(
          'Click.htm-clicks',
          clicks
        );

    }else{
        window.localStorage.removeItem('Click.htm-clicks');
    }

    // Save upgrades into window.localStorage.
    for(var id in upgrades){
        // Save upgrade keybinds, if different from default.
        if(document.getElementById('keybind-' + id).value != upgrades[id]['keybind']){
            window.localStorage.setItem(
              'Click.htm-keybind-' + id,
              document.getElementById('keybind-' + id).value
            );

        }else{
            window.localStorage.removeItem('Click.htm-keybind-' + id);
        }

        // Only save level if greater than 0.
        if(upgrades[id]['level'] > 0){
            window.localStorage.setItem(
              'Click.htm-upgrade-' + id,
              upgrades[id]['level']
            );
        }

    }

    // Save click keybind, if different from default.
    if(document.getElementById('keybind-click').value != 'C'){
        window.localStorage.setItem(
          'Click.htm-keybind-click',
          document.getElementById('keybind-click').value
        );

    }else{
        window.localStorage.removeItem('Click.htm-keybind-click');
    }
};

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: show settings.
    if(key === 187){
        settings_toggle(true);
        return;

    // -: hide settings.
    }else if(key === 189){
        settings_toggle(false);
        return;
    }

    key = String.fromCharCode(key);

    if(key === document.getElementById('keybind-click').value){
        if(keyclick_ready > 0){
            keyclick_ready = 0;
            click_button();
        }

        return;
    }

    for(var id in upgrades){
        if(key != document.getElementById('keybind-' + id).value){
            continue;
        }

        purchase(
          id,
          upgrades[id]['cost'],
          'clicks-' + upgrades[id]['type']
        );
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === document.getElementById('keybind-click').value){
        keyclick_ready = 1;
    }
};

window.onload = function(){
    // Load values from window.localStorage, if they exist.
    document.getElementById('keybind-click').value =
      window.localStorage.getItem('Click.htm-keybind-click') === null
        ? 'C'
        : window.localStorage.getItem('Click.htm-keybind-click');

    var ids = {
      'clicks': 0,
      'clicks-multiplier': 100,
      'clicks-per-click': 1,
      'clicks-per-second': 0,
    };

    for(var id in ids){
        document.getElementById(id).innerHTML =
          window.localStorage.getItem('Click.htm-' + id) === null
            ? ids[id]
            : window.localStorage.getItem('Click.htm-' + id);
    }

    var multiplier = (parseInt(document.getElementById('clicks-multiplier').innerHTML) / 100);
    document.getElementById('clicks-per-click-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-click').innerHTML) * multiplier);
    document.getElementById('clicks-per-second-multiplied').innerHTML =
      Math.floor(parseInt(document.getElementById('clicks-per-second').innerHTML) * multiplier);

    for(id in upgrades){
        var upgrade = id[0].toUpperCase() + id.substring(1);

        document.getElementById('upgrades').innerHTML +=
          '0'
          + ' <input onclick=purchase("'
            + id + '",'
            + upgrades[id]['cost'] + ',"'
            + 'clicks-' + upgrades[id]['type']
          + '") type=button value=' + upgrade + '>'
          + '<input class=keybind id=keybind-' + id + ' maxlength=1>'
          + ' ' + (upgrades[id]['base'] + upgrades[id]['cost']) +'
';
    }

    for(id in upgrades){
        document.getElementById('keybind-' + id).value =
          window.localStorage.getItem('Click.htm-keybind-' + id) === null
            ? upgrades[id]['keybind']
            : window.localStorage.getItem('Click.htm-keybind-' + id);

        var level = parseInt(window.localStorage.getItem('Click.htm-upgrade-' + id));
        level = isNaN(level)
          ? 0
          : level;
        while(level > 0){
            purchase(
              id,
              upgrades[id]['cost'],
              'clicks-' + upgrades[id]['type'],
              true
            );
            level -= 1;
        }
    }

    window.setTimeout(
      second,
      1000
    );
};
<|endoftext|>


<commit_before>
var gocdMapper = function(_, moment, gocdReader) {
  var readHistoryAndActivity = function(callWhenDone) {
    gocdReader.readData(function(data) {

      var activityHaring = mapActivityDataToFigures(data.activity);
      var historyHaring = mapPipelineDataToFigures(data.history);

      var greatSuccess = ! _.any(data.history, function(entry) {
        return ! entry.wasSuccessful();
      });

      var historyFigures = historyHaring.figures;
      mapInitialsFromHistoryToActivity(historyFigures, activityHaring.figures);

      var finalFigures = { greatSuccess: greatSuccess };
      finalFigures.figures = activityHaring.figures.concat(historyFigures);
      finalFigures.background = activityHaring.background || historyHaring.background;

      callWhenDone(finalFigures);

    });

  };

  function mapInitialsFromHistoryToActivity(historyFigures, activityFigures) {
    _.each(activityFigures, function(activityFigure) {
      var historyFigureWithSameKey = _.find(historyFigures, function(historyFigure) {
        return activityFigure.key === historyFigure.key;
      });
      if(historyFigureWithSameKey !== undefined) {
        activityFigure.initials = historyFigureWithSameKey.hiddenInitials;
      }
    });
  }

  function getFigureType(entry, lastEntryWasSuccessful) {

    if(entry.wasSuccessful() && !lastEntryWasSuccessful) {
      return 'flying';
    } else if (entry.wasSuccessful()) {
      return 'walking';
    } else if ( ! entry.wasSuccessful() && !lastEntryWasSuccessful) {
      return 'crawling';
    } else {
      return 'stumbling';
    }
  }

  function getColor(entry) {
    if(entry.wasSuccessful()) {
      return 'COLD';
    } else {
      return 'WARM';
    }
  }

  function getInitialsOfAuthor(entry) {

    function onlyAtoZ(character) {
      var isLetter = character.toLowerCase() >= "a" && character.toLowerCase() <= "z";
      if (! isLetter) {
        return 'x';
      } else {
        return character;
      }
    }

    if(entry.author !== undefined && entry.author.name !== undefined) {
      var nameParts = entry.author.name.split(' ');

      var initials = _.map(nameParts, function(namePart, index) {
        if (index !== nameParts.length - 1) {
          return onlyAtoZ(namePart[0]);
        } else {
          return onlyAtoZ(namePart[0]) + onlyAtoZ(namePart[1]);
        }
      }).join('');

      return initials.toLowerCase().substr(0, 3);
    }
  }

  function compareNumbers(a, b) {
    // JS does lexicographical sorting by default, need to sort by number
    return a - b;
  }

  function mapPipelineDataToFigures(history, callWhenDone) {

    function getChangesByInfo(historyEntry) {
      return 'changes by ' + (historyEntry.author ? historyEntry.author.name : 'UNKNOWN');
    }

    function getInfo(historyEntry, buildNumber) {
      var theTime = moment(historyEntry.time).format('MMMM Do YYYY, h:mm:ss a');
      var theCommit = historyEntry.materials ? historyEntry.materials.comment : 'Unknown change';
      var theAuthor = historyEntry.author ? historyEntry.author.name : 'Unknown author';
      var theResult = historyEntry.wasSuccessful() ? 'Success' : historyEntry.stageFailed + ' | ' + getChangesByInfo(historyEntry);
      return '[' + buildNumber + '] ' + theTime + ' | ' + theResult + ' | ' + theCommit + ' | ' + theAuthor;
    }

    var keysDescending = _.keys(history).sort(compareNumbers).reverse();
    if(keysDescending.length === 0) {
      return { figures: [] };
    }

    var figures = _.map(keysDescending, function(key, index) {

      var entry = history[key];
      var previous = index < keysDescending.length ? history[keysDescending[index + 1]] : undefined;

      return {
        color: getColor(entry),
        info: getInfo(entry, key),
        type: getFigureType(entry, previous ? previous.wasSuccessful() : true),
        hiddenInitials: getInitialsOfAuthor(entry), // need to save initials for merging with activity
        initials: entry.wasSuccessful() ? undefined : getInitialsOfAuthor(entry),
        key: key
      };
    });

    var lastBuildSuccessful = history[keysDescending[0]].wasSuccessful();

    var changesExist = true;
    var result = {
      background: lastBuildSuccessful ? 'green' : 'orange',
      figures: figures
    };

    if(callWhenDone !== undefined) {
      callWhenDone(result, changesExist);
    } else {
      return result;
    }

  }

  function mapActivityDataToFigures(activity, callWhenDone) {

    function getFigureTypeForActivity(entry) {

      if(entry.activity === 'Building') {
        return 'skating';
      } else {
        return getFigureType(entry, true);
      }
    }

    function getColor(entry) {
      if(entry.lastBuildStatus === 'Success') {
        return 'COLD';
      } else if (entry.lastBuildStatus === 'Failure') {
        return 'WARM';
      } else {
        return 'grey';
      }
    }

    function getInfo(entry) {
      var entryTitle = '[' + entry.buildNumber + '] ' + entry.name;
      if(entry.activity === 'Building') {
        return entryTitle + ' is building';
      } else {
        var info = entryTitle + ' | ' + entry.lastBuildStatus;
        if(!entry.wasSuccessful() && entry.author) {
          info += ' | changes by ' + entry.author.name;
        }
        return info;
      }
    }

    var figures = _.map(activity.jobs, function(entry) {
      return {
        color: getColor(entry),
        info: getInfo(entry),
        showInfo: ! entry.wasSuccessful(),
        type: getFigureTypeForActivity(entry),
        border: 'dotted',
        initials: getInitialsOfAuthor(entry),
        key: entry.buildNumber
      }
    });

    var isBuilding = _.any(activity.jobs, function(entry) {
      return entry.activity === 'Building';
    });

    var changesExist = true;
    if(callWhenDone !== undefined) {
      callWhenDone({ figures: figures }, changesExist);
    } else {
      return {
        background: isBuilding ? 'blue' : undefined,
        figures: figures
      };
    }

  }

  return {
    readHistoryAndActivity: readHistoryAndActivity
  }
};

define(['lodash', 'moment', 'server/sources/gocd/gocdReader'], gocdMapper);<commit_msg>Debugging GS<commit_after>
var gocdMapper = function(_, moment, gocdReader) {
  var readHistoryAndActivity = function(callWhenDone) {
    gocdReader.readData(function(data) {

      var activityHaring = mapActivityDataToFigures(data.activity);
      var historyHaring = mapPipelineDataToFigures(data.history);

      var greatSuccess = ! _.any(data.history, function(entry) {
        return ! entry.wasSuccessful();
      });
      var allResults = _.map(data.history, function(entry) {
        return entry.wasSuccessful();
      });
      console.log('GREAT SUCCESS?', greatSuccess, allResults);

      var historyFigures = historyHaring.figures;
      mapInitialsFromHistoryToActivity(historyFigures, activityHaring.figures);

      var finalFigures = { greatSuccess: greatSuccess };
      finalFigures.figures = activityHaring.figures.concat(historyFigures);
      finalFigures.background = activityHaring.background || historyHaring.background;

      callWhenDone(finalFigures);

    });

  };

  function mapInitialsFromHistoryToActivity(historyFigures, activityFigures) {
    _.each(activityFigures, function(activityFigure) {
      var historyFigureWithSameKey = _.find(historyFigures, function(historyFigure) {
        return activityFigure.key === historyFigure.key;
      });
      if(historyFigureWithSameKey !== undefined) {
        activityFigure.initials = historyFigureWithSameKey.hiddenInitials;
      }
    });
  }

  function getFigureType(entry, lastEntryWasSuccessful) {

    if(entry.wasSuccessful() && !lastEntryWasSuccessful) {
      return 'flying';
    } else if (entry.wasSuccessful()) {
      return 'walking';
    } else if ( ! entry.wasSuccessful() && !lastEntryWasSuccessful) {
      return 'crawling';
    } else {
      return 'stumbling';
    }
  }

  function getColor(entry) {
    if(entry.wasSuccessful()) {
      return 'COLD';
    } else {
      return 'WARM';
    }
  }

  function getInitialsOfAuthor(entry) {

    function onlyAtoZ(character) {
      var isLetter = character.toLowerCase() >= "a" && character.toLowerCase() <= "z";
      if (! isLetter) {
        return 'x';
      } else {
        return character;
      }
    }

    if(entry.author !== undefined && entry.author.name !== undefined) {
      var nameParts = entry.author.name.split(' ');

      var initials = _.map(nameParts, function(namePart, index) {
        if (index !== nameParts.length - 1) {
          return onlyAtoZ(namePart[0]);
        } else {
          return onlyAtoZ(namePart[0]) + onlyAtoZ(namePart[1]);
        }
      }).join('');

      return initials.toLowerCase().substr(0, 3);
    }
  }

  function compareNumbers(a, b) {
    // JS does lexicographical sorting by default, need to sort by number
    return a - b;
  }

  function mapPipelineDataToFigures(history, callWhenDone) {

    function getChangesByInfo(historyEntry) {
      return 'changes by ' + (historyEntry.author ? historyEntry.author.name : 'UNKNOWN');
    }

    function getInfo(historyEntry, buildNumber) {
      var theTime = moment(historyEntry.time).format('MMMM Do YYYY, h:mm:ss a');
      var theCommit = historyEntry.materials ? historyEntry.materials.comment : 'Unknown change';
      var theAuthor = historyEntry.author ? historyEntry.author.name : 'Unknown author';
      var theResult = historyEntry.wasSuccessful() ? 'Success' : historyEntry.stageFailed + ' | ' + getChangesByInfo(historyEntry);
      return '[' + buildNumber + '] ' + theTime + ' | ' + theResult + ' | ' + theCommit + ' | ' + theAuthor;
    }

    var keysDescending = _.keys(history).sort(compareNumbers).reverse();
    if(keysDescending.length === 0) {
      return { figures: [] };
    }

    var figures = _.map(keysDescending, function(key, index) {

      var entry = history[key];
      var previous = index < keysDescending.length ? history[keysDescending[index + 1]] : undefined;

      return {
        color: getColor(entry),
        info: getInfo(entry, key),
        type: getFigureType(entry, previous ? previous.wasSuccessful() : true),
        hiddenInitials: getInitialsOfAuthor(entry), // need to save initials for merging with activity
        initials: entry.wasSuccessful() ? undefined : getInitialsOfAuthor(entry),
        key: key
      };
    });

    var lastBuildSuccessful = history[keysDescending[0]].wasSuccessful();

    var changesExist = true;
    var result = {
      background: lastBuildSuccessful ? 'green' : 'orange',
      figures: figures
    };

    if(callWhenDone !== undefined) {
      callWhenDone(result, changesExist);
    } else {
      return result;
    }

  }

  function mapActivityDataToFigures(activity, callWhenDone) {

    function getFigureTypeForActivity(entry) {

      if(entry.activity === 'Building') {
        return 'skating';
      } else {
        return getFigureType(entry, true);
      }
    }

    function getColor(entry) {
      if(entry.lastBuildStatus === 'Success') {
        return 'COLD';
      } else if (entry.lastBuildStatus === 'Failure') {
        return 'WARM';
      } else {
        return 'grey';
      }
    }

    function getInfo(entry) {
      var entryTitle = '[' + entry.buildNumber + '] ' + entry.name;
      if(entry.activity === 'Building') {
        return entryTitle + ' is building';
      } else {
        var info = entryTitle + ' | ' + entry.lastBuildStatus;
        if(!entry.wasSuccessful() && entry.author) {
          info += ' | changes by ' + entry.author.name;
        }
        return info;
      }
    }

    var figures = _.map(activity.jobs, function(entry) {
      return {
        color: getColor(entry),
        info: getInfo(entry),
        showInfo: ! entry.wasSuccessful(),
        type: getFigureTypeForActivity(entry),
        border: 'dotted',
        initials: getInitialsOfAuthor(entry),
        key: entry.buildNumber
      }
    });

    var isBuilding = _.any(activity.jobs, function(entry) {
      return entry.activity === 'Building';
    });

    var changesExist = true;
    if(callWhenDone !== undefined) {
      callWhenDone({ figures: figures }, changesExist);
    } else {
      return {
        background: isBuilding ? 'blue' : undefined,
        figures: figures
      };
    }

  }

  return {
    readHistoryAndActivity: readHistoryAndActivity
  }
};

define(['lodash', 'moment', 'server/sources/gocd/gocdReader'], gocdMapper);<|endoftext|>


<commit_before>// This module exports a function that copies all the static assets into the
// appropriate location in the build output directory.

'use strict'

const path = require('path')
const fs = require('fs-extra')
const CONFIG = require('../config')
const glob = require('glob')
const includePathInPackagedApp = require('./include-path-in-packaged-app')

module.exports = function () {
  console.log(`Copying assets to ${CONFIG.intermediateAppPath}`)
  let srcPaths = [
    path.join(CONFIG.repositoryRootPath, 'benchmarks', 'benchmark-runner.js'),
    path.join(CONFIG.repositoryRootPath, 'dot-atom'),
    path.join(CONFIG.repositoryRootPath, 'exports'),
    path.join(CONFIG.repositoryRootPath, 'package.json'),
    path.join(CONFIG.repositoryRootPath, 'static'),
    path.join(CONFIG.repositoryRootPath, 'src'),
    path.join(CONFIG.repositoryRootPath, 'vendor')
  ]
  srcPaths = srcPaths.concat(glob.sync(path.join(CONFIG.repositoryRootPath, 'spec', '*.*'), {ignore: path.join('**', '*-spec.*')}))
  for (let srcPath of srcPaths) {
    fs.copySync(srcPath, computeDestinationPath(srcPath), {filter: includePathInPackagedApp})
  }

  // Run a copy pass to dereference symlinked directories under node_modules.
  // We do this to ensure that symlinked repo-local bundled packages get
  // copied to the output folder correctly.  We dereference only the top-level
  // symlinks and not nested symlinks to avoid issues where symlinked binaries
  // are duplicated in Atom's installation packages (see atom/atom#18490).
  const nodeModulesPath = path.join(CONFIG.repositoryRootPath, 'node_modules')
  glob.sync(path.join(nodeModulesPath, '*'))
      .map(p => fs.lstatSync(p).isSymbolicLink() ? fs.readlinkSync(p) : p)
      .forEach(modulePath => {
        const destPath = path.join(CONFIG.intermediateAppPath, 'node_modules', path.basename(modulePath))
        fs.copySync(modulePath, destPath, { filter: includePathInPackagedApp })
      })

  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'png', '1024.png'),
    path.join(CONFIG.intermediateAppPath, 'resources', 'atom.png')
  )
}

function computeDestinationPath (srcPath) {
  const relativePath = path.relative(CONFIG.repositoryRootPath, srcPath)
  return path.join(CONFIG.intermediateAppPath, relativePath)
}
<commit_msg>Resolve dereferenced symlinks relative to node_modules<commit_after>// This module exports a function that copies all the static assets into the
// appropriate location in the build output directory.

'use strict'

const path = require('path')
const fs = require('fs-extra')
const CONFIG = require('../config')
const glob = require('glob')
const includePathInPackagedApp = require('./include-path-in-packaged-app')

module.exports = function () {
  console.log(`Copying assets to ${CONFIG.intermediateAppPath}`)
  let srcPaths = [
    path.join(CONFIG.repositoryRootPath, 'benchmarks', 'benchmark-runner.js'),
    path.join(CONFIG.repositoryRootPath, 'dot-atom'),
    path.join(CONFIG.repositoryRootPath, 'exports'),
    path.join(CONFIG.repositoryRootPath, 'package.json'),
    path.join(CONFIG.repositoryRootPath, 'static'),
    path.join(CONFIG.repositoryRootPath, 'src'),
    path.join(CONFIG.repositoryRootPath, 'vendor')
  ]
  srcPaths = srcPaths.concat(glob.sync(path.join(CONFIG.repositoryRootPath, 'spec', '*.*'), {ignore: path.join('**', '*-spec.*')}))
  for (let srcPath of srcPaths) {
    fs.copySync(srcPath, computeDestinationPath(srcPath), {filter: includePathInPackagedApp})
  }

  // Run a copy pass to dereference symlinked directories under node_modules.
  // We do this to ensure that symlinked repo-local bundled packages get
  // copied to the output folder correctly.  We dereference only the top-level
  // symlinks and not nested symlinks to avoid issues where symlinked binaries
  // are duplicated in Atom's installation packages (see atom/atom#18490).
  const nodeModulesPath = path.join(CONFIG.repositoryRootPath, 'node_modules')
  glob.sync(path.join(nodeModulesPath, '*'))
      .map(p => fs.lstatSync(p).isSymbolicLink() ? path.resolve(nodeModulesPath, fs.readlinkSync(p)) : p)
      .forEach(modulePath => {
        const destPath = path.join(CONFIG.intermediateAppPath, 'node_modules', path.basename(modulePath))
        fs.copySync(modulePath, destPath, { filter: includePathInPackagedApp })
      })

  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'png', '1024.png'),
    path.join(CONFIG.intermediateAppPath, 'resources', 'atom.png')
  )
}

function computeDestinationPath (srcPath) {
  const relativePath = path.relative(CONFIG.repositoryRootPath, srcPath)
  return path.join(CONFIG.intermediateAppPath, relativePath)
}
<|endoftext|>


<commit_before>var map, markers = [], lines = [];

window.onload = function(){
	$(document).bind("keyup keydown", function(e){
    	if(e.ctrlKey && e.keyCode == 76)
        	resetMap();
        	$("#query-text").focus();
	});
};

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		mapTypeId: 'roadmap',
    	center: {lat: 41.158, lng: -8.629},
    	zoom: 2
    });
}

function centerMap() {
	map.panTo({lat: 41.158, lng: -8.629});
	map.setZoom(2);
}

function removeLines() {
	for (var i = 0; i < lines.length; i++)
    	lines[i].setMap(null);
    lines = [];
}

function removeMarkers() {
	for (var i = 0; i < markers.length; i++)
    	markers[i].setMap(null);
    markers = [];
}

function resetMap() {
	removeLines();
	removeMarkers();
	centerMap();
	$("#show-error").hide();
	$("#query-text").val("");
	$("#response-list").hide();
	$("#query-text").focus();
}

function query() {
	var question = $('#query-text').val();

	question = question.toLowerCase();
	question = question.replace('?','');
	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/query?question='+question,
	    //data: question,
	    success: function(response){
	    	console.log(response);
	    	var response_array = response.replace(new RegExp(/[\[\]]/g), "").split(",");

	    	if (question.indexOf("rivers") >= 0)
	    		displayRivers(response_array);
	    	else if (question.indexOf("capital") >= 0)
	    		displayCapitals(response_array);
	    	else if (question.indexOf("largest city") >= 0)
	    		displayCapitals(response_array);
	    	else if (question.indexOf("largest country") >= 0)
	    		displayCountries(response_array);
	    	else if (question.indexOf("countries") >= 0)
	    		displayCountries(response_array);
	    	else if (question.indexOf("cities") >= 0 && question.indexOf("continents") == -1)
	    		displayCities(response_array);
	    	else if (question.indexOf("bordering") >= 0)
	    		displayCountries(response_array);

	    	$("#response-list").show();
	    	$("#error").text("");
	    	$("#show-error").hide();
	    	showResponseOnList(response_array);

	    },
	    error: function(response){
	    	console.log("FAIL");
    		sentences = ["Do you think this is funny?","I know where you live!","Stop playing around!","Are you dumb?"];
    		var sentence = sentences[Math.floor(Math.random()*sentences.length)];
    		//alert(sentence);
    		$("#show-error").show();
    		$("#error").text(sentence);
	    }
	});
}

function showResponseOnList(response_array) {
	$('#response-list').empty();
	//var response_array = response.replace(new RegExp(/[\[\]]/g), "").split(",");
	for (var i = 0; i < response_array.length; i++) {
        var li = document.createElement('li');
        li.innerHTML = response_array[i];
        $('#response-list').append(li);
    }
}

function displayRivers(rivers_array) {
	for (var i = 0; i < rivers_array.length; i++)
		displayRiver(rivers_array[i]);
}

function displayRiver(river) {
	var json_coords_array = [];
	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?river=' + river,
	    success: function(response){
	    	var coords_array = response.substring(2,response.length-3).split("],[");

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)};
 				json_coords_array.push(coords_json);
			}

			drawLine(river, json_coords_array);
	    }
	});
}

function displayCapitals(capital_array) {
	//var capital = response.substring(1,response.length-2);
	console.log(capital_array[0]);
	displayCapital(capital_array[0]);
}

function displayCapital(capital) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?capital=' + capital,
	    success: function(response){
	    	console.log(response);
	    	var coords_array = response.substring(2,response.length-3).split(",");
	    	console.log(coords_array);
    		var lat = coords_array[0];
    		var lng = coords_array[1];
    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}

			createMarker( capital, coords_json);
			map.panTo(coords_json);
			map.setZoom(4);
			console.log(lat+":"+lng);
	    }
	});
}

function displayCountries(countries_array) {
		if (countries_array.length == 1) {
			console.log(countries_array[0]);
			displayCountry(countries_array[0]);
		}
		else {
			for (var i = 0; i < countries_array.length; i++){
				console.log(countries_array[i]);
				country = countries_array[i];
				displayCountry2(country);
			}
		}
}

function displayCountry(country) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?country=' + country,
	    success: function(response){
	    	console.log(response);

    		var coords_array = response.substring(2,response.length-3).split("],[");
	    	console.log(coords_array);

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}
	    		createMarker( country, coords_json);
			    map.panTo(coords_json);
			}

			map.setZoom(3);
	    }
	});
}

function displayCountry2(country) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?capital=' + country,
	    success: function(response){
	    	console.log(response);

    		var coords_array = response.substring(2,response.length-3).split("],[");
	    	console.log(coords_array);

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}
	    		createMarker( country, coords_json);
			    map.panTo(coords_json);
			}

			map.setZoom(3);
	    }
	});
}

function displayCities(cities_array) {
		console.log(cities_array.length);
		for (var i = 0; i < cities_array.length; i++){
			console.log(cities_array[i]);
			city = cities_array[i];
			displayCity(city);
		}
}

function displayCity(city) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?city=' + city,
	    success: function(response){
	    	//console.log("resposta: "+response);

    		var coords_array = response.substring(2,response.length-3).split("],[");
	    	//console.log("coords array: "+coords_array);

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}
	    		if (lat!==undefined && lng!==undefined){
		    		createMarker( city, coords_json);
				    map.panTo(coords_json);
				}
			}

			map.setZoom(3);
	    }
	});
}

function drawLine(name, path) {
	var line = new google.maps.Polyline({
		path: path,
		title: name,
		geodesic: true,
		strokeColor: '#06425C',
		strokeOpacity: 1.0,
		strokeWeight: 4
	});
  	lines.push(line);
  	line.setMap(map);
}

function createMarker(name, myLatLng){
	var marker = new google.maps.Marker({
       position: myLatLng,
       map: map,
       title: name
    });
    markers.push(marker);
}<commit_msg>added region verification for questions (no need to write underscore anymore)<commit_after>var map, markers = [], lines = [];
var region_keywords = ['northern', 'southern', 'eastern', 'western', 'central', 'middle', 'south', 'australia and'];

window.onload = function() {
	$(document).bind("keyup keydown", function(e) {
    	if (e.ctrlKey && e.keyCode == 76)
        	resetMap();
        	$("#query-text").focus();
	});
};

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		mapTypeId: 'roadmap',
    	center: {lat: 41.158, lng: -8.629},
    	zoom: 2
    });
}

function centerMap() {
	map.panTo({lat: 41.158, lng: -8.629});
	map.setZoom(2);
}

function removeLines() {
	for (var i = 0; i < lines.length; i++)
    	lines[i].setMap(null);
    lines = [];
}

function removeMarkers() {
	for (var i = 0; i < markers.length; i++)
    	markers[i].setMap(null);
    markers = [];
}

function resetMap() {
	removeLines();
	removeMarkers();
	centerMap();
	$("#show-error").hide();
	$("#query-text").val("");
	$("#response-list").hide();
	$("#query-text").focus();
}

function formatQuestion(raw_question) {
	raw_question = raw_question.toLowerCase();
	raw_question = raw_question.replace('?','');

	for (var i = 0; i < region_keywords.length; i++) {
		var index = raw_question.indexOf(region_keywords[i]);
		if (index >= 0) {
			console.log(region_keywords[i]);
			var question_first_part = raw_question.substring(0, index);
			var region = raw_question.substring(index).replace(/ /g, '_');
		}
	}
	return question_first_part + region;
}

function query() {
	var raw_question = $('#query-text').val();
	var question = formatQuestion(raw_question);

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/query?question='+question,
	    success: function(response){
	    	console.log(response);
	    	var response_array = response.replace(new RegExp(/[\[\]]/g), "").split(",");

	    	if (question.indexOf("rivers") >= 0)
	    		displayRivers(response_array);
	    	else if (question.indexOf("capital") >= 0)
	    		displayCapitals(response_array);
	    	else if (question.indexOf("largest city") >= 0)
	    		displayCapitals(response_array);
	    	else if (question.indexOf("largest country") >= 0)
	    		displayCountries(response_array);
	    	else if (question.indexOf("countries") >= 0)
	    		displayCountries(response_array);
	    	else if (question.indexOf("cities") >= 0 && question.indexOf("continents") == -1)
	    		displayCities(response_array);
	    	else if (question.indexOf("bordering") >= 0)
	    		displayCountries(response_array);

	    	$("#response-list").show();
	    	$("#error").text("");
	    	$("#show-error").hide();
	    	showResponseOnList(response_array);

	    },
	    error: function(response){
	    	console.log("FAIL");
    		sentences = ["Do you think this is funny?","I know where you live!","Stop playing around!","Are you dumb?"];
    		var sentence = sentences[Math.floor(Math.random()*sentences.length)];
    		//alert(sentence);
    		$("#show-error").show();
    		$("#error").text(sentence);
	    }
	});
}

function showResponseOnList(response_array) {
	$('#response-list').empty();
	//var response_array = response.replace(new RegExp(/[\[\]]/g), "").split(",");
	for (var i = 0; i < response_array.length; i++) {
        var li = document.createElement('li');
        li.innerHTML = response_array[i];
        $('#response-list').append(li);
    }
}

function displayRivers(rivers_array) {
	for (var i = 0; i < rivers_array.length; i++)
		displayRiver(rivers_array[i]);
}

function displayRiver(river) {
	var json_coords_array = [];
	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?river=' + river,
	    success: function(response){
	    	var coords_array = response.substring(2,response.length-3).split("],[");

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)};
 				json_coords_array.push(coords_json);
			}

			drawLine(river, json_coords_array);
	    }
	});
}

function displayCapitals(capital_array) {
	//var capital = response.substring(1,response.length-2);
	console.log(capital_array[0]);
	displayCapital(capital_array[0]);
}

function displayCapital(capital) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?capital=' + capital,
	    success: function(response){
	    	console.log(response);
	    	var coords_array = response.substring(2,response.length-3).split(",");
	    	console.log(coords_array);
    		var lat = coords_array[0];
    		var lng = coords_array[1];
    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}

			createMarker( capital, coords_json);
			map.panTo(coords_json);
			map.setZoom(4);
			console.log(lat+":"+lng);
	    }
	});
}

function displayCountries(countries_array) {
		if (countries_array.length == 1) {
			console.log(countries_array[0]);
			displayCountry(countries_array[0]);
		}
		else {
			for (var i = 0; i < countries_array.length; i++){
				console.log(countries_array[i]);
				country = countries_array[i];
				displayCountry2(country);
			}
		}
}

function displayCountry(country) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?country=' + country,
	    success: function(response){
	    	console.log(response);

    		var coords_array = response.substring(2,response.length-3).split("],[");
	    	console.log(coords_array);

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}
	    		createMarker( country, coords_json);
			    map.panTo(coords_json);
			}

			map.setZoom(3);
	    }
	});
}

function displayCountry2(country) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?capital=' + country,
	    success: function(response){
	    	console.log(response);

    		var coords_array = response.substring(2,response.length-3).split("],[");
	    	console.log(coords_array);

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}
	    		createMarker( country, coords_json);
			    map.panTo(coords_json);
			}

			map.setZoom(3);
	    }
	});
}

function displayCities(cities_array) {
		console.log(cities_array.length);
		for (var i = 0; i < cities_array.length; i++){
			console.log(cities_array[i]);
			city = cities_array[i];
			displayCity(city);
		}
}

function displayCity(city) {

	$.ajax({
	    type: 'GET',
	    contentType: 'text/plain',
	    url: '/coords?city=' + city,
	    success: function(response){
	    	//console.log("resposta: "+response);

    		var coords_array = response.substring(2,response.length-3).split("],[");
	    	//console.log("coords array: "+coords_array);

	    	for (var i = 0; i < coords_array.length; i++) {
	    		var lat = coords_array[i].split(",")[0];
	    		var lng = coords_array[i].split(",")[1];
	    		var coords_json = {"lat":parseFloat(lat), "lng":parseFloat(lng)}
	    		if (lat!==undefined && lng!==undefined){
		    		createMarker( city, coords_json);
				    map.panTo(coords_json);
				}
			}

			map.setZoom(3);
	    }
	});
}

function drawLine(name, path) {
	var line = new google.maps.Polyline({
		path: path,
		title: name,
		geodesic: true,
		strokeColor: '#06425C',
		strokeOpacity: 1.0,
		strokeWeight: 4
	});
  	lines.push(line);
  	line.setMap(map);
}

function createMarker(name, myLatLng){
	var marker = new google.maps.Marker({
       position: myLatLng,
       map: map,
       title: name
    });
    markers.push(marker);
}<|endoftext|>