<commit_before>var nodeunit = require('nodeunit');
var nodeunitUtils = require('nodeunit/lib/utils');

// ============================================================================
// CUSTOM NODEUNIT REPORTER
// ============================================================================

// Keep track of the last-started module.
var currentModule;
// Keep track of the last-started test(s).
var unfinished = {};

// If Nodeunit explodes because a test was missing test.done(), handle it.
process.on('exit', function() {
  var len = Object.keys(unfinished).length;
  // If there are unfinished tests, tell the user why Nodeunit killed grunt.
  if (len > 0) {
    log.muted = false;
    verbose.error().or.writeln('F'.red);
    log.error('Incomplete tests/setups/teardowns:');
    Object.keys(unfinished).forEach(log.error.bind(log));
    fail.fatal('A test was missing test.done(), so nodeunit exploded. Sorry!',
      Math.min(99, 90 + len));
  }
});

// Keep track of failed assertions for pretty-printing.
var failedAssertions = [];
function logFailedAssertions() {
  var assertion;
  // Print each assertion error + stack.
  while (assertion = failedAssertions.shift()) {
    nodeunitUtils.betterErrors(assertion);
    verbose.or.error(assertion.testName);
    if (assertion.error.name === 'AssertionError' && assertion.message) {
      log.error('AssertionMessage: ' + assertion.message.magenta);
    }
    log.error(assertion.error.stack.replace(/:(.*?\n)/, '$1'.magenta) + '\n');
  }
}

// Define our own Nodeunit reporter.
nodeunit.reporters.grunt = {
  info: 'Grunt reporter',
  run: function(files, options, callback) {
    var opts = {
      // No idea.
      testspec: undefined,
      // Executed when the first test in a file is run. If no tests exist in
      // the file, this doesn't execute.
      moduleStart: function(name) {
        // Keep track of this so that moduleDone output can be suppressed in
        // cases where a test file contains no tests.
        currentModule = name;
        verbose.subhead('Testing ' + name).or.write('Testing ' + name);
      },
      // Executed after a file is done being processed. This executes whether
      // tests exist in the file or not.
      moduleDone: function(name) {
        // Abort if no tests actually ran.
        if (name !== currentModule) { return; }
        // Print assertion errors here, if verbose mode is disabled.
        if (!option('verbose')) {
          if (failedAssertions.length > 0) {
            log.writeln();
            logFailedAssertions();
          } else {
            log.ok();
          }
        }
      },
      // Executed before each test is run.
      testStart: function(name) {
        // Keep track of the current test, in case test.done() was omitted
        // and Nodeunit explodes.
        unfinished[name] = name;
        verbose.write(name + '...');
        // Mute output, in cases where a function being tested logs through
        // grunt (for testing grunt internals).
        log.muted = true;
      },
      // Executed after each test and all its assertions are run.
      testDone: function(name, assertions) {
        delete unfinished[name];
        // Un-mute output.
        log.muted = false;
        // Log errors if necessary, otherwise success.
        if (assertions.failures()) {
          assertions.forEach(function(ass) {
            if (ass.failed()) {
              ass.testName = name;
              failedAssertions.push(ass);
            }
          });
          if (option('verbose')) {
            log.error();
            logFailedAssertions();
          } else {
            log.write('F'.red);
          }
        } else {
          verbose.ok().or.write('.');
        }
      },
      // Executed when everything is all done.
      done: function (assertions) {
        if (assertions.failures()) {
          fail.warn(assertions.failures() + '/' + assertions.length +
            ' assertions failed (' + assertions.duration + 'ms)',
            Math.min(99, 90 + assertions.failures()));
        } else {
          verbose.writeln();
          log.ok(assertions.length + ' assertions passed (' +
            assertions.duration + 'ms)');
        }
        // Tell the task manager we're all done.
        callback(); // callback(assertions.failures() === 0);
      }
    };

    // Nodeunit needs absolute paths.
    var paths = files.map(function (filepath) {
      return path.join(process.cwd(), filepath);
    });
    nodeunit.runFiles(paths, opts);
  }
};

// ============================================================================
// TASKS
// ============================================================================

task.registerBasicTask('test', 'Run unit tests.*', function(data, name) {
  // File paths.
  var filepaths = file.expand(data);
  // Clear all tests' cached require data, in case this task is run inside a
  // "watch" task loop.
  file.clearRequireCache(filepaths);
  // Run test(s)... asynchronously!
  nodeunit.reporters.grunt.run(filepaths, {}, this.async());
});
<commit_msg>Oops. Tests are fixed now.<commit_after>var path = require('path');
var nodeunit = require('nodeunit');
var nodeunitUtils = require('nodeunit/lib/utils');

// ============================================================================
// CUSTOM NODEUNIT REPORTER
// ============================================================================

// Keep track of the last-started module.
var currentModule;
// Keep track of the last-started test(s).
var unfinished = {};

// If Nodeunit explodes because a test was missing test.done(), handle it.
process.on('exit', function() {
  var len = Object.keys(unfinished).length;
  // If there are unfinished tests, tell the user why Nodeunit killed grunt.
  if (len > 0) {
    log.muted = false;
    verbose.error().or.writeln('F'.red);
    log.error('Incomplete tests/setups/teardowns:');
    Object.keys(unfinished).forEach(log.error.bind(log));
    fail.fatal('A test was missing test.done(), so nodeunit exploded. Sorry!',
      Math.min(99, 90 + len));
  }
});

// Keep track of failed assertions for pretty-printing.
var failedAssertions = [];
function logFailedAssertions() {
  var assertion;
  // Print each assertion error + stack.
  while (assertion = failedAssertions.shift()) {
    nodeunitUtils.betterErrors(assertion);
    verbose.or.error(assertion.testName);
    if (assertion.error.name === 'AssertionError' && assertion.message) {
      log.error('AssertionMessage: ' + assertion.message.magenta);
    }
    log.error(assertion.error.stack.replace(/:(.*?\n)/, '$1'.magenta) + '\n');
  }
}

// Define our own Nodeunit reporter.
nodeunit.reporters.grunt = {
  info: 'Grunt reporter',
  run: function(files, options, callback) {
    var opts = {
      // No idea.
      testspec: undefined,
      // Executed when the first test in a file is run. If no tests exist in
      // the file, this doesn't execute.
      moduleStart: function(name) {
        // Keep track of this so that moduleDone output can be suppressed in
        // cases where a test file contains no tests.
        currentModule = name;
        verbose.subhead('Testing ' + name).or.write('Testing ' + name);
      },
      // Executed after a file is done being processed. This executes whether
      // tests exist in the file or not.
      moduleDone: function(name) {
        // Abort if no tests actually ran.
        if (name !== currentModule) { return; }
        // Print assertion errors here, if verbose mode is disabled.
        if (!option('verbose')) {
          if (failedAssertions.length > 0) {
            log.writeln();
            logFailedAssertions();
          } else {
            log.ok();
          }
        }
      },
      // Executed before each test is run.
      testStart: function(name) {
        // Keep track of the current test, in case test.done() was omitted
        // and Nodeunit explodes.
        unfinished[name] = name;
        verbose.write(name + '...');
        // Mute output, in cases where a function being tested logs through
        // grunt (for testing grunt internals).
        log.muted = true;
      },
      // Executed after each test and all its assertions are run.
      testDone: function(name, assertions) {
        delete unfinished[name];
        // Un-mute output.
        log.muted = false;
        // Log errors if necessary, otherwise success.
        if (assertions.failures()) {
          assertions.forEach(function(ass) {
            if (ass.failed()) {
              ass.testName = name;
              failedAssertions.push(ass);
            }
          });
          if (option('verbose')) {
            log.error();
            logFailedAssertions();
          } else {
            log.write('F'.red);
          }
        } else {
          verbose.ok().or.write('.');
        }
      },
      // Executed when everything is all done.
      done: function (assertions) {
        if (assertions.failures()) {
          fail.warn(assertions.failures() + '/' + assertions.length +
            ' assertions failed (' + assertions.duration + 'ms)',
            Math.min(99, 90 + assertions.failures()));
        } else {
          verbose.writeln();
          log.ok(assertions.length + ' assertions passed (' +
            assertions.duration + 'ms)');
        }
        // Tell the task manager we're all done.
        callback(); // callback(assertions.failures() === 0);
      }
    };

    // Nodeunit needs absolute paths.
    var paths = files.map(function (filepath) {
      return path.join(process.cwd(), filepath);
    });
    nodeunit.runFiles(paths, opts);
  }
};

// ============================================================================
// TASKS
// ============================================================================

task.registerBasicTask('test', 'Run unit tests.*', function(data, name) {
  // File paths.
  var filepaths = file.expand(data);
  // Clear all tests' cached require data, in case this task is run inside a
  // "watch" task loop.
  file.clearRequireCache(filepaths);
  // Run test(s)... asynchronously!
  nodeunit.reporters.grunt.run(filepaths, {}, this.async());
});
<|endoftext|>


<commit_before>var ES6 = require('./ES6Fixer');

var Clerobee = require('clerobee');
var clerobee = new Clerobee( 32 );

var VERSION = exports.VERSION = '0.6.5';
function extend(obj, extension){
	for(var key in extension){
		if( extension[key] )
			obj[key] = extension[key];
	}
	return obj;
}

function Radiation( inflicter, options ){
	var self = this;

	this.toREST = [ ];
	this.toWebsocket = [ ];

	this.options = options || {};
	this.hideInnerServices = this.options.hideInnerServices;
	this.logLevel = this.options.level || 'info';
	this.logger = this.options.logger || inflicter.logger;

	this.logger.radiationlog = function( err, message, obj, level ){
		this.log( err ? 'error' : (level || 'debug'), err ? err.message : message, extend( obj || {}, { 'radiation': VERSION } ) );
	}.bind( self.logger );

	this.inflicter = inflicter;
	this.firestarter = inflicter.addicts( {
		name: this.options.name || 'Radiation',
		options: this.options,
		auditor: true,
		context: inflicter.name,
		castOf: function( name, firestarter, callback ){
			if( firestarter.object ){
				if( firestarter.object.rest ){
					self.logger.radiationlog( null, 'UnResting', { name: firestarter.name }, self.logLevel );
					self.unrest( name, firestarter );
				}
				if( firestarter.object.websocket ){
					self.logger.radiationlog( null, 'UnSocketing', { name: firestarter.name }, self.logLevel );
					self.desocket( name, firestarter );
				}
			}
			callback();
		},
		affiliate: function( firestarter, callback ){
			if( firestarter.object ){
				if( firestarter.object.rest ){
					self.logger.radiationlog( null, 'Resting', { name: firestarter.name }, self.logLevel );
					self.dorest( firestarter );
				}
				if( firestarter.object.websocket ){
					self.logger.radiationlog( null, 'Socketing', { name: firestarter.name }, self.logLevel );
					self.dosocket( firestarter );
				}
			}
			callback();
		},
		close: function( ){
			if( this.options.closeRest )
				self.restify.shutdown();
		}
	} );
	this.divisions = {};
}

var context = function( firestarter ){
	return (firestarter.division?'/'+firestarter.division:'') + '/'+firestarter.context;
};
var qualify = function( firestarter ){
	return (firestarter.division?firestarter.division+'.':'') + firestarter.context+'.';
};

var radiation = Radiation.prototype;

radiation.ignite = function( id, terms, division, event, params, callback ){
	var parameters = [ id, division, event ].concat( params );
	parameters.push( function(err, res){
		return callback( err, res );
	} );
	this.firestarter.addTerms( id, terms );
	this.firestarter.ignite.apply( this.firestarter, parameters );
};

radiation.publish = function( firestarter, protocol, publisherFN ){
	var self = this;

	if( !self[protocol] )
		return self.logger.warn( protocol + ' has not been started yet.', firestarter.name );

	if( self[protocol][ firestarter.name ] )
		return self.logger.warn( 'Component has been published already.', firestarter.name );

	self[protocol][ firestarter.name ] = [];
	self[protocol][ firestarter.name ].firestarter = firestarter;
	firestarter.services().forEach( function(service){
		if( !service || (self.hideInnerServices && service.charAt(0) === '_') ) return;

		var address = publisherFN(firestarter, service);
		self[protocol][ firestarter.name ].push( address );

		self.logger.radiationlog( null, service + ' has been published on ' + protocol, { name: firestarter.name, address: address}, self.logLevel );
	});
};

radiation.revoke = function( firestarter, protocol, revokerFN ){
	var self = this;

	if( !self[protocol] )
		return self.logger.warn( protocol + ' has not been started yet.', firestarter.name );

	if( self[protocol][ firestarter.name ] ){
		self[protocol][ firestarter.name ].forEach(function( element ){
			revokerFN( firestarter, element );
			self.logger.radiationlog( null,  protocol + ' service has been revoked.', { name: firestarter.name, address: element}, self.logLevel );
		});
		delete self[protocol][ firestarter.name ];
	}
};

radiation.unrest = function( name, firestarter ){
	var self = this;
	this.revoke( firestarter, 'REST', function(firestarter, path){
		self.restify.unpost( path.context + path.path );
	});
};

radiation.desocket = function( name, firestarter ) {
	this.revoke( firestarter, 'Websocket', function(firestarter, websocket){
	});
};

radiation.dorest = function( firestarter ){
	var self = this;

	if( !self.REST )
		return this.toREST.push( firestarter );

	this.publish( firestarter, 'REST', function(firestarter, service){
		var path = { path: '/' + service, context: context(firestarter) };
		var security = firestarter.object.security || {};
		path.protector = security.protector;
		var interceptor = firestarter.object.inceptors || {};
		self.restify.post( path, function( request, content, callback ){
			var params = content.params || content.parameters || [];
			if( interceptor.parametrise )
				params = interceptor.parametrise( params );
			self.ignite( clerobee.generate(), { request: request, content: content }, firestarter.division, firestarter.context + '.' + service, params, function(err, res){
				if( interceptor.endorse )
					interceptor.endorse( request, content, err, res );
				callback( err, res );
			} );
		}, null, security );
		return path;
	} );
};

radiation.dosocket = function( firestarter ) {
	if( !this.Websocket )
		return this.toWebsocket.push( firestarter );

	this.publish( firestarter, 'Websocket', function(firestarter, service){
		var websocket = qualify(firestarter) + service;
		return websocket;
	} );
};

radiation.rester = function( rest, options ) {
	var self = this;

	this.restify = rest;
	this.REST = { };
	this.logger.radiationlog( null, 'REST service has been activated.', {}, this.logLevel );

	this.toREST.forEach( function(firestarter){
		self.logger.radiationlog( null, 'Posteriorly executed publishing for REST...', { name: firestarter.name }, self.logLevel );
		self.dorest( firestarter );
	} );
	this.toREST.length = 0;

	return rest.rester( options || {} );
};

radiation.checkSecurity = function( data, callback ){
	var self = this;
	for(var fName in this.Websocket) {
		if( fName && this.Websocket[fName] ){
			var fs = this.Websocket[fName].firestarter;
			if( fs.matches( data.division, data.event ) && fs.object ){
				var security = fs.object.security || {};
				if( security.apiKeys && !security.apiKeys.contains( data.apiKey ) )
					return callback( null, false );
				if( security.iohalter )
					return security.iohalter( data, callback );
				else
					return callback( null, true );
			}
			//self.options.ioProtector
		}
	}
	return callback( null, false );
};

radiation.io = function( io ) {
	var self = this;
	self.io = io;
	self.Websocket = { };

	self.ioNamespace = io.of('/' + self.inflicter.name );
	self.ioNamespace.on('connection', function(socket){
		socket.on('ignite', function( data ){
			if( data && data.event ){
				self.checkSecurity(data, function(er, secure){
					if( er )
						return self.logger.error( er, data );
					if( secure )
						return self.ignite( data.id, null, data.division, data.event, data.params || data.parameters || [], function(err, res){
							socket.emit( err ? 'error' : 'done', err ? { id: data.id, message: err.message } : { id: data.id, result: res } );
						} );
					else
						self.logger.warn( 'This message won\'t be handled.', data );
				});
			}
		});
	});
	this.logger.radiationlog( null, 'Websocket service has been activated.', {}, self.logLevel );

	this.toWebsocket.forEach( function(firestarter){
		self.logger.radiationlog( null, 'Posteriorly executed publishing for Websocket...', { name: firestarter.name }, self.logLevel );
		self.dosocket( firestarter );
	} );
	this.toWebsocket.length = 0;

	return io;
};

module.exports = Radiation;
<commit_msg>removed interceptors<commit_after>var ES6 = require('./ES6Fixer');

var Clerobee = require('clerobee');
var clerobee = new Clerobee( 32 );

var VERSION = exports.VERSION = '0.6.5';
function extend(obj, extension){
	for(var key in extension){
		if( extension[key] )
			obj[key] = extension[key];
	}
	return obj;
}

function Radiation( inflicter, options ){
	var self = this;

	this.toREST = [ ];
	this.toWebsocket = [ ];

	this.options = options || {};
	this.hideInnerServices = this.options.hideInnerServices;
	this.logLevel = this.options.level || 'info';
	this.logger = this.options.logger || inflicter.logger;

	this.logger.radiationlog = function( err, message, obj, level ){
		this.log( err ? 'error' : (level || 'debug'), err ? err.message : message, extend( obj || {}, { 'radiation': VERSION } ) );
	}.bind( self.logger );

	this.inflicter = inflicter;
	this.firestarter = inflicter.addicts( {
		name: this.options.name || 'Radiation',
		options: this.options,
		auditor: true,
		context: inflicter.name,
		castOf: function( name, firestarter, callback ){
			if( firestarter.object ){
				if( firestarter.object.rest ){
					self.logger.radiationlog( null, 'UnResting', { name: firestarter.name }, self.logLevel );
					self.unrest( name, firestarter );
				}
				if( firestarter.object.websocket ){
					self.logger.radiationlog( null, 'UnSocketing', { name: firestarter.name }, self.logLevel );
					self.desocket( name, firestarter );
				}
			}
			callback();
		},
		affiliate: function( firestarter, callback ){
			if( firestarter.object ){
				if( firestarter.object.rest ){
					self.logger.radiationlog( null, 'Resting', { name: firestarter.name }, self.logLevel );
					self.dorest( firestarter );
				}
				if( firestarter.object.websocket ){
					self.logger.radiationlog( null, 'Socketing', { name: firestarter.name }, self.logLevel );
					self.dosocket( firestarter );
				}
			}
			callback();
		},
		close: function( ){
			if( this.options.closeRest )
				self.restify.shutdown();
		}
	} );
	this.divisions = {};
}

var context = function( firestarter ){
	return (firestarter.division?'/'+firestarter.division:'') + '/'+firestarter.context;
};
var qualify = function( firestarter ){
	return (firestarter.division?firestarter.division+'.':'') + firestarter.context+'.';
};

var radiation = Radiation.prototype;

radiation.ignite = function( id, terms, division, event, params, callback ){
	var parameters = [ id, division, event ].concat( params );
	parameters.push( function(err, res){
		return callback( err, res );
	} );
	this.firestarter.addTerms( id, terms );
	this.firestarter.ignite.apply( this.firestarter, parameters );
};

radiation.publish = function( firestarter, protocol, publisherFN ){
	var self = this;

	if( !self[protocol] )
		return self.logger.warn( protocol + ' has not been started yet.', firestarter.name );

	if( self[protocol][ firestarter.name ] )
		return self.logger.warn( 'Component has been published already.', firestarter.name );

	self[protocol][ firestarter.name ] = [];
	self[protocol][ firestarter.name ].firestarter = firestarter;
	firestarter.services().forEach( function(service){
		if( !service || (self.hideInnerServices && service.charAt(0) === '_') ) return;

		var address = publisherFN(firestarter, service);
		self[protocol][ firestarter.name ].push( address );

		self.logger.radiationlog( null, service + ' has been published on ' + protocol, { name: firestarter.name, address: address}, self.logLevel );
	});
};

radiation.revoke = function( firestarter, protocol, revokerFN ){
	var self = this;

	if( !self[protocol] )
		return self.logger.warn( protocol + ' has not been started yet.', firestarter.name );

	if( self[protocol][ firestarter.name ] ){
		self[protocol][ firestarter.name ].forEach(function( element ){
			revokerFN( firestarter, element );
			self.logger.radiationlog( null,  protocol + ' service has been revoked.', { name: firestarter.name, address: element}, self.logLevel );
		});
		delete self[protocol][ firestarter.name ];
	}
};

radiation.unrest = function( name, firestarter ){
	var self = this;
	this.revoke( firestarter, 'REST', function(firestarter, path){
		self.restify.unpost( path.context + path.path );
	});
};

radiation.desocket = function( name, firestarter ) {
	this.revoke( firestarter, 'Websocket', function(firestarter, websocket){
	});
};

radiation.dorest = function( firestarter ){
	var self = this;

	if( !self.REST )
		return this.toREST.push( firestarter );

	this.publish( firestarter, 'REST', function(firestarter, service){
		var path = { path: '/' + service, context: context(firestarter) };
		var security = firestarter.object.security || {};
		path.protector = security.protector;
		self.restify.post( path, function( request, content, callback ){
			var params = content.params || content.parameters || [];
			self.ignite( clerobee.generate(), { request: request, content: content }, firestarter.division, firestarter.context + '.' + service, params, callback );
		}, null, security );
		return path;
	} );
};

radiation.dosocket = function( firestarter ) {
	if( !this.Websocket )
		return this.toWebsocket.push( firestarter );

	this.publish( firestarter, 'Websocket', function(firestarter, service){
		var websocket = qualify(firestarter) + service;
		return websocket;
	} );
};

radiation.rester = function( rest, options ) {
	var self = this;

	this.restify = rest;
	this.REST = { };
	this.logger.radiationlog( null, 'REST service has been activated.', {}, this.logLevel );

	this.toREST.forEach( function(firestarter){
		self.logger.radiationlog( null, 'Posteriorly executed publishing for REST...', { name: firestarter.name }, self.logLevel );
		self.dorest( firestarter );
	} );
	this.toREST.length = 0;

	return rest.rester( options || {} );
};

radiation.checkSecurity = function( data, callback ){
	var self = this;
	for(var fName in this.Websocket) {
		if( fName && this.Websocket[fName] ){
			var fs = this.Websocket[fName].firestarter;
			if( fs.matches( data.division, data.event ) && fs.object ){
				var security = fs.object.security || {};
				if( security.apiKeys && !security.apiKeys.contains( data.apiKey ) )
					return callback( null, false );
				if( security.iohalter )
					return security.iohalter( data, callback );
				else
					return callback( null, true );
			}
			//self.options.ioProtector
		}
	}
	return callback( null, false );
};

radiation.io = function( io ) {
	var self = this;
	self.io = io;
	self.Websocket = { };

	self.ioNamespace = io.of('/' + self.inflicter.name );
	self.ioNamespace.on('connection', function(socket){
		socket.on('ignite', function( data ){
			if( data && data.event ){
				self.checkSecurity(data, function(er, secure){
					if( er )
						return self.logger.error( er, data );
					if( secure )
						return self.ignite( data.id, null, data.division, data.event, data.params || data.parameters || [], function(err, res){
							socket.emit( err ? 'error' : 'done', err ? { id: data.id, message: err.message } : { id: data.id, result: res } );
						} );
					else
						self.logger.warn( 'This message won\'t be handled.', data );
				});
			}
		});
	});
	this.logger.radiationlog( null, 'Websocket service has been activated.', {}, self.logLevel );

	this.toWebsocket.forEach( function(firestarter){
		self.logger.radiationlog( null, 'Posteriorly executed publishing for Websocket...', { name: firestarter.name }, self.logLevel );
		self.dosocket( firestarter );
	} );
	this.toWebsocket.length = 0;

	return io;
};

module.exports = Radiation;
<|endoftext|>


<commit_before>(function () {
  'use strict';
  angular
    .module('porttare.controllers')
    .controller('CourierOrderController', CourierOrderController);

  function CourierOrderController(courierOrder,
                                  $q,
                                  $scope,
                                  $ionicLoading,
                                  $ionicPopup,
                                  MapsService,
                                  GeolocationService,
                                  ShippingRequestService) {
    var coVm = this,
        currentLocation;
    coVm.order = courierOrder;
    coVm.showTakeRequestModal = showTakeRequestModal;
    coVm.courierIsInStore = courierIsInStore;
    coVm.courierHasDelivered = courierHasDelivered;
    init();

    function init() {
      preloadShippingRequestData();
      performing();
      $q.all([
        loadMaps(),
        getCurrentPosition()
      ]).then(function(){
        var mapContainer = angular.element('#order-map')[0];
        var map = MapsService.renderMap(mapContainer);
        MapsService.renderRoute({
          map: map,
          origin: getOrigin(),
          target: getTarget(),
          waypoints: getWaypoints(),
        });
        finishedPerforming();
      });
    }

    function preloadShippingRequestData() {
      coVm.address = coVm.order.address_attributes; // jshint ignore:line
      coVm.provider = coVm.order.provider_profile; // jshint ignore:line
      coVm.shouldDisplayClientDetails = getShouldDisplayClientDetails();
      coVm.orderItemsTotal = getOrderItemsTotal();
      // jshint ignore:start
      if (coVm.order.customer_order) {
        coVm.fareCurrency = coVm.order.customer_order.subtotal_items_currency;
        coVm.billingAddress = coVm.order.customer_order.customer_billing_address;

      }
      if (coVm.order.customer_order_delivery) {
        coVm.fareCurrencyCents = coVm.order.customer_order_delivery.shipping_fare_price_cents;
      }
      // jshint ignore:end
    }

    function getOrderItemsTotal() {
      // jshint ignore:start
      var customerOrderItems = coVm.order.customer_order.customer_order_items;
      return customerOrderItems.reduce(function(memo, orderItem){
        var subtotalOrderItem = orderItem.cantidad * orderItem.provider_item_precio_cents;
        return memo + subtotalOrderItem;
      }, 0);
      // jshint ignore:end
    }

    function getShouldDisplayClientDetails(){
      return coVm.order.customer_order_delivery && coVm.order.status !== 'new'; // jshint ignore:line
    }

    function getWaypoints(){
      if (!coVm.order.waypoints) { return; }
      return coVm.order.waypoints.map(function(waypoint){
        var location = new google.maps.LatLng(
          waypoint.lat,
          waypoint.lon
        );
        return {
          stopover: true,
          location: location
        };
      });
    }

    function getOrigin(){
      return new google.maps.LatLng(
        currentLocation.coords.latitude,
        currentLocation.coords.longitude
      );
    }

    function getTarget(){
      return new google.maps.LatLng(
        coVm.order.address_attributes.lat, // jshint ignore:line
        coVm.order.address_attributes.lon // jshint ignore:line
      );
    }

    function loadMaps(){
      return MapsService.loadGMaps();
    }

    function getCurrentPosition(){
      return GeolocationService
        .getCurrentPosition()
        .then(function(resp){
          currentLocation = resp;
        }).catch(function (error){
          finishedPerforming();
          $ionicPopup.alert({
            title: 'Error',
            template: error
          });
          coVm.mapIsHidden = true;
          return $q.reject(error);
        });
    }

    function performing(){
      $ionicLoading.show({
        template: '{{::("globals.loading"|translate)}}'
      });
    }

    function finishedPerforming(){
      $ionicLoading.hide();
    }

    function showTakeRequestModal(){
      // TODO translate me?
      $ionicPopup.show({
        scope: $scope,
        template: '<input type="number" ng-model="coVm.takeRequestTime" min="0" placeholder="Tiempo en minutos">',
        title: 'Tiempo estimado para la entrega',
        subTitle: 'incluye el tiempo que tomará recoger el pedido',
        buttons: [
          { text: 'Cancelar',
            onTap: function(){
              coVm.takeRequestTime = null;
            }
          },
          {
            text: 'Confirmar',
            type: 'button-positive',
            onTap: function(e) {
              if (!coVm.takeRequestTime) {
                e.preventDefault();
              } else {
                performTakeRequest();
              }
            }
          }
        ]
      });
    }

    function performTakeRequest(){
      performing();
      ShippingRequestService.takeShippingRequest(
        coVm.order,
        coVm.takeRequestTime
      ).then(successFromShippingRequestService)
      .finally(finishedPerforming);
    }

    function courierIsInStore(){
      performing();
      ShippingRequestService.courierIsInStore(
        coVm.order
      ).then(successFromShippingRequestService)
      .finally(finishedPerforming);
    }

    function courierHasDelivered(){
      performing();
      ShippingRequestService.courierHasDelivered(
        coVm.order
      ).then(successFromShippingRequestService)
      .finally(finishedPerforming);
    }

    function successFromShippingRequestService(respShippingReq){
      coVm.order = respShippingReq;
      init();
    }
  }
})();
<commit_msg>Prevent error when no order is present<commit_after>(function () {
  'use strict';
  angular
    .module('porttare.controllers')
    .controller('CourierOrderController', CourierOrderController);

  function CourierOrderController(courierOrder,
                                  $q,
                                  $scope,
                                  $ionicLoading,
                                  $ionicPopup,
                                  MapsService,
                                  GeolocationService,
                                  ShippingRequestService) {
    var coVm = this,
        currentLocation;
    coVm.order = courierOrder;
    coVm.showTakeRequestModal = showTakeRequestModal;
    coVm.courierIsInStore = courierIsInStore;
    coVm.courierHasDelivered = courierHasDelivered;
    init();

    function init() {
      preloadShippingRequestData();
      performing();
      $q.all([
        loadMaps(),
        getCurrentPosition()
      ]).then(function(){
        var mapContainer = angular.element('#order-map')[0];
        var map = MapsService.renderMap(mapContainer);
        MapsService.renderRoute({
          map: map,
          origin: getOrigin(),
          target: getTarget(),
          waypoints: getWaypoints(),
        });
        finishedPerforming();
      });
    }

    function preloadShippingRequestData() {
      coVm.address = coVm.order.address_attributes; // jshint ignore:line
      coVm.provider = coVm.order.provider_profile; // jshint ignore:line
      coVm.shouldDisplayClientDetails = getShouldDisplayClientDetails();
      // jshint ignore:start
      if (coVm.order.customer_order) {
        coVm.fareCurrency = coVm.order.customer_order.subtotal_items_currency;
        coVm.billingAddress = coVm.order.customer_order.customer_billing_address;
        coVm.orderItemsTotal = getOrderItemsTotal();
      }
      if (coVm.order.customer_order_delivery) {
        coVm.fareCurrencyCents = coVm.order.customer_order_delivery.shipping_fare_price_cents;
      }
      // jshint ignore:end
    }

    function getOrderItemsTotal() {
      // jshint ignore:start
      var customerOrderItems = coVm.order.customer_order.customer_order_items;
      return customerOrderItems.reduce(function(memo, orderItem){
        var subtotalOrderItem = orderItem.cantidad * orderItem.provider_item_precio_cents;
        return memo + subtotalOrderItem;
      }, 0);
      // jshint ignore:end
    }

    function getShouldDisplayClientDetails(){
      return coVm.order.customer_order_delivery && coVm.order.status !== 'new'; // jshint ignore:line
    }

    function getWaypoints(){
      if (!coVm.order.waypoints) { return; }
      return coVm.order.waypoints.map(function(waypoint){
        var location = new google.maps.LatLng(
          waypoint.lat,
          waypoint.lon
        );
        return {
          stopover: true,
          location: location
        };
      });
    }

    function getOrigin(){
      return new google.maps.LatLng(
        currentLocation.coords.latitude,
        currentLocation.coords.longitude
      );
    }

    function getTarget(){
      return new google.maps.LatLng(
        coVm.order.address_attributes.lat, // jshint ignore:line
        coVm.order.address_attributes.lon // jshint ignore:line
      );
    }

    function loadMaps(){
      return MapsService.loadGMaps();
    }

    function getCurrentPosition(){
      return GeolocationService
        .getCurrentPosition()
        .then(function(resp){
          currentLocation = resp;
        }).catch(function (error){
          finishedPerforming();
          $ionicPopup.alert({
            title: 'Error',
            template: error
          });
          coVm.mapIsHidden = true;
          return $q.reject(error);
        });
    }

    function performing(){
      $ionicLoading.show({
        template: '{{::("globals.loading"|translate)}}'
      });
    }

    function finishedPerforming(){
      $ionicLoading.hide();
    }

    function showTakeRequestModal(){
      // TODO translate me?
      $ionicPopup.show({
        scope: $scope,
        template: '<input type="number" ng-model="coVm.takeRequestTime" min="0" placeholder="Tiempo en minutos">',
        title: 'Tiempo estimado para la entrega',
        subTitle: 'incluye el tiempo que tomará recoger el pedido',
        buttons: [
          { text: 'Cancelar',
            onTap: function(){
              coVm.takeRequestTime = null;
            }
          },
          {
            text: 'Confirmar',
            type: 'button-positive',
            onTap: function(e) {
              if (!coVm.takeRequestTime) {
                e.preventDefault();
              } else {
                performTakeRequest();
              }
            }
          }
        ]
      });
    }

    function performTakeRequest(){
      performing();
      ShippingRequestService.takeShippingRequest(
        coVm.order,
        coVm.takeRequestTime
      ).then(successFromShippingRequestService)
      .finally(finishedPerforming);
    }

    function courierIsInStore(){
      performing();
      ShippingRequestService.courierIsInStore(
        coVm.order
      ).then(successFromShippingRequestService)
      .finally(finishedPerforming);
    }

    function courierHasDelivered(){
      performing();
      ShippingRequestService.courierHasDelivered(
        coVm.order
      ).then(successFromShippingRequestService)
      .finally(finishedPerforming);
    }

    function successFromShippingRequestService(respShippingReq){
      coVm.order = respShippingReq;
      init();
    }
  }
})();
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {

	THREE.Geometry.call( this );

	this.type = 'CylinderGeometry';

	this.parameters = {
		radiusTop: radiusTop,
		radiusBottom: radiusBottom,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded
	};

	radiusTop = radiusTop !== undefined ? radiusTop : 20;
	radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
	height = height !== undefined ? height : 100;

	radialSegments = radialSegments || 8;
	heightSegments = heightSegments || 1;

	openEnded = openEnded !== undefined ? openEnded : false;

	var heightHalf = height / 2;

	var x, y, vertices = [], uvs = [];

	for ( y = 0; y <= heightSegments; y ++ ) {

		var verticesRow = [];
		var uvsRow = [];

		var v = y / heightSegments;
		var radius = v * ( radiusBottom - radiusTop ) + radiusTop;

		for ( x = 0; x <= radialSegments; x ++ ) {

			var u = x / radialSegments;

			var vertex = new THREE.Vector3();
			vertex.x = radius * Math.sin( u * Math.PI * 2 );
			vertex.y = - v * height + heightHalf;
			vertex.z = radius * Math.cos( u * Math.PI * 2 );

			this.vertices.push( vertex );

			verticesRow.push( this.vertices.length - 1 );
			uvsRow.push( new THREE.Vector2( u, 1 - v ) );

		}

		vertices.push( verticesRow );
		uvs.push( uvsRow );

	}

	var tanTheta = ( radiusBottom - radiusTop ) / height;
	var na, nb;

	for ( x = 0; x < radialSegments; x ++ ) {

		if ( radiusTop !== 0 ) {

			na = this.vertices[ vertices[ 0 ][ x ] ].clone();
			nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();

		} else {

			na = this.vertices[ vertices[ 1 ][ x ] ].clone();
			nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();

		}

		na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
		nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();

		for ( y = 0; y < heightSegments; y ++ ) {

			var v1 = vertices[ y ][ x ];
			var v2 = vertices[ y + 1 ][ x ];
			var v3 = vertices[ y + 1 ][ x + 1 ];
			var v4 = vertices[ y ][ x + 1 ];

			var n1 = na.clone();
			var n2 = na.clone();
			var n3 = nb.clone();
			var n4 = nb.clone();

			var uv1 = uvs[ y ][ x ].clone();
			var uv2 = uvs[ y + 1 ][ x ].clone();
			var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
			var uv4 = uvs[ y ][ x + 1 ].clone();

			this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );

			this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );

		}

	}

	// top cap

	if ( openEnded === false && radiusTop > 0 ) {

		this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );

		for ( x = 0; x < radialSegments; x ++ ) {

			var v1 = vertices[ 0 ][ x ];
			var v2 = vertices[ 0 ][ x + 1 ];
			var v3 = this.vertices.length - 1;

			var n1 = new THREE.Vector3( 0, 1, 0 );
			var n2 = new THREE.Vector3( 0, 1, 0 );
			var n3 = new THREE.Vector3( 0, 1, 0 );

			var uv1 = uvs[ 0 ][ x ].clone();
			var uv2 = uvs[ 0 ][ x + 1 ].clone();
			var uv3 = new THREE.Vector2( uv2.x, 0 );

			this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

		}

	}

	// bottom cap

	if ( openEnded === false && radiusBottom > 0 ) {

		this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );

		for ( x = 0; x < radialSegments; x ++ ) {

			var v1 = vertices[ y ][ x + 1 ];
			var v2 = vertices[ y ][ x ];
			var v3 = this.vertices.length - 1;

			var n1 = new THREE.Vector3( 0, - 1, 0 );
			var n2 = new THREE.Vector3( 0, - 1, 0 );
			var n3 = new THREE.Vector3( 0, - 1, 0 );

			var uv1 = uvs[ y ][ x + 1 ].clone();
			var uv2 = uvs[ y ][ x ].clone();
			var uv3 = new THREE.Vector2( uv2.x, 1 );

			this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

		}

	}

	this.computeFaceNormals();

}

THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
<commit_msg>Support Sector of CylinderGeometry<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	THREE.Geometry.call( this );

	this.type = 'CylinderGeometry';

	this.parameters = {
		radiusTop: radiusTop,
		radiusBottom: radiusBottom,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	radiusTop = radiusTop !== undefined ? radiusTop : 20;
	radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
	height = height !== undefined ? height : 100;

	radialSegments = radialSegments || 8;
	heightSegments = heightSegments || 1;

	openEnded = openEnded !== undefined ? openEnded : false;
	thetaStart = thetaStart !== undefined ? thetaStart : 0;
	thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;

	var heightHalf = height / 2;

	var x, y, vertices = [], uvs = [];

	for ( y = 0; y <= heightSegments; y ++ ) {

		var verticesRow = [];
		var uvsRow = [];

		var v = y / heightSegments;
		var radius = v * ( radiusBottom - radiusTop ) + radiusTop;

		for ( x = 0; x <= radialSegments; x ++ ) {

			var u = x / radialSegments;

			var vertex = new THREE.Vector3();
			vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
			vertex.y = - v * height + heightHalf;
			vertex.z = radius * Math.cos( u * thetaLength + thetaStart );

			this.vertices.push( vertex );

			verticesRow.push( this.vertices.length - 1 );
			uvsRow.push( new THREE.Vector2( u, 1 - v ) );

		}

		vertices.push( verticesRow );
		uvs.push( uvsRow );

	}

	var tanTheta = ( radiusBottom - radiusTop ) / height;
	var na, nb;

	for ( x = 0; x < radialSegments; x ++ ) {

		if ( radiusTop !== 0 ) {

			na = this.vertices[ vertices[ 0 ][ x ] ].clone();
			nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();

		} else {

			na = this.vertices[ vertices[ 1 ][ x ] ].clone();
			nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();

		}

		na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
		nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();

		for ( y = 0; y < heightSegments; y ++ ) {

			var v1 = vertices[ y ][ x ];
			var v2 = vertices[ y + 1 ][ x ];
			var v3 = vertices[ y + 1 ][ x + 1 ];
			var v4 = vertices[ y ][ x + 1 ];

			var n1 = na.clone();
			var n2 = na.clone();
			var n3 = nb.clone();
			var n4 = nb.clone();

			var uv1 = uvs[ y ][ x ].clone();
			var uv2 = uvs[ y + 1 ][ x ].clone();
			var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
			var uv4 = uvs[ y ][ x + 1 ].clone();

			this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );

			this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );

		}

	}

	// top cap

	if ( openEnded === false && radiusTop > 0 ) {

		this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );

		for ( x = 0; x < radialSegments; x ++ ) {

			var v1 = vertices[ 0 ][ x ];
			var v2 = vertices[ 0 ][ x + 1 ];
			var v3 = this.vertices.length - 1;

			var n1 = new THREE.Vector3( 0, 1, 0 );
			var n2 = new THREE.Vector3( 0, 1, 0 );
			var n3 = new THREE.Vector3( 0, 1, 0 );

			var uv1 = uvs[ 0 ][ x ].clone();
			var uv2 = uvs[ 0 ][ x + 1 ].clone();
			var uv3 = new THREE.Vector2( uv2.x, 0 );

			this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

		}

	}

	// bottom cap

	if ( openEnded === false && radiusBottom > 0 ) {

		this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );

		for ( x = 0; x < radialSegments; x ++ ) {

			var v1 = vertices[ heightSegments ][ x + 1 ];
			var v2 = vertices[ heightSegments ][ x ];
			var v3 = this.vertices.length - 1;

			var n1 = new THREE.Vector3( 0, - 1, 0 );
			var n2 = new THREE.Vector3( 0, - 1, 0 );
			var n3 = new THREE.Vector3( 0, - 1, 0 );

			var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
			var uv2 = uvs[ heightSegments ][ x ].clone();
			var uv3 = new THREE.Vector2( uv2.x, 1 );

			this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
			this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

		}

	}

	this.computeFaceNormals();

};

THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
<|endoftext|>


<commit_before>'use strict';

import _ from 'lodash';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.titus.serverGroup.transformer', [])
  .factory('titusServerGroupTransformer', function ($q) {

    function normalizeServerGroup(serverGroup) {
      return $q.when(serverGroup); // no-op
    }

    function convertServerGroupCommandToDeployConfiguration(base) {
      // use _.defaults to avoid copying the backingData, which is huge and expensive to copy over
      var command = _.defaults({backingData: [], viewState: []}, base);
      if (base.viewState.mode !== 'clone') {
        delete command.source;
      }
      command.account = command.credentials;
      if (command.securityGroups) {
        var securityGroups = '' + command.securityGroups;
        command.securityGroups = securityGroups.split(/\s*,\s*/);
      }
      if (command.securityGroups === '') {
        delete command.securityGroups;
      }
      if (command.resources.allocateIpAddress === true) {
        delete command.resources.ports;
      }
      delete command.viewState;
      delete command.backingData;
      delete command.selectedProvider;
      return command;
    }

    return {
      convertServerGroupCommandToDeployConfiguration: convertServerGroupCommandToDeployConfiguration,
      normalizeServerGroup: normalizeServerGroup,
    };

  });
<commit_msg>(titus) do not touch security groups in transformer (#2875)<commit_after>'use strict';

import _ from 'lodash';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.titus.serverGroup.transformer', [])
  .factory('titusServerGroupTransformer', function ($q) {

    function normalizeServerGroup(serverGroup) {
      return $q.when(serverGroup); // no-op
    }

    function convertServerGroupCommandToDeployConfiguration(base) {
      // use _.defaults to avoid copying the backingData, which is huge and expensive to copy over
      var command = _.defaults({backingData: [], viewState: []}, base);
      if (base.viewState.mode !== 'clone') {
        delete command.source;
      }
      command.account = command.credentials;
      if (command.resources.allocateIpAddress === true) {
        delete command.resources.ports;
      }
      delete command.viewState;
      delete command.backingData;
      delete command.selectedProvider;
      return command;
    }

    return {
      convertServerGroupCommandToDeployConfiguration: convertServerGroupCommandToDeployConfiguration,
      normalizeServerGroup: normalizeServerGroup,
    };

  });
<|endoftext|>


<commit_before>'use strict';
/**
 * @file Retrieve cards for the account
 */

var async = require('async');
var Trello = require("node-trello");
var config = require('../../config/configuration.js');

var Entities = require('html-entities').AllHtmlEntities;
var entities = new Entities();

var cleanUp = function(rawCard) {
  var card = {};

  card.members = rawCard.members.map(function(member) {
    return member.fullName ? entities.decode(member.fullName) : undefined;
  });

  card.checklists = rawCard.checklists.map(function(checklist) {
    return {
      name: checklist.name ? entities.decode(checklist.name) : undefined,
      checkItems: checklist.checkItems.map(function(checkItem) {
        return {
          name: checkItem.name ? entities.decode(checkItem.name) : undefined,
          completed: checkItem.state === 'complete'
        };
      })
    };
  });

  card.comments = rawCard.actions
    .filter(function(action) {
      return action.type === 'commentCard';
    })
    .map(function(comment) {
      return {
        text: comment.data.text ? entities.decode(comment.data.text) : undefined,
        creator: comment.memberCreator.fullName ? entities.decode(comment.memberCreator.fullName) : undefined
      };
    });

  card.dateLastActivity = rawCard.dateLastActivity;

  rawCard.actions.forEach(function(action) {
    if(action.type === 'createCard') {
      card.creationDate = action.date;
    }
  });

  card.labels = rawCard.labels.map(function(label) {
    return {
      name: label.name ? entities.decode(label.name) : undefined,
      color: label.color
    };
  });

  card.board = rawCard.board ? entities.decode(rawCard.board) : undefined;

  card.list = rawCard.list ? entities.decode(rawCard.list) : undefined;

  card.url = rawCard.shortUrl;

  card.identifier = rawCard.shortUrl;

  card.title = rawCard.name ? entities.decode(rawCard.name) : undefined;

  card.description = rawCard.desc ? entities.decode(rawCard.desc) : undefined;

  return card;
};

/**
 * Retrieve all cards associated with this user account,
 *
 * @param {String} accessToken AccessToken to identify the account
 * @param {Date} since Retrieve cards updated since this date
 * @param {Function} cb Callback. First parameter is the error (if any), then an array of all the cards.
 */
var retrieveCards = function(accessToken, since, cb) {
  var t = new Trello(config.trelloKey, accessToken);

  var boardsName = {};
  var listsName = {};

  async.waterfall([
    function getBoards(cb) {
      t.get("1/members/my/boards", {lists: 'all'}, cb);
    },
    function cleanBoards(boards, cb) {
      var boardIds = [];
      boards.forEach(function(board) {
        if(board.name !== 'Welcome Board') {
          boardIds.push(board.id);
          boardsName[board.id] = board.name;
          board.lists.forEach(function(list) {
            listsName[list.id] = list.name;
          });
        }
      });
      cb(null, boardIds);
    },
    function getCards(boards, cb) {
      var options = {
        attachments: 'true',
        members: 'true',
        checklists: 'all',
        actions: ['commentCard', 'createCard'],
        fields: [
          'dateLastActivity',
          'desc',
          'labels',
          'name',
          'shortUrl',
          'idList',
          'idBoard'
        ],
        since: since
      };

      var urlArguments = Object.keys(options).map(function(key) {
        return key + '=' + encodeURIComponent(options[key]);
      }).join('&');

      var urls = boards.map(function(board) {
        return '/boards/' + board + '/cards?' + urlArguments;
      }).join(',');

      t.get("/1/batch", {urls: urls}, cb);
    },
    function parseCards(data, cb) {
      var cards = [];
      if(data) {
        data.forEach(function(res) {
          res['200'].forEach(function(card) {
            // populate with list and board
            card.board = boardsName[card.idBoard];
            card.list = listsName[card.idList];
            cards.push(cleanUp(card));
          });
        });
      }
      cb(null, cards);
    }
  ], cb);
};

/**
 * Download all cards from the specified Trello Account.
 *
 * @param {String} refreshToken Refresh_token to identify the account
 * @param {Date} since Retrieve contacts updated since this date
 * @param {Function} cb Callback. First parameter is the error (if any), second an array of all the cards.
 */
module.exports = retrieveCards;

// For testing only
module.exports.cleanUp = cleanUp;
<commit_msg>Fucking test<commit_after>'use strict';
/**
 * @file Retrieve cards for the account
 */

var async = require('async');
var Trello = require("node-trello");
var config = require('../../config/configuration.js');

var Entities = require('html-entities').AllHtmlEntities;
var entities = new Entities();

var cleanUp = function(rawCard) {
  var card = {};

  card.members = rawCard.members.map(function(member) {
    return member.fullName ? entities.decode(member.fullName) : "";
  });

  card.checklists = rawCard.checklists.map(function(checklist) {
    return {
      name: checklist.name ? entities.decode(checklist.name) : "",
      checkItems: checklist.checkItems.map(function(checkItem) {
        return {
          name: checkItem.name ? entities.decode(checkItem.name) : "",
          completed: checkItem.state === 'complete'
        };
      })
    };
  });

  card.comments = rawCard.actions
    .filter(function(action) {
      return action.type === 'commentCard';
    })
    .map(function(comment) {
      return {
        text: comment.data.text ? entities.decode(comment.data.text) : "",
        creator: comment.memberCreator.fullName ? entities.decode(comment.memberCreator.fullName) : ""
      };
    });

  card.dateLastActivity = rawCard.dateLastActivity;

  rawCard.actions.forEach(function(action) {
    if(action.type === 'createCard') {
      card.creationDate = action.date;
    }
  });

  card.labels = rawCard.labels.map(function(label) {
    return {
      name: label.name ? entities.decode(label.name) : "",
      color: label.color
    };
  });

  card.board = rawCard.board ? entities.decode(rawCard.board) : "";

  card.list = rawCard.list ? entities.decode(rawCard.list) : "";

  card.url = rawCard.shortUrl;

  card.identifier = rawCard.shortUrl;

  card.title = rawCard.name ? entities.decode(rawCard.name) : "";

  card.description = rawCard.desc ? entities.decode(rawCard.desc) : "";

  return card;
};

/**
 * Retrieve all cards associated with this user account,
 *
 * @param {String} accessToken AccessToken to identify the account
 * @param {Date} since Retrieve cards updated since this date
 * @param {Function} cb Callback. First parameter is the error (if any), then an array of all the cards.
 */
var retrieveCards = function(accessToken, since, cb) {
  var t = new Trello(config.trelloKey, accessToken);

  var boardsName = {};
  var listsName = {};

  async.waterfall([
    function getBoards(cb) {
      t.get("1/members/my/boards", {lists: 'all'}, cb);
    },
    function cleanBoards(boards, cb) {
      var boardIds = [];
      boards.forEach(function(board) {
        if(board.name !== 'Welcome Board') {
          boardIds.push(board.id);
          boardsName[board.id] = board.name;
          board.lists.forEach(function(list) {
            listsName[list.id] = list.name;
          });
        }
      });
      cb(null, boardIds);
    },
    function getCards(boards, cb) {
      var options = {
        attachments: 'true',
        members: 'true',
        checklists: 'all',
        actions: ['commentCard', 'createCard'],
        fields: [
          'dateLastActivity',
          'desc',
          'labels',
          'name',
          'shortUrl',
          'idList',
          'idBoard'
        ],
        since: since
      };

      var urlArguments = Object.keys(options).map(function(key) {
        return key + '=' + encodeURIComponent(options[key]);
      }).join('&');

      var urls = boards.map(function(board) {
        return '/boards/' + board + '/cards?' + urlArguments;
      }).join(',');

      t.get("/1/batch", {urls: urls}, cb);
    },
    function parseCards(data, cb) {
      var cards = [];
      if(data) {
        data.forEach(function(res) {
          res['200'].forEach(function(card) {
            // populate with list and board
            card.board = boardsName[card.idBoard];
            card.list = listsName[card.idList];
            cards.push(cleanUp(card));
          });
        });
      }
      cb(null, cards);
    }
  ], cb);
};

/**
 * Download all cards from the specified Trello Account.
 *
 * @param {String} refreshToken Refresh_token to identify the account
 * @param {Date} since Retrieve contacts updated since this date
 * @param {Function} cb Callback. First parameter is the error (if any), second an array of all the cards.
 */
module.exports = retrieveCards;

// For testing only
module.exports.cleanUp = cleanUp;
<|endoftext|>


<commit_before>import stringify from 'json-stringify-safe'
import validator from 'validator'

const OBJLENGTH = 10
const ARRLENGTH = 10
const STRINGLIMIT = 10000
const STRINGTRUNCATE = 200

let sanitizeString = function (str) {
    if (!str) {
        return ''
    }

    return String(str)
        .replace(/\./g, '_')
        .replace(/\s/g, '')
        .toLowerCase()
}

/**
 * formats capability object into sanitized string for e.g.filenames
 * @param {Object} caps  Selenium capabilities
 */
let caps = function (caps) {
    let result

    /**
     * mobile caps
     */
    if (caps.deviceName) {
        result = [sanitizeString(caps.deviceName), sanitizeString(caps.platformName), sanitizeString(caps.platformVersion), sanitizeString(caps.app)]
    } else {
        result = [sanitizeString(caps.browserName), sanitizeString(caps.version), sanitizeString(caps.platform)]
    }

    result = result.filter(n => n !== undefined && n !== '')
    return result.join('.')
}

/**
 * formats arguments into string
 * @param  {Array} args arguments object
 */
let args = function (args) {
    return args.map((arg) => {
        if (typeof arg === 'function' || (typeof arg === 'string' && arg.indexOf('return (function') === 0)) {
            return '<Function>'
        } else if (typeof arg === 'string') {
            return '"' + arg + '"'
        } else if (Array.isArray(arg)) {
            return arg.join(', ')
        }

        return arg
    }).join(', ')
}

let css = function (value) {
    if (!value) {
        return value
    }

    return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase()
}

/**
 * Limit the length of an arbritrary variable of any type, suitable for being logged or displayed
 * @param  {Any} val Any variable
 * @return {Any}     Limited var of same type
 */
let limit = function (val) {
    switch (Object.prototype.toString.call(val)) {
    case '[object String]':
        if (validator.isBase64(val)) {
            return '[base64] ' + val.length + ' bytes'
        }

        if (val.length > STRINGLIMIT) {
            return val.substr(0, STRINGTRUNCATE) + ' ... (' + (val.length - STRINGTRUNCATE) + ' more bytes)'
        }

        return val
    case '[object Array]':
        const length = val.length
        if (length > ARRLENGTH) {
            val = val.slice(0, ARRLENGTH)
            val.push(' ... (' + (length - ARRLENGTH) + ' more items)')
        }
        return val.map(limit)
    case '[object Object]':
        const keys = Object.keys(val)
        const removed = []
        for (let i = 0, l = keys.length; i < l; i++) {
            if (i < OBJLENGTH) {
                val[keys[i]] = limit(val[keys[i]])
            } else {
                delete val[keys[i]]
                removed.push(keys[i])
            }
        }
        if (keys.length > OBJLENGTH) {
            val._ = (keys.length - OBJLENGTH) + ' more keys: ' + stringify(removed)
        }
        return val
    }
}

export default {
    css,
    args,
    caps,
    limit
}
<commit_msg>Only test for base64 with longish strings<commit_after>import stringify from 'json-stringify-safe'
import validator from 'validator'

const OBJLENGTH = 10
const ARRLENGTH = 10
const STRINGLIMIT = 10000
const STRINGTRUNCATE = 200

let sanitizeString = function (str) {
    if (!str) {
        return ''
    }

    return String(str)
        .replace(/\./g, '_')
        .replace(/\s/g, '')
        .toLowerCase()
}

/**
 * formats capability object into sanitized string for e.g.filenames
 * @param {Object} caps  Selenium capabilities
 */
let caps = function (caps) {
    let result

    /**
     * mobile caps
     */
    if (caps.deviceName) {
        result = [sanitizeString(caps.deviceName), sanitizeString(caps.platformName), sanitizeString(caps.platformVersion), sanitizeString(caps.app)]
    } else {
        result = [sanitizeString(caps.browserName), sanitizeString(caps.version), sanitizeString(caps.platform)]
    }

    result = result.filter(n => n !== undefined && n !== '')
    return result.join('.')
}

/**
 * formats arguments into string
 * @param  {Array} args arguments object
 */
let args = function (args) {
    return args.map((arg) => {
        if (typeof arg === 'function' || (typeof arg === 'string' && arg.indexOf('return (function') === 0)) {
            return '<Function>'
        } else if (typeof arg === 'string') {
            return '"' + arg + '"'
        } else if (Array.isArray(arg)) {
            return arg.join(', ')
        }

        return arg
    }).join(', ')
}

let css = function (value) {
    if (!value) {
        return value
    }

    return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase()
}

/**
 * Limit the length of an arbritrary variable of any type, suitable for being logged or displayed
 * @param  {Any} val Any variable
 * @return {Any}     Limited var of same type
 */
let limit = function (val) {
    switch (Object.prototype.toString.call(val)) {
    case '[object String]':
        if (val.length > 100 && validator.isBase64(val)) {
            return '[base64] ' + val.length + ' bytes'
        }

        if (val.length > STRINGLIMIT) {
            return val.substr(0, STRINGTRUNCATE) + ' ... (' + (val.length - STRINGTRUNCATE) + ' more bytes)'
        }

        return val
    case '[object Array]':
        const length = val.length
        if (length > ARRLENGTH) {
            val = val.slice(0, ARRLENGTH)
            val.push(' ... (' + (length - ARRLENGTH) + ' more items)')
        }
        return val.map(limit)
    case '[object Object]':
        const keys = Object.keys(val)
        const removed = []
        for (let i = 0, l = keys.length; i < l; i++) {
            if (i < OBJLENGTH) {
                val[keys[i]] = limit(val[keys[i]])
            } else {
                delete val[keys[i]]
                removed.push(keys[i])
            }
        }
        if (keys.length > OBJLENGTH) {
            val._ = (keys.length - OBJLENGTH) + ' more keys: ' + stringify(removed)
        }
        return val
    }
}

export default {
    css,
    args,
    caps,
    limit
}
<|endoftext|>


<commit_before>/**
 * @file Contains functions related to the creation of the data pipelines used
 * by this importer, like record streams for OpenAddresses files and the
 * elasticsearch sink.
 */

'use strict';

var fs = require( 'fs' );
var csvParse = require( 'csv-parse' );
var through = require( 'through2' );
var logger = require( 'pelias-logger' ).get( 'openaddresses' );
var peliasModel = require( 'pelias-model' );
var peliasDbclient = require( 'pelias-dbclient' );
var cleanup = require( './cleanupStream' );

/*
 * Return true if a record has all of LON, LAT, NUMBER and STREET defined
 */
function isValidCsvRecord( record ){
  return [ 'LON', 'LAT', 'NUMBER', 'STREET' ].every(function(prop) {
    return record[ prop ].length > 0;
  });
}

/*
 * Create a through2 stream to filter out invalid records
 */
function createValidRecordFilterStream() {
  return through.obj(function( record, enc, next ) {
    if (isValidCsvRecord(record)) {
      this.push(record);
    }
    next();
  });
}

/*
 * Create a stream of Documents from valid, cleaned CSV records
 */
function createDocumentStream(stats) {
  /**
   * Used to track the UID of individual records passing through the stream
   * created by `createRecordStream()`.  See `peliasModel.Document.setId()` for
   * information about UIDs.
   */
  var uid = 0;

  return through.obj(
    function write( record, enc, next ){
      var model_id = ( uid++ ).toString();
      try {
        var addrDoc = new peliasModel.Document( 'openaddresses', model_id )
        .setName( 'default', (record.NUMBER + ' ' + record.STREET).replace(/ +/g, ' ') )
        .setCentroid( { lon: record.LON, lat: record.LAT } );

        addrDoc.setAddress( 'number', record.NUMBER );

        addrDoc.setAddress( 'street', record.STREET );

        try {
          addrDoc.setAddress( 'zip', record.POSTCODE );
        } catch ( ex ) {}

        addrDoc.phrase = addrDoc.name;
        this.push( addrDoc );
      }
      catch ( ex ){
        stats.badRecordCount++;
      }

      next();
    }
  );
}

/**
 * Create a stream of Documents from an OpenAddresses file.
 *
 * @param {string} filePath The path of an OpenAddresses CSV file.
 * @return {stream.Readable} A stream of `Document` objects, one
 *    for every valid record inside the OA file.
 */
function createRecordStream( filePath ){
  /**
   * A stream to convert rows of a CSV to Document objects.
   */
  var stats = {
    badRecordCount: 0
  };

  var intervalId = setInterval( function (){
    logger.verbose( 'Number of bad records: ' + stats.badRecordCount );
  }, 10000 );

  var csvParser = csvParse({
    trim: true,
    skip_empty_lines: true,
    relax: true,
    columns: true
  });

  var validRecordFilterStream = createValidRecordFilterStream();
  var cleanupStream = cleanup.createCleanupStream();

  var documentStream = createDocumentStream(stats);

  documentStream._flush = function end( done ){
    clearInterval( intervalId );
    done();
  };

  return fs.createReadStream( filePath )
    .pipe( csvParser )
    .pipe( validRecordFilterStream )
    .pipe( cleanupStream )
    .pipe( documentStream );
}

/**
 * Create the Pelias elasticsearch import pipeline.
 *
 * @return {stream.Writable} The entry point to the elasticsearch pipeline,
 *    which will perform additional processing on inbound `Document` objects
 *    before indexing them in the elasticsearch pelias index.
 */
function createPeliasElasticsearchPipeline(){
  var dbclientMapper = through.obj( function( model, enc, next ){
    this.push({
      _index: 'pelias',
      _type: model.getType(),
      _id: model.getId(),
      data: model
    });
    next();
  });

  var entryPoint = dbclientMapper;
  entryPoint.pipe( peliasDbclient() );

  return entryPoint;
}

module.exports = {
  createRecordStream: createRecordStream,
  createPeliasElasticsearchPipeline: createPeliasElasticsearchPipeline,
  isValidCsvRecord: isValidCsvRecord,
  createDocumentStream: createDocumentStream
};
<commit_msg>Use conditional instead of try/catch<commit_after>/**
 * @file Contains functions related to the creation of the data pipelines used
 * by this importer, like record streams for OpenAddresses files and the
 * elasticsearch sink.
 */

'use strict';

var fs = require( 'fs' );
var csvParse = require( 'csv-parse' );
var through = require( 'through2' );
var logger = require( 'pelias-logger' ).get( 'openaddresses' );
var peliasModel = require( 'pelias-model' );
var peliasDbclient = require( 'pelias-dbclient' );
var cleanup = require( './cleanupStream' );

/*
 * Return true if a record has all of LON, LAT, NUMBER and STREET defined
 */
function isValidCsvRecord( record ){
  return [ 'LON', 'LAT', 'NUMBER', 'STREET' ].every(function(prop) {
    return record[ prop ].length > 0;
  });
}

/*
 * Create a through2 stream to filter out invalid records
 */
function createValidRecordFilterStream() {
  return through.obj(function( record, enc, next ) {
    if (isValidCsvRecord(record)) {
      this.push(record);
    }
    next();
  });
}

/*
 * Create a stream of Documents from valid, cleaned CSV records
 */
function createDocumentStream(stats) {
  /**
   * Used to track the UID of individual records passing through the stream
   * created by `createRecordStream()`.  See `peliasModel.Document.setId()` for
   * information about UIDs.
   */
  var uid = 0;

  return through.obj(
    function write( record, enc, next ){
      var model_id = ( uid++ ).toString();
      try {
        var addrDoc = new peliasModel.Document( 'openaddresses', model_id )
        .setName( 'default', (record.NUMBER + ' ' + record.STREET).replace(/ +/g, ' ') )
        .setCentroid( { lon: record.LON, lat: record.LAT } );

        addrDoc.setAddress( 'number', record.NUMBER );

        addrDoc.setAddress( 'street', record.STREET );

        if (record.POSTCODE) {
          addrDoc.setAddress( 'zip', record.POSTCODE );
        }

        addrDoc.phrase = addrDoc.name;
        this.push( addrDoc );
      }
      catch ( ex ){
        stats.badRecordCount++;
      }

      next();
    }
  );
}

/**
 * Create a stream of Documents from an OpenAddresses file.
 *
 * @param {string} filePath The path of an OpenAddresses CSV file.
 * @return {stream.Readable} A stream of `Document` objects, one
 *    for every valid record inside the OA file.
 */
function createRecordStream( filePath ){
  /**
   * A stream to convert rows of a CSV to Document objects.
   */
  var stats = {
    badRecordCount: 0
  };

  var intervalId = setInterval( function (){
    logger.verbose( 'Number of bad records: ' + stats.badRecordCount );
  }, 10000 );

  var csvParser = csvParse({
    trim: true,
    skip_empty_lines: true,
    relax: true,
    columns: true
  });

  var validRecordFilterStream = createValidRecordFilterStream();
  var cleanupStream = cleanup.createCleanupStream();

  var documentStream = createDocumentStream(stats);

  documentStream._flush = function end( done ){
    clearInterval( intervalId );
    done();
  };

  return fs.createReadStream( filePath )
    .pipe( csvParser )
    .pipe( validRecordFilterStream )
    .pipe( cleanupStream )
    .pipe( documentStream );
}

/**
 * Create the Pelias elasticsearch import pipeline.
 *
 * @return {stream.Writable} The entry point to the elasticsearch pipeline,
 *    which will perform additional processing on inbound `Document` objects
 *    before indexing them in the elasticsearch pelias index.
 */
function createPeliasElasticsearchPipeline(){
  var dbclientMapper = through.obj( function( model, enc, next ){
    this.push({
      _index: 'pelias',
      _type: model.getType(),
      _id: model.getId(),
      data: model
    });
    next();
  });

  var entryPoint = dbclientMapper;
  entryPoint.pipe( peliasDbclient() );

  return entryPoint;
}

module.exports = {
  createRecordStream: createRecordStream,
  createPeliasElasticsearchPipeline: createPeliasElasticsearchPipeline,
  isValidCsvRecord: isValidCsvRecord,
  createDocumentStream: createDocumentStream
};
<|endoftext|>


<commit_before>'use strict'

var jetUtils = require('./utils')
var isDefined = jetUtils.isDefined

var contains = function (what) {
  return function (path) {
    return path.indexOf(what) !== -1
  }
}

var containsAllOf = function (whatArray) {
  return function (path) {
    var i
    for (i = 0; i < whatArray.length; i = i + 1) {
      if (path.indexOf(whatArray[i]) === -1) {
        return false
      }
    }
    return true
  }
}

var containsOneOf = function (whatArray) {
  return function (path) {
    var i
    for (i = 0; i < whatArray.length; i = i + 1) {
      if (path.indexOf(whatArray[i]) !== -1) {
        return true
      }
    }
    return false
  }
}

var startsWith = function (what) {
  return function (path) {
    return path.substr(0, what.length) === what
  }
}

var endsWith = function (what) {
  return function (path) {
    return path.lastIndexOf(what) === (path.length - what.length)
  }
}

var equals = function (what) {
  return function (path) {
    return path === what
  }
}

var equalsOneOf = function (whatArray) {
  return function (path) {
    var i
    for (i = 0; i < whatArray.length; i = i + 1) {
      if (path === whatArray[i]) {
        return true
      }
    }
    return false
  }
}

var negate = function (gen) {
  return function () {
    var f = gen.apply(undefined, arguments)
    return function () {
      return !f.apply(undefined, arguments)
    }
  }
}

var generators = {
  equals: equals,
  equalsNot: negate(equals),
  contains: contains,
  containsNot: negate(contains),
  containsAllOf: containsAllOf,
  containsOneOf: containsOneOf,
  startsWith: startsWith,
  startsNotWith: negate(startsWith),
  endsWith: endsWith,
  endsNotWith: negate(endsWith),
  equalsOneOf: equalsOneOf,
  equalsNotOneOf: negate(equalsOneOf)
}

var predicateOrder = [
  'equals',
  'equalsNot',
  'endsWith',
  'startsWith',
  'contains',
  'containsNot',
  'containsAllOf',
  'containsOneOf',
  'startsNotWith',
  'endsNotWith',
  'equalsOneOf',
  'equalsNotOneOf'
]

exports.create = function (options) {
  if (!isDefined(options.path)) {
    return
  }
  var po = options.path
  var ci = po.caseInsensitive
  var pred
  var predicates = []

  predicateOrder.forEach(function (name) {
    var gen
    var option = po[name]
    if (isDefined(option)) {
      gen = generators[name]
      if (ci) {
        if (Array.isArray(option)) {
          option = option.map((op) => op.toLowerCase())
        } else {
          option = option.toLowerCase()
        }
      }
      predicates.push(gen(option))
    }
  })

  var applyPredicates = function (path) {
    for (var i = 0; i < predicates.length; ++i) {
      if (!predicates[i](path)) {
        return false
      }
    }
    return true
  }

  var pathMatcher

  if (ci) {
    if (predicates.length === 1) {
      pred = predicates[0]
      pathMatcher = function (path, lowerPath) {
        return pred(lowerPath)
      }
    } else {
      pathMatcher = function (path, lowerPath) {
        return applyPredicates(lowerPath)
      }
    }
  } else {
    if (predicates.length === 1) {
      pred = predicates[0]
      pathMatcher = function (path) {
        return pred(path)
      }
    } else {
      pathMatcher = function (path) {
        return applyPredicates(path)
      }
    }
  }

  return pathMatcher // eslint-disable-line consistent-return
}
<commit_msg>no fat arrows for node 0.12<commit_after>'use strict'

var jetUtils = require('./utils')
var isDefined = jetUtils.isDefined

var contains = function (what) {
  return function (path) {
    return path.indexOf(what) !== -1
  }
}

var containsAllOf = function (whatArray) {
  return function (path) {
    var i
    for (i = 0; i < whatArray.length; i = i + 1) {
      if (path.indexOf(whatArray[i]) === -1) {
        return false
      }
    }
    return true
  }
}

var containsOneOf = function (whatArray) {
  return function (path) {
    var i
    for (i = 0; i < whatArray.length; i = i + 1) {
      if (path.indexOf(whatArray[i]) !== -1) {
        return true
      }
    }
    return false
  }
}

var startsWith = function (what) {
  return function (path) {
    return path.substr(0, what.length) === what
  }
}

var endsWith = function (what) {
  return function (path) {
    return path.lastIndexOf(what) === (path.length - what.length)
  }
}

var equals = function (what) {
  return function (path) {
    return path === what
  }
}

var equalsOneOf = function (whatArray) {
  return function (path) {
    var i
    for (i = 0; i < whatArray.length; i = i + 1) {
      if (path === whatArray[i]) {
        return true
      }
    }
    return false
  }
}

var negate = function (gen) {
  return function () {
    var f = gen.apply(undefined, arguments)
    return function () {
      return !f.apply(undefined, arguments)
    }
  }
}

var generators = {
  equals: equals,
  equalsNot: negate(equals),
  contains: contains,
  containsNot: negate(contains),
  containsAllOf: containsAllOf,
  containsOneOf: containsOneOf,
  startsWith: startsWith,
  startsNotWith: negate(startsWith),
  endsWith: endsWith,
  endsNotWith: negate(endsWith),
  equalsOneOf: equalsOneOf,
  equalsNotOneOf: negate(equalsOneOf)
}

var predicateOrder = [
  'equals',
  'equalsNot',
  'endsWith',
  'startsWith',
  'contains',
  'containsNot',
  'containsAllOf',
  'containsOneOf',
  'startsNotWith',
  'endsNotWith',
  'equalsOneOf',
  'equalsNotOneOf'
]

exports.create = function (options) {
  if (!isDefined(options.path)) {
    return
  }
  var po = options.path
  var ci = po.caseInsensitive
  var pred
  var predicates = []

  predicateOrder.forEach(function (name) {
    var gen
    var option = po[name]
    if (isDefined(option)) {
      gen = generators[name]
      if (ci) {
        if (Array.isArray(option)) {
          option = option.map(function (op) {
            return op.toLowerCase()
          })
        } else {
          option = option.toLowerCase()
        }
      }
      predicates.push(gen(option))
    }
  })

  var applyPredicates = function (path) {
    for (var i = 0; i < predicates.length; ++i) {
      if (!predicates[i](path)) {
        return false
      }
    }
    return true
  }

  var pathMatcher

  if (ci) {
    if (predicates.length === 1) {
      pred = predicates[0]
      pathMatcher = function (path, lowerPath) {
        return pred(lowerPath)
      }
    } else {
      pathMatcher = function (path, lowerPath) {
        return applyPredicates(lowerPath)
      }
    }
  } else {
    if (predicates.length === 1) {
      pred = predicates[0]
      pathMatcher = function (path) {
        return pred(path)
      }
    } else {
      pathMatcher = function (path) {
        return applyPredicates(path)
      }
    }
  }

  return pathMatcher // eslint-disable-line consistent-return
}
<|endoftext|>


<commit_before>const allAttributes = require('../fixtures/attributes');
const allRelationships = require('../fixtures/relationships');
const TypeMapping = require('./type-mapping');
const getNestedProperty = require('./nested-property');
const checkPurchased = require('./check-purchased');
const slug = require('slugg');
const sortImages = require('./helpers/jsonapi-response/sort-images.js');

module.exports = (data, config, relatedItems) => {
  const type = TypeMapping.toExternal(data._type);
  const id = TypeMapping.toExternal(data._id);
  const attributes = getAttributes(data._source);
  const relationships = getRelationships(data._source, relatedItems, type);
  const included = getIncluded(data._source, relationships, config, relatedItems, type);
  const links = getLinks(config, type, id, relationships);
  const inProduction = config && config.NODE_ENV === 'production';

  if (attributes.multimedia) {
    attributes.multimedia = getImagePaths(attributes, config);
    attributes.multimedia = sortImages(attributes.multimedia);
  }

  return {data: {type, id, attributes, links, relationships}, included, inProduction};
};

function getImagePaths (attributes, config) {
  var multimedia = attributes.multimedia;
  multimedia = multimedia.map(e => {
    if (e.processed) {
      var processed = e.processed;
      Object.keys(processed).forEach(k => {
        if (k === 'zoom') {
          processed[k].location = config.zoomPath + processed[k].location;
        } else {
          processed[k].location = config.mediaPath + processed[k].location;
        }

        delete processed[k].location_is_relative;
      });
      e.processed = processed;
    }
    return e;
  });

  return multimedia;
}

function getAttributes (data) {
  const attributes = {};

  allAttributes.forEach((key) => {
    if (data[key]) {
      attributes[key] = data[key];
      // temporary - restrict credit line if it contains 'Purchased'
      // https://github.com/TheScienceMuseum/collectionsonline/issues/195
      if (key === 'legal' && checkPurchased(attributes, key)) {
        delete attributes[key].credit_line;
      }
    }
  });

  return attributes;
}

function getLinks (config, type, id, relationships) {
  var links = {
    self: `${config.rootUrl}/${type}/${id}`,
    root: config.rootUrl,
    api: `${config.rootUrl}/api/${type}/${id}`
  };
  if (relationships && relationships.parent) {
    links.parent = `${config.rootUrl}/${relationships.parent.data[0].type}/${relationships.parent.data[0].id}`;
  }
  return links;
}

function getRelationships (data, relatedItems, type) {
  const relationships = {};

  allRelationships.forEach((key) => {
    const externalKey = TypeMapping.toExternal(key);

    if (data[key]) {
      relationships[externalKey] = {data: []};

      data[key].forEach((el, i) => {
        var rel = {
          type: '',
          id: ''
        };

        if (el.admin) {
          rel.id = TypeMapping.toExternal(el.admin.uid);
          rel.type = TypeMapping.toExternal(el.admin.id.split('-')[0]);
          relationships[externalKey].data.push(rel);
        }
      });
    }
  });

  const creationDetails = getCreationDetails(data);

  if (creationDetails) {
    relationships.maker = creationDetails.makers;
    relationships.places = creationDetails.places;
  }

  if (relatedItems && type === 'people') {
    relationships.objects = {};
    relationships.documents = {};
    relationships.objects.data = relatedItems.relatedObjects.map(returnRelationship);
    relationships.documents.data = relatedItems.relatedDocuments.map(returnRelationship);
  } else if (relatedItems && type === 'documents') {
    relationships.children = {};
    relationships.siblings = {};
    relationships.children.data = relatedItems.relatedChildren.map(returnRelationship);
    relationships.siblings.data = relatedItems.relatedSiblings.map(returnRelationship);
  } else if (relatedItems && type === 'objects') {
    relationships.objects = {};
    relationships.objects.data = relatedItems.relatedObjects.map(returnRelationship);
  }

  if (Object.keys(relationships).length) {
    return relationships;
  }
}

function returnRelationship (el) {
  return {
    type: el.type || TypeMapping.toExternal(el._type),
    id: el.id || TypeMapping.toExternal(el._id)
  };
}

function getIncluded (data, relationships, config, relatedItems, type) {
  if (relationships) {
    var included = [];

    Object.keys(relationships).forEach((key) => {
      var internalKey;
      if (key !== 'objects' && key !== 'children' && key !== 'siblings' && key !== 'documents') {
        var resources = relationships[key] || {data: []};
        resources.data.forEach((res) => {
          var resource = {};
          var originalResource;

          resource.type = res.type;
          resource.id = res.id;

          resource.attributes = {};

          if (
            key === 'maker' || (key === 'places' &&
            getNestedProperty(data, 'lifecycle.creation.0.places') &&
            getNestedProperty(data, 'lifecycle.creation.0.places').some(el => {
              if (el.admin) {
                return el.admin.uid === res.id;
              }
            }))
          ) {
            originalResource = data.lifecycle.creation[0][TypeMapping.toInternal(key)];
            resource.attributes.role = {type: key};
          } else {
            if (key === 'people') {
              internalKey = 'agents';
            } else {
              internalKey = TypeMapping.toInternal(key);
            }
            originalResource = data[internalKey] || [];
          }

          originalResource.forEach((el) => {
            if (el.admin && TypeMapping.toExternal(el.admin.uid) === resource.id) {
              Object.keys(el).forEach((key) => {
                if (key !== '@link' && key !== 'admin') {
                  resource.attributes[key] = el[key];
                } else if (key === '@link' && el[key].role) {
                  resource.attributes.role = resource.attributes.role || {};
                  resource.attributes.role.value = el[key].role[0].value;
                }
              });
            }
          });
          resource.links = {};
          var slugValue = resource.attributes.summary_title && slug(resource.attributes.summary_title).toLowerCase();
          slugValue = slugValue ? ('/' + slugValue) : '';
          resource.links.self = config.rootUrl + '/' + resource.type + '/' + resource.id + slugValue;
          included.push(resource);
        });
      }
    });

    if (relatedItems) {
      var allRelated = Object.keys(relatedItems).map(el => {
        return relatedItems[el];
      }).reduce((prev, curr) => {
        return prev.concat(curr);
      });
      included = included.concat(allRelated);
    }

    return included;
  }
}

function getCreationDetails (data) {
  if (data.lifecycle && data.lifecycle.creation) {
    const makers = {data: []};
    const places = {data: []};

    data.lifecycle.creation.forEach((el) => {
      if (el.maker) {
        el.maker.forEach((el) => {
          const maker = {};
          if (el.admin) {
            maker.type = el.admin.id && TypeMapping.toExternal(el.admin.id.split('-')[0]);
            maker.id = TypeMapping.toExternal(el.admin.uid);
            makers.data.push(maker);
          }
        });
      }

      if (el.places) {
        el.places.forEach((el) => {
          const place = {};
          if (el.admin) {
            place.type = el.admin.id && TypeMapping.toExternal(el.admin.id.split('-')[0]);
            place.id = TypeMapping.toExternal(el.admin.uid);
            places.data.push(place);
          }
        });
      }
    });

    return { makers, places };
  }
}
<commit_msg>gets related people for archives #747<commit_after>const allAttributes = require('../fixtures/attributes');
const allRelationships = require('../fixtures/relationships');
const TypeMapping = require('./type-mapping');
const getNestedProperty = require('./nested-property');
const checkPurchased = require('./check-purchased');
const slug = require('slugg');
const sortImages = require('./helpers/jsonapi-response/sort-images.js');

module.exports = (data, config, relatedItems) => {
  const type = TypeMapping.toExternal(data._type);
  const id = TypeMapping.toExternal(data._id);
  const attributes = getAttributes(data._source);
  const relationships = getRelationships(data._source, relatedItems, type);
  const included = getIncluded(data._source, relationships, config, relatedItems, type);
  const links = getLinks(config, type, id, relationships);
  const inProduction = config && config.NODE_ENV === 'production';

  if (attributes.multimedia) {
    attributes.multimedia = getImagePaths(attributes, config);
    attributes.multimedia = sortImages(attributes.multimedia);
  }

  return {data: {type, id, attributes, links, relationships}, included, inProduction};
};

function getImagePaths (attributes, config) {
  var multimedia = attributes.multimedia;
  multimedia = multimedia.map(e => {
    if (e.processed) {
      var processed = e.processed;
      Object.keys(processed).forEach(k => {
        if (k === 'zoom') {
          processed[k].location = config.zoomPath + processed[k].location;
        } else {
          processed[k].location = config.mediaPath + processed[k].location;
        }

        delete processed[k].location_is_relative;
      });
      e.processed = processed;
    }
    return e;
  });

  return multimedia;
}

function getAttributes (data) {
  const attributes = {};

  allAttributes.forEach((key) => {
    if (data[key]) {
      attributes[key] = data[key];
      // temporary - restrict credit line if it contains 'Purchased'
      // https://github.com/TheScienceMuseum/collectionsonline/issues/195
      if (key === 'legal' && checkPurchased(attributes, key)) {
        delete attributes[key].credit_line;
      }
    }
  });

  return attributes;
}

function getLinks (config, type, id, relationships) {
  var links = {
    self: `${config.rootUrl}/${type}/${id}`,
    root: config.rootUrl,
    api: `${config.rootUrl}/api/${type}/${id}`
  };
  if (relationships && relationships.parent) {
    links.parent = `${config.rootUrl}/${relationships.parent.data[0].type}/${relationships.parent.data[0].id}`;
  }
  return links;
}

function getRelationships (data, relatedItems, type) {
  const relationships = {};

  allRelationships.forEach((key) => {
    const externalKey = TypeMapping.toExternal(key);

    if (data[key] || (data.content && data.content[key])) {
      var dk = data[key] || data.content[key];
      relationships[externalKey] = {data: []};

      dk.forEach((el, i) => {
        var rel = {
          type: '',
          id: ''
        };

        if (el.admin) {
          rel.id = TypeMapping.toExternal(el.admin.uid);
          rel.type = TypeMapping.toExternal(el.admin.id.split('-')[0]);
          relationships[externalKey].data.push(rel);
        }
      });
    }
  });

  const creationDetails = getCreationDetails(data);

  if (creationDetails) {
    relationships.maker = creationDetails.makers;
    relationships.places = creationDetails.places;
  }

  if (relatedItems && type === 'people') {
    relationships.objects = {};
    relationships.documents = {};
    relationships.objects.data = relatedItems.relatedObjects.map(returnRelationship);
    relationships.documents.data = relatedItems.relatedDocuments.map(returnRelationship);
  } else if (relatedItems && type === 'documents') {
    relationships.children = {};
    relationships.siblings = {};
    relationships.children.data = relatedItems.relatedChildren.map(returnRelationship);
    relationships.siblings.data = relatedItems.relatedSiblings.map(returnRelationship);
  } else if (relatedItems && type === 'objects') {
    relationships.objects = {};
    relationships.objects.data = relatedItems.relatedObjects.map(returnRelationship);
  }

  if (Object.keys(relationships).length) {
    return relationships;
  }
}

function returnRelationship (el) {
  return {
    type: el.type || TypeMapping.toExternal(el._type),
    id: el.id || TypeMapping.toExternal(el._id)
  };
}

function getIncluded (data, relationships, config, relatedItems, type) {
  if (relationships) {
    var included = [];

    Object.keys(relationships).forEach((key) => {
      var internalKey;
      if (key !== 'objects' && key !== 'children' && key !== 'siblings' && key !== 'documents') {
        var resources = relationships[key] || {data: []};
        resources.data.forEach((res) => {
          var resource = {};
          var originalResource;

          resource.type = res.type;
          resource.id = res.id;

          resource.attributes = {};

          if (
            key === 'maker' || (key === 'places' &&
            getNestedProperty(data, 'lifecycle.creation.0.places') &&
            getNestedProperty(data, 'lifecycle.creation.0.places').some(el => {
              if (el.admin) {
                return el.admin.uid === res.id;
              }
            }))
          ) {
            originalResource = data.lifecycle.creation[0][TypeMapping.toInternal(key)];
            resource.attributes.role = {type: key};
          } else {
            if (key === 'people') {
              internalKey = 'agents';
            } else {
              internalKey = TypeMapping.toInternal(key);
            }
            originalResource = data[internalKey] || (data.content && data.content[internalKey]) || [];
          }

          originalResource.forEach((el) => {
            if (el.admin && TypeMapping.toExternal(el.admin.uid) === resource.id) {
              Object.keys(el).forEach((key) => {
                if (key !== '@link' && key !== 'admin') {
                  resource.attributes[key] = el[key];
                } else if (key === '@link' && el[key].role) {
                  resource.attributes.role = resource.attributes.role || {};
                  resource.attributes.role.value = el[key].role[0].value;
                }
              });
            }
          });
          resource.links = {};
          var slugValue = resource.attributes.summary_title && slug(resource.attributes.summary_title).toLowerCase();
          slugValue = slugValue ? ('/' + slugValue) : '';
          resource.links.self = config.rootUrl + '/' + resource.type + '/' + resource.id + slugValue;
          included.push(resource);
        });
      }
    });

    if (relatedItems) {
      var allRelated = Object.keys(relatedItems).map(el => {
        return relatedItems[el];
      }).reduce((prev, curr) => {
        return prev.concat(curr);
      });
      included = included.concat(allRelated);
    }

    return included;
  }
}

function getCreationDetails (data) {
  if (data.lifecycle && data.lifecycle.creation) {
    const makers = {data: []};
    const places = {data: []};

    data.lifecycle.creation.forEach((el) => {
      if (el.maker) {
        el.maker.forEach((el) => {
          const maker = {};
          if (el.admin) {
            maker.type = el.admin.id && TypeMapping.toExternal(el.admin.id.split('-')[0]);
            maker.id = TypeMapping.toExternal(el.admin.uid);
            makers.data.push(maker);
          }
        });
      }

      if (el.places) {
        el.places.forEach((el) => {
          const place = {};
          if (el.admin) {
            place.type = el.admin.id && TypeMapping.toExternal(el.admin.id.split('-')[0]);
            place.id = TypeMapping.toExternal(el.admin.uid);
            places.data.push(place);
          }
        });
      }
    });

    return { makers, places };
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    extends: require.resolve('eslint-config-hapi'),
    parserOptions: {
        ecmaVersion: 8,
        ecmaFeatures: {
            experimentalObjectRestSpread: true
        }
    }
};
<commit_msg>Update ecmaversion in eslint<commit_after>'use strict';

module.exports = {
    extends: require.resolve('eslint-config-hapi'),
    parserOptions: {
        ecmaVersion: 9
    }
};
<|endoftext|>