<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var reverseArguments = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof reverseArguments, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function throws an error if not provided a function', function test( t ) {
	var values;
	var i;

	values = [
		'5',
		5,
		NaN,
		true,
		null,
		undefined,
		{},
		[]
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function badValue() {
			reverseArguments( value );
		};
	}
});

tape( 'the function returns a function', function test( t ) {
	var bar;

	function foo( a, b, c ) {
		return [ a, b, c ];
	}

	bar = reverseArguments( foo );

	t.strictEqual( typeof bar, 'function', 'returns a function' );
	t.end();
});

tape( 'the returned function invokes a function with arguments in reverse order', function test( t ) {
	var bar;

	function foo( a, b, c ) {
		return [ a, b, c ];
	}

	bar = reverseArguments( foo );

	t.deepEqual( foo( 1, 2, 3 ), [ 1, 2, 3 ], 'returns arguments in order' );
	t.deepEqual( bar( 1, 2, 3 ), [ 3, 2, 1 ], 'applies arguments in reverse order' );
	t.end();
});

tape( 'the function supports providing a `this` context', function test( t ) {
	var ctx;
	var bar;
	var i;

	function foo( a, b, c ) {
		return [ a, b, c ];
	}

	ctx = [
		null,
		undefined,
		[],
		{},
		'beep',
		3.14,
		function() {}
	];

	bar = reverseArguments( foo, ctx );

	for ( i = 0; i < ctx.length; i++ ) {
		t.deepEqual( bar( 1, 2, 3 ), [ 3, 2, 1 ], 'applies arguments in reverse order' );
	}
	t.end();
});

tape( 'the function supports providing a `this` context', function test( t ) {
	var ctx;
	var bar;
	var foo;

	function Foo() {
		this.a = 1;
		this.b = 2;
		this.c = 3;
		return this;
	}

	Foo.prototype.scale = function scale( a, b, c ) {
		return [ this.a*a, this.b*b, this.c*c ];
	};

	ctx = {
		'a': 10,
		'b': 20,
		'c': 30
	};

	foo = new Foo();
	bar = reverseArguments( foo.scale, ctx );

	t.deepEqual( bar( 1, 2, 3 ), [ 30, 40, 30 ], 'applies arguments in reverse order' );
	t.end();
});
<commit_msg>Assign function name<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var reverseArguments = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof reverseArguments, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function throws an error if not provided a function', function test( t ) {
	var values;
	var i;

	values = [
		'5',
		5,
		NaN,
		true,
		null,
		undefined,
		{},
		[]
	];

	for ( i = 0; i < values.length; i++ ) {
		t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
	}
	t.end();

	function badValue( value ) {
		return function badValue() {
			reverseArguments( value );
		};
	}
});

tape( 'the function returns a function', function test( t ) {
	var bar;

	function foo( a, b, c ) {
		return [ a, b, c ];
	}

	bar = reverseArguments( foo );

	t.strictEqual( typeof bar, 'function', 'returns a function' );
	t.end();
});

tape( 'the returned function invokes a function with arguments in reverse order', function test( t ) {
	var bar;

	function foo( a, b, c ) {
		return [ a, b, c ];
	}

	bar = reverseArguments( foo );

	t.deepEqual( foo( 1, 2, 3 ), [ 1, 2, 3 ], 'returns arguments in order' );
	t.deepEqual( bar( 1, 2, 3 ), [ 3, 2, 1 ], 'applies arguments in reverse order' );
	t.end();
});

tape( 'the function supports providing a `this` context', function test( t ) {
	var ctx;
	var bar;
	var i;

	function foo( a, b, c ) {
		return [ a, b, c ];
	}

	ctx = [
		null,
		undefined,
		[],
		{},
		'beep',
		3.14,
		function noop() {}
	];

	bar = reverseArguments( foo, ctx );

	for ( i = 0; i < ctx.length; i++ ) {
		t.deepEqual( bar( 1, 2, 3 ), [ 3, 2, 1 ], 'applies arguments in reverse order' );
	}
	t.end();
});

tape( 'the function supports providing a `this` context', function test( t ) {
	var ctx;
	var bar;
	var foo;

	function Foo() {
		this.a = 1;
		this.b = 2;
		this.c = 3;
		return this;
	}

	Foo.prototype.scale = function scale( a, b, c ) {
		return [ this.a*a, this.b*b, this.c*c ];
	};

	ctx = {
		'a': 10,
		'b': 20,
		'c': 30
	};

	foo = new Foo();
	bar = reverseArguments( foo.scale, ctx );

	t.deepEqual( bar( 1, 2, 3 ), [ 30, 40, 30 ], 'applies arguments in reverse order' );
	t.end();
});
<|endoftext|>


<commit_before>'use strict';
var camelCase = require('lodash.camelcase');
var reduce = require('lodash.reduce');
var React = require('react');
var camelCaseAttrMap = require('./camel-case-attribute-names');

function getCamelCaseAttr(key) {
    key = key.replace(/-/, '');
    return camelCaseAttrMap[key];
}

function createStyleJsonFromString(styleString) {
    if (!styleString) {
        return {};
    }
    var styles = styleString.split(';');
    var singleStyle, key, value, jsonStyles = {};
    for (var i = 0; i < styles.length; i++) {
        singleStyle = styles[i].split(':');
        key = camelCase(singleStyle[0]);
        value = singleStyle[1];
        if (key.length > 0 && value.length > 0) {
            jsonStyles[key] = value;
        }
    }
    return jsonStyles;
}

function createElementProps(node, index) {
    var elementProps = {
        key: index,
    };
    if (node.attribs) {
        elementProps = reduce(node.attribs, function(result, value, key) {
            key = getCamelCaseAttr(key) || key;
            if (key === 'style') {
                value = createStyleJsonFromString(node.attribs.style);
            } else if (key === 'class') {
                key = 'className';
            }
            result[key] = value || key;
            return result;
        }, elementProps);
    }

    return elementProps;
}

function createElement(name, elementProps, data, children) {
    children = children || [];
    var allChildren = data != null ? [data,].concat(children) : children;
    return React.createElement.apply(
        null, [name, elementProps,].concat(allChildren)
    );
}

module.exports = {
    createElementProps: createElementProps,
    createElement: createElement,
};
<commit_msg>Simplify<commit_after>'use strict';
var camelCase = require('lodash.camelcase');
var reduce = require('lodash.reduce');
var React = require('react');
var camelCaseAttrMap = require('./camel-case-attribute-names');

function createStyleJsonFromString(styleString) {
    if (!styleString) {
        return {};
    }
    var styles = styleString.split(';');
    var singleStyle, key, value, jsonStyles = {};
    for (var i = 0; i < styles.length; i++) {
        singleStyle = styles[i].split(':');
        key = camelCase(singleStyle[0]);
        value = singleStyle[1];
        if (key.length > 0 && value.length > 0) {
            jsonStyles[key] = value;
        }
    }
    return jsonStyles;
}

function createElementProps(node, index) {
    var elementProps = {
        key: index,
    };
    if (node.attribs) {
        elementProps = reduce(node.attribs, function(result, value, key) {
            key = camelCaseAttrMap[key.replace(/-/, '')] || key;
            if (key === 'style') {
                value = createStyleJsonFromString(node.attribs.style);
            } else if (key === 'class') {
                key = 'className';
            }
            result[key] = value || key;
            return result;
        }, elementProps);
    }

    return elementProps;
}

function createElement(name, elementProps, data, children) {
    children = children || [];
    var allChildren = data != null ? [data,].concat(children) : children;
    return React.createElement.apply(
        null, [name, elementProps,].concat(allChildren)
    );
}

module.exports = {
    createElementProps: createElementProps,
    createElement: createElement,
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var bodyParser = require('body-parser');

var multer = require('multer');
var upload = multer();

var log = require('debug')('tricket:api');

var ticketService = require('../services/ticket-service.js')();
var mailService = require('../services/mail-service.js')();
var counterService = require('../services/counter-service.js')();

router.post('/ticket/new', function(req, res) {
  //log(req.body);
  var date = new Date();
  var note = {
    'body': req.body.body,
    'type': 'external',
    'dateCreated': date.toISOString(),
    'worklog': req.body.worklog || 0,
    'user' : req.user.displayName
  };
  var ticket = {
    customer: {
      email: req.body.customer,
      name: ''
    },
    asignee: 'Not asigned',
    status: req.body.close !== undefined ? 'Closed' : 'Open',
    title: req.body.title || '<Empty subject>',
    dateCreated: new Date().toISOString(),
    notes: [note]
  };
  ticketService.insertTicket(ticket, function(result) {
    log('Inserted ticket to mongo');
    res.redirect(302, '/app/tickets');
  });
});

router.get('/ticket/:id/asign/:user', function(req, res) {
  var id = req.params.id;
  var user = req.params.user;

  ticketService.asignTicket(id, user, function(result) {
    log('Ticket claimed');
  });
  res.redirect(302, '/app/ticket/'+id);
});

router.get('/ticket/:id/reject', function(req, res) {
  var id = req.params.id;
  //TODO: if external, send mail to customer
  ticketService.rejectTicket(id, function(result) {
    log('Ticket rejected');
  });
  res.redirect(302, '/app/ticket/'+id);
});

router.post('/ticket/:id/note', function(req, res) {
  var id = req.params.id;
  var date = new Date();
  var note = {
    'body': req.body.body,
    'type': req.body.type,
    'dateCreated': date.toISOString(),
    'worklog': req.body.worklog || 0,
    'user' : req.user.displayName
  };

  mailService.externalNote(id, note, function(result) {
    log('External note sent to client');
  });
  ticketService.addNoteToTicket(id, note, function(result) {
    log('Inserted note to ticket');
  });

  if(req.body.note === undefined){
    var status = req.body.close !== undefined ? 'Closed' : 'Open';
    ticketService.updateTicketStatus(id, status , function(result) {
      log('Ticket status updated: ' +status);
    });
    if(status === 'Closed'){
      res.redirect(302, '/app/tickets');
      return;
    }
  }
  res.redirect(302, '/app/ticket/'+id);
});

router.post('/emails', upload.array(), function(req, res, next) {
  var msg = null;
  if (typeof req.body.mailinMsg === 'string') {
    msg = JSON.parse(req.body.mailinMsg);
  } else {
    msg = req.body.mailinMsg;
  }
  log('Parsed msg: ' + JSON.stringify(msg, null, 2));

  var ticket = ticketService.createTicket(msg);
  log('Created ticket from email');
  ticketService.insertTicket(ticket, function(result) {
    log('Inserted ticket to mongo');
    mailService.newTicketNotification(ticket, function(result) {
      log('Sending ticket');
    });
    res.status(201).send(ticket);
  });
});

router.get('/ticket/:id/trash', function(req, res) {
  var id = req.params.id;
  var status = 'Trashed';
  ticketService.updateTicketStatus(id, status , function(result) {
    log('Ticket status updated: ' +status);
  });
  res.redirect(302, '/app/tickets');
  return;
});

router.get('/ticket/:id/untrash', function(req, res) {
  var id = req.params.id;
  var status = 'Open';
  ticketService.updateTicketStatus(id, status , function(result) {
    log('Ticket status updated: ' +status);
  });
  res.redirect(302, '/app/tickets');
  return;
});

router.post('/ticket/:id/save', function(req, res) {
  var id = req.params.id;
  //console.log('req.body: ' + JSON.stringify(req.body, null, 2));
  var prop = req.body.name;
  var value = req.body.value;

  var ticket = {
  };

  ticket[prop] = value;
  ticketService.updateTicket(id, ticket, function(result) {
    res.status(200).end();
  });
});

router.head('/emails', function(req, res, next) {
  res.status(200).end();
});

router.get('/emails', function(req, res, next) {
  res.status(200).end();
});

router.post('/counter/:id/rename', function(req, res) {
  var oldId = req.params.id;
  var newId = req.body.newId;
  counterService.rename(oldId, newId, function(result) {
    log('Counter ' + oldId + ' renamed to ' + newId);
      ticketService.renameAllTickets(oldId, newId, function(result) {
    });
  });
  res.redirect(302, '/app/counters');
});

module.exports = router;
<commit_msg>Corrección envío solo en caso de externas<commit_after>'use strict';
var express = require('express');
var router = express.Router();

var multer = require('multer');
var upload = multer();

var log = require('debug')('tricket:api');

var ticketService = require('../services/ticket-service.js')();
var mailService = require('../services/mail-service.js')();
var counterService = require('../services/counter-service.js')();

router.post('/ticket/new', function(req, res) {
  //log(req.body);
  var date = new Date();
  var note = {
    'body': req.body.body,
    'type': 'external',
    'dateCreated': date.toISOString(),
    'worklog': req.body.worklog || 0,
    'user' : req.user.displayName
  };
  var ticket = {
    customer: {
      email: req.body.customer,
      name: ''
    },
    asignee: 'Not asigned',
    status: req.body.close !== undefined ? 'Closed' : 'Open',
    title: req.body.title || '<Empty subject>',
    dateCreated: new Date().toISOString(),
    notes: [note]
  };
  ticketService.insertTicket(ticket, function(result) {
    log('Inserted ticket to mongo');
    res.redirect(302, '/app/tickets');
  });
});

router.get('/ticket/:id/asign/:user', function(req, res) {
  var id = req.params.id;
  var user = req.params.user;

  ticketService.asignTicket(id, user, function(result) {
    log('Ticket claimed');
  });
  res.redirect(302, '/app/ticket/'+id);
});

router.get('/ticket/:id/reject', function(req, res) {
  var id = req.params.id;
  //TODO: if external, send mail to customer
  ticketService.rejectTicket(id, function(result) {
    log('Ticket rejected');
  });
  res.redirect(302, '/app/ticket/'+id);
});

router.post('/ticket/:id/note', function(req, res) {
  var id = req.params.id;
  var date = new Date();
  var note = {
    'body': req.body.body,
    'type': req.body.type,
    'dateCreated': date.toISOString(),
    'worklog': req.body.worklog || 0,
    'user' : req.user.displayName
  };

  //console.log('Tipo:' +req.body.type);
  if(req.body.type === 'external'){
    mailService.externalNote(id, note, function(result) {
      log('External note sent to client');
    });
  }

  ticketService.addNoteToTicket(id, note, function(result) {
    log('Inserted note to ticket');
  });

  if(req.body.note === undefined){
    var status = req.body.close !== undefined ? 'Closed' : 'Open';
    ticketService.updateTicketStatus(id, status , function(result) {
      log('Ticket status updated: ' +status);
    });
    if(status === 'Closed'){
      res.redirect(302, '/app/tickets');
      return;
    }
  }
  res.redirect(302, '/app/ticket/'+id);
});

router.post('/emails', upload.array(), function(req, res, next) {
  var msg = null;
  if (typeof req.body.mailinMsg === 'string') {
    msg = JSON.parse(req.body.mailinMsg);
  } else {
    msg = req.body.mailinMsg;
  }
  log('Parsed msg: ' + JSON.stringify(msg, null, 2));

  var ticket = ticketService.createTicket(msg);
  log('Created ticket from email');
  ticketService.insertTicket(ticket, function(result) {
    log('Inserted ticket to mongo');
    mailService.newTicketNotification(ticket, function(result) {
      log('Sending ticket');
    });
    res.status(201).send(ticket);
  });
});

router.get('/ticket/:id/trash', function(req, res) {
  var id = req.params.id;
  var status = 'Trashed';
  ticketService.updateTicketStatus(id, status , function(result) {
    log('Ticket status updated: ' +status);
  });
  res.redirect(302, '/app/tickets');
  return;
});

router.get('/ticket/:id/untrash', function(req, res) {
  var id = req.params.id;
  var status = 'Open';
  ticketService.updateTicketStatus(id, status , function(result) {
    log('Ticket status updated: ' +status);
  });
  res.redirect(302, '/app/tickets');
  return;
});

router.post('/ticket/:id/save', function(req, res) {
  var id = req.params.id;
  //console.log('req.body: ' + JSON.stringify(req.body, null, 2));
  var prop = req.body.name;
  var value = req.body.value;

  var ticket = {
  };

  ticket[prop] = value;
  ticketService.updateTicket(id, ticket, function(result) {
    res.status(200).end();
  });
});

router.head('/emails', function(req, res, next) {
  res.status(200).end();
});

router.get('/emails', function(req, res, next) {
  res.status(200).end();
});

router.post('/counter/:id/rename', function(req, res) {
  var oldId = req.params.id;
  var newId = req.body.newId;
  counterService.rename(oldId, newId, function(result) {
    log('Counter ' + oldId + ' renamed to ' + newId);
      ticketService.renameAllTickets(oldId, newId, function(result) {
    });
  });
  res.redirect(302, '/app/counters');
});

module.exports = router;
<|endoftext|>


<commit_before>var coffee = require("coffee-script");

function base64decode(input) {
    return new Buffer(input, "base64").toString("utf-8");
}

function compileCoffeeResource(resourceSet, coffeePath, jsPath) {
    var coffeeResource = resourceSet.get(coffeePath);
    resourceSet.addResource({
        path: jsPath,
        content: function () {
            if (coffeeResource.encoding === "base64") {
                return coffeeResource.content()
                    .then(base64decode).then(coffee.compile);
            } else {
                return coffeeResource.content().then(coffee.compile);
            }
        }
    });
}

module.exports = {
    name: "buster-coffee",

    configure: function (config) {
        config.on("load:resources", function (resourceSet) {
            var paths = resourceSet.loadPath.paths();
            resourceSet.loadPath.clear();
            paths.forEach(function (path) {
                if (/\.coffee$/.test(path)) {
                    var jsPath = path + ".js";
                    compileCoffeeResource(resourceSet, path, jsPath);
                    resourceSet.loadPath.append(jsPath);
                } else {
                    resourceSet.loadPath.append(path);
                }
            });
        });
    }
};
<commit_msg>Made it not intervene when nodejs is the environment<commit_after>var coffee = require("coffee-script");

function base64decode(input) {
    return new Buffer(input, "base64").toString("utf-8");
}

function compileCoffeeResource(resourceSet, coffeePath, jsPath) {
    var coffeeResource = resourceSet.get(coffeePath);
    resourceSet.addResource({
        path: jsPath,
        content: function () {
            if (coffeeResource.encoding === "base64") {
                return coffeeResource.content()
                    .then(base64decode).then(coffee.compile);
            } else {
                return coffeeResource.content().then(coffee.compile);
            }
        }
    });
}

module.exports = {
    name: "buster-coffee",

    configure: function (config) {
        if (config.environment != "node") {
            config.on("load:resources", function (resourceSet) {
                var paths = resourceSet.loadPath.paths();
                resourceSet.loadPath.clear();
                paths.forEach(function (path) {
                    if (/\.coffee$/.test(path)) {
                        var jsPath = path + ".js";
                        compileCoffeeResource(resourceSet, path, jsPath);
                        resourceSet.loadPath.append(jsPath);
                    } else {
                        resourceSet.loadPath.append(path);
                    }
                });
            });
        }
    }
};
<|endoftext|>


<commit_before>var shellwords = require('shellwords');
var cp = require('child_process');
var semver = require('semver');
var path = require('path');
var url = require('url');
var os = require('os');
var fs = require('fs');

function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

module.exports.clone = clone;

var escapeQuotes = function(str) {
  if (typeof str === 'string') {
    return str.replace(/(["$`\\])/g, '\\$1');
  } else {
    return str;
  }
};

var inArray = function(arr, val) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === val) {
      return true;
    }
  }
  return false;
};

var notifySendFlags = {
  u: 'urgency',
  urgency: 'urgency',
  t: 'expire-time',
  e: 'expire-time',
  expire: 'expire-time',
  'expire-time': 'expire-time',
  i: 'icon',
  icon: 'icon',
  c: 'category',
  category: 'category',
  subtitle: 'category',
  h: 'hint',
  hint: 'hint'
};

module.exports.command = function(notifier, options, cb) {
  notifier = shellwords.escape(notifier);
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (command):');
    console.info('[notifier path]', notifier);
    console.info('[notifier options]', options.join(' '));
  }

  return cp.exec(notifier + ' ' + options.join(' '), function(
    error,
    stdout,
    stderr
  ) {
    if (error) return cb(error);
    cb(stderr, stdout);
  });
};

module.exports.fileCommand = function(notifier, options, cb) {
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (fileCommand):');
    console.info('[notifier path]', notifier);
    console.info('[notifier options]', options.join(' '));
  }

  return cp.execFile(notifier, options, function(error, stdout, stderr) {
    if (error) return cb(error, stdout);
    cb(stderr, stdout);
  });
};

module.exports.fileCommandJson = function(notifier, options, cb) {
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (fileCommandJson):');
    console.info('[notifier path]', notifier);
    console.info('[notifier options]', options.join(' '));
  }
  return cp.execFile(notifier, options, function(error, stdout, stderr) {
    if (error) return cb(error, stdout);

    try {
      var data = JSON.parse(stdout);
      cb(stderr, data);
    } catch (e) {
      cb(e, stdout);
    }
  });
};

module.exports.immediateFileCommand = function(notifier, options, cb) {
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (notifier):');
    console.info('[notifier path]', notifier);
  }

  notifierExists(notifier, function(exists) {
    if (!exists) {
      return cb(new Error('Notifier (' + notifier + ') not found on system.'));
    }
    cp.execFile(notifier, options);
    cb();
  });
};

function notifierExists(notifier, cb) {
  return fs.stat(notifier, function(err, stat) {
    if (!err) return cb(stat.isFile());

    // Check if Windows alias
    if (path.extname(notifier)) {
      // Has extentioon, no need to check more
      return cb(false);
    }

    // Check if there is an exe file in the directory
    return fs.stat(notifier + '.exe', function(err, stat) {
      if (err) return cb(false);
      cb(stat.isFile());
    });
  });
}

var mapAppIcon = function(options) {
  if (options.appIcon) {
    options.icon = options.appIcon;
    delete options.appIcon;
  }

  return options;
};

var mapText = function(options) {
  if (options.text) {
    options.message = options.text;
    delete options.text;
  }

  return options;
};

var mapIconShorthand = function(options) {
  if (options.i) {
    options.icon = options.i;
    delete options.i;
  }

  return options;
};

module.exports.mapToNotifySend = function(options) {
  options = mapAppIcon(options);
  options = mapText(options);

  for (var key in options) {
    if (key === 'message' || key === 'title') continue;
    if (options.hasOwnProperty(key) && notifySendFlags[key] !== key) {
      options[notifySendFlags[key]] = options[key];
      delete options[key];
    }
  }

  return options;
};

module.exports.mapToGrowl = function(options) {
  options = mapAppIcon(options);
  options = mapIconShorthand(options);
  options = mapText(options);

  if (options.icon && !Buffer.isBuffer(options.icon)) {
    try {
      options.icon = fs.readFileSync(options.icon);
    } catch (ex) {
    }
  }

  return options;
};

module.exports.mapToMac = function(options) {
  options = mapIconShorthand(options);
  options = mapText(options);

  if (options.icon) {
    options.appIcon = options.icon;
    delete options.icon;
  }

  if (options.sound === true) {
    options.sound = 'Bottle';
  }

  if (options.sound === false) {
    delete options.sound;
  }

  if (options.wait === true) {
    if (!options.timeout) {
      options.timeout = 5;
    }
    delete options.wait;
  }

  options.json = true;
  return options;
};

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]';
}

function noop() {
}
module.exports.actionJackerDecorator = function(emitter, options, fn, mapper) {
  options = clone(options);
  fn = fn || noop;

  if (typeof fn !== 'function') {
    throw new TypeError(
      'The second argument must be a function callback. You have passed ' +
        typeof fn
    );
  }

  return function(err, data) {
    var resultantData = data;
    var metadata = {};
    // Allow for extra data if resultantData is an object
    if (resultantData && typeof resultantData === 'object') {
      metadata = resultantData;
      resultantData = resultantData.activationType;
    }

    // Sanitize the data
    if (resultantData) {
      resultantData = resultantData.toLowerCase().trim();
      if (resultantData.match(/^activate|clicked$/)) {
        resultantData = 'activate';
      }
    }

    fn.apply(emitter, [ err, resultantData, metadata ]);
    if (err || !mapper || !resultantData) return;

    var key = mapper(resultantData);
    if (!key) return;
    emitter.emit(key, emitter, options, metadata);
  };
};

module.exports.constructArgumentList = function(options, extra) {
  var args = [];
  extra = extra || {};

  // Massive ugly setup. Default args
  var initial = extra.initial || [];
  var keyExtra = extra.keyExtra || '';
  var allowedArguments = extra.allowedArguments || [];
  var noEscape = extra.noEscape !== void 0;
  var checkForAllowed = extra.allowedArguments !== void 0;
  var explicitTrue = !!extra.explicitTrue;
  var wrapper = extra.wrapper === void 0 ? '"' : extra.wrapper;

  var escapeFn = function(arg) {
    if (isArray(arg)) {
      return removeNewLines(
        arg.map(function(current) {
          return '"' + escapeQuotes(current) + '"';
        }).join(',')
      );
    }

    if (!noEscape) {
      arg = escapeQuotes(arg);
    }
    if (typeof arg === 'string') {
      arg = removeNewLines(arg);
    }
    return wrapper + arg + wrapper;
  };

  initial.forEach(function(val) {
    args.push(escapeFn(val));
  });
  for (var key in options) {
    if (
      options.hasOwnProperty(key) &&
        (!checkForAllowed || inArray(allowedArguments, key))
    ) {
      if (explicitTrue && options[key] === true) {
        args.push('-' + keyExtra + key);
      } else if (explicitTrue && options[key] === false) continue;
      else args.push('-' + keyExtra + key, escapeFn(options[key]));
    }
  }
  return args;
};

function removeNewLines(str) {
  return str.replace(/\r?\n/g, '\\n');
}

module.exports.mapToWin8 = function(options) {
  options = mapAppIcon(options);
  options = mapText(options);

  if (options.icon) {
    if (/^file:\/+/.test(options.icon)) {
      // should parse file protocol URL to path
      options.p = url.parse(options.icon).pathname
        .replace(/^\/(\w:\/)/, '$1')
        .replace(/\//g, '\\');
    } else {
      options.p = options.icon;
    }
    delete options.icon;
  }

  if (options.message) {
    // Remove escape char to debug "HRESULT : 0xC00CE508" exception
    options.m = options.message.replace(/\x1b/g, '');
    delete options.message;
  }

  if (options.title) {
    options.t = options.title;
    delete options.title;
  }

  if (options.quiet || options.silent) {
    options.silent = options.quiet || options.silent;
    delete options.quiet;
  }

  if (options.sound) {
    delete options.q;
    delete options.sound;
  }

  if (options.wait) {
    options.w = options.wait;
    delete options.wait;
  }

  return options;
};

module.exports.mapToNotifu = function(options) {
  options = mapAppIcon(options);
  options = mapText(options);

  if (options.icon) {
    options.i = options.icon;
    delete options.icon;
  }

  if (options.message) {
    options.m = options.message;
    delete options.message;
  }

  if (options.title) {
    options.p = options.title;
    delete options.title;
  }

  if (options.time) {
    options.d = options.time;
    delete options.time;
  }

  if (options.q !== false) {
    options.q = true;
  } else {
    delete options.q;
  }

  if (options.quiet === false) {
    delete options.q;
    delete options.quiet;
  }

  if (options.sound) {
    delete options.q;
    delete options.sound;
  }

  if (options.t) {
    options.d = options.t;
    delete options.t;
  }

  if (options.type) {
    options.t = sanitizeNotifuTypeArgument(options.type);
    delete options.type;
  }

  return options;
};

module.exports.isMac = function() {
  return os.type() === 'Darwin';
};

module.exports.isMountainLion = function() {
  return os.type() === 'Darwin' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '>=12.0.0');
};

module.exports.isWin8 = function() {
  return os.type() === 'Windows_NT' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '>=6.2.9200');
};

module.exports.isLessThanWin8 = function() {
  return os.type() === 'Windows_NT' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '<6.2.9200');
};

function garanteeSemverFormat(version) {
  if (version.split('.').length === 2) {
    version += '.0';
  }
  return version;
}

function sanitizeNotifuTypeArgument(type) {
  if (typeof type === 'string' || type instanceof String) {
    if (type.toLowerCase() === 'info') return 'info';
    if (type.toLowerCase() === 'warn') return 'warn';
    if (type.toLowerCase() === 'error') return 'error';
  }

  return 'info';
}
<commit_msg>#123 Fixes new lines on windows<commit_after>var shellwords = require('shellwords');
var cp = require('child_process');
var semver = require('semver');
var path = require('path');
var url = require('url');
var os = require('os');
var fs = require('fs');

function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

module.exports.clone = clone;

var escapeQuotes = function(str) {
  if (typeof str === 'string') {
    return str.replace(/(["$`\\])/g, '\\$1');
  } else {
    return str;
  }
};

var inArray = function(arr, val) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === val) {
      return true;
    }
  }
  return false;
};

var notifySendFlags = {
  u: 'urgency',
  urgency: 'urgency',
  t: 'expire-time',
  e: 'expire-time',
  expire: 'expire-time',
  'expire-time': 'expire-time',
  i: 'icon',
  icon: 'icon',
  c: 'category',
  category: 'category',
  subtitle: 'category',
  h: 'hint',
  hint: 'hint'
};

module.exports.command = function(notifier, options, cb) {
  notifier = shellwords.escape(notifier);
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (command):');
    console.info('[notifier path]', notifier);
    console.info('[notifier options]', options.join(' '));
  }

  return cp.exec(notifier + ' ' + options.join(' '), function(
    error,
    stdout,
    stderr
  ) {
    if (error) return cb(error);
    cb(stderr, stdout);
  });
};

module.exports.fileCommand = function(notifier, options, cb) {
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (fileCommand):');
    console.info('[notifier path]', notifier);
    console.info('[notifier options]', options.join(' '));
  }

  return cp.execFile(notifier, options, function(error, stdout, stderr) {
    if (error) return cb(error, stdout);
    cb(stderr, stdout);
  });
};

module.exports.fileCommandJson = function(notifier, options, cb) {
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (fileCommandJson):');
    console.info('[notifier path]', notifier);
    console.info('[notifier options]', options.join(' '));
  }
  return cp.execFile(notifier, options, function(error, stdout, stderr) {
    if (error) return cb(error, stdout);

    try {
      var data = JSON.parse(stdout);
      cb(stderr, data);
    } catch (e) {
      cb(e, stdout);
    }
  });
};

module.exports.immediateFileCommand = function(notifier, options, cb) {
  if (process.env.DEBUG) {
    console.info('node-notifier debug info (notifier):');
    console.info('[notifier path]', notifier);
  }

  notifierExists(notifier, function(exists) {
    if (!exists) {
      return cb(new Error('Notifier (' + notifier + ') not found on system.'));
    }
    cp.execFile(notifier, options);
    cb();
  });
};

function notifierExists(notifier, cb) {
  return fs.stat(notifier, function(err, stat) {
    if (!err) return cb(stat.isFile());

    // Check if Windows alias
    if (path.extname(notifier)) {
      // Has extentioon, no need to check more
      return cb(false);
    }

    // Check if there is an exe file in the directory
    return fs.stat(notifier + '.exe', function(err, stat) {
      if (err) return cb(false);
      cb(stat.isFile());
    });
  });
}

var mapAppIcon = function(options) {
  if (options.appIcon) {
    options.icon = options.appIcon;
    delete options.appIcon;
  }

  return options;
};

var mapText = function(options) {
  if (options.text) {
    options.message = options.text;
    delete options.text;
  }

  return options;
};

var mapIconShorthand = function(options) {
  if (options.i) {
    options.icon = options.i;
    delete options.i;
  }

  return options;
};

module.exports.mapToNotifySend = function(options) {
  options = mapAppIcon(options);
  options = mapText(options);

  for (var key in options) {
    if (key === 'message' || key === 'title') continue;
    if (options.hasOwnProperty(key) && notifySendFlags[key] !== key) {
      options[notifySendFlags[key]] = options[key];
      delete options[key];
    }
  }

  return options;
};

module.exports.mapToGrowl = function(options) {
  options = mapAppIcon(options);
  options = mapIconShorthand(options);
  options = mapText(options);

  if (options.icon && !Buffer.isBuffer(options.icon)) {
    try {
      options.icon = fs.readFileSync(options.icon);
    } catch (ex) {
    }
  }

  return options;
};

module.exports.mapToMac = function(options) {
  options = mapIconShorthand(options);
  options = mapText(options);

  if (options.icon) {
    options.appIcon = options.icon;
    delete options.icon;
  }

  if (options.sound === true) {
    options.sound = 'Bottle';
  }

  if (options.sound === false) {
    delete options.sound;
  }

  if (options.wait === true) {
    if (!options.timeout) {
      options.timeout = 5;
    }
    delete options.wait;
  }

  options.json = true;
  return options;
};

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]';
}

function noop() {
}
module.exports.actionJackerDecorator = function(emitter, options, fn, mapper) {
  options = clone(options);
  fn = fn || noop;

  if (typeof fn !== 'function') {
    throw new TypeError(
      'The second argument must be a function callback. You have passed ' +
        typeof fn
    );
  }

  return function(err, data) {
    var resultantData = data;
    var metadata = {};
    // Allow for extra data if resultantData is an object
    if (resultantData && typeof resultantData === 'object') {
      metadata = resultantData;
      resultantData = resultantData.activationType;
    }

    // Sanitize the data
    if (resultantData) {
      resultantData = resultantData.toLowerCase().trim();
      if (resultantData.match(/^activate|clicked$/)) {
        resultantData = 'activate';
      }
    }

    fn.apply(emitter, [ err, resultantData, metadata ]);
    if (err || !mapper || !resultantData) return;

    var key = mapper(resultantData);
    if (!key) return;
    emitter.emit(key, emitter, options, metadata);
  };
};

module.exports.constructArgumentList = function(options, extra) {
  var args = [];
  extra = extra || {};

  // Massive ugly setup. Default args
  var initial = extra.initial || [];
  var keyExtra = extra.keyExtra || '';
  var allowedArguments = extra.allowedArguments || [];
  var noEscape = extra.noEscape !== void 0;
  var checkForAllowed = extra.allowedArguments !== void 0;
  var explicitTrue = !!extra.explicitTrue;
  var wrapper = extra.wrapper === void 0 ? '"' : extra.wrapper;

  var escapeFn = function(arg) {
    if (isArray(arg)) {
      return removeNewLines(
        arg.map(function(current) {
          return '"' + escapeQuotes(current) + '"';
        }).join(',')
      );
    }

    if (!noEscape) {
      arg = escapeQuotes(arg);
    }
    if (typeof arg === 'string') {
      arg = removeNewLines(arg);
    }
    return wrapper + arg + wrapper;
  };

  initial.forEach(function(val) {
    args.push(escapeFn(val));
  });
  for (var key in options) {
    if (
      options.hasOwnProperty(key) &&
        (!checkForAllowed || inArray(allowedArguments, key))
    ) {
      if (explicitTrue && options[key] === true) {
        args.push('-' + keyExtra + key);
      } else if (explicitTrue && options[key] === false) continue;
      else args.push('-' + keyExtra + key, escapeFn(options[key]));
    }
  }
  return args;
};

function removeNewLines(str) {
  var excapedNewline = process.platform === 'win32' ? '\\r\\n' : '\\n';
  return str.replace(/\r?\n/g, excapedNewline);
}

module.exports.mapToWin8 = function(options) {
  options = mapAppIcon(options);
  options = mapText(options);

  if (options.icon) {
    if (/^file:\/+/.test(options.icon)) {
      // should parse file protocol URL to path
      options.p = url.parse(options.icon).pathname
        .replace(/^\/(\w:\/)/, '$1')
        .replace(/\//g, '\\');
    } else {
      options.p = options.icon;
    }
    delete options.icon;
  }

  if (options.message) {
    // Remove escape char to debug "HRESULT : 0xC00CE508" exception
    options.m = options.message.replace(/\x1b/g, '');
    delete options.message;
  }

  if (options.title) {
    options.t = options.title;
    delete options.title;
  }

  if (options.quiet || options.silent) {
    options.silent = options.quiet || options.silent;
    delete options.quiet;
  }

  if (options.sound) {
    delete options.q;
    delete options.sound;
  }

  if (options.wait) {
    options.w = options.wait;
    delete options.wait;
  }

  return options;
};

module.exports.mapToNotifu = function(options) {
  options = mapAppIcon(options);
  options = mapText(options);

  if (options.icon) {
    options.i = options.icon;
    delete options.icon;
  }

  if (options.message) {
    options.m = options.message;
    delete options.message;
  }

  if (options.title) {
    options.p = options.title;
    delete options.title;
  }

  if (options.time) {
    options.d = options.time;
    delete options.time;
  }

  if (options.q !== false) {
    options.q = true;
  } else {
    delete options.q;
  }

  if (options.quiet === false) {
    delete options.q;
    delete options.quiet;
  }

  if (options.sound) {
    delete options.q;
    delete options.sound;
  }

  if (options.t) {
    options.d = options.t;
    delete options.t;
  }

  if (options.type) {
    options.t = sanitizeNotifuTypeArgument(options.type);
    delete options.type;
  }

  return options;
};

module.exports.isMac = function() {
  return os.type() === 'Darwin';
};

module.exports.isMountainLion = function() {
  return os.type() === 'Darwin' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '>=12.0.0');
};

module.exports.isWin8 = function() {
  return os.type() === 'Windows_NT' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '>=6.2.9200');
};

module.exports.isLessThanWin8 = function() {
  return os.type() === 'Windows_NT' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '<6.2.9200');
};

function garanteeSemverFormat(version) {
  if (version.split('.').length === 2) {
    version += '.0';
  }
  return version;
}

function sanitizeNotifuTypeArgument(type) {
  if (typeof type === 'string' || type instanceof String) {
    if (type.toLowerCase() === 'info') return 'info';
    if (type.toLowerCase() === 'warn') return 'warn';
    if (type.toLowerCase() === 'error') return 'error';
  }

  return 'info';
}
<|endoftext|>


<commit_before>jest.setTimeout(10000)<commit_msg>Fix StandardJS code style<commit_after>jest.setTimeout(10000) // eslint-disable-line
<|endoftext|>


<commit_before>'use strict';

/* global CloudCmd */

const {eachSeries} = require('execon');
const wraptile = require('wraptile/legacy');

const DOM = require('.');
const load = require('./load');
const Images = require('./images');

const {FS} = require('../../common/cloudfunc');
const {CurrentInfo} = DOM;

const onEnd = wraptile(_onEnd);
const loadFile = wraptile(_loadFile);

module.exports = (dir, files) => {
    if (!files) {
        files = dir;
        dir = CurrentInfo.dirPath;
    }

    const n = files.length;

    if (!n)
        return;

    const array = [...files];
    const {name} = files[0];

    eachSeries(array, loadFile(dir, n), onEnd(name));
};

function _onEnd(name) {
    CloudCmd.refresh(null, () => {
        DOM.setCurrentByName(name);
    });
}

function _loadFile(dir, n, file, callback) {
    let i = 0;

    const name = file.name;
    const path = dir + name;
    const {PREFIX_URL} = CloudCmd;
    const api = PREFIX_URL + FS;

    const percent = (i, n, per = 100) => {
        return Math.round(i * per / n);
    };

    const step = (n) => 100 / n;

    ++i;

    load.put(api + path, file)
        .on('end', callback)
        .on('progress', (count) => {
            const max = step(n);
            const value = (i - 1) * max + percent(count, 100, max);

            Images.show.load('top');
            Images.setProgress(Math.round(value));
        });
}

<commit_msg>fix(upload-files) upload a file to an empty root directory (#113)<commit_after>'use strict';

/* global CloudCmd */

const {eachSeries} = require('execon');
const wraptile = require('wraptile/legacy');

const DOM = require('.');
const load = require('./load');
const Images = require('./images');

const {FS} = require('../../common/cloudfunc');

const onEnd = wraptile(_onEnd);
const loadFile = wraptile(_loadFile);

const {
    getCurrentDirPath: getPathWhenRootEmpty
} = DOM;

module.exports = (dir, files) => {
    if (!files) {
        files = dir;
        dir = getPathWhenRootEmpty();
    }

    const n = files.length;

    if (!n)
        return;

    const array = [...files];
    const {name} = files[0];

    eachSeries(array, loadFile(dir, n), onEnd(name));
};

function _onEnd(name) {
    CloudCmd.refresh(null, () => {
        DOM.setCurrentByName(name);
    });
}

function _loadFile(dir, n, file, callback) {
    let i = 0;

    const name = file.name;
    const path = dir + name;
    const {PREFIX_URL} = CloudCmd;
    const api = PREFIX_URL + FS;

    const percent = (i, n, per = 100) => {
        return Math.round(i * per / n);
    };

    const step = (n) => 100 / n;

    ++i;

    load.put(api + path, file)
        .on('end', callback)
        .on('progress', (count) => {
            const max = step(n);
            const value = (i - 1) * max + percent(count, 100, max);

            Images.show.load('top');
            Images.setProgress(Math.round(value));
        });
}

<|endoftext|>


<commit_before>/**
 * Router for /
 */
'use strict';

var mongoose = require('../controller/mongo.js');
var fs = require('fs');

var models = {
  "view": mongoose.model('view', require('../schemas/view.js')),
  "page": mongoose.model('page', require('../schemas/page.js'))
};

var express = require('express');
var reader = require('../controller/templateReader.js');
var router = express.Router();

router.get('/getList', function(req, res) {
  reader.getAll(function(templates) {
    res.json(templates);
  });
});

router.post('/batch/:model', function(req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  if (!req.body) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].find({ _id : { $in : req.body } }).exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      res.json(docs);
    }
  });
});

router.get('/html/:name', function (req, res) {

  if (!req.params.name) {
    res.sendStatus(400);
    return;
  }

  if(req.params.name === 'master') {
    fs.readFile('templates/master.handlebars', function(err, file) {
      if(err) {
        res.send(err);
        return;
      }
      res.send(file);
    });
  } else {
    fs.readFile('templates/partials/' + req.params.name +'.handlebars', function(err, file) {
      if(err) {
        res.send(err);
        return;
      }
      res.send(file);
    });
  }
});

router.get('/:model', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  models[req.params.model].find({}).exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      res.json(docs);
    }
  });

});

router.get('/:model/:id', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  if (!req.params.id) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].findOne({'_id':req.params.id}).exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      res.json(docs);
    }
  });

});

router.post('/:model', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  /*if (req.params.model === 'template') {
    res.sendStatus(403);
    return;
  }*/

  if (!req.body) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].create(req.body, function (err, docs) {
    if (err) {
      console.log(req.body);
      res.send(err);
    } else {
      res.json(docs);
    }
  });

});

router.put('/:model/:id', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  /*if (req.params.model === 'template') {
    res.sendStatus(403);
    return;
  }*/

  if (!req.body || !req.params.id) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].findOneAndUpdate({_id: req.params.id}, req.body, {new: true}, function (err, doc) {
    if (err) {
      res.send(err);
    } else {
      res.json(doc);
    }
  });

});

router.delete('/:model/:id', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  /*if (req.params.model === 'template') {
    res.sendStatus(403);
    return;
  }*/

  if (!req.params.id) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].findOneAndRemove({_id: req.params.id}, function (err, doc) {
    if (err) {
      res.send(err);
    } else {
      res.json(doc);
    }
  });

});

module.exports = router;<commit_msg>Add mini css delivery<commit_after>/**
 * Router for /
 */
'use strict';

var mongoose = require('../controller/mongo.js');
var fs = require('fs');

var models = {
  "view": mongoose.model('view', require('../schemas/view.js')),
  "page": mongoose.model('page', require('../schemas/page.js'))
};

var express = require('express');
var reader = require('../controller/templateReader.js');
var router = express.Router();

router.get('/getList', function(req, res) {
  reader.getAll(function(templates) {
    res.json(templates);
  });
});

router.post('/batch/:model', function(req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  if (!req.body) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].find({ _id : { $in : req.body } }).exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      res.json(docs);
    }
  });
});

router.get('/css', function (req, res) {
  fs.readFile('public/css/temp_style.min.css', function(err, file) {
    if(err) {
      res.send(err);
      return;
    }
    res.send(file);
  });
});

router.get('/html/:name', function (req, res) {

  if (!req.params.name) {
    res.sendStatus(400);
    return;
  }

  if(req.params.name === 'master') {
    fs.readFile('templates/master.handlebars', function(err, file) {
      if(err) {
        res.send(err);
        return;
      }
      res.send(file);
    });
  } else {
    fs.readFile('templates/partials/' + req.params.name +'.handlebars', function(err, file) {
      if(err) {
        res.send(err);
        return;
      }
      res.send(file);
    });
  }
});

router.get('/:model', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  models[req.params.model].find({}).exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      res.json(docs);
    }
  });

});

router.get('/:model/:id', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  if (!req.params.id) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].findOne({'_id':req.params.id}).exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      res.json(docs);
    }
  });

});

router.post('/:model', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  /*if (req.params.model === 'template') {
    res.sendStatus(403);
    return;
  }*/

  if (!req.body) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].create(req.body, function (err, docs) {
    if (err) {
      console.log(req.body);
      res.send(err);
    } else {
      res.json(docs);
    }
  });

});

router.put('/:model/:id', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  /*if (req.params.model === 'template') {
    res.sendStatus(403);
    return;
  }*/

  if (!req.body || !req.params.id) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].findOneAndUpdate({_id: req.params.id}, req.body, {new: true}, function (err, doc) {
    if (err) {
      res.send(err);
    } else {
      res.json(doc);
    }
  });

});

router.delete('/:model/:id', function (req, res) {

  var model = models[req.params.model] ? models[req.params.model] : null;

  if (!model) {
    res.sendStatus(404);
    return;
  }

  /*if (req.params.model === 'template') {
    res.sendStatus(403);
    return;
  }*/

  if (!req.params.id) {
    res.sendStatus(400);
    return;
  }

  models[req.params.model].findOneAndRemove({_id: req.params.id}, function (err, doc) {
    if (err) {
      res.send(err);
    } else {
      res.json(doc);
    }
  });

});

module.exports = router;<|endoftext|>


<commit_before>// # Utils package for `lookback:emails`

const fs = Npm.require('fs');
const Path = Npm.require('path');
const htmlToText = Npm.require('html-to-text');

const isDevEnv = process.env.NODE_ENV === 'development';
const minorVersion = parseInt(Meteor.release.split('.')[1], 10);

const isModernMeteor = minorVersion >= 3;

// since meteor 1.3 we no longer need meteor hacks just use the npm version
const sass = (function() {
  if (isModernMeteor) {
    try {
      return require('node-sass');
    } catch (ex) {} // eslint-disable-line no-empty
  } else if (Package['chrisbutler:node-sass']) {
    return Package['chrisbutler:node-sass'].sass;
  }

  return null;
})();

/**
 * Check if file exists
 * @param  {String} filePath
 * @return {Boolean}
 */
const fileExists = function (filePath) {
  try {
    return fs.statSync(filePath).isFile();
  }
  catch (err)
  {
      return false;
  }
}

const TAG = 'mailer-utils';

// This package assumes that assets (templates, SCSS, CSS ..) are
// stored in the `private` directory. Thanks to that, Meteor won't
// touch the HTML and CSS, which are non-JS files.
//
// However, since the file paths are screwed up when bundling and
// deploying Meteor apps, we need to set the BUNDLE_PATH env var
// to keep track of where the bundle lives.
//
// When deployed, set the `BUNDLE_PATH` env var to the location, perhaps:
//
//     /var/www/app/bundle
//
// For Modulus, you need to use the `APP_DIR` variable, which you do NOT need to set.
const developmentPrivateDir = () => {
  if (!isDevEnv) {
    return '';
  }

  // In development, using `pwd` is fine. Remove the .meteor/foo/bar stuff though.
  const reg = new RegExp(`${Path.sep}\.meteor.*`, 'g');
  const meteorRoot = process.cwd().replace(reg, '');
  return Path.join(meteorRoot, 'private');
};

const productionPrivateDir = () => {
  if (isDevEnv) {
    return '';
  }

  const meteorRoot = fs.realpathSync(`${process.cwd()}/../`);
  return fs.realpathSync(`${meteorRoot}/../`);
};

const privateDir = process.env.BUNDLE_PATH || productionPrivateDir();

let ROOT = privateDir && Path.join(privateDir, 'programs', 'server', 'assets', 'app');

ROOT = ROOT || developmentPrivateDir();

Utils = {
  // Takes an HTML string and outputs a text version of it. Catches and logs errors.
  toText(html, opts = {}) {
    try {
      return htmlToText.fromString(html, opts);
    } catch (ex) {
      return Utils.Logger.error(`Could not make plain-text version from html: ${ex.message}`);
    }
  },

  capitalizeFirstChar(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  // Set up a logger to use through `Utils.Logger`. Verify
  // that necessary methods exists on the injected `logger` and
  // fallback if not.
  setupLogger(logger, opts) {
    const defaults = {
      suppressInfo: false
    };

    opts = _.extend({}, defaults, opts);

    const res = ['info', 'warn', 'error'].map(method => {
      if (!_.has(logger, method)) {
        console.warn(`The injected logger must support the ${method} method.`);
        return false;
      }
      return true;
    });

    if (_.compact(res).length === 0) {
      console.warn('Falling back to the native logger.');
      this.Logger = console;
    } else {
      this.Logger = logger;
    }

    // Just do a noop for the `info` method
    // if we're in silent mode.
    if (opts.suppressInfo === true) {
      this.Logger.info = function() {};
    }
  },

  joinUrl(base, path) {
    // Remove any trailing slashes and add front slash if not exist already.
    const root = base.replace(/\/$/, '');

    if (!/^\//.test(path)) {
      path = `/${path}`;
    }

    return root + path;
  },

  addStylesheets(template, html, juiceOpts = {}) {
    check(template, Match.ObjectIncluding({
      name: String,
      css: Match.Optional(String),
      scss: Match.Optional(String)
    }));

    try {
      let content = html;

      if (template.css) {
        const css = Utils.readFile(template.css);
        content = juice.inlineContent(content, css, juiceOpts);
      }

      if (template.scss) {
        const scss = Utils.toCSS(template.scss);
        content = juice.inlineContent(content, scss, juiceOpts);
      }

      return content;

    } catch (ex) {
      Utils.Logger.error(`Could not add CSS to ${template.name}: ${ex.message}`, TAG);
      return html;
    }
  },

  addDoctype(html) {
    return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n${html}`;
  },

  readFile(relativePathFromApp) {
    let file
    if (Meteor.isAppTest
      || Meteor.isTest) {
      // note:
      //  * this DOES WORK with Meteor.isTest (=unit test mode)
      //  * Meteor.isAppTest is NOT TESTED yet (=in-app test mode)
      //
      // background-info: we had NO luck with "Assets.absoluteFilePath(relativePathFromApp)",
      //  so lets build the path ourselves.
      //  see discussion https://github.com/lookback/meteor-emails/issues/76
      file = Path.join(process.cwd(), 'assets', 'app', relativePathFromApp);
    } else {
      // = standard mode (development || production)
      file = Path.join(ROOT, relativePathFromApp);
    }

    try {
      return fs.readFileSync(file, {
        encoding: 'utf8'
      });
    } catch (ex) {
      throw new Meteor.Error(500, `Could not find file: ${file}`, ex.message);
    }
  },

  // Take a path to a SCSS file and compiles it to CSS with `node-sass`.
  toCSS(scss) {
    if (!sass) {
      const packageToRecommend = isModernMeteor
        ? 'Please run `meteor npm install --save node-sass` in your app to add sass support.'
        : 'Please run `meteor add chrisbutler:node-sass` to add sass support.';

      Utils.Logger.warn(`Could not find sass module. Sass support is opt-in since lookback:emails@0.5.0.

${packageToRecommend}`, TAG);
      return Utils.readFile(scss);
    }

    let file
    if (Meteor.isAppTest
      || Meteor.isTest) {
      // note:
      //  * this DOES WORK with Meteor.isTest (=unit test mode)
      //  * Meteor.isAppTest is NOT TESTED yet (=in-app test mode)
      file = Path.join(process.cwd(), 'assets', 'app', scss);
    } else {
      // = standard mode (development || production)
      file = Path.join(ROOT, scss);
    }

    if (fileExists(file)) {
      console.log('SCSS EXISTS')
      try {
        return sass.renderSync({
          file: file,
          sourceMap: false
        }).css.toString();
      } catch (ex) {
        console.error(`Sass failed to compile: ${ex.message}`);
        console.error(`In ${ex.file || scss} at line ${ex.line}, column ${ex.column}`);
      }
    }
    return '';  // fallback: on error, or if file does NOT exist
  }
};
<commit_msg>removed log statement<commit_after>// # Utils package for `lookback:emails`

const fs = Npm.require('fs');
const Path = Npm.require('path');
const htmlToText = Npm.require('html-to-text');

const isDevEnv = process.env.NODE_ENV === 'development';
const minorVersion = parseInt(Meteor.release.split('.')[1], 10);

const isModernMeteor = minorVersion >= 3;

// since meteor 1.3 we no longer need meteor hacks just use the npm version
const sass = (function() {
  if (isModernMeteor) {
    try {
      return require('node-sass');
    } catch (ex) {} // eslint-disable-line no-empty
  } else if (Package['chrisbutler:node-sass']) {
    return Package['chrisbutler:node-sass'].sass;
  }

  return null;
})();

/**
 * Check if file exists
 * @param  {String} filePath
 * @return {Boolean}
 */
const fileExists = function (filePath) {
  try {
    return fs.statSync(filePath).isFile();
  }
  catch (err)
  {
      return false;
  }
}

const TAG = 'mailer-utils';

// This package assumes that assets (templates, SCSS, CSS ..) are
// stored in the `private` directory. Thanks to that, Meteor won't
// touch the HTML and CSS, which are non-JS files.
//
// However, since the file paths are screwed up when bundling and
// deploying Meteor apps, we need to set the BUNDLE_PATH env var
// to keep track of where the bundle lives.
//
// When deployed, set the `BUNDLE_PATH` env var to the location, perhaps:
//
//     /var/www/app/bundle
//
// For Modulus, you need to use the `APP_DIR` variable, which you do NOT need to set.
const developmentPrivateDir = () => {
  if (!isDevEnv) {
    return '';
  }

  // In development, using `pwd` is fine. Remove the .meteor/foo/bar stuff though.
  const reg = new RegExp(`${Path.sep}\.meteor.*`, 'g');
  const meteorRoot = process.cwd().replace(reg, '');
  return Path.join(meteorRoot, 'private');
};

const productionPrivateDir = () => {
  if (isDevEnv) {
    return '';
  }

  const meteorRoot = fs.realpathSync(`${process.cwd()}/../`);
  return fs.realpathSync(`${meteorRoot}/../`);
};

const privateDir = process.env.BUNDLE_PATH || productionPrivateDir();

let ROOT = privateDir && Path.join(privateDir, 'programs', 'server', 'assets', 'app');

ROOT = ROOT || developmentPrivateDir();

Utils = {
  // Takes an HTML string and outputs a text version of it. Catches and logs errors.
  toText(html, opts = {}) {
    try {
      return htmlToText.fromString(html, opts);
    } catch (ex) {
      return Utils.Logger.error(`Could not make plain-text version from html: ${ex.message}`);
    }
  },

  capitalizeFirstChar(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  // Set up a logger to use through `Utils.Logger`. Verify
  // that necessary methods exists on the injected `logger` and
  // fallback if not.
  setupLogger(logger, opts) {
    const defaults = {
      suppressInfo: false
    };

    opts = _.extend({}, defaults, opts);

    const res = ['info', 'warn', 'error'].map(method => {
      if (!_.has(logger, method)) {
        console.warn(`The injected logger must support the ${method} method.`);
        return false;
      }
      return true;
    });

    if (_.compact(res).length === 0) {
      console.warn('Falling back to the native logger.');
      this.Logger = console;
    } else {
      this.Logger = logger;
    }

    // Just do a noop for the `info` method
    // if we're in silent mode.
    if (opts.suppressInfo === true) {
      this.Logger.info = function() {};
    }
  },

  joinUrl(base, path) {
    // Remove any trailing slashes and add front slash if not exist already.
    const root = base.replace(/\/$/, '');

    if (!/^\//.test(path)) {
      path = `/${path}`;
    }

    return root + path;
  },

  addStylesheets(template, html, juiceOpts = {}) {
    check(template, Match.ObjectIncluding({
      name: String,
      css: Match.Optional(String),
      scss: Match.Optional(String)
    }));

    try {
      let content = html;

      if (template.css) {
        const css = Utils.readFile(template.css);
        content = juice.inlineContent(content, css, juiceOpts);
      }

      if (template.scss) {
        const scss = Utils.toCSS(template.scss);
        content = juice.inlineContent(content, scss, juiceOpts);
      }

      return content;

    } catch (ex) {
      Utils.Logger.error(`Could not add CSS to ${template.name}: ${ex.message}`, TAG);
      return html;
    }
  },

  addDoctype(html) {
    return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n${html}`;
  },

  readFile(relativePathFromApp) {
    let file
    if (Meteor.isAppTest
      || Meteor.isTest) {
      // note:
      //  * this DOES WORK with Meteor.isTest (=unit test mode)
      //  * Meteor.isAppTest is NOT TESTED yet (=in-app test mode)
      //
      // background-info: we had NO luck with "Assets.absoluteFilePath(relativePathFromApp)",
      //  so lets build the path ourselves.
      //  see discussion https://github.com/lookback/meteor-emails/issues/76
      file = Path.join(process.cwd(), 'assets', 'app', relativePathFromApp);
    } else {
      // = standard mode (development || production)
      file = Path.join(ROOT, relativePathFromApp);
    }

    try {
      return fs.readFileSync(file, {
        encoding: 'utf8'
      });
    } catch (ex) {
      throw new Meteor.Error(500, `Could not find file: ${file}`, ex.message);
    }
  },

  // Take a path to a SCSS file and compiles it to CSS with `node-sass`.
  toCSS(scss) {
    if (!sass) {
      const packageToRecommend = isModernMeteor
        ? 'Please run `meteor npm install --save node-sass` in your app to add sass support.'
        : 'Please run `meteor add chrisbutler:node-sass` to add sass support.';

      Utils.Logger.warn(`Could not find sass module. Sass support is opt-in since lookback:emails@0.5.0.

${packageToRecommend}`, TAG);
      return Utils.readFile(scss);
    }

    let file
    if (Meteor.isAppTest
      || Meteor.isTest) {
      // note:
      //  * this DOES WORK with Meteor.isTest (=unit test mode)
      //  * Meteor.isAppTest is NOT TESTED yet (=in-app test mode)
      file = Path.join(process.cwd(), 'assets', 'app', scss);
    } else {
      // = standard mode (development || production)
      file = Path.join(ROOT, scss);
    }

    if (fileExists(file)) {
      try {
        return sass.renderSync({
          file: file,
          sourceMap: false
        }).css.toString();
      } catch (ex) {
        console.error(`Sass failed to compile: ${ex.message}`);
        console.error(`In ${ex.file || scss} at line ${ex.line}, column ${ex.column}`);
      }
    }
    return '';  // fallback: on error, or if file does NOT exist
  }
};
<|endoftext|>


<commit_before>// API for activity spam checker
//
// Copyright 2011, 2012 StatusNet Inc.
//
// 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.

// Training and measuring values

var Tokenizer = require('../lib/tokenizer').Tokenizer,
    SpamFilter = require('../lib/spamfilter').SpamFilter;

exports.thisIsSpam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {
        if (!authenticated) {
            res.writeHead(401, {'Content-Type': 'application/json'});
            res.end(JSON.stringify("Not authorized"));
            return;
        }
        SpamFilter.train('spam', req.body, function(err, trainrec) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json'});
                res.end(JSON.stringify({error: err.message}));
            } else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(trainrec));
            }
        });
    });
};

exports.thisIsHam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {
        if (!authenticated) {
            res.writeHead(401, {'Content-Type': 'application/json'});
            res.end(JSON.stringify("Not authorized"));
            return;
        }
        SpamFilter.train('ham', req.body, function(err, trainrec) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json'});
                res.end(JSON.stringify({error: err.message}));
            } else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(trainrec));
            }
        });
    });
};

var uniq = function(arr) {
    var newArr = [], i;

    for (i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i]);
        }
    }

    return newArr;
};

exports.isThisSpam = function(req, res, next) {

    req.authenticate(['oauth'], function(error, authenticated) {

        if (!authenticated) {
            res.writeHead(401, {'Content-Type': 'application/json'});
            res.end(JSON.stringify("Not authorized"));
            return;
        }

        var tokens = uniq(Tokenizer.tokenize(req.body));

        SpamFilter.test(tokens, function(err, decision) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(err.message));
            } else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(decision));
            }
        });
    });
};

exports.testTokenize = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {

        if (error) {
            console.log(error);
            res.writeHead(500, {'Content-Type': 'application/json'});
            res.end(JSON.stringify(err.message));
            return;
        }

        if (authenticated) {
            var tokens = Tokenizer.tokenize(req.body);
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end(JSON.stringify(tokens));
        }
    });
};
<commit_msg>problem with double-headers<commit_after>// API for activity spam checker
//
// Copyright 2011, 2012 StatusNet Inc.
//
// 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.

// Training and measuring values

var Tokenizer = require('../lib/tokenizer').Tokenizer,
    SpamFilter = require('../lib/spamfilter').SpamFilter;

exports.thisIsSpam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {
	if (error) {
	    return;
	}
        SpamFilter.train('spam', req.body, function(err, trainrec) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json'});
                res.end(JSON.stringify({error: err.message}));
            } else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(trainrec));
            }
        });
    });
};

exports.thisIsHam = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {
	if (error) {
	    return;
	}
        SpamFilter.train('ham', req.body, function(err, trainrec) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json'});
                res.end(JSON.stringify({error: err.message}));
            } else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(trainrec));
            }
        });
    });
};

var uniq = function(arr) {
    var newArr = [], i;

    for (i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i]);
        }
    }

    return newArr;
};

exports.isThisSpam = function(req, res, next) {

    req.authenticate(['oauth'], function(error, authenticated) {

	if (error) {
	    return;
	}

        var tokens = uniq(Tokenizer.tokenize(req.body));

        SpamFilter.test(tokens, function(err, decision) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(err.message));
            } else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify(decision));
            }
        });
    });
};

exports.testTokenize = function(req, res, next) {
    req.authenticate(['oauth'], function(error, authenticated) {

	if (error) {
	    return;
	}

        if (authenticated) {
            var tokens = Tokenizer.tokenize(req.body);
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end(JSON.stringify(tokens));
        }
    });
};
<|endoftext|>


<commit_before>import Vue from 'vue'
import Password from '../components/user/Password.vue'
Vue.use(require('vue-resource'));

/* eslint-disable no-new */
new Vue({
  el: 'body',
  components: { Password }
})

require('bootstrap/dist/css/bootstrap.css')
<commit_msg>remove useless page<commit_after><|endoftext|>


<commit_before>const { BagItProfile } = require('../../bagit/bagit_profile');
const { Choice } = require('./choice');
const { Context } = require('../../core/context');
const { Field } = require('./field');
const { Form } = require('./form');
const { PluginManager } = require('../../plugins/plugin_manager');

/**
 * JobPackageOpForm can present and parse the form that allows
 * the user to specify how files should be packaged for a job.
 */
class JobPackageOpForm extends Form {

    constructor(job) {
        super('JobPackageOp', JobPackageOpForm.getCustomObject(job));
        this._init();
        window.formy = this;
    }

    static getCustomObject(job) {
        return {
            packageFormat: job.packageFormat,
            pluginId: job.pluginId,
            bagItProfileId: job.bagItProfile ? job.bagItProfile.id : '',
            outputPath: job.outputPath,
            packageName: job.packageName,
            id: job.id
        }
    }

    _init() {
        this._listPackageFormats();
        this._listBagItProfiles();
    }

    _listPackageFormats() {
        let formats = [
            {
                id: 'None',
                name: 'None'
            },
            {
                id: 'BagIt',
                name: 'BagIt'
            }
        ];
        for (let writer of PluginManager.getModuleCollection('FormatWriter')) {
            let description = writer.description();
            for (let format of description.writesFormats) {
                formats.push({
                    id: description.id,
                    name: format
                });
            };
        }
        this.fields['packageFormat'].choices = Choice.makeList(
            formats,
            this.obj.packageFormat,
            false
        );
    }

    _listBagItProfiles() {
        var selectedProfileId = this.obj.bagItProfile ? this.obj.bagItProfile.id : '';
        var profiles = BagItProfile.list(null, {
            limit: 0,
            offset: 0,
            orderBy: 'name',
            sortDirection: 'asc'
        });
        this.fields['bagItProfile'] = new Field(
            `${this.formId}_bagItProfile`,
            'bagItProfile',
            Context.y18n.__('BagIt Profile'),
            null
        );
        this.fields['bagItProfile'].choices = Choice.makeList(
            profiles,
            selectedProfileId,
            true
        );
    }

    // parseFromDOM() {
    //     super.parseFromDOM();
    //     // Plugin Id is the value of the selected item.
    //     // Format name is the name of the selected item.
    //     // Not pretty from a dev perspective, but it simplifies
    //     // things for the user.
    //     let selectedPluginId = this.obj.packageFormat;
    //     let formatName = $('#jobPackageOpForm_packageFormat option:selected').text();
    //     this.obj.pluginId = selectedPluginId;
    //     if (formatName) {
    //         this.obj.packageFormat = formatName.trim();
    //     }
    // }

}

module.exports.JobPackageOpForm = JobPackageOpForm;
<commit_msg>Fixed packageOp properties<commit_after>const { BagItProfile } = require('../../bagit/bagit_profile');
const { Choice } = require('./choice');
const { Context } = require('../../core/context');
const { Field } = require('./field');
const { Form } = require('./form');
const { PluginManager } = require('../../plugins/plugin_manager');

/**
 * JobPackageOpForm can present and parse the form that allows
 * the user to specify how files should be packaged for a job.
 */
class JobPackageOpForm extends Form {

    constructor(job) {
        super('JobPackageOp', JobPackageOpForm.getCustomObject(job));
        this._init();
        window.formy = this;
    }

    static getCustomObject(job) {
        return {
            packageFormat: job.packageOp.packageFormat,
            pluginId: job.packageOp.pluginId,
            bagItProfileId: job.bagItProfile ? job.bagItProfile.id : '',
            outputPath: job.packageOp.outputPath,
            packageName: job.packageOp.packageName,
            id: job.id
        }
    }

    _init() {
        this._listPackageFormats();
        this._listBagItProfiles();
    }

    _listPackageFormats() {
        let formats = [
            {
                id: 'None',
                name: 'None'
            },
            {
                id: 'BagIt',
                name: 'BagIt'
            }
        ];
        for (let writer of PluginManager.getModuleCollection('FormatWriter')) {
            let description = writer.description();
            for (let format of description.writesFormats) {
                formats.push({
                    id: description.id,
                    name: format
                });
            };
        }
        this.fields['packageFormat'].choices = Choice.makeList(
            formats,
            this.obj.pluginId,
            false
        );
    }

    _listBagItProfiles() {
        var selectedProfileId = this.obj.bagItProfile ? this.obj.bagItProfile.id : '';
        var profiles = BagItProfile.list(null, {
            limit: 0,
            offset: 0,
            orderBy: 'name',
            sortDirection: 'asc'
        });
        this.fields['bagItProfile'] = new Field(
            `${this.formId}_bagItProfile`,
            'bagItProfile',
            Context.y18n.__('BagIt Profile'),
            null
        );
        this.fields['bagItProfile'].choices = Choice.makeList(
            profiles,
            selectedProfileId,
            true
        );
    }

    // parseFromDOM() {
    //     super.parseFromDOM();
    //     // Plugin Id is the value of the selected item.
    //     // Format name is the name of the selected item.
    //     // Not pretty from a dev perspective, but it simplifies
    //     // things for the user.
    //     let selectedPluginId = this.obj.packageFormat;
    //     let formatName = $('#jobPackageOpForm_packageFormat option:selected').text();
    //     this.obj.pluginId = selectedPluginId;
    //     if (formatName) {
    //         this.obj.packageFormat = formatName.trim();
    //     }
    // }

}

module.exports.JobPackageOpForm = JobPackageOpForm;
<|endoftext|>


<commit_before>'use strict'

const util = require('util')
const bignumber = require('bignumber.js').BigNumber

const constants = require('./constants')
const NUMBYTES = constants.NUMBYTES
const SHIFT32 = constants.SHIFT32
const MAX_SAFE_HIGH = 0x1fffff

exports.hasBigInt = (typeof BigInt === 'function')

/**
 * Convert a UTF8-encoded Buffer to a JS string.  If possible, throw an error
 * on invalid UTF8.  Byte Order Marks are not looked at or stripped.
 */
const TD = (typeof TextDecoder === 'function') ? TextDecoder : util.TextDecoder
/* istanbul ignore else */
if (TD) {
  // node 11+, browsers : node 8.3+
  const td = new TD('utf8', {fatal: true, ignoreBOM: true})
  exports.utf8 = (buf) => td.decode(buf)
  exports.utf8.checksUTF8 = true
} else {
  // TODO: polyfill a slow one or wait for node6 to die
  exports.utf8 = (buf) => buf.toString('utf8')
  exports.utf8.checksUTF8 = false
}

exports.parseCBORint = function(ai, buf) {
  switch (ai) {
    case NUMBYTES.ONE:
      return buf.readUInt8(0)
    case NUMBYTES.TWO:
      return buf.readUInt16BE(0)
    case NUMBYTES.FOUR:
      return buf.readUInt32BE(0)
    case NUMBYTES.EIGHT:
      const f = buf.readUInt32BE(0)
      const g = buf.readUInt32BE(4)
      if (f > MAX_SAFE_HIGH) {
        return new bignumber(f).times(SHIFT32).plus(g)
      } else {
        return (f * SHIFT32) + g
      }
    default:
      throw new Error('Invalid additional info for int: ' + ai)
  }
}

exports.writeHalf = function writeHalf(buf, half) {
  // assume 0, -0, NaN, Infinity, and -Infinity have already been caught

  // HACK: everyone settle in.  This isn't going to be pretty.
  // Translate cn-cbor's C code (from Carsten Borman):

  // uint32_t be32;
  // uint16_t be16, u16;
  // union {
  //   float f;
  //   uint32_t u;
  // } u32;
  // u32.f = float_val;

  const u32 = Buffer.allocUnsafe(4)
  u32.writeFloatBE(half, 0)
  const u = u32.readUInt32BE(0)

  // if ((u32.u & 0x1FFF) == 0) { /* worth trying half */

  // hildjj: If the lower 13 bits are 0,
  // we won't lose anything in the conversion
  if ((u & 0x1FFF) !== 0) {
    return false
  }

  //   int s16 = (u32.u >> 16) & 0x8000;
  //   int exp = (u32.u >> 23) & 0xff;
  //   int mant = u32.u & 0x7fffff;

  let s16 = (u >> 16) & 0x8000 // top bit is sign
  const exp = (u >> 23) & 0xff // then 5 bits of exponent
  const mant = u & 0x7fffff

  //   if (exp == 0 && mant == 0)
  //     ;              /* 0.0, -0.0 */

  // hildjj: zeros already handled.  Assert if you don't believe me.

  //   else if (exp >= 113 && exp <= 142) /* normalized */
  //     s16 += ((exp - 112) << 10) + (mant >> 13);

  if ((exp >= 113) && (exp <= 142)) {
    s16 += ((exp - 112) << 10) + (mant >> 13)
  } else if ((exp >= 103) && (exp < 113)) {
    //   else if (exp >= 103 && exp < 113) { /* denorm, exp16 = 0 */
    //     if (mant & ((1 << (126 - exp)) - 1))
    //       goto float32;         /* loss of precision */
    //     s16 += ((mant + 0x800000) >> (126 - exp));

    if (mant & ((1 << (126 - exp)) - 1)) {
      return false
    }
    s16 += ((mant + 0x800000) >> (126 - exp))
  } else {
  //   } else if (exp == 255 && mant == 0) { /* Inf */
  //     s16 += 0x7c00;

    // hildjj: Infinity already handled

    //   } else
    //     goto float32;           /* loss of range */

    return false
  }

  //   ensure_writable(3);
  //   u16 = s16;
  //   be16 = hton16p((const uint8_t*)&u16);
  buf.writeUInt16BE(s16)
  return true
}

exports.parseHalf = function parseHalf(buf) {
  const sign = buf[0] & 0x80 ? -1 : 1
  const exp = (buf[0] & 0x7C) >> 2
  const mant = ((buf[0] & 0x03) << 8) | buf[1]
  if (!exp) {
    return sign * 5.9604644775390625e-8 * mant
  } else if (exp === 0x1f) {
    return sign * (mant ? 0 / 0 : 2e308)
  } else {
    return sign * Math.pow(2, exp - 25) * (1024 + mant)
  }
}

exports.parseCBORfloat = function parseCBORfloat(buf) {
  switch (buf.length) {
    case 2:
      return exports.parseHalf(buf)
    case 4:
      return buf.readFloatBE(0)
    case 8:
      return buf.readDoubleBE(0)
    default:
      throw new Error('Invalid float size: ' + buf.length)
  }
}

exports.hex = function hex(s) {
  return Buffer.from(s.replace(/^0x/, ''), 'hex')
}

exports.bin = function bin(s) {
  s = s.replace(/\s/g, '')
  let start = 0
  let end = (s.length % 8) || 8
  const chunks = []
  while (end <= s.length) {
    chunks.push(parseInt(s.slice(start, end), 2))
    start = end
    end += 8
  }
  return Buffer.from(chunks)
}

exports.extend = function extend(old={}, ...adds) {
  const len = adds.length
  for (let j = 0; j < len; j++) {
    const a = adds[j]
    for (const k in a) {
      const v = a[k]
      old[k] = v
    }
  }
  return old
}

exports.arrayEqual = function arrayEqual(a, b) {
  if ((a == null) && (b == null)) {
    return true
  }
  if ((a == null) || (b == null)) {
    return false
  }
  return (a.length === b.length) && a.every((elem, i) => elem === b[i])
}

exports.bufferEqual = function bufferEqual(a, b) {
  if ((a == null) && (b == null)) {
    return true
  }
  if ((a == null) || (b == null)) {
    return false
  }
  if (!(Buffer.isBuffer(a) && Buffer.isBuffer(b) && (a.length === b.length))) {
    return false
  }
  const len = a.length
  let ret = true
  let i
  let j
  for (i = j = 0; j < len; i = ++j) {
    const byte = a[i]
    ret = ret && (b[i] === byte)
  }
  return !!ret
}

exports.bufferToBignumber = function bufferToBignumber(buf) {
  return new bignumber(buf.toString('hex'), 16)
}

exports.toBigInt = function toBigInt(num) {
  if (!exports.hasBigInt) {
    return Number(num) // lossy.  Better than nothing?
  }
  return BigInt(num)
}

exports.bigIntize = function bigIntize(obj) {
  const ret = {}
  for (const k in obj) { // stupid node 6
    ret[k] = exports.toBigInt(obj[k])
  }
}

exports.bufferToBigInt = function bufferToBigInt(buf) {
  return exports.toBigInt('0x' + buf.toString('hex'))
}

exports.guessEncoding = function guessEncoding(input) {
  if (typeof input == 'string') {
    return 'hex'
  } else if (Buffer.isBuffer(input)) {
    return undefined
  }
  throw new Error('Unknown input type')
}

<commit_msg>Re-fix node 10+<commit_after>'use strict'

const util = require('util')
const bignumber = require('bignumber.js').BigNumber

const constants = require('./constants')
const NUMBYTES = constants.NUMBYTES
const SHIFT32 = constants.SHIFT32
const MAX_SAFE_HIGH = 0x1fffff

exports.hasBigInt = (typeof BigInt === 'function')

/**
 * Convert a UTF8-encoded Buffer to a JS string.  If possible, throw an error
 * on invalid UTF8.  Byte Order Marks are not looked at or stripped.
 */
const TD = (typeof TextDecoder === 'function') ? TextDecoder : util.TextDecoder
/* istanbul ignore else */
if (TD) {
  // node 11+, browsers : node 8.3+
  const td = new TD('utf8', {fatal: true, ignoreBOM: true})
  exports.utf8 = (buf) => td.decode(buf)
  exports.utf8.checksUTF8 = true
} else {
  // TODO: polyfill a slow one or wait for node6 to die
  exports.utf8 = (buf) => buf.toString('utf8')
  exports.utf8.checksUTF8 = false
}

exports.parseCBORint = function(ai, buf) {
  switch (ai) {
    case NUMBYTES.ONE:
      return buf.readUInt8(0)
    case NUMBYTES.TWO:
      return buf.readUInt16BE(0)
    case NUMBYTES.FOUR:
      return buf.readUInt32BE(0)
    case NUMBYTES.EIGHT:
      const f = buf.readUInt32BE(0)
      const g = buf.readUInt32BE(4)
      if (f > MAX_SAFE_HIGH) {
        return new bignumber(f).times(SHIFT32).plus(g)
      } else {
        return (f * SHIFT32) + g
      }
    default:
      throw new Error('Invalid additional info for int: ' + ai)
  }
}

exports.writeHalf = function writeHalf(buf, half) {
  // assume 0, -0, NaN, Infinity, and -Infinity have already been caught

  // HACK: everyone settle in.  This isn't going to be pretty.
  // Translate cn-cbor's C code (from Carsten Borman):

  // uint32_t be32;
  // uint16_t be16, u16;
  // union {
  //   float f;
  //   uint32_t u;
  // } u32;
  // u32.f = float_val;

  const u32 = Buffer.allocUnsafe(4)
  u32.writeFloatBE(half, 0)
  const u = u32.readUInt32BE(0)

  // if ((u32.u & 0x1FFF) == 0) { /* worth trying half */

  // hildjj: If the lower 13 bits are 0,
  // we won't lose anything in the conversion
  if ((u & 0x1FFF) !== 0) {
    return false
  }

  //   int s16 = (u32.u >> 16) & 0x8000;
  //   int exp = (u32.u >> 23) & 0xff;
  //   int mant = u32.u & 0x7fffff;

  let s16 = (u >> 16) & 0x8000 // top bit is sign
  const exp = (u >> 23) & 0xff // then 5 bits of exponent
  const mant = u & 0x7fffff

  //   if (exp == 0 && mant == 0)
  //     ;              /* 0.0, -0.0 */

  // hildjj: zeros already handled.  Assert if you don't believe me.

  //   else if (exp >= 113 && exp <= 142) /* normalized */
  //     s16 += ((exp - 112) << 10) + (mant >> 13);

  if ((exp >= 113) && (exp <= 142)) {
    s16 += ((exp - 112) << 10) + (mant >> 13)
  } else if ((exp >= 103) && (exp < 113)) {
    //   else if (exp >= 103 && exp < 113) { /* denorm, exp16 = 0 */
    //     if (mant & ((1 << (126 - exp)) - 1))
    //       goto float32;         /* loss of precision */
    //     s16 += ((mant + 0x800000) >> (126 - exp));

    if (mant & ((1 << (126 - exp)) - 1)) {
      return false
    }
    s16 += ((mant + 0x800000) >> (126 - exp))
  } else {
  //   } else if (exp == 255 && mant == 0) { /* Inf */
  //     s16 += 0x7c00;

    // hildjj: Infinity already handled

    //   } else
    //     goto float32;           /* loss of range */

    return false
  }

  //   ensure_writable(3);
  //   u16 = s16;
  //   be16 = hton16p((const uint8_t*)&u16);
  buf.writeUInt16BE(s16)
  return true
}

exports.parseHalf = function parseHalf(buf) {
  const sign = buf[0] & 0x80 ? -1 : 1
  const exp = (buf[0] & 0x7C) >> 2
  const mant = ((buf[0] & 0x03) << 8) | buf[1]
  if (!exp) {
    return sign * 5.9604644775390625e-8 * mant
  } else if (exp === 0x1f) {
    return sign * (mant ? 0 / 0 : 2e308)
  } else {
    return sign * Math.pow(2, exp - 25) * (1024 + mant)
  }
}

exports.parseCBORfloat = function parseCBORfloat(buf) {
  switch (buf.length) {
    case 2:
      return exports.parseHalf(buf)
    case 4:
      return buf.readFloatBE(0)
    case 8:
      return buf.readDoubleBE(0)
    default:
      throw new Error('Invalid float size: ' + buf.length)
  }
}

exports.hex = function hex(s) {
  return Buffer.from(s.replace(/^0x/, ''), 'hex')
}

exports.bin = function bin(s) {
  s = s.replace(/\s/g, '')
  let start = 0
  let end = (s.length % 8) || 8
  const chunks = []
  while (end <= s.length) {
    chunks.push(parseInt(s.slice(start, end), 2))
    start = end
    end += 8
  }
  return Buffer.from(chunks)
}

exports.extend = function extend(old={}, ...adds) {
  const len = adds.length
  for (let j = 0; j < len; j++) {
    const a = adds[j]
    for (const k in a) {
      const v = a[k]
      old[k] = v
    }
  }
  return old
}

exports.arrayEqual = function arrayEqual(a, b) {
  if ((a == null) && (b == null)) {
    return true
  }
  if ((a == null) || (b == null)) {
    return false
  }
  return (a.length === b.length) && a.every((elem, i) => elem === b[i])
}

exports.bufferEqual = function bufferEqual(a, b) {
  if ((a == null) && (b == null)) {
    return true
  }
  if ((a == null) || (b == null)) {
    return false
  }
  if (!(Buffer.isBuffer(a) && Buffer.isBuffer(b) && (a.length === b.length))) {
    return false
  }
  const len = a.length
  let ret = true
  let i
  let j
  for (i = j = 0; j < len; i = ++j) {
    const byte = a[i]
    ret = ret && (b[i] === byte)
  }
  return !!ret
}

exports.bufferToBignumber = function bufferToBignumber(buf) {
  return new bignumber(buf.toString('hex'), 16)
}

exports.toBigInt = function toBigInt(num) {
  if (!exports.hasBigInt) {
    return Number(num) // lossy.  Better than nothing?
  }
  return BigInt(num)
}

exports.bigIntize = function bigIntize(obj) {
  const ret = {}
  for (const k in obj) { // stupid node 6
    ret[k] = exports.toBigInt(obj[k])
  }
  return ret
}

exports.bufferToBigInt = function bufferToBigInt(buf) {
  return exports.toBigInt('0x' + buf.toString('hex'))
}

exports.guessEncoding = function guessEncoding(input) {
  if (typeof input == 'string') {
    return 'hex'
  } else if (Buffer.isBuffer(input)) {
    return undefined
  }
  throw new Error('Unknown input type')
}

<|endoftext|>


<commit_before>var Circle = require('../shapes/Circle')
,   Plane = require('../shapes/Plane')
,   Shape = require('../shapes/Shape')
,   Particle = require('../shapes/Particle')
,   Utils = require('../utils/Utils')
,   Broadphase = require('../collision/Broadphase')
,   vec2 = require('../math/vec2')

module.exports = SAP1DBroadphase;

/**
 * Sweep and prune broadphase along one axis.
 *
 * @class SAP1DBroadphase
 * @constructor
 * @extends Broadphase
 */
function SAP1DBroadphase(){
    Broadphase.apply(this);

    /**
     * List of bodies currently in the broadphase.
     * @property axisList
     * @type {Array}
     */
    this.axisList = [];

    /**
     * The world to search in.
     * @property world
     * @type {World}
     */
    this.world = world;

    /**
     * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on.
     * @property axisIndex
     * @type {Number}
     */
    this.axisIndex = 0;

    var axisList = this.axisList;

    this._addBodyHandler = function(e){
        axisList.push(e.body);
    };

    this._removeBodyHandler = function(e){
        var idx = axisList.indexOf(e.body);
        if(idx !== -1)
            axisList.splice(idx,1);
    }

    /*
    // Add listeners to update the list of bodies.
    world.on("addBody",function(e){
        axisList.push(e.body);
    }).on("removeBody",function(e){
        var idx = axisList.indexOf(e.body);
        if(idx !== -1)
            axisList.splice(idx,1);
    });
    */
};
SAP1DBroadphase.prototype = new Broadphase();

/**
 * Change the world
 * @method setWorld
 * @param  {World} world
 */
SAP1DBroadphase.prototype.setWorld = function(world){
    // Clear the old axis array
    this.axisList.length = 0;

    // Add all bodies from the new world
    Utils.appendArray(this.axisList,world.bodies);

    // Remove old handlers, if any
    world
        .off("addBody",this._addBodyHandler)
        .off("removeBody",this._removeBodyHandler);

    // Add handlers to update the list of bodies.
    world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);

    this.world = world;
};

/**
 * Function for sorting bodies along the X axis. To be passed to array.sort()
 * @method sortAxisListX
 * @param  {Body} bodyA
 * @param  {Body} bodyB
 * @return {Number}
 */
SAP1DBroadphase.sortAxisListX = function(bodyA,bodyB){
    return (bodyA.position[0]-bodyA.boundingRadius) - (bodyB.position[0]-bodyB.boundingRadius);
};

/**
 * Function for sorting bodies along the Y axis. To be passed to array.sort()
 * @method sortAxisListY
 * @param  {Body} bodyA
 * @param  {Body} bodyB
 * @return {Number}
 */
SAP1DBroadphase.sortAxisListY = function(bodyA,bodyB){
    return (bodyA.position[1]-bodyA.boundingRadius) - (bodyB.position[1]-bodyB.boundingRadius);
};

/**
 * Get the colliding pairs
 * @method getCollisionPairs
 * @param  {World} world
 * @return {Array}
 */
SAP1DBroadphase.prototype.getCollisionPairs = function(world){
    var bodies = this.axisList,
        result = this.result,
        axisIndex = this.axisIndex,
        i,j;

    result.length = 0;

    // Sort the list
    bodies.sort(axisIndex === 0 ? SAP1DBroadphase.sortAxisListX : SAP1DBroadphase.sortAxisListY );

    // Look through the list
    for(i=0, N=bodies.length; i!==N; i++){
        var bi = bodies[i];

        for(j=i+1; j<N; j++){
            var bj = bodies[j];

            if(!SAP1DBroadphase.checkBounds(bi,bj,axisIndex))
                break;

            // If we got overlap, add pair
            if(Broadphase.boundingRadiusCheck(bi,bj))
                result.push(bi,bj);
        }
    }

    return result;
};

/**
 * Check if the bounds of two bodies overlap, along the given SAP axis.
 * @static
 * @method checkBounds
 * @param  {Body} bi
 * @param  {Body} bj
 * @param  {Number} axisIndex
 * @return {Boolean}
 */
SAP1DBroadphase.checkBounds = function(bi,bj,axisIndex){
    var biPos = bi.position[axisIndex],
        ri = bi.boundingRadius,
        bjPos = bj.position[axisIndex],
        rj = bj.boundingRadius,
        boundA1 = biPos-ri,
        boundA2 = biPos+ri,
        boundB1 = bjPos-rj,
        boundB2 = bjPos+rj;

    return boundB1 < boundA2;
};
<commit_msg>fixed undefined parameter bug<commit_after>var Circle = require('../shapes/Circle')
,   Plane = require('../shapes/Plane')
,   Shape = require('../shapes/Shape')
,   Particle = require('../shapes/Particle')
,   Utils = require('../utils/Utils')
,   Broadphase = require('../collision/Broadphase')
,   vec2 = require('../math/vec2')

module.exports = SAP1DBroadphase;

/**
 * Sweep and prune broadphase along one axis.
 *
 * @class SAP1DBroadphase
 * @constructor
 * @extends Broadphase
 */
function SAP1DBroadphase(){
    Broadphase.apply(this);

    /**
     * List of bodies currently in the broadphase.
     * @property axisList
     * @type {Array}
     */
    this.axisList = [];

    /**
     * The world to search in.
     * @property world
     * @type {World}
     */
    this.world = null;

    /**
     * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on.
     * @property axisIndex
     * @type {Number}
     */
    this.axisIndex = 0;

    var axisList = this.axisList;

    this._addBodyHandler = function(e){
        axisList.push(e.body);
    };

    this._removeBodyHandler = function(e){
        var idx = axisList.indexOf(e.body);
        if(idx !== -1)
            axisList.splice(idx,1);
    }

    /*
    // Add listeners to update the list of bodies.
    world.on("addBody",function(e){
        axisList.push(e.body);
    }).on("removeBody",function(e){
        var idx = axisList.indexOf(e.body);
        if(idx !== -1)
            axisList.splice(idx,1);
    });
    */
};
SAP1DBroadphase.prototype = new Broadphase();

/**
 * Change the world
 * @method setWorld
 * @param  {World} world
 */
SAP1DBroadphase.prototype.setWorld = function(world){
    // Clear the old axis array
    this.axisList.length = 0;

    // Add all bodies from the new world
    Utils.appendArray(this.axisList,world.bodies);

    // Remove old handlers, if any
    world
        .off("addBody",this._addBodyHandler)
        .off("removeBody",this._removeBodyHandler);

    // Add handlers to update the list of bodies.
    world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);

    this.world = world;
};

/**
 * Function for sorting bodies along the X axis. To be passed to array.sort()
 * @method sortAxisListX
 * @param  {Body} bodyA
 * @param  {Body} bodyB
 * @return {Number}
 */
SAP1DBroadphase.sortAxisListX = function(bodyA,bodyB){
    return (bodyA.position[0]-bodyA.boundingRadius) - (bodyB.position[0]-bodyB.boundingRadius);
};

/**
 * Function for sorting bodies along the Y axis. To be passed to array.sort()
 * @method sortAxisListY
 * @param  {Body} bodyA
 * @param  {Body} bodyB
 * @return {Number}
 */
SAP1DBroadphase.sortAxisListY = function(bodyA,bodyB){
    return (bodyA.position[1]-bodyA.boundingRadius) - (bodyB.position[1]-bodyB.boundingRadius);
};

/**
 * Get the colliding pairs
 * @method getCollisionPairs
 * @param  {World} world
 * @return {Array}
 */
SAP1DBroadphase.prototype.getCollisionPairs = function(world){
    var bodies = this.axisList,
        result = this.result,
        axisIndex = this.axisIndex,
        i,j;

    result.length = 0;

    // Sort the list
    bodies.sort(axisIndex === 0 ? SAP1DBroadphase.sortAxisListX : SAP1DBroadphase.sortAxisListY );

    // Look through the list
    for(i=0, N=bodies.length; i!==N; i++){
        var bi = bodies[i];

        for(j=i+1; j<N; j++){
            var bj = bodies[j];

            if(!SAP1DBroadphase.checkBounds(bi,bj,axisIndex))
                break;

            // If we got overlap, add pair
            if(Broadphase.boundingRadiusCheck(bi,bj))
                result.push(bi,bj);
        }
    }

    return result;
};

/**
 * Check if the bounds of two bodies overlap, along the given SAP axis.
 * @static
 * @method checkBounds
 * @param  {Body} bi
 * @param  {Body} bj
 * @param  {Number} axisIndex
 * @return {Boolean}
 */
SAP1DBroadphase.checkBounds = function(bi,bj,axisIndex){
    var biPos = bi.position[axisIndex],
        ri = bi.boundingRadius,
        bjPos = bj.position[axisIndex],
        rj = bj.boundingRadius,
        boundA1 = biPos-ri,
        boundA2 = biPos+ri,
        boundB1 = bjPos-rj,
        boundB2 = bjPos+rj;

    return boundB1 < boundA2;
};
<|endoftext|>