<commit_before>/**
 * Tiny library for interacting with Circonus' API v2
 *
 * Exported methods
 *  setup:  inital setup function to give the API your auth token an app name
 *  get, post, put, delete: docs for each method below, are proxies for the
 *                          various methods for REST calls
 *
 * Notes:
 *  callback functions take 3 args (code, error, body)
 *    code:   HTTP Response code, if null a non HTTP error occurred
 *    error:  Error message from API, null on 200 responses
 *    body:   Response body, i.e. the thing you probably want
 */

var https = require('http'),
    qs = require('querystring'),
    apihost = 'api.circonus.com',
    apiport = 443,
    apipath = '/v2/',
    authtoken = null,
    appname = null;

exports.setup = function (token, app) {
  authtoken = token;
  appname = app;
};

/**
 * GET:
 *
 *  endpoint: (/check_bundle, /check/1, etc.)
 *  data:     object which will be converted to a query string
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
exports.get = function (endpoint, data, callback) {
  var options = get_request_options('GET', endpoint, data);
  do_request(options, callback);
};

/**
 * POST:
 *
 *  endpoint: specify an object collection (/check_bundle, /graph, etc.)
 *  data:     object which will be stringified to JSON and written to the server
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
exports.post = function (endpoint, data, callback) {
  var options = get_request_options('POST', endpoint, data);
  do_request(options, callback);
};

/**
 * PUT:
 *
 *  endpoint: specify an exact object (/check_bundle/1, /template/2, etc.)
 *  data:     object which will be stringified to JSON and written to the server
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
exports.put = function (endpoint, data, callback) {
  var options = get_request_options('PUT', endpoint, data);
  do_request(options, callback);
};

/**
 * DELETE:
 *
 *  endpoint: specify an exact object (/check_bundle/1, /rule_set/1_foo, etc.)
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
exports.delete = function (endpoint, callback) {
  var options = get_request_options('DELETE', endpoint);
  do_request(options, callback);
};

/**
 * This is called from the various exported functions to actually perform
 * the request.  Will retry up to 5 times in the event we get a connection
 * reset error.
 */
var do_request = function (options, callback) {
  var req = https.request(options, function(res) {
    var body = '';

    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      var err_msg = null;

      // If this isn't a 200 level, extract the message from the body
      if ( res.statusCode < 200 || res.statusCode > 299 ) {
        try {
          err_msg = JSON.parse(body).message;
        }
        catch (err) {
          err_msg = "An error occurred, but the body could not be parsed: " + err;
        }
      }

      callback(res.statusCode, err_msg, (body) ? JSON.parse(body) : null);
    });
  });

  req.on('error', function(e) {
    if ( e.code === 'ECONNRESET' && options.circapi.retry < 5 ) {
      options.circapi.retry += 1;
      // sleep 1 second and try again, probably hit the rate limit
      setTimeout(function() {
        this.do_request(options, callback);
      }, 1000 * options.circapi.retry);
    }
    else {
      callback(null, e.message, null);
    }
  });

  if ( options.method.toUpperCase() === 'POST' || options.method.toUpperCase() === 'PUT' ) {
    req.write(JSON.stringify(options.circapi.data));
  }
  req.end();
};

/**
 * Hands back an options object suitable to use with the HTTPS class
 */
var get_request_options = function (method, endpoint, data) {
  var options = {
        host: apihost,
        port: apiport,
        path: apipath,
        method: method.toUpperCase(),
        agent: false,
        headers: {
          "X-Circonus-Auth-Token": authtoken,
          "X-Circonus-App-Name": appname,
          "Accept": "application/json"
        },
        circapi: {
          retry: 0,
          data: null
        }
      };

  options.circapi.data = data;
  if ( options.method === 'GET' && data !== null && Object.keys(data).length !== 0 ) {
    options.path += '?' + qs.stringify(data);
  }

  if ( endpoint.match(/^\//) ) {
    endpoint = endpoint.substring(1);
  }
  options.path += endpoint;

  return options;
};
<commit_msg>pull in latest circonusapi2<commit_after>/**
 * Tiny library for interacting with Circonus' API v2
 *
 * Exported methods
 *  setup:  inital setup function to give the API your auth token an app name
 *  get, post, put, delete: docs for each method below, are proxies for the
 *                          various methods for REST calls
 *
 * Notes:
 *  callback functions take 3 args (code, error, body)
 *    code:   HTTP Response code, if null a non HTTP error occurred
 *    error:  Error message from API, null on 200 responses
 *    body:   Response body, i.e. the thing you probably want
 */

var qs = require('querystring'),
    singleton,
    api;

api = function(token, app, options) {
  options = options || {};
  this.authtoken = token;
  this.appname = app;
  var protocol = options.protocol;
  if(typeof protocol === 'string'){
    protocol = (protocol === 'http') ? require('http') : undefined;
  }
  this.protocol = protocol || require('https');
  this.apihost = options.host || 'api.circonus.com';
  this.apiport = options.port || 443;
  this.apipath = options.path || '/v2/';
};

/**
 * GET:
 *
 *  endpoint: (/check_bundle, /check/1, etc.)
 *  data:     object which will be converted to a query string
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
api.prototype.get = function (endpoint, data, callback) {
  var options = this.get_request_options('GET', endpoint, data);
  this.do_request(options, callback);
};

/**
 * POST:
 *
 *  endpoint: specify an object collection (/check_bundle, /graph, etc.)
 *  data:     object which will be stringified to JSON and written to the server
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
api.prototype.post = function (endpoint, data, callback) {
  var options = this.get_request_options('POST', endpoint, data);
  this.do_request(options, callback);
};

/**
 * PUT:
 *
 *  endpoint: specify an exact object (/check_bundle/1, /template/2, etc.)
 *  data:     object which will be stringified to JSON and written to the server
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
api.prototype.put = function (endpoint, data, callback) {
  var options = this.get_request_options('PUT', endpoint, data);
  this.do_request(options, callback);
};

/**
 * DELETE:
 *
 *  endpoint: specify an exact object (/check_bundle/1, /rule_set/1_foo, etc.)
 *  callback: what do we call when the response from the server is complete,
 *            arguments are callback(code, error, body)
 */
api.prototype.delete = function (endpoint, callback) {
  var options = this.get_request_options('DELETE', endpoint);
  this.do_request(options, callback);
};

/**
 * This is called from the various exported functions to actually perform
 * the request.  Will retry up to 5 times in the event we get a connection
 * reset error.
 */
api.prototype.do_request = function (options, callback) {
  var req = this.protocol.request(options, function(res) {
    var body = '';

    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      var err_msg = null;

      // If this isn't a 200 level, extract the message from the body
      if ( res.statusCode < 200 || res.statusCode > 299 ) {
        try {
          err_msg = JSON.parse(body).message;
        }
        catch (err) {
          err_msg = "An error occurred, but the body could not be parsed: " + err;
        }
      }
      var parsed = null;
      try { if ( body ) parsed = JSON.parse(body); } catch ( unused ) {}
      callback(res.statusCode, err_msg, parsed, body);
    });
  });

  req.on('error', function(e) {
    if ( e.code === 'ECONNRESET' && options.circapi.retry < 5 ) {
      options.circapi.retry += 1;
      // sleep 1 second and try again, probably hit the rate limit
      setTimeout(function() {
        this.do_request(options, callback);
      }, 1000 * options.circapi.retry);
    }
    else {
      callback(null, e.message, null);
    }
  });

  if ( options.method.toUpperCase() === 'POST' || options.method.toUpperCase() === 'PUT' ) {
    req.write(JSON.stringify(options.circapi.data));
  }
  req.end();
};

/**
 * Hands back an options object suitable to use with the HTTPS class
 */
api.prototype.get_request_options = function (method, endpoint, data) {
  var options = {
        host: this.apihost,
        port: this.apiport,
        path: this.apipath,
        method: method.toUpperCase(),
        agent: false,
        headers: {
          "X-Circonus-Auth-Token": this.authtoken,
          "X-Circonus-App-Name": this.appname,
          "Accept": "application/json"
        },
        circapi: {
          retry: 0,
          data: null
        }
      };

  options.circapi.data = data;
  if ( options.method === 'GET' && data !== null && Object.keys(data).length !== 0 ) {
    options.path += '?' + qs.stringify(data);
  }

  if ( endpoint.match(/^\//) ) {
    endpoint = endpoint.substring(1);
  }
  options.path += endpoint;

  return options;
};

exports.API = api;

/* support legacy API */
exports.setup = function (token, app, options) {
  singleton = new api(token, app, options);
};
exports.get = function (endpoint, data, callback) {
  singleton.get(endpoint, data, callback);
}
exports.post = function (endpoint, data, callback) {
  singleton.post(endpoint, data, callback);
};
exports.put = function (endpoint, data, callback) {
  singleton.put(endpoint, data, callback);
};
exports.delete = function (endpoint, callback) {
  singleton.delete(endpoint, callback);
};

<|endoftext|>


<commit_before>var program = require('commander'),
    demeteorizer = require('../lib/demeteorizer'),
    path = require('path');

program
  .version(require('../package.json').version)
  .option('-o, --output <path>', 'Output folder for converted application. Defaults to ./.demeteorized.')
  .option('-r, --release <version>', 'The Meteor version. Defaults to latest installed.')
  .option('-t, --tarball <path>', 'Output tarball path. If specified, creates a tar.gz of demeteorized application instead of directory.')
  .option('-a, --app_name <name>', 'Value to put in the package.json name field. Defaults to the current directory name.')
  .option('-p, --prerelease', 'Ignore Meteor prerelease warnings when running bundle.', false)
  .option('-d, --debug', 'Bundle in debug mode (don\'t minify, etc).', false)
  .parse(process.argv);

var output = program.output;
var release = program.release;
var tarball = program.tarball;
var appName = program.app_name;
var prerelease = program.prerelease;
var debug = program.debug;

var input = process.cwd();

if(!output) {
  output = path.join(process.cwd(), '.demeteorized');
}

console.log('Input: ' + input);
console.log('Output: ' + output);
if(release) {
  console.log('Release: ' + release);
}

demeteorizer.on('progress', function(msg) {
  console.log(msg);
});

var options = {
  input: input,
  output: output,
  release: release,
  tarball: tarball,
  appName: appName,
  prerelease: prerelease,
  debug: debug
};

demeteorizer.convert(
  options,
  function(err) {
    if(err) {
      console.log('ERROR: ' + err);
    }
    else {
      console.log('Demeteorization complete.');
    }
  }
);
<commit_msg>demeteorizer should exit with errror code if error occurs<commit_after>var program = require('commander'),
    demeteorizer = require('../lib/demeteorizer'),
    path = require('path');

program
  .version(require('../package.json').version)
  .option('-o, --output <path>', 'Output folder for converted application. Defaults to ./.demeteorized.')
  .option('-r, --release <version>', 'The Meteor version. Defaults to latest installed.')
  .option('-t, --tarball <path>', 'Output tarball path. If specified, creates a tar.gz of demeteorized application instead of directory.')
  .option('-a, --app_name <name>', 'Value to put in the package.json name field. Defaults to the current directory name.')
  .option('-p, --prerelease', 'Ignore Meteor prerelease warnings when running bundle.', false)
  .option('-d, --debug', 'Bundle in debug mode (don\'t minify, etc).', false)
  .parse(process.argv);

var output = program.output;
var release = program.release;
var tarball = program.tarball;
var appName = program.app_name;
var prerelease = program.prerelease;
var debug = program.debug;

var input = process.cwd();

if(!output) {
  output = path.join(process.cwd(), '.demeteorized');
}

console.log('Input: ' + input);
console.log('Output: ' + output);
if(release) {
  console.log('Release: ' + release);
}

demeteorizer.on('progress', function(msg) {
  console.log(msg);
});

var options = {
  input: input,
  output: output,
  release: release,
  tarball: tarball,
  appName: appName,
  prerelease: prerelease,
  debug: debug
};

demeteorizer.convert(
  options,
  function(err) {
    if(err) {
      console.log('ERROR: ' + err);
      process.exit(1);
    }
    else {
      console.log('Demeteorization complete.');
    }
  }
);
<|endoftext|>


<commit_before>/**
 * jQuery Masonry v2.1.08
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2012 David DeSandro
 */
(function(e,t,n){"use strict";var r=t.event,i;r.special.smartresize={setup:function(){t(this).bind("resize",r.special.smartresize.handler)},teardown:function(){t(this).unbind("resize",r.special.smartresize.handler)},handler:function(e,t){var n=this,s=arguments;e.type="smartresize",i&&clearTimeout(i),i=setTimeout(function(){r.dispatch.apply(n,s)},t==="execAsap"?0:100)}},t.fn.smartresize=function(e){return e?this.bind("smartresize",e):this.trigger("smartresize",["execAsap"])},t.Mason=function(e,n){this.element=t(n),this._create(e),this._init()},t.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1,containerStyle:{position:"relative"}},t.Mason.prototype={_filterFindBricks:function(e){var t=this.options.itemSelector;return t?e.filter(t).add(e.find(t)):e},_getBricks:function(e){var t=this._filterFindBricks(e).css({position:"absolute"}).addClass("masonry-brick");return t},_create:function(n){this.options=t.extend(!0,{},t.Mason.settings,n),this.styleQueue=[];var r=this.element[0].style;this.originalStyle={height:r.height||""};var i=this.options.containerStyle;for(var s in i)this.originalStyle[s]=r[s]||"";this.element.css(i),this.horizontalDirection=this.options.isRTL?"right":"left";var o=this.element.css("padding-"+this.horizontalDirection),u=this.element.css("padding-top");this.offset={x:o?parseInt(o,10):0,y:u?parseInt(u,10):0},this.isFluid=this.options.columnWidth&&typeof this.options.columnWidth=="function";var a=this;setTimeout(function(){a.element.addClass("masonry")},0),this.options.isResizable&&t(e).bind("smartresize.masonry",function(){a.resize()}),this.reloadItems()},_init:function(e){this._getColumns(),this._reLayout(e)},option:function(e,n){t.isPlainObject(e)&&(this.options=t.extend(!0,this.options,e))},layout:function(e,t){for(var n=0,r=e.length;n<r;n++)this._placeBrick(e[n]);var i={};i.height=Math.max.apply(Math,this.colYs);if(this.options.isFitWidth){var s=0;n=this.cols;while(--n){if(this.colYs[n]!==0)break;s++}i.width=(this.cols-s)*this.columnWidth-this.options.gutterWidth}this.styleQueue.push({$el:this.element,style:i});var o=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",u=this.options.animationOptions,a;for(n=0,r=this.styleQueue.length;n<r;n++)a=this.styleQueue[n],a.$el[o](a.style,u);this.styleQueue=[],t&&t.call(e),this.isLaidOut=!0},_getColumns:function(){var e=this.options.isFitWidth?this.element.parent():this.element,t=e.width();this.columnWidth=this.isFluid?this.options.columnWidth(t):this.options.columnWidth||this.$bricks.outerWidth(!0)||t,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((t+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(e){var n=t(e),r,i,s,o,u;r=Math.ceil(n.outerWidth(!0)/this.columnWidth),r=Math.min(r,this.cols);if(r===1)s=this.colYs;else{i=this.cols+1-r,s=[];for(u=0;u<i;u++)o=this.colYs.slice(u,u+r),s[u]=Math.max.apply(Math,o)}var a=Math.min.apply(Math,s),f=0;for(var l=0,c=s.length;l<c;l++)if(s[l]===a){f=l;break}var h={top:a+this.offset.y};h[this.horizontalDirection]=this.columnWidth*f+this.offset.x,this.styleQueue.push({$el:n,style:h});var p=a+n.outerHeight(!0),d=this.cols+1-c;for(l=0;l<d;l++)this.colYs[f+l]=p},resize:function(){var e=this.cols;this._getColumns(),(this.isFluid||this.cols!==e)&&this._reLayout()},_reLayout:function(e){var t=this.cols;this.colYs=[];while(t--)this.colYs.push(0);this.layout(this.$bricks,e)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(e){this.reloadItems(),this._init(e)},appended:function(e,t,n){if(t){this._filterFindBricks(e).css({top:this.element.height()});var r=this;setTimeout(function(){r._appended(e,n)},1)}else this._appended(e,n)},_appended:function(e,t){var n=this._getBricks(e);this.$bricks=this.$bricks.add(n),this.layout(n,t)},remove:function(e){this.$bricks=this.$bricks.not(e),e.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position="",this.style.top="",this.style.left=""});var n=this.element[0].style;for(var r in this.originalStyle)n[r]=this.originalStyle[r];this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),t(e).unbind(".masonry")}},t.fn.imagesLoaded=function(e){function u(){e.call(n,r)}function a(e){var n=e.target;n.src!==s&&t.inArray(n,o)===-1&&(o.push(n),--i<=0&&(setTimeout(u),r.unbind(".imagesLoaded",a)))}var n=this,r=n.find("img").add(n.filter("img")),i=r.length,s="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",o=[];return i||u(),r.bind("load.imagesLoaded error.imagesLoaded",a).each(function(){var e=this.src;this.src=s,this.src=e}),n};var s=function(t){e.console&&e.console.error(t)};t.fn.masonry=function(e){if(typeof e=="string"){var n=Array.prototype.slice.call(arguments,1);this.each(function(){var r=t.data(this,"masonry");if(!r){s("cannot call methods on masonry prior to initialization; attempted to call method '"+e+"'");return}if(!t.isFunction(r[e])||e.charAt(0)==="_"){s("no such method '"+e+"' for masonry instance");return}r[e].apply(r,n)})}else this.each(function(){var n=t.data(this,"masonry");n?(n.option(e||{}),n._init()):t.data(this,"masonry",new t.Mason(e,this))});return this}})(window,jQuery);<commit_msg>jQuery Masonry version up to v2.1.08<commit_after>/**
 * jQuery Masonry v2.1.08
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2012 David DeSandro
 */
(function(e,t,n){"use strict";var r=t.event,i;r.special.smartresize={setup:function(){t(this).bind("resize",r.special.smartresize.handler)},teardown:function(){t(this).unbind("resize",r.special.smartresize.handler)},handler:function(e,t){var n=this,s=arguments;e.type="smartresize",i&&clearTimeout(i),i=setTimeout(function(){r.dispatch.apply(n,s)},t==="execAsap"?0:100)}},t.fn.smartresize=function(e){return e?this.bind("smartresize",e):this.trigger("smartresize",["execAsap"])},t.Mason=function(e,n){this.element=t(n),this._create(e),this._init()},t.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1,containerStyle:{position:"relative"}},t.Mason.prototype={_filterFindBricks:function(e){var t=this.options.itemSelector;return t?e.filter(t).add(e.find(t)):e},_getBricks:function(e){var t=this._filterFindBricks(e).css({position:"absolute"}).addClass("masonry-brick");return t},_create:function(n){this.options=t.extend(!0,{},t.Mason.settings,n),this.styleQueue=[];var r=this.element[0].style;this.originalStyle={height:r.height||""};var i=this.options.containerStyle;for(var s in i)this.originalStyle[s]=r[s]||"";this.element.css(i),this.horizontalDirection=this.options.isRTL?"right":"left";var o=this.element.css("padding-"+this.horizontalDirection),u=this.element.css("padding-top");this.offset={x:o?parseInt(o,10):0,y:u?parseInt(u,10):0},this.isFluid=this.options.columnWidth&&typeof this.options.columnWidth=="function";var a=this;setTimeout(function(){a.element.addClass("masonry")},0),this.options.isResizable&&t(e).bind("smartresize.masonry",function(){a.resize()}),this.reloadItems()},_init:function(e){this._getColumns(),this._reLayout(e)},option:function(e,n){t.isPlainObject(e)&&(this.options=t.extend(!0,this.options,e))},layout:function(e,t){for(var n=0,r=e.length;n<r;n++)this._placeBrick(e[n]);var i={};i.height=Math.max.apply(Math,this.colYs);if(this.options.isFitWidth){var s=0;n=this.cols;while(--n){if(this.colYs[n]!==0)break;s++}i.width=(this.cols-s)*this.columnWidth-this.options.gutterWidth}this.styleQueue.push({$el:this.element,style:i});var o=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",u=this.options.animationOptions,a;for(n=0,r=this.styleQueue.length;n<r;n++)a=this.styleQueue[n],a.$el[o](a.style,u);this.styleQueue=[],t&&t.call(e),this.isLaidOut=!0},_getColumns:function(){var e=this.options.isFitWidth?this.element.parent():this.element,t=e.width();this.columnWidth=this.isFluid?this.options.columnWidth(t):this.options.columnWidth||this.$bricks.outerWidth(!0)||t,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((t+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(e){var n=t(e),r,i,s,o,u;r=Math.ceil(n.outerWidth(!0)/this.columnWidth),r=Math.min(r,this.cols);if(r===1)s=this.colYs;else{i=this.cols+1-r,s=[];for(u=0;u<i;u++)o=this.colYs.slice(u,u+r),s[u]=Math.max.apply(Math,o)}var a=Math.min.apply(Math,s),f=0;for(var l=0,c=s.length;l<c;l++)if(s[l]===a){f=l;break}var h={top:a+this.offset.y};h[this.horizontalDirection]=this.columnWidth*f+this.offset.x,this.styleQueue.push({$el:n,style:h});var p=a+n.outerHeight(!0),d=this.cols+1-c;for(l=0;l<d;l++)this.colYs[f+l]=p},resize:function(){var e=this.cols;this._getColumns(),(this.isFluid||this.cols!==e)&&this._reLayout()},_reLayout:function(e){var t=this.cols;this.colYs=[];while(t--)this.colYs.push(0);this.layout(this.$bricks,e)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(e){this.reloadItems(),this._init(e)},appended:function(e,t,n){if(t){this._filterFindBricks(e).css({top:this.element.height()});var r=this;setTimeout(function(){r._appended(e,n)},1)}else this._appended(e,n)},_appended:function(e,t){var n=this._getBricks(e);this.$bricks=this.$bricks.add(n),this.layout(n,t)},remove:function(e){this.$bricks=this.$bricks.not(e),e.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position="",this.style.top="",this.style.left=""});var n=this.element[0].style;for(var r in this.originalStyle)n[r]=this.originalStyle[r];this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),t(e).unbind(".masonry")}},t.fn.imagesLoaded=function(e){function u(){e.call(n,r)}function a(e){var n=e.target;n.src!==s&&t.inArray(n,o)===-1&&(o.push(n),--i<=0&&(setTimeout(u),r.unbind(".imagesLoaded",a)))}var n=this,r=n.find("img").add(n.filter("img")),i=r.length,s="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",o=[];return i||u(),r.bind("load.imagesLoaded error.imagesLoaded",a).each(function(){var e=this.src;this.src=s,this.src=e}),n};var s=function(t){e.console&&e.console.error(t)};t.fn.masonry=function(e){if(typeof e=="string"){var n=Array.prototype.slice.call(arguments,1);this.each(function(){var r=t.data(this,"masonry");if(!r){s("cannot call methods on masonry prior to initialization; attempted to call method '"+e+"'");return}if(!t.isFunction(r[e])||e.charAt(0)==="_"){s("no such method '"+e+"' for masonry instance");return}r[e].apply(r,n)})}else this.each(function(){var n=t.data(this,"masonry");n?(n.option(e||{}),n._init()):t.data(this,"masonry",new t.Mason(e,this))});return this}})(window,jQuery);
<|endoftext|>


<commit_before>(function() {

    /**
     * Backbone Forms File editor
     * @author gerardobort <gerardobort@gmail.com>
     * @requires fancy-file
     */
    Backbone.Form.editors.Image = Backbone.Form.editors.Base.extend({

        tagName: 'div',

        defaultValue: '',

        initialize: function(options) {
            var editor = this;

            var options = options || {};

            //Set initial value
            if (options.model) {
                if (!options.key) throw "Missing option: 'key'";

                this.model = options.model;

                // string from model
                this.value = this.model.get(options.key);
            } else if (options.value) {
                // object from list
                this.value = options.value;
            }

            this.$el.removeClass('form-control');
            editor.options = options;
            _.extend(editor, _.pick(options, 'key', 'form'));
            var schema = editor.schema = options.schema || {};
            editor.validators = options.validators || schema.validators;

            // taken from: https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader#readAsDataURL%28%29
            this.oFReader = new FileReader();
            this.rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
        },

        /**
         * Adds the editor to the DOM
         */
        render: function() {
            var editor = this;
            editor.$el.css({ width: 290, display: 'block' });
            editor.$el.toggle(false);
            editor.$el.html(
                '' +
                '<input name="upload" type="file" data-toggle="fancyfile" />' +
                '<button class="btn btn-danger remove-file"></button>' +
                '

'
            );
            setTimeout(function () { // once appended to the DOM
                editor.$el.toggle(true);
                $('[type="file"]', editor.$el).fancyfile({
                    text  : 'Upload',
                    icon  : '',
                    style : 'btn-info',
                    placeholder : 'Select Image…'
                });
                $('.fancy-file', editor.$el).toggle(!editor.value);
                $('.remove-file', editor.$el).toggle(!!editor.value);
                $('.image-preview', editor.$el).toggle(!!editor.value);
            }, 200)
            if (editor.value) {
                if ('object' === typeof editor.value) {
                    $('.image-preview', editor.$el).attr('src', '/api/fs.files/' + editor.value._id + '/raw');
                } else {
                    $('.image-preview', editor.$el).attr('src', '/api/fs.files/' + editor.value + '/raw');
                }
            }
            this._delegateEvents();

            return this;
        },

        _delegateEvents: function () {
            var editor = this;

            editor.oFReader.onload = function (oFREvent) {
                $('.image-preview', editor.$el).one('load', function () {
                    $('.image-preview', editor.$el).toggle(true);
                });
                $('.image-preview', editor.$el).attr('src', oFREvent.target.result);
            };

            $('[type="file"]', editor.$el).on('change', function (event) {
                if (this.files.length === 0) { return; }
                var oFile = this.files[0];
                // only in the case of images... TODO
                if (!editor.rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }

                editor.oFReader.readAsDataURL(oFile);

                //---
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/api/fs.files');

                xhr.upload.onprogress = function (e) {
                    console.log(e.loaded + ' of ' + e.total);
                    var percent = (e.loaded/(e.total||1))*100 + '%';
                    $('.progress-container .progress-bar', editor.$el)
                        .css('width', percent)
                        .text('Uploading... ' + percent);
                };

                xhr.onload = function (xhr) {
                    var response = JSON.parse(arguments[0].currentTarget.response);
                    editor.setValue(response.data[0]);
                    $('.remove-file', editor.$el).toggle(!!editor.value);
                    $('.fancy-file', editor.$el).toggle(!editor.value);
                    $('.image-preview', editor.$el).toggle(!!editor.value);
                    $('.progress-container', editor.$el).html('');
                };

                var form = new FormData();
                var collectionName = $('#collection-form').data('collection-name'); // TODO get this var in a better manner
                form.append(collectionName + '.' + editor.options.key, this.files[0]);
                xhr.send(form);
                $('.progress-container', editor.$el).html(
                    '
' +
                    '

' +
                    '
'
                );
                //---
            });

            $('.remove-file', editor.$el).on('click', function (event) {
                event.preventDefault();
                if (confirm('Are you sure you want to remove this file?')) {
                    $.ajax({
                        url: '/api/fs.files/' + editor.value._id,
                        method: 'DELETE'
                    })
                    .success(function () {
                        editor.setValue(null);
                        //$('[type="file"]', editor.$el).val();
                        $('.image-preview', editor.$el).attr('src', 'about:blank');
                        $('.remove-file', editor.$el).toggle(!!editor.value);
                        $('.fancy-file', editor.$el).toggle(!editor.value);
                        $('.image-preview', editor.$el).toggle(!!editor.value);
                    })
                    .error(function () {
                        alert('An error has occurred.');
                    })
                }
            });

        },

        /**
         * Returns the current editor value
         * @return {String}
         */
        getValue: function() {
            // set the file object w/ObjectId
            if ('object' === typeof this.value) {
                return this.value._id;
            }
            return this.value;
        },

        /**
         * Sets the value of the form element
         * @param {String}
         */
        setValue: function(value) {
            // set the file object w/ObjectId
            this.value = value;
        },

        focus: function () {
            $('[type="file"]', this.$el).get(0).focus();
        }

    });

}());
<commit_msg>image editor fix<commit_after>(function() {

    /**
     * Backbone Forms File editor
     * @author gerardobort <gerardobort@gmail.com>
     * @requires fancy-file
     */
    Backbone.Form.editors.Image = Backbone.Form.editors.Base.extend({

        tagName: 'div',

        defaultValue: '',

        initialize: function(options) {
            var editor = this;

            var options = options || {};

            //Set initial value
            if (options.model) {
                if (!options.key) throw "Missing option: 'key'";

                this.model = options.model;

                // string from model
                this.value = this.model.get(options.key);
            } else if (options.value) {
                // object from list
                this.value = options.value;
            }

            this.$el.removeClass('form-control');
            editor.options = options;
            _.extend(editor, _.pick(options, 'key', 'form'));
            var schema = editor.schema = options.schema || {};
            editor.validators = options.validators || schema.validators;

            // taken from: https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader#readAsDataURL%28%29
            this.oFReader = new FileReader();
            this.rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
        },

        /**
         * Adds the editor to the DOM
         */
        render: function() {
            var editor = this;
            editor.$el.css({ width: 290, display: 'block' });
            editor.$el.toggle(false);
            editor.$el.html(
                '' +
                '<input name="upload" type="file" data-toggle="fancyfile" />' +
                '<button class="btn btn-danger remove-file"></button>' +
                '

'
            );
            setTimeout(function () { // once appended to the DOM
                editor.$el.toggle(true);
                $('[type="file"]', editor.$el).fancyfile({
                    text  : 'Upload',
                    icon  : '',
                    style : 'btn-info',
                    placeholder : 'Select Image…'
                });
                $('.fancy-file', editor.$el).toggle(!editor.value);
                $('.remove-file', editor.$el).toggle(!!editor.value);
                $('.image-preview', editor.$el).toggle(!!editor.value);
            }, 200)
            if (editor.value) {
                if ('object' === typeof editor.value) {
                    $('.image-preview', editor.$el).attr('src', '/api/fs.files/' + editor.value._id + '/raw');
                } else {
                    $('.image-preview', editor.$el).attr('src', '/api/fs.files/' + editor.value + '/raw');
                }
            }
            this._delegateEvents();

            return this;
        },

        _delegateEvents: function () {
            var editor = this;

            editor.oFReader.onload = function (oFREvent) {
                $('.image-preview', editor.$el).one('load', function () {
                    $('.image-preview', editor.$el).toggle(true);
                });
                $('.image-preview', editor.$el).attr('src', oFREvent.target.result);
            };

            $('[type="file"]', editor.$el).on('change', function (event) {
                if (this.files.length === 0) { return; }
                var oFile = this.files[0];
                // only in the case of images... TODO
                if (!editor.rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }

                editor.oFReader.readAsDataURL(oFile);

                //---
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/api/fs.files');

                xhr.upload.onprogress = function (e) {
                    console.log(e.loaded + ' of ' + e.total);
                    var percent = (e.loaded/(e.total||1))*100 + '%';
                    $('.progress-container .progress-bar', editor.$el)
                        .css('width', percent)
                        .text('Uploading... ' + percent);
                };

                xhr.onload = function (xhr) {
                    var response = JSON.parse(arguments[0].currentTarget.response);
                    editor.setValue(response.data[0]);
                    $('.remove-file', editor.$el).toggle(!!editor.value);
                    $('.fancy-file', editor.$el).toggle(!editor.value);
                    $('.image-preview', editor.$el).toggle(!!editor.value);
                    $('.progress-container', editor.$el).html('');
                };

                var form = new FormData();
                var collectionName = $('#collection-form').data('collection-name'); // TODO get this var in a better manner
                form.append(collectionName + '.' + editor.options.key, this.files[0]);
                xhr.send(form);
                $('.progress-container', editor.$el).html(
                    '
' +
                    '

' +
                    '
'
                );
                //---
            });

            $('.remove-file', editor.$el).on('click', function (event) {
                event.preventDefault();
                if (confirm('Are you sure you want to remove this file?')) {
                    $.ajax({
                        url: '/api/fs.files/' + editor.value._id,
                        method: 'DELETE'
                    })
                    .success(function () {
                        editor.setValue(null);
                        //$('[type="file"]', editor.$el).val();
                        $('.image-preview', editor.$el).attr('src', 'about:blank');
                        $('.remove-file', editor.$el).toggle(!!editor.value);
                        $('.fancy-file', editor.$el).toggle(!editor.value);
                        $('.image-preview', editor.$el).toggle(!!editor.value);
                    })
                    .error(function () {
                        alert('An error has occurred.');
                    })
                }
            });

        },

        /**
         * Returns the current editor value
         * @return {String}
         */
        getValue: function() {
            // set the file object w/ObjectId
            if (this.vaue && 'object' === typeof this.value) {
                return this.value._id;
            }
            return this.value;
        },

        /**
         * Sets the value of the form element
         * @param {String}
         */
        setValue: function(value) {
            // set the file object w/ObjectId
            this.value = value;
        },

        focus: function () {
            $('[type="file"]', this.$el).get(0).focus();
        }

    });

}());
<|endoftext|>


<commit_before>(function(win, doc) {

	var init = function() {

		var nav_script = doc.getElementById('jakiestfu-nav-api');
		var frame = doc.createElement('iframe');
		frame.setAttribute([
			"display: block;",
			"position: fixed;",
			"top: 0;",
			"left:0;",
			"right:0;",
			"border:none;"
		].join(""));
		nav_script.parentNode.insertBefore(frame, nav_script.nextSibling);

		frame.src = "";
	};

	window.onload = init;

}).call(this, window, document);
<commit_msg>absolute uri<commit_after>(function(win, doc) {

	var init = function() {

		var nav_script = doc.getElementById('jakiestfu-nav-api');
		var frame = doc.createElement('iframe');
		frame.setAttribute([
			"display: block;",
			"position: fixed;",
			"top: 0;",
			"left:0;",
			"right:0;",
			"border:none;"
		].join(""));
		nav_script.parentNode.insertBefore(frame, nav_script.nextSibling);

		frame.src = "//jakiestfu.github.io/lab-tools/nav/";
	};

	window.onload = init;

}).call(this, window, document);
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Teppo Kurki <teppo.kurki@iki.fi>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Transform = require('stream').Transform;
var gpsd = require('node-gpsd');
var debug = require('debug')('signalk:provider:gpsd');

function Gpsd(options) {
  Transform.call(this, {
    objectMode: true
  });
  this.listener = new gpsd.Listener({
    port: options.port || 2947,
    hostname: options.hostname || 'localhost',
    logger: {
      info: debug,
      warn: console.warn,
      error: console.error
    },
    emitraw: true,
    parsejson: false
  });

  this.listener.connect(function() {
    debug('Connected');
  });

  var self = this;
  this.listener.on('raw', function(data) {
    self.push(data);
  })

  this.listener.watch({
    class: 'WATCH',
    nmea: true
  });
}

require('util').inherits(Gpsd, Transform);

Gpsd.prototype._transform = function(chunk, encoding, done) {
  done();
}

module.exports = Gpsd;<commit_msg>Fix the options for node-gpsd;<commit_after>/*
 * Copyright 2014-2015 Teppo Kurki <teppo.kurki@iki.fi>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Transform = require('stream').Transform;
var gpsd = require('node-gpsd');
var debug = require('debug')('signalk:provider:gpsd');

function Gpsd(options) {
  Transform.call(this, {
    objectMode: true
  });
  this.listener = new gpsd.Listener({
    port: options.port || 2947,
    hostname: options.hostname || 'localhost',
    logger: {
      info: debug,
      warn: console.warn,
      error: console.error
    },
    parse: false
  });

  this.listener.connect(function() {
    debug('Connected');
  });

  var self = this;
  this.listener.on('raw', function(data) {
    self.push(data);
  })

  this.listener.watch({
    class: 'WATCH',
    nmea: true
  });
}

require('util').inherits(Gpsd, Transform);

Gpsd.prototype._transform = function(chunk, encoding, done) {
  done();
}

module.exports = Gpsd;<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// var Data = require('./data.js');
// var osc = require("osc.js");

// var socket = new WebSocket('ws://localhost:8766/osc');
// // Open the socket
// socket.onopen = function(event) {

//     // Send an initial message
//     // socket.send('I am the client and I\'m listening!');

//     // Listen for messages
//     socket.onmessage = function(event) {
//         console.log('Client received a message: ',event);
//     };

//     // Listen for socket closes
//     socket.onclose = function(event) {
//         console.log('Client notified socket has closed',event);
//     };

//     //socket.close()

// };

var oscPort = new osc.WebSocketPort({
    url: "ws://localhost:8766/osc" // URL to your Web Socket server.
});
oscPort.on("message", function (oscMsg) {
    console.log("An OSC message just arrived!", oscMsg);
});

},{}]},{},[1]);
<commit_msg>client-ng build<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// var Data = require('./data.js');
// var osc = require("osc.js");
var Neopixel = require("./neopixel.js");

var container = d3.select('.neopixel');

var neopixel = new Neopixel(container);
var con = document.getElementById('console');
var body = d3.select('body');
var conColumns = {};

function handleOSC(message) {
  logOSC(message);
  if (message.address === '/metronome') {
    strobe(message);
  }
}

function strobe(message) {
  var bpm = message.args[0];
  var delay = 0; // (60 / bpm) / 4.0;
  var duration = (60.0 / bpm) * 1000 / 2.0;
  body
    .style('background-color', '#000')
    .transition()
    .delay(delay)
    .duration(duration)
    .style('background-color','white');
}

function logOSC(message) {
  var div = document.createElement('div');
  div.textContent = message.address + ' ' + message.args;
  var colId = message.address.replace(/\//g,'');
  var col = conColumns[colId];
  if (! col) {
    col = document.createElement('div');
    conColumns[colId] = col;
    con.appendChild(col);
  }
  col.appendChild(div);
  col.scrollTop = col.scrollHeight;
}

var hostName = window.location.hostname;

var socket = new WebSocket('ws://' + hostName + ':8766/osc');
socket.onopen = function(event) {

  socket.onmessage = function(event) {
    reader = new FileReader();
    reader.onloadend = function(e) {
      var arr = new Uint8Array(e.target.result);
      var message = osc.readMessage(arr);
      handleOSC(message);
    }
    reader.readAsArrayBuffer(event.data);
  };

  // Listen for socket closes
  socket.onclose = function(event) {
    console.log('Client notified socket has closed',event);
  };
};

var firehoseSocket = new WebSocket('ws://' + hostName + ':8766/firehose');
firehoseSocket.onopen = function(event) {
  firehoseSocket.onmessage = function(event) {
    reader = new FileReader();
    reader.onloadend = function(e) {
      neopixel.draw(e.target.result);
      firehoseSocket.send(0);

    }
    reader.readAsArrayBuffer(event.data);
  };
  // Listen for socket closes
  socket.onclose = function(event) {
    console.log('Client notified socket has closed',event);
  };
};
},{"./neopixel.js":2}],2:[function(require,module,exports){
var Neopixel = function(container) {

  // var div = d3.select('.neopixel');

  // function getElementDimensions() {
  //    return { 'h': div.offsetHeight, 'w': div.offsetWidth };
  //  };

  // constants
  var width = 500,
    height = 500,
    radius = width/105.0,
    color = d3.interpolateRgb("#f77", "#77f"),
    // N=420
    x1 = 105,
    y1 = 105,
    x2 = 105,
    y2 = 105;

  var iToXY = function(i) {
    var ret = null;
    if (i < y1) {
      ret = [width-radius, i*radius];
    } else if (i >= y1 && i < (x2+y1)) {
      ret = [width - (i-y1)*radius, width-radius];
    } else if (i >= (y1+x2) && i < (y1+x2+y2)) {
      ret = [0, ~~((y1+x1+y2-i)*radius)];
    } else {
      ret = [~~((i-(y1+y2+x2))*radius), 0];
    }
    return ret;
  };

  var svg = container.append("svg")
      .attr("width", width)
      .attr("height", height)
      .style('position', 'absolute');

  this.draw = function(data) {
    // var arr = new Uint8Array(e.target.result);
    var parsedData = [];
    for (var i=0; i<(data.byteLength/3); i++) {
      parsedData[i] = new Uint8Array(data, i*3, 3);
    }
    var shp = svg.selectAll("rect").data(parsedData); // identity function to update existing
    shp
      .style('fill', function(d) {return d3.rgb(d[0],d[1],d[2])})
      .enter()
      .append("rect")
      .attr('x', function(d,i){ return iToXY(i)[0];})
      .attr('y', function(d,i){ return iToXY(i)[1];})
      .attr('width', radius)
      .attr('height', radius);
    shp.exit().remove();
  }

};

module.exports = Neopixel;

},{}]},{},[1]);
<|endoftext|>


<commit_before>// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//mm
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

require('cypress-downloadfile/lib/downloadFileCommand')

Cypress.Commands.add('setYesNoRadioInput', (selector, value) => {
  const selectorValue = value === 'Yes' ? '0' : '1'
  cy.get(`#${selector}-${selectorValue}`).check();
})

Cypress.Commands.add('setTextInput', (selector, value) => {
  cy.get(`#${selector}`).type(value);
})

Cypress.Commands.add('setCheckboxInput', selector => {
  cy.get(`#${selector}`).check();
})
Cypress.Commands.add('setSelectInput', (selector, value) => {
  cy.get(`#${selector}`).select(value);
})

Cypress.Commands.add('setRadioInput', selector => {
  cy.get(`#${selector}`).check();
})

Cypress.Commands.add('savePage', fileName => {
  cy.url().then(url => {
    cy.downloadFile(url, '/Users/mayowaaderohunmu-adeniyi/Documents/GovCode/cla_public/cypress/pages', `${fileName}.html`)
  })
})<commit_msg>Change folder path to match path on circleci<commit_after>// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//mm
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

require('cypress-downloadfile/lib/downloadFileCommand')

Cypress.Commands.add('setYesNoRadioInput', (selector, value) => {
  const selectorValue = value === 'Yes' ? '0' : '1'
  cy.get(`#${selector}-${selectorValue}`).check();
})

Cypress.Commands.add('setTextInput', (selector, value) => {
  cy.get(`#${selector}`).type(value);
})

Cypress.Commands.add('setCheckboxInput', selector => {
  cy.get(`#${selector}`).check();
})
Cypress.Commands.add('setSelectInput', (selector, value) => {
  cy.get(`#${selector}`).select(value);
})

Cypress.Commands.add('setRadioInput', selector => {
  cy.get(`#${selector}`).check();
})

Cypress.Commands.add('savePage', fileName => {
  cy.url().then(url => {
    cy.downloadFile(url, '~/project/cypress-pages/', `${fileName}.html`)
  })
})<|endoftext|>


<commit_before>var _ = require('lodash');
var fs = require('fs');
var keystone = require('../../index.js');
var path = require('path');

keystone.init();

var typesLoc = path.resolve('fields/types');
var types = fs.readdirSync(typesLoc);

types.forEach(function (name) {
	var filtersTestPath = typesLoc + '/' + name + '/test/filters.js';
	if (!fs.existsSync(filtersTestPath)) return;

	var listKey = name + 'FiltersTest';

	// nocreate option prevents warnings for required / not initial fields
	var List = keystone.List(listKey, { nocreate: true });
	var test = require(filtersTestPath);

	test.initList(List);
	List.register();

	var testItems = {};
	testItems[listKey] = test.getTestItems();

	var filter = function (filters, prop, callback) {
		if (typeof prop === 'function') {
			callback = prop;
			prop = null;
		}
		var where = List.addFiltersToQuery(filters);
		List.model.find(where, function (err, results) {
			results = prop ? _.map(results, prop) : results;
			callback(results);
		});
	}

	describe('FieldType: ' + name.substr(0,1).toUpperCase() + name.substr(1) + ': Filter', function () {
		before(function (done) {
			List.model.remove().exec(function (err) {
				if (err) throw err;
				keystone.createItems(testItems, done);
			});
		});
		test.testFilters(List, filter);
	});
});
<commit_msg>Allowing async createItems in Field type filter tests<commit_after>var _ = require('lodash');
var fs = require('fs');
var keystone = require('../../index.js');
var path = require('path');

keystone.init();

var typesLoc = path.resolve('fields/types');
var types = fs.readdirSync(typesLoc);

types.forEach(function (name) {
	var filtersTestPath = typesLoc + '/' + name + '/test/filters.js';
	if (!fs.existsSync(filtersTestPath)) return;

	var listKey = name + 'FiltersTest';

	// nocreate option prevents warnings for required / not initial fields
	var List = keystone.List(listKey, { nocreate: true });
	var test = require(filtersTestPath);

	test.initList(List);
	List.register();

	var filter = function (filters, prop, callback) {
		if (typeof prop === 'function') {
			callback = prop;
			prop = null;
		}
		var where = List.addFiltersToQuery(filters);
		List.model.find(where, function (err, results) {
			results = prop ? _.map(results, prop) : results;
			callback(results);
		});
	}

	describe('FieldType: ' + name.substr(0,1).toUpperCase() + name.substr(1) + ': Filter', function () {
		before(function (done) {
			List.model.remove().exec(function (err) {
				if (err) throw err;
				var testItems = {};
				if (test.getTestItems.length < 2) {
					testItems[listKey] = test.getTestItems(List);
					return keystone.createItems(testItems, done);
				} else {
					test.getTestItems(List, function (err, data) {
						if (err) throw err;
						testItems[listKey] = data;
						keystone.createItems(testItems, done);
					});
				}
			});
		});
		test.testFilters(List, filter);
	});
});
<|endoftext|>


<commit_before>import React from 'react'
import {Link} from 'react-router'
import {prefixLink} from 'gatsby-helpers'
import Helmet from 'react-helmet'
import {config} from 'config'
import ExecutionEnvironment from 'exenv'; // Environment checking for universal apps
import ReactCursorPosition from 'react-cursor-position';

// ** REACT THREE ** //
import React3 from 'react-three-renderer';
import * as THREE from 'three';
import ReactDOM from 'react-dom';
// ** REACT THREE ** //

const ParticleCount = 200;

function NewParticlePos() {
  return (2*Math.random() - 1) * ParticleCount;
}

class Starfield extends React.Component {
    constructor(props, context) {
        super(props, context);

        // construct the position vector here, because if we use 'new' within render,
        // React will think that things have changed when they have not.

        this.renderClock = new THREE.Clock(true);

        this.cameraPosition = new THREE.Vector3(0, 0, 50);

        var textureLoader = new THREE.TextureLoader();
        const sprite1 = textureLoader.load("./snowflake.png");
        const sprite2 = textureLoader.load("./snowflake-2.png");
        const sprite3 = textureLoader.load("./snowflake-3.png");
        const sprite4 = textureLoader.load("./snowflake-4.png");
        const sprite5 = textureLoader.load("./snowflake-5.png");

        this.particleParameters = [
            [
                [
                    1.0, 0.2, 0.5
                ],
                sprite2,
                3
            ],
            [
                [
                    0.95, 0.1, 0.5
                ],
                sprite3,
                15
            ],
            [
                [
                    0.90, 0.05, 0.5
                ],
                sprite1,
                7
            ],
            [
                [
                    0.85, 0, 0.5
                ],
                sprite5,
                8
            ],
            [
                [
                    0.80, 0, 0.5
                ],
                sprite4,
                5
            ]
        ];

        this.state = {
            particleVertices: null,
            particleRotations: null,
        };

        this._onAnimate = () => {
            // we will get this callback every frame

            // pretend cubeRotation is immutable.
            // this helps with updates and pure rendering.
            // React will be sure that the rotation has now updated.
            // this.animateParticles()

            if (this.state.particleVertices != null) {
              this.updateParticles(() => {
                this.particleSystem = this.createParticleSystem();
              })
            }
        };
    }

    animateParticles() {
        for (let i = 0; i < this.state.particleSystem.length; i++) {

            let particleBlock = this.particleSystem[i];

            var verts = particleBlock.geometry.vertices;
            for (let ii = 0; ii < verts.length; ii++) {
                var vert = verts[ii];
                if (vert.z < -200) {
                    vert.z = Math.random() * 400 - 200;
                }
                vert.z = vert.z + (0.2 * deltaTime);
                // vert.y = vert.y - (lastScrollY * 0.002);
            }
            particleBlock.geometry.verticesNeedUpdate = true;

            particleBlock.rotation.y -= .005 * deltaTime;
            particleBlock.position.y = lastScrollY * 0.2 * parallaxVals[i];
            console.log('particle block: ' + i);
            particleBlock.rotation.x = .02 * mouseY * 0.01 * parallaxVals[i];
            particleBlock.rotation.y = .01 * mouseX * 0.01 * parallaxVals[i];

        }
    }

    updateParticles(callback) {

      const deltaTime = this.renderClock.getDelta();
      // Vertices
      const newVertices = this.state.particleVertices.map((vertex) => {
        if (vertex.z < (-2 * ParticleCount) || vertex.z > (ParticleCount)) {
          vertex.z = NewParticlePos();
        }
        vertex.z += 0.3 * deltaTime * (window.innerWidth*0.75/2 - this.props.cursorPosition.x);
        return vertex;
      })

      // Block rotation
      const newRotations = this.state.particleRotations.map((rotation) => {
        rotation.z -= 0.5 * deltaTime;
        return rotation
      })

      this.setState({
        particleVertices: newVertices,
        particleRotations: newRotations,
      }, callback())
    }

    createParticleSystem() {
        var tempParticleArray = [];

        let geometryVertices = this.state.particleVertices;

        if (geometryVertices == null) {

          geometryVertices = [];

          for (let i = 0; i < ParticleCount; i++) {
              var vertex = new THREE.Vector3();
              vertex.x = NewParticlePos();
              vertex.y = NewParticlePos();
              vertex.z = NewParticlePos();
              geometryVertices.push(vertex);
          }
        }

        let particleRotations = this.state.particleRotations;
        if (particleRotations == null) {
          particleRotations = [];
        }

        for (const particleParameter of this.particleParameters) {
            const particleColor = particleParameter[0];
            const particleSprite = particleParameter[1];
            const particleSize = particleParameter[2];

            const rotationIndex = this.particleParameters.indexOf(particleParameter);
            let particleRotation = particleRotations[rotationIndex];
            if (particleRotation == null) {
              particleRotation = new THREE.Euler(Math.random() * 0.1, Math.random() * 0.1, Math.random() * 6);
              particleRotations.push(particleRotation);
            }

            const particleFog = new THREE.FogExp2(0x000000, 0.0008);

            const particles = (
                <points rotation={particleRotation}>
                  <geometry vertices={geometryVertices} // USE STATE OR OTHER
                    dynamic={true}/>
                  <pointsMaterial size={particleSize} map={particleSprite} blending={THREE.AdditiveBlending} depthTest={false} transparent={true} color={particleColor} fog={particleFog}/>
                </points>
            )
            tempParticleArray.push(particles);
        }

        this.setState({
          particleVertices: geometryVertices,
          particleRotations: particleRotations,
        });
        return tempParticleArray;

    }

    componentWillMount() {
      this.particleSystem = this.createParticleSystem();
    }

    render() {

        const width = window.innerWidth*0.75; // canvas width
        const height = window.innerHeight; // canvas height

        const particles = this.particleSystem.map((particle) => {
            return particle
        })

        return (
            <React3 mainCamera="camera" // this points to the perspectiveCamera which has the name set to "camera" below
              width={width} height={height} onAnimate={this._onAnimate}>
              <scene>
                <perspectiveCamera name="camera" fov={70} aspect={width / height} near={1} far={1000} position={this.cameraPosition}/>
                <directionalLight position={new THREE.Vector3(1, -1, 1)}/>
                {particles}
              </scene>
            </React3>
        );
    }
}

export default class Index extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        canUseDOM: ExecutionEnvironment.canUseDOM,
      }
    }

    render() {

      const canUseDOM = this.state.canUseDOM;
      let canvas = null

      if (canUseDOM) {
        canvas = (
        <ReactCursorPosition>
          <Starfield/>
        </ReactCursorPosition>
      )
      }

        return (

              <Helmet title={config.siteTitle} meta={[
                {
                        "name": "description",
                        "content": "Sample"
                }, {
                        "name": "keywords",
                        "content": "sample, something"
                }
              ]}/>
              {canvas}

                  Hi people

Welcome to your new Gatsby site

Below are some pages showing different capabilities built-in to Gatsby

Supported file types

                    <Link to={prefixLink('/markdown/')}>Markdown</Link>

                    <Link to={prefixLink('/react/')}>JSX (React components)</Link>

                    <Link to={prefixLink('/coffee-react/')}>CJSX (Coffeescript React components)</Link>

                    <Link to={prefixLink('/html/')}>HTML</Link>

                    <Link to={prefixLink('/json/')}>JSON</Link>

                    <Link to={prefixLink('/yaml/')}>YAML</Link>

                    <Link to={prefixLink('/toml/')}>TOML</Link>

Supported CSS processors

                    <Link to={prefixLink('/postcss/')}>PostCSS</Link>

                    <Link to={prefixLink('/css-modules/')}>CSS Modules</Link>

                    <Link to={prefixLink('/sass/')}>Sass</Link>

                    <Link to={prefixLink('/less/')}>Less</Link>

                )
                }
                }
<commit_msg>fixed rotation and added parallaxing<commit_after>import React from 'react'
import {Link} from 'react-router'
import {prefixLink} from 'gatsby-helpers'
import Helmet from 'react-helmet'
import {config} from 'config'
import ExecutionEnvironment from 'exenv'; // Environment checking for universal apps
import ReactCursorPosition from 'react-cursor-position';

// ** REACT THREE ** //
import React3 from 'react-three-renderer';
import * as THREE from 'three';
import ReactDOM from 'react-dom';
// ** REACT THREE ** //

const ParticleCount = 200;

function NewParticlePos() {
  return (2*Math.random() - 1) * ParticleCount;
}

class Starfield extends React.Component {
    constructor(props, context) {
        super(props, context);

        // construct the position vector here, because if we use 'new' within render,
        // React will think that things have changed when they have not.

        this.renderClock = new THREE.Clock(true);

        this.cameraPosition = new THREE.Vector3(0, 0, 50);

        var textureLoader = new THREE.TextureLoader();
        const sprite1 = textureLoader.load("./snowflake.png");
        const sprite2 = textureLoader.load("./snowflake-2.png");
        const sprite3 = textureLoader.load("./snowflake-3.png");
        const sprite4 = textureLoader.load("./snowflake-4.png");
        const sprite5 = textureLoader.load("./snowflake-5.png");

        this.particleParameters = [
            [
                [
                    1.0, 0.2, 0.5
                ],
                sprite2,
                3
            ],
            [
                [
                    0.95, 0.1, 0.5
                ],
                sprite3,
                15
            ],
            [
                [
                    0.90, 0.05, 0.5
                ],
                sprite1,
                7
            ],
            [
                [
                    0.85, 0, 0.5
                ],
                sprite5,
                8
            ],
            [
                [
                    0.80, 0, 0.5
                ],
                sprite4,
                5
            ]
        ];

        this.parallaxValues = [2.0, 0.6, 1.2, 0.8, 0.9];

        this.state = {
            particleVertices: null,
            particleRotations: null,
        };

        this._onAnimate = () => {
            // we will get this callback every frame

            // pretend cubeRotation is immutable.
            // this helps with updates and pure rendering.
            // React will be sure that the rotation has now updated.
            // this.animateParticles()

            if (this.state.particleVertices != null) {
              this.updateParticles(() => {
                this.particleSystem = this.createParticleSystem();
              })
            }
        };
    }

    animateParticles() {
        for (let i = 0; i < this.state.particleSystem.length; i++) {

            let particleBlock = this.particleSystem[i];

            var verts = particleBlock.geometry.vertices;
            for (let ii = 0; ii < verts.length; ii++) {
                var vert = verts[ii];
                if (vert.z < -200) {
                    vert.z = Math.random() * 400 - 200;
                }
                vert.z = vert.z + (0.2 * deltaTime);
                // vert.y = vert.y - (lastScrollY * 0.002);
            }
            particleBlock.geometry.verticesNeedUpdate = true;

            particleBlock.rotation.y -= .005 * deltaTime;
            particleBlock.position.y = lastScrollY * 0.2 * parallaxVals[i];
            console.log('particle block: ' + i);
            particleBlock.rotation.x = .02 * mouseY * 0.01 * parallaxVals[i];
            particleBlock.rotation.y = .01 * mouseX * 0.01 * parallaxVals[i];

        }
    }

    updateParticles(callback) {

      const deltaTime = this.renderClock.getDelta();
      // Vertices
      const newVertices = this.state.particleVertices.map((vertex) => {
        if (vertex.z < (-2 * ParticleCount) || vertex.z > (ParticleCount)) {
          vertex.z = NewParticlePos()*-2;
        }
        vertex.z += 2 * deltaTime;
        return vertex;
      })

      // Block rotation
      const newRotations = this.state.particleRotations.map((rotation) => {

        const rotationIndex = this.state.particleRotations.indexOf(rotation);
        const parallax = this.parallaxValues[rotationIndex];

        // Need to create a new Euler instead of directly modifying the old one
        rotation = new THREE.Euler(
          rotation.x = -(0.0001 * this.props.cursorPosition.y)*parallax,
          rotation.y = -(0.0001 * this.props.cursorPosition.x)*parallax,
          rotation.z = rotation.z
        );

        return rotation
      })

      this.setState({
        particleVertices: newVertices,
        particleRotations: newRotations,
      }, callback())
    }

    createParticleSystem() {
        var tempParticleArray = [];

        let geometryVertices = this.state.particleVertices;

        if (geometryVertices == null) {

          geometryVertices = [];

          for (let i = 0; i < ParticleCount; i++) {
              var vertex = new THREE.Vector3();
              vertex.x = NewParticlePos();
              vertex.y = NewParticlePos();
              vertex.z = NewParticlePos();
              geometryVertices.push(vertex);
          }
        }

        let particleRotations = this.state.particleRotations;
        if (particleRotations == null) {
          console.log("used null");
          particleRotations = [];
        }

        for (const particleParameter of this.particleParameters) {

            const colorBit = particleParameter[0];
            const hslColorString = new String('hsl(%s, %s, %s)', colorBit[0], colorBit[1], colorBit[2])

            const particleColor = new THREE.Color(hslColorString);
            const particleSprite = particleParameter[1];
            const particleSize = particleParameter[2];

            const rotationIndex = this.particleParameters.indexOf(particleParameter);
            let particleRotation = particleRotations[rotationIndex];
            if (particleRotation == null) {
              particleRotation = new THREE.Euler(Math.random() * 0.1, Math.random() * 0.1, Math.random() * 6);
              particleRotations.push(particleRotation);
            } else {
              // console.log(particleRotation.y)
            }

            const particles = (
                <points key={'pointBlock-'+rotationIndex} rotation={particleRotation}>
                  <geometry vertices={geometryVertices} // USE STATE OR OTHER
                    dynamic={true}/>
                  <pointsMaterial size={particleSize} map={particleSprite} blending={THREE.AdditiveBlending} depthTest={false} transparent={true} color={particleColor} />
                </points>
            )
            tempParticleArray.push(particles);
        }

        this.setState({
          particleVertices: geometryVertices,
          particleRotations: particleRotations,
        });
        return tempParticleArray;

    }

    componentWillMount() {
      this.particleSystem = this.createParticleSystem();
    }

    render() {

        const width = window.innerWidth*0.75; // canvas width
        const height = window.innerHeight; // canvas height

        const particles = this.particleSystem.map((particle) => {
            return particle
        })

        return (
            <React3 mainCamera="camera" // this points to the perspectiveCamera which has the name set to "camera" below
              width={width} height={height} onAnimate={this._onAnimate}>
              <scene fog={new THREE.Fog(0x000000, 0.0008)}>
                <perspectiveCamera name="camera" fov={70} aspect={width / height} near={1} far={1000} position={this.cameraPosition}/>
                <directionalLight position={new THREE.Vector3(1, -1, 1)}/>
                {particles}
              </scene>
            </React3>
        );
    }
}

export default class Index extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        canUseDOM: ExecutionEnvironment.canUseDOM,
      }
    }

    render() {

      const canUseDOM = this.state.canUseDOM;
      let canvas = null

      if (canUseDOM) {
        canvas = (
        <ReactCursorPosition>
          <Starfield/>
        </ReactCursorPosition>
      )
      }

        return (

              <Helmet title={config.siteTitle} meta={[
                {
                        "name": "description",
                        "content": "Sample"
                }, {
                        "name": "keywords",
                        "content": "sample, something"
                }
              ]}/>
              {canvas}

                  Hi people

Welcome to your new Gatsby site

Below are some pages showing different capabilities built-in to Gatsby

Supported file types

                    <Link to={prefixLink('/markdown/')}>Markdown</Link>

                    <Link to={prefixLink('/react/')}>JSX (React components)</Link>

                    <Link to={prefixLink('/coffee-react/')}>CJSX (Coffeescript React components)</Link>

                    <Link to={prefixLink('/html/')}>HTML</Link>

                    <Link to={prefixLink('/json/')}>JSON</Link>

                    <Link to={prefixLink('/yaml/')}>YAML</Link>

                    <Link to={prefixLink('/toml/')}>TOML</Link>

Supported CSS processors

                    <Link to={prefixLink('/postcss/')}>PostCSS</Link>

                    <Link to={prefixLink('/css-modules/')}>CSS Modules</Link>

                    <Link to={prefixLink('/sass/')}>Sass</Link>

                    <Link to={prefixLink('/less/')}>Less</Link>

                )
                }
                }
<|endoftext|>


<commit_before>import take from 'lodash.take'
import { className as validateClassName } from './validationHelpers'
/**
/**
 * Inspect the element's siblings by CSS Class names and compare them to the analyzed element.
 * @param {array} hierarchy. The hierarchy of elements
 * @param {object} state. The current calculated CSS selector
 */
export default function (hierarchy, state) {
  hierarchy.forEach((currentElem, index) => {
    // get class attribute
    const currentClasses = (currentElem.el.getAttribute('class') || '')
      .replace(/^\s\s*/, '')
      .replace(/\s\s*$/, '')

    if (currentClasses && typeof currentClasses === 'string') {
      const validClasses = take(currentClasses.match(/([^\s]+)/gi) || [], 10)
        .filter(validateClassName)
        .map(className => `.${className}`)

      if (validClasses.length) {
        // limit to 10 classes
        state.stack[index].push(validClasses.join(''))
        state.specificity += 10 * validClasses.length
      }
    }
  })
  return state
}
<commit_msg>cleaned up inspect Siblings<commit_after>import take from 'lodash.take'
import { className as validateClassName } from './validationHelpers'
/**
/**
 * Inspect the element's siblings by CSS Class names and compare them to the analyzed element.
 * @param {array} hierarchy. The hierarchy of elements
 * @param {object} state. The current calculated CSS selector
 */
export default function (hierarchy, state) {
  return hierarchy.reduce((selectorState, currentElem, index) => {
    const validClasses = take(currentElem.getClasses(), 10)
      .filter(validateClassName)
      .map(className => `.${className}`)

    if (validClasses.length) {
      // limit to 10 classes
      selectorState.stack[index].push(validClasses.join(''))
      selectorState.specificity += 10 * validClasses.length
    }
    return selectorState
  }, state)
}
<|endoftext|>


<commit_before>/**
 * Simplified version of directive found on Stack Overflow.
 *
 * @see http://stackoverflow.com/a/14837021/3807342
 */
admin.directive('focusOnce', function($timeout, $parse) {
    return {
        link: function( scope, element, attrs ) {
        var model = $parse( attrs.focusOnce );
            scope.$watch( model, function( value ) {
                if( value === true ) {
                    $timeout( function() {
                        element[ 0 ].focus();
                    });
                }
            });
        }
    };
});<commit_msg>Dummy edit to trigger build<commit_after>/**
 * Simplified version of directive found on Stack Overflow.
 *
 * @see http://stackoverflow.com/a/14837021/3807342
 */
admin.directive( "focusOnce", function($timeout, $parse) {
    return {
        link: function( scope, element, attrs ) {
        var model = $parse( attrs.focusOnce );
            scope.$watch( model, function( value ) {
                if( value === true ) {
                    $timeout( function() {
                        element[ 0 ].focus();
                    });
                }
            });
        }
    };
});<|endoftext|>


<commit_before>// Flow properties of BusinessProcess model

'use strict';

var memoize                     = require('memoizee/plain')
  , defineBusinessProcessStatus = require('../lib/business-process-status')
  , defineGuide                 = require('./guide')
  , defineDataForms             = require('./data-forms')
  , defineRequirementUploads    = require('./requirement-uploads')
  , defineCosts                 = require('./costs')
  , defineSubmissionForms       = require('./submission-forms')
  , defineProcessingSteps       = require('./processing-steps');

module.exports = memoize(function (db/*, options*/) {
	var BusinessProcess = defineGuide(db, arguments[1])
	  , BusinessProcessStatus = defineBusinessProcessStatus(db);

	defineDataForms(db);
	defineRequirementUploads(db);
	defineCosts(db);
	defineSubmissionForms(db);
	defineProcessingSteps(db);

	BusinessProcess.prototype.defineProperties({
		// Whether business process is submitted to Part B
		isSubmitted: { type: db.Boolean, value: function (_observe) {
			// 0. Guide
			if (this.guideProgress !== 1) return false;
			// 1. Forms
			if (_observe(this.dataForms._progress) !== 1) return false;
			// 2. Uploads
			if (_observe(this.requirementUploads._progress) !== 1) return false;
			// 3. (optional) Payments
			if (_observe(this.costs._onlinePaymentProgress) !== 1) return false;
			// 4. Submission
			if (_observe(this.submissionForms._progress) !== 1) return false;
			return true;
		} },
		// Whether business process was sent back to Part A
		isSentBack: { type: db.Boolean, value: function (_observe) {
			if (!this.isSubmitted) return false;
			return _observe(this.processingSteps.applicable).some(function (step) {
				return _observe(step._isSentBack);
			});
		} },
		// Whether business process was rejected
		isRejected: { type: db.Boolean, value: function (_observe) {
			if (!this.isSubmitted) return false;
			return _observe(this.processingSteps.applicable).some(function (step) {
				return _observe(step._isRejected);
			});
		} },
		// Whether business process is closed
		isClosed: { type: db.Boolean, value: function (_observe) {
			if (!this.isSubmitted) return false;
			return _observe(this.processingSteps.applicable).every(function (step) {
				return _observe(step._isClosed);
			});
		} },
		// Computed status of registration
		status: { type: BusinessProcessStatus, value: function (_observe) {
			var frontDesk;
			if (!this.isSubmitted) return 'draft';
			if (this.isClosed) return 'closed';
			frontDesk = this.processingSteps.map.frontDesk;
			if (frontDesk && _observe(frontDesk._isPending)) return 'pickup';
			return 'process';
		} }
	});
	return BusinessProcess;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<commit_msg>Fix isClosed resolution<commit_after>// Flow properties of BusinessProcess model

'use strict';

var memoize                     = require('memoizee/plain')
  , defineBusinessProcessStatus = require('../lib/business-process-status')
  , defineGuide                 = require('./guide')
  , defineDataForms             = require('./data-forms')
  , defineRequirementUploads    = require('./requirement-uploads')
  , defineCosts                 = require('./costs')
  , defineSubmissionForms       = require('./submission-forms')
  , defineProcessingSteps       = require('./processing-steps');

module.exports = memoize(function (db/*, options*/) {
	var BusinessProcess = defineGuide(db, arguments[1])
	  , BusinessProcessStatus = defineBusinessProcessStatus(db);

	defineDataForms(db);
	defineRequirementUploads(db);
	defineCosts(db);
	defineSubmissionForms(db);
	defineProcessingSteps(db);

	BusinessProcess.prototype.defineProperties({
		// Whether business process is submitted to Part B
		isSubmitted: { type: db.Boolean, value: function (_observe) {
			// 0. Guide
			if (this.guideProgress !== 1) return false;
			// 1. Forms
			if (_observe(this.dataForms._progress) !== 1) return false;
			// 2. Uploads
			if (_observe(this.requirementUploads._progress) !== 1) return false;
			// 3. (optional) Payments
			if (_observe(this.costs._onlinePaymentProgress) !== 1) return false;
			// 4. Submission
			if (_observe(this.submissionForms._progress) !== 1) return false;
			return true;
		} },
		// Whether business process was sent back to Part A
		isSentBack: { type: db.Boolean, value: function (_observe) {
			if (!this.isSubmitted) return false;
			return _observe(this.processingSteps.applicable).some(function (step) {
				return _observe(step._isSentBack);
			});
		} },
		// Whether business process was rejected
		isRejected: { type: db.Boolean, value: function (_observe) {
			if (!this.isSubmitted) return false;
			return _observe(this.processingSteps.applicable).some(function (step) {
				return _observe(step._isRejected);
			});
		} },
		// Whether business process is closed
		isClosed: { type: db.Boolean, value: function (_observe) {
			if (!this.isSubmitted) return false;
			if (this.isRejected) return true;
			return _observe(this.processingSteps.applicable).every(function (step) {
				return _observe(step._isClosed);
			});
		} },
		// Computed status of registration
		status: { type: BusinessProcessStatus, value: function (_observe) {
			var frontDesk;
			if (!this.isSubmitted) return 'draft';
			if (this.isClosed) return 'closed';
			frontDesk = this.processingSteps.map.frontDesk;
			if (frontDesk && _observe(frontDesk._isPending)) return 'pickup';
			return 'process';
		} }
	});
	return BusinessProcess;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<|endoftext|>