<commit_before>var config = require('./config');
var mongo = require('./mongoFunctions.js');

function sendSubstitutions(senderID){
	mongo.findById(userId,'person',function(err,doc){
		if (err)
			console.log('prolem with settings: ',userId);
		console.log('Settings file: ',doc);
		var params = (doc['settings']);
		if(params == '')
			params={setClass:'all',notification:'no'};
		var table=[];
		console.log(params.setClass);
	})
}

function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  // The 'payload' param is a developer-defined field which is set in a postback
  // button for Structured Messages.
  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  sendTextMessage(senderID, "Postback called");
}

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;

  /*if (messageText) {

    // If we receive a text message, check to see if it matches a keyword
    // and send back the example. Otherwise, just echo the text we received.
    switch (messageText) {
      case 'generic':
        sendGenericMessage(senderID);
        break;

      default:
        sendTextMessage(senderID, messageText);
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment received");
  }*/
  sendSubstitutions(senderID);
  sendTextMessage(senderID, messageText);
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<commit_msg>fix userId-senderId<commit_after>var config = require('./config');
var mongo = require('./mongoFunctions.js');

function sendSubstitutions(senderID){
	mongo.findById(senderId,'person',function(err,doc){
		if (err)
			console.log('prolem with settings: ',userId);
		console.log('Settings file: ',doc);
		var params = (doc['settings']);
		if(params == '')
			params={setClass:'all',notification:'no'};
		var table=[];
		console.log(params.setClass);
	})
}

function receivedPostback(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfPostback = event.timestamp;

  // The 'payload' param is a developer-defined field which is set in a postback
  // button for Structured Messages.
  var payload = event.postback.payload;

  console.log("Received postback for user %d and page %d with payload '%s' " +
    "at %d", senderID, recipientID, payload, timeOfPostback);

  // When a postback is called, we'll send a message back to the sender to
  // let them know it was successful
  sendTextMessage(senderID, "Postback called");
}

function receivedMessage(event) {
  var senderID = event.sender.id;
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;

  /*if (messageText) {

    // If we receive a text message, check to see if it matches a keyword
    // and send back the example. Otherwise, just echo the text we received.
    switch (messageText) {
      case 'generic':
        sendGenericMessage(senderID);
        break;

      default:
        sendTextMessage(senderID, messageText);
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, "Message with attachment received");
  }*/
  sendSubstitutions(senderID);
  sendTextMessage(senderID, messageText);
}

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.7/me/messages',
    qs: { access_token: config.pageToken },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s",
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });
}

/*function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}*/

/*function sendGenericMessage(recipientId) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: "template",
        payload: {
          template_type: "generic",
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: "http://messengerdemo.parseapp.com/img/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: "http://messengerdemo.parseapp.com/img/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        }
      }
    }
  };

  callSendAPI(messageData);
}*/

exports.receivedPostback=receivedPostback;
exports.receivedMessage=receivedMessage;
<|endoftext|>


<commit_before>import notificationReducers from '../'
import notificationListReducer from '../notifications-list';
import visibilityFilterReducer from '../visibility-filter';
import { ADD_NOTIFICATION, READ_NOTIFICATION, SET_VISIBILITY_FILTER } from '../../actions';
import generateError from '../util/error-generator';
const INITAL_ARRAY_STATE = [{content: 'LOPEZ JOE'}];
describe('reducers', () => {
    it('should be a function', () => {
        expect(notificationReducers).to.be.a('function');
    });
    describe('notificationListReducer', () => {
        const REDUCER_NAME = 'NOTIFICATION_LIST';
        it('should be a function', () => {
            expect(notificationListReducer).to.be.a('function');
        });
        it('should return an empty array when the state is undefined', () => {
            expect(notificationListReducer()).to.be.an('array');
        });
        it('should return the initial array state when called without action', () => {
            expect(notificationListReducer(INITAL_ARRAY_STATE))
            .to.be.an('array')
            .and.equal(INITAL_ARRAY_STATE);
        });
        it('should return the initial state when the action is unkown', () => {
            expect(notificationListReducer(INITAL_ARRAY_STATE, {type: 'unknown'}))
            .to.be.an('array')
            .and.equal(INITAL_ARRAY_STATE);
        });
        describe('when it receive an ADD_NOTIFICATION action ', () => {
            it('should throw an error when the payload is not an object', () => {
                const NEW_NOTIF = {content: 'new super notification', author: 'rodrigo', targetURL: 'http://test.com'};
                const reducerCaller = (payload) => notificationListReducer(INITAL_ARRAY_STATE, {type: ADD_NOTIFICATION, payload});
                expect(() => reducerCaller(3)).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATION', payload: 3}, expectedType: 'object'}));
                expect(() => reducerCaller('ABCD')).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATION', payload: 'ABCD'}, expectedType: 'object'}));
            });
            it('should add the notification given ad add the read property', () => {
                const NEW_NOTIF = {content: 'new super notification', author: 'rodrigo', targetURL: 'http://test.com'};
                const reducerCall = notificationListReducer(INITAL_ARRAY_STATE, {type: ADD_NOTIFICATION, payload: NEW_NOTIF});
                expect(reducerCall).to.be.an('array');
                // it should add the read attribute
                expect(reducerCall).to.include({...NEW_NOTIF, read: false});
            });

        });
    });

});
<commit_msg>[reducers] Add the ADD_NOTIFICATIONS wrong payload test.<commit_after>import notificationReducers from '../'
import notificationListReducer from '../notifications-list';
import visibilityFilterReducer from '../visibility-filter';
import { ADD_NOTIFICATION, ADD_NOTIFICATIONS, READ_NOTIFICATION, SET_VISIBILITY_FILTER } from '../../actions';
import generateError from '../util/error-generator';
const INITAL_ARRAY_STATE = [{content: 'LOPEZ JOE'}];
describe('reducers', () => {
    it('should be a function', () => {
        expect(notificationReducers).to.be.a('function');
    });
    describe('notificationListReducer', () => {
        const REDUCER_NAME = 'NOTIFICATION_LIST';
        it('should be a function', () => {
            expect(notificationListReducer).to.be.a('function');
        });
        it('should return an empty array when the state is undefined', () => {
            expect(notificationListReducer()).to.be.an('array');
        });
        it('should return the initial array state when called without action', () => {
            expect(notificationListReducer(INITAL_ARRAY_STATE))
            .to.be.an('array')
            .and.equal(INITAL_ARRAY_STATE);
        });
        it('should return the initial state when the action is unkown', () => {
            expect(notificationListReducer(INITAL_ARRAY_STATE, {type: 'unknown'}))
            .to.be.an('array')
            .and.equal(INITAL_ARRAY_STATE);
        });
        describe('when it receive an ADD_NOTIFICATION action ', () => {
            it('should throw an error when the payload is not an object', () => {
                const NEW_NOTIF = {content: 'new super notification', author: 'rodrigo', targetURL: 'http://test.com'};
                const reducerCaller = (payload) => notificationListReducer(INITAL_ARRAY_STATE, {type: ADD_NOTIFICATION, payload});
                expect(() => reducerCaller(3)).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATION', payload: 3}, expectedType: 'object'}));
                expect(() => reducerCaller('ABCD')).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATION', payload: 'ABCD'}, expectedType: 'object'}));
            });
            it('should add the notification given ad add the read property', () => {
                const NEW_NOTIF = {content: 'new super notification', author: 'rodrigo', targetURL: 'http://test.com'};
                const reducerCall = notificationListReducer(INITAL_ARRAY_STATE, {type: ADD_NOTIFICATION, payload: NEW_NOTIF});
                expect(reducerCall).to.be.an('array');
                // it should add the read attribute
                expect(reducerCall).to.include({...NEW_NOTIF, read: false});
            });
        });
        describe('when it receive an ADD_NOTIFICATIONS action ', () => {
            it('should throw an error when the payload is not an array', () => {
                const NEW_NOTIF = {content: 'new super notification', author: 'rodrigo', targetURL: 'http://test.com'};
                const reducerCaller = (payload) => notificationListReducer(INITAL_ARRAY_STATE, {type: ADD_NOTIFICATIONS, payload});
                expect(() => reducerCaller(3)).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATIONS', payload: 3}, expectedType: 'array'}));
                expect(() => reducerCaller('ABCD')).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATIONS', payload: 'ABCD'}, expectedType: 'array'}));
                expect(() => reducerCaller({a: 'a'})).to.throw(generateError({name: REDUCER_NAME, action: {type: 'ADD_NOTIFICATIONS', payload: {a: 'a'}}, expectedType: 'array'}));
            });
            it.skip('should add the notification given ad add the read property', () => {
                const NEW_NOTIF = {content: 'new super notification', author: 'rodrigo', targetURL: 'http://test.com'};
                const reducerCall = notificationListReducer(INITAL_ARRAY_STATE, {type: ADD_NOTIFICATION, payload: NEW_NOTIF});
                expect(reducerCall).to.be.an('array');
                // it should add the read attribute
                expect(reducerCall).to.include({...NEW_NOTIF, read: false});
            });
        });
    });

});
<|endoftext|>


<commit_before>var DOMParser = require('../dom-parser').DOMParser;
var doc = new DOMParser().parseFromString(
    ''+
    '
'+
        'abcd'+
    '
'+
    '
'+
        ''+
    '
'+
    ''
    ,'text/html');

// console.log(doc.getElementsByAttribute('class', 'b'));
console.log(doc.getElementsByClassName('b', false))
//console.log(doc.querySelect('.div.aa       class#a a'))
//console.log(doc.findSelector('div.aa#in[ii="a"]'))
//console.log(doc.getElementsBySelector('a[href="aa"]#b'))
//console.log(doc.getElementsBySelector('div.b'))
// console.log(doc.querySelect('div.a a.b'))
console.log('end')
<commit_msg>More thorough example in test<commit_after>var DOMParser = require('../dom-parser').DOMParser;

var doc = new DOMParser().parseFromString(
  `

      abcd

      efgh

3:40

9:33

4:21

  `
  ,'text/html');

// console.log(doc.getElementsByAttribute('class', 'b'));
var ulResults = Array.from(doc.getElementsByClassName('video_link', false))
ulResults.forEach(el => console.log(el.getAttribute("href").replace(/\\/g, '')))
ulResults.forEach(el => console.log(el.querySelect('img')[0].getAttribute("alt")))
ulResults.forEach(el => console.log(el.getElementsByClassName('duration', false)[0].textContent))
// console.log(ulResults[0].querySelect('img')[0].getAttribute("alt"))

// console.log(doc.querySelect('.div.aa       class#a a'))
//console.log(doc.findSelector('div.aa#in[ii="a"]'))
//console.log(doc.getElementsBySelector('a[href="aa"]#b'))
//console.log(doc.getElementsBySelector('div.b'))
console.log('end')
<|endoftext|>


<commit_before>'use strict';
// @ts-check;
// ==================================================================================
// battery.js
// ----------------------------------------------------------------------------------
// Description:   System Information - library
//                for Node.js
// Copyright:     (c) 2014 - 2021
// Author:        Sebastian Hildebrandt
// ----------------------------------------------------------------------------------
// License:       MIT
// ==================================================================================
// 6. Battery
// ----------------------------------------------------------------------------------

const exec = require('child_process').exec;
const fs = require('fs');
const util = require('./util');

let _platform = process.platform;

const _linux = (_platform === 'linux');
const _darwin = (_platform === 'darwin');
const _windows = (_platform === 'win32');
const _freebsd = (_platform === 'freebsd');
const _openbsd = (_platform === 'openbsd');
const _netbsd = (_platform === 'netbsd');
const _sunos = (_platform === 'sunos');

function parseWinBatteryPart(lines, designCapacity, fullChargeCapacity) {
  const result = {};
  let status = util.getValue(lines, 'BatteryStatus', '=').trim();
  // 1 = "Discharging"
  // 2 = "On A/C"
  // 3 = "Fully Charged"
  // 4 = "Low"
  // 5 = "Critical"
  // 6 = "Charging"
  // 7 = "Charging High"
  // 8 = "Charging Low"
  // 9 = "Charging Critical"
  // 10 = "Undefined"
  // 11 = "Partially Charged"
  if (lines.join('').toLowerCase().indexOf('BatteryStatus') >= 0) {
    const statusValue = status ? parseInt(status) : 0;
    result.status = statusValue;
    result.hasBattery = true;
    result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', '=') || 0);
    result.designCapacity = parseInt(util.getValue(lines, 'DesignCapacity', '=') || designCapacity);
    result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', '=') || 0) / 1000.0;
    result.capacityUnit = 'mWh';
    result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', '=') || 0);
    result.currentCapacity = parseInt(result.maxcapacity * result.percent / 100);
    result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || (!(statusValue === 3) && !(statusValue === 1) && result.percent < 100);
    result.acConnected = result.ischarging || statusValue === 2;
    result.model = util.getValue(lines, 'DeviceID', '=');
  } else {
    result.status = -1;
  }

  return result;
}

module.exports = function (callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let result = {
        hasBattery: false,
        cycleCount: 0,
        isCharging: false,
        designedCapacity: 0,
        maxCapacity: 0,
        currentCapacity: 0,
        voltage: 0,
        capacityUnit: '',
        percent: 0,
        timeRemaining: null,
        acConnected: true,
        type: '',
        model: '',
        manufacturer: '',
        serial: ''
      };

      if (_linux) {
        let battery_path = '';
        if (fs.existsSync('/sys/class/power_supply/BAT1/uevent')) {
          battery_path = '/sys/class/power_supply/BAT1/';
        } else if (fs.existsSync('/sys/class/power_supply/BAT0/uevent')) {
          battery_path = '/sys/class/power_supply/BAT0/';
        }
        if (battery_path) {
          fs.readFile(battery_path + 'uevent', function (error, stdout) {
            if (!error) {
              let lines = stdout.toString().split('\n');

              result.isCharging = (util.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging');
              result.acConnected = result.isCharging;
              result.voltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0;
              result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
              result.cycleCount = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10);
              result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '='), 10) / 1000.0 / (result.voltage || 1));
              result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '='), 10) / 1000.0 / (result.voltage || 1)) | result.maxcapacity;
              result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 / (result.voltage || 1));
              if (!result.maxCapacity) {
                result.maxCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '='), 10) / 1000.0;
                result.designCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '='), 10) / 1000.0 | result.maxCapacity;
                result.currentCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0;
              }
              const percent = util.getValue(lines, 'POWER_SUPPLY_CAPACITY', '=');
              const energy = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10);
              const power = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10);
              const current = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10);

              result.percent = parseInt('0' + percent, 10);
              if (result.maxCapacity && result.currentCapacity) {
                result.hasBattery = true;
                if (!percent) {
                  result.percent = 100.0 * result.currentCapacity / result.maxCapacity;
                }
              }
              if (result.isCharging) {
                result.hasBattery = true;
              }
              if (energy && power) {
                result.timeRemaining = Math.floor(energy / power * 60);
              } else if (current && result.currentCapacity) {
                result.timeRemaining = Math.floor(result.currentCapacity / current * 60);
              }
              result.type = util.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '=');
              result.model = util.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '=');
              result.manufacturer = util.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '=');
              result.serial = util.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '=');
              if (callback) { callback(result); }
              resolve(result);
            } else {
              if (callback) { callback(result); }
              resolve(result);
            }
          });
        } else {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
      if (_freebsd || _openbsd || _netbsd) {
        exec('sysctl hw.acpi.battery hw.acpi.acline', function (error, stdout) {
          let lines = stdout.toString().split('\n');
          const batteries = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.units'), 10);
          const percent = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.life'), 10);
          result.hasBattery = (batteries > 0);
          result.cycleCount = null;
          result.isCharging = util.getValue(lines, 'hw.acpi.acline') !== '1';
          result.acConnected = result.isCharging;
          result.maxCapacity = null;
          result.currentCapacity = null;
          result.capacityUnit = 'unknown';
          result.percent = batteries ? percent : null;
          if (callback) { callback(result); }
          resolve(result);
        });
      }

      if (_darwin) {
        exec('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|BatterySerialNumber|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) {
          if (stdout) {
            let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n');
            result.cycleCount = parseInt('0' + util.getValue(lines, 'cyclecount', '='), 10);
            result.voltage = parseInt('0' + util.getValue(lines, 'voltage', '='), 10) / 1000.0;
            result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
            result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'maxcapacity', '='), 10) * (result.voltage || 1));
            result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'currentcapacity', '='), 10) * (result.voltage || 1));
            result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1));
            result.manufacturer = 'Apple';
            result.serial = util.getValue(lines, 'BatterySerialNumber', '=');
            let percent = null;
            const line = util.getValue(lines, 'internal', 'Battery');
            let parts = line.split(';');
            if (parts && parts[0]) {
              let parts2 = parts[0].split('\t');
              if (parts2 && parts2[1]) {
                percent = parseFloat(parts2[1].trim().replace(/%/g, ''));
              }
            }
            if (parts && parts[1]) {
              result.isCharging = (parts[1].trim() === 'charging');
              result.acConnected = (parts[1].trim() !== 'discharging');
            } else {
              result.isCharging = util.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes';
              result.acConnected = result.isCharging;
            }
            if (result.maxCapacity && result.currentCapacity) {
              result.hasBattery = true;
              result.type = 'Li-ion';
              result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity);
              if (!result.isCharging) {
                result.timeRemaining = parseInt('0' + util.getValue(lines, 'TimeRemaining', '='), 10);
              }
            }
          }
          if (callback) { callback(result); }
          resolve(result);
        });
      }
      if (_sunos) {
        if (callback) { callback(result); }
        resolve(result);
      }
      if (_windows) {
        try {
          const workload = [];
          workload.push(util.wmic('Path Win32_Battery Get /value'));
          workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
          workload.push(util.powerShell('(Get-WmiObject -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
          util.promiseAll(
            workload
          ).then(data => {
            if (data) {
              let parts = data.results[0].split(/\n\s*\n/);
              let designCapacities = data.results[1].split('\r\n');
              let fullChargeCapacities = data.results[2].split('\r\n');
              if (parts && parts.length) {
                let first = false;
                let additionalBatteries = [];
                for (let i = 0; i < parts.length; i++) {
                  let lines = parts[i].split('\r\n');
                  const designCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util.toInt(designCapacities[i]) : 0;
                  const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util.toInt(fullChargeCapacities[i]) : 0;
                  const parsed = parseWinBatteryPart(lines, designCapacity, fullChargeCapacity);
                  if (!first && parsed.status > 0 && parsed.status !== 10) {
                    result.hasBattery = parsed.hasBattery;
                    result.maxCapacity = parsed.maxCapacity;
                    result.designCapacity = parsed.designCapacity;
                    result.voltage = parsed.voltage;
                    result.capacityUnit = parsed.capacityUnit;
                    result.percent = parsed.percent;
                    result.currentCapacity = parsed.currentCapacity;
                    result.isCharging = parsed.isCharging;
                    result.acConnected = parsed.acConnected;
                    result.model = parsed.model;
                    first = true;
                  } else if (parsed.status !== -1) {
                    additionalBatteries.push(
                      {
                        hasBattery: parsed.hasBattery,
                        maxCapacity: parsed.maxCapacity,
                        designCapacity: parsed.designCapacity,
                        voltage: parsed.voltage,
                        capacityUnit: parsed.capacityUnit,
                        percent: parsed.percent,
                        currentCapacity: parsed.currentCapacity,
                        isCharging: parsed.isCharging,
                        timeRemaining: null,
                        acConnected: parsed.acConnected,
                        model: parsed.model,
                        type: '',
                        manufacturer: '',
                        serial: ''
                      }
                    );
                  }
                }
                if (!first && additionalBatteries.length) {
                  result = additionalBatteries[0];
                  additionalBatteries.shift();
                }
                if (additionalBatteries.length) {
                  result.additionalBatteries = additionalBatteries;
                }
              }
            }
            if (callback) { callback(result); }
            resolve(result);
          });
        } catch (e) {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
    });
  });
};
<commit_msg>fix: windows battery Dell & ThinkPad<commit_after>'use strict';
// @ts-check;
// ==================================================================================
// battery.js
// ----------------------------------------------------------------------------------
// Description:   System Information - library
//                for Node.js
// Copyright:     (c) 2014 - 2021
// Author:        Sebastian Hildebrandt
// ----------------------------------------------------------------------------------
// License:       MIT
// ==================================================================================
// 6. Battery
// ----------------------------------------------------------------------------------

const exec = require('child_process').exec;
const fs = require('fs');
const util = require('./util');

let _platform = process.platform;

const _linux = (_platform === 'linux');
const _darwin = (_platform === 'darwin');
const _windows = (_platform === 'win32');
const _freebsd = (_platform === 'freebsd');
const _openbsd = (_platform === 'openbsd');
const _netbsd = (_platform === 'netbsd');
const _sunos = (_platform === 'sunos');

function parseWinBatteryPart(lines, designCapacity, fullChargeCapacity) {
  const result = {};
  let status = util.getValue(lines, 'BatteryStatus', '=').trim();
  // 1 = "Discharging"
  // 2 = "On A/C"
  // 3 = "Fully Charged"
  // 4 = "Low"
  // 5 = "Critical"
  // 6 = "Charging"
  // 7 = "Charging High"
  // 8 = "Charging Low"
  // 9 = "Charging Critical"
  // 10 = "Undefined"
  // 11 = "Partially Charged"
  if (status >= 0) {
    const statusValue = status ? parseInt(status) : 0;
    result.status = statusValue;
    result.hasBattery = true;
    result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', '=') || 0);
    result.designCapacity = parseInt(util.getValue(lines, 'DesignCapacity', '=') || designCapacity);
    result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', '=') || 0) / 1000.0;
    result.capacityUnit = 'mWh';
    result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', '=') || 0);
    result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100);
    result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || (!(statusValue === 3) && !(statusValue === 1) && result.percent < 100);
    result.acConnected = result.ischarging || statusValue === 2;
    result.model = util.getValue(lines, 'DeviceID', '=');
  } else {
    result.status = -1;
  }

  return result;
}

module.exports = function (callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let result = {
        hasBattery: false,
        cycleCount: 0,
        isCharging: false,
        designedCapacity: 0,
        maxCapacity: 0,
        currentCapacity: 0,
        voltage: 0,
        capacityUnit: '',
        percent: 0,
        timeRemaining: null,
        acConnected: true,
        type: '',
        model: '',
        manufacturer: '',
        serial: ''
      };

      if (_linux) {
        let battery_path = '';
        if (fs.existsSync('/sys/class/power_supply/BAT1/uevent')) {
          battery_path = '/sys/class/power_supply/BAT1/';
        } else if (fs.existsSync('/sys/class/power_supply/BAT0/uevent')) {
          battery_path = '/sys/class/power_supply/BAT0/';
        }
        if (battery_path) {
          fs.readFile(battery_path + 'uevent', function (error, stdout) {
            if (!error) {
              let lines = stdout.toString().split('\n');

              result.isCharging = (util.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging');
              result.acConnected = result.isCharging;
              result.voltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0;
              result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
              result.cycleCount = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10);
              result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '='), 10) / 1000.0 / (result.voltage || 1));
              result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '='), 10) / 1000.0 / (result.voltage || 1)) | result.maxcapacity;
              result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 / (result.voltage || 1));
              if (!result.maxCapacity) {
                result.maxCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '='), 10) / 1000.0;
                result.designCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '='), 10) / 1000.0 | result.maxCapacity;
                result.currentCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0;
              }
              const percent = util.getValue(lines, 'POWER_SUPPLY_CAPACITY', '=');
              const energy = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10);
              const power = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10);
              const current = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10);

              result.percent = parseInt('0' + percent, 10);
              if (result.maxCapacity && result.currentCapacity) {
                result.hasBattery = true;
                if (!percent) {
                  result.percent = 100.0 * result.currentCapacity / result.maxCapacity;
                }
              }
              if (result.isCharging) {
                result.hasBattery = true;
              }
              if (energy && power) {
                result.timeRemaining = Math.floor(energy / power * 60);
              } else if (current && result.currentCapacity) {
                result.timeRemaining = Math.floor(result.currentCapacity / current * 60);
              }
              result.type = util.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '=');
              result.model = util.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '=');
              result.manufacturer = util.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '=');
              result.serial = util.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '=');
              if (callback) { callback(result); }
              resolve(result);
            } else {
              if (callback) { callback(result); }
              resolve(result);
            }
          });
        } else {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
      if (_freebsd || _openbsd || _netbsd) {
        exec('sysctl hw.acpi.battery hw.acpi.acline', function (error, stdout) {
          let lines = stdout.toString().split('\n');
          const batteries = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.units'), 10);
          const percent = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.life'), 10);
          result.hasBattery = (batteries > 0);
          result.cycleCount = null;
          result.isCharging = util.getValue(lines, 'hw.acpi.acline') !== '1';
          result.acConnected = result.isCharging;
          result.maxCapacity = null;
          result.currentCapacity = null;
          result.capacityUnit = 'unknown';
          result.percent = batteries ? percent : null;
          if (callback) { callback(result); }
          resolve(result);
        });
      }

      if (_darwin) {
        exec('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|BatterySerialNumber|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) {
          if (stdout) {
            let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n');
            result.cycleCount = parseInt('0' + util.getValue(lines, 'cyclecount', '='), 10);
            result.voltage = parseInt('0' + util.getValue(lines, 'voltage', '='), 10) / 1000.0;
            result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
            result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'maxcapacity', '='), 10) * (result.voltage || 1));
            result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'currentcapacity', '='), 10) * (result.voltage || 1));
            result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1));
            result.manufacturer = 'Apple';
            result.serial = util.getValue(lines, 'BatterySerialNumber', '=');
            let percent = null;
            const line = util.getValue(lines, 'internal', 'Battery');
            let parts = line.split(';');
            if (parts && parts[0]) {
              let parts2 = parts[0].split('\t');
              if (parts2 && parts2[1]) {
                percent = parseFloat(parts2[1].trim().replace(/%/g, ''));
              }
            }
            if (parts && parts[1]) {
              result.isCharging = (parts[1].trim() === 'charging');
              result.acConnected = (parts[1].trim() !== 'discharging');
            } else {
              result.isCharging = util.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes';
              result.acConnected = result.isCharging;
            }
            if (result.maxCapacity && result.currentCapacity) {
              result.hasBattery = true;
              result.type = 'Li-ion';
              result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity);
              if (!result.isCharging) {
                result.timeRemaining = parseInt('0' + util.getValue(lines, 'TimeRemaining', '='), 10);
              }
            }
          }
          if (callback) { callback(result); }
          resolve(result);
        });
      }
      if (_sunos) {
        if (callback) { callback(result); }
        resolve(result);
      }
      if (_windows) {
        try {
          const workload = [];
          workload.push(util.wmic('Path Win32_Battery Get /value'));
          workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
          workload.push(util.powerShell('(Get-WmiObject -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
          util.promiseAll(
            workload
          ).then(data => {
            if (data) {
              let parts = data.results[0].split('\r\n')
              let batteries = [];
              for (let i = 0; i < parts.length; i++) {
                const hasValue = value => /\S/.test(value);
                if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) {
                  batteries.push([])
                }
                if (hasValue(parts[i])) {
                  batteries[batteries.length - 1].push(parts[i]);
                }
              }
              let designCapacities = data.results[1].split('\r\n');
              let fullChargeCapacities = data.results[2].split('\r\n');
              if (batteries && batteries.length) {
                let first = false;
                let additionalBatteries = [];
                for (let i = 0; i < batteries.length; i++) {
                  let lines = batteries[i]
                  const designCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util.toInt(designCapacities[i]) : 0;
                  const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util.toInt(fullChargeCapacities[i]) : 0;
                  const parsed = parseWinBatteryPart(lines, designCapacity, fullChargeCapacity);
                  if (!first && parsed.status > 0 && parsed.status !== 10) {
                    result.hasBattery = parsed.hasBattery;
                    result.maxCapacity = parsed.maxCapacity;
                    result.designCapacity = parsed.designCapacity;
                    result.voltage = parsed.voltage;
                    result.capacityUnit = parsed.capacityUnit;
                    result.percent = parsed.percent;
                    result.currentCapacity = parsed.currentCapacity;
                    result.isCharging = parsed.isCharging;
                    result.acConnected = parsed.acConnected;
                    result.model = parsed.model;
                    first = true;
                  } else if (parsed.status !== -1) {
                    additionalBatteries.push(
                      {
                        hasBattery: parsed.hasBattery,
                        maxCapacity: parsed.maxCapacity,
                        designCapacity: parsed.designCapacity,
                        voltage: parsed.voltage,
                        capacityUnit: parsed.capacityUnit,
                        percent: parsed.percent,
                        currentCapacity: parsed.currentCapacity,
                        isCharging: parsed.isCharging,
                        timeRemaining: null,
                        acConnected: parsed.acConnected,
                        model: parsed.model,
                        type: '',
                        manufacturer: '',
                        serial: ''
                      }
                    );
                  }
                }
                if (!first && additionalBatteries.length) {
                  result = additionalBatteries[0];
                  additionalBatteries.shift();
                }
                if (additionalBatteries.length) {
                  result.additionalBatteries = additionalBatteries;
                }
              }
            }
            if (callback) { callback(result); }
            resolve(result);
          });
        } catch (e) {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
    });
  });
};
<|endoftext|>


<commit_before>'use strict'

const each = require('async/each')
const isEqual = require('lodash/isEqual')
const program = require('commander')
const series = require('async/series')

process.env.NODE_ENV = 'test'
const constants = require('../../initializers/constants')

const loginUtils = require('../utils/login')
const podsUtils = require('../utils/pods')
const serversUtils = require('../utils/servers')
const videosUtils = require('../utils/videos')

program
  .option('-c, --create [weight]', 'Weight for creating videos')
  .option('-r, --remove [weight]', 'Weight for removing videos')
  .option('-p, --pods [n]', 'Number of pods to run (3 or 6)', /^3|6$/, 3)
  .option('-a, --action [interval]', 'Interval in ms for an action')
  .option('-i, --integrity [interval]', 'Interval in ms for an integrity check')
  .option('-f, --flush', 'Flush datas on exit')
  .parse(process.argv)

const createWeight = parseInt(program.create) || 5
const removeWeight = parseInt(program.remove) || 4
const flushAtExit = program.flush || false
const actionInterval = parseInt(program.action) || 500
let integrityInterval = parseInt(program.integrity) || 60000

const numberOfPods = 6
// Wait requests between pods
const requestsMaxPerInterval = constants.REQUESTS_INTERVAL / actionInterval
const intervalsToMakeAllRequests = Math.ceil(requestsMaxPerInterval / constants.REQUESTS_LIMIT)
const waitForBeforeIntegrityCheck = (intervalsToMakeAllRequests * constants.REQUESTS_INTERVAL) + 1000

integrityInterval += waitForBeforeIntegrityCheck

console.log('Create weight: %d, remove weight: %d.', createWeight, removeWeight)
if (flushAtExit) {
  console.log('Program will flush data on exit.')
} else {
  console.log('Program will not flush data on exit.')
}
console.log('Interval in ms for each action: %d.', actionInterval)
console.log('Interval in ms for each integrity check: %d.', integrityInterval)
console.log('Will wait %d ms before an integrity check.', waitForBeforeIntegrityCheck)

console.log('Run servers...')
runServers(numberOfPods, function (err, servers) {
  if (err) throw err

  process.on('exit', function () {
    exitServers(servers, flushAtExit)
  })
  process.on('SIGINT', goodbye)
  process.on('SIGTERM', goodbye)

  console.log('Servers runned')

  let checking = false

  setInterval(function () {
    if (checking === true) return

    const rand = getRandomInt(0, createWeight + removeWeight)

    if (rand < createWeight) {
      upload(servers, getRandomNumServer(servers))
    } else {
      remove(servers, getRandomNumServer(servers))
    }
  }, actionInterval)

  setInterval(function () {
    console.log('Checking integrity...')
    checking = true

    setTimeout(function () {
      checkIntegrity(servers, function () {
        checking = false
      })
    }, waitForBeforeIntegrityCheck)
  }, integrityInterval)
})

// ----------------------------------------------------------------------------

function getRandomInt (min, max) {
  return Math.floor(Math.random() * (max - min)) + min
}

function getRandomNumServer (servers) {
  return getRandomInt(0, servers.length)
}

function runServers (numberOfPods, callback) {
  let servers = null

  series([
    // Run servers
    function (next) {
      serversUtils.flushAndRunMultipleServers(numberOfPods, function (serversRun) {
        servers = serversRun
        next()
      })
    },
    // Get the access tokens
    function (next) {
      each(servers, function (server, callbackEach) {
        loginUtils.loginAndGetAccessToken(server, function (err, accessToken) {
          if (err) return callbackEach(err)

          server.accessToken = accessToken
          callbackEach()
        })
      }, next)
    },
    function (next) {
      const server = servers[1]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      const server = servers[0]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      setTimeout(next, 1000)
    },
    function (next) {
      const server = servers[3]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      const server = servers[5]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      const server = servers[4]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      setTimeout(next, 1000)
    }
  ], function (err) {
    return callback(err, servers)
  })
}

function exitServers (servers, callback) {
  if (!callback) callback = function () {}

  servers.forEach(function (server) {
    if (server.app) process.kill(-server.app.pid)
  })

  if (flushAtExit) serversUtils.flushTests(callback)
}

function upload (servers, numServer, callback) {
  if (!callback) callback = function () {}

  const name = Date.now() + ' name'
  const description = Date.now() + ' description'
  const tags = [ Date.now().toString().substring(0, 5) + 't1', Date.now().toString().substring(0, 5) + 't2' ]
  const file = 'video_short1.webm'

  console.log('Upload video to server ' + numServer)

  videosUtils.uploadVideo(servers[numServer].url, servers[numServer].accessToken, name, description, tags, file, callback)
}

function remove (servers, numServer, callback) {
  if (!callback) callback = function () {}

  videosUtils.getVideosList(servers[numServer].url, function (err, res) {
    if (err) throw err

    const videos = res.body.data
    if (videos.length === 0) return callback()

    const toRemove = videos[getRandomInt(0, videos.length)].id

    console.log('Removing video from server ' + numServer)
    videosUtils.removeVideo(servers[numServer].url, servers[numServer].accessToken, toRemove, callback)
  })
}

function checkIntegrity (servers, callback) {
  const videos = []
  each(servers, function (server, callback) {
    videosUtils.getAllVideosListBy(server.url, function (err, res) {
      if (err) throw err
      const serverVideos = res.body.data
      for (const serverVideo of serverVideos) {
        delete serverVideo.id
        delete serverVideo.isLocal
        delete serverVideo.thumbnailPath
      }

      videos.push(serverVideos)
      callback()
    })
  }, function () {
    for (const video of videos) {
      if (!isEqual(video, videos[0])) {
        console.error('Integrity not ok!')

        process.exit(-1)
      }
    }

    console.log('Integrity ok.')
    return callback()
  })
}

function goodbye () {
  return process.exit(-1)
}
<commit_msg>Server: improve real world script<commit_after>'use strict'

const each = require('async/each')
const isEqual = require('lodash/isEqual')
const differenceWith = require('lodash/differenceWith')
const program = require('commander')
const series = require('async/series')

process.env.NODE_ENV = 'test'
const constants = require('../../initializers/constants')

const loginUtils = require('../utils/login')
const podsUtils = require('../utils/pods')
const serversUtils = require('../utils/servers')
const videosUtils = require('../utils/videos')

program
  .option('-c, --create [weight]', 'Weight for creating videos')
  .option('-r, --remove [weight]', 'Weight for removing videos')
  .option('-p, --pods [n]', 'Number of pods to run (3 or 6)', /^3|6$/, 3)
  .option('-a, --action [interval]', 'Interval in ms for an action')
  .option('-i, --integrity [interval]', 'Interval in ms for an integrity check')
  .option('-f, --flush', 'Flush datas on exit')
  .option('-d, --difference', 'Display difference if integrity is not okay')
  .parse(process.argv)

const createWeight = program.create !== undefined ? parseInt(program.create) : 5
const removeWeight = program.remove !== undefined ? parseInt(program.remove) : 4
const flushAtExit = program.flush || false
const actionInterval = program.action !== undefined ? parseInt(program.action) : 500
let integrityInterval = program.integrity !== undefined ? parseInt(program.integrity) : 60000
const displayDiffOnFail = program.integrity || false

const numberOfPods = 6

// Wait requests between pods
const baseRequestInterval = integrityInterval < constants.REQUESTS_INTERVAL ? integrityInterval : constants.REQUESTS_INTERVAL
const requestsMaxPerInterval = baseRequestInterval / actionInterval
const intervalsToMakeAllRequests = Math.ceil(requestsMaxPerInterval / constants.REQUESTS_LIMIT)
const waitForBeforeIntegrityCheck = (intervalsToMakeAllRequests * constants.REQUESTS_INTERVAL) + 1000

console.log('Create weight: %d, remove weight: %d.', createWeight, removeWeight)
if (flushAtExit) {
  console.log('Program will flush data on exit.')
} else {
  console.log('Program will not flush data on exit.')
}
if (displayDiffOnFail) {
  console.log('Program will display diff on failure.')
} else {
  console.log('Program will not display diff on failure')
}
console.log('Interval in ms for each action: %d.', actionInterval)
console.log('Interval in ms for each integrity check: %d.', integrityInterval)
console.log('Will wait %d ms before an integrity check.', waitForBeforeIntegrityCheck)

console.log('Run servers...')
runServers(numberOfPods, function (err, servers) {
  if (err) throw err

  process.on('exit', function () {
    exitServers(servers, flushAtExit)
  })
  process.on('SIGINT', goodbye)
  process.on('SIGTERM', goodbye)

  console.log('Servers runned')

  let checking = false

  setInterval(function () {
    if (checking === true) return

    const rand = getRandomInt(0, createWeight + removeWeight)

    if (rand < createWeight) {
      upload(servers, getRandomNumServer(servers))
    } else {
      remove(servers, getRandomNumServer(servers))
    }
  }, actionInterval)

  setInterval(function () {
    if (checking === true) return

    console.log('Checking integrity...')
    checking = true

    setTimeout(function () {
      checkIntegrity(servers, function () {
        checking = false
      })
    }, waitForBeforeIntegrityCheck)
  }, integrityInterval)
})

// ----------------------------------------------------------------------------

function getRandomInt (min, max) {
  return Math.floor(Math.random() * (max - min)) + min
}

function getRandomNumServer (servers) {
  return getRandomInt(0, servers.length)
}

function runServers (numberOfPods, callback) {
  let servers = null

  series([
    // Run servers
    function (next) {
      serversUtils.flushAndRunMultipleServers(numberOfPods, function (serversRun) {
        servers = serversRun
        next()
      })
    },
    // Get the access tokens
    function (next) {
      each(servers, function (server, callbackEach) {
        loginUtils.loginAndGetAccessToken(server, function (err, accessToken) {
          if (err) return callbackEach(err)

          server.accessToken = accessToken
          callbackEach()
        })
      }, next)
    },
    function (next) {
      const server = servers[1]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      const server = servers[0]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      setTimeout(next, 1000)
    },
    function (next) {
      const server = servers[3]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      const server = servers[5]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      const server = servers[4]
      podsUtils.makeFriends(server.url, server.accessToken, next)
    },
    function (next) {
      setTimeout(next, 1000)
    }
  ], function (err) {
    return callback(err, servers)
  })
}

function exitServers (servers, callback) {
  if (!callback) callback = function () {}

  servers.forEach(function (server) {
    if (server.app) process.kill(-server.app.pid)
  })

  if (flushAtExit) serversUtils.flushTests(callback)
}

function upload (servers, numServer, callback) {
  if (!callback) callback = function () {}

  const name = Date.now() + ' name'
  const description = Date.now() + ' description'
  const tags = [ Date.now().toString().substring(0, 5) + 't1', Date.now().toString().substring(0, 5) + 't2' ]
  const file = 'video_short1.webm'

  console.log('Upload video to server ' + numServer)

  videosUtils.uploadVideo(servers[numServer].url, servers[numServer].accessToken, name, description, tags, file, callback)
}

function remove (servers, numServer, callback) {
  if (!callback) callback = function () {}

  videosUtils.getVideosList(servers[numServer].url, function (err, res) {
    if (err) throw err

    const videos = res.body.data
    if (videos.length === 0) return callback()

    const toRemove = videos[getRandomInt(0, videos.length)].id

    console.log('Removing video from server ' + numServer)
    videosUtils.removeVideo(servers[numServer].url, servers[numServer].accessToken, toRemove, callback)
  })
}

function checkIntegrity (servers, callback) {
  const videos = []
  each(servers, function (server, callback) {
    videosUtils.getAllVideosListBy(server.url, function (err, res) {
      if (err) throw err
      const serverVideos = res.body.data
      for (const serverVideo of serverVideos) {
        delete serverVideo.id
        delete serverVideo.isLocal
        delete serverVideo.thumbnailPath
        delete serverVideo.updatedAt
      }

      videos.push(serverVideos)
      callback()
    })
  }, function () {
    for (const video of videos) {
      if (!isEqual(video, videos[0])) {
        console.error('Integrity not ok!')

        if (displayDiffOnFail) {
          console.log(differenceWith(videos[0], video, isEqual))
        }

        process.exit(-1)
      }
    }

    console.log('Integrity ok.')
    return callback()
  })
}

function goodbye () {
  return process.exit(-1)
}
<|endoftext|>


<commit_before>//A TDD test suite to check for correctness
//and accuracy of an OOP Model of a bank account

//fat arrows not allowed inside test suite
//mochajs.org/#arrow-functions
<commit_msg>fix error in first failing test<commit_after>//A TDD test suite to check for correctness
//and accuracy of an OOP Model of a bank account

//fat arrows not allowed inside mocha test suite
//see ---> mochajs.org/#arrow-functions

const expect = require('chai').expect;

describe('Bank Account Suite', function(){
	it('Should Return 5000',function(){
    	expect(Ade.balance()).to.equal(5000);})
})<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var fs = require('fs');

/**
 * Represents the C/C++ binding layer that the Node.js SDK is built upon.
 * This library handles all network I/O along with most configuration and
 * bootstrapping requirements.
 * @external CouchbaseBinding
 */
/**
 * @name CouchbaseBinding._setErrorClass
 */
/**
 * @class CouchbaseBinding.Error
 * @private
 * @ignore
 */
/**
 * @class CouchbaseBinding.CouchbaseImpl
 * @private
 * @ignore
 */
/** @name CouchbaseBinding.CouchbaseImpl#shutdown */
/** @name CouchbaseBinding.CouchbaseImpl#control */
/** @name CouchbaseBinding.CouchbaseImpl#connect */
/** @name CouchbaseBinding.CouchbaseImpl#getViewNode */
/** @name CouchbaseBinding.CouchbaseImpl#getMgmtNode */
/** @name CouchbaseBinding.CouchbaseImpl#setConnectCallback */
/** @name CouchbaseBinding.CouchbaseImpl#setTranscoder */
/** @name CouchbaseBinding.CouchbaseImpl#lcbVersion */
/** @name CouchbaseBinding.CouchbaseImpl#get */
/** @name CouchbaseBinding.CouchbaseImpl#getReplica */
/** @name CouchbaseBinding.CouchbaseImpl#touch */
/** @name CouchbaseBinding.CouchbaseImpl#unlock */
/** @name CouchbaseBinding.CouchbaseImpl#remove */
/** @name CouchbaseBinding.CouchbaseImpl#store */
/** @name CouchbaseBinding.CouchbaseImpl#arithmetic */
/** @name CouchbaseBinding.CouchbaseImpl#durability */
/** @name CouchbaseBinding.CouchbaseImpl#_errorTest */
/**
 * @namespace CouchbaseBinding.Constants
 * @ignore
 */
/** @name CouchbaseBinding.Constants.CNTL_SET */
/** @name CouchbaseBinding.Constants.CNTL_GET */
/** @name CouchbaseBinding.Constants.CNTL_OP_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_DURABILITY_INTERVAL */
/** @name CouchbaseBinding.Constants.CNTL_DURABILITY_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_HTTP_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_VIEW_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_RBUFSIZE */
/** @name CouchbaseBinding.Constants.CNTL_WBUFSIZE */
/** @name CouchbaseBinding.Constants.CNTL_CONFIGURATION_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_VBMAP */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_HTTP_NODES */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_CCCP_NODES */
/** @name CouchbaseBinding.Constants.CNTL_CHANGESET */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_ALL_NODES */
/** @name CouchbaseBinding.Constants.CNTL_CONFIGCACHE */
/** @name CouchbaseBinding.Constants.CNTL_SSL_MODE */
/** @name CouchbaseBinding.Constants.CNTL_SSL_CACERT */
/** @name CouchbaseBinding.Constants.CNTL_RETRYMODE */
/** @name CouchbaseBinding.Constants.CNTL_HTCONFIG_URLTYPE */
/** @name CouchbaseBinding.Constants.CNTL_COMPRESSION_OPTS */
/** @name CouchbaseBinding.Constants.CNTL_RDBALLOCFACTORY */
/** @name CouchbaseBinding.Constants.CNTL_SYNCDESTROY */
/** @name CouchbaseBinding.Constants.CNTL_CONLOGGER_LEVEL */
/** @name CouchbaseBinding.Constants.CNTL_DETAILED_ERRCODES */
/** @name CouchbaseBinding.Constants.CNTL_REINIT_DSN */
/** @name CouchbaseBinding.Constants.CNTL_CONFDELAY_THRESH */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_NODE_TIMEOUT */
/** @name CouchbaseBinding.Constants.ADD */
/** @name CouchbaseBinding.Constants.REPLACE */
/** @name CouchbaseBinding.Constants.SET */
/** @name CouchbaseBinding.Constants.APPEND */
/** @name CouchbaseBinding.Constants.PREPEND */
/** @name CouchbaseBinding.Constants.SUCCESS */
/** @name CouchbaseBinding.Constants.AUTH_CONTINUE */
/** @name CouchbaseBinding.Constants.AUTH_ERROR */
/** @name CouchbaseBinding.Constants.DELTA_BADVAL */
/** @name CouchbaseBinding.Constants.E2BIG */
/** @name CouchbaseBinding.Constants.EBUSY */
/** @name CouchbaseBinding.Constants.ENOMEM */
/** @name CouchbaseBinding.Constants.ERANGE */
/** @name CouchbaseBinding.Constants.ERROR */
/** @name CouchbaseBinding.Constants.ETMPFAIL */
/** @name CouchbaseBinding.Constants.EINVAL */
/** @name CouchbaseBinding.Constants.CLIENT_ETMPFAIL */
/** @name CouchbaseBinding.Constants.KEY_EEXISTS */
/** @name CouchbaseBinding.Constants.KEY_ENOENT */
/** @name CouchbaseBinding.Constants.DLOPEN_FAILED */
/** @name CouchbaseBinding.Constants.DLSYM_FAILED */
/** @name CouchbaseBinding.Constants.NETWORK_ERROR */
/** @name CouchbaseBinding.Constants.NOT_MY_VBUCKET */
/** @name CouchbaseBinding.Constants.NOT_STORED */
/** @name CouchbaseBinding.Constants.NOT_SUPPORTED */
/** @name CouchbaseBinding.Constants.UNKNOWN_COMMAND */
/** @name CouchbaseBinding.Constants.UNKNOWN_HOST */
/** @name CouchbaseBinding.Constants.PROTOCOL_ERROR */
/** @name CouchbaseBinding.Constants.ETIMEDOUT */
/** @name CouchbaseBinding.Constants.BUCKET_ENOENT */
/** @name CouchbaseBinding.Constants.CLIENT_ENOMEM */
/** @name CouchbaseBinding.Constants.CONNECT_ERROR */
/** @name CouchbaseBinding.Constants.EBADHANDLE */
/** @name CouchbaseBinding.Constants.SERVER_BUG */
/** @name CouchbaseBinding.Constants.PLUGIN_VERSION_MISMATCH */
/** @name CouchbaseBinding.Constants.INVALID_HOST_FORMAT */
/** @name CouchbaseBinding.Constants.INVALID_CHAR */
/** @name CouchbaseBinding.Constants.DURABILITY_ETOOMANY */
/** @name CouchbaseBinding.Constants.DUPLICATE_COMMANDS */
/** @name CouchbaseBinding.Constants.EINTERNAL */
/** @name CouchbaseBinding.Constants.NO_MATCHING_SERVER */
/** @name CouchbaseBinding.Constants.BAD_ENVIRONMENT */
/** @name CouchbaseBinding.Constants.HTTP_TYPE_VIEW */
/** @name CouchbaseBinding.Constants.HTTP_TYPE_MANAGEMENT */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_GET */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_POST */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_PUT */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_DELETE) */

/**
 * Track all errors when attempting to find the binding...
 *
 * @type {Array}
 */
var bindingLoadErrors = [];

/**
 * Attempts to load a binding by path ignoring not-found errors.
 *
 * @param {string} path The path to the binding to attempt loading.
 * @returns {CouchbaseBinding}
 *
 * @ignore
 */
function tryLoadBinding(path) {
  try {
    return require('bindings')(path);
  } catch(e) {
    bindingLoadErrors.push({
      path: path,
      error: e
    });
  }
  return null;
}

/**
 * @type {CouchbaseBinding}
 * @ignore
 */
var couchnode = tryLoadBinding('couchbase_impl');
if (!couchnode && process.platform === 'win32') {
  // Try to load prebuilt windows binaries
  if (process.arch === 'x64') {
    couchnode = tryLoadBinding('../prebuilt/win/x64/couchbase_impl');
  } else if (process.arch === 'ia32') {
    couchnode = tryLoadBinding('../prebuilt/win/ia32/couchbase_impl');
  }
}
if (!couchnode) {
  var buildErrorLogPath = __dirname + '/../builderror.log';
  var buildErrorLogData = '';
  try {
    buildErrorLogData = fs.readFileSync(buildErrorLogPath, 'utf8');
  } catch(e) {
    buildErrorLogData = '*** FAILED TO READ FILE';
  }

  console.error('---');
  console.error('build errors (' + buildErrorLogPath + '):');
  console.error('---');
  console.error(buildErrorLogData);
  console.error('---');

  console.error('load exceptions:');
  console.error('---');
  for (var i = 0; i < bindingLoadErrors.length; ++i) {
    var loadError = bindingLoadErrors[i];
    console.error('`' + loadError.path + '`:');
    console.error(loadError.error);
  }
  console.error('---');

  throw new Error('Failed to locate couchnode native binding' +
    ' (see above for more information!)');
}

function CouchbaseError(message) {
  Error.call(this);
  Error.captureStackTrace(this, CouchbaseError);
  this.message = message;
}
util.inherits(CouchbaseError, Error);
CouchbaseError.prototype.name = 'CouchbaseError';
couchnode._setErrorClass(CouchbaseError);
couchnode.Error = CouchbaseError;

module.exports = couchnode;
<commit_msg>JSCBC-215: Use module versioning to find appropriate prebuilt binary.<commit_after>'use strict';

var util = require('util');
var fs = require('fs');

/**
 * Represents the C/C++ binding layer that the Node.js SDK is built upon.
 * This library handles all network I/O along with most configuration and
 * bootstrapping requirements.
 * @external CouchbaseBinding
 */
/**
 * @name CouchbaseBinding._setErrorClass
 */
/**
 * @class CouchbaseBinding.Error
 * @private
 * @ignore
 */
/**
 * @class CouchbaseBinding.CouchbaseImpl
 * @private
 * @ignore
 */
/** @name CouchbaseBinding.CouchbaseImpl#shutdown */
/** @name CouchbaseBinding.CouchbaseImpl#control */
/** @name CouchbaseBinding.CouchbaseImpl#connect */
/** @name CouchbaseBinding.CouchbaseImpl#getViewNode */
/** @name CouchbaseBinding.CouchbaseImpl#getMgmtNode */
/** @name CouchbaseBinding.CouchbaseImpl#setConnectCallback */
/** @name CouchbaseBinding.CouchbaseImpl#setTranscoder */
/** @name CouchbaseBinding.CouchbaseImpl#lcbVersion */
/** @name CouchbaseBinding.CouchbaseImpl#get */
/** @name CouchbaseBinding.CouchbaseImpl#getReplica */
/** @name CouchbaseBinding.CouchbaseImpl#touch */
/** @name CouchbaseBinding.CouchbaseImpl#unlock */
/** @name CouchbaseBinding.CouchbaseImpl#remove */
/** @name CouchbaseBinding.CouchbaseImpl#store */
/** @name CouchbaseBinding.CouchbaseImpl#arithmetic */
/** @name CouchbaseBinding.CouchbaseImpl#durability */
/** @name CouchbaseBinding.CouchbaseImpl#_errorTest */
/**
 * @namespace CouchbaseBinding.Constants
 * @ignore
 */
/** @name CouchbaseBinding.Constants.CNTL_SET */
/** @name CouchbaseBinding.Constants.CNTL_GET */
/** @name CouchbaseBinding.Constants.CNTL_OP_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_DURABILITY_INTERVAL */
/** @name CouchbaseBinding.Constants.CNTL_DURABILITY_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_HTTP_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_VIEW_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_RBUFSIZE */
/** @name CouchbaseBinding.Constants.CNTL_WBUFSIZE */
/** @name CouchbaseBinding.Constants.CNTL_CONFIGURATION_TIMEOUT */
/** @name CouchbaseBinding.Constants.CNTL_VBMAP */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_HTTP_NODES */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_CCCP_NODES */
/** @name CouchbaseBinding.Constants.CNTL_CHANGESET */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_ALL_NODES */
/** @name CouchbaseBinding.Constants.CNTL_CONFIGCACHE */
/** @name CouchbaseBinding.Constants.CNTL_SSL_MODE */
/** @name CouchbaseBinding.Constants.CNTL_SSL_CACERT */
/** @name CouchbaseBinding.Constants.CNTL_RETRYMODE */
/** @name CouchbaseBinding.Constants.CNTL_HTCONFIG_URLTYPE */
/** @name CouchbaseBinding.Constants.CNTL_COMPRESSION_OPTS */
/** @name CouchbaseBinding.Constants.CNTL_RDBALLOCFACTORY */
/** @name CouchbaseBinding.Constants.CNTL_SYNCDESTROY */
/** @name CouchbaseBinding.Constants.CNTL_CONLOGGER_LEVEL */
/** @name CouchbaseBinding.Constants.CNTL_DETAILED_ERRCODES */
/** @name CouchbaseBinding.Constants.CNTL_REINIT_DSN */
/** @name CouchbaseBinding.Constants.CNTL_CONFDELAY_THRESH */
/** @name CouchbaseBinding.Constants.CNTL_CONFIG_NODE_TIMEOUT */
/** @name CouchbaseBinding.Constants.ADD */
/** @name CouchbaseBinding.Constants.REPLACE */
/** @name CouchbaseBinding.Constants.SET */
/** @name CouchbaseBinding.Constants.APPEND */
/** @name CouchbaseBinding.Constants.PREPEND */
/** @name CouchbaseBinding.Constants.SUCCESS */
/** @name CouchbaseBinding.Constants.AUTH_CONTINUE */
/** @name CouchbaseBinding.Constants.AUTH_ERROR */
/** @name CouchbaseBinding.Constants.DELTA_BADVAL */
/** @name CouchbaseBinding.Constants.E2BIG */
/** @name CouchbaseBinding.Constants.EBUSY */
/** @name CouchbaseBinding.Constants.ENOMEM */
/** @name CouchbaseBinding.Constants.ERANGE */
/** @name CouchbaseBinding.Constants.ERROR */
/** @name CouchbaseBinding.Constants.ETMPFAIL */
/** @name CouchbaseBinding.Constants.EINVAL */
/** @name CouchbaseBinding.Constants.CLIENT_ETMPFAIL */
/** @name CouchbaseBinding.Constants.KEY_EEXISTS */
/** @name CouchbaseBinding.Constants.KEY_ENOENT */
/** @name CouchbaseBinding.Constants.DLOPEN_FAILED */
/** @name CouchbaseBinding.Constants.DLSYM_FAILED */
/** @name CouchbaseBinding.Constants.NETWORK_ERROR */
/** @name CouchbaseBinding.Constants.NOT_MY_VBUCKET */
/** @name CouchbaseBinding.Constants.NOT_STORED */
/** @name CouchbaseBinding.Constants.NOT_SUPPORTED */
/** @name CouchbaseBinding.Constants.UNKNOWN_COMMAND */
/** @name CouchbaseBinding.Constants.UNKNOWN_HOST */
/** @name CouchbaseBinding.Constants.PROTOCOL_ERROR */
/** @name CouchbaseBinding.Constants.ETIMEDOUT */
/** @name CouchbaseBinding.Constants.BUCKET_ENOENT */
/** @name CouchbaseBinding.Constants.CLIENT_ENOMEM */
/** @name CouchbaseBinding.Constants.CONNECT_ERROR */
/** @name CouchbaseBinding.Constants.EBADHANDLE */
/** @name CouchbaseBinding.Constants.SERVER_BUG */
/** @name CouchbaseBinding.Constants.PLUGIN_VERSION_MISMATCH */
/** @name CouchbaseBinding.Constants.INVALID_HOST_FORMAT */
/** @name CouchbaseBinding.Constants.INVALID_CHAR */
/** @name CouchbaseBinding.Constants.DURABILITY_ETOOMANY */
/** @name CouchbaseBinding.Constants.DUPLICATE_COMMANDS */
/** @name CouchbaseBinding.Constants.EINTERNAL */
/** @name CouchbaseBinding.Constants.NO_MATCHING_SERVER */
/** @name CouchbaseBinding.Constants.BAD_ENVIRONMENT */
/** @name CouchbaseBinding.Constants.HTTP_TYPE_VIEW */
/** @name CouchbaseBinding.Constants.HTTP_TYPE_MANAGEMENT */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_GET */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_POST */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_PUT */
/** @name CouchbaseBinding.Constants.HTTP_METHOD_DELETE) */

/**
 * Track all errors when attempting to find the binding...
 *
 * @type {Array}
 */
var bindingLoadErrors = [];

/**
 * Attempts to load a binding by path ignoring not-found errors.
 *
 * @param {string} path The path to the binding to attempt loading.
 * @returns {CouchbaseBinding}
 *
 * @ignore
 */
function tryLoadBinding(path) {
  try {
    return require('bindings')(path);
  } catch(e) {
    bindingLoadErrors.push({
      path: path,
      error: e
    });
  }
  return null;
}

/**
 * @type {CouchbaseBinding}
 * @ignore
 */
var couchnode = tryLoadBinding('couchbase_impl');
if (!couchnode && process.platform === 'win32') {
  // Try to load prebuilt windows binaries
  couchnode = tryLoadBinding(
      '../prebuilt/' +
      process.versions.modules +
      '/win/' +
      process.arch +
      '/couchbase_impl');
}
if (!couchnode) {
  var buildErrorLogPath = __dirname + '/../builderror.log';
  var buildErrorLogData = '';
  try {
    buildErrorLogData = fs.readFileSync(buildErrorLogPath, 'utf8');
  } catch(e) {
    buildErrorLogData = '*** FAILED TO READ FILE';
  }

  console.error('---');
  console.error('build errors (' + buildErrorLogPath + '):');
  console.error('---');
  console.error(buildErrorLogData);
  console.error('---');

  console.error('load exceptions:');
  console.error('---');
  for (var i = 0; i < bindingLoadErrors.length; ++i) {
    var loadError = bindingLoadErrors[i];
    console.error('`' + loadError.path + '`:');
    console.error(loadError.error);
  }
  console.error('---');

  throw new Error('Failed to locate couchnode native binding' +
    ' (see above for more information!)');
}

function CouchbaseError(message) {
  Error.call(this);
  Error.captureStackTrace(this, CouchbaseError);
  this.message = message;
}
util.inherits(CouchbaseError, Error);
CouchbaseError.prototype.name = 'CouchbaseError';
couchnode._setErrorClass(CouchbaseError);
couchnode.Error = CouchbaseError;

module.exports = couchnode;
<|endoftext|>


<commit_before>/*!
 * Clean Blog v1.0.0 (http://startbootstrap.com)
 * Copyright 2015 Start Bootstrap
 * Licensed under MIT (https://spdx.org/licenses/MIT)
 */

// Tooltip Init
$(function() {
    $("[data-toggle='tooltip']").tooltip();
});

// Make all images responsive
$(function() {
	$("img").addClass("img-responsive");
});

// Navigation Scripts to Show Header on Scroll-Up
jQuery(document).ready(function($) {
    var MQL = 1170;

    //primary navigation slide-in effect
    if ($(window).width() > MQL) {
        var headerHeight = $('.navbar-custom').height();
        $(window).on('scroll', {
                previousTop: 0
            },
            function() {
                var currentTop = $(window).scrollTop();
                //check if user is scrolling up
                if (currentTop < this.previousTop) {
                    //if scrolling up...
                    if (currentTop > 0 && $('.navbar-custom').hasClass('is-fixed')) {
                        $('.navbar-custom').addClass('is-visible');
                    } else {
                        $('.navbar-custom').removeClass('is-visible is-fixed');
                    }
                } else {
                    //if scrolling down...
                    $('.navbar-custom').removeClass('is-visible');
                    if (currentTop > headerHeight && !$('.navbar-custom').hasClass('is-fixed')) $('.navbar-custom').addClass('is-fixed');
                }
                this.previousTop = currentTop;
            });
    }
});
<commit_msg>refactor: eliminado js que no se usa<commit_after><|endoftext|>


<commit_before>var QUnit = require("steal-qunit");
var F = require("funcunit");

QUnit.config.testTimeout = 10000;

F.attach(QUnit);

QUnit.module("worker-render", {
	setup: function(){
		F.open("//../demo/simple_event.html");
	}
});

QUnit.test("does initial render", function(){
	F("[can-click=toggle]").exists("The link renders");
});

QUnit.test("Event handlers work", function(){
	F("[can-click=toggle]").exists().click();
	F("[can-click=log]").exists("The span was rendered");
});
<commit_msg>increase the test timeout<commit_after>var QUnit = require("steal-qunit");
var F = require("funcunit");

QUnit.config.testTimeout = 30000;

F.attach(QUnit);

QUnit.module("worker-render", {
	setup: function(){
		F.open("//../demo/simple_event.html");
	}
});

QUnit.test("does initial render", function(){
	F("[can-click=toggle]").exists("The link renders");
});

QUnit.test("Event handlers work", function(){
	F("[can-click=toggle]").exists().click();
	F("[can-click=log]").exists("The span was rendered");
});
<|endoftext|>


<commit_before>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "http://jkaleko.comxa.com/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
             /*--   success: function() {   For some reason ajax always interpreted the PHP return as an error... so decided to have it return success message regardless.
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },*/
            });

               // Enable button & show success message.  NOTE: THIS WAS COPY/PASTED FROM ABOVE.  NOW EXECUTES REGARDLESS OF SUCCESS/ERROR
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");

        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});
<commit_msg>Update contact_me.js<commit_after>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "http://jkaleko.byethost5.com/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
             /*--   success: function() {   For some reason ajax always interpreted the PHP return as an error... so decided to have it return success message regardless.
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },*/
            });

               // Enable button & show success message.  NOTE: THIS WAS COPY/PASTED FROM ABOVE.  NOW EXECUTES REGARDLESS OF SUCCESS/ERROR
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");

        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});
<|endoftext|>


<commit_before>dojo.provide("dijit.form.Hidden");

dojo.require("dijit._Widget");

dojo.declare("dijit.form.Hidden",
	[dijit._Widget, dijit._Templated],
	{
	// summary:
	//		A widget corresponding to a native input type="hidden" element,
	//		which responds to dijit.form.Form, and degrades.
	//
	// example:
	//	|	<input type="hidden" dojoType="dijit.form.Hidden" name="foo" value="bar" />
	//

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	templateString: "<input type='hidden' dojoAttachEvent='onchange: onChange'>",
	attributeMap: {value:"domNode", name:"domNode", id:"domNode"},

	getValue: function(){
		// summary: Normalized getter for this input
		return this.domNode.value || this.value; // String
	},

	setValue: function(/* String */val){
		// summary: Normalized control over this input
		this.onChange(val);
		this.domNode.value = this.value = val;
	},

	onChange: function(val){
		// summary: stub -- connect or override to use
	}
});<commit_msg>Name attribute has to be directly in template, due to browser quirks. Refs #5700<commit_after>dojo.provide("dijit.form.Hidden");

dojo.require("dijit._Widget");

dojo.declare("dijit.form.Hidden",
	[dijit._Widget, dijit._Templated],
	{
	// summary:
	//		A widget corresponding to a native input type="hidden" element,
	//		which responds to dijit.form.Form, and degrades.
	//
	// example:
	//	|	<input type="hidden" dojoType="dijit.form.Hidden" name="foo" value="bar" />
	//

	// name: String
	//		Name used when submitting form; same as "name" attribute or plain HTML elements
	name: "",

	// value: String
	//		Corresponds to the native HTML <input> element's attribute.
	value: "",

	templateString: "<input type='hidden' name='${name}' dojoAttachEvent='onchange: onChange'>",
	attributeMap: {value:"domNode", id:"domNode"},

	getValue: function(){
		// summary: Normalized getter for this input
		return this.domNode.value || this.value; // String
	},

	setValue: function(/* String */val){
		// summary: Normalized control over this input
		this.onChange(val);
		this.domNode.value = this.value = val;
	},

	onChange: function(val){
		// summary: stub -- connect or override to use
	}
});<|endoftext|>


<commit_before>//import React from "react";
'use strict';

class PersonalContact extends React.Component {
    constructor(props) {
        super(props);
        this.submitForm = this.submitForm.bind(this);
        this.state = {
            status: ""
        };
    }
    render() {
        const { status } = this.state;
        return(
            <form
                onSubmit={this.submitForm}
                action="https://formspree.io/xpzypzqk"
                method="POST"
            >
                Name:
                <input type="text" name="name" />
                Email:
                <input type="email" name="email" />
                Message:
                <input type="text" name="message" />
                {status === "SUCCESS" ?
Thanks!
 : <button>Submit</button>}
                {status === "ERROR"  &&
There appears to be a problem with my mail server right now, please try again later.
}
            </form>
        );

    }
    submitForm(ev) {
        ev.preventDefault();
        const form = ev.target;
        const data = new FormData(form);
        const xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) return;
            if (xhr.status === 200)
            {
                form.reset();
                this.setState({ status: "SUCCESS" });
            }
            else
            {
                this.setState({ status: "ERROR" });
            }
        };
        xhr.send(data);
    }
}
//el = () => (
hi
);
const domContainer = document.getElementById('contactDiv');
ReactDOM.render(el, domContainer);<commit_msg>new form<commit_after>//import React from "react";
'use strict';

class PersonalContact extends React.Component {
    constructor(props) {
        super(props);
        this.submitForm = this.submitForm.bind(this);
        this.state = {
            status: ""
        };
    }
    render() {
        const { status } = this.state;
        return(
            <form
                onSubmit={this.submitForm}
                action="https://formspree.io/xpzypzqk"
                method="POST"
            >
                Name:
                <input type="text" name="name" />
                Email:
                <input type="email" name="email" />
                Message:
                <input type="text" name="message" />
                {status === "SUCCESS" ?
Thanks!
 : <button>Submit</button>}
                {status === "ERROR"  &&
There appears to be a problem with my mail server right now, please try again later.
}
            </form>
        );

    }
    submitForm(ev) {
        ev.preventDefault();
        const form = ev.target;
        const data = new FormData(form);
        const xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) return;
            if (xhr.status === 200)
            {
                form.reset();
                this.setState({ status: "SUCCESS" });
            }
            else
            {
                this.setState({ status: "ERROR" });
            }
        };
        xhr.send(data);
    }
}
//el = () => (
hi
);
const domContainer = document.getElementById('contactDiv');
ReactDOM.render(<PersonalContact/>, domContainer);<|endoftext|>