<commit_before>const jwt = require('jsonwebtoken');
const fs = require('fs');

const tokenDao = require('./token.dao.js');
const utils = require('../utils');
const uuidv4 = require('uuid/v4');
const config = require('../../config');

const s = {};

s.save = function (tokenObj, options) {
  let rt;
  options = options || {};

  if (!tokenObj.consumerId) {
    return Promise.reject(new Error('invalid token args'));
  }

  if (options.refreshTokenOnly) {
    const rt = createInternalToken(tokenObj, newUuid(), newUuid(), 'refresh_token');

    return tokenDao.save(rt, { type: 'refresh_token' })
      .then(() => {
        return { refresh_token: formExternalToken(rt) };
      });
  }

  const at = createInternalToken(tokenObj, newUuid(), newUuid(), 'access_token');
  const tokenSavePromises = [tokenDao.save(at)];

  if (options.includeRefreshToken) {
    rt = createInternalToken(tokenObj, newUuid(), newUuid(), 'refresh_token');
    tokenSavePromises.push(tokenDao.save(rt, { type: 'refresh_token' }));
  }

  return Promise.all(tokenSavePromises)
    .then(() => {
      return {
        access_token: formExternalToken(at),
        refresh_token: formExternalToken(rt)
      };
    });
};

s.findOrSave = function (tokenObj, options) {
  options = options || {};

  return this.find(tokenObj, options)
    .then(tokens => {
      if (tokens.access_token) {
        if (options.includeRefreshToken && !tokens.refresh_token) {
          return this.save(tokenObj, { refreshTokenOnly: true })
            .then(rt => {
              tokens.refresh_token = rt.refresh_token;
              return tokens;
            });
        } else return tokens;
      }

      if (tokens.refresh_token) {
        return this.save(tokenObj)
          .then(at => {
            tokens.access_token = at.access_token;
            return tokens;
          });
      }

      return this.save(tokenObj, options);
    });
};

s.find = function (tokenObj, options) {
  options = options || {};
  const tokenQueryCriteria = Object.assign({}, tokenObj);

  if (tokenQueryCriteria.scopes && Array.isArray(tokenQueryCriteria.scopes)) {
    tokenQueryCriteria.scopes = JSON.stringify(tokenQueryCriteria.scopes.sort());
  }

  const findQueries = [tokenDao.find(tokenQueryCriteria)];

  if (options.includeRefreshToken) {
    findQueries.push(tokenDao.find(tokenQueryCriteria, { type: 'refresh_token' }));
  }

  return Promise.all(findQueries)
    .then(([accessToken, refreshToken]) => {
      return {
        access_token: formExternalToken(accessToken),
        refresh_token: formExternalToken(refreshToken)
      };
    });
};

s.get = function (_token, options) {
  options = options || {};
  const tokenId = _token.split('|')[0];

  return tokenDao.get(tokenId, options)
    .then(token => {
      if (!token) {
        return null;
      }

      if (token.scopes) {
        token.scopes = JSON.parse(token.scopes);
      }

      token.tokenDecrypted = utils.decrypt(token.tokenEncrypted);
      delete token.tokenEncrypted;

      return token;
    });
};

s.getTokenObject = function (refreshToken) {
  return this.get(refreshToken, { type: 'refresh_token' })
    .then(rtObj => {
      if (!rtObj) {
        return null;
      }

      const tokenObj = Object.assign({}, rtObj);
      delete tokenObj.createdAt;
      delete tokenObj.updatedAt;
      delete tokenObj.expiresAt;
      delete tokenObj.tokenDecrypted;
      delete tokenObj.id;

      return tokenObj;
    });
};

s.getTokensByConsumer = function (id, options) {
  return tokenDao.getTokensByConsumer(id, options);
};

s.revoke = function (accessToken) {
  return this.get(accessToken).then(token => {
    if (!token) {
      throw new Error('Token not found ' + token);
    }

    return tokenDao.revoke(token);
  });
};

s.createJWT = function (payload) {
  const accessTokenConfig = config.systemConfig.accessTokens;
  const secret = accessTokenConfig.secretOrPrivateKeyFile
    ? fs.readFileSync(accessTokenConfig.secretOrPrivateKeyFile)
    : accessTokenConfig.secretOrPrivateKey;

  return new Promise((resolve, reject) => {
    jwt.sign(payload, secret, {
      issuer: accessTokenConfig.issuer,
      audience: accessTokenConfig.audience,
      expiresIn: accessTokenConfig.timeToExpiry,
      subject: accessTokenConfig.subject
    }, (err, jwt) => {
      if (err) { return reject(err); }
      return resolve(jwt);
    });
  });
};

const createInternalToken = (criteria, id, token, type) => {
  let timeToExpiry;

  if (type === 'access_token') {
    timeToExpiry = config.systemConfig.accessTokens.timeToExpiry;
  } else timeToExpiry = config.systemConfig.refreshTokens.timeToExpiry;

  const internalTokenObj = Object.assign({
    id,
    tokenEncrypted: utils.encrypt(token),
    expiresAt: Date.now() + timeToExpiry
  }, criteria);

  if (internalTokenObj.scopes && Array.isArray(internalTokenObj.scopes)) {
    internalTokenObj.scopes = JSON.stringify(internalTokenObj.scopes.sort());
  }

  utils.appendCreatedAt(internalTokenObj);
  return internalTokenObj;
};

const formExternalToken = (tokenObj) => {
  if (!tokenObj) return null;
  return tokenObj.id.concat('|', utils.decrypt(tokenObj.tokenEncrypted));
};

const newUuid = () => {
  return uuidv4().replace(new RegExp('-', 'g'), '');
};

module.exports = s;
<commit_msg>Defer secret loading for config sync issues<commit_after>const jwt = require('jsonwebtoken');
const fs = require('fs');
const uuidv4 = require('uuid/v4');

const tokenDao = require('./token.dao.js');
const utils = require('../utils');
const config = require('../../config');

function getSecret () {
  if (!this._secret) {
    this._secret = config.systemConfig.accessTokens.secretOrPrivateKeyFile
      ? fs.readFileSync(config.systemConfig.accessTokens.secretOrPrivateKeyFile)
      : config.systemConfig.accessTokens.secretOrPrivateKey;
  }
  return this._secret;
}

const s = {};

s.save = function (tokenObj, options) {
  let rt;
  options = options || {};

  if (!tokenObj.consumerId) {
    return Promise.reject(new Error('invalid token args'));
  }

  if (options.refreshTokenOnly) {
    const rt = createInternalToken(tokenObj, newUuid(), newUuid(), 'refresh_token');

    return tokenDao.save(rt, { type: 'refresh_token' })
      .then(() => {
        return { refresh_token: formExternalToken(rt) };
      });
  }

  const at = createInternalToken(tokenObj, newUuid(), newUuid(), 'access_token');
  const tokenSavePromises = [tokenDao.save(at)];

  if (options.includeRefreshToken) {
    rt = createInternalToken(tokenObj, newUuid(), newUuid(), 'refresh_token');
    tokenSavePromises.push(tokenDao.save(rt, { type: 'refresh_token' }));
  }

  return Promise.all(tokenSavePromises)
    .then(() => {
      return {
        access_token: formExternalToken(at),
        refresh_token: formExternalToken(rt)
      };
    });
};

s.findOrSave = function (tokenObj, options) {
  options = options || {};

  return this.find(tokenObj, options)
    .then(tokens => {
      if (tokens.access_token) {
        if (options.includeRefreshToken && !tokens.refresh_token) {
          return this.save(tokenObj, { refreshTokenOnly: true })
            .then(rt => {
              tokens.refresh_token = rt.refresh_token;
              return tokens;
            });
        } else return tokens;
      }

      if (tokens.refresh_token) {
        return this.save(tokenObj)
          .then(at => {
            tokens.access_token = at.access_token;
            return tokens;
          });
      }

      return this.save(tokenObj, options);
    });
};

s.find = function (tokenObj, options) {
  options = options || {};
  const tokenQueryCriteria = Object.assign({}, tokenObj);

  if (tokenQueryCriteria.scopes && Array.isArray(tokenQueryCriteria.scopes)) {
    tokenQueryCriteria.scopes = JSON.stringify(tokenQueryCriteria.scopes.sort());
  }

  const findQueries = [tokenDao.find(tokenQueryCriteria)];

  if (options.includeRefreshToken) {
    findQueries.push(tokenDao.find(tokenQueryCriteria, { type: 'refresh_token' }));
  }

  return Promise.all(findQueries)
    .then(([accessToken, refreshToken]) => {
      return {
        access_token: formExternalToken(accessToken),
        refresh_token: formExternalToken(refreshToken)
      };
    });
};

s.get = function (_token, options) {
  options = options || {};
  const tokenId = _token.split('|')[0];

  return tokenDao.get(tokenId, options)
    .then(token => {
      if (!token) {
        return null;
      }

      if (token.scopes) {
        token.scopes = JSON.parse(token.scopes);
      }

      token.tokenDecrypted = utils.decrypt(token.tokenEncrypted);
      delete token.tokenEncrypted;

      return token;
    });
};

s.getTokenObject = function (refreshToken) {
  return this.get(refreshToken, { type: 'refresh_token' })
    .then(rtObj => {
      if (!rtObj) {
        return null;
      }

      const tokenObj = Object.assign({}, rtObj);
      delete tokenObj.createdAt;
      delete tokenObj.updatedAt;
      delete tokenObj.expiresAt;
      delete tokenObj.tokenDecrypted;
      delete tokenObj.id;

      return tokenObj;
    });
};

s.getTokensByConsumer = function (id, options) {
  return tokenDao.getTokensByConsumer(id, options);
};

s.revoke = function (accessToken) {
  return this.get(accessToken).then(token => {
    if (!token) {
      throw new Error('Token not found ' + token);
    }

    return tokenDao.revoke(token);
  });
};

s.createJWT = function (payload) {
  return new Promise((resolve, reject) => {
    jwt.sign(payload, getSecret(), {
      issuer: config.systemConfig.accessTokens.issuer,
      audience: config.systemConfig.accessTokens.audience,
      expiresIn: config.systemConfig.accessTokens.timeToExpiry,
      subject: config.systemConfig.accessTokens.subject
    }, (err, jwt) => {
      if (err) { return reject(err); }
      return resolve(jwt);
    });
  });
};

const createInternalToken = (criteria, id, token, type) => {
  let timeToExpiry;

  if (type === 'access_token') {
    timeToExpiry = config.systemConfig.accessTokens.timeToExpiry;
  } else timeToExpiry = config.systemConfig.refreshTokens.timeToExpiry;

  const internalTokenObj = Object.assign({
    id,
    tokenEncrypted: utils.encrypt(token),
    expiresAt: Date.now() + timeToExpiry
  }, criteria);

  if (internalTokenObj.scopes && Array.isArray(internalTokenObj.scopes)) {
    internalTokenObj.scopes = JSON.stringify(internalTokenObj.scopes.sort());
  }

  utils.appendCreatedAt(internalTokenObj);
  return internalTokenObj;
};

const formExternalToken = (tokenObj) => {
  if (!tokenObj) return null;
  return tokenObj.id.concat('|', utils.decrypt(tokenObj.tokenEncrypted));
};

const newUuid = () => {
  return uuidv4().replace(new RegExp('-', 'g'), '');
};

module.exports = s;
<|endoftext|>


<commit_before>/*jshint -W032 */
;
/*jshint +W032 */
/* istanbul ignore next */
(function(root, factory) {
  if (typeof define === 'function') {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.ajaxer = factory();
  }
}(this, function() {
  var
    prepareData = function(data) {
      if (!data || typeof data !== "object") {
        return;
      }
      return Object.keys(data).map(function(k) {
        return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
      }).join("&");
    },
    setCallback = function(fn, request) {
      if (!isFunctionArray(fn)) {
        return;
      }
      var onYes,
          onBad;
      if (typeof fn == "function") {
        onYes = fn;
        onBad = null;
      } else {
        onYes = fn.onSuccess;
        onBad = fn.onFail;
      }
      request.onreadystatechange = (function() {
        if (request.readyState === 4) {
          if (request.status === 200) {
            onYes(request.responseText);
          } else {
            onBad(request.response);
          }
        }
      }).bind(request);
    },
    isFunctionArray = function(fnArray) {
      if (typeof fnArray == "function") {
        return true;
      } else if (typeof nArray != "object") {
        return false;
      } else {
        Object.keys(fnArray).forEach(function(x) {
          if (typeof x != "function") {
            return false;
          }
        });
        return true;
      }
    };

  return {
    post: function(url, data, callback, requestInfo) {
      this.connect("POST", url, data, callback, requestInfo);
    },

    get: function(url, data, callback, requestInfo) {
      this.connect("GET", url, data, callback, requestInfo);
    },

    connect: function(style, url, data, callback, requestInfo) {
      if (style !== 'POST' && style !== 'GET') {
        return;
      }
      if (isFunctionArray(data) && typeof callback === "undefined") {
        requestInfo = callback;
        callback = data;
        data = '';
      }

      var request = new XMLHttpRequest(),
        sendData = prepareData(data);

      if (style === "GET" && sendData) {
        var urlParams = "?" + sendData;
        url += urlParams;
        sendData = "";
      }

      setCallback(callback, request);

      request.open(style, url, true);

      if (requestInfo) {
        if (requestInfo.responseType) {
          request.responseType = requestInfo.responseType;
        }
      }

      if (style === "POST") {
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      }
      request.send(sendData);
    }
  };
}));
<commit_msg>json requestHeader has json support<commit_after>/*jshint -W032 */
;
/*jshint +W032 */
(function(root, factory) {
  /* istanbul ignore next */
  if (typeof define === 'function') {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.ajaxer = factory();
  }
}(this, function() {
  var
    prepareData = function(data) {
      if (!data || typeof data !== "object") {
        return;
      }
      return Object.keys(data).map(function(k) {
        return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
      }).join("&");
    },
    setCallback = function(fn, request) {
      if (!isFunctionArray(fn)) {
        return;
      }
      var onYes,
        onBad;
      if (typeof fn == "function") {
        onYes = fn;
        onBad = null;
      } else {
        onYes = fn.onSuccess;
        onBad = fn.onFail;
      }
      request.onreadystatechange = (function() {
        if (request.readyState === 4) {
          if (request.status === 200) {
            onYes(request.response);
          } else {
            onBad(request.response);
          }
        }
      }).bind(request);
    },
    isFunctionArray = function(fnArray) {
      if (typeof fnArray == "function") {
        return true;
      } else if (typeof nArray != "object") {
        return false;
      } else {
        Object.keys(fnArray).forEach(function(x) {
          if (typeof x != "function") {
            return false;
          }
        });
        return true;
      }
    };

  JSON.prototype.isValid = function(tryJson) {
    try {
      var t = JSON.parse(tryJson);
      return t;
    } catch (e) {
      return false;
    }
  };

  return {
    post: function(url, data, callback, requestInfo) {
      this.connect("POST", url, data, callback, requestInfo);
    },

    get: function(url, data, callback, requestInfo) {
      this.connect("GET", url, data, callback, requestInfo);
    },

    connect: function(style, url, data, callback, requestInfo) {
      if (style !== 'POST' && style !== 'GET') {
        return;
      }
      if (isFunctionArray(data) && typeof callback === "undefined") {
        requestInfo = callback;
        callback = data;
        data = '';
      }

      var request = new XMLHttpRequest(),
        sendData = prepareData(data);

      if (style === "GET" && sendData) {
        var urlParams = "?" + sendData;
        url += urlParams;
        sendData = "";
      }

      setCallback(callback, request);

      request.open(style, url, true);

      if (requestInfo) {
        if (requestInfo.responseType) {
          request.responseType = requestInfo.responseType;
        }
      }

      if (style === "POST") {
        if (JSON.isValid(data)) {
          sendData = data;
          request.setRequestHeader("Content-type", "application/json");
        } else {
          request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        }
      }
      request.send(sendData);
    }
  };
}));
<|endoftext|>


<commit_before>describe("watch", function() {
    "use strict";

    var WAIT_FOR_WATCH_TIME = 30,
        callback;

    beforeEach(function() {
        callback = jasmine.createSpy("callback");
    });

    it("should execute callback for every existed element on page", function() {
        setFixtures("");

        DOM.watch(".watch", callback);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(3);
        });
    });

    it("should execute for each matched future element on page", function() {
        DOM.watch(".watch1", callback);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback).not.toHaveBeenCalled();

            setFixtures("");
        });

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(2);
        });
    });

    it("should have DOM element as the first argument", function() {
        setFixtures("");

        DOM.watch(".watch2", callback.andCallFake(function(el) {
            expect(el).toBeDefined();
            expect(el._node).toBeTruthy();
        }));

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(2);
        });
    });

    it("should accept several watchers of the same selector", function() {
        var spy = jasmine.createSpy("callback2");

        setFixtures("");

        DOM.watch(".watch4", callback);
        DOM.watch(".watch4", spy);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(2);
            expect(spy.callCount).toBe(2);
        });
    });

    // FIXME: find a way to test without exception in browser
    // it("should not stop handle other listeners if any throws an error", function() {
    //     var otherCallback = jasmine.createSpy("otherCallback");

    //     DOM.watch(".watch5", callback.andCallFake(function() {
    //         throw "watch";
    //     }));

    //     DOM.watch(".watch5", otherCallback);

    //     setFixtures("");

    //     waits(WAIT_FOR_WATCH_TIME);

    //     runs(function() {
    //         expect(callback).toHaveBeenCalled();
    //         expect(otherCallback).toHaveBeenCalled();
    //     });
    // });

    it("should accept callbacks with different once argument for the same selector", function() {
        var otherCallback = jasmine.createSpy("otherCallback");

        DOM.watch("#watch6", callback, true);
        DOM.watch("#watch6", otherCallback);

        setFixtures("");

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(1);
            expect(otherCallback.callCount).toBe(1);
        });

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            var link = DOM.find("#watch6");

            link.remove();

            setFixtures(link._node);
        });

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(1);
            expect(otherCallback.callCount).toBe(2);
        });
    });

    it("should not match parent elements", function() {
        var spy1 = jasmine.createSpy("spy1"),
            spy2 = jasmine.createSpy("spy2");

        setFixtures("<form id='watch7'><input id='watch8'/></form>");

        DOM.watch("#watch7", spy1);
        DOM.watch("#watch8", spy2);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(spy1.callCount).toBe(1);
            expect(spy2.callCount).toBe(1);
        });
    });

});<commit_msg>WAIT_FOR_WATCH_TIME = 50<commit_after>describe("watch", function() {
    "use strict";

    var WAIT_FOR_WATCH_TIME = 50,
        callback;

    beforeEach(function() {
        callback = jasmine.createSpy("callback");
    });

    it("should execute callback for every existed element on page", function() {
        setFixtures("");

        DOM.watch(".watch", callback);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(3);
        });
    });

    it("should execute for each matched future element on page", function() {
        DOM.watch(".watch1", callback);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback).not.toHaveBeenCalled();

            setFixtures("");
        });

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(2);
        });
    });

    it("should have DOM element as the first argument", function() {
        setFixtures("");

        DOM.watch(".watch2", callback.andCallFake(function(el) {
            expect(el).toBeDefined();
            expect(el._node).toBeTruthy();
        }));

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(2);
        });
    });

    it("should accept several watchers of the same selector", function() {
        var spy = jasmine.createSpy("callback2");

        setFixtures("");

        DOM.watch(".watch4", callback);
        DOM.watch(".watch4", spy);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(2);
            expect(spy.callCount).toBe(2);
        });
    });

    // FIXME: find a way to test without exception in browser
    // it("should not stop handle other listeners if any throws an error", function() {
    //     var otherCallback = jasmine.createSpy("otherCallback");

    //     DOM.watch(".watch5", callback.andCallFake(function() {
    //         throw "watch";
    //     }));

    //     DOM.watch(".watch5", otherCallback);

    //     setFixtures("");

    //     waits(WAIT_FOR_WATCH_TIME);

    //     runs(function() {
    //         expect(callback).toHaveBeenCalled();
    //         expect(otherCallback).toHaveBeenCalled();
    //     });
    // });

    it("should accept callbacks with different once argument for the same selector", function() {
        var otherCallback = jasmine.createSpy("otherCallback");

        DOM.watch("#watch6", callback, true);
        DOM.watch("#watch6", otherCallback);

        setFixtures("");

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(1);
            expect(otherCallback.callCount).toBe(1);
        });

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            var link = DOM.find("#watch6");

            link.remove();

            setFixtures(link._node);
        });

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(callback.callCount).toBe(1);
            expect(otherCallback.callCount).toBe(2);
        });
    });

    it("should not match parent elements", function() {
        var spy1 = jasmine.createSpy("spy1"),
            spy2 = jasmine.createSpy("spy2");

        setFixtures("<form id='watch7'><input id='watch8'/></form>");

        DOM.watch("#watch7", spy1);
        DOM.watch("#watch8", spy2);

        waits(WAIT_FOR_WATCH_TIME);

        runs(function() {
            expect(spy1.callCount).toBe(1);
            expect(spy2.callCount).toBe(1);
        });
    });

});<|endoftext|>


<commit_before>var fs   = require('fs'),
burrito  = require('burrito'),
outcome  = require('outcome'),
uglify = require('uglify-js'),
parser   = uglify.parser;

/**
 * finds an expression based on the filter given
 */

function traverse(ast, filter, filtered) {
	if(!filtered) filtered = [];

	for(var i = ast.length; i--;) {

		var node = ast[i];
		if(!(node instanceof Array)) continue;

		if(filter(node)) {
			filtered.push(node);
		}

		traverse(node, filter, filtered);
	}

	return filtered;
}

/**
 */

function cloneArray(target) {
	return JSON.parse(JSON.stringify(target));
}

/**
 */

function parse(content) {
	return parser.parse(content);
}

/**
 */

function stringify(ast, b) {
	return uglify.uglify.gen_code(ast, { beautify : b });
}

/**
 * wraps the target JS around a shit-ton of try catch blocks. Oh god why >.>...
 */

function wrapWithShitLoadsOfTryCatchBlocks(content, ops) {

	//preprend the error handler if the option is set for it.
	if(ops.addHandler)
	content = "var catchall = catchall || { \
		error: function() {} \
	}" + content;

	var ast = parse(content);

	//first need to find ALL the functions in the given script
	var fns = traverse(ast, function(x) {
		return x[0] == 'defun' || x[0] == 'function';
	}),

	//next we need to parse a try-catch block. this wraps around the function body
	tryCatchAst = traverse(parse('try { } catch(e){ catchall.error(e); }'), function(x) {
		return x[0] == 'try';
	}).pop();

	//finally - need to loop through all the functions and wrap the
	//bodies in try/catch blocks
	for(var i = fns.length; i--;) {
		var fn = fns[i],
		tryCatchAstClone = cloneArray(tryCatchAst);

		//set the body to the try catch tpl
		tryCatchAstClone[1] = fn[3];

		//set fn body to the try-catch block
		fn[3] = [tryCatchAstClone];

	}

	return ast;

}

/**
 * generates from content
 */

exports.generate = function(content, ops, callback) {

	if(typeof ops == 'function') {

		callback = ops;
		ops = undefined;

	}

	try {

		//grap the new ast
		var ast = wrapWithShitLoadsOfTryCatchBlocks(content, ops);

		//error not thrown at this point - good, now we can return the result.
		callback(null, stringify(ast, true));

	} catch(e) {

		//uglify-js didn't like the input
		return callback(e);

	}

}
<commit_msg>cleanup<commit_after>var fs   = require('fs'),
burrito  = require('burrito'),
outcome  = require('outcome'),
uglify = require('uglify-js'),
parser   = uglify.parser;

/**
 * finds an expression based on the filter given
 */

function traverse(ast, filter, filtered) {

	var node;

	if(!filtered) filtered = [];

	for(var i = ast.length; i--;) {

		node = ast[i];

		if(!(node instanceof Array)) continue;

		if(filter(node)) {

			filtered.push(node);

		}

		traverse(node, filter, filtered);

	}

	return filtered;

}

/**
 */

function cloneArray(target) {

	return JSON.parse(JSON.stringify(target));

}

/**
 */

function parse(content) {

	return parser.parse(content);

}

/**
 */

function stringify(ast, b) {

	return uglify.uglify.gen_code(ast, { beautify : b });

}

/**
 * wraps the target JS around a shit-ton of try catch blocks. Oh god why >.>...
 */

function wrapWithShitLoadsOfTryCatchBlocks(content, ops) {

	var ast, fn, fns, tryCatchAst, tryCatchAstClone, cnt = content;

	//preprend the error handler if the option is set for it.
	if(ops.addHandler) {

		cnt = "var catchall = catchall || { \
			error: function() {} \
		}" + cnt;

	}

	ast = parse(cnt);

	//first need to find ALL the functions in the given script
	fns = traverse(ast, function(x) {

		return x[0] == 'defun' || x[0] == 'function';

	});

	//next we need to parse a try-catch block. this wraps around the function body
	tryCatchAst = traverse(parse('try { } catch(e){ catchall.error(e); }'), function(x) {

		return x[0] == 'try';

	}).pop();

	//finally - need to loop through all the functions and wrap the
	//bodies in try/catch blocks
	for(var i = fns.length; i--;) {

		fn = fns[i];

		tryCatchAstClone = cloneArray(tryCatchAst);

		//set the body to the try catch tpl
		tryCatchAstClone[1] = fn[3];

		//set fn body to the try-catch block
		fn[3] = [tryCatchAstClone];

	}

	return ast;

}

/**
 * generates from content
 */

exports.generate = function(content, ops, callback) {

	if(typeof ops == 'function') {

		callback = ops;
		ops = undefined;

	}

	try {

		//grap the new ast
		var ast = wrapWithShitLoadsOfTryCatchBlocks(content, ops);

		//error not thrown at this point - good, now we can return the result.
		callback(null, stringify(ast, true));

	} catch(e) {

		//uglify-js didn't like the input
		return callback(e);

	}

}
<|endoftext|>


<commit_before>const noLaunch = process.argv.includes('--no-launch')
const testMinified = process.argv.includes('--minified')
const isSauce = process.argv.includes('--sauce')
const isNetlify = process.argv.includes('--netlify')

if (isNetlify) {
  process.env.CHROME_BIN = require('puppeteer').executablePath()
}

const webpackConfig = {
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|dist)/,
        use: {
          loader: 'babel-loader',
          options: {/* babel options */}
        }
      }
    ]
  }
}

const karmaPlugins = [
  'karma-webpack',
  'karma-qunit',
  'karma-spec-reporter',
  'karma-sourcemap-loader',
  'karma-chrome-launcher',
  'karma-firefox-launcher',
  'karma-ie-launcher',
  'karma-sauce-launcher'
]

const preprocessors = {
  'test/qunit/**/*.js': [
    'webpack',
    'sourcemap'
  ],
}

const sauceLabsLaunchers = {
  safari: {
    base: 'SauceLabs',
    browserName: 'Safari',
    version: 'latest',
    platform: 'macOS 10.15'
  },
  edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    browserVersion: '18.17763',
    platform: 'Windows 10',
  },
  ie: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platformVersion: '11.0',
    platform: 'Windows 7'
  },
  iphone: {
    base: 'SauceLabs',
    browserName: 'Safari',
    deviceName: 'iPhone Simulator',
    platformName: 'iOS',
    platformVersion: 'latest'
  },
}

function checkSauceCredentials () {
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.error('SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables must be set')
    process.exit(1)
  }
}

function getFiles () {
  let files
  if (testMinified) {
    files = [
      'dist/sweetalert2.all.min.js'
    ]
  } else {
    files = [
      'dist/sweetalert2.css',
      'dist/sweetalert2.js'
    ]
  }
  return files.concat([
    'node_modules/promise-polyfill/dist/polyfill.min.js',
    'test/qunit/**/*.js'
  ])
}

function getBrowsers () {
  if (noLaunch) {
    return []
  }

  let browsers = ['ChromeHeadless']

  // Cron on GitHub Actions or check:qunit --sauce
  if (isSauce) {
    checkSauceCredentials()
    browsers = Object.keys(sauceLabsLaunchers)

  // GitHub Actions
  } else if (process.env.GITHUB_ACTION) {
    browsers = ['ChromeHeadless', 'FirefoxHeadless']
  }

  return browsers
}

module.exports = function (config) {
  config.set({
    port: 3000,
    plugins: karmaPlugins,

    frameworks: ['qunit'],
    qunit: { reorder: false },

    customLaunchers: sauceLabsLaunchers,

    files: getFiles(),
    browsers: getBrowsers(),
    reporters: ['spec', 'saucelabs'],
    preprocessors,

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: 'errors-only'
    },

    captureTimeout: 360000,
    browserNoActivityTimeout: 360000
  })
}
<commit_msg>chore: remove iOS from sauce platforms<commit_after>const noLaunch = process.argv.includes('--no-launch')
const testMinified = process.argv.includes('--minified')
const isSauce = process.argv.includes('--sauce')
const isNetlify = process.argv.includes('--netlify')

if (isNetlify) {
  process.env.CHROME_BIN = require('puppeteer').executablePath()
}

const webpackConfig = {
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|dist)/,
        use: {
          loader: 'babel-loader',
          options: {/* babel options */}
        }
      }
    ]
  }
}

const karmaPlugins = [
  'karma-webpack',
  'karma-qunit',
  'karma-spec-reporter',
  'karma-sourcemap-loader',
  'karma-chrome-launcher',
  'karma-firefox-launcher',
  'karma-ie-launcher',
  'karma-sauce-launcher'
]

const preprocessors = {
  'test/qunit/**/*.js': [
    'webpack',
    'sourcemap'
  ],
}

const sauceLabsLaunchers = {
  safari: {
    base: 'SauceLabs',
    browserName: 'Safari',
    version: 'latest',
    platform: 'macOS 10.15'
  },
  edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    browserVersion: '18.17763',
    platform: 'Windows 10',
  },
  ie: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platformVersion: '11.0',
    platform: 'Windows 7'
  },
}

function checkSauceCredentials () {
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.error('SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables must be set')
    process.exit(1)
  }
}

function getFiles () {
  let files
  if (testMinified) {
    files = [
      'dist/sweetalert2.all.min.js'
    ]
  } else {
    files = [
      'dist/sweetalert2.css',
      'dist/sweetalert2.js'
    ]
  }
  return files.concat([
    'node_modules/promise-polyfill/dist/polyfill.min.js',
    'test/qunit/**/*.js'
  ])
}

function getBrowsers () {
  if (noLaunch) {
    return []
  }

  let browsers = ['ChromeHeadless']

  // Cron on GitHub Actions or check:qunit --sauce
  if (isSauce) {
    checkSauceCredentials()
    browsers = Object.keys(sauceLabsLaunchers)

  // GitHub Actions
  } else if (process.env.GITHUB_ACTION) {
    browsers = ['ChromeHeadless', 'FirefoxHeadless']
  }

  return browsers
}

module.exports = function (config) {
  config.set({
    port: 3000,
    plugins: karmaPlugins,

    frameworks: ['qunit'],
    qunit: { reorder: false },

    customLaunchers: sauceLabsLaunchers,

    files: getFiles(),
    browsers: getBrowsers(),
    reporters: ['spec', 'saucelabs'],
    preprocessors,

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: 'errors-only'
    },

    captureTimeout: 360000,
    browserNoActivityTimeout: 360000
  })
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Jul 04 2015 11:53:54 GMT+0200 (CEST)

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: 'script',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'requirejs'],

        // list of files / patterns to load in the browser
        files: [
            '../tests/test-main.js', {
                pattern: '../tests/tests.js',
                included: false
            }
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {},

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome', 'Safari', 'Firefox'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    });
};
<commit_msg>some changes to improve tests<commit_after>// Karma configuration
// Generated on Sat Jul 04 2015 11:53:54 GMT+0200 (CEST)

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: 'script',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'requirejs'],

        // list of files / patterns to load in the browser
        files: [
            '../tests/test-main.js', {
                pattern: '../tests/tests.js',
                included: false
            }, {
                pattern: 'script/sphere.min.js',
                included: false
            }
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {},

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome', 'Firefox'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    });
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  View,
  ActivityIndicator
} from 'react-native';
import { Field, reduxForm } from 'redux-form';
import { withNavigation } from 'react-navigation';
import { getLanguage } from 'helpers/language';

import I18n from 'locales';
import Theme from 'config/theme';
import StepsSlider from 'components/common/steps-slider';
import getInputForm from 'components/common/form-inputs';
import ActionButton from 'components/common/action-button';
import Header from './header';
import NextButton from './next-button';
import styles from './styles';

function isEmptyAnswer(answer) {
  if (!answer) return true;
  switch (answer.constructor) {
    case Array:
      return answer.length <= 0;
    case String:
      return answer === '';
    case Object:
      return Object.keys(answer) <= 0;
    default:
      return true;
  }
}

function getBtnTextByType(type) {
  switch (type) {
    case 'text':
      return I18n.t('report.inputText');
    case 'radio':
      return I18n.t('report.inputRadio');
    case 'select':
      return I18n.t('report.inputSelect');
    default:
      return I18n.t('report.input');
  }
}

function getBtnTextByPosition(position, total) {
  return position < total
    ? 'Next'
    : 'Save';
}

function renderLoading() {
  return (
    <View style={[styles.container, styles.containerCenter]}>
      <ActivityIndicator
        color={Theme.colors.color1}
        style={{ height: 80 }}
        size={'large'}
      />
    </View>
  );
}

class FeedBackForm extends Component {
  constructor() {
    super();

    this.state = {
      page: 0
    };
    this.questionsToSkip = 0;
    this.pageHistory = [];
  }

  componentWillMount() {
    if ((this.props.questions && !this.props.questions.length) || this.isDifferentLanguage()) {
      this.props.getQuestions(this.props.feedback);
    }
  }

  isDifferentLanguage() {
    return this.props.reportLanguage !== getLanguage().toUpperCase();
  }

  handleBack = () => {
    if (this.state.page > 0) {
      const prevPage = this.pageHistory[this.pageHistory.length - 1];
      if (prevPage >= 0) {
        this.setState({
          page: this.pageHistory[this.pageHistory.length - 1]
        });
        this.pageHistory.pop();
      }
      this.prevPag = this.prevPage - 1;
    } else {
      this.props.navigation.goBack();
    }
  }

  goToNextPage = () => {
    const { questions, answers } = this.props;
    const currentQuestion = this.state.page + this.questionsToSkip;
    let next = 1;
    if (currentQuestion < questions.length - 1) {
      for (let i = currentQuestion + 1, qLength = questions.length; i < qLength; i++) {
        const nextConditions = questions[i].conditions;
        const nexthasConditions = nextConditions && nextConditions.length > 0;
        if (!nexthasConditions || (answers[nextConditions[0].name] === nextConditions[0].value)) {
          this.jumptToPage(next);
          break;
        } else {
          next += 1;
        }
      }
    } else {
      const { state } = this.props.navigation;
      const feedback = state && state.params && state.params.feedback;
      this.props.finishFeedback(feedback);
      this.props.navigation.goBack();
    }
  }

  jumptToPage(jump) {
    this.pageHistory.push(this.state.page);
    this.setState((prevState) => ({
      page: prevState.page + jump
    }));
  }

  render() {
    const { questions, answers } = this.props;
    if (!questions || !questions.length) return renderLoading();

    const questionNumber = this.state.page + this.questionsToSkip;
    const question = questions[questionNumber];
    const isImageInput = question.type === 'blob';
    const answer = answers && answers[question.name];
    const emptyAnswer = isEmptyAnswer(answer);
    const disabled = emptyAnswer && question.required;
    const btnText = disabled ? getBtnTextByType(question.type) : getBtnTextByPosition(questionNumber, questions.length - 1);
    return (
      <View style={styles.container}>
        <Header
          light={isImageInput && emptyAnswer}
          title={isImageInput && emptyAnswer ? I18n.t('report.takePicture') : I18n.t('report.title')}
          onBackPress={this.handleBack}
        />
        <StepsSlider
          style={isImageInput && emptyAnswer ? styles.containerFull : styles.containerFloat}
          page={this.state.page}
          hideIndex={isImageInput && emptyAnswer}
          onChangeTab={this.updatePage}
        >
          {questions.map((item, index) => {
            if (index < this.questionsToSkip) return null;
            return (
              <View style={styles.container} key={index}>
                <Field
                  name={item.name} // eslint-disable-line
                  component={getInputForm}
                  question={item}
                />
              </View>
            );
          })}
        </StepsSlider>
        {isImageInput
          ? <NextButton transparent={emptyAnswer} style={styles.buttonNextPos} disabled={disabled} onPress={this.goToNextPage} />
          : <ActionButton style={styles.buttonPos} disabled={disabled} onPress={this.goToNextPage} text={btnText} />
        }
      </View>
    );
  }
}

FeedBackForm.propTypes = {
  finishFeedback: React.PropTypes.func.isRequired,
  getQuestions: React.PropTypes.func.isRequired,
  reportLanguage: React.PropTypes.string.isRequired,
  feedback: React.PropTypes.string.isRequired,
  questions: React.PropTypes.array.isRequired,
  answers: React.PropTypes.object.isRequired,
  navigation: React.PropTypes.object.isRequired
};

export default reduxForm({
  destroyOnUnmount: false
})(withNavigation(FeedBackForm));
<commit_msg>Fix missing translation<commit_after>import React, { Component } from 'react';
import {
  View,
  ActivityIndicator
} from 'react-native';
import { Field, reduxForm } from 'redux-form';
import { withNavigation } from 'react-navigation';
import { getLanguage } from 'helpers/language';

import I18n from 'locales';
import Theme from 'config/theme';
import StepsSlider from 'components/common/steps-slider';
import getInputForm from 'components/common/form-inputs';
import ActionButton from 'components/common/action-button';
import Header from './header';
import NextButton from './next-button';
import styles from './styles';

function isEmptyAnswer(answer) {
  if (!answer) return true;
  switch (answer.constructor) {
    case Array:
      return answer.length <= 0;
    case String:
      return answer === '';
    case Object:
      return Object.keys(answer) <= 0;
    default:
      return true;
  }
}

function getBtnTextByType(type) {
  switch (type) {
    case 'text':
      return I18n.t('report.inputText');
    case 'radio':
      return I18n.t('report.inputRadio');
    case 'select':
      return I18n.t('report.inputSelect');
    default:
      return I18n.t('report.input');
  }
}

function getBtnTextByPosition(position, total) {
  return position < total
    ? I18n.t('commonText.next')
    : I18n.t('commonText.save');
}

function renderLoading() {
  return (
    <View style={[styles.container, styles.containerCenter]}>
      <ActivityIndicator
        color={Theme.colors.color1}
        style={{ height: 80 }}
        size={'large'}
      />
    </View>
  );
}

class FeedBackForm extends Component {
  constructor() {
    super();

    this.state = {
      page: 0
    };
    this.questionsToSkip = 0;
    this.pageHistory = [];
  }

  componentWillMount() {
    if ((this.props.questions && !this.props.questions.length) || this.isDifferentLanguage()) {
      this.props.getQuestions(this.props.feedback);
    }
  }

  isDifferentLanguage() {
    return this.props.reportLanguage !== getLanguage().toUpperCase();
  }

  handleBack = () => {
    if (this.state.page > 0) {
      const prevPage = this.pageHistory[this.pageHistory.length - 1];
      if (prevPage >= 0) {
        this.setState({
          page: this.pageHistory[this.pageHistory.length - 1]
        });
        this.pageHistory.pop();
      }
      this.prevPag = this.prevPage - 1;
    } else {
      this.props.navigation.goBack();
    }
  }

  goToNextPage = () => {
    const { questions, answers } = this.props;
    const currentQuestion = this.state.page + this.questionsToSkip;
    let next = 1;
    if (currentQuestion < questions.length - 1) {
      for (let i = currentQuestion + 1, qLength = questions.length; i < qLength; i++) {
        const nextConditions = questions[i].conditions;
        const nexthasConditions = nextConditions && nextConditions.length > 0;
        if (!nexthasConditions || (answers[nextConditions[0].name] === nextConditions[0].value)) {
          this.jumptToPage(next);
          break;
        } else {
          next += 1;
        }
      }
    } else {
      const { state } = this.props.navigation;
      const feedback = state && state.params && state.params.feedback;
      this.props.finishFeedback(feedback);
      this.props.navigation.goBack();
    }
  }

  jumptToPage(jump) {
    this.pageHistory.push(this.state.page);
    this.setState((prevState) => ({
      page: prevState.page + jump
    }));
  }

  render() {
    const { questions, answers } = this.props;
    if (!questions || !questions.length) return renderLoading();

    const questionNumber = this.state.page + this.questionsToSkip;
    const question = questions[questionNumber];
    const isImageInput = question.type === 'blob';
    const answer = answers && answers[question.name];
    const emptyAnswer = isEmptyAnswer(answer);
    const disabled = emptyAnswer && question.required;
    const btnText = disabled ? getBtnTextByType(question.type) : getBtnTextByPosition(questionNumber, questions.length - 1);
    return (
      <View style={styles.container}>
        <Header
          light={isImageInput && emptyAnswer}
          title={isImageInput && emptyAnswer ? I18n.t('report.takePicture') : I18n.t('report.title')}
          onBackPress={this.handleBack}
        />
        <StepsSlider
          style={isImageInput && emptyAnswer ? styles.containerFull : styles.containerFloat}
          page={this.state.page}
          hideIndex={isImageInput && emptyAnswer}
          onChangeTab={this.updatePage}
        >
          {questions.map((item, index) => {
            if (index < this.questionsToSkip) return null;
            return (
              <View style={styles.container} key={index}>
                <Field
                  name={item.name} // eslint-disable-line
                  component={getInputForm}
                  question={item}
                />
              </View>
            );
          })}
        </StepsSlider>
        {isImageInput
          ? <NextButton transparent={emptyAnswer} style={styles.buttonNextPos} disabled={disabled} onPress={this.goToNextPage} />
          : <ActionButton style={styles.buttonPos} disabled={disabled} onPress={this.goToNextPage} text={btnText} />
        }
      </View>
    );
  }
}

FeedBackForm.propTypes = {
  finishFeedback: React.PropTypes.func.isRequired,
  getQuestions: React.PropTypes.func.isRequired,
  reportLanguage: React.PropTypes.string.isRequired,
  feedback: React.PropTypes.string.isRequired,
  questions: React.PropTypes.array.isRequired,
  answers: React.PropTypes.object.isRequired,
  navigation: React.PropTypes.object.isRequired
};

export default reduxForm({
  destroyOnUnmount: false
})(withNavigation(FeedBackForm));
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var Form              = require('./Form');

var Field             = require('./Field');
var Fieldset          = require('./Fieldset');
var RepeatingFieldset = require('./RepeatingFieldset');
var Element           = require('./Element');
var Input             = require('./Input');
var ValidationResult  = require('./ValidationResult');

var Message           = require('./Message');
var Label             = require('./Label');

var PropTypes         = require('./PropTypes');

var messages          = require('./messages');
var schema            = require('./value/schema');

module.exports = {
  Form,
  Field, Fieldset, RepeatingFieldset,
  Element, Input,
  Message, Label,
  PropTypes,
  schema, messages, ValidationResult
};
<commit_msg>Remove old code require.<commit_after>/**
 * @jsx React.DOM
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var Form              = require('./Form');

var Field             = require('./Field');
var Fieldset          = require('./Fieldset');
var RepeatingFieldset = require('./RepeatingFieldset');
var Element           = require('./Element');
var Input             = require('./Input');

var Message           = require('./Message');
var Label             = require('./Label');

var PropTypes         = require('./PropTypes');

var messages          = require('./messages');
var schema            = require('./value/schema');

module.exports = {
  Form,
  Field, Fieldset, RepeatingFieldset,
  Element, Input,
  Message, Label,
  PropTypes,
  schema, messages
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var urls = require('./web/urls');
var schema = require('../extern/devopsjson/lib/web/schema').schema;
var JSV = require('JSV').JSV;
var _ = require('underscore');

/**
 * makeClass - By John Resig (MIT Licensed)
 * Takes a function and ensures that new is called so that __this__ is properly bound
 * @param {proto} optional prototype to set on the returned function
 */
exports.make_class = function(proto){
  var f = function(args){
    // did you make me with new?
    if (this instanceof arguments.callee){
      // am I a function?
      if (typeof this.init === "function"){
          //PREGUNTA: why not always pass apply arguments?
          if (args){
            return this.init.apply(this, args.callee ? args : arguments );
          }
          else{
            return this.init.apply(this, arguments);
          }
        }
    } else{
      // didn't use new, return a properly instantiated object
      return new arguments.callee(arguments);
    }
  };
  if (proto){
    f.prototype = proto;
  }
  return f;
};
var HEALTH_OK = 1;
var HEALTH_WARNING = 2;
var HEALTH_ERROR = 3;
var HEALTH_UNKNOWN = 4;

exports.HEALTH_ENUM = {};
exports.HEALTH_ENUM[HEALTH_OK] = 'OK';
exports.HEALTH_ENUM[HEALTH_WARNING] = 'PROBLEM';
exports.HEALTH_ENUM[HEALTH_ERROR] = 'ERROR';
exports.HEALTH_ENUM[HEALTH_UNKNOWN] = 'UNKNOWN';

// build an array (of Numbers) to check against
var VALID_HEALTH = _.map(_.keys(exports.HEALTH_ENUM), function(n){return Number(n);});

var api_host_properties = exports.make_class({
  init: function(data){
    this.validate_data(data);
    _.extend(this, data);
  },
  handle_new_data: function(data){
    var fresh, that;
    this.validate_data(data);

    fresh = false;
    if (data.timestamp >= this.timestamp){
      fresh = true;
      this.timestamp = data.timestamp;
      this.health = data.health;
      this.ip = data.ip;
    }

    that = this;
    _.each(data.services, function(service, service_name){
      var should_update_service = (!that.services[service_name]) ||
        (that.services[service_name].timestamp < service.timestamp);
      if (should_update_service){
        that.services[service_name] = service;
      }
    });
  },
  validate_data: function(data){
    var that;
    //TODO: use swiz for this
    if (!data.timestamp){
      throw new Error('You must specify a timestamp');
    }
    if (!data.name){
      throw new Error('You must specify a name');
    }
    that = this;
    debugger;
    data.timestamp = this._validate_time(data.timestamp);
    data.health = this._validate_health(data.health);
    _.each(data.services, function(service, service_name){
      service.timestamp = data.timestamp;
      service.health = that._validate_health(service.health);
    });
  },
  expire_data: function(old){
  },
  _validate_time: function(time_like){
    // have Date parse the time like thing and convert to a Number
    return (new Date(time_like)).getTime();
  },
  _validate_health: function(health){
    if (VALID_HEALTH.indexOf(health) != -1){
      return health;
    }
    throw new Error('Health status: ' + health + ' is not valid');
  }
});

exports.api_cache = exports.make_class({
  init: function(){
    //this.interval_id = setInterval(_.bind(this._purge_old_data, this), this._purge_interval);
  },
  handle_push: function(project, host_data){
    if (!this._projects[project]){
      this._projects[project] = {};
    }
    if (!this._projects[project][host_data.name]){
      this._projects[project][host_data.name] = new api_host_properties(host_data);
    } else{
     this._projects[project][host_data.name].handle_new_data(host_data);
    }
  },
  _purge_old_data: function(){
    var old = this.get_expired_time();
    _.each(this._projects, function(project){
      _.each(project, function(service){
        service.expire_data(old);
      });
    });
  },
  get_expired_time: function(){
    return Date.now() - this._stats_window;
  },
  _projects: {},
  _purge_interval: 60 * 1000
});

/**
 * Takes a username and password and returns a basic auth token fully formed
 *
 */
exports.create_basic_auth = function(username, password){
  var auth_token = new Buffer(username + ':' + password).toString('base64');
  return "Basic " + auth_token;
};

/**
 * Takes middlware function pointer with arrity of 5 and returns a middleware
 *
 * @param {string} name the name of the middleware (should be unique)
 * @param {fn} the middleware proper which should accept (req, res, next, payload, api_config- set payload.data/errors to cache stuff, api_config = req.devops[name]
 * @return {fn} middleware function
 */
exports.create_middleware = function(name, middleware){
  return function(req, res, next){
    // Do they have the api defined in the devops ball?
    if (!req.devops.related_apis || !req.devops.related_apis[name]) {
      req.devops[name] = null;
      next();
      return;
    }
      var payload = {error: null, data: null};
      req.devops[name] = payload;
      try{
        middleware(req, res, next, payload, req.devops.related_apis[name]);
      }catch (e){
        payload.error = e;
        // TODO: this may not be callable if the error was with express
        next();
      }
  };
};

/**
 * Makes a fake response object which the injector middleware needs (as for unit tests).  Call with new!
 *
 * @return {obj}
 */
 var mock_res = function(){};
 mock_res.prototype.locals = function(obj){
  if (!this._locals){
    this._locals = {};
  }
  if (!obj){
    return this._locals;
  }
  for (var key in obj){
    var val = obj[key];
    if (val===undefined){
      continue;
    }
    this._locals[key] = val;
  }
};
exports.mock_res = mock_res;
/**
 * Takes a relative or absolute devops filename and returns the parsed content
 *
 * @param {string} devops_filename the filename of the devopsjson file relative to the fixtures directory
 * @return {Object} parsed content of JSON file
 */
exports.load_devops = function(devops_path) {
  var devops;
  devops = fs.readFileSync(devops_path);
  devops = JSON.parse(devops);
  return devops;
};

/** A convenience function for making requests without having to build up response body data.
 * Also useful for mocking the making of requests in tests
 * @param {Object} options an options dict such as http.request would use
 * @param {fn} on_success callback that takes the complete response body data as a parameter
 * @param {fn} on_error callback that takes an Exception as a parameter
 */
exports.request_maker = function(options, call_back) {
  var req = {'443': https, '80': http}[options.port].get(options, function(res) {
    var data = '';
    res.setEncoding('utf8');
    res.on('data', function(d) {
      data += d;
    });
    res.on('end', function() {
      //TODO:  this is pretty strange, change me.
      try{
        call_back(null, data);
      }catch(e){
        call_back(e, data);
      }
    });
  }).on('error', function(e) {
    call_back(e, null);
  });
};

/**
 *@param project {string} Project name (should match devops.json file name)
 *@param devops {Object} devops.json object
 */
exports.create_navbar = function(project, devops) {
  var navbar;
  var related_apis = devops.related_apis;
  navbar = {};
  navbar[exports.capitalize(project)] = '/p/' + project;

  if (related_apis.version_one) {
    navbar.Defects = urls.DEFECTS.replace(':project', project);
  }
  if (related_apis.github) {
    navbar.DevHealth = urls.DEVHEALTH.replace(':project', project);
  }
  navbar["Service Health"] = urls.SERVICE_HEALTH.replace(':project', project);

  return navbar;
};

/**
 * @param string
 * @returns new string with first letter capitalized
 */
exports.capitalize = function(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

exports.validate_devops = function(devops){
  var jsv_env = JSV.createEnvironment('json-schema-draft-03');
  var report = jsv_env.validate(devops, schema);

  if (report.errors.length > 0) {
    console.log("ERRORS: ", report.errors);
  }
  return report;
};
<commit_msg>no more debugger statements<commit_after>var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var urls = require('./web/urls');
var schema = require('../extern/devopsjson/lib/web/schema').schema;
var JSV = require('JSV').JSV;
var _ = require('underscore');

/**
 * makeClass - By John Resig (MIT Licensed)
 * Takes a function and ensures that new is called so that __this__ is properly bound
 * @param {proto} optional prototype to set on the returned function
 */
exports.make_class = function(proto){
  var f = function(args){
    // did you make me with new?
    if (this instanceof arguments.callee){
      // am I a function?
      if (typeof this.init === "function"){
          //PREGUNTA: why not always pass apply arguments?
          if (args){
            return this.init.apply(this, args.callee ? args : arguments );
          }
          else{
            return this.init.apply(this, arguments);
          }
        }
    } else{
      // didn't use new, return a properly instantiated object
      return new arguments.callee(arguments);
    }
  };
  if (proto){
    f.prototype = proto;
  }
  return f;
};
var HEALTH_OK = 1;
var HEALTH_WARNING = 2;
var HEALTH_ERROR = 3;
var HEALTH_UNKNOWN = 4;

exports.HEALTH_ENUM = {};
exports.HEALTH_ENUM[HEALTH_OK] = 'OK';
exports.HEALTH_ENUM[HEALTH_WARNING] = 'PROBLEM';
exports.HEALTH_ENUM[HEALTH_ERROR] = 'ERROR';
exports.HEALTH_ENUM[HEALTH_UNKNOWN] = 'UNKNOWN';

// build an array (of Numbers) to check against
var VALID_HEALTH = _.map(_.keys(exports.HEALTH_ENUM), function(n){return Number(n);});

var api_host_properties = exports.make_class({
  init: function(data){
    this.validate_data(data);
    _.extend(this, data);
  },
  handle_new_data: function(data){
    var fresh, that;
    this.validate_data(data);

    fresh = false;
    if (data.timestamp >= this.timestamp){
      fresh = true;
      this.timestamp = data.timestamp;
      this.health = data.health;
      this.ip = data.ip;
    }

    that = this;
    _.each(data.services, function(service, service_name){
      var should_update_service = (!that.services[service_name]) ||
        (that.services[service_name].timestamp < service.timestamp);
      if (should_update_service){
        that.services[service_name] = service;
      }
    });
  },
  validate_data: function(data){
    var that;
    //TODO: use swiz for this
    if (!data.timestamp){
      throw new Error('You must specify a timestamp');
    }
    if (!data.name){
      throw new Error('You must specify a name');
    }
    that = this;
    data.timestamp = this._validate_time(data.timestamp);
    data.health = this._validate_health(data.health);
    _.each(data.services, function(service, service_name){
      service.timestamp = data.timestamp;
      service.health = that._validate_health(service.health);
    });
  },
  expire_data: function(old){
  },
  _validate_time: function(time_like){
    // have Date parse the time like thing and convert to a Number
    return (new Date(time_like)).getTime();
  },
  _validate_health: function(health){
    if (VALID_HEALTH.indexOf(health) != -1){
      return health;
    }
    throw new Error('Health status: ' + health + ' is not valid');
  }
});

exports.api_cache = exports.make_class({
  init: function(){
    //this.interval_id = setInterval(_.bind(this._purge_old_data, this), this._purge_interval);
  },
  handle_push: function(project, host_data){
    if (!this._projects[project]){
      this._projects[project] = {};
    }
    if (!this._projects[project][host_data.name]){
      this._projects[project][host_data.name] = new api_host_properties(host_data);
    } else{
     this._projects[project][host_data.name].handle_new_data(host_data);
    }
  },
  _purge_old_data: function(){
    var old = this.get_expired_time();
    _.each(this._projects, function(project){
      _.each(project, function(service){
        service.expire_data(old);
      });
    });
  },
  get_expired_time: function(){
    return Date.now() - this._stats_window;
  },
  _projects: {},
  _purge_interval: 60 * 1000
});

/**
 * Takes a username and password and returns a basic auth token fully formed
 *
 */
exports.create_basic_auth = function(username, password){
  var auth_token = new Buffer(username + ':' + password).toString('base64');
  return "Basic " + auth_token;
};

/**
 * Takes middlware function pointer with arrity of 5 and returns a middleware
 *
 * @param {string} name the name of the middleware (should be unique)
 * @param {fn} the middleware proper which should accept (req, res, next, payload, api_config- set payload.data/errors to cache stuff, api_config = req.devops[name]
 * @return {fn} middleware function
 */
exports.create_middleware = function(name, middleware){
  return function(req, res, next){
    // Do they have the api defined in the devops ball?
    if (!req.devops.related_apis || !req.devops.related_apis[name]) {
      req.devops[name] = null;
      next();
      return;
    }
      var payload = {error: null, data: null};
      req.devops[name] = payload;
      try{
        middleware(req, res, next, payload, req.devops.related_apis[name]);
      }catch (e){
        payload.error = e;
        // TODO: this may not be callable if the error was with express
        next();
      }
  };
};

/**
 * Makes a fake response object which the injector middleware needs (as for unit tests).  Call with new!
 *
 * @return {obj}
 */
 var mock_res = function(){};
 mock_res.prototype.locals = function(obj){
  if (!this._locals){
    this._locals = {};
  }
  if (!obj){
    return this._locals;
  }
  for (var key in obj){
    var val = obj[key];
    if (val===undefined){
      continue;
    }
    this._locals[key] = val;
  }
};
exports.mock_res = mock_res;
/**
 * Takes a relative or absolute devops filename and returns the parsed content
 *
 * @param {string} devops_filename the filename of the devopsjson file relative to the fixtures directory
 * @return {Object} parsed content of JSON file
 */
exports.load_devops = function(devops_path) {
  var devops;
  devops = fs.readFileSync(devops_path);
  devops = JSON.parse(devops);
  return devops;
};

/** A convenience function for making requests without having to build up response body data.
 * Also useful for mocking the making of requests in tests
 * @param {Object} options an options dict such as http.request would use
 * @param {fn} on_success callback that takes the complete response body data as a parameter
 * @param {fn} on_error callback that takes an Exception as a parameter
 */
exports.request_maker = function(options, call_back) {
  var req = {'443': https, '80': http}[options.port].get(options, function(res) {
    var data = '';
    res.setEncoding('utf8');
    res.on('data', function(d) {
      data += d;
    });
    res.on('end', function() {
      //TODO:  this is pretty strange, change me.
      try{
        call_back(null, data);
      }catch(e){
        call_back(e, data);
      }
    });
  }).on('error', function(e) {
    call_back(e, null);
  });
};

/**
 *@param project {string} Project name (should match devops.json file name)
 *@param devops {Object} devops.json object
 */
exports.create_navbar = function(project, devops) {
  var navbar;
  var related_apis = devops.related_apis;
  navbar = {};
  navbar[exports.capitalize(project)] = '/p/' + project;

  if (related_apis.version_one) {
    navbar.Defects = urls.DEFECTS.replace(':project', project);
  }
  if (related_apis.github) {
    navbar.DevHealth = urls.DEVHEALTH.replace(':project', project);
  }
  navbar["Service Health"] = urls.SERVICE_HEALTH.replace(':project', project);

  return navbar;
};

/**
 * @param string
 * @returns new string with first letter capitalized
 */
exports.capitalize = function(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

exports.validate_devops = function(devops){
  var jsv_env = JSV.createEnvironment('json-schema-draft-03');
  var report = jsv_env.validate(devops, schema);

  if (report.errors.length > 0) {
    console.log("ERRORS: ", report.errors);
  }
  return report;
};
<|endoftext|>


<commit_before>const base = require('skatejs-build/karma.conf');
module.exports = function (config) {
  base(config);

  // Remove all explicit IE definitions.
  config.browsers = config.browsers.filter(name => !/^internet_explorer/.test(name));

  // Only test IE latest.
  config.browsers.push('internet_explorer_11');

  // Shims for testing.
  config.files = [
    'node_modules/es6-shim/es6-shim.js'
  ].concat(config.files);

  // Ensure mobile browsers have enough time to run.
  config.browserNoActivityTimeout = 60000;
};
<commit_msg>chore(test): Fix tests so that it only tries to run IE11 if running in Sauce Labs.<commit_after>const base = require('skatejs-build/karma.conf');
module.exports = function (config) {
  base(config);

  // Setup IE if testing in SauceLabs.
  if (config.sauceLabs) {
    // Remove all explicit IE definitions.
    config.browsers = config.browsers.filter(name => !/^internet_explorer/.test(name));

    // Only test IE latest.
    config.browsers.push('internet_explorer_11');
  }

  // Shims for testing.
  config.files = [
    'node_modules/es6-shim/es6-shim.js',
  ].concat(config.files);

  // Ensure mobile browsers have enough time to run.
  config.browserNoActivityTimeout = 60000;
};
<|endoftext|>


<commit_before>const t = require('tape')
const transform = require('../')

const xml = `
    <root>
        <single>20.1</single>
        <number>10.2</number>
        <number>20.3</number>
        <boolean>TrUe</boolean>
        <items>
            <item>hEllo WorlD camaRo</item>
            <item>Hello World cAmaro</item>
            <item>hello wOrld caMaro</item>
            <item>hEllO wOrlD camaRo</item>
        </items>
    </root>
`

t.test('test function upper-case()', (t) => {
    const result = transform(xml, {
        upperCase: ['//items/item', 'upper-case(.)']
    })
    result.upperCase.forEach(u => {
        t.equal(u, 'HELLO WORLD CAMARO')
    })
    t.end()
})

t.test('test function lower-case()', (t) => {
    const result = transform(xml, {
        lowerCase: ['//items/item', 'lower-case(.)']
    })
    result.lowerCase.forEach(u => {
        t.equal(u, 'hello world camaro')
    })
    t.end()
})

t.test('test function title-case()', (t) => {
    const result = transform(xml, {
        titleCase: ['//items/item', 'title-case(.)']
    })
    result.titleCase.forEach(u => {
        t.equal(u, 'Hello World Camaro')
    })
    t.end()
})

t.test('test function camel-case()', (t) => {
    const result = transform(xml, {
        camelCase: ['//items/item', 'camel-case(.)']
    })
    result.camelCase.forEach(u => {
        t.equal(u, 'helloWorldCamaro')
    })
    t.end()
})

t.test('test function snake-case()', (t) => {
    const result = transform(xml, {
        snakeCase: ['//items/item', 'snake-case(.)']
    })
    result.snakeCase.forEach(u => {
        t.equal(u, 'hello_world_camaro')
    })
    t.end()
})

t.test('test function round()', (t) => {
    const result = transform(xml, { round: 'round(root/single)' })
    t.equal(result.round, 20)
    t.end()
})

t.test('test function floor()', (t) => {
    const result = transform(xml, { floor: 'floor(root/single)' })
    t.equal(result.floor, 20)
    t.end()
})

t.test('test function ceiling()', (t) => {
    const result = transform(xml, { ceiling: 'ceiling(root/single)' })
    t.equal(result.ceiling, 21)
    t.end()
})

t.test('test function sum()', (t) => {
    const result = transform(xml, { sum: 'sum(root/number)' })
    t.equal(result.sum, 30.5)
    t.end()
})

t.test('test function count()', (t) => {
    const result = transform(xml, { count: 'count(root/number)' })
    t.equal(result.count, 2)
    t.end()
})

t.test('test function boolean()', (t) => {
    const result = transform(xml, {
        boolean: 'boolean(root/boolean = "TrUe")',
        boolean_false: 'boolean(root/boolean = "true")'
    })
    t.equal(result.boolean, true, 'boolean should be true')
    t.equal(result.boolean_false, false, 'boolean_false should be false')
    t.end()
})
<commit_msg>test: add nested xpath function call<commit_after>const t = require('tape')
const transform = require('../')

const xml = `
    <root>
        <single>20.1</single>
        <number>10.2</number>
        <number>20.3</number>
        <boolean>TrUe</boolean>
        <items>
            <item>hEllo WorlD camaRo</item>
            <item>Hello World cAmaro</item>
            <item>hello wOrld caMaro</item>
            <item>hEllO wOrlD camaRo</item>
        </items>
    </root>
`

t.test('test function upper-case()', (t) => {
    const result = transform(xml, {
        upperCase: ['//items/item', 'upper-case(.)']
    })
    result.upperCase.forEach(u => {
        t.equal(u, 'HELLO WORLD CAMARO')
    })
    t.end()
})

t.test('test function lower-case()', (t) => {
    const result = transform(xml, {
        lowerCase: ['//items/item', 'lower-case(.)']
    })
    result.lowerCase.forEach(u => {
        t.equal(u, 'hello world camaro')
    })
    t.end()
})

t.test('test function title-case()', (t) => {
    const result = transform(xml, {
        titleCase: ['//items/item', 'title-case(.)']
    })
    result.titleCase.forEach(u => {
        t.equal(u, 'Hello World Camaro')
    })
    t.end()
})

t.test('test function camel-case()', (t) => {
    const result = transform(xml, {
        camelCase: ['//items/item', 'camel-case(.)']
    })
    result.camelCase.forEach(u => {
        t.equal(u, 'helloWorldCamaro')
    })
    t.end()
})

t.test('test function snake-case()', (t) => {
    const result = transform(xml, {
        snakeCase: ['//items/item', 'snake-case(.)']
    })
    result.snakeCase.forEach(u => {
        t.equal(u, 'hello_world_camaro')
    })
    t.end()
})

t.test('test nested function calls', (t) => {
    const result = transform(xml, {
        snakeCase: ['//items/item', 'snake-case(lower-case(.))']
    })
    result.snakeCase.forEach(u => {
        t.equal(u, 'hello_world_camaro')
    })
    t.end()
})

t.test('test function round()', (t) => {
    const result = transform(xml, { round: 'round(root/single)' })
    t.equal(result.round, 20)
    t.end()
})

t.test('test function floor()', (t) => {
    const result = transform(xml, { floor: 'floor(root/single)' })
    t.equal(result.floor, 20)
    t.end()
})

t.test('test function ceiling()', (t) => {
    const result = transform(xml, { ceiling: 'ceiling(root/single)' })
    t.equal(result.ceiling, 21)
    t.end()
})

t.test('test function sum()', (t) => {
    const result = transform(xml, { sum: 'sum(root/number)' })
    t.equal(result.sum, 30.5)
    t.end()
})

t.test('test function count()', (t) => {
    const result = transform(xml, { count: 'count(root/number)' })
    t.equal(result.count, 2)
    t.end()
})

t.test('test function boolean()', (t) => {
    const result = transform(xml, {
        boolean: 'boolean(root/boolean = "TrUe")',
        boolean_false: 'boolean(root/boolean = "true")'
    })
    t.equal(result.boolean, true, 'boolean should be true')
    t.equal(result.boolean_false, false, 'boolean_false should be false')
    t.end()
})
<|endoftext|>


<commit_before>import InputWrapperComponent from 'oss-components/components/input-group';
export default InputWrapperComponent;
<commit_msg>fix import path<commit_after>import InputWrapperComponent from 'oss-components/components/input-wrapper';
export default InputWrapperComponent;
<|endoftext|>


<commit_before>var expect, spearson;

expect = require("expect.js");
spearson = require("../lib/spearson.js");

describe("Spearson", function () {

    describe("round", function () {
        it("the rounded value of 0.4281 is 0", function () {
            var res;
            res = spearson.round(0.4281);
            expect(res).to.equal(0);
        });
        it("the rounded value of 0.4281 with two decimal points is 0.43", function () {
            var res;
            res = spearson.round(0.4281, 2);
            expect(res).to.equal(0.43);
        });
    });

    describe("sum", function () {
        it("the sum of [1,2,3,4,5] is 15", function () {
         // Compare to MATLAB: sum([1 2 3 4 5])
         // Compare to R: sum(c(1,2,3,4,5))
            var res;
            res = spearson.sum([1, 2, 3, 4, 5]);
            expect(res).to.equal(15);
        });
    });

    describe("mean", function () {
        it("the mean of [1,2,3,4,5] is 3", function () {
         // Compare to MATLAB: mean([1 2 3 4 5])
         // Compare to R: mean(c(1,2,3,4,5))
            var res;
            res = spearson.mean([1, 2, 3, 4, 5]);
            expect(res).to.equal(3);
        });
    });

    describe("deviation", function () {
        it("the deviation of [1,2,3,4,5] is [-2,-1,0,1,2]", function () {
         // Compare to MATLAB: [1 2 3 4 5] - mean([1 2 3 4 5])
         // Compare to R: c(1,2,3,4,5) - mean(c(1,2,3,4,5))
            var res;
            res = spearson.deviation([1, 2, 3, 4, 5]);
            expect(res).to.eql([-2, -1, 0, 1, 2]);
        });
    });

    describe("variance", function () {
        it("the unbiased sample variance of [1,2,3,4,5] is 2.5", function () {
         // Compare to MATLAB: sum(([1 2 3 4 5] - mean([1 2 3 4 5])) .^ 2) / (5 - 1)
         // Compare to R: sum((c(1,2,3,4,5) - mean(c(1,2,3,4,5))) ^ 2) / (5 - 1)
            var res;
            res = spearson.variance([1, 2, 3, 4, 5]);
            expect(res).to.equal(2.5);
        });
        it("the biased variance of [1,2,3,4,5] is 2", function () {
         // Compare to MATLAB: sum(([1 2 3 4 5] - mean([1 2 3 4 5])) .^ 2) / 5
         // Compare to R: sum((c(1,2,3,4,5) - mean(c(1,2,3,4,5))) ^ 2) / 5
            var res;
            res = spearson.variance([1, 2, 3, 4, 5], true);
            expect(res).to.equal(2);
        });
    });

    describe("standardDeviation", function () {
        it("the standard deviation of [1,2,3,4,5] is 1.5811", function () {
         // Compare to MATLAB: std([1 2 3 4 5])
         // Compare to R: sd(c(1,2,3,4,5))
            var res;
            res = spearson.standardDeviation([1, 2, 3, 4, 5]);
            res = spearson.round(res, 4);
            expect(res).to.equal(1.5811);
        });
    });

    describe("standardize", function () {
        it("the z score of [1,3,2] is [-1,1,0]", function () {
         // Compare to MATLAB: zscore([1,3,2])
            var res;
            res = spearson.standardize([1, 3, 2]);
            expect(res).to.eql([-1,1,0]);
        });
    });

    describe("rank", function () {
        it("the rank of [54,17,8,109,78] is [3,2,1,5,4]", function () {
         // Compare to MATLAB: tiedrank([54 17 8 109 78])
            var res;
            res = spearson.rank([54, 17, 8, 109, 78]);
            expect(res).to.eql([3, 2, 1, 5, 4]);
        });
    });

    describe("correlation", function () {
        describe("pearson", function () {
            it("the Pearson correlation coefficient of [1,7,2,3,4] and [9,3,5,2,1] is -0.6181", function () {
             // Compare to MATLAB: corr([1;7;2;3;4], [9;3;5;2;1])
             // Compare to R: cor(c(1,7,2,3,4), c(9,3,5,2,1))
                var res;
                res = spearson.correlation.pearson([1, 7, 2, 3, 4], [9, 3, 5, 2, 1]);
                res = spearson.round(res, 4);
                expect(res).to.equal(-0.6181);
            });
        });
        describe("spearman", function () {
            it("the Spearman correlation coefficient of [1,7,2,3,4] and [9,3,5,2,1] is -0.7", function () {
             // Compare to MATLAB: corr([1;7;2;3;4], [9;3;5;2;1], 'type', 'Spearman')
             // Compare to R: cor(x=c(1,7,2,3,4), y=c(9,3,5,2,1), method="spearman")
                var res;
                res = spearson.correlation.spearman([1, 7, 2, 3, 4], [9, 3, 5, 2, 1]);
                expect(res).to.equal(-0.7);
            });
            it("the Spearman correlation coefficient of [1,7,2,3,1] and [9,3,2,2,1] is 0.1579", function () {
             // Compare to MATLAB: corr([1;7;2;3;1], [9;3;2;2;1], 'type', 'Spearman')
             // Compare to R: cor(x=c(1,7,2,3,1), y=c(9,3,2,2,1), method="spearman")
                var res;
                res = spearson.correlation.spearman([1, 7, 2, 3, 1], [9, 3, 2, 2, 1]);
                res = spearson.round(res, 4);
                expect(res).to.equal(0.1579);
            });
        });
    });

    describe("hierarchicalClustering", function () {
        describe("linkage.single", function () {
            it("the distance at which all observations are merged into a single cluster is 126.7517", function () {
             // Compare to MATLAB: linkage(pdist([81 91 28 96 96; 91 63 55 16 49; 13 10 96 97 80]))
                var clust, res;
                clust = spearson.hierarchicalClustering([
                    [81, 91, 28, 96, 96],
                    [91, 63, 55, 16, 49],
                    [13, 10, 96, 97, 80]
                ], spearson.linkage.single, spearson.distance.euclidean)
                res = spearson.round(clust[1].distance, 4)
                expect(res).to.equal(126.7517);
            });
        });
        describe("linkage.complete", function () {
            it("the distance at which all observations are merged into a single cluster is 134.5214", function () {
             // Compare to MATLAB: linkage(pdist([81 91 28 96 96; 91 63 55 16 49; 13 10 96 97 80]), 'complete')
                var clust, res;
                clust = spearson.hierarchicalClustering([
                    [81, 91, 28, 96, 96],
                    [91, 63, 55, 16, 49],
                    [13, 10, 96, 97, 80]
                ], spearson.linkage.complete, spearson.distance.euclidean)
                res = spearson.round(clust[1].distance, 4)
                expect(res).to.equal(134.5214);
            });
        });
        describe("linkage.upgma", function () {
            it("the distance at which all observations are merged into a single cluster is 130.6365", function () {
             // Compare to MATLAB: linkage(pdist([81 91 28 96 96; 91 63 55 16 49; 13 10 96 97 80]), 'average')
                var clust, res;
                clust = spearson.hierarchicalClustering([
                    [81, 91, 28, 96, 96],
                    [91, 63, 55, 16, 49],
                    [13, 10, 96, 97, 80]
                ], spearson.linkage.upgma, spearson.distance.euclidean)
                res = spearson.round(clust[1].distance, 4)
                expect(res).to.equal(130.6365);
            });
        });
    });

});
<commit_msg>Improve test documentation.<commit_after>var expect, spearson;

expect = require("expect.js");
spearson = require("../lib/spearson.js");

describe("Spearson", function () {

    describe("round", function () {
        it("the rounded value of 0.4281 is 0", function () {
            var res;
            res = spearson.round(0.4281);
            expect(res).to.equal(0);
        });
        it("the rounded value of 0.4281 with two decimal points is 0.43", function () {
            var res;
            res = spearson.round(0.4281, 2);
            expect(res).to.equal(0.43);
        });
    });

    describe("sum", function () {
        it("the sum of [1,2,3,4,5] is 15", function () {
         // Compare to MATLAB: sum([1 2 3 4 5])
         // Compare to R: sum(c(1,2,3,4,5))
            var res;
            res = spearson.sum([1, 2, 3, 4, 5]);
            expect(res).to.equal(15);
        });
    });

    describe("mean", function () {
        it("the mean of [1,2,3,4,5] is 3", function () {
         // Compare to MATLAB: mean([1 2 3 4 5])
         // Compare to R: mean(c(1,2,3,4,5))
            var res;
            res = spearson.mean([1, 2, 3, 4, 5]);
            expect(res).to.equal(3);
        });
    });

    describe("deviation", function () {
        it("the deviation of [1,2,3,4,5] is [-2,-1,0,1,2]", function () {
         // Compare to MATLAB: [1 2 3 4 5] - mean([1 2 3 4 5])
         // Compare to R: c(1,2,3,4,5) - mean(c(1,2,3,4,5))
            var res;
            res = spearson.deviation([1, 2, 3, 4, 5]);
            expect(res).to.eql([-2, -1, 0, 1, 2]);
        });
    });

    describe("variance", function () {
        it("the unbiased sample variance of [1,2,3,4,5] is 2.5", function () {
         // Compare to MATLAB: sum(([1 2 3 4 5] - mean([1 2 3 4 5])) .^ 2) / (5 - 1)
         // Compare to R: var(c(1,2,3,4,5))
            var res;
            res = spearson.variance([1, 2, 3, 4, 5]);
            expect(res).to.equal(2.5);
        });
        it("the biased sample / population variance of [1,2,3,4,5] is 2", function () {
         // Compare to MATLAB: sum(([1 2 3 4 5] - mean([1 2 3 4 5])) .^ 2) / 5
            var res;
            res = spearson.variance([1, 2, 3, 4, 5], true);
            expect(res).to.equal(2);
        });
    });

    describe("standardDeviation", function () {
        it("the sample standard deviation of [1,2,3,4,5] is 1.5811", function () {
         // Compare to MATLAB: std([1 2 3 4 5])
         // Compare to R: sd(c(1,2,3,4,5))
            var res;
            res = spearson.standardDeviation([1, 2, 3, 4, 5]);
            res = spearson.round(res, 4);
            expect(res).to.equal(1.5811);
        });
    });

    describe("standardize", function () {
        it("the z score of [1,3,2] is [-1,1,0]", function () {
         // Compare to MATLAB: zscore([1,3,2])
            var res;
            res = spearson.standardize([1, 3, 2]);
            expect(res).to.eql([-1,1,0]);
        });
    });

    describe("rank", function () {
        it("the rank of [54,17,8,109,78] is [3,2,1,5,4]", function () {
         // Compare to MATLAB: tiedrank([54 17 8 109 78])
            var res;
            res = spearson.rank([54, 17, 8, 109, 78]);
            expect(res).to.eql([3, 2, 1, 5, 4]);
        });
    });

    describe("correlation", function () {
        describe("pearson", function () {
            it("the Pearson correlation coefficient of [1,7,2,3,4] and [9,3,5,2,1] is -0.6181", function () {
             // Compare to MATLAB: corr([1;7;2;3;4], [9;3;5;2;1])
             // Compare to R: cor(c(1,7,2,3,4), c(9,3,5,2,1))
                var res;
                res = spearson.correlation.pearson([1, 7, 2, 3, 4], [9, 3, 5, 2, 1]);
                res = spearson.round(res, 4);
                expect(res).to.equal(-0.6181);
            });
        });
        describe("spearman", function () {
            it("the Spearman correlation coefficient of [1,7,2,3,4] and [9,3,5,2,1] is -0.7", function () {
             // Compare to MATLAB: corr([1;7;2;3;4], [9;3;5;2;1], 'type', 'Spearman')
             // Compare to R: cor(x=c(1,7,2,3,4), y=c(9,3,5,2,1), method="spearman")
                var res;
                res = spearson.correlation.spearman([1, 7, 2, 3, 4], [9, 3, 5, 2, 1]);
                expect(res).to.equal(-0.7);
            });
            it("the Spearman correlation coefficient of [1,7,2,3,1] and [9,3,2,2,1] is 0.1579", function () {
             // Compare to MATLAB: corr([1;7;2;3;1], [9;3;2;2;1], 'type', 'Spearman')
             // Compare to R: cor(x=c(1,7,2,3,1), y=c(9,3,2,2,1), method="spearman")
                var res;
                res = spearson.correlation.spearman([1, 7, 2, 3, 1], [9, 3, 2, 2, 1]);
                res = spearson.round(res, 4);
                expect(res).to.equal(0.1579);
            });
        });
    });

    describe("hierarchicalClustering", function () {
        describe("linkage.single", function () {
            it("the distance at which all observations are merged into a single cluster is 126.7517", function () {
             // Compare to MATLAB: linkage(pdist([81 91 28 96 96; 91 63 55 16 49; 13 10 96 97 80]))
                var clust, res;
                clust = spearson.hierarchicalClustering([
                    [81, 91, 28, 96, 96],
                    [91, 63, 55, 16, 49],
                    [13, 10, 96, 97, 80]
                ], spearson.linkage.single, spearson.distance.euclidean)
                res = spearson.round(clust[1].distance, 4)
                expect(res).to.equal(126.7517);
            });
        });
        describe("linkage.complete", function () {
            it("the distance at which all observations are merged into a single cluster is 134.5214", function () {
             // Compare to MATLAB: linkage(pdist([81 91 28 96 96; 91 63 55 16 49; 13 10 96 97 80]), 'complete')
                var clust, res;
                clust = spearson.hierarchicalClustering([
                    [81, 91, 28, 96, 96],
                    [91, 63, 55, 16, 49],
                    [13, 10, 96, 97, 80]
                ], spearson.linkage.complete, spearson.distance.euclidean)
                res = spearson.round(clust[1].distance, 4)
                expect(res).to.equal(134.5214);
            });
        });
        describe("linkage.upgma", function () {
            it("the distance at which all observations are merged into a single cluster is 130.6365", function () {
             // Compare to MATLAB: linkage(pdist([81 91 28 96 96; 91 63 55 16 49; 13 10 96 97 80]), 'average')
                var clust, res;
                clust = spearson.hierarchicalClustering([
                    [81, 91, 28, 96, 96],
                    [91, 63, 55, 16, 49],
                    [13, 10, 96, 97, 80]
                ], spearson.linkage.upgma, spearson.distance.euclidean)
                res = spearson.round(clust[1].distance, 4)
                expect(res).to.equal(130.6365);
            });
        });
    });

});
<|endoftext|>


<commit_before>function removeDashes(str) {
    return str.replace(/-([a-z])/g, function (match, lower) {
        return lower.toUpperCase();
    });
}

module.exports = function invokeHandlers(config, handlers, path) {
    function error(message, cause) {
        if (cause) {
            if (cause.__propertyHandlers) {
                throw cause;
            }

            message += '. Cause: ' + (cause.stack || cause);
        }

        if (path) {
            message = 'Error while handling properties for ' + path + ': ' + message;
        }

        var e = new Error(message);
        e.__propertyHandlers = true;
        throw e;
    }

    if (!config) {
        error('"config" argument is required');
    }

    if (typeof config !== 'object') {
        error('object expected');
    }

    for (var k in config) {
        if (config.hasOwnProperty(k)) {
            var value = config[k];
            k = removeDashes(k);
            var handler = handlers[k];

            if (!handler) {
                error('Invalid option of "' + k + '". Allowed: ' + Object.keys(handlers).join(', '));
            }

            try {
                handler(value);
            }
            catch(e) {
                error('Error while applying option of "' + k + '"', e);
            }
        }
    }

    if (handlers._end) {
        try {
            handlers._end();
        }
        catch(e) {
            error('Error after applying properties', e);
        }
    }
};<commit_msg>Added support for wildcard properties<commit_after>function removeDashes(str) {
    return str.replace(/-([a-z])/g, function (match, lower) {
        return lower.toUpperCase();
    });
}

module.exports = function invokeHandlers(config, handlers, options) {
    var path;

    if (options != null) {
        if (typeof options === 'string') {
            path = options;
        } else {
            path = options.path;
        }
    }

    function error(message, cause) {
        if (cause) {
            if (cause.__propertyHandlers) {
                throw cause;
            }

            message += '. Cause: ' + (cause.stack || cause);
        }

        if (path) {
            message = 'Error while handling properties for ' + path + ': ' + message;
        }

        var e = new Error(message);
        e.__propertyHandlers = true;
        throw e;
    }

    if (!config) {
        error('"config" argument is required');
    }

    if (typeof config !== 'object') {
        error('object expected');
    }

    for (var k in config) {
        if (config.hasOwnProperty(k)) {
            var value = config[k];
            var keyNoDashes = removeDashes(k);
            var handler = handlers[keyNoDashes];
            var isDefaultHandler = false;

            if (!handler) {
                handler = handlers['*'];
                isDefaultHandler = true;
            }

            if (!handler) {
                error('Invalid option of "' + keyNoDashes + '". Allowed: ' + Object.keys(handlers).join(', '));
            }

            try {
                if (isDefaultHandler) {
                    if (handler.call(handlers, k, value) === false) {
                        error('Invalid option: ' + k);
                    }
                } else {
                    handler.call(handlers, value);
                }
            } catch(e) {
                error('Error while applying option of "' + k + '"', e);
            }
        }
    }

    if (handlers._end) {
        try {
            handlers._end();
        }
        catch(e) {
            error('Error after applying properties', e);
        }
    }
};<|endoftext|>