<commit_before>/**
	Cuddle.js

	@author	Raven Lagrimas
*/

var https	= require('https'),
	http	= require('http'),

	logger 	= {log:function(){}},

	Request = function (method) {
		this.method		= method;
		this.secure 	= false;
		this.started 	= false;
		this._raw 		= false;
		this.headers 	= {};
		this.retries	= 0;
		this.max_retry	= 3;

		this.stringify = function () {
			return [
				this.method,
				' ' ,
				'http',
				this.secured ? 's' : '',
				'://',
				this.host,
				':',
				this.port,
				this.path,
				'\n',
				this.data,
				'\n',
				this.headers
			].join('');
		};

		this.to = function (host, port, path) {
			this.path = path;
			this.host = host;
			this.port = port;
			return this;
		};

		this.set_max_retry = function (max) {
			this.max_retry = max;
			return this;
		};

		this.secured = function () {
			this.secure = true;
			return this;
		};

		this.add_header = function (key, value) {
			this.headers[key] = value;
			return this;
		};

		this.raw = function () {
			this._raw = true;
			return this;
		};

		this.then = function (cb) {
			if (!this.cb) {
				this.cb = cb;
			}

			!this.started && this.send();
			return this;
		};

		this.args = function () {
			this.additional_arguments = arguments;
			return this;
		};

		this.set_before_json = function (fn) {
			this.before_json = fn;
			return this;
		};

		this.stringify = function (obj) {
		    var ret = [],
		        key;

		    for (key in obj) {
		        ret.push(
		            obj[key] === null
		            ? encodeURIComponent(key)
		            : encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])
		        );
		    }

		    return ret.join('&');
		};

		this.retry = function () {
			this.retries++;
			if (this.retries > this.max_retry) {
				logger.log('error', 'Reached max retries');
				this.cb({
						message : 'Reached max retries',
						url : this.host + ':' + this.port + this.path
					},
					null,
					this,
					this.additional_arguments
				);
				return this;
			}
			logger.log('warn', 'Retrying request');
			return this.send(this.data);
		};

		this.send = function (data) {
			var new_path = this.path,
				self = this,
				protocol,
				payload,
				req;

			this.started = true;
			this.data = data;

			if (data && this.method === 'GET') {
				new_path += '?' + this.stringify(data);
			}
			else {
				if (!this.headers['Content-Type']) {
					payload = this.stringify(data);
					this.headers['Content-Type'] = 'application/x-www-form-urlencoded';
					this.headers['Content-Length'] = payload.length;
				}
				else {
					payload = JSON.stringify(data);
				}
			}

			if (!this._raw) {
				this.headers['Accept'] = 'application/json';
			}

			logger.log('verbose', this.method, this.host + ':' + this.port + new_path);

			if (payload) {
				logger.log('debug', 'data\n', payload);
			}

			logger.log('debug', 'headers\n', this.headers);

			protocol = this.secure ? https : http;

			try {
				req = protocol.request({
					host: this.host,
					port: this.port,
					path: new_path,
					method: this.method,
					headers: this.headers
				}, function (response) {
					var s = '';

					response.setEncoding('utf8');

					response.on('data', function (chunk) {
						s += chunk;
					});

					response.on('end', function () {

						self.response_headers = response.headers;

						if (self._raw) {
							if (response.statusCode === 200) {
								logger.log('verbose', 'Response', response.statusCode);
								logger.log('silly', s);
								self.cb(null, s, self, self.additional_arguments);
							}
							else {
								s = {
									response : s,
									statusCode : response.statusCode
								};
								self.cb(s, null, self, self.additional_arguments);
							}
						}
						else {
							logger.log('verbose', 'Response', response.statusCode);
							logger.log('silly', s);

							if (this.before_json) {
								s = this.before_json(s);
							}

							try {
								JSON.parse(s);
							}
							catch (e) {
								logger.log('error', 'JSON is invalid');
								logger.log('error', s);
								e.statusCode = response.statusCode;
								return self.cb(e, s, self, self.additional_arguments);
							}
							if (response.statusCode === 200) {
								self.cb(null, JSON.parse(s), self, self.additional_arguments);
							}
							else {
								s = JSON.parse(s);
								s.statusCode = response.statusCode;
								self.cb(s, null, self, self.additional_arguments);
							}
						}
					});
				});

				req.on('error', function (err) {
					var retryable_errors = [
							'ECONNREFUSED',
							'ENOTFOUND',
							'ECONNRESET',
							'EADDRINFO',
							'EMFILE'
						];

					logger.log('error', 'Request error', err, self.host + ':' + self.port + self.path);

	                if (~retryable_errors.indexOf(err.code)) {
	    				if (self.retries < self.max_retry) {
							return self.retry();
						}
	                    err.message = 'OMG. Server on ' + self.host + ':' + self.port + ' seems dead';
	                }

					self.cb(err, null, self, self.additional_arguments);
				});

				if (this.method !== 'GET') {
					req.write(payload);
				}

				req.end();
			} catch (e) {
				console.dir(e);
				self.retry();
			}
			return this;
		};
	},

	attach = function (object) {
		object.get = {
			to : function (host, port, path) {
				return new Request('GET').to(host, port, path);
			}
		};

		object.post = {
			to : function (host, port, path) {
				return new Request('POST').to(host, port, path);
			}
		};

		object.put = {
			to : function (host, port, path) {
				return new Request('PUT').to(host, port, path);
			}
		};

		object.delete = {
			to : function (host, port, path) {
				return new Request('DELETE').to(host, port, path);
			}
		};

		object.request = function (method) {
			this.to = function (host, port, path) {
				return new Request(method).to(host, port, path);
			};
			return this;
		};

		return object;
	};

module.exports = function (_logger) {
	logger = _logger || logger;
	return attach({});
};

attach(module.exports);
<commit_msg>Fixed bug on stringify<commit_after>/**
	Cuddle.js

	@author	Raven Lagrimas
*/

var https	= require('https'),
	http	= require('http'),

	logger 	= {log:function(){}},

	Request = function (method) {
		this.method		= method;
		this.secure 	= false;
		this.started 	= false;
		this._raw 		= false;
		this.headers 	= {};
		this.retries	= 0;
		this.max_retry	= 3;

		this.toString = function () {
			return [
				this.method,
				' ' ,
				'http',
				this.secured ? 's' : '',
				'://',
				this.host,
				':',
				this.port,
				this.path,
				'\n',
				this.data,
				'\n',
				this.headers
			].join('');
		};

		this.to = function (host, port, path) {
			this.path = path;
			this.host = host;
			this.port = port;
			return this;
		};

		this.set_max_retry = function (max) {
			this.max_retry = max;
			return this;
		};

		this.secured = function () {
			this.secure = true;
			return this;
		};

		this.add_header = function (key, value) {
			this.headers[key] = value;
			return this;
		};

		this.raw = function () {
			this._raw = true;
			return this;
		};

		this.then = function (cb) {
			if (!this.cb) {
				this.cb = cb;
			}

			!this.started && this.send();
			return this;
		};

		this.args = function () {
			this.additional_arguments = arguments;
			return this;
		};

		this.set_before_json = function (fn) {
			this.before_json = fn;
			return this;
		};

		this.stringify = function (obj) {
		    var ret = [],
		        key;

		    for (key in obj) {
		        ret.push(
		            obj[key] === null
		            ? encodeURIComponent(key)
		            : encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])
		        );
		    }

		    return ret.join('&');
		};

		this.retry = function () {
			this.retries++;
			if (this.retries > this.max_retry) {
				logger.log('error', 'Reached max retries');
				this.cb({
						message : 'Reached max retries',
						url : this.host + ':' + this.port + this.path
					},
					null,
					this,
					this.additional_arguments
				);
				return this;
			}
			logger.log('warn', 'Retrying request');
			return this.send(this.data);
		};

		this.send = function (data) {
			var new_path = this.path,
				self = this,
				protocol,
				payload,
				req;

			this.started = true;
			this.data = data;

			if (data && this.method === 'GET') {
				new_path += '?' + this.stringify(data);
			}
			else {
				if (!this.headers['Content-Type']) {
					payload = this.stringify(data);
					this.headers['Content-Type'] = 'application/x-www-form-urlencoded';
					this.headers['Content-Length'] = payload.length;
				}
				else {
					payload = JSON.stringify(data);
				}
			}

			if (!this._raw) {
				this.headers['Accept'] = 'application/json';
			}

			logger.log('verbose', this.method, this.host + ':' + this.port + new_path);

			if (payload) {
				logger.log('debug', 'data\n', payload);
			}

			logger.log('debug', 'headers\n', this.headers);

			protocol = this.secure ? https : http;

			try {
				req = protocol.request({
					host: this.host,
					port: this.port,
					path: new_path,
					method: this.method,
					headers: this.headers
				}, function (response) {
					var s = '';

					response.setEncoding('utf8');

					response.on('data', function (chunk) {
						s += chunk;
					});

					response.on('end', function () {

						self.response_headers = response.headers;

						if (self._raw) {
							if (response.statusCode === 200) {
								logger.log('verbose', 'Response', response.statusCode);
								logger.log('silly', s);
								self.cb(null, s, self, self.additional_arguments);
							}
							else {
								s = {
									response : s,
									statusCode : response.statusCode
								};
								self.cb(s, null, self, self.additional_arguments);
							}
						}
						else {
							logger.log('verbose', 'Response', response.statusCode);
							logger.log('silly', s);

							if (this.before_json) {
								s = this.before_json(s);
							}

							try {
								JSON.parse(s);
							}
							catch (e) {
								logger.log('error', 'JSON is invalid');
								logger.log('error', s);
								e.statusCode = response.statusCode;
								return self.cb(e, s, self, self.additional_arguments);
							}
							if (response.statusCode === 200) {
								self.cb(null, JSON.parse(s), self, self.additional_arguments);
							}
							else {
								s = JSON.parse(s);
								s.statusCode = response.statusCode;
								self.cb(s, null, self, self.additional_arguments);
							}
						}
					});
				});

				req.on('error', function (err) {
					var retryable_errors = [
							'ECONNREFUSED',
							'ENOTFOUND',
							'ECONNRESET',
							'EADDRINFO',
							'EMFILE'
						];

					logger.log('error', 'Request error', err, self.host + ':' + self.port + self.path);

	                if (~retryable_errors.indexOf(err.code)) {
	    				if (self.retries < self.max_retry) {
							return self.retry();
						}
	                    err.message = 'OMG. Server on ' + self.host + ':' + self.port + ' seems dead';
	                }

					self.cb(err, null, self, self.additional_arguments);
				});

				if (this.method !== 'GET') {
					req.write(payload);
				}

				req.end();
			} catch (e) {
				console.dir(e);
				self.retry();
			}
			return this;
		};
	},

	attach = function (object) {
		object.get = {
			to : function (host, port, path) {
				return new Request('GET').to(host, port, path);
			}
		};

		object.post = {
			to : function (host, port, path) {
				return new Request('POST').to(host, port, path);
			}
		};

		object.put = {
			to : function (host, port, path) {
				return new Request('PUT').to(host, port, path);
			}
		};

		object.delete = {
			to : function (host, port, path) {
				return new Request('DELETE').to(host, port, path);
			}
		};

		object.request = function (method) {
			this.to = function (host, port, path) {
				return new Request(method).to(host, port, path);
			};
			return this;
		};

		return object;
	};

module.exports = function (_logger) {
	logger = _logger || logger;
	return attach({});
};

attach(module.exports);
<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var assert = require('assert');
var bunyan = require('bunyan');
var Executor = require('./executor.js');
var findImage = require('./docker').findImage;

module.exports = function(config, logger) {
  logger = logger || bunyan.createLogger({name: 'docker-registry-container'});
  var executor = new Executor(config);

  /**
   * build the container
   * system - the system definition
   * cdef - contianer definition block
   * out - ouput stream
   * cb - complete callback
   */
  var build = function build(mode, system, containerDef, out, cb) {
    logger.info('building');
    out.stdout('--> building');

    var name = containerDef.specific.name;

    if (!name) {
      return cb(new Error('missing name for definition ' + containerDef.id));
    }

    if (containerDef.specific.execute) {
      return cb(new Error('missing execute block in ' + containerDef.id + ' container definition'));
    }

    var pullCmd = 'docker pull ' + name;
    var tag = system.name + '/' + containerDef.id;
    var tagCmd = 'docker tag ' + name + ' ' + tag;

    executor.exec(null, pullCmd, out, function(err) {
      if (err) {
        return cb(err);
      }

      executor.exec(null, tagCmd, out, function(err) {

        if (err) {
          return cb(err);
        }

        findImage(tag, function(err, image) {
          if (err) {
            return cb(err);
          }

          cb(null, {
            dockerImageId: image.Id,
            imageTag: tag
          });
        });
      });
    });
  };

  /**
   * deploy the continaer
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var deploy = function deploy(mode, target, system, containerDef, container, out, cb) {
    cb();
  };

  /**
   * undeploy the container from the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var undeploy = function undeploy(mode, target, system, containerDef, container, out, cb) {
    cb();
  };

  /**
   * start the container on the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var start = function start(mode, target, system, containerDef, container, out, cb) {
    logger.info('starting');
    out.stdout('--> starting');

    var name = containerDef.specific.name;
    var args = containerDef.specific.execute.args || '';
    var exec = containerDef.specific.execute.exec || '';
    var cmd = 'docker run ' + args + ' ' + name + ' ' + exec;

    if (mode === 'preview') {
      out.preview({ host: target.privateIpAddress || 'localhost', cmd: cmd });
      return cb();
    }

    executor.exec(target.privateIpAddress, cmd, out, cb);
  };

  /**
   * stop the container on the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var stop = function stop(mode, target, system, containerDef, container, out, cb) {
    logger.info('stopping');
    out.stdout('stopping');
    cb();
  };

  /**
   * link the container to the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var link = function link(mode, target, system, containerDef, container, out, cb) {
    logger.info('linking');
    out.stdout('linking');
    cb();
  };

  /**
   * unlink the container from the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var unlink = function unlink(mode, target, system, containerDef, container, out, cb) {
    logger.info('unlinking');
    out.stdout('unlinking');
    cb();
  };

  return {
    build: build,
    deploy: deploy,
    start: start,
    stop: stop,
    link: link,
    unlink: unlink,
    undeploy: undeploy,
    add: deploy,
    remove: undeploy
  };
};

<commit_msg>Fixed bug preventing anything to be built.<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var assert = require('assert');
var bunyan = require('bunyan');
var Executor = require('./executor.js');
var findImage = require('./docker').findImage;

module.exports = function(config, logger) {
  logger = logger || bunyan.createLogger({name: 'docker-registry-container'});
  var executor = new Executor(config);

  /**
   * build the container
   * system - the system definition
   * cdef - contianer definition block
   * out - ouput stream
   * cb - complete callback
   */
  var build = function build(mode, system, containerDef, out, cb) {
    logger.info('building');
    out.stdout('--> building');

    var name = containerDef.specific.name;

    if (!name) {
      return cb(new Error('missing name for definition ' + containerDef.id));
    }

    if (!containerDef.specific.execute) {
      return cb(new Error('missing execute block in ' + containerDef.id + ' container definition'));
    }

    var pullCmd = 'docker pull ' + name;
    var tag = system.name + '/' + containerDef.id;
    var tagCmd = 'docker tag ' + name + ' ' + tag;

    executor.exec(null, pullCmd, out, function(err) {
      if (err) {
        return cb(err);
      }

      executor.exec(null, tagCmd, out, function(err) {

        if (err) {
          return cb(err);
        }

        findImage(tag, function(err, image) {
          if (err) {
            return cb(err);
          }

          cb(null, {
            dockerImageId: image.Id,
            imageTag: tag
          });
        });
      });
    });
  };

  /**
   * deploy the continaer
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var deploy = function deploy(mode, target, system, containerDef, container, out, cb) {
    cb();
  };

  /**
   * undeploy the container from the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var undeploy = function undeploy(mode, target, system, containerDef, container, out, cb) {
    cb();
  };

  /**
   * start the container on the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var start = function start(mode, target, system, containerDef, container, out, cb) {
    logger.info('starting');
    out.stdout('--> starting');

    var name = containerDef.specific.name;
    var args = containerDef.specific.execute.args || '';
    var exec = containerDef.specific.execute.exec || '';
    var cmd = 'docker run ' + args + ' ' + name + ' ' + exec;

    if (mode === 'preview') {
      out.preview({ host: target.privateIpAddress || 'localhost', cmd: cmd });
      return cb();
    }

    executor.exec(target.privateIpAddress, cmd, out, cb);
  };

  /**
   * stop the container on the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var stop = function stop(mode, target, system, containerDef, container, out, cb) {
    logger.info('stopping');
    out.stdout('stopping');
    cb();
  };

  /**
   * link the container to the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var link = function link(mode, target, system, containerDef, container, out, cb) {
    logger.info('linking');
    out.stdout('linking');
    cb();
  };

  /**
   * unlink the container from the target
   * target - target to deploy to
   * system - the target system defintinion
   * cdef - the contianer definition
   * container - the container as defined in the system topology
   * out - ouput stream
   * cb - complete callback
   */
  var unlink = function unlink(mode, target, system, containerDef, container, out, cb) {
    logger.info('unlinking');
    out.stdout('unlinking');
    cb();
  };

  return {
    build: build,
    deploy: deploy,
    start: start,
    stop: stop,
    link: link,
    unlink: unlink,
    undeploy: undeploy,
    add: deploy,
    remove: undeploy
  };
};

<|endoftext|>


<commit_before>var im = require('imagemagick');
var fs = require('fs');
var http = require('http');
var mime = require('mime');

var resizeImage = function(option, width, height, stream, next) {
    if (option) {
        im.crop({
            srcData: stream,
            width: width,
            height: height,
            gravity: "center"
        }, function(err, stdout, stderr) {
            var image = new Buffer(stdout, "binary");
            next(image);
        });
    } else {
        im.resize({
            srcData: stream,
            width: width,
            height: height
        }, function(err, stdout, stderr) {
            var image = new Buffer(stdout, "binary");
            next(image);
        });
    }
};

module.exports = {
    resize: function(format, width, height, url, next) {
        try {
            var path = `${__dirname}\\${url}`;
            fs.accessSync(path);
            var stream = fs.readFileSync(path);
            resizeImage(option, width, height, stream, (image) => {
                var type = mime.lookup(path);
                next(type, image);
            });
        } catch (ex) {
            // file doesn't exist, try to download file
            http.get(url).on('response', function(response) {
                var total = response.headers['content-length']; //total byte length
                var buffer = [];
                response.on('data', function(data) {
                    buffer.push(data);
                });
                response.on('end', function() {
                    var stream = Buffer.concat(buffer);
                    resizeImage(option, width, height, stream, (image) => {
                        var type = response.headers['content-type'];
                        next(type, image);
                    });
                });
            });
        }
    }
};
<commit_msg>fixed errors<commit_after>var im = require('imagemagick');
var fs = require('fs');
var http = require('http');
var mime = require('mime');

var resizeImage = function(option, width, height, stream, next) {
    if (option) {
        im.crop({
            srcData: stream,
            width: width,
            height: height,
            gravity: "center"
        }, function(err, stdout, stderr) {
            var image = new Buffer(stdout, "binary");
            next(image);
        });
    } else {
        im.resize({
            srcData: stream,
            width: width,
            height: height
        }, function(err, stdout, stderr) {
            var image = new Buffer(stdout, "binary");
            next(image);
        });
    }
};

module.exports = {
    resize: function(option, width, height, url, next) {
        var path = `${__dirname}\\${url}`;
        var download = false;

        // check if file exists locally
        try {
            fs.accessSync(path);
        } catch (ex) {
            download = true;
        }

        try {

            if (!download) {
                // file is on server
                var stream = fs.readFileSync(path);
                resizeImage(option, width, height, stream, (image) => {
                    var type = mime.lookup(path);
                    next(type, image);
                });

            } else {
                // file doesn't exist, try to download file
                if (url.indexOf('http://')) {
                    http.get(url).on('response', function(response) {
                        var total = response.headers['content-length']; //total byte length
                        var buffer = [];
                        response.on('data', function(data) {
                            buffer.push(data);
                        });
                        response.on('end', function() {
                            var stream = Buffer.concat(buffer);
                            resizeImage(option, width, height, stream, (image) => {
                                var type = response.headers['content-type'];
                                next(type, image);
                            });
                        });
                    });
                } else {
                    next("text/plain", "Not a valid url");
                }
            }
        } catch (ex) {
            next("text/plain", "Image not found");
        }

    }
};<|endoftext|>


<commit_before>/**
 * `confirm` type prompt
 */

var util = require('util');
var Prompt = require('prompt-base');
var cyan = require('ansi-cyan');

/**
 * Create a new `Confirm` prompt, with the given `question`.
 */

function Confirm(/*question, answers, rl*/) {
  Prompt.apply(this, arguments);
  this.defaultValue = true

  if (typeof this.question.default === 'boolean') {
    this.defaultValue = this.question.default;
  }
  this.question.default = this.defaultValue ? 'Y/n' : 'y/N';
  return this;
}

/**
 * Inherit `Prompt`
 */

util.inherits(Confirm, Prompt);

/**
 * Start the prompt session
 * @param  {Function} `cb` Callback when prompt is finished
 * @return {Object} Returns the `Confirm` instance
 */

Confirm.prototype.ask = function(cb) {
  this.callback = cb;
  this.ui.once('line', this.onSubmit.bind(this));
  this.ui.on('keypress', this.onKeypress.bind(this));
  this.render();
  return this;
};

/**
 * When user presses the `enter` key
 */

Confirm.prototype.onSubmit = function(input) {
  this.answer = this.getAnswer(input);
  this.status = 'answered';
  this.submitAnswer();
};

/**
 * When a keypress is emitted (user types)
 */

Confirm.prototype.getAnswer = function(input) {
  return isString(input) ? isTrue(input) : this.defaultValue
};

/**
 * When a keypress is emitted (user types)
 */

Confirm.prototype.onKeypress = function() {
  this.render();
};

/**
 * Return true if `str` is a truthy value.
 * @param {String} `str`
 * @return {Boolean}
 */

function isTrue(str) {
  return /^(y|yes|ok|true)$/i.test(String(str));
}

/**
 * Return true if val is a non-empty string.
 */

function isString(val) {
  return typeof val === 'string' && val.length > 0
}

/**
 * Module exports
 */

module.exports = Confirm;
<commit_msg>update to new signature<commit_after>/**
 * `confirm` type prompt
 */

var koalas = require('koalas');
var debug = require('debug')('prompt-confirm');
var Prompt = require('prompt-base');

/**
 * Create a new `Confirm` prompt, with the given `question`.
 */

function Confirm(/*question, answers, rl*/) {
  debug('initializing from <%s>', __filename);
  Prompt.apply(this, arguments);
  this.setDefault();
  this.validate = function() {
    return true;
  };
}

/**
 * Inherit `Prompt`
 */

Prompt.extend(Confirm);

/**
 * Get the default value to use
 */

Confirm.prototype.setDefault = function() {
  var val = koalas(this.question.getAnswer(), this.question.default, true);
  this.question.default = val ? 'Y/n' : 'y/N';
  this.defaultValue = val;
};

/**
 * Get the answer to use
 */

Confirm.prototype.getAnswer = function(input) {
  return isString(input) ? isTrue(input) : koalas(input, this.defaultValue);
};

/**
 * Return true if `str` is a truthy value.
 * @param {String} `str`
 * @return {Boolean}
 */

function isTrue(str) {
  return /^(y|ye(s|ah)|ok(ay)?|true)$/i.test(String(str));
}

/**
 * Return true if val is a non-empty string.
 */

function isString(val) {
  return val && typeof val === 'string';
}

/**
 * Module exports
 */

module.exports = Confirm;
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*!
 * -----------
 * ASPDB®-Data
 * -----------
 * Data of ASPDB — A manually curated dedicated acid shock proteins database.
 * ___________________________________________________________________________
 *
 * CCPE ——————— Centre for Computational Protein Engineering.
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 10-Dec-2016
 * @license   : Apache, version 2.0
 * @purpose   : To create Data System(s) with Node.js® and NPM.
 * @require   : Node.js®
 * @require   : NPM
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Data System/-- of "ASPDB®-Data".
 * ___________________________________________________________________________
 */
<commit_msg>Initial commit.🚩<commit_after>#!/usr/bin/env node
/*!
 * -----------
 * ASPDB®-Data
 * -----------
 * Data of ASPDB — A manually curated dedicated acid shock proteins database.
 * ___________________________________________________________________________
 *
 * CCPE ——————— Centre for Computational Protein Engineering.
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 10-Dec-2016
 * @license   : Apache, version 2.0
 * @purpose   : To create Data System(s) with Node.js® and NPM.
 * @require   : Node.js®
 * @require   : NPM
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Data System/-- of "ASPDB®-Data".
 * ___________________________________________________________________________
 */

// global __dirname: true
// global require: true
<|endoftext|>


<commit_before>var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cron = require('node-cron');
var cheerio = require('cheerio');

var app = express();
app.listen((process.env.PORT || 3000));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// Current version
ver = 'v.0.0.15';
// Facebook pageId
pageId = '1167308473348175';
// My user on Facebook
me = '1221242727898531';

// Server endpoint
app.get('/', function (req, res) {
    res.send('JKDbot here! ' + ver);
});

// Facebook webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'jkdbot_verify_token') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }
});

// Handler receiving messages
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {
            switch(event.message.text) {
                case("cmd_version"):
                    sendMessage(event.sender.id, {text: ver});
                    break;
                case("cmd_subscribers"):
                    sendMessage(event.sender.id, {text: getUserIds()});
                    break;
                case("cmd_timezone"):
                    sendMessage(event.sender.id, {text: getUserTimezone("1")});
                    break;
              case("cmd_stop_cron"):
                    task.stop();
                    break;
              case("cmd_stop_restart"):
                    task.start();
                    break;
                default:
                    sendMessage(event.sender.id, {text: "Message received: " + event.message.text + " by " + event.sender.id});
                    break;
            }
        }
    }
    res.sendStatus(200);
});

// Scheduler
var task = cron.schedule('*/2 * * * *', function() {
    console.log('Running sendout');
    doSendout();
});
task.start();

// Main task
var doSendout = function() {
    sendMessage(me, {text: "jkdbot here"});
}

// Sends a message to a Facebook user
var sendMessage = function(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.8/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, html) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
};

// Facebook page with the likes of our app
var url = 'https://www.facebook.com/browse/?type=page_fans&page_id='+pageId;
// Collects the userId's from the page likes html
var getUserIds = function() {
    var userIds = [];
    request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(body);
        $('a[data-gt]').each(function(i, a) {
            var gt = JSON.parse(a.dataset.gt);
            if(!gt.engagement || gt.engagement.eng_type !== "1") {
                return;
            }
            console.log(gt.engagement.eng_tid);
            userIds.push(gt.engagement.eng_tid)
        });
    } else {
        console.log('Error retrieving likes: ', error);
    }
    });
};

// Retrieves the timezone of a user
var getUserTimezone = function(userId) {
    return "-9";
};
<commit_msg>Scheduler<commit_after>var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cron = require('node-cron');
var cheerio = require('cheerio');

var app = express();
app.listen((process.env.PORT || 3000));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

// Current version
ver = 'v.0.0.16';
// Facebook pageId
pageId = '1167308473348175';
// My user on Facebook
me = '1221242727898531';

// Server endpoint
app.get('/', function (req, res) {
    res.send('JKDbot here! ' + ver);
});

// Facebook webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'jkdbot_verify_token') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }
});

// Handler receiving messages
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {
            switch(event.message.text) {
                case("cmd_version"):
                    sendMessage(event.sender.id, {text: ver});
                    break;
                case("cmd_subscribers"):
                    sendMessage(event.sender.id, {text: getUserIds()});
                    break;
                case("cmd_timezone"):
                    sendMessage(event.sender.id, {text: getUserTimezone("1")});
                    break;
              case("cmd_stop_cron"):
                    task.stop();
                    break;
              case("cmd_stop_restart"):
                    task.start();
                    break;
                default:
                    sendMessage(event.sender.id, {text: "Message received: " + event.message.text + " by " + event.sender.id});
                    break;
            }
        }
    }
    res.sendStatus(200);
});

// Scheduler
var task = cron.schedule('* * 9 * *', function() {
    console.log('Running sendout');
    doSendout();
});
task.start();

// Main task
var doSendout = function() {
    sendMessage(me, {text: "jkdbot here"});
}

// Sends a message to a Facebook user
var sendMessage = function(recipientId, message) {
    request({
        url: 'https://graph.facebook.com/v2.8/me/messages',
        qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, html) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
};

// Facebook page with the likes of our app
var url = 'https://www.facebook.com/browse/?type=page_fans&page_id='+pageId;
// Collects the userId's from the page likes html
var getUserIds = function() {
    var userIds = [];
    request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(body);
        $('a[data-gt]').each(function(i, a) {
            var gt = JSON.parse(a.dataset.gt);
            if(!gt.engagement || gt.engagement.eng_type !== "1") {
                return;
            }
            console.log(gt.engagement.eng_tid);
            userIds.push(gt.engagement.eng_tid)
        });
    } else {
        console.log('Error retrieving likes: ', error);
    }
    });
};

// Retrieves the timezone of a user
var getUserTimezone = function(userId) {
    return "-9";
};
<|endoftext|>


<commit_before>"use strict";

var recursiveFlatten = function (array) {
  var res = []
  for (let e of array) {
    if (Array.isArray(e)) {
      res.push(...recursiveFlatten(e))
      continue
    }
    res.push(e)
  }
  return res
}

/**
 * Flatten all the elements.
 * E.g. [1, [2, [3] ], 4] -> [1, 2, 3, 4]
 *
 * @param {Array} array
 */
module.exports = recursiveFlatten
<commit_msg>Trivial<commit_after>"use strict";

var recursiveFlatten = function (array) {
  var res = []
  for (let e of array) {
    if (Array.isArray(e)) {
      res.push(...recursiveFlatten(e))
      continue
    }
    res.push(e)
  }
  return res
}

/**
 * Flatten all the elements of array.
 * E.g. [1, [2, [3] ], 4] -> [1, 2, 3, 4]
 *
 * @param {Array} array
 */
module.exports = recursiveFlatten
<|endoftext|>


<commit_before>module.exports = function (opts) {
  var req = 1, p

  var requests = [], instreams = [], outstreams = []

  function onMessage (msg) {
    opts.message(msg)
  }

  function onRequest (msg) {
    //call the local api.
    if(msg.req < 0)
      requests[msg.req*-1](msg.error, msg.value)
    else {
      var id = msg.req*-1, once = false
      //must callback exactly once.
      //any extra callbacks are just ignored.

      opts.request(msg.value, function (err, value) {
        if(once) throw new Error('cb called twice from local api')
        once = true
        if(err) p.read({error: err.message, req: id})
        else    p.read({value: value, req: id})
      })
    }
  }

  function createStream(id) {
    var seq = 1
    var stream = {
      id: id,
      write: function (data, err) {
        p.read({req: id, seq: seq++, value: data, end: err})
      },
      end: function (err) {
        stream.write(null, err || true)
      },
      read: null
    }

    return stream
  }

  function onStream (msg) {

    if(msg.req < 0) { // it's a response
      var outs = outstreams[msg.req*-1]
      if(msg.end) {
        outstreams[msg.req*-1] = null
        outs.read(null, msg.end)
      }
      else
        outs.read(msg.value)
    }
    else {
      var ins = instreams[msg.req]
      if(ins) {
        if(ins.read) {
          if(msg.end) {
            instreams[msg.req] = null
            ins.read(null, msg.end)
          }
          else
            ins.read(msg.value)
        }
        else console.error('no .read for stream:', ins.id, 'dropped:', msg)
      }
      else {
        var seq = 1, req = msg.req
        var stream = instreams[req] = createStream(req*-1)
        opts.stream(stream)
        stream.read(msg.value, msg.end)
      }
    }

  }

  return p = {
    ended: false,
    //message with no response, or stream
    message: function (obj) {
      p.read(obj)
    },

    request: function (obj, callback) {
      var id = req++
      requests[id] = function (err, value) {
        delete requests[id]
        callback(err, value)
      }
      p.read({value: obj, req: id})
    },

    stream: function (recv) {
      var id = req++
      return outstreams[id] = createStream(id)
    },

    read: function (msg) {
      console.error('please overwrite write method to do IO', msg)
    },

    write: function (msg, end) {
      if(p.ended) return
      if(end) {
        p.ended = end
        var err = end === true ? new Error('unexpected end of parent stream') : err
        requests.forEach(function (cb) { cb(err) })
        instreams.forEach(function (s, id) {
          delete instream[id]
          s.read(null, err)
        })
        outstreams.forEach(function (s, id) {
          delete outstreams[id]
          s.write(null, err)
        })
        return
      }
      //handle requests
      ; (msg.req && !msg.seq) ? onRequest(msg)
      : (msg.req && msg.seq)  ? onStream(msg)
      :                         onMessage(msg)
    }
  }
}
<commit_msg>instreams not instream<commit_after>module.exports = function (opts) {
  var req = 1, p

  var requests = [], instreams = [], outstreams = []

  function onMessage (msg) {
    opts.message(msg)
  }

  function onRequest (msg) {
    //call the local api.
    if(msg.req < 0)
      requests[msg.req*-1](msg.error, msg.value)
    else {
      var id = msg.req*-1, once = false
      //must callback exactly once.
      //any extra callbacks are just ignored.

      opts.request(msg.value, function (err, value) {
        if(once) throw new Error('cb called twice from local api')
        once = true
        if(err) p.read({error: err.message, req: id})
        else    p.read({value: value, req: id})
      })
    }
  }

  function createStream(id) {
    var seq = 1
    var stream = {
      id: id,
      write: function (data, err) {
        p.read({req: id, seq: seq++, value: data, end: err})
      },
      end: function (err) {
        stream.write(null, err || true)
      },
      read: null
    }

    return stream
  }

  function onStream (msg) {

    if(msg.req < 0) { // it's a response
      var outs = outstreams[msg.req*-1]
      if(msg.end) {
        outstreams[msg.req*-1] = null
        outs.read(null, msg.end)
      }
      else
        outs.read(msg.value)
    }
    else {
      var ins = instreams[msg.req]
      if(ins) {
        if(ins.read) {
          if(msg.end) {
            instreams[msg.req] = null
            ins.read(null, msg.end)
          }
          else
            ins.read(msg.value)
        }
        else console.error('no .read for stream:', ins.id, 'dropped:', msg)
      }
      else {
        var seq = 1, req = msg.req
        var stream = instreams[req] = createStream(req*-1)
        opts.stream(stream)
        stream.read(msg.value, msg.end)
      }
    }

  }

  return p = {
    ended: false,
    //message with no response, or stream
    message: function (obj) {
      p.read(obj)
    },

    request: function (obj, callback) {
      var id = req++
      requests[id] = function (err, value) {
        delete requests[id]
        callback(err, value)
      }
      p.read({value: obj, req: id})
    },

    stream: function (recv) {
      var id = req++
      return outstreams[id] = createStream(id)
    },

    read: function (msg) {
      console.error('please overwrite write method to do IO', msg)
    },

    write: function (msg, end) {
      if(p.ended) return
      if(end) {
        p.ended = end
        var err = end === true ? new Error('unexpected end of parent stream') : err
        requests.forEach(function (cb) { cb(err) })
        instreams.forEach(function (s, id) {
          delete instreams[id]
          s.read(null, err)
        })
        outstreams.forEach(function (s, id) {
          delete outstreams[id]
          s.write(null, err)
        })
        return
      }
      //handle requests
      ; (msg.req && !msg.seq) ? onRequest(msg)
      : (msg.req && msg.seq)  ? onStream(msg)
      :                         onMessage(msg)
    }
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var program = require('commander');
var platformIs = require('platform-is');

program
  .option('-e, --encoding [type]', 'Specify the encoding of dotenv file')
  .option('-p, --path [type]', 'Specify a custom path of dotenv file')
  .option('-r, --raw', 'Should run a raw command ?')
  .option('-o, --on <items>', 'Specify a platform to run on', function (val) {
    return val.split(',');
  })
  .option('-s, --silent', 'silent')
  .parse(process.argv);
var scriptName = program.args[0];

if (!program.silent) {
  console.log('running better-npm-run in', process.cwd());
}
if (program.on && program.on.length === 1){
  var platform = program.on[0];
  if (platform === 'mac' && !platformIs.isMac()) process.exit();
  if (platform === 'linux' && !platformIs.isLinux()) process.exit();
  if (platform === 'windows' && !platformIs.isWindows()) process.exit();
} else if (program.on && program.on.length > 1){
  var exit = false;
  for (var i = 0; i < program.on.length; i ++){
    var v = program.on[i];
    if (v === 'mac') exit = !platformIs.isMac();
    if (v === 'linux') exit = !platformIs.isLinux();
    if (v === 'windows') exit = !platformIs.isWindows();
    if (!exit) break;
  }
  if (exit) process.exit();
} else if (program.on && program.on.length === 0) {
  if (program.on) {
    process.stderr.write('ERROR: Please set run platform');
    process.exit(1);
  }
}

var join = require('path').join;
var fullPackagePath = join(process.cwd(), 'package.json');
var pkg = require(fullPackagePath);
var exec = require('./lib/exec.js');

if (!pkg.scripts) {
  process.stderr.write('ERROR: No scripts found!');
  process.exit(1);
}
if (!scriptName) {
  process.stderr.write('ERROR: No script name provided!');
  process.exit(1);
}
if ((!pkg.betterScripts[scriptName] || !pkg.scripts[scriptName]) && !program.raw) {
  process.stderr.write('ERROR: No script / betterScript with name "' + scriptName + '" was found!');
  process.exit(1);
}

if(!program.silent) {
  console.log('Executing script: ' + scriptName + '\n');
}

var run = '';
if (program.raw){
  run = program.args.join(' ');
} else {
  run = pkg.betterScripts[scriptName] || pkg.scripts[scriptName];
}
exec(run, program, function (error, stdout, stderr) {
  process.stderr.write(stderr);
  process.stdout.write(stdout);
  if(error !== null) {
    console.log('exec error: '+error);
  }
});
<commit_msg>fix raw option<commit_after>#!/usr/bin/env node
var program = require('commander');
var platformIs = require('platform-is');

program
  .option('-e, --encoding [type]', 'Specify the encoding of dotenv file')
  .option('-p, --path [type]', 'Specify a custom path of dotenv file')
  .option('-r, --raw', 'Should run a raw command ?')
  .option('-o, --on <items>', 'Specify a platform to run on', function (val) {
    return val.split(',');
  })
  .option('-s, --silent', 'silent')
  .parse(process.argv);
var scriptName = program.args[0];

if (!program.silent) {
  console.log('running better-npm-run in', process.cwd());
}
if (program.on && program.on.length === 1){
  var platform = program.on[0];
  if (platform === 'mac' && !platformIs.isMac()) process.exit();
  if (platform === 'linux' && !platformIs.isLinux()) process.exit();
  if (platform === 'windows' && !platformIs.isWindows()) process.exit();
} else if (program.on && program.on.length > 1){
  var exit = false;
  for (var i = 0; i < program.on.length; i ++){
    var v = program.on[i];
    if (v === 'mac') exit = !platformIs.isMac();
    if (v === 'linux') exit = !platformIs.isLinux();
    if (v === 'windows') exit = !platformIs.isWindows();
    if (!exit) break;
  }
  if (exit) process.exit();
} else if (program.on && program.on.length === 0) {
  if (program.on) {
    process.stderr.write('ERROR: Please set run platform');
    process.exit(1);
  }
}

var join = require('path').join;
var fullPackagePath = join(process.cwd(), 'package.json');
var pkg = require(fullPackagePath);
var exec = require('./lib/exec.js');

if (!pkg.scripts) {
  process.stderr.write('ERROR: No scripts found!');
  process.exit(1);
}
if (!scriptName) {
  process.stderr.write('ERROR: No script name provided!');
  process.exit(1);
}
if ((pkg.betterScripts && !pkg.betterScripts[scriptName] || pkg.scripts && !pkg.scripts[scriptName]) && !program.raw) {
  process.stderr.write('ERROR: No script / betterScript with name "' + scriptName + '" was found!');
  process.exit(1);
}

if(!program.silent) {
  console.log('Executing script: ' + scriptName + '\n');
}

var run = '';
if (program.raw){
  run = program.args.join(' ');
} else {
  run = pkg.betterScripts[scriptName] || pkg.scripts[scriptName];
}
exec(run, program, function (error, stdout, stderr) {
  process.stderr.write(stderr);
  process.stdout.write(stdout);
  if(error !== null) {
    console.log('exec error: '+error);
  }
});
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');

function FileWebpackPlugin(files) {
  this.files = files || {};
}

FileWebpackPlugin.prototype.apply = function(compiler) {
  var self = this;
  compiler.plugin('emit', function(compiler, done) {
    var data = {};

    var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
      var promise = Promise
        .fromNode(asyncTemplate.bind(null, data))
        .then(createAssetFromContents)

      return promise;
    });

    Promise.props(assetPromises)
      .then(addAssetsToCompiler(compiler))
      .nodeify(done);
  });
};

var addAssetsToCompiler = curry(function(compiler, assets) {
  assign(compiler.assets, assets);
});

function createAssetFromContents(contents) {
  return {
    source: function() {
      return contents;
    },
    size: function() {
      return contents.length;
    }
  };
}

module.exports = FileWebpackPlugin;
<commit_msg>Simplify mapValues body into a single return<commit_after>var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');

function FileWebpackPlugin(files) {
  this.files = files || {};
}

FileWebpackPlugin.prototype.apply = function(compiler) {
  var self = this;
  compiler.plugin('emit', function(compiler, done) {
    var data = {};

    var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
      return Promise
        .fromNode(asyncTemplate.bind(null, data))
        .then(createAssetFromContents);
    });

    Promise.props(assetPromises)
      .then(addAssetsToCompiler(compiler))
      .nodeify(done);
  });
};

var addAssetsToCompiler = curry(function(compiler, assets) {
  assign(compiler.assets, assets);
});

function createAssetFromContents(contents) {
  return {
    source: function() {
      return contents;
    },
    size: function() {
      return contents.length;
    }
  };
}

module.exports = FileWebpackPlugin;
<|endoftext|>


<commit_before>var PgpContent = require('pgp-encrypt-content')
var mount = require('choo/mount')
var html = require('choo/html')
var css = require('sheetify')
var choo = require('choo')
var path = require('path')
var fs = require('fs')

var style = css('./index.css')
css('tachyons')

var app = choo()

app.model({
  namespace: 'email',
  state: { contents: [] },
  reducers: {
    send: function (state, data) {
      return { contents: data }
    }
  },
  effects: {
    getFormData: function (state, data, send, done) {
      var opts = {}
      var inputs = document.querySelectorAll('input')
      opts.contents = []
      opts.pgpKey = fs.readFileSync(path.join(__dirname, '/assets/pub_key'), 'utf8')

      for (var i = 0; i < inputs.length; i++) {
        var item
        if (inputs[i].type === 'radio' && inputs[i].checked) {
          item = inputs[i].name + ': ' + inputs[i].value
        } else if (inputs[i].type !== 'submit') {
          item = inputs[i].name + ': ' + inputs[i].value
        }
        opts.contents.push(item)
      }

      var pgpContent = PgpContent(opts)
      pgpContent.send(function (err, val) {
        if (err) console.log('err', err)
        openEmailClient(val)
      })
    }
  }
})

function mainView (state, prev, send) {
  addFont()

  return html`

      ${intro()}
      ${about()}
      ${getInTouch(state, prev, send)}
      ${origins()}
      ${footer()}

  `
}

function intro () {
  var text = fs.readFileSync(path.join(__dirname, '/assets/intro.txt'), 'utf8')

  return html`

        ${href('white', '#contact', 'contact')}

      ${border('white')}

${text}

  `
}

function about () {
  var about = fs.readFileSync(path.join(__dirname, '/assets/about.txt'), 'utf8')
  var aboutEmergency = fs.readFileSync(path.join(__dirname, '/assets/about-emergency.txt'), 'utf8')
  var logo = fs.readFileSync(path.join(__dirname, '/assets/civicdr-logo.svg'), 'utf8')

  return html`

        ${toHtml(logo)}

      ${border('salmon')}

 what we do

${about}

${aboutEmergency}

  `
}

function getInTouch (state, prev, send) {
  return html`

      ${border('salmon')}

        ${formDescription()}
        ${form(state, prev, send)}

  `
}

function origins () {
  var origins = fs.readFileSync(path.join(__dirname, '/assets/origins.txt'), 'utf8')

  return html`

      ${border('salmon')}

 what we do

${origins}

          ${href('salmon', 'https://d2sxu8bam0n8dc.cloudfront.net', 'Security Policy Generator')}

  `
}

function footer () {
  var logo = fs.readFileSync(path.join(__dirname, '/assets/civicdr-logo.svg'), 'utf8')

  return html`

        back to top

          ${toHtml(logo)}

  `
}

function formDescription () {
  var organizations = fs.readFileSync(path.join(__dirname, '/assets/organizations.txt'), 'utf8')
  var partner = fs.readFileSync(path.join(__dirname, '/assets/partner.txt'), 'utf8')

  return html`

 we can help

${organizations}

${partner}

        ${href('salmon', 'https://www.accessnow.org/help/', 'Access Now Digital Security Helpline')}

        ${href('salmon', 'https://securitywithoutborders.org/', 'Security Without Borders')}

  `
}

function form (state, prev, send) {
  return html`
    <form class="w-50-ns" onsubmit=${email}>
      ${input({ type: 'text', name: 'organisation', placeholder: 'Your organisation name*' })}
      ${input({ type: 'text', name: 'issue', placeholder: 'Briefly describe your problem*' })}

Does the person dealing with the incident speak English?*

        <input id="yes" value="yes" name="english" type="radio">
        YES
        <input id="no" value="no" name="english" type="radio">
        NO

      ${input({ type: 'email', name: 'email', placeholder: 'Contact email address*' })}

        <input type="submit" class="pt3 pb3 w-100 white ttu bg-salmon b--transparent br2" value="submit">

    </form>
  `

  function email (e) {
    e.preventDefault()
    send('email:getFormData', e.target)
  }
}

function border (colour) {
  return html`

  `
}

function href (color, href, text) {
  return html`
    ${text}
  `
}

function input (opts) {
  var id = opts.id || ''
  var type = opts.type || 'text'
  var placeholder = opts.placeholder || ''
  var name = opts.name || ''

  return html`
    <input id=${id} name=${name} class="input-reset w-100 pt3 pb4 pr3 pl3 ba b--black-20 mb3" type=${type} placeholder=${placeholder}>
  `
}

function toHtml (item) {
  var element = html`<div></div>`
  element.innerHTML = item

  return element.childNodes[0]
}

function openEmailClient (content) {
  var email = 'help@civicdr.org'
  var subject = 'CiviCDR Contact Form'
  var mailto = 'mailto:' + email + '?subject=' + subject + '&body=' + content
  window.open(mailto, '_self')
}

function addFont () {
  var link = document.createElement('link')
  var head = document.getElementsByTagName('head')[0]
  link.href = 'https://fonts.googleapis.com/css?family=Roboto:400,700'
  link.rel = 'stylesheet'
  head.appendChild(link)
}

app.router(['/', mainView])
mount('body', app.start())
<commit_msg>generator link removed<commit_after>var PgpContent = require('pgp-encrypt-content')
var mount = require('choo/mount')
var html = require('choo/html')
var css = require('sheetify')
var choo = require('choo')
var path = require('path')
var fs = require('fs')

var style = css('./index.css')
css('tachyons')

var app = choo()

app.model({
  namespace: 'email',
  state: { contents: [] },
  reducers: {
    send: function (state, data) {
      return { contents: data }
    }
  },
  effects: {
    getFormData: function (state, data, send, done) {
      var opts = {}
      var inputs = document.querySelectorAll('input')
      opts.contents = []
      opts.pgpKey = fs.readFileSync(path.join(__dirname, '/assets/pub_key'), 'utf8')

      for (var i = 0; i < inputs.length; i++) {
        var item
        if (inputs[i].type === 'radio' && inputs[i].checked) {
          item = inputs[i].name + ': ' + inputs[i].value
        } else if (inputs[i].type !== 'submit') {
          item = inputs[i].name + ': ' + inputs[i].value
        }
        opts.contents.push(item)
      }

      var pgpContent = PgpContent(opts)
      pgpContent.send(function (err, val) {
        if (err) console.log('err', err)
        openEmailClient(val)
      })
    }
  }
})

function mainView (state, prev, send) {
  addFont()

  return html`

      ${intro()}
      ${about()}
      ${getInTouch(state, prev, send)}
      ${origins()}
      ${footer()}

  `
}

function intro () {
  var text = fs.readFileSync(path.join(__dirname, '/assets/intro.txt'), 'utf8')

  return html`

        ${href('white', '#contact', 'contact')}

      ${border('white')}

${text}

  `
}

function about () {
  var about = fs.readFileSync(path.join(__dirname, '/assets/about.txt'), 'utf8')
  var aboutEmergency = fs.readFileSync(path.join(__dirname, '/assets/about-emergency.txt'), 'utf8')
  var logo = fs.readFileSync(path.join(__dirname, '/assets/civicdr-logo.svg'), 'utf8')

  return html`

        ${toHtml(logo)}

      ${border('salmon')}

 what we do

${about}

${aboutEmergency}

  `
}

function getInTouch (state, prev, send) {
  return html`

      ${border('salmon')}

        ${formDescription()}
        ${form(state, prev, send)}

  `
}

function origins () {
  var origins = fs.readFileSync(path.join(__dirname, '/assets/origins.txt'), 'utf8')

  return html`

      ${border('salmon')}

 what we do

${origins}

  `
}

function footer () {
  var logo = fs.readFileSync(path.join(__dirname, '/assets/civicdr-logo.svg'), 'utf8')

  return html`

        back to top

          ${toHtml(logo)}

  `
}

function formDescription () {
  var organizations = fs.readFileSync(path.join(__dirname, '/assets/organizations.txt'), 'utf8')
  var partner = fs.readFileSync(path.join(__dirname, '/assets/partner.txt'), 'utf8')

  return html`

 we can help

${organizations}

${partner}

        ${href('salmon', 'https://www.accessnow.org/help/', 'Access Now Digital Security Helpline')}

        ${href('salmon', 'https://securitywithoutborders.org/', 'Security Without Borders')}

  `
}

function form (state, prev, send) {
  return html`
    <form class="w-50-ns" onsubmit=${email}>
      ${input({ type: 'text', name: 'organisation', placeholder: 'Your organisation name*' })}
      ${input({ type: 'text', name: 'issue', placeholder: 'Briefly describe your problem*' })}

Does the person dealing with the incident speak English?*

        <input id="yes" value="yes" name="english" type="radio">
        YES
        <input id="no" value="no" name="english" type="radio">
        NO

      ${input({ type: 'email', name: 'email', placeholder: 'Contact email address*' })}

        <input type="submit" class="pt3 pb3 w-100 white ttu bg-salmon b--transparent br2" value="submit">

    </form>
  `

  function email (e) {
    e.preventDefault()
    send('email:getFormData', e.target)
  }
}

function border (colour) {
  return html`

  `
}

function href (color, href, text) {
  return html`
    ${text}
  `
}

function input (opts) {
  var id = opts.id || ''
  var type = opts.type || 'text'
  var placeholder = opts.placeholder || ''
  var name = opts.name || ''

  return html`
    <input id=${id} name=${name} class="input-reset w-100 pt3 pb4 pr3 pl3 ba b--black-20 mb3" type=${type} placeholder=${placeholder}>
  `
}

function toHtml (item) {
  var element = html`<div></div>`
  element.innerHTML = item

  return element.childNodes[0]
}

function openEmailClient (content) {
  var email = 'help@civicdr.org'
  var subject = 'CiviCDR Contact Form'
  var mailto = 'mailto:' + email + '?subject=' + subject + '&body=' + content
  window.open(mailto, '_self')
}

function addFont () {
  var link = document.createElement('link')
  var head = document.getElementsByTagName('head')[0]
  link.href = 'https://fonts.googleapis.com/css?family=Roboto:400,700'
  link.rel = 'stylesheet'
  head.appendChild(link)
}

app.router(['/', mainView])
mount('body', app.start())
<|endoftext|>


<commit_before>var util = require('util');

var internal = require('./build/Release/gss');

// Export all the constants, as-is.
Object.keys(internal.constants).forEach(function(key) {
  exports[key] = internal.constants[key];
});

var GSS_C_CALLING_ERROR_OFFSET = 24;
var GSS_C_ROUTINE_ERROR_OFFSET = 16;
var GSS_C_SUPPLEMENTARY_OFFSET = 0;
var GSS_C_CALLING_ERROR_MASK = 0377;
var GSS_C_ROUTINE_ERROR_MASK = 0377;
var GSS_C_SUPPLEMENTARY_MASK = 0177777;

function GSS_CALLING_ERROR(x) {
  return (x & (GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET)) >>> 0;
}
function GSS_ROUTINE_ERROR(x) {
  return (x & (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET)) >>> 0;
}
function GSS_SUPPLEMENTARY_INFO(x) {
  return (x & (GSS_C_SUPPLEMENTARY_MASK << GSS_C_SUPPLEMENTARY_OFFSET)) >>> 0;
}
function GSS_ERROR(x) {
  return (x & ((GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET) |
               (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET))) >>> 0;
}

function GSSError(major, minor, mechanism) {
  // Apparently you're supposed to do this?
  Error.captureStackTrace(this, GSSError);
  this.major = major;
  this.minor = minor;
  this.mechanism = mechanism;
}
util.inherits(GSSError, Error);
GSSError.prototype.callingError = function() {
  return GSS_CALLING_ERROR(this.major);
}
GSSError.prototype.routineError = function() {
  return GSS_ROUTINE_ERROR(this.major);
}
GSSError.prototype.supplementaryInfo = function() {
  return GSS_SUPPLEMENTARY_INFO(this.major);
}
GSSError.prototype.toString = function() {
  var statuses = internal.displayStatus(this.major, exports.C_GSS_CODE,
                                        this.mechanism);
  if (this.minor) {
    statuses = statuses.concat(
      internal.displayStatus(this.minor, exports.C_MECH_CODE, this.mechanism));
  }
  statuses = statuses.map(function(status) {
    return status.toString('utf8');
  });
  return 'GSS error: ' + statuses.join('; ');
};
exports.Error = GSSError;

function gssCall(mech, fn) {
  var args = [].slice.call(arguments, 2);
  var ret = fn.apply(internal, args);
  if (GSS_ERROR(ret.major)) {
    throw new GSSError(ret.major, ret.minor);
  }
  return ret;
}

function Name(handle) {
  this.handle_ = handle;
}
Name.prototype.toString = function() {
  // TODO(davidben): Care about the OID? OIDs are pretty useless right
  // now.
  return gssCall(null, internal.displayName,
                 this.handle_).buffer.toString('utf8');
};
Name.prototype.exportName = function() {
  return gssCall(null, internal.exportName, this.handle_).buffer;
};
Name.prototype.compareName = function(name) {
  return gssCall(null, internal.compareName,
                 this.handle_, name.handle_).nameEqual != 0;
};
Name.prototype.canonicalize = function(oid) {
  var handle = new internal.NameHandle();
  gssCall(null, internal.canonicalizeName, this.handle_, oid, handle);
  return new Name(handle);
};

exports.importName = function(buffer, oid) {
  if (typeof buffer === "string")
    buffer = new Buffer(buffer, "utf8");
  var handle = new internal.NameHandle();
  gssCall(null, internal.importName, buffer, oid, handle);
  return new Name(handle);
};

function Credential(handle) {
  this.handle_ = handle;
}

exports.acquireCredential = function(name,
                                     timeReq,
                                     desiredMechs,
                                     credUsage) {
  var nameHandle = name ? name.handle_ : new internal.NameHandle();
  var handle = new internal.CredHandle();
  var ret = gssCall(null, internal.acquireCred,
                    nameHandle, timeReq, desiredMechs, credUsage, handle);
  // TODO(davidben): Actually do something with the return value? We
  // went through all this trouble to plumb the the gss_OID_set
  // through...
  return new Credential(handle);
};

function Context(credential) {
  this.credHandle_ =
    credential ? credential.handle_ : new internal.CredHandle();
  this.handle_ = new internal.ContextHandle();
  this.established_ = false;
  this.retFlags_ = 0;
}
Context.prototype.isEstablished = function() {
  return this.established_;
};
Context.prototype.flags = function() {
  return this.retFlags_;
};

function AcceptContext(credential, opts) {
  Context.call(this, credential);
  // TODO(davidben): Pull channel bindings out of opts.
}
util.inherits(AcceptContext, Context);
AcceptContext.prototype.acceptSecContext = function(token) {
  var srcNameHandle = new internal.NameHandle();
  var ret = gssCall(null, internal.acceptSecContext,
                    this.handle_, this.credHandle_, token, null, srcNameHandle);
  this.retFlags_ = ret.retFlags;
  if (!(ret.major & exports.S_CONTINUE_NEEDED)) {
    this.established_ = true;
    this.srcName_ = new Name(srcNameHandle);
  }
  return ret.outputToken;
}
AcceptContext.prototype.srcName = function() {
  return this.srcName_;
};

exports.createAcceptor = function(credential, opts) {
  return new AcceptContext(credential, opts);
};

function InitContext(credential, target, opts) {
  Context.call(this, credential);
  opts = opts || { };
  this.target_ = target;
  this.flags_ = opts.flags;
  this.mechanism_ = opts.mechanism || new internal.OidHandle();
  this.lifetime_ = opts.lifetime || 0;
}
util.inherits(InitContext, Context);
InitContext.prototype.initSecContext = function(token) {
  // C++ code can't deal with NULL buffers, but an empty buffer works
  // too, according to RFC.
  token = token || new Buffer(0);
  var ret = gssCall(null, internal.initSecContext,
                    this.credHandle_, this.handle_, this.target_.handle_,
                    this.mechanism_, this.flags_, this.lifetime_,
                    null, token);
  this.actualMechanism_ = ret.actualMechType;
  this.retFlags_ = ret.retFlags;
  if (!(ret.major & exports.S_CONTINUE_NEEDED)) {
    this.established_ = true;
    this.srcName_ = new Name(srcNameHandle);
  }
  return ret.outputToken;

}

exports.createInitiator = function(credential, target, opts) {
  return new InitContext(credential, target, opts);
};
<commit_msg>Get the initiator working<commit_after>var util = require('util');

var internal = require('./build/Release/gss');

// Export all the constants, as-is.
Object.keys(internal.constants).forEach(function(key) {
  exports[key] = internal.constants[key];
});

var GSS_C_CALLING_ERROR_OFFSET = 24;
var GSS_C_ROUTINE_ERROR_OFFSET = 16;
var GSS_C_SUPPLEMENTARY_OFFSET = 0;
var GSS_C_CALLING_ERROR_MASK = 0377;
var GSS_C_ROUTINE_ERROR_MASK = 0377;
var GSS_C_SUPPLEMENTARY_MASK = 0177777;

function GSS_CALLING_ERROR(x) {
  return (x & (GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET)) >>> 0;
}
function GSS_ROUTINE_ERROR(x) {
  return (x & (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET)) >>> 0;
}
function GSS_SUPPLEMENTARY_INFO(x) {
  return (x & (GSS_C_SUPPLEMENTARY_MASK << GSS_C_SUPPLEMENTARY_OFFSET)) >>> 0;
}
function GSS_ERROR(x) {
  return (x & ((GSS_C_CALLING_ERROR_MASK << GSS_C_CALLING_ERROR_OFFSET) |
               (GSS_C_ROUTINE_ERROR_MASK << GSS_C_ROUTINE_ERROR_OFFSET))) >>> 0;
}

function GSSError(major, minor, mechanism) {
  // Apparently you're supposed to do this?
  Error.captureStackTrace(this, GSSError);
  this.major = major;
  this.minor = minor;
  this.mechanism = mechanism;
}
util.inherits(GSSError, Error);
GSSError.prototype.callingError = function() {
  return GSS_CALLING_ERROR(this.major);
}
GSSError.prototype.routineError = function() {
  return GSS_ROUTINE_ERROR(this.major);
}
GSSError.prototype.supplementaryInfo = function() {
  return GSS_SUPPLEMENTARY_INFO(this.major);
}
GSSError.prototype.toString = function() {
  var statuses = internal.displayStatus(this.major, exports.C_GSS_CODE,
                                        this.mechanism);
  if (this.minor) {
    statuses = statuses.concat(
      internal.displayStatus(this.minor, exports.C_MECH_CODE, this.mechanism));
  }
  statuses = statuses.map(function(status) {
    return status.toString('utf8');
  });
  return 'GSS error: ' + statuses.join('; ');
};
exports.Error = GSSError;

function gssCall(mech, fn) {
  var args = [].slice.call(arguments, 2);
  var ret = fn.apply(internal, args);
  if (GSS_ERROR(ret.major)) {
    throw new GSSError(ret.major, ret.minor);
  }
  return ret;
}

function Name(handle) {
  this.handle_ = handle;
}
Name.prototype.toString = function() {
  // TODO(davidben): Care about the OID? OIDs are pretty useless right
  // now.
  return gssCall(null, internal.displayName,
                 this.handle_).buffer.toString('utf8');
};
Name.prototype.exportName = function() {
  return gssCall(null, internal.exportName, this.handle_).buffer;
};
Name.prototype.compareName = function(name) {
  return gssCall(null, internal.compareName,
                 this.handle_, name.handle_).nameEqual != 0;
};
Name.prototype.canonicalize = function(oid) {
  var handle = new internal.NameHandle();
  gssCall(null, internal.canonicalizeName, this.handle_, oid, handle);
  return new Name(handle);
};

exports.importName = function(buffer, oid) {
  if (typeof buffer === "string")
    buffer = new Buffer(buffer, "utf8");
  var handle = new internal.NameHandle();
  gssCall(null, internal.importName, buffer, oid, handle);
  return new Name(handle);
};

function Credential(handle) {
  this.handle_ = handle;
}

exports.acquireCredential = function(name,
                                     timeReq,
                                     desiredMechs,
                                     credUsage) {
  var nameHandle = name ? name.handle_ : new internal.NameHandle();
  var handle = new internal.CredHandle();
  var ret = gssCall(null, internal.acquireCred,
                    nameHandle, timeReq, desiredMechs, credUsage, handle);
  // TODO(davidben): Actually do something with the return value? We
  // went through all this trouble to plumb the the gss_OID_set
  // through...
  return new Credential(handle);
};

function Context(credential) {
  this.credHandle_ =
    credential ? credential.handle_ : new internal.CredHandle();
  this.handle_ = new internal.ContextHandle();
  this.established_ = false;
  this.retFlags_ = 0;
}
Context.prototype.isEstablished = function() {
  return this.established_;
};
Context.prototype.flags = function() {
  return this.retFlags_;
};

function AcceptContext(credential, opts) {
  Context.call(this, credential);
  // TODO(davidben): Pull channel bindings out of opts.
}
util.inherits(AcceptContext, Context);
AcceptContext.prototype.acceptSecContext = function(token) {
  var srcNameHandle = new internal.NameHandle();
  var ret = gssCall(null, internal.acceptSecContext,
                    this.handle_, this.credHandle_, token, null, srcNameHandle);
  this.retFlags_ = ret.retFlags;
  if (!(ret.major & exports.S_CONTINUE_NEEDED)) {
    this.established_ = true;
    this.srcName_ = new Name(srcNameHandle);
  }
  return ret.outputToken;
}
AcceptContext.prototype.srcName = function() {
  return this.srcName_;
};

exports.createAcceptor = function(credential, opts) {
  return new AcceptContext(credential, opts);
};

function InitContext(credential, target, opts) {
  Context.call(this, credential);
  opts = opts || { };
  this.target_ = target;
  this.flags_ = opts.flags;
  this.mechanism_ = opts.mechanism || new internal.OidHandle();
  this.lifetime_ = opts.lifetime || 0;
}
util.inherits(InitContext, Context);
InitContext.prototype.initSecContext = function(token) {
  // C++ code can't deal with NULL buffers, but an empty buffer works
  // too, according to RFC.
  token = token || new Buffer(0);
  var ret = gssCall(null, internal.initSecContext,
                    this.credHandle_, this.handle_, this.target_.handle_,
                    this.mechanism_, this.flags_, this.lifetime_,
                    null, token);
  this.actualMechanism_ = ret.actualMechType;
  this.retFlags_ = ret.retFlags;
  if (!(ret.major & exports.S_CONTINUE_NEEDED)) {
    this.established_ = true;
  }
  return ret.outputToken;

}

exports.createInitiator = function(credential, target, opts) {
  return new InitContext(credential, target, opts);
};
<|endoftext|>


<commit_before>
const profiler = require('v8-profiler');
const path = require('path');
const client = require('prom-client');
const registry = new client.Registry();
let gauge = null;
let timeoutProfiling = null;
const timeoutProfilingDuration = 1000 * 60 * 5;

const resetProfiling = () => {
    if (timeoutProfiling)
        clearTimeout(timeoutProfiling);
    timeoutProfiling = setTimeout(resetProfiling, timeoutProfilingDuration);
    const profile = profiler.stopProfiling();
    profile.delete();
    // due to memory leaks
    profiler.deleteAllProfiles();
    profiler.startProfiling();
    return profile;
}

const initProfiling = () => {
    profiler.setSamplingInterval(100);
    profiler.startProfiling();
    timeoutProfiling = setTimeout(resetProfiling, timeoutProfilingDuration);
};

const clear = () => {
    registry.clear();
    gauge = new client.Gauge({ name: 'profiling', help: 'test', labelNames: [ 'signature' ], registers: [ registry ] });
};

const describe = (doc, parents, depth) => {
    if (doc.functionName) {
        if (parents + doc.functionName === "(root)#(idle)")
            return;
        if (parents + doc.functionName === "(root)#(garbage collector)")
            return;
        if (parents + doc.functionName === "(root)#(program)")
            return;
        if (doc.functionName === "slash_metrics_handler")
            return;

        //        console.log('-'.repeat(depth) + ' ' + doc.signature, doc.hitCount);
        //        console.log(parents + doc.functionName, doc.hitCount);
        gauge.set({ signature: parents + doc.functionName }, doc.hitCount);
        parents += doc.functionName + "#";
    }
//    else
//        console.log('-'.repeat(depth) + ' ' + doc.url, doc.hitCount);

    if (doc.children)
        for (var i = 0; i < doc.children.length; i++)
            describe(doc.children[i], parents, depth + 1);
};

const slash_metrics_handler = () => {
    const profile = resetProfiling();
    clear();
    describe(profile.head, "", 1);
    return registry.metrics();
}

const hostname = "0.0.0.0"
const port = 9142;

const http = require('http');

const server = http.createServer((req, res) => {
    const { method, url } = req;

    if (method === "GET" && url === "/metrics") {
        res.statusCode = 200;
        const metrics = slash_metrics_handler();
        res.end(metrics);
        return;
    } else if (method === "GET" && url === "/") {
        res.writeHead(301, {
            'Location': '/metrics'
        });
        res.end(`
<title>Node profiling exporter</title>

Node profiling exporter

Metrics

`);
	return;
    }

    res.statusCode = 404;
    res.end();
    return;
});

server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

const executeApp = () => {
    const appModule = path.resolve(path.join(process.argv[2]));
    console.info("\n");
    console.info("*********************************************");
    console.info('*****  Profiler listening on ' + hostname + ":" + port);
    console.info("*****  Executing:", appModule);
    console.info("*********************************************");
    console.info("\n");
    process.argv.shift();
    process.argv.shift();
    require(appModule);
}

const mainPromfiler = () => {
    server.listen(port, hostname, () => {
        initProfiling();
        executeApp();
    });
};

mainPromfiler();
<commit_msg>clean<commit_after>
const profiler = require('v8-profiler');
const path = require('path');
const client = require('prom-client');
const registry = new client.Registry();
let gauge = null;
let timeoutProfiling = null;
const timeoutProfilingDuration = 1000 * 60 * 5;

const resetProfiling = () => {
    if (timeoutProfiling)
        clearTimeout(timeoutProfiling);
    timeoutProfiling = setTimeout(resetProfiling, timeoutProfilingDuration);
    const profile = profiler.stopProfiling();
    profile.delete();
    profiler.startProfiling();
    return profile;
}

const initProfiling = () => {
    profiler.setSamplingInterval(100);
    profiler.startProfiling();
    timeoutProfiling = setTimeout(resetProfiling, timeoutProfilingDuration);
};

const clear = () => {
    registry.clear();
    gauge = new client.Gauge({ name: 'profiling', help: 'test', labelNames: [ 'signature' ], registers: [ registry ] });
};

const describe = (doc, parents, depth) => {
    if (doc.functionName) {
        // @todo: add a promfiler argument for verbose mode
        if (parents + doc.functionName === "(root)#(idle)")
            return;
        if (parents + doc.functionName === "(root)#(garbage collector)")
            return;
        if (parents + doc.functionName === "(root)#(program)")
            return;
        if (doc.functionName === "slash_metrics_handler")
            return;

        gauge.set({ signature: parents + doc.functionName }, doc.hitCount);
        parents += doc.functionName + "#";
    }

    if (doc.children)
        for (var i = 0; i < doc.children.length; i++)
            describe(doc.children[i], parents, depth + 1);
};

const slash_metrics_handler = () => {
    const profile = resetProfiling();
    clear();
    describe(profile.head, "", 1);
    return registry.metrics();
}

const hostname = "0.0.0.0"
const port = 9142;

const http = require('http');

const server = http.createServer((req, res) => {
    const { method, url } = req;

    if (method === "GET" && url === "/metrics") {
        res.statusCode = 200;
        const metrics = slash_metrics_handler();
        res.end(metrics);
        return;
    } else if (method === "GET" && url === "/") {
        res.writeHead(301, {
            'Location': '/metrics'
        });
        res.end(`
<title>Node profiling exporter</title>

Node profiling exporter

Metrics

`);
        return;
    }

    res.statusCode = 404;
    res.end();
    return;
});

server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

const executeApp = () => {
    const appModule = path.resolve(path.join(process.argv[2]));
    console.info("\n");
    console.info("*********************************************");
    console.info('*****  Profiler listening on ' + hostname + ":" + port);
    console.info("*****  Executing:", appModule);
    console.info("*********************************************");
    console.info("\n");
    process.argv.shift();
    process.argv.shift();
    require(appModule);
}

const mainPromfiler = () => {
    server.listen(port, hostname, () => {
        initProfiling();
        executeApp();
    });
};

mainPromfiler();
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var isDocker;

function check() {
	try {
		fs.statSync('/.dockerinit');
		return true;
	} catch (err) {
		return false;
	}
}

module.exports = function () {
	if (isDocker === undefined) {
		isDocker = check();
	}

	return isDocker;
};
<commit_msg>Use /.dockerenv as a fallback mechanism<commit_after>'use strict';
var fs = require('fs');
var isDocker;

function check() {
	try {
		fs.statSync('/.dockerinit');
		fs.statSync('/.dockerenv');
		return true;
	} catch (err) {
		return false;
	}
}

module.exports = function () {
	if (isDocker === undefined) {
		isDocker = check();
	}

	return isDocker;
};
<|endoftext|>


<commit_before>var chai = require('chai');
var should = chai.should();
var expect = chai.expect;

var testNumbers = [0, 1, 3, 4, 1968, 2999, 3000, 10000];
var testChars = [null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];
var testAll = [0, 1, 3, 4, 1968, 2999, 3000, 10000, null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];

describe('Number', function(){
  it('should return number', function()
  {
    /*
    var number = RomanNumber(20);
    expect(number.toInt()).not.to.be.NaN;
    */
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber(4000)}
    expect(invalidNumber).to.throw(Error);
  });

  it('should not be undefined', function()
  {
    var invalidNumber = function(){new RomanNumber()}
    expect(invalidNumber).to.throw(Error);
  });
  it('should not be null', function()
  {
    var invalidNumber = function(){new RomanNumber(null)}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testNumbers.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      if(number >=1 && number <= 3999)
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('Roman Numeral', function(){
  it('should validate to ensure a valid roman numeral was entered', function()
  {

  });
  it('should throw error if roman numeral is not valid', function()
  {
    var number = function(){new RomanNumber("JARED")}
    expect(number).to.throw(Error);
  });

  it('should return roman numeral', function()
  {
    var number = RomanNumber(21);
    expect(number.toString()).to.equal("XXI");
  });
  it('should not be null', function()
  {
    var number = function(){new RomanNumber(null)}
    expect(number).to.throw(Error);
  });
  it('should not return an error', function()
  {
    var number = function(){new RomanNumber("XX")}
    expect(number).to.not.throw(Error);
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber("MMMMDMXCIX")}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testChars.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(validator.test(number) && number != null && number != "")
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('All Values', function(){
  it('should test all values', function()
  {
    testAll.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(typeof number === 'string')
      {
        if(validator.test(number) && number != null && number != "")
        {
          expect(testValue).not.to.throw(Error);
        }
        else {
          expect(testValue).to.throw(Error);
        }
      }
      else
      {
        if(number >=1 && number <= 3999)
        {
          expect(testValue).not.to.throw(Error);
        }
        else
        {
          expect(testValue).to.throw(Error);
        }
      }

    });
  });
});

function RomanNumber(pNumber)
{
	if (!(this instanceof RomanNumber)){
        return new RomanNumber(pNumber);
   }

var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};

var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

   //Checks the user value added
   if(typeof pNumber === 'string')
   {

     if(validator.test(pNumber) && pNumber != null && pNumber != "")
     {
       this.romanNumeral = pNumber;
     }
     else
     {
        throw new Error("Please enter valid Roman Numeral");
     }
   }
   else
   {
      if(pNumber !== undefined && pNumber >=1 && pNumber <= 3999)
     	{
        this.integer = pNumber;
      }
      else if(pNumber !== undefined)
    	{
    		throw new Error("Please enter number");
    	}
      else
      {
          throw new Error("Number must be between 1 and 3999");
      }
   }

	this.toInt = function()
	{
    if(this.romanNumeral !== undefined)
    {
      var	token = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
        num = 0, m;
      while (m = token.exec(this.romanNumeral))
      {
        num += lookup[m[0]];
      }
      return num;
    }
    else
    {
      return this.integer;
    }
	};

	this.toString = function()
	{
    var roman = '';

    for ( var i in lookup ) {
      while ( this.integer >= lookup[i] ) {
        roman += i;
        this.integer -= lookup[i];
      }
    }
    return roman;
	};
}
<commit_msg>Update test suite<commit_after>var chai = require('chai');
var should = chai.should();
var expect = chai.expect;

var testNumbers = [0, 1, 3, 4, 1968, 2999, 3000, 10000];
var testChars = [null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];
var testAll = [0, 1, 3, 4, 1968, 2999, 3000, 10000, null, '', "I", "III", "IIII", "IV", "V", 'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MMMMCMXCIX', 'MMMMDMXCIX', '1493'];

describe('Number', function(){
  it('should return number', function()
  {
    /*
    var number = RomanNumber(20);
    expect(number.toInt()).not.to.be.NaN;
    */
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber(4000)}
    expect(invalidNumber).to.throw(Error);
  });

  it('should not be undefined', function()
  {
    var invalidNumber = function(){new RomanNumber()}
    expect(invalidNumber).to.throw(Error);
  });
  it('should not be null', function()
  {
    var invalidNumber = function(){new RomanNumber(null)}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testNumbers.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      if(number >=1 && number <= 3999)
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('Roman Numeral', function(){
  it('should validate to ensure a valid roman numeral was entered', function()
  {

  });
  it('should throw error if roman numeral is not valid', function()
  {
    var number = function(){new RomanNumber("JARED")}
    expect(number).to.throw(Error);
  });

  it('should return roman numeral', function()
  {
    var number = RomanNumber(21);
    expect(number.toString()).to.equal("XXI");
  });
  it('should not be null', function()
  {
    var number = function(){new RomanNumber(null)}
    expect(number).to.throw(Error);
  });
  it('should not return an error', function()
  {
    var number = function(){new RomanNumber("XX")}
    expect(number).to.not.throw(Error);
  });

  it('should be between 1 and 3999', function()
  {
    var invalidNumber = function(){new RomanNumber("MMMMDMXCIX")}
    expect(invalidNumber).to.throw(Error);
  });
  it('should test multiple numbers', function()
  {
    testChars.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(validator.test(number) && number != null && number != "")
      {
        expect(testValue).not.to.throw(Error);
      }
      else
      {
        expect(testValue).to.throw(Error);
      }
    });
  });
});

describe('All Values', function(){
  it('should test all values', function()
  {
    testAll.forEach(function(number)
    {
      var testValue = function(){new RomanNumber(number)};
      var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

      if(typeof number === 'string')
      {
        if(validator.test(number) && number != null && number != "")
        {
          expect(testValue).not.to.throw(Error);
        }
        else {
          expect(testValue).to.throw(Error);
        }
      }
      else
      {
        if(number >=1 && number <= 3999)
        {
          expect(testValue).not.to.throw(Error);
        }
        else
        {
          expect(testValue).to.throw(Error);
        }
      }

    });
  });
});

function RomanNumber(pNumber)
{
	if (!(this instanceof RomanNumber)){
        return new RomanNumber(pNumber);
   }

var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};
var validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/;

   //Checks the user value added
   if(typeof pNumber === 'string')
   {
     //Valid string to ensure it is a valid Roman Numeral
      if(validator.test(pNumber) && pNumber !== null && pNumber !== "")
     {
       this.romanNumeral = pNumber;
     }
     else
     {
        throw new Error("Please enter valid Roman Numeral");
     }
   }
   else
   {
     //Check number is not empty and is between 1 and 3999
      if(pNumber !== undefined && pNumber >=1 && pNumber <= 3999)
     	{
        this.integer = pNumber;
      }
      else if(pNumber !== undefined)
    	{
    		throw new Error("Please enter number");
    	}
      else
      {
          throw new Error("Number must be between 1 and 3999");
      }
   }

	this.toInt = function()
	{
    if(this.romanNumeral !== undefined)
    {
      var	token = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
        num = 0, m;
      while (m = token.exec(this.romanNumeral))
      {
        num += lookup[m[0]];
      }
      return num;
    }
    else
    {
      return this.integer;
    }
	};

	this.toString = function()
	{
    var roman = '';

    for ( var i in lookup ) {
      while ( this.integer >= lookup[i] ) {
        roman += i;
        this.integer -= lookup[i];
      }
    }
    return roman;
	};
}
<|endoftext|>