<commit_before>const personalData = require('./personalData');

function textMe(text, debug) {
  // Send myself text messages with twilio
  // https://www.twilio.com/docs/quickstart/node/programmable-sms

  if (
    personalData.twilio.account_sid !== '' &&
    personalData.twilio.auth_token !== ''
  ) {
    // eslint-disable-next-line global-require
    const client = require('twilio')(
      personalData.twilio.account_sid,
      personalData.twilio.auth_token,
    );
    // Pass in parameters to the REST API using an object literal notation. The
    // REST client will handle authentication and response serialzation for you.
    client.messages.create(
      {
        to: personalData.twilio.my_phone_number,
        from: personalData.twilio.number,
        body: text,
      },
      (error, message) => {
        // The HTTP request to Twilio will run asynchronously. This callback
        // function will be called when a response is received from Twilio
        // The "error" variable will contain error information, if any.
        // If the request was successful, this value will be "falsy"
        if (!error) {
          // The second argument to the callback will contain the information
          // sent back by Twilio for the request. In this case, it is the
          // information about the text message you just sent:
          if (debug) {
            console.log('Success! The SID for this SMS message is:');
            console.log(message.sid);
            console.log('Message sent on:');
            console.log(message.dateCreated);
          }
        } else if (debug) {
          console.error('Twilio Error:');
          console.error(error);
        } else {
          console.error('Twilio Error');
        }
      },
    );
  }
}

module.exports = textMe;

if (require.main === module) {
  if (process.argv.length < 3) {
    console.log('You must provide text for the message, like this:');
    console.log(`node textme.js "test message"`);
    process.exit();
  }
  textMe(process.argv[2], true);
}
<commit_msg>Speling<commit_after>const personalData = require('./personalData');

function textMe(text, debug) {
  // Send myself text messages with twilio
  // https://www.twilio.com/docs/quickstart/node/programmable-sms

  if (
    personalData.twilio.account_sid !== '' &&
    personalData.twilio.auth_token !== ''
  ) {
    // eslint-disable-next-line global-require
    const client = require('twilio')(
      personalData.twilio.account_sid,
      personalData.twilio.auth_token,
    );
    // Pass in parameters to the REST API using an object literal notation. The
    // REST client will handle authentication and response serialization for you.
    client.messages.create(
      {
        to: personalData.twilio.my_phone_number,
        from: personalData.twilio.number,
        body: text,
      },
      (error, message) => {
        // The HTTP request to Twilio will run asynchronously. This callback
        // function will be called when a response is received from Twilio
        // The "error" variable will contain error information, if any.
        // If the request was successful, this value will be "falsy"
        if (!error) {
          // The second argument to the callback will contain the information
          // sent back by Twilio for the request. In this case, it is the
          // information about the text message you just sent:
          if (debug) {
            console.log('Success! The SID for this SMS message is:');
            console.log(message.sid);
            console.log('Message sent on:');
            console.log(message.dateCreated);
          }
        } else if (debug) {
          console.error('Twilio Error:');
          console.error(error);
        } else {
          console.error('Twilio Error');
        }
      },
    );
  }
}

module.exports = textMe;

if (require.main === module) {
  if (process.argv.length < 3) {
    console.log('You must provide text for the message, like this:');
    console.log(`node textme.js "test message"`);
    process.exit();
  }
  textMe(process.argv[2], true);
}
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-g-map',

  included: function(app, parentAddon) {
    var target = (parentAddon || app);
    target.import('vendor/addons.css');
  },

  contentFor: function(type, config) {
    var content = '';

    if (type === 'head') {
      var src = '//maps.googleapis.com/maps/api/js';
      var gMapConfig = config['g-map'] || {};
      var params = [];

      var key = gMapConfig.key;
      if (key) {
        params.push('key=' + encodeURIComponent(key));
      }

      var version = gMapConfig.version;
      if (version) {
        params.push('v=' + encodeURIComponent(version));
      }

      var client = gMapConfig.client;
      if (client) {
        params.push('client=' + encodeURIComponent(client));
        if (!version) {
          params.push('v=3');
        }
      }

      var libraries = gMapConfig.libraries;
      if (libraries && libraries.length) {
        params.push('libraries=' + encodeURIComponent(libraries.join(',')));
      }

      var language = gMapConfig.language;
      if (language) {
        params.push('language=' + encodeURIComponent(language));
      }

      var protocol = gMapConfig.protocol;
      if (protocol) {
        src = protocol + ':' + src;
      }

      src += '?' + params.join('&');
      content = '<script type="text/javascript" src="' + src + '"></script>';

      var exclude = gMapConfig.exclude;
      if (exclude) {
        content = ''
      }
    }

    return content;
  }
};
<commit_msg>Remove version when client is used<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-g-map',

  included: function(app, parentAddon) {
    var target = (parentAddon || app);
    target.import('vendor/addons.css');
  },

  contentFor: function(type, config) {
    var content = '';

    if (type === 'head') {
      var src = '//maps.googleapis.com/maps/api/js';
      var gMapConfig = config['g-map'] || {};
      var params = [];

      var key = gMapConfig.key;
      if (key) {
        params.push('key=' + encodeURIComponent(key));
      }

      var version = gMapConfig.version;
      if (version) {
        params.push('v=' + encodeURIComponent(version));
      }

      var client = gMapConfig.client;
      if (client) {
        params.push('client=' + encodeURIComponent(client));
      }

      var libraries = gMapConfig.libraries;
      if (libraries && libraries.length) {
        params.push('libraries=' + encodeURIComponent(libraries.join(',')));
      }

      var language = gMapConfig.language;
      if (language) {
        params.push('language=' + encodeURIComponent(language));
      }

      var protocol = gMapConfig.protocol;
      if (protocol) {
        src = protocol + ':' + src;
      }

      src += '?' + params.join('&');
      content = '<script type="text/javascript" src="' + src + '"></script>';

      var exclude = gMapConfig.exclude;
      if (exclude) {
        content = ''
      }
    }

    return content;
  }
};
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');

AWS.config.update({accessKeyId: 'your-access-key', secretAccessKey: 'your-secret-access'});
AWS.config.update({region: 'your-region'});

var ec2 = new AWS.EC2();

module.exports.changeTag = function(timeout, oldTags, newTags, beforeHook) {
  schedule(timeout, beforeHook, function() {
    getInstanceId(oldTags, function(id) {
      ec2.createTags({ Resources: [id], Tags: newTags }, function(err, data) {
        if (err) console.log(err);
      });
    });
  });
};

module.exports.terminate = function(timeout, tags, beforeHook) {
  schedule(timeout, beforeHook, function() {
    getInstanceId(tags, function(id) {
      ec2.terminateInstances({ InstanceIds: [ id ] }, function(err, data) {
        if (err) console.log(err);
      });
    });
  });
};

function schedule(timeout, beforeHook, action) {
  timeout = timeout || 60 * 60 * 1000;
  beforeHook = beforeHook || function(cb) { cb(); };
  setTimeout(function() {
    beforeHook(action);
  }, timeout * Math.random());
}

function getInstanceId(tags, cb) {
  var params = {
    Filters: [
      { Name: 'instance-state-name', Values: ['running'] },
      { Name: 'tag-key', Values: tags.names },
      { Name: 'tag-value', Values: tags.values }
    ]
  };

  ec2.describeInstances(params, function(error, data) {
    if (error) return console.log(error);
    var instanceIds = data.Reservations.map(function(reservation) {
      return reservation.Instances[0].InstanceId;
    });
    var instanceId = instanceIds[Math.floor(Math.random() * instanceIds.length)];
    cb(instanceId);
  });
}
<commit_msg>reuse the instanceId, minor tweaks<commit_after>var AWS = require('aws-sdk');
AWS.config.update({
  accessKeyId: 'your-access-key',
  secretAccessKey: 'your-secret-access',
  region: 'your-region'
});
var ec2 = new AWS.EC2();

var instanceId;

module.exports.changeTag = function(timeout, oldTags, newTags, beforeHook, afterHook) {
  schedule(timeout, beforeHook, function() {
    getInstanceId(oldTags, function(id) {
      instanceId = instanceId || id;
      ec2.createTags({ Resources: [id], Tags: newTags }, function(err, data) {
        if (err) console.log(err);
        afterHook(err, data);
      });
    });
  });
};

module.exports.terminate = function(timeout, tags, beforeHook, afterHook) {
  schedule(timeout, beforeHook, function() {
    getInstanceId(tags, function(id) {
      instanceId = instanceId || id;
      ec2.terminateInstances({ InstanceIds: [ id ] }, function(err, data) {
        if (err) console.log(err);
        afterHook(err, data);
      });
    });
  });
};

function schedule(timeout, beforeHook, action) {
  timeout = timeout || 60 * 60 * 1000;
  beforeHook = beforeHook || function(cb) { cb(); };
  setTimeout(function() {
    beforeHook(action);
  }, timeout * Math.random());
}

function getInstanceId(tags, cb) {
  var params = {
    Filters: [
      { Name: 'instance-state-name', Values: ['running'] },
      { Name: 'tag-key', Values: tags.names },
      { Name: 'tag-value', Values: tags.values }
    ]
  };

  ec2.describeInstances(params, function(error, data) {
    if (error) return console.log(error);
    var instanceIds = data.Reservations.map(function(reservation) {
      return reservation.Instances[0].InstanceId;
    });
    var instanceId = instanceIds[Math.floor(Math.random() * instanceIds.length)];
    cb(instanceId);
  });
}
<|endoftext|>


<commit_before>'use strict';

var d              = require('d')
  , assign         = require('es5-ext/object/assign')
  , forEach        = require('es5-ext/object/for-each')
  , map            = require('es5-ext/object/map')
  , repeat         = require('es5-ext/string/#/repeat')
  , memoize        = require('memoizee')
  , memoizeMethods = require('memoizee/methods')
  , tty            = require('tty')

  , join = Array.prototype.join, defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties, abs = Math.abs
  , floor = Math.floor, max = Math.max, min = Math.min

  , mods, proto, getFn, getMove, xtermMatch
  , up, down, right, left, getHeight, memoized;

mods = assign({
	// Style
	bold:      { _bold: [1, 22] },
	italic:    { _italic: [3, 23] },
	underline: { _underline: [4, 24] },
	blink:     { _blink: [5, 25] },
	inverse:   { _inverse: [7, 27] },
	strike:    { _strike: [9, 29] }
},

	// Color
	['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
		.reduce(function (obj, color, index) {
		// foreground
		obj[color] = { _fg: [30 + index, 39] };
		obj[color + 'Bright'] = { _fg: [90 + index, 39] };

		// background
		obj['bg' + color[0].toUpperCase() + color.slice(1)] =
			{ _bg: [40 + index, 49] };
		obj['bg' + color[0].toUpperCase() + color.slice(1) + 'Bright'] =
			{ _bg: [100 + index, 49] };

		return obj;
	}, {}));

// Some use cli-color as: console.log(clc.red('Error!'));
// Which is inefficient as on each call it configures new clc object
// with memoization we reuse once created object
memoized = memoize(function (scope, mod) {
	return defineProperty(getFn(), '_cliColorData',
		d(assign({}, scope._cliColorData, mod)));
});

proto = Object.create(Function.prototype, assign(map(mods, function (mod) {
	return d.gs(function () { return memoized(this, mod); });
}), memoizeMethods({
	// xterm (255) color
	xterm: d(function (code) {
		code = isNaN(code) ? 255 : min(max(code, 0), 255);
		return defineProperty(getFn(), '_cliColorData',
			d(assign({}, this._cliColorData, {
				_fg: [xtermMatch ? xtermMatch[code] : ('38;5;' + code), 39]
			})));
	}),
	bgXterm: d(function (code) {
		code = isNaN(code) ? 255 : min(max(code, 0), 255);
		return defineProperty(getFn(), '_cliColorData',
			d(assign({}, this._cliColorData, {
				_bg: [xtermMatch ? (xtermMatch[code] + 10) : ('48;5;' + code), 49]
			})));
	})
})));

if (process.platform === 'win32') {
	xtermMatch = require('./lib/xterm-match');
}

getFn = function () {
	var fn = function (/*…msg*/) {
		var start = '', end = '';
		forEach(fn._cliColorData, function (mod) {
			end = '\x1b[' + mod[1] + 'm' + end;
			start += '\x1b[' + mod[0] + 'm';
		}, null, true);
		return start + join.call(arguments, ' ') + end;
	};
	fn.__proto__ = proto;
	return fn;
};

getMove = function (control) {
	return function (num) {
		num = isNaN(num) ? 0 : max(floor(num), 0);
		return num ? ('\x1b[' + num + control) : '';
	};
};

module.exports = defineProperties(getFn(), {
	width: d.gs(process.stdout.getWindowSize ? function () {
		return process.stdout.getWindowSize()[0];
	} : function () {
		return tty.getWindowSize ? tty.getWindowSize()[1] : 0;
	}),
	height: d.gs(getHeight = process.stdout.getWindowSize ? function () {
		return process.stdout.getWindowSize()[1];
	} : function () {
		return tty.getWindowSize ? tty.getWindowSize()[0] : 0;
	}),
	reset: d.gs(function () {
		return repeat.call('\n', getHeight() - 1) + '\x1bc';
	}),
	up: d(up = getMove('A')),
	down: d(down = getMove('B')),
	right: d(right = getMove('C')),
	left: d(left = getMove('D')),
	move: d(function (x, y) {
		x = isNaN(x) ? 0 : floor(x);
		y = isNaN(y) ? 0 : floor(y);
		return ((x > 0) ? right(x) : left(-x)) + ((y > 0) ? down(y) : up(-y));
	}),
	moveTo: d(function (x, y) {
		x = isNaN(x) ? 1 : (max(floor(x), 0) + 1);
		y = isNaN(y) ? 1 : (max(floor(y), 0) + 1);
		return '\x1b[' + y + ';' + x + 'H';
	}),
	bol: d(function (n/*, erase*/) {
		var dir;
		n = isNaN(n) ? 0 : Number(n);
		dir = (n >= 0) ? 'E' : 'F';
		n = floor(abs(n));
		return arguments[1] ?
				(((!n || (dir === 'F')) ? '\x1b[0E\x1bK' : '') +
					repeat.call('\x1b[1' + dir + '\x1b[K', n)) : '\x1b[' + n + dir;
	}),
	beep: d('\x07'),
	xtermSupported: d(!xtermMatch),
	_cliColorData: d({})
});
<commit_msg>-- whitespace<commit_after>'use strict';

var d              = require('d')
  , assign         = require('es5-ext/object/assign')
  , forEach        = require('es5-ext/object/for-each')
  , map            = require('es5-ext/object/map')
  , repeat         = require('es5-ext/string/#/repeat')
  , memoize        = require('memoizee')
  , memoizeMethods = require('memoizee/methods')
  , tty            = require('tty')

  , join = Array.prototype.join, defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties, abs = Math.abs
  , floor = Math.floor, max = Math.max, min = Math.min

  , mods, proto, getFn, getMove, xtermMatch
  , up, down, right, left, getHeight, memoized;

mods = assign({
	// Style
	bold:      { _bold: [1, 22] },
	italic:    { _italic: [3, 23] },
	underline: { _underline: [4, 24] },
	blink:     { _blink: [5, 25] },
	inverse:   { _inverse: [7, 27] },
	strike:    { _strike: [9, 29] }
},

	// Color
	['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
		.reduce(function (obj, color, index) {
		// foreground
		obj[color] = { _fg: [30 + index, 39] };
		obj[color + 'Bright'] = { _fg: [90 + index, 39] };

		// background
		obj['bg' + color[0].toUpperCase() + color.slice(1)] = { _bg: [40 + index, 49] };
		obj['bg' + color[0].toUpperCase() + color.slice(1) + 'Bright'] = { _bg: [100 + index, 49] };

		return obj;
	}, {}));

// Some use cli-color as: console.log(clc.red('Error!'));
// Which is inefficient as on each call it configures new clc object
// with memoization we reuse once created object
memoized = memoize(function (scope, mod) {
	return defineProperty(getFn(), '_cliColorData', d(assign({}, scope._cliColorData, mod)));
});

proto = Object.create(Function.prototype, assign(map(mods, function (mod) {
	return d.gs(function () { return memoized(this, mod); });
}), memoizeMethods({
	// xterm (255) color
	xterm: d(function (code) {
		code = isNaN(code) ? 255 : min(max(code, 0), 255);
		return defineProperty(getFn(), '_cliColorData',
			d(assign({}, this._cliColorData, {
				_fg: [xtermMatch ? xtermMatch[code] : ('38;5;' + code), 39]
			})));
	}),
	bgXterm: d(function (code) {
		code = isNaN(code) ? 255 : min(max(code, 0), 255);
		return defineProperty(getFn(), '_cliColorData',
			d(assign({}, this._cliColorData, {
				_bg: [xtermMatch ? (xtermMatch[code] + 10) : ('48;5;' + code), 49]
			})));
	})
})));

if (process.platform === 'win32') xtermMatch = require('./lib/xterm-match');

getFn = function () {
	var fn = function (/*…msg*/) {
		var start = '', end = '';
		forEach(fn._cliColorData, function (mod) {
			end = '\x1b[' + mod[1] + 'm' + end;
			start += '\x1b[' + mod[0] + 'm';
		}, null, true);
		return start + join.call(arguments, ' ') + end;
	};
	fn.__proto__ = proto;
	return fn;
};

getMove = function (control) {
	return function (num) {
		num = isNaN(num) ? 0 : max(floor(num), 0);
		return num ? ('\x1b[' + num + control) : '';
	};
};

module.exports = defineProperties(getFn(), {
	width: d.gs(process.stdout.getWindowSize ? function () {
		return process.stdout.getWindowSize()[0];
	} : function () {
		return tty.getWindowSize ? tty.getWindowSize()[1] : 0;
	}),
	height: d.gs(getHeight = process.stdout.getWindowSize ? function () {
		return process.stdout.getWindowSize()[1];
	} : function () {
		return tty.getWindowSize ? tty.getWindowSize()[0] : 0;
	}),
	reset: d.gs(function () { return repeat.call('\n', getHeight() - 1) + '\x1bc'; }),
	up: d(up = getMove('A')),
	down: d(down = getMove('B')),
	right: d(right = getMove('C')),
	left: d(left = getMove('D')),
	move: d(function (x, y) {
		x = isNaN(x) ? 0 : floor(x);
		y = isNaN(y) ? 0 : floor(y);
		return ((x > 0) ? right(x) : left(-x)) + ((y > 0) ? down(y) : up(-y));
	}),
	moveTo: d(function (x, y) {
		x = isNaN(x) ? 1 : (max(floor(x), 0) + 1);
		y = isNaN(y) ? 1 : (max(floor(y), 0) + 1);
		return '\x1b[' + y + ';' + x + 'H';
	}),
	bol: d(function (n/*, erase*/) {
		var dir;
		n = isNaN(n) ? 0 : Number(n);
		dir = (n >= 0) ? 'E' : 'F';
		n = floor(abs(n));
		return (arguments[1]
			? (((!n || (dir === 'F')) ? '\x1b[0E\x1bK' : '') + repeat.call('\x1b[1' + dir + '\x1b[K', n))
			: '\x1b[' + n + dir);
	}),
	beep: d('\x07'),
	xtermSupported: d(!xtermMatch),
	_cliColorData: d({})
});
<|endoftext|>


<commit_before>/* Magic Mirror
 * Module: MVG-LocalTransport
 *
 * By Anthony Graglia
 * Derived from Georg Peters (https://lane6.de)
 * Based on a script from Benjamin Angst http://www.beny.ch
 * MIT Licensed.
 */

const NodeHelper = require("node_helper");
const forge = require('node-forge');
const unirest = require('unirest');

module.exports = NodeHelper.create({

    start: function () {
        this.started = false;
    },

    /* updateTimetable(transports)
     * Calls processTrains on successful response.
     */
    updateTimetable: function () {
        var url = this.config.apiBase + this.config.id;
        var retry = true;
        var data = {};

        unirest.get(url)
            .headers({
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            })
            .send(JSON.stringify(data))
            .end(function (json) {
                console.log("RESPONSE: ", JSON.stringify(json));
                this.processTrains(json['departures']);

                /*if (retry) {
                 this.scheduleUpdate(this.loaded ? -1 : this.config.retryDelay);
                 }*/
            });
    },

    /* processTrains(departures)
     * Uses the received data to build a data structure for rendering.
     */
    processTrains: function (departures) {
        var now = new Date();
        var items = {};

        for (var i = 0; i < departures.length; i++) {
            var departure = departures[i];
            var destination = departure['destination'];
            var departureTime = new Date(departure['departureTime']);
            var departureMinutes = Math.floor((Math.abs(departureTime - now) / 1000) / 60);

            items[destination] = items[destination] || {
                    'label': departure['label'],
                    'product': departure['product'],
                    'lineColor': departure['lineBackgroundColor'],
                    'departureTimes': []
                };
            items[destination]['departureTimes'].push(departureMinutes);
        }

        this.items = items;
        this.loaded = true;
        this.sendSocketNotification("TRAINS", this.items);
    },

    /* scheduleUpdate()
     * Schedule next update.
     * argument delay number - Millis econds before next update. If empty, this.config.updateInterval is used.
     */
    scheduleUpdate: function (delay) {
        var nextLoad = this.config.updateInterval;
        if (typeof delay !== "undefined" && delay >= 0) {
            nextLoad = delay;
        }

        var self = this;
        clearTimeout(this.updateTimer);
        this.updateTimer = setTimeout(function () {
            self.updateTimetable();
        }, nextLoad);
    },

    socketNotificationReceived: function (notification, payload) {
        const self = this;
        if (notification === 'CONFIG' && this.started == false) {
            this.config = payload;
            this.started = true;
            self.scheduleUpdate(this.config.initialLoadDelay);
        }
    }
});
<commit_msg>It is too late... Must improve dev workflow here...<commit_after>/* Magic Mirror
 * Module: MVG-LocalTransport
 *
 * By Anthony Graglia
 * Derived from Georg Peters (https://lane6.de)
 * Based on a script from Benjamin Angst http://www.beny.ch
 * MIT Licensed.
 */

const NodeHelper = require("node_helper");
const forge = require('node-forge');
const unirest = require('unirest');

module.exports = NodeHelper.create({

    start: function () {
        this.started = false;
    },

    /* updateTimetable(transports)
     * Calls processTrains on successful response.
     */
    updateTimetable: function () {
        var self = this;
        var url = this.config.apiBase + this.config.id;
        var retry = true;
        var data = {};

        unirest.get(url)
            .headers({
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            })
            .send(JSON.stringify(data))
            .end(function (response) {
                console.log("RESPONSE: ", JSON.stringify(response));
                self.processTrains(response['departures']);

                /*if (retry) {
                 this.scheduleUpdate(this.loaded ? -1 : this.config.retryDelay);
                 }*/
            });
    },

    /* processTrains(departures)
     * Uses the received data to build a data structure for rendering.
     */
    processTrains: function (departures) {
        var now = new Date();
        var items = {};

        for (var i = 0; i < departures.length; i++) {
            var departure = departures[i];
            var destination = departure['destination'];
            var departureTime = new Date(departure['departureTime']);
            var departureMinutes = Math.floor((Math.abs(departureTime - now) / 1000) / 60);

            items[destination] = items[destination] || {
                    'label': departure['label'],
                    'product': departure['product'],
                    'lineColor': departure['lineBackgroundColor'],
                    'departureTimes': []
                };
            items[destination]['departureTimes'].push(departureMinutes);
        }

        this.items = items;
        this.loaded = true;
        this.sendSocketNotification("TRAINS", this.items);
    },

    /* scheduleUpdate()
     * Schedule next update.
     * argument delay number - Millis econds before next update. If empty, this.config.updateInterval is used.
     */
    scheduleUpdate: function (delay) {
        var nextLoad = this.config.updateInterval;
        if (typeof delay !== "undefined" && delay >= 0) {
            nextLoad = delay;
        }

        var self = this;
        clearTimeout(this.updateTimer);
        this.updateTimer = setTimeout(function () {
            self.updateTimetable();
        }, nextLoad);
    },

    socketNotificationReceived: function (notification, payload) {
        const self = this;
        if (notification === 'CONFIG' && this.started == false) {
            this.config = payload;
            this.started = true;
            self.scheduleUpdate(this.config.initialLoadDelay);
        }
    }
});
<|endoftext|>


<commit_before>var transformTools = require("browserify-transform-tools");
var path = require("path");

module.exports = transformTools.makeRequireTransform(
    "fite-browserify-aws-sdk",
    {
        evaluateArguments: true,
        includeExtensions: [ "js" ]
    },
    function (args, opts, cb) {
        if (opts.file.match(/[\/\\]aws-sdk[\/\\]lib[\/\\]aws\.js$/)) {
            switch (args[0]) {
                case "./api_loader":
                    return cb(null, "{ load: function(svc, version) { return AWS.apiLoader.services[svc][version]; } }");
                case "./services":
                    var services = opts.config.services;
                    if (services instanceof Array) {
                        services = services.join(",");
                    }
                    if (services === undefined) {
                        services = "all";
                    }
                    var inject = "AWS.apiLoader.services = {};\n";
                    if (services) {
                        var collector = require(path.resolve(path.dirname(opts.file), "../dist-tools/service-collector"));
                        inject += collector(services);
                    }
                    return cb(null, inject);
            }
        }
        return cb();
    }
);
<commit_msg>pre-exclude regex for files<commit_after>var transformTools = require("browserify-transform-tools");
var path = require("path");

module.exports = transformTools.makeRequireTransform(
    "fite-browserify-aws-sdk",
    {
        evaluateArguments: true,
        regex: /[\/\\]aws-sdk[\/\\]lib[\/\\]aws\.js$/
    },
    function (args, opts, cb) {
        switch (args[0]) {
            case "./api_loader":
                return cb(null, "{ load: function(svc, version) { return AWS.apiLoader.services[svc][version]; } }");
            case "./services":
                var services = opts.config.services;
                if (services instanceof Array) {
                    services = services.join(",");
                }
                if (services === undefined) {
                    services = "all";
                }
                var inject = "AWS.apiLoader.services = {};\n";
                if (services) {
                    var collector = require(path.resolve(path.dirname(opts.file), "../dist-tools/service-collector"));
                    inject += collector(services);
                }
                return cb(null, inject);
        }
        return cb();
    }
);
<|endoftext|>


<commit_before>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleGuard = require('role.guard');
var roleRepair = require('role.repair');

module.exports = {

    run: function() {

    	create();

        for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	setRoleForCreep(creep);
	    }

	}
};

// Runs the role for the given creep.
function setRoleForCreep(creep){
   if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'builder') {
        roleBuilder.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'repair') {
        roleRepair.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'guard') {
        roleGuard.run(creep);
    }
}

// Counts the creeps attached to the given source.
function getCreepCountForSource(source){
	var count = 0;
	 for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	if (creep.memory.sourceId == source.id){
	    		count++;
	    	}
	 }
	 return count;
}

// Gets the source with the lowest creep count.
function getSourceWithMinCreepCount(creep){
	 var sources = creep.room.find(FIND_SOURCES);

    var minSource = null;

	 for (var i = 0; i < sources.length ; i++ ){
		 var tmpSource = sources[i];

	     if (minSource==null){
	         minSource = creep.room.find(FIND_SOURCES)[0];
	     }
		 var minSourceCount = getCreepCountForSource(minSource);
		 var tmpSourceCount = getCreepCountForSource(tmpSource);

		 if(minSourceCount >  tmpSourceCount){
			 minSource = tmpSource;
		 }
	 }
	 return minSource;
}

// Getting the source for the given creep. If the creep is not assinged to a
// source a source is randomly chossen and saved for the creep.
function getSourceForCreep(creep){
	 var sources = creep.room.find(FIND_SOURCES);
	 var sourceToMine = sources[0];

	// If the creep has no assigned source the source with the minimun creep
	// count is set for the creep.
    if (creep.memory.sourceId === undefined){
    	sourceToMine = getSourceWithMinCreepCount(creep);
        creep.memory.sourceId = sourceToMine.id;
        console.log(creep.name+"  role: "+creep.memory.role+ " source: "+creep.memory.sourceId);
    }
    return Game.getObjectById(creep.memory.sourceId);
}

// Creating all the creeps.
function create(creps) {

	clean();

	if (isEmergencyCreepCreation()){
	    console.log("Emergency creep creation.");
		if (createCreep('harvester', 8, [WORK, WORK, CARRY, MOVE])){
			return;
		}
	}

	if (createCreep('harvester', 8, [WORK, WORK, WORK, CARRY, CARRY,  MOVE, MOVE])){
		return;
	}
	if(createCreep('upgrader', 4, [WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE])){
		return;
	}
	if(createCreep('builder', 6, [WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE])){
		return;
	}
	if(createCreep('guard', 3, [ATTACK, ATTACK, MOVE, MOVE, MOVE, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH])){
		return;
	}

}

// Creates a single creep with the given role and work
function createCreep(roleTyp, counter, work){
    var exisitingCreeps = _.filter(Game.creeps, (creep) => creep.memory.role == roleTyp);
    if(exisitingCreeps.length < counter) {
        var newName = Game.spawns.Spawn1.createCreep(work, undefined, {role: roleTyp});
        if (newName<0){
        	return true;
        }
        console.log('Spawning new creep for role '+roleTyp+' with name ' + newName);
        return true;
    }
    return false;
}

// Cleans the memory from dead creeps.
function clean(){
	for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing dead creep memory:', name);
        }
    }
}

function isEmergencyCreepCreation(){
	var counter = 0;
	try{
    	for(var name in Game.creeps){
    		var creep = Game.creeps[name];
    		if(creep.memory.role){
    		    if (creep.memory.role === 'harvester'){
    		       counter++;
    		    }
    		}
    	}
	}catch(exception){
		return true;
	}

	if (counter<=5){
		return true;
	}
	return false;
}
<commit_msg>Five emergency harvester<commit_after>var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleGuard = require('role.guard');
var roleRepair = require('role.repair');

module.exports = {

    run: function() {

    	create();

        for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	setRoleForCreep(creep);
	    }

	}
};

// Runs the role for the given creep.
function setRoleForCreep(creep){
   if(creep.memory.role == 'harvester') {
        roleHarvester.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'upgrader') {
        roleUpgrader.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'builder') {
        roleBuilder.run(creep,  getSourceForCreep(creep));
    }
    if(creep.memory.role == 'repair') {
        roleRepair.run(creep, getSourceForCreep(creep));
    }
    if(creep.memory.role == 'guard') {
        roleGuard.run(creep);
    }
}

// Counts the creeps attached to the given source.
function getCreepCountForSource(source){
	var count = 0;
	 for(var name in Game.creeps) {
	    	var creep = Game.creeps[name];
	    	if (creep.memory.sourceId == source.id){
	    		count++;
	    	}
	 }
	 return count;
}

// Gets the source with the lowest creep count.
function getSourceWithMinCreepCount(creep){
	 var sources = creep.room.find(FIND_SOURCES);

    var minSource = null;

	 for (var i = 0; i < sources.length ; i++ ){
		 var tmpSource = sources[i];

	     if (minSource==null){
	         minSource = creep.room.find(FIND_SOURCES)[0];
	     }
		 var minSourceCount = getCreepCountForSource(minSource);
		 var tmpSourceCount = getCreepCountForSource(tmpSource);

		 if(minSourceCount >  tmpSourceCount){
			 minSource = tmpSource;
		 }
	 }
	 return minSource;
}

// Getting the source for the given creep. If the creep is not assinged to a
// source a source is randomly chossen and saved for the creep.
function getSourceForCreep(creep){
	 var sources = creep.room.find(FIND_SOURCES);
	 var sourceToMine = sources[0];

	// If the creep has no assigned source the source with the minimun creep
	// count is set for the creep.
    if (creep.memory.sourceId === undefined){
    	sourceToMine = getSourceWithMinCreepCount(creep);
        creep.memory.sourceId = sourceToMine.id;
        console.log(creep.name+"  role: "+creep.memory.role+ " source: "+creep.memory.sourceId);
    }
    return Game.getObjectById(creep.memory.sourceId);
}

// Creating all the creeps.
function create(creps) {

	clean();

	if (isEmergencyCreepCreation()){
	    console.log("Emergency creep creation.");
		if (createCreep('harvester', 8, [WORK, WORK, CARRY, MOVE])){
			return;
		}
	}

	if (createCreep('harvester', 8, [WORK, WORK, WORK, CARRY, CARRY,  MOVE, MOVE])){
		return;
	}
	if(createCreep('upgrader', 4, [WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE])){
		return;
	}
	if(createCreep('builder', 6, [WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE])){
		return;
	}
	if(createCreep('guard', 3, [ATTACK, ATTACK, MOVE, MOVE, MOVE, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH])){
		return;
	}

}

// Creates a single creep with the given role and work
function createCreep(roleTyp, counter, work){
    var exisitingCreeps = _.filter(Game.creeps, (creep) => creep.memory.role == roleTyp);
    if(exisitingCreeps.length < counter) {
        var newName = Game.spawns.Spawn1.createCreep(work, undefined, {role: roleTyp});
        if (newName<0){
        	return true;
        }
        console.log('Spawning new creep for role '+roleTyp+' with name ' + newName);
        return true;
    }
    return false;
}

// Cleans the memory from dead creeps.
function clean(){
	for(var name in Memory.creeps) {
        if(!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log('Clearing dead creep memory:', name);
        }
    }
}

function isEmergencyCreepCreation(){
	var counter = 0;
	try{
    	for(var name in Game.creeps){
    		var creep = Game.creeps[name];
    		if(creep.memory.role){
    		    if (creep.memory.role === 'harvester'){
    		       counter++;
    		    }
    		}
    	}
	}catch(exception){
		return true;
	}

	if (counter<5){
		return true;
	}
	return false;
}
<|endoftext|>


<commit_before>/* global require, module */
/* Magic Mirror
 * Node Helper: MMM-NetworkScanner
 *
 * By Ian Perrin http://ianperrin.com
 * MIT Licensed.
 */

const NodeHelper = require("node_helper");
const ping = require("ping");
const sudo = require("sudo");

module.exports = NodeHelper.create({
    start: function function_name () {
        console.log("Starting module: " + this.name);
    },

    // Override socketNotificationReceived method.
    socketNotificationReceived: function(notification, payload) {
        console.log(this.name + " received " + notification);

        if (notification === "SCAN_NETWORK") {
            this.devices = payload;
            this.scanNetworkMAC();
            this.scanNetworkIP(payload);
            return true;
        }

    },

    scanNetworkMAC: function() {
        console.log(this.name + " is scanning for mac addresses");

        var self = this;
        var arp = sudo(['arp-scan', '-l', '-q']);
        var buffer = '';
        var errstream = '';

        arp.stdout.on('data', function (data) {
            buffer += data;
        });

        arp.stderr.on('data', function (data) {
            errstream += data;
        });

        arp.on('error', function (err) {
            errstream += err;
        });

        arp.on('close', function (code) {
            if (code !== 0) {
                console.log(self.name + " received an error running arp-scan: " + code + " - " + errstream);
                return;
            }
            //Parse the response
            var rows = buffer.split('\n');
            var macAddresses = [];

            // ARP-SCAN table
            for (var i = 2; i < rows.length; i++) {
                var cells = rows[i].split('\t').filter(String);
                if (cells[1] && macAddresses.indexOf(cells[1].toUpperCase()) === -1) {
                    macAddresses.push(cells[1].toUpperCase());
                }
            }

            self.sendSocketNotification("MAC_ADDRESSES", macAddresses);
        });

    },

   scanNetworkIP: function(payload) {
      var self = this;
      console.log(this.name + " is scanning for ip addresses", payload);

      var devices = payload;
      var deviceList = [];

      function updateIPAddresses(devices) {
         devices.forEach( function(device) {
            if ("ipAddress" in device) {
               ping.sys.probe(device.ipAddress, function(isAlive) {
                  var deviceStatus = {name: device.name, online:isAlive};
                  deviceList.push(deviceStatus);
                  self.sendSocketNotification("IP_ADDRESS", deviceStatus);
               });
            }
         });
      }

      updateIPAddresses(devices);

   },
});
<commit_msg>fixing regressions - duplicate devices<commit_after>/* global require, module */
/* Magic Mirror
 * Node Helper: MMM-NetworkScanner
 *
 * By Ian Perrin http://ianperrin.com
 * MIT Licensed.
 */

const NodeHelper = require("node_helper");
const ping = require("ping");
const sudo = require("sudo");

module.exports = NodeHelper.create({

    start: function function_name () {
        this.log("Starting module: " + this.name);
    },

    // Override socketNotificationReceived method.
    socketNotificationReceived: function(notification, payload) {
        this.log(this.name + " received " + notification);

        if (notification === "CONFIG") {
            this.config = payload;
            return true;
        }

        if (notification === "SCAN_NETWORK") {
            this.scanNetworkMAC();
            this.scanNetworkIP();
            return true;
        }

    },

    scanNetworkMAC: function() {
        this.log(this.name + " is performing arp-scan");

        var self = this;
        var arp = sudo(['arp-scan', '-l', '-q']);
        var buffer = '';
        var errstream = '';
        var discoveredMacAddresses = [];
        var discoveredDevices = [];

        arp.stdout.on('data', function (data) {
            buffer += data;
        });

        arp.stderr.on('data', function (data) {
            errstream += data;
        });

        arp.on('error', function (err) {
            errstream += err;
        });

        arp.on('close', function (code) {
            if (code !== 0) {
                this.log(self.name + " received an error running arp-scan: " + code + " - " + errstream);
                return;
            }

            // Parse the ARP-SCAN table response
            var rows = buffer.split('\n');
            for (var i = 2; i < rows.length; i++) {
                var cells = rows[i].split('\t').filter(String);

                // Update device status
                if (cells && cells[1]) {
                    var macAddress = cells[1].toUpperCase()
                    if (macAddress && discoveredMacAddresses.indexOf(macAddress) === -1) {
                        discoveredMacAddresses.push(macAddress);
                        device = self.findDeviceByMacAddress(macAddress);
                        if (device) {
                            device.online = true;
                            discoveredDevices.push(device);
                        }
                    }
                }
            }

            self.log(self.name + " arp scan addresses: ", discoveredMacAddresses);
            self.log(self.name + " arp scan devices: ", discoveredDevices);
            self.sendSocketNotification("MAC_ADDRESSES", discoveredDevices);
        });

    },

    scanNetworkIP: function() {
        this.log(this.name + " is scanning for ip addresses", this.config.devices);

        var discoveredDevices = [];
        var self = this;
        this.config.devices.forEach( function(device) {
            if ("ipAddress" in device) {
                self.log("pinging for ", device);
                ping.sys.probe(device.ipAddress, function(isAlive) {
                    device.online = isAlive;
                    if (isAlive) {
                        discoveredDevices.push(device);
                    }
                    self.sendSocketNotification("IP_ADDRESS", device);
                });
            }
        });

        this.log(self.name + " ping results: ", discoveredDevices);

    },

    findDeviceByMacAddress: function (macAddress) {
        // Find first device with matching macAddress
        for (var i = 0; i < this.config.devices.length; i++) {
            var device = this.config.devices[i];
            if (device.hasOwnProperty("macAddress")) {
                if (macAddress.toUpperCase() === device.macAddress.toUpperCase()){
                    this.log(this.name + " found device by MAC Address", device);
                    return device;
                }
            }
        }
        // Return macAddress (if showing unknown) or null
        if (this.config.showUnknown) {
            return {macAddress: macAddress, name: macAddress, icon: "question", type: "Unknown"};
        } else {
            return null;
        }
    },

    log: function(message, object) {
        // Log if config is message or in debug mode
        if (!this.config || this.config.debug) {
            if (object) {
                console.log(message, object);
            } else {
                console.log(message);
            }
        }
    },

});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2002-2017 "Neo Technology,","
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {int, isInt, inSafeRange, toNumber, toString} from './integer';
import {Node, Relationship, UnboundRelationship, PathSegment, Path} from './graph-types'
import {Neo4jError, SERVICE_UNAVAILABLE, SESSION_EXPIRED, PROTOCOL_ERROR} from './error';
import Result from './result';
import ResultSummary from './result-summary';
import Record from './record';
import {Driver, READ, WRITE} from './driver';
import RoutingDriver from './routing-driver';
import VERSION from '../version';
import {parseScheme, parseUrl} from "./internal/connector";
import {assertString} from "./internal/util";

const auth ={
  basic: (username, password, realm = undefined) => {
    if (realm) {
      return {scheme: "basic", principal: username, credentials: password, realm: realm};
    } else {
      return {scheme: "basic", principal: username, credentials: password};
    }
  },
    custom: (principal, credentials, realm, scheme, parameters = undefined ) => {
    if (parameters) {
      return  {scheme: scheme, principal: principal, credentials: credentials, realm: realm,
        parameters: parameters}
    } else {
      return  {scheme: scheme, principal: principal, credentials: credentials, realm: realm}
    }
  }
};
let USER_AGENT = "neo4j-javascript/" + VERSION;

/**
 * Construct a new Neo4j Driver. This is your main entry point for this
 * library.
 *
 * ## Configuration
 *
 * This function optionally takes a configuration argument. Available configuration
 * options are as follows:
 *
 *     {
 *       // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF.
 *       encrypted: ENCRYPTION_ON|ENCRYPTION_OFF
 *
 *       // Trust strategy to use if encryption is enabled. There is no mode to disable
 *       // trust other than disabling encryption altogether. The reason for
 *       // this is that if you don't know who you are talking to, it is easy for an
 *       // attacker to hijack your encrypted connection, rendering encryption pointless.
 *       //
 *       // TRUST_ALL_CERTIFICATES is the default choice for NodeJS deployments. It only requires
 *       // new host to provide a certificate and does no verification of the provided certificate.
 *       //
 *       // TRUST_ON_FIRST_USE is available for modern NodeJS deployments, and works
 *       // similarly to how `ssl` works - the first time we connect to a new host,
 *       // we remember the certificate they use. If the certificate ever changes, we
 *       // assume it is an attempt to hijack the connection and require manual intervention.
 *       // This means that by default, connections "just work" while still giving you
 *       // good encrypted protection.
 *       //
 *       // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is the classic approach to trust verification -
 *       // whenever we establish an encrypted connection, we ensure the host is using
 *       // an encryption certificate that is in, or is signed by, a certificate listed
 *       // as trusted. In the web bundle, this list of trusted certificates is maintained
 *       // by the web browser. In NodeJS, you configure the list with the next config option.
 *       //
 *       // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES meand that you trust whatever certificates
 *       // are in the default certificate chain of th
 *       trust: "TRUST_ALL_CERTIFICATES" | "TRUST_ON_FIRST_USE" | "TRUST_SIGNED_CERTIFICATES" |
  *       "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES",
 *
 *       // List of one or more paths to trusted encryption certificates. This only
 *       // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES".
 *       // The certificate files should be in regular X.509 PEM format.
 *       // For instance, ['./trusted.pem']
 *       trustedCertificates: [],
 *
 *       // Path to a file where the driver saves hosts it has seen in the past, this is
 *       // very similar to the ssl tool's known_hosts file. Each time we connect to a
 *       // new host, a hash of their certificate is stored along with the domain name and
 *       // port, and this is then used to verify the host certificate does not change.
 *       // This setting has no effect unless TRUST_ON_FIRST_USE is enabled.
 *       knownHosts:"~/.neo4j/known_hosts",
 *
 *       // The max number of connections that are allowed idle in the pool at any time.
 *       // Connection will be destroyed if this threshold is exceeded.
 *       connectionPoolSize: 50,
 *
 *       // Specify the maximum time in milliseconds transactions are allowed to retry via
 *       // {@link Session#readTransaction()} and {@link Session#writeTransaction()} functions. These functions
 *       // will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient errors with
 *       // exponential backoff using initial delay of 1 second. Default value is 30000 which is 30 seconds.
 *       maxTransactionRetryTime: 30000,
 *     }
 *
 * @param {string} url The URL for the Neo4j database, for instance "bolt://localhost"
 * @param {Map<String,String>} authToken Authentication credentials. See {@link auth} for helpers.
 * @param {Object} config Configuration object. See the configuration section above for details.
 * @returns {Driver}
 */
function driver(url, authToken, config = {}) {
  assertString(url, 'Bolt URL');
  const scheme = parseScheme(url);
  if (scheme === "bolt+routing://") {
    return new RoutingDriver(parseUrl(url), USER_AGENT, authToken, config);
  } else if (scheme === "bolt://") {
    return new Driver(parseUrl(url), USER_AGENT, authToken, config);
  } else {
    throw new Error("Unknown scheme: " + scheme);

  }
}

const types ={
  Node,
  Relationship,
  UnboundRelationship,
  PathSegment,
  Path,
  Result,
  ResultSummary,
  Record
  };

const session = {
  READ,
  WRITE
};
const error = {
  SERVICE_UNAVAILABLE,
  SESSION_EXPIRED,
  PROTOCOL_ERROR
};
const integer = {
  toNumber,
  toString,
  inSafeRange
};

const forExport = {
  driver,
  int,
  isInt,
  integer,
  Neo4jError,
  auth,
  types,
  session,
  error
};

export {
  driver,
  int,
  isInt,
  integer,
  Neo4jError,
  auth,
  types,
  session,
  error
}
export default forExport
<commit_msg>Adding kerberos auth support<commit_after>/**
 * Copyright (c) 2002-2017 "Neo Technology,","
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {int, isInt, inSafeRange, toNumber, toString} from './integer';
import {Node, Relationship, UnboundRelationship, PathSegment, Path} from './graph-types'
import {Neo4jError, SERVICE_UNAVAILABLE, SESSION_EXPIRED, PROTOCOL_ERROR} from './error';
import Result from './result';
import ResultSummary from './result-summary';
import Record from './record';
import {Driver, READ, WRITE} from './driver';
import RoutingDriver from './routing-driver';
import VERSION from '../version';
import {parseScheme, parseUrl} from "./internal/connector";
import {assertString} from "./internal/util";

const auth ={
  basic: (username, password, realm = undefined) => {
    if (realm) {
      return {scheme: "basic", principal: username, credentials: password, realm: realm};
    } else {
      return {scheme: "basic", principal: username, credentials: password};
    }
  },
    kerberos:(base64EncodedTicket)=> {
    return {scheme:"kerberos", credentials: base64EncodedTicket};
    },
    custom: (principal, credentials, realm, scheme, parameters = undefined ) => {
    if (parameters) {
      return  {scheme: scheme, principal: principal, credentials: credentials, realm: realm,
        parameters: parameters}
    } else {
      return  {scheme: scheme, principal: principal, credentials: credentials, realm: realm}
    }
  }
};
let USER_AGENT = "neo4j-javascript/" + VERSION;

/**
 * Construct a new Neo4j Driver. This is your main entry point for this
 * library.
 *
 * ## Configuration
 *
 * This function optionally takes a configuration argument. Available configuration
 * options are as follows:
 *
 *     {
 *       // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF.
 *       encrypted: ENCRYPTION_ON|ENCRYPTION_OFF
 *
 *       // Trust strategy to use if encryption is enabled. There is no mode to disable
 *       // trust other than disabling encryption altogether. The reason for
 *       // this is that if you don't know who you are talking to, it is easy for an
 *       // attacker to hijack your encrypted connection, rendering encryption pointless.
 *       //
 *       // TRUST_ALL_CERTIFICATES is the default choice for NodeJS deployments. It only requires
 *       // new host to provide a certificate and does no verification of the provided certificate.
 *       //
 *       // TRUST_ON_FIRST_USE is available for modern NodeJS deployments, and works
 *       // similarly to how `ssl` works - the first time we connect to a new host,
 *       // we remember the certificate they use. If the certificate ever changes, we
 *       // assume it is an attempt to hijack the connection and require manual intervention.
 *       // This means that by default, connections "just work" while still giving you
 *       // good encrypted protection.
 *       //
 *       // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is the classic approach to trust verification -
 *       // whenever we establish an encrypted connection, we ensure the host is using
 *       // an encryption certificate that is in, or is signed by, a certificate listed
 *       // as trusted. In the web bundle, this list of trusted certificates is maintained
 *       // by the web browser. In NodeJS, you configure the list with the next config option.
 *       //
 *       // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES meand that you trust whatever certificates
 *       // are in the default certificate chain of th
 *       trust: "TRUST_ALL_CERTIFICATES" | "TRUST_ON_FIRST_USE" | "TRUST_SIGNED_CERTIFICATES" |
  *       "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES",
 *
 *       // List of one or more paths to trusted encryption certificates. This only
 *       // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES".
 *       // The certificate files should be in regular X.509 PEM format.
 *       // For instance, ['./trusted.pem']
 *       trustedCertificates: [],
 *
 *       // Path to a file where the driver saves hosts it has seen in the past, this is
 *       // very similar to the ssl tool's known_hosts file. Each time we connect to a
 *       // new host, a hash of their certificate is stored along with the domain name and
 *       // port, and this is then used to verify the host certificate does not change.
 *       // This setting has no effect unless TRUST_ON_FIRST_USE is enabled.
 *       knownHosts:"~/.neo4j/known_hosts",
 *
 *       // The max number of connections that are allowed idle in the pool at any time.
 *       // Connection will be destroyed if this threshold is exceeded.
 *       connectionPoolSize: 50,
 *
 *       // Specify the maximum time in milliseconds transactions are allowed to retry via
 *       // {@link Session#readTransaction()} and {@link Session#writeTransaction()} functions. These functions
 *       // will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient errors with
 *       // exponential backoff using initial delay of 1 second. Default value is 30000 which is 30 seconds.
 *       maxTransactionRetryTime: 30000,
 *     }
 *
 * @param {string} url The URL for the Neo4j database, for instance "bolt://localhost"
 * @param {Map<String,String>} authToken Authentication credentials. See {@link auth} for helpers.
 * @param {Object} config Configuration object. See the configuration section above for details.
 * @returns {Driver}
 */
function driver(url, authToken, config = {}) {
  assertString(url, 'Bolt URL');
  const scheme = parseScheme(url);
  if (scheme === "bolt+routing://") {
    return new RoutingDriver(parseUrl(url), USER_AGENT, authToken, config);
  } else if (scheme === "bolt://") {
    return new Driver(parseUrl(url), USER_AGENT, authToken, config);
  } else {
    throw new Error("Unknown scheme: " + scheme);

  }
}

const types ={
  Node,
  Relationship,
  UnboundRelationship,
  PathSegment,
  Path,
  Result,
  ResultSummary,
  Record
  };

const session = {
  READ,
  WRITE
};
const error = {
  SERVICE_UNAVAILABLE,
  SESSION_EXPIRED,
  PROTOCOL_ERROR
};
const integer = {
  toNumber,
  toString,
  inSafeRange
};

const forExport = {
  driver,
  int,
  isInt,
  integer,
  Neo4jError,
  auth,
  types,
  session,
  error
};

export {
  driver,
  int,
  isInt,
  integer,
  Neo4jError,
  auth,
  types,
  session,
  error
}
export default forExport
<|endoftext|>


<commit_before>'use strict';

/**
 * This controller handles trigger requests from the Cumulus system that fires
 * when assets are updated, inserted or deleted.
 *
 * An example request is:
 *
 * req.body = {
 *   id: 'FHM-25757',
 *   action: 'asset-update',
 *   catalog: 'Frihedsmuseet',
 *   apiKey: ''
 * }
 */

const ds = require('collections-online/lib/services/documents');
const config = require('collections-online/lib/config');

if(!config.es || !config.es.index || typeof(config.es.index) !== 'string') {
  throw new Error('Need exactly one index for Cumulus triggers to work.');
}

const indexing = require('../indexing/run');

var helpers = {
  thousandsSeparator: function(number) {
    return number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1.');
  }
};

function updateAsset(catalogAlias, assetId) {
  var state = {
    'es': ds,
    'index': config.es.index,
    'mode': 'single',
    'reference': catalogAlias + '/' + assetId
  };
  return indexing(state);
}

function deleteAsset(catalogAlias, assetId) {
  return ds.delete({
    index: config.es.index,
    type: 'asset',
    id: catalogAlias + '-' + assetId
  });
}

exports.asset = function(req, res, next) {
  const action = req.body.action || null;
  const catalogName = req.body.catalog || null;
  let id = req.body.id || '';
  let catalogAlias = null;

  console.log('Index asset called with body =', req.body);

  // If the catalog alias is not sat in the ID
  if(id.indexOf('-') > -1) {
    [catalogAlias, id] = id.split('-');
  } else if(catalogName) {
    // No slash in the id - the catalog should be read from .collection
    catalogAlias = Object.keys(config.cip.catalogs)
    .reduce(function(result, alias) {
      const candidateCatalogName = config.cip.catalogs[alias];
      console.log('trying', candidateCatalogName);
      if(candidateCatalogName === catalogName) {
        return alias;
      } else {
        return result;
      }
    }, null);
  }

  if (!catalogAlias) {
    throw new Error('Failed to determine catalog alias');
  }

  function success() {
    res.json({
      'success': true
    });
  }

  if (id && action) {
    if (action === 'asset-update') {
      updateAsset(catalogAlias, id).then(success, next);
    } else if (action === 'asset-create') {
      updateAsset(catalogAlias, id).then(success, next);
    } else if (action === 'asset-delete') {
      deleteAsset(catalogAlias, id).then(success, next);
    } else {
      next(new Error('Unexpected action from Cumulus: ' + action));
    }
  } else {
    var requestBody = JSON.stringify(req.body);
    next(new Error('Missing an id or an action, requested: ' + requestBody));
  }
};
<commit_msg>Calling the single mode directly + the key from Cumulus was indeed collection<commit_after>'use strict';

/**
 * This controller handles trigger requests from the Cumulus system that fires
 * when assets are updated, inserted or deleted.
 *
 * An example request is:
 *
 * req.body = {
 *   id: 'FHM-25757',
 *   action: 'asset-update',
 *   collection: 'Frihedsmuseet',
 *   apiKey: ''
 * }
 */

const ds = require('collections-online/lib/services/documents');
const config = require('collections-online/lib/config');

if(!config.es || !config.es.index || typeof(config.es.index) !== 'string') {
  throw new Error('Need exactly one index for Cumulus triggers to work.');
}

const indexing = require('../indexing/modes/run');

var helpers = {
  thousandsSeparator: function(number) {
    return number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1.');
  }
};

function updateAsset(catalogAlias, assetId) {
  var state = {
    'es': ds,
    'index': config.es.index,
    'mode': 'single',
    'reference': catalogAlias + '/' + assetId
  };
  return indexing(state);
}

function deleteAsset(catalogAlias, assetId) {
  return ds.delete({
    index: config.es.index,
    type: 'asset',
    id: catalogAlias + '-' + assetId
  });
}

exports.asset = function(req, res, next) {
  const action = req.body.action || null;
  const catalogName = req.body.collection || null;
  let id = req.body.id || '';
  let catalogAlias = null;

  console.log('Index asset called with body: ', JSON.stringify(req.body));

  // If the catalog alias is not sat in the ID
  if(id.indexOf('-') > -1) {
    [catalogAlias, id] = id.split('-');
  } else if(catalogName) {
    // No slash in the id - the catalog should be read from .collection
    catalogAlias = Object.keys(config.cip.catalogs)
    .reduce(function(result, alias) {
      const candidateCatalogName = config.cip.catalogs[alias];
      if(candidateCatalogName === catalogName) {
        return alias;
      } else {
        return result;
      }
    }, null);
  }

  if (!catalogAlias) {
    throw new Error('Failed to determine catalog alias');
  }

  function success() {
    res.json({
      'success': true
    });
  }

  if (id && action) {
    if (action === 'asset-update') {
      updateAsset(catalogAlias, id).then(success, next);
    } else if (action === 'asset-create') {
      updateAsset(catalogAlias, id).then(success, next);
    } else if (action === 'asset-delete') {
      deleteAsset(catalogAlias, id).then(success, next);
    } else {
      next(new Error('Unexpected action from Cumulus: ' + action));
    }
  } else {
    var requestBody = JSON.stringify(req.body);
    next(new Error('Missing an id or an action, requested: ' + requestBody));
  }
};
<|endoftext|>


<commit_before>var nconf = require("nconf"),
	express = require('express'),
	app = express();

nconf.env().file({file: ".env"});

var port = nconf.get("PORT");

app.use('/', express.static(__dirname + "/html"));

//javascript files
app.use("/js", express.static(__dirname + "/js"));

//css files
app.use("/css", express.static(__dirname + "/css"));

//static images
app.use("/img", express.static(__dirname + "/img"));

app.listen(port, function() {
  console.log("Listening on " + port);
});	<commit_msg>Refactoring routes to take advantage of flickr library. Other minor tweaks.<commit_after>"use strict";

var nconf = require("nconf");
nconf.env().file({file: ".env"});

var express = require('express'),
	flickr = require("./flickr.js"),
	fs = require("fs"),
	app = express(),
	port = nconf.get("PORT");

flickr.init(function(err){
	if(err){
		console.error("Error retrieving flickr api.", error);
		throw err;
	}
	else{
		console.log("Flickr apis are ready");
	}

	app.get("/getPhotos.php", function(req, res){
		var page = req.query.page || 1,
			tag = req.query.tag;
		flickr.getPhotos(page, tag, function(err, results){
			res.send(results);
		});
  	});

	app.get('/', function(req, res){
		fs.readFile("./html/index.html", "utf8", function(fileErr, fileContents){
			if(err){
				console.error("Error reading file", fileErr);
				res.status(404);
			}
			else{
				flickr.getPhotosDefault(function(photoErr, results){
					if(err){
						console.error("Error fetching photos", photoErr);
						results = "{}";
					}

					//lame template, but it's the only place I need it.
					fileContents = fileContents.split("//STARTING_DATA_HERE").join(JSON.stringify(results));
					res.send(fileContents);
				});

			}

		});
	});
	app.use('/', express.static(__dirname + "/html"));

	//javascript files
	app.use("/js", express.static(__dirname + "/js"));

	//css files
	app.use("/css", express.static(__dirname + "/css"));

	//static images
	app.use("/img", express.static(__dirname + "/img"));

	app.listen(port, function() {
	  console.log("Listening on " + port);
	});

});<|endoftext|>


<commit_before>import { getRequestErrorMessage } from 'ghost/utils/ajax';

var PostsController = Ember.ArrayController.extend({
    // this will cause the list to re-sort when any of these properties change on any of the models
    sortProperties: ['status', 'published_at', 'updated_at'],

    // override Ember.SortableMixin
    //
    // this function will keep the posts list sorted when loading individual/bulk
    // models from the server, even if records in between haven't been loaded.
    // this can happen when reloading the page on the Editor or PostsPost routes.
    //
    // a custom sort function is needed in order to sort the posts list the same way the server would:
    //     status: ASC
    //     published_at: DESC
    //     updated_at: DESC
    orderBy: function (item1, item2) {
        var status1 = item1.get('status'),
            status2 = item2.get('status'),

            updatedAt1, updatedAt2,
            publishedAt1, publishedAt2;

        if (status1 === status2) {
            if (status1 === 'draft') {
                updatedAt1 = item1.get('updated_at');
                updatedAt2 = item2.get('updated_at');

                return (new Date(updatedAt1)) < (new Date(updatedAt2)) ? 1 : -1;
            } else {
                publishedAt1 = item1.get('published_at');
                publishedAt2 = item2.get('published_at');

                return (new Date(publishedAt1)) < new Date(publishedAt2) ? 1 : -1;
            }
        }

        if (status2 === 'draft') {
            return 1;
        }

        return -1;
    },

    // set from PostsRoute
    paginationSettings: null,

    // holds the next page to load during infinite scroll
    nextPage: null,

    // indicates whether we're currently loading the next page
    isLoading: null,

    init: function () {
        this._super();

        var metadata = this.store.metadataFor('post');
        this.set('nextPage', metadata.pagination.next);
    },

    /**
     * Takes an ajax response, concatenates any error messages, then generates an error notification.
     * @param {jqXHR} response The jQuery ajax reponse object.
     * @return
     */
    reportLoadError: function (response) {
        var message = 'A problem was encountered while loading more posts';

        if (response) {
            // Get message from response
            message += ': ' + getRequestErrorMessage(response);
        } else {
            message += '.';
        }

        this.notifications.showError(message);
    },

    actions: {
        /**
        * Loads the next paginated page of posts into the ember-data store. Will cause the posts list UI to update.
        * @return
        */
        loadNextPage: function () {
            var self = this,
                store = this.get('store'),
                nextPage = this.get('nextPage'),
                paginationSettings = this.get('paginationSettings');

            if (nextPage) {
                this.set('isLoading', true);
                this.set('paginationSettings.page', nextPage);
                store.find('post', paginationSettings).then(function () {
                    var metadata = store.metadataFor('post');

                    self.set('nextPage', metadata.pagination.next);
                    self.set('isLoading', false);
                }, function (response) {
                    self.reportLoadError(response);
                });
            }
        }
    }
});

export default PostsController;
<commit_msg>Ember post order matches server post order<commit_after>import { getRequestErrorMessage } from 'ghost/utils/ajax';

var PostsController = Ember.ArrayController.extend({
    // this will cause the list to re-sort when any of these properties change on any of the models
    sortProperties: ['status', 'published_at', 'updated_at'],

    // override Ember.SortableMixin
    //
    // this function will keep the posts list sorted when loading individual/bulk
    // models from the server, even if records in between haven't been loaded.
    // this can happen when reloading the page on the Editor or PostsPost routes.
    //
    // a custom sort function is needed in order to sort the posts list the same way the server would:
    //     status: ASC
    //     published_at: DESC
    //     updated_at: DESC
    orderBy: function (item1, item2) {

        function publishedAtCompare() {
            var published1 = item1.get('published_at'),
                published2 = item2.get('published_at');

            if (!published1 && !published2) {
                return 0;
            }

            if (!published1 && published2) {
                return -1;
            }

            if (!published2 && published1) {
                return 1;
            }

            return Ember.compare(item1.get('published_at').valueOf(), item2.get('published_at').valueOf());
        }

        var statusResult = Ember.compare(item1.get('status'), item2.get('status')),
            updatedAtResult = Ember.compare(item1.get('updated_at').valueOf(), item2.get('updated_at').valueOf()),
            publishedAtResult = publishedAtCompare();

        if (statusResult === 0) {
            if (publishedAtResult === 0) {
                // This should be DESC
                return updatedAtResult * -1;
            }
            // This should be DESC
            return publishedAtResult * -1;
        }

        return statusResult;
    },

    // set from PostsRoute
    paginationSettings: null,

    // holds the next page to load during infinite scroll
    nextPage: null,

    // indicates whether we're currently loading the next page
    isLoading: null,

    init: function () {
        this._super();

        var metadata = this.store.metadataFor('post');
        this.set('nextPage', metadata.pagination.next);
    },

    /**
     * Takes an ajax response, concatenates any error messages, then generates an error notification.
     * @param {jqXHR} response The jQuery ajax reponse object.
     * @return
     */
    reportLoadError: function (response) {
        var message = 'A problem was encountered while loading more posts';

        if (response) {
            // Get message from response
            message += ': ' + getRequestErrorMessage(response);
        } else {
            message += '.';
        }

        this.notifications.showError(message);
    },

    actions: {
        /**
        * Loads the next paginated page of posts into the ember-data store. Will cause the posts list UI to update.
        * @return
        */
        loadNextPage: function () {
            var self = this,
                store = this.get('store'),
                nextPage = this.get('nextPage'),
                paginationSettings = this.get('paginationSettings');

            if (nextPage) {
                this.set('isLoading', true);
                this.set('paginationSettings.page', nextPage);
                store.find('post', paginationSettings).then(function () {
                    var metadata = store.metadataFor('post');

                    self.set('nextPage', metadata.pagination.next);
                    self.set('isLoading', false);
                }, function (response) {
                    self.reportLoadError(response);
                });
            }
        }
    }
});

export default PostsController;
<|endoftext|>


<commit_before>/**
 * @module Lyria
 */
define('lyria/viewport', ['root', 'jquery'], function(root, $) {
  'use strict';

  return (function() {

  /**
   * @class Viewport
   * @constructor
   */
    function Viewport(container, options) {
      var defaultOptions = {
        parent: null,
        trigger: {
          element: window,
          event: 'resize'
        },
        scaleMode: 'scaleToFit'
      };

      options = $.extend(options, defaultOptions);

      /**
       * The viewport width
       *
       * @property width
       * @type {Number}
       * @default 800
       */
      this.width = 800;

      /**
       * The viewport height
       *
       * @property height
       * @type {Number}
       * @default 600
       */
      this.height = 600;

      this.transforms = {};

      this.scaleMode = options.scaleMode;

      // Defaults container to the string 'viewport'
      if (container == null) {
        container = 'viewport';
      }

      /**
       * The viewport element (jQuery object)
       *
       * @property $element
       * @type {jQuery}
       */
      if ($('#' + container).length > 0) {
        this.$element = $('#' + container);
      } else {
        var createdElement = $(root.document.createElement('div')).attr('id', container).attr('class', 'viewport');

        if (options.parent) {
          $(options.parent).prepend(createdElement);
        } else {
          $('body').prepend(createdElement);
        }

        this.$element = $('#' + container);
      }

      var self = this;
      $(options.trigger.element).on(options.trigger.event, function() {
        var scaleFactor = 0;
        var scaleExp = 0;

        switch (self.scaleMode) {
          // TODO: Seperate scaleToFit from scaleHeightToFit
          case 'scaleToFit':
          case 'scaleHeightToFit':
            if (self.height > $(options.trigger.element).innerHeight()) {
              scaleFactor = $(options.trigger.element).innerHeight() / self.height;
              scaleExp = 'scale(' + scaleFactor + ', ' + scaleFactor + ')';

              self.$element.css('transform', scaleExp);
            }
            break;
          case 'scaleWidthToFit':
            if (self.width > $(options.trigger.element).innerWidth()) {
              scaleFactor = $(options.trigger.element).innerWidth() / self.width;
              scaleExp = 'scale(' + scaleFactor + ', ' + scaleFactor + ')';

              self.$element.css('transform', scaleExp);
            }
            break;
          default: break;
        }
      });
    }

    /**
     * Adds a behaviour which will be triggered on certain events
     *
     * @method behaviour
     * @param {Object} fn
     */
    Viewport.prototype.behaviour = function(fn) {

    };

    /**
     * Reset all CSS transforms on the viewport
     *
     * @method resetTransforms
     */
    Viewport.prototype.resetTransforms = function() {
      this.transforms = {};
    };

    /**
     * Updated CSS transforms on the viewport
     *
     * @method updateTransforms
     */
    Viewport.prototype.updateTransforms = function() {
      if ($.isEmptyObject(this.transforms)) {
        return;
      }

      this.$element.css('transform', this.transforms.join(' '));
    };

    /**
     * Scales the viewport
     *
     * @method scale
     * @param {Object} scaleX
     * @param {Object} scaleY
     */
    Viewport.prototype.scale = function(scaleX, scaleY) {
      if (scaleX == null) {
        return;
      }

      if (scaleY == null) {
        scaleY = scaleX;
      }

      this.transforms.scale = this.transforms.scale || {};
      this.transforms.scale.x = scaleX;
      this.transforms.scale.y = scaleY;

      this.$element.css('transform', '');
    };

    /**
     * Sets an origin for the viewport
     *
     * @method origin
     * @param {Number} originX
     * @param {Number} originY
     */
    Viewport.prototype.origin = function(originX, originY) {

    };

    /**
     * Centers the viewport
     *
     * @method center
     */
    Viewport.prototype.center = function() {

    };

    /**
     * Rotate the viewport
     *
     * @method rotate
     * @param {Number} angle
     */
    Viewport.prototype.rotate = function(angle) {
      if (angle == null) {
        return;
      }

      this.transforms.rotate = angle;

      this.$element.css('transform', 'rotate(' + angle + ')');
    };

    return Viewport;

  })();
});
<commit_msg>Implementing scaleToFit properly<commit_after>/**
 * @module Lyria
 */
define('lyria/viewport', ['root', 'jquery', 'mixer', 'eventmap'], function(root, $, mixer, EventMap) {'use strict';

  return (function() {

    /**
     * @class Viewport
     * @constructor
     */
    function Viewport(container, options) {
      var defaultOptions = {
        parent: null,
        trigger: {
          element: window,
          event: 'resize'
        },
        scaleMode: 'scaleToFit'
      };

      options = $.extend(options, defaultOptions);

      mixer(Viewport.prototype, new EventMap());

      this.scaleMode = options.scaleMode;

      // Defaults container to the string 'viewport'
      if (container == null) {
        container = 'viewport';
      }

      /**
       * The viewport element (jQuery object)
       *
       * @property $element
       * @type {jQuery}
       */
      if ($('#' + container).length > 0) {
        this.$element = $('#' + container);
      } else {
        var createdElement = $(root.document.createElement('div')).attr('id', container).attr('class', 'viewport');

        if (options.parent) {
          $(options.parent).prepend(createdElement);
        } else {
          $('body').prepend(createdElement);
        }

        this.$element = $('#' + container);
      }

      Object.defineProperty(this, 'width', {
        get: function() {
          return this.$element.outerWidth();
        }
      });

      Object.defineProperty(this, 'height', {
        get: function() {
          return this.$element.outerHeight();
        }
      });

      var self = this;

      this.on('scale', function() {
        var scaleFactor = 0;
        var scaleExp = 0;

        var scaleHeightToFit = function() {
          if (self.height > $(options.trigger.element).innerHeight()) {
            scaleFactor = $(options.trigger.element).innerHeight() / self.height;
            scaleExp = 'scale(' + scaleFactor + ', ' + scaleFactor + ')';

            self.$element.css('transform', scaleExp);
          }
        };

        var scaleWidthToFit = function() {
          if (self.width > $(options.trigger.element).innerWidth()) {
            scaleFactor = $(options.trigger.element).innerWidth() / self.width;
            scaleExp = 'scale(' + scaleFactor + ', ' + scaleFactor + ')';

            self.$element.css('transform', scaleExp);
          }
        };

        switch (self.scaleMode) {
          case 'scaleToFit':
            if ($(options.trigger.element).innerWidth() > self.width) {
              scaleWidthToFit();
            } else {
              scaleHeightToFit();
            }
            break;
          case 'scaleHeightToFit':
            scaleHeightToFit();
            break;
          case 'scaleWidthToFit':
            scaleWidthToFit();
            break;
          default:
            break;
        }
      });

      $(options.trigger.element).on(options.trigger.event, function() {
        self.trigger('scale');
      });
    }

    /**
     * Adds a behaviour which will be triggered on certain events
     *
     * @method behaviour
     * @param {Object} fn
     */
    Viewport.prototype.behaviour = function(fn) {

    };

    /**
     * Reset all CSS transforms on the viewport
     *
     * @method resetTransforms
     */
    Viewport.prototype.resetTransforms = function() {
      this.transforms = {};
    };

    /**
     * Updated CSS transforms on the viewport
     *
     * @method updateTransforms
     */
    Viewport.prototype.updateTransforms = function() {
      if ($.isEmptyObject(this.transforms)) {
        return;
      }

      this.$element.css('transform', this.transforms.join(' '));
    };

    /**
     * Scales the viewport
     *
     * @method scale
     * @param {Object} scaleX
     * @param {Object} scaleY
     */
    Viewport.prototype.scale = function(scaleX, scaleY) {
      if (scaleX == null) {
        return;
      }

      if (scaleY == null) {
        scaleY = scaleX;
      }

      this.transforms.scale = this.transforms.scale || {};
      this.transforms.scale.x = scaleX;
      this.transforms.scale.y = scaleY;

      this.$element.css('transform', '');
    };

    /**
     * Sets an origin for the viewport
     *
     * @method origin
     * @param {Number} originX
     * @param {Number} originY
     */
    Viewport.prototype.origin = function(originX, originY) {

    };

    /**
     * Centers the viewport
     *
     * @method center
     */
    Viewport.prototype.center = function() {

    };

    /**
     * Rotate the viewport
     *
     * @method rotate
     * @param {Number} angle
     */
    Viewport.prototype.rotate = function(angle) {
      if (angle == null) {
        return;
      }

      this.transforms.rotate = angle;

      this.$element.css('transform', 'rotate(' + angle + ')');
    };

    return Viewport;

  })();
});
<|endoftext|>


<commit_before>/*jslint unparam: true, node: true, plusplus: true, nomen: true, indent: 2, todo: true */
'use strict';

var BookingModel  = require('../models/booking');
var UserModel     = require('../models/user');

var UserController = {

  /**
   * Lists all users
   * @todo  Pagination?
   */
  listAll: function (req, res, next) {

    UserModel.find({}).limit(200).exec(function (err, users) {
      res.render('users/list', {
        title: 'Users',
        users : users
      });
    });
  },

  /**
   * Fetches details and bookings for a single user
   */
  list: function (req, res, next) {
    UserModel.findById(req.params.id, function (err, user) {
      if (err) { return next(err); }

      BookingModel.find({ user: user._id }, function (err, bookings) {
        if (err) { return next(err); }

        res.render('users/detail', {
          title: user.email,
          euser: user,
          bookings: bookings
        });

      });
    });
  },

  /**
   * Updates a user entry
   */
  update: function (req, res, next) {
    UserModel.findByIdAndUpdate(req.params.id, {
      role: req.body.role,
      active: req.body.active,
    }, function (err) {
      if (err) { return next(err); }

      res.redirect('/users/' + req.params.id);
    });
  },

  /**
   * Removes a user and related bookings from db
   */
  remove: function (req, res, next) {
    // delete user from db
    UserModel.findByIdAndRemove(req.params.id, function (err) {
      if (err) { return next(err); }

      // delete users bookings from db
      BookingModel.remove({ user: req.params.id }, function (err) {
        if (err) { return next(err); }

        res.redirect('/users/');
      });
    });
  }

};

module.exports = UserController;<commit_msg>Helper function<commit_after>/*jslint unparam: true, node: true, plusplus: true, nomen: true, indent: 2, todo: true */
'use strict';

var BookingModel  = require('../models/booking');
var UserModel     = require('../models/user');

var UserController = {

  /**
   * Lists all users
   * @todo  Pagination?
   */
  listAll: function (req, res, next) {

    UserModel.find({}).limit(200).exec(function (err, users) {
      res.render('users/list', {
        title: 'Users',
        users : users
      });
    });
  },

  /**
   * Fetches details and bookings for a single user
   */
  list: function (req, res, next) {
    UserModel.findById(req.params.id, function (err, user) {
      if (err) { return next(err); }

      BookingModel.find({ user: user._id }, function (err, bookings) {
        if (err) { return next(err); }

        res.render('users/detail', {
          title: user.email,
          euser: user,
          bookings: bookings
        });

      });
    });
  },

  /**
   * Updates a user entry
   */
  update: function (req, res, next) {
    UserModel.findByIdAndUpdate(req.params.id, {
      role: req.body.role,
      active: req.body.active,
    }, function (err) {
      if (err) { return next(err); }

      res.redirect('/users/' + req.params.id);
    });
  },

  /**
   * Removes a user and related bookings from db
   */
  remove: function (req, res, next) {
    // delete user from db
    UserModel.findByIdAndRemove(req.params.id, function (err) {
      if (err) { return next(err); }

      // delete users bookings from db
      BookingModel.remove({ user: req.params.id }, function (err) {
        if (err) { return next(err); }

        res.redirect('/users/');
      });
    });
  },

  /**
   * Helper for switching users role
   * @todo Remove in production!
   */
  makeAdmin: function (req, res, next) {
    // delete user from db
    UserModel.findByIdAndUpdate(
      req.session.user._id,
      {
        role: 'admin'
      },
      function (err) {
        if (err) { return next(err); }

        req.session.user.role = 'admin';

        res.redirect('/');
      }
    );
  }

};

module.exports = UserController;<|endoftext|>