<commit_before>"use strict";
var WebSocket = require("ws");
var EventEmitter = require("events");

/**
 * Small helper in creating gateways to communicate between client and server.
 */
class WsGateway extends EventEmitter {
    static get ERROR() {
        return "error";
    }
    static get CLOSE() {
        return "close";
    }
    static get START() {
        return "start";
    }
    static get CONNECT() {
        return "connect";
    }
    static get MESSAGE() {
        return "message";
    }
    /**
     *
     * @param opt : Options
     * @param basicAuth : Basic Auth by origin
     * @param onConnectAuth : Extend Auth by cookie
     */
    constructor(opt, basicAuth, extendAuth, headers) {
        super();
        this.ip = opt.ip;//for client
        this.origin = opt.origin;
        this.port = opt.port;
        this.hashKey = opt.hash != null ? opt.hash : opt.hashKey != null ? opt.hashKey : "hash=";
        this.handlers = {};
        this.socket = null;//    -  websocket
        var self = this;
        if (this.ip == null) {//server
            this.basicAuth = basicAuth != null ? basicAuth : function (info, done) {
                var origin;
                try {
                    origin = info.req.headers.origin;
                } catch (e) {
                    return done(false);
                }
                if (origin !== self.origin)
                    return done(false);
                return done(true);
            }
            this.extendAuth = extendAuth != null ? extendAuth : function (gw, cb) {
                var hash;
                try {
                    hash = gw.upgradeReq.headers["sec-websocket-protocol"];
                } catch (e) {
                    cb(e);
                    return;
                }
                if (hash == null) {
                    cb("Hash not find");
                    return;
                }
                cb(null, {});
            };
            return;
        }
        //is client - use extendAuth as message reader
        this.extendAuth = extendAuth != null ? extendAuth : function (message, arg) {
            self.messageParser(self.socket, self.socket, message, arg);
        };
        this.basicAuth = basicAuth != null ? basicAuth : function () {
            self.socket.on("message", self.extendAuth);
        };
        this.headers = headers;
    }
    addHandler(code, container) {
        container.Code = code;
        this.handlers[code] = container.RequestHandler;
    }
    /**
     * Server start
     */
    start() {
        this.socket = new WebSocket.Server({ port: this.port, verifyClient: this.basicAuth });
        var self = this;
        this.socket.on("connection",
            function (ws) {
                self.extendAuth(ws, function (error, user) {
                    if (error)
                        return;
                    ws.on("message", function (msg, arg) {
                        self.messageParser(ws, user, msg, arg);
                    });
                    ws.on("close", function (c, m) {
                        self.emit(WsGateway.CLOSE, c, m, user);
                    });
                    ws.on("error", function (e) {
                        self.emit(WsGateway.ERROR, e, ws, user);
                    });
                    self.emit(WsGateway.CONNECT, ws, user);
                });

            });
        this.emit(WsGateway.START, this);
    }
    /**
     * Client connect
     */
    connect() {
        var self = this;
        var op = { "origin": this.origin };
        if (this.headers != null)
            op.headers = this.headers;
        this.socket = new WebSocket(`ws:${this.ip}:${this.port}`, this.hashKey, op);
        this.socket.on("open", function (a1, a2, a3) {
            self.emit(WsGateway.CONNECT, self);
            self.basicAuth();
        });
    }
    sendTo(socket, target, method, packet, buffer) {
        if (socket == null || socket.readyState !== 1/*WebSocket.OPEN*/) return;
        const self = this;
        if (buffer == null)
            buffer = Buffer.allocUnsafe(0);
        try {
            const header = this.getHeader(target, method, packet);
            const buff = Buffer.concat([header, buffer]);
            socket.send(buff, { binary: true, mask: true }, function (error) {
                if (error != null)
                    self.emit(WsGateway.ERROR, error, socket);
            });
        } catch (e) {
            this.emit(WsGateway.ERROR, e, socket);
        }
    }
    send(target, method, packet, buffer) {
        this.sendTo(this.socket, target, method, packet, buffer);
    }
    stop() {
        if (this.socket != null)
            this.socket.close();
    }
    messageParser(socket, user, message, arg) {
        let target;
        let method;
        let packet;
        let data;
        try {
            [target, method] = message;
            packet = message.readInt32LE(2);
            data = message.slice(8);
        } catch (e) {
            this.emit(WsGateway.ERROR, e, socket, user);
            return;
        }
        const handler = this.handlers[target];
        if (!handler) {
            this.emit(WsGateway.MESSAGE, user, target, method, packet, data);
            return;
        }
        var self = this;
        handler(user, method, packet, data, function (t, m, p, d) {
            try {
                socket.send(Buffer.concat([self.getHeader(t, m, p), d]), { binary: true, mask: true }, function (error) {
                    if (error != null)
                        self.emit(WsGateway.ERROR, error, socket);
                });
            } catch (e) {
                self.emit(WsGateway.ERROR, e, socket, user);
            }
        });
    }
    getHeader(t, m, p) {
        const buffer = Buffer.allocUnsafe(8);
        buffer[0] = t;
        buffer[1] = m;
        buffer.writeInt32LE(p != null ? p : 0, 2);
        return buffer;
    }
}
module.exports = WsGateway;<commit_msg>Fix message read<commit_after>"use strict";
var WebSocket = require("ws");
var EventEmitter = require("events");

/**
 * Small helper in creating gateways to communicate between client and server.
 */
class WsGateway extends EventEmitter {
    static get ERROR() {
        return "error";
    }
    static get CLOSE() {
        return "close";
    }
    static get START() {
        return "start";
    }
    static get CONNECT() {
        return "connect";
    }
    static get MESSAGE() {
        return "message";
    }
    /**
     *
     * @param opt : Options
     * @param basicAuth : Basic Auth by origin
     * @param onConnectAuth : Extend Auth by cookie
     */
    constructor(opt, basicAuth, extendAuth, headers) {
        super();
        this.ip = opt.ip;//for client
        this.origin = opt.origin;
        this.port = opt.port;
        this.hashKey = opt.hash != null ? opt.hash : opt.hashKey != null ? opt.hashKey : "hash=";
        this.handlers = {};
        this.socket = null;//    -  websocket
        var self = this;
        if (this.ip == null) {//server
            this.basicAuth = basicAuth != null ? basicAuth : function (info, done) {
                var origin;
                try {
                    origin = info.req.headers.origin;
                } catch (e) {
                    return done(false);
                }
                if (origin !== self.origin)
                    return done(false);
                return done(true);
            }
            this.extendAuth = extendAuth != null ? extendAuth : function (gw, cb) {
                var hash;
                try {
                    hash = gw.upgradeReq.headers["sec-websocket-protocol"];
                } catch (e) {
                    cb(e);
                    return;
                }
                if (hash == null) {
                    cb("Hash not find");
                    return;
                }
                cb(null, {});
            };
            return;
        }
        //is client - use extendAuth as message reader
        this.extendAuth = extendAuth != null ? extendAuth : function (message, arg) {
            self.messageParser(self.socket,self, self.socket, message, arg);
        };
        this.basicAuth = basicAuth != null ? basicAuth : function () {
            self.socket.on("message", self.extendAuth);
        };
        this.headers = headers;
    }
    addHandler(code, container) {
        container.Code = code;
        this.handlers[code] = container.RequestHandler;
    }
    /**
     * Server start
     */
    start() {
        this.socket = new WebSocket.Server({ port: this.port, verifyClient: this.basicAuth });
        var self = this;
        this.socket.on("connection",
            function (ws) {
                self.extendAuth(ws, function (error, user) {
                    if (error)
                        return;
                    ws.on("message", function (msg, arg) {
                        self.messageParser(ws, user, msg, arg);
                    });
                    ws.on("close", function (c, m) {
                        self.emit(WsGateway.CLOSE, c, m, user);
                    });
                    ws.on("error", function (e) {
                        self.emit(WsGateway.ERROR, e, ws, user);
                    });
                    self.emit(WsGateway.CONNECT, ws, user);
                });

            });
        this.emit(WsGateway.START, this);
    }
    /**
     * Client connect
     */
    connect() {
        var self = this;
        var op = { "origin": this.origin };
        if (this.headers != null)
            op.headers = this.headers;
        this.socket = new WebSocket(`ws:${this.ip}:${this.port}`, this.hashKey, op);
        this.socket.on("open", function (a1, a2, a3) {
            self.emit(WsGateway.CONNECT, self);
            self.basicAuth();
        });
    }
    sendTo(socket, target, method, packet, buffer) {
        if (socket == null || socket.readyState !== 1/*WebSocket.OPEN*/) return;
        const self = this;
        if (buffer == null)
            buffer = Buffer.allocUnsafe(0);
        try {
            const header = this.getHeader(target, method, packet);
            const buff = Buffer.concat([header, buffer]);
            socket.send(buff, { binary: true, mask: true }, function (error) {
                if (error != null)
                    self.emit(WsGateway.ERROR, error, socket);
            });
        } catch (e) {
            this.emit(WsGateway.ERROR, e, socket);
        }
    }
    send(target, method, packet, buffer) {
        this.sendTo(this.socket, target, method, packet, buffer);
    }
    stop() {
        if (this.socket != null)
            this.socket.close();
    }
    messageParser(socket, user, message, arg) {
        let target;
        let method;
        let packet;
        let data;
        try {
            target = message[0];
            method = message[1];
            packet = message.readInt32LE(2);
            data = message.slice(8);
        } catch (e) {
            this.emit(WsGateway.ERROR, e, socket, user);
            return;
        }
        const handler = this.handlers[target];
        if (!handler) {
            this.emit(WsGateway.MESSAGE, user, target, method, packet, data);
            return;
        }
        var self = this;
        handler(user, method, packet, data, function (t, m, p, d) {
            try {
                socket.send(Buffer.concat([self.getHeader(t, m, p), d]), { binary: true, mask: true }, function (error) {
                    if (error != null)
                        self.emit(WsGateway.ERROR, error, socket);
                });
            } catch (e) {
                self.emit(WsGateway.ERROR, e, socket, user);
            }
        });
    }
    getHeader(t, m, p) {
        const buffer = Buffer.allocUnsafe(8);
        buffer[0] = t;
        buffer[1] = m;
        buffer.writeInt32LE(p != null ? p : 0, 2);
        return buffer;
    }
}
module.exports = WsGateway;<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('fs');
var stylus = require('stylus');
var clone = require('clone');

exports.name = 'stylus';
exports.inputFormats = ['styl', 'stylus'];
exports.outputFormat = 'css';

/**
 * Retrieves a Stylus renderer from the given options.
 */
function getRenderer(str, options, locals) {
  var renderer = stylus(str);

  // Special handling for stylus js api functions
  // given { define: { foo: 'bar', baz: 'quux' } }
  // runs renderer.define('foo', 'bar').define('baz', 'quux')

  var allowed = ['set', 'include', 'import', 'define', 'use'];
  var special = {}
  var normal = clone(options);
  for (var v in options) {
    if (allowed.indexOf(v) > -1) {
      special[v] = options[v];
      delete normal[v];
    }
  }

  // special options through their function names
  for (var k in special) {
    for (var v in special[k]) {
      renderer[k](v, special[k][v]);
    }
  }

  // normal options through set()
  for (var k in normal) {
    renderer.set(k, normal[k]);
  }

  // Register locals as defines.
  for (var key in locals || {}) {
    renderer.define(key, locals[key]);
  }
  return renderer;
}

exports.render = function (str, options, locals) {
  var result;
  getRenderer(str, options, locals).render(function (err, res) {
    if (err) throw err;
    // todo: how do we know what the dependencies are?
    result = res;
  });
  if (!result) {
    throw new Error('stylus compilation could not complete synchronously.');
  }
  return result;
};

exports.renderFile = function (filename, options, locals) {
  options = options || {};
  options.filename = path.resolve(filename);
  var str = fs.readFileSync(filename, 'utf8');
  return exports.render(str, options, locals);
};

exports.renderAsync = function (str, options, locals) {
  return new Promise(function (fulfill, reject) {
    getRenderer(str, options, locals).render(function (err, res) {
      if (err) {
        reject(err);
      }
      else {
        fulfill(res)
      }
    });
  });
};

exports.renderFileAsync = function (filename, options, locals) {
  options = options || {};
  options.filename = path.resolve(filename);
  var str = fs.readFileSync(filename, 'utf8');
  return exports.renderAsync(str, options, locals);
};
<commit_msg>Fix Node 0.10 support<commit_after>'use strict';

var path = require('path');
var fs = require('fs');
var stylus = require('stylus');
var clone = require('clone');
var Promise = require('promise');

exports.name = 'stylus';
exports.inputFormats = ['styl', 'stylus'];
exports.outputFormat = 'css';

/**
 * Retrieves a Stylus renderer from the given options.
 */
function getRenderer(str, options, locals) {
  var renderer = stylus(str);

  // Special handling for stylus js api functions
  // given { define: { foo: 'bar', baz: 'quux' } }
  // runs renderer.define('foo', 'bar').define('baz', 'quux')

  var allowed = ['set', 'include', 'import', 'define', 'use'];
  var special = {}
  var normal = clone(options);
  for (var v in options) {
    if (allowed.indexOf(v) > -1) {
      special[v] = options[v];
      delete normal[v];
    }
  }

  // special options through their function names
  for (var k in special) {
    for (var v in special[k]) {
      renderer[k](v, special[k][v]);
    }
  }

  // normal options through set()
  for (var k in normal) {
    renderer.set(k, normal[k]);
  }

  // Register locals as defines.
  for (var key in locals || {}) {
    renderer.define(key, locals[key]);
  }
  return renderer;
}

exports.render = function (str, options, locals) {
  var result;
  getRenderer(str, options, locals).render(function (err, res) {
    if (err) throw err;
    // todo: how do we know what the dependencies are?
    result = res;
  });
  if (!result) {
    throw new Error('stylus compilation could not complete synchronously.');
  }
  return result;
};

exports.renderFile = function (filename, options, locals) {
  options = options || {};
  options.filename = path.resolve(filename);
  var str = fs.readFileSync(filename, 'utf8');
  return exports.render(str, options, locals);
};

exports.renderAsync = function (str, options, locals) {
  return new Promise(function (fulfill, reject) {
    getRenderer(str, options, locals).render(function (err, res) {
      if (err) {
        reject(err);
      }
      else {
        fulfill(res)
      }
    });
  });
};

exports.renderFileAsync = function (filename, options, locals) {
  options = options || {};
  options.filename = path.resolve(filename);
  var str = fs.readFileSync(filename, 'utf8');
  return exports.renderAsync(str, options, locals);
};
<|endoftext|>


<commit_before>var dc = require('dependency-check');
var format = require('util').format;
var debug = require('debug')('mongodb-js-precommit');
var glob = require('glob');
var CLIEngine = require('eslint').CLIEngine;
var jsfmt = require('jsfmt');
var async = require('async');
var fs = require('fs');

function check(mode, done) {
  var pkg = require(process.cwd() + '/package.json');
  pkg['dependency-check'] = pkg['dependency-check'] || {
      entries: [],
      ignore: []
    };
  pkg.devDependencies = pkg.devDependencies || {};

  var opts = {
    path: process.cwd() + '/package.json',
    entries: pkg['dependency-check'].entries,
    ignore: pkg['dependency-check'].ignore
  };

  /**
   * Sane defaults for common devDependencies not used via an `entry` script.
   */
  opts.ignore.push.apply(opts.ignore, [
    'eslint-config-mongodb-js',
    'mongodb-js-precommit'
  ]);

  var test = pkg.scripts.test;
  /**
   * If mocha already a dependency and we're using it for `test`,
   * ignore it so it doesn't show up as an extra dependency.
   */
  if (test && test.indexOf('mocha') > -1 && pkg.devDependencies.mocha) {
    opts.ignore.push('mocha');
  }

  function filterIgnored(results) {
    return results.filter(function(name) {
      return opts.ignore.indexOf(name) === -1;
    });
  }

  dc(opts, function(err, data) {
    if (err) return done(err);
    var pkg = data.package;
    var deps = data.used;
    var results;
    var errMsg;
    var corrector;

    if (mode === 'extra') {
      // Are all dependencies in package.json are used in the code?
      results = filterIgnored(dc.extra(pkg, deps, {
        excludeDev: true
      }));
      errMsg = 'Modules in package.json not used in code';
      corrector = 'npm uninstall --save ' + results.join(' ') + ';';
    } else {
      // Are we missing any dependencies in package.json?
      results = filterIgnored(dc.missing(pkg, deps));
      errMsg = 'Dependencies not listed in package.json';
      corrector = 'npm install --save ' + results.join(' ') + ';';
    }

    if (results.length === 0) {
      return done();
    }
    console.error('Error: ' + errMsg + '. To fix this, run:\n\n    ' + corrector + '\n');
    return done(new Error(errMsg));
  });
}

var lint = function(opts, done) {
  var cli = new CLIEngine({
    useEslintrc: true
  });

  debug('Getting paths to lint...');
  debug('Linting files', opts.files);
  var report = cli.executeOnFiles(opts.files);
  var formatter = cli.getFormatter();
  console.log(formatter(report.results));

  if (report.errorCount > 0) {
    return done(new Error(format('Please fix the %d error(s) above and try again.',
      report.errorCount)));
  }
  done();
};

var fmt = function(opts, done) {
  var config = jsfmt.getConfig();

  function fmt(src, cb) {
    fs.readFile(src, function(err, buf) {
      if (err) return cb(err);
      try {
        var formatted = jsfmt.format(buf.toString('utf-8'), config);
        fs.writeFile(src, formatted, cb);
      } catch (e) {
        return cb(e);
      }
    });
  }
  async.parallel(opts.files.map(function(file) {
    return fmt.bind(null, file);
  }), done);
};

module.exports = function(done) {
  var opts = {};
  glob('**/*.js', {
    ignore: ['node_modules/**']
  }, function(err, files) {
    if (err) return done(err);

    opts.files = files;

    async.series({
      'missing dependencies': check.bind(null, 'missing'),
      'extra dependencies': check.bind(null, 'extra'),
      fmt: fmt.bind(null, opts),
      lint: lint.bind(null, opts)
    }, done);
  });
};
<commit_msg>fix: handle ignore not set in package.json<commit_after>var dc = require('dependency-check');
var format = require('util').format;
var debug = require('debug')('mongodb-js-precommit');
var glob = require('glob');
var CLIEngine = require('eslint').CLIEngine;
var jsfmt = require('jsfmt');
var async = require('async');
var fs = require('fs');

function check(mode, done) {
  var pkg = require(process.cwd() + '/package.json');
  pkg['dependency-check'] = pkg['dependency-check'] || {
      entries: [],
      ignore: []
    };
  pkg.devDependencies = pkg.devDependencies || {};

  var opts = {
    path: process.cwd() + '/package.json',
    entries: pkg['dependency-check'].entries,
    ignore: pkg['dependency-check'].ignore
  };
  opts.ignore = opts.ignore || [];
  opts.entries = opts.entries || [];

  /**
   * Sane defaults for common devDependencies not used via an `entry` script.
   */
  opts.ignore.push.apply(opts.ignore, [
    'eslint-config-mongodb-js',
    'mongodb-js-precommit'
  ]);

  var test = pkg.scripts.test;
  /**
   * If mocha already a dependency and we're using it for `test`,
   * ignore it so it doesn't show up as an extra dependency.
   */
  if (test && test.indexOf('mocha') > -1 && pkg.devDependencies.mocha) {
    opts.ignore.push('mocha');
  }

  function filterIgnored(results) {
    return results.filter(function(name) {
      return opts.ignore.indexOf(name) === -1;
    });
  }

  dc(opts, function(err, data) {
    if (err) return done(err);
    var pkg = data.package;
    var deps = data.used;
    var results;
    var errMsg;
    var corrector;

    if (mode === 'extra') {
      // Are all dependencies in package.json are used in the code?
      results = filterIgnored(dc.extra(pkg, deps, {
        excludeDev: true
      }));
      errMsg = 'Modules in package.json not used in code';
      corrector = 'npm uninstall --save ' + results.join(' ') + ';';
    } else {
      // Are we missing any dependencies in package.json?
      results = filterIgnored(dc.missing(pkg, deps));
      errMsg = 'Dependencies not listed in package.json';
      corrector = 'npm install --save ' + results.join(' ') + ';';
    }

    if (results.length === 0) {
      return done();
    }
    console.error('Error: ' + errMsg + '. To fix this, run:\n\n    ' + corrector + '\n');
    return done(new Error(errMsg));
  });
}

var lint = function(opts, done) {
  var cli = new CLIEngine({
    useEslintrc: true
  });

  debug('Getting paths to lint...');
  debug('Linting files', opts.files);
  var report = cli.executeOnFiles(opts.files);
  var formatter = cli.getFormatter();
  console.log(formatter(report.results));

  if (report.errorCount > 0) {
    return done(new Error(format('Please fix the %d error(s) above and try again.',
      report.errorCount)));
  }
  done();
};

var fmt = function(opts, done) {
  var config = jsfmt.getConfig();

  function fmt(src, cb) {
    fs.readFile(src, function(err, buf) {
      if (err) return cb(err);
      try {
        var formatted = jsfmt.format(buf.toString('utf-8'), config);
        fs.writeFile(src, formatted, cb);
      } catch (e) {
        return cb(e);
      }
    });
  }
  async.parallel(opts.files.map(function(file) {
    return fmt.bind(null, file);
  }), done);
};

module.exports = function(done) {
  var opts = {};
  glob('**/*.js', {
    ignore: ['node_modules/**']
  }, function(err, files) {
    if (err) return done(err);

    opts.files = files;

    async.series({
      'missing dependencies': check.bind(null, 'missing'),
      'extra dependencies': check.bind(null, 'extra'),
      fmt: fmt.bind(null, opts),
      lint: lint.bind(null, opts)
    }, done);
  });
};
<|endoftext|>


<commit_before>// INITIALIZE AND CENTER MAP
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: 63.986807, lng: -22.627967},
    //mapTypeId: google.maps.MapTypeId.HYBRID,
    styles: [
            {elementType: 'geometry', stylers: [{color: '#242f3e'}]},
            {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
            {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
            {
              featureType: 'administrative.locality',
              elementType: 'labels.text.fill',
              stylers: [{color: '#d59563'}]
            },
            {
              featureType: 'poi',
              elementType: 'labels.text.fill',
              stylers: [{color: '#d59563'}]
            },
            {
              featureType: 'poi.park',
              elementType: 'geometry',
              stylers: [{color: '#263c3f'}]
            },
            {
              featureType: 'poi.park',
              elementType: 'labels.text.fill',
              stylers: [{color: '#6b9a76'}]
            },
            {
              featureType: 'road',
              elementType: 'geometry',
              stylers: [{color: '#38414e'}]
            },
            {
              featureType: 'road',
              elementType: 'geometry.stroke',
              stylers: [{color: '#212a37'}]
            },
            {
              featureType: 'road',
              elementType: 'labels.text.fill',
              stylers: [{color: '#9ca5b3'}]
            },
            {
              featureType: 'road.highway',
              elementType: 'geometry',
              stylers: [{color: '#746855'}]
            },
            {
              featureType: 'road.highway',
              elementType: 'geometry.stroke',
              stylers: [{color: '#1f2835'}]
            },
            {
              featureType: 'road.highway',
              elementType: 'labels.text.fill',
              stylers: [{color: '#f3d19c'}]
            },
            {
              featureType: 'transit',
              elementType: 'geometry',
              stylers: [{color: '#2f3948'}]
            },
            {
              featureType: 'transit.station',
              elementType: 'labels.text.fill',
              stylers: [{color: '#d59563'}]
            },
            {
              featureType: 'water',
              elementType: 'geometry',
              stylers: [{color: '#17263c'}]
            },
            {
              featureType: 'water',
              elementType: 'labels.text.fill',
              stylers: [{color: '#515c6d'}]
            },
            {
              featureType: 'water',
              elementType: 'labels.text.stroke',
              stylers: [{color: '#17263c'}]
            }
          ]
  });

  var geocoder = new google.maps.Geocoder();

  $(document).on("click", "#flight-data tr", function(e) {
    geocodeAddress(this.id, geocoder, map);
  });
}

// Get the address location for the airport and mark it on the map
function geocodeAddress(destination, geocoder, resultsMap) {
  var address = destination;
  var localAirport = {lat: 63.986807, lng: -22.627967};

  resultsMap.setCenter(localAirport);

  var markerLocalAirport = new google.maps.Marker({
    map: resultsMap,
    position: localAirport
  });

  geocoder.geocode({'address': address}, function(results, status) {
    if (status === 'OK') {
      var destinationAirport = results[0].geometry.location;

      // Get weather by city
        $.ajax({
          'url': 'http://api.openweathermap.org/data/2.5/weather?q=' + address + '&APPID=fc1985651a1e35c2012d94faa3c8f43e',
          'type': 'GET',
          'dataType': 'json',
          success: function(response) {
            //console.log(address + ': ' + response.main.temp);
            console.log(address + ': ' + response.main.temp);
          }
        });

      var contentString = address;

      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });

      var markerDestinationAirport = new google.maps.Marker({
        map: resultsMap,
        position: destinationAirport,
        title: address
      });

      markerDestinationAirport.addListener('click', function() {
        infowindow.open(resultsMap, markerDestinationAirport);
      });

      var flightPlanCoordinates = [
        localAirport,
        destinationAirport
      ];
      var flightPath = new google.maps.Polyline({
        path: flightPlanCoordinates,
        geodesic: true,
        strokeColor: 'white',
        strokeOpacity: 1.0,
        strokeWeight: 1
      });

      flightPath.setMap(resultsMap);

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

// POPULATE FLIGHT TABLE

$.ajax({
  'url': 'http://apis.is/flight',
  'type': 'GET',
  'dataType': 'json',
  'data': {'language': 'en', 'type': 'departures'},
  success: function(response) {
    console.log(response);
    SetTable(response);
  }
});

function SetTable(data) {
  var d = data.results;

  for (var i = 0; i < d.length; i++) {
  $(  '
' +
      '' + d[i].to + '	' +
      '' + d[i].airline + '	' +
      '' + d[i].date + '	' +
      '' + d[i].flightNumber + '	' +
      '' + d[i].plannedArrival + '	' +
      '' + d[i].realArrival + '	' +
      '
'
    ).insertAfter('#table-data');
  }
}<commit_msg>Simple modification of weather output<commit_after>// INITIALIZE AND CENTER MAP
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: 63.986807, lng: -22.627967},
    //mapTypeId: google.maps.MapTypeId.HYBRID,
    styles: [
            {elementType: 'geometry', stylers: [{color: '#242f3e'}]},
            {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
            {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
            {
              featureType: 'administrative.locality',
              elementType: 'labels.text.fill',
              stylers: [{color: '#d59563'}]
            },
            {
              featureType: 'poi',
              elementType: 'labels.text.fill',
              stylers: [{color: '#d59563'}]
            },
            {
              featureType: 'poi.park',
              elementType: 'geometry',
              stylers: [{color: '#263c3f'}]
            },
            {
              featureType: 'poi.park',
              elementType: 'labels.text.fill',
              stylers: [{color: '#6b9a76'}]
            },
            {
              featureType: 'road',
              elementType: 'geometry',
              stylers: [{color: '#38414e'}]
            },
            {
              featureType: 'road',
              elementType: 'geometry.stroke',
              stylers: [{color: '#212a37'}]
            },
            {
              featureType: 'road',
              elementType: 'labels.text.fill',
              stylers: [{color: '#9ca5b3'}]
            },
            {
              featureType: 'road.highway',
              elementType: 'geometry',
              stylers: [{color: '#746855'}]
            },
            {
              featureType: 'road.highway',
              elementType: 'geometry.stroke',
              stylers: [{color: '#1f2835'}]
            },
            {
              featureType: 'road.highway',
              elementType: 'labels.text.fill',
              stylers: [{color: '#f3d19c'}]
            },
            {
              featureType: 'transit',
              elementType: 'geometry',
              stylers: [{color: '#2f3948'}]
            },
            {
              featureType: 'transit.station',
              elementType: 'labels.text.fill',
              stylers: [{color: '#d59563'}]
            },
            {
              featureType: 'water',
              elementType: 'geometry',
              stylers: [{color: '#17263c'}]
            },
            {
              featureType: 'water',
              elementType: 'labels.text.fill',
              stylers: [{color: '#515c6d'}]
            },
            {
              featureType: 'water',
              elementType: 'labels.text.stroke',
              stylers: [{color: '#17263c'}]
            }
          ]
  });

  var geocoder = new google.maps.Geocoder();

  $(document).on("click", "#flight-data tr", function(e) {
    geocodeAddress(this.id, geocoder, map);
  });
}

// Get the address location for the airport and mark it on the map
function geocodeAddress(destination, geocoder, resultsMap) {
  var address = destination;
  var localAirport = {lat: 63.986807, lng: -22.627967};

  resultsMap.setCenter(localAirport);

  var markerLocalAirport = new google.maps.Marker({
    map: resultsMap,
    position: localAirport
  });

function toCelsius(kelvin) {
	var celsius = kelvin - 273.15;

	return celsius;
}

  geocoder.geocode({'address': address}, function(results, status) {
    if (status === 'OK') {
      var destinationAirport = results[0].geometry.location;

      // Get weather by city
        $.ajax({
          'url': 'http://api.openweathermap.org/data/2.5/weather?q=' + address + '&APPID=fc1985651a1e35c2012d94faa3c8f43e',
          'type': 'GET',
          'dataType': 'json',
          success: function(response) {
            //console.log(address + ': ' + response.main.temp);
            var celsius = toCelsius(response.main.temp);
            alert(	address + '\nTemperature: ' + celsius +
            		' °C \nWind Speed: ' + response.wind.speed + ' km/h');
          }
        });

      var contentString = address;

      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });

      var markerDestinationAirport = new google.maps.Marker({
        map: resultsMap,
        position: destinationAirport,
        title: address
      });

      markerDestinationAirport.addListener('click', function() {
        infowindow.open(resultsMap, markerDestinationAirport);
      });

      var flightPlanCoordinates = [
        localAirport,
        destinationAirport
      ];
      var flightPath = new google.maps.Polyline({
        path: flightPlanCoordinates,
        geodesic: true,
        strokeColor: 'white',
        strokeOpacity: 1.0,
        strokeWeight: 1
      });

      flightPath.setMap(resultsMap);

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

// POPULATE FLIGHT TABLE

$.ajax({
  'url': 'http://apis.is/flight',
  'type': 'GET',
  'dataType': 'json',
  'data': {'language': 'en', 'type': 'departures'},
  success: function(response) {
    console.log(response);
    SetTable(response);
  }
});

function SetTable(data) {
  var d = data.results;

  for (var i = 0; i < d.length; i++) {
  $(  '
' +
      '' + d[i].to + '	' +
      '' + d[i].airline + '	' +
      '' + d[i].date + '	' +
      '' + d[i].flightNumber + '	' +
      '' + d[i].plannedArrival + '	' +
      '' + d[i].realArrival + '	' +
      '
'
    ).insertAfter('#table-data');
  }
}<|endoftext|>


<commit_before>/**
 * @function ua
 * Returns an object representing the user agent including data such as browser, device and platform
 * @param {string} _ua - the raw user agent string to be converted
 * @param {string} obj - (optional) object to be merged to the output result
 * @returns {object} object representing your user agent
 */
module.exports = exports = function (_ua, obj) {
  if (typeof _ua === 'string') {
    _ua = _ua.toLowerCase()
  } else {
    _ua = ''
  }
  if (obj === true) {
    obj = exports
  } else if (!obj) {
    obj = {}
  }
  // _ua = 'webos; linux - large screen'
  var _ff = 'firefox'
  var _android = 'android'
  var _mobile = '.+mobile'
  var _webkit = 'webkit'
  var _ps = 'playstation'
  var _xbox = 'xbox'
  var _linux = 'linux'
  var _castDetect = 'crkey'
  var _chromecast = 'chromecast'
  var _tablet = 'tablet'
  var _windows = 'windows'
  var _phone = 'phone'
  var _firetv = 'firetv'
  var _sticktv = 'sticktv'
  var _rikstv = 'rikstv'
  var _facebook = 'facebook'

  /**
   * browser detection
   */
  test.call(obj, _ua,
    function (query, arr) {
      obj.browser = arr[ 2 ] || query
      var _v = _ua.match(
        new RegExp('((([\\/ ]version|' + arr[ 0 ] + '(?!.+version))[\/ ])| rv:)([0-9]{1,4}\\.[0-9]{0,2})')
      )
      obj.version = _v ? Number(_v[ 4 ]) : 0
      obj.prefix = arr[ 1 ]
      // TODO: add prefix for opera v>12.15;
      // TODO: windows check for ie 11 may be too general;
    },
    [ true, _webkit ],
    [ '\\(windows', 'ms', 'ie' ],
    [ 'safari', _webkit ],
    [ _ff, 'Moz' ],
    [ 'opera', 'O' ],
    [ 'msie', 'ms', 'ie' ],
    [ _facebook, _facebook ],
    [ 'chrome|crios\/', _webkit, 'chrome' ]
  )

  /**
   * platform detection
   */
  test.call(obj, _ua, 'platform',
    [ true, _windows ],
    [ _linux, _linux ],
    [ 'lg.{0,3}netcast', 'lg' ], // TODO:propably need to add more!
    [ _ff + _mobile, _ff ],
    [ 'mac os x', 'mac' ], [ 'iphone|ipod|ipad', 'ios' ],
    [ _xbox, _xbox ],
    [ _ps, _ps ],
    [ _android, _android ],
    [ _windows, _windows ],
    [ _castDetect, _chromecast ],
    [ 'smart-tv;|;samsung;smarttv', 'samsung' ], // SmartTV2013
    [ _rikstv, _rikstv ]
  )

  /**
   * device detection
   */
  test.call(obj, _ua, 'device',
    [ true, 'desktop' ],
    [ _windows + '.+touch|ipad|' + _android, _tablet ],
    [
      'phone|iphone|(' +
      _android + _mobile + ')|(' + _ff + _mobile +
      ')|' + _windows + ' phone|iemobile', _phone
    ],
    [ _xbox + '|' + _ps, 'console' ],
    [ 'tv|smarttv|googletv|appletv|hbbtv|pov_tv|netcast.tv|webos.+large', 'tv' ],
    [ _castDetect, _chromecast ],
    [ 'tablet|amazon-fireos|nexus (?=[^1-6])\\d{1,2}', _tablet ],
    [ 'aftb|afts', _firetv ],
    [ 'aftm', _sticktv ],
    [ _rikstv, _rikstv ]
  )

  /**
   * wrapped webview native app detection
   */
  test.call(obj, _ua, 'webview',
    [ true, false ],
    [ 'vigour-wrapper', 'vigour' ],
    [ 'crosswalk', 'crosswalk' ],
    [ 'cordova', 'cordova' ]
  )

  return obj

  /**
   * test
   * search for regexps in the userAgent
   * fn is a on succes callback
   * check tests in https://github.com/faisalman/ua-parser-js to test for userAgents
   * @method
   */
  function test (_ua, fn) {
    for (var tests = arguments, i = tests.length - 1, query = tests[i][0]; query !== true && !new RegExp(query).test(_ua) && i > 0; query = tests[--i][0]); //eslint-disable-line
    // this for has no body
    if (fn.slice || fn.call(this, query, tests[i])) {
      this[fn] = tests[i][1]
    }
  }
}
<commit_msg>put wrapper in case of vigour-wrapper webview<commit_after>/**
 * @function ua
 * Returns an object representing the user agent including data such as browser, device and platform
 * @param {string} _ua - the raw user agent string to be converted
 * @param {string} obj - (optional) object to be merged to the output result
 * @returns {object} object representing your user agent
 */
module.exports = exports = function (_ua, obj) {
  if (typeof _ua === 'string') {
    _ua = _ua.toLowerCase()
  } else {
    _ua = ''
  }
  if (obj === true) {
    obj = exports
  } else if (!obj) {
    obj = {}
  }
  // _ua = 'webos; linux - large screen'
  var _ff = 'firefox'
  var _android = 'android'
  var _mobile = '.+mobile'
  var _webkit = 'webkit'
  var _ps = 'playstation'
  var _xbox = 'xbox'
  var _linux = 'linux'
  var _castDetect = 'crkey'
  var _chromecast = 'chromecast'
  var _tablet = 'tablet'
  var _windows = 'windows'
  var _phone = 'phone'
  var _firetv = 'firetv'
  var _sticktv = 'sticktv'
  var _rikstv = 'rikstv'
  var _facebook = 'facebook'

  /**
   * browser detection
   */
  test.call(obj, _ua,
    function (query, arr) {
      obj.browser = arr[ 2 ] || query
      var _v = _ua.match(
        new RegExp('((([\\/ ]version|' + arr[ 0 ] + '(?!.+version))[\/ ])| rv:)([0-9]{1,4}\\.[0-9]{0,2})')
      )
      obj.version = _v ? Number(_v[ 4 ]) : 0
      obj.prefix = arr[ 1 ]
      // TODO: add prefix for opera v>12.15;
      // TODO: windows check for ie 11 may be too general;
    },
    [ true, _webkit ],
    [ '\\(windows', 'ms', 'ie' ],
    [ 'safari', _webkit ],
    [ _ff, 'Moz' ],
    [ 'opera', 'O' ],
    [ 'msie', 'ms', 'ie' ],
    [ _facebook, _facebook ],
    [ 'chrome|crios\/', _webkit, 'chrome' ]
  )

  /**
   * platform detection
   */
  test.call(obj, _ua, 'platform',
    [ true, _windows ],
    [ _linux, _linux ],
    [ 'lg.{0,3}netcast', 'lg' ], // TODO:propably need to add more!
    [ _ff + _mobile, _ff ],
    [ 'mac os x', 'mac' ], [ 'iphone|ipod|ipad', 'ios' ],
    [ _xbox, _xbox ],
    [ _ps, _ps ],
    [ _android, _android ],
    [ _windows, _windows ],
    [ _castDetect, _chromecast ],
    [ 'smart-tv;|;samsung;smarttv', 'samsung' ], // SmartTV2013
    [ _rikstv, _rikstv ]
  )

  /**
   * device detection
   */
  test.call(obj, _ua, 'device',
    [ true, 'desktop' ],
    [ _windows + '.+touch|ipad|' + _android, _tablet ],
    [
      'phone|iphone|(' +
      _android + _mobile + ')|(' + _ff + _mobile +
      ')|' + _windows + ' phone|iemobile', _phone
    ],
    [ _xbox + '|' + _ps, 'console' ],
    [ 'tv|smarttv|googletv|appletv|hbbtv|pov_tv|netcast.tv|webos.+large', 'tv' ],
    [ _castDetect, _chromecast ],
    [ 'tablet|amazon-fireos|nexus (?=[^1-6])\\d{1,2}', _tablet ],
    [ 'aftb|afts', _firetv ],
    [ 'aftm', _sticktv ],
    [ _rikstv, _rikstv ]
  )

  /**
   * wrapped webview native app detection
   */
  test.call(obj, _ua, 'webview',
    [ true, false ],
    [ 'crosswalk', 'crosswalk' ],
    [ 'vigour-wrapper', 'wrapper' ],
    [ 'cordova', 'cordova' ]
  )

  return obj

  /**
   * test
   * search for regexps in the userAgent
   * fn is a on succes callback
   * check tests in https://github.com/faisalman/ua-parser-js to test for userAgents
   * @method
   */
  function test (_ua, fn) {
    for (var tests = arguments, i = tests.length - 1, query = tests[i][0]; query !== true && !new RegExp(query).test(_ua) && i > 0; query = tests[--i][0]); //eslint-disable-line
    // this for has no body
    if (fn.slice || fn.call(this, query, tests[i])) {
      this[fn] = tests[i][1]
    }
  }
}
<|endoftext|>


<commit_before>'use strict'

const stream = require('stream')
const vfs = require('vinyl-fs')
const postcss = require('postcss')
const url = require('postcss-custom-url')
const File = require('vinyl')
const combine = require('stream-combiner2')
const buffer = require('vinyl-buffer')
const Depsify = require('depsify')

function bundler(b, opts) {
  if (typeof opts === 'function' || Array.isArray(opts)) {
    return b.plugin(opts)
  }

  opts = opts || {}
  if (typeof opts === 'string') {
    opts = { groups: { output: opts } }
  }

  let urlProcessor = postcss(url)
  opts.pack = function (options) {
    let pipeline = b.pack()
    pipeline.pop()
    pipeline.push(
      through(function (row, _, next) {
        urlProcessor.process(row.source, {
          from: row.file,
          to: options.to,
        }).then(function (result) {
          next(null, result.css)
        })
      })
    )
    return pipeline
  }
  b.plugin(require('common-bundle'), opts)
}

function through(write, end) {
  return stream.Transform({
    objectMode: true,
    transform: write,
    flush: end,
  })
}

function watcher(b, wopts) {
  b.plugin(require('watchify2'), wopts)
  let close = b.close
  b.close = function () {
    close()
    b.emit('close')
  }
  b.start = function () {
    b.emit('bundle-stream', b.bundle())
  }
  b.on('update', b.start)
}

function bundle(b, opts) {
  b.plugin(bundler, opts)

  return through(
    function (file, enc, next) {
      b.add(file.path)
      next()
    },
    function (next) {
      b.bundle()
        .on('data', data => this.push(data))
        .on('end', next)
    }
  )
}

function watch(b, opts, wopts) {
  b.plugin(bundler, opts)
  b.plugin(watcher, wopts)

  return through(
    function (file, enc, next) {
      b.add(file.path)
      next()
    },
    function (next) {
      b.on('bundle-stream', s => this.emit('bundle', s))
      b.once('close', next)
      b.start()
    }
  )
}

function src(pattern, opts) {
  opts = opts || {}
  opts.read = false
  return vfs.src(pattern, opts)
}

function dest(outFolder, outOpts, urlOpts) {
  let files = []
  let emptyFiles = []
  let urlProcessor = postcss(url([
    [ url.util.inline, urlOpts ],
    [ url.util.copy, urlOpts ],
  ]))
  return combine.obj(
    buffer(),
    through(function (file, _, next) {
      files.push(file)
      let f = new File({
        cwd: file.cwd,
        base: file.base,
        path: file.path,
        contents: null,
      })
      emptyFiles.push(f)
      next(null, f)
    }),
    vfs.dest(outFolder, outOpts),
    through(function (file, _, next) {
      let i = emptyFiles.indexOf(file)
      let writePath = file.path
      file = files[i]
      urlProcessor.process(
        file.contents.toString('utf8'),
        { from: file.path, to: writePath }
      ).then(function (result) {
        file.contents = Buffer(result.css)
        next(null, file)
      }, err => this.emit('error', err))
    }),
    vfs.dest(outFolder, outOpts)
  )
}

function create(opts) {
  opts = opts || {}
  let b = new Depsify(Object.assign({ atRuleName: 'external' }, opts))
  if (opts.postcss !== false) {
    b.plugin(require('reduce-css-postcss'), {
      processorFilter: function (pipeline) {
        pipeline.get('postcss-simple-import').push({
          resolve: b._options.resolve,
        })

        if (typeof opts.postcss === 'function') {
          return opts.postcss(pipeline)
        }

        pipeline.push.apply(
          pipeline, [].concat(opts.postcss).filter(Boolean)
        )
      },
    })
  }
  return b
}

module.exports = {
  bundler,
  watcher,
  bundle,
  watch,
  dest,
  src,
  create,
}

<commit_msg>Fix: remove null file before dest<commit_after>'use strict'

const stream = require('stream')
const vfs = require('vinyl-fs')
const postcss = require('postcss')
const url = require('postcss-custom-url')
const File = require('vinyl')
const combine = require('stream-combiner2')
const buffer = require('vinyl-buffer')
const Depsify = require('depsify')

function bundler(b, opts) {
  if (typeof opts === 'function' || Array.isArray(opts)) {
    return b.plugin(opts)
  }

  opts = opts || {}
  if (typeof opts === 'string') {
    opts = { groups: { output: opts } }
  }

  let urlProcessor = postcss(url)
  opts.pack = function (options) {
    let pipeline = b.pack()
    pipeline.pop()
    pipeline.push(
      through(function (row, _, next) {
        urlProcessor.process(row.source, {
          from: row.file,
          to: options.to,
        }).then(function (result) {
          next(null, result.css)
        })
      })
    )
    return pipeline
  }
  b.plugin(require('common-bundle'), opts)
}

function through(write, end) {
  return stream.Transform({
    objectMode: true,
    transform: write,
    flush: end,
  })
}

function watcher(b, wopts) {
  b.plugin(require('watchify2'), wopts)
  let close = b.close
  b.close = function () {
    close()
    b.emit('close')
  }
  b.start = function () {
    b.emit('bundle-stream', b.bundle())
  }
  b.on('update', b.start)
}

function bundle(b, opts) {
  b.plugin(bundler, opts)

  return through(
    function (file, enc, next) {
      b.add(file.path)
      next()
    },
    function (next) {
      b.bundle()
        .on('data', data => this.push(data))
        .on('end', next)
    }
  )
}

function watch(b, opts, wopts) {
  b.plugin(bundler, opts)
  b.plugin(watcher, wopts)

  return through(
    function (file, enc, next) {
      b.add(file.path)
      next()
    },
    function (next) {
      b.on('bundle-stream', s => this.emit('bundle', s))
      b.once('close', next)
      b.start()
    }
  )
}

function src(pattern, opts) {
  opts = opts || {}
  opts.read = false
  return vfs.src(pattern, opts)
}

function dest(outFolder, outOpts, urlOpts) {
  let files = []
  let emptyFiles = []
  let urlProcessor = postcss(url([
    [ url.util.inline, urlOpts ],
    [ url.util.copy, urlOpts ],
  ]))
  return combine.obj(
    buffer(),
    through(function (file, _, next) {
      if (file.isNull()) return next()
      files.push(file)
      let f = new File({
        cwd: file.cwd,
        base: file.base,
        path: file.path,
        contents: null,
      })
      emptyFiles.push(f)
      next(null, f)
    }),
    vfs.dest(outFolder, outOpts),
    through(function (file, _, next) {
      let i = emptyFiles.indexOf(file)
      let writePath = file.path
      file = files[i]
      urlProcessor.process(
        file.contents.toString('utf8'),
        { from: file.path, to: writePath }
      ).then(function (result) {
        file.contents = Buffer(result.css)
        next(null, file)
      }, err => this.emit('error', err))
    }),
    vfs.dest(outFolder, outOpts)
  )
}

function create(opts) {
  opts = opts || {}
  let b = new Depsify(Object.assign({ atRuleName: 'external' }, opts))
  if (opts.postcss !== false) {
    b.plugin(require('reduce-css-postcss'), {
      processorFilter: function (pipeline) {
        pipeline.get('postcss-simple-import').push({
          resolve: b._options.resolve,
        })

        if (typeof opts.postcss === 'function') {
          return opts.postcss(pipeline)
        }

        pipeline.push.apply(
          pipeline, [].concat(opts.postcss).filter(Boolean)
        )
      },
    })
  }
  return b
}

module.exports = {
  bundler,
  watcher,
  bundle,
  watch,
  dest,
  src,
  create,
}

<|endoftext|>


<commit_before>'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');

module.exports = () => {
	if (process.platform !== 'linux') {
		return Promise.reject(new Error('Only Linux systems are supported'));
	}

	return execa('lsb_release', ['-a', '--short']).then(res => {
		const stdout = res.stdout.split('\n');

		return {
			os: stdout[0],
			name: stdout[1],
			release: stdout[2],
			code: stdout[3]
		};
	}).catch(() => {
		return pify(getos)(res => {
			return {
				os: res.dist,
				name: `${res.dist} ${res.release}`,
				release: res.release,
				code: res.codename
			};
		});
	});
};
<commit_msg>Fix returned promise upon errors<commit_after>'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');

module.exports = () => {
	if (process.platform !== 'linux') {
		return Promise.reject(new Error('Only Linux systems are supported'));
	}

	return execa('lsb_release', ['-a', '--short']).then(res => {
		const stdout = res.stdout.split('\n');

		return {
			os: stdout[0],
			name: stdout[1],
			release: stdout[2],
			code: stdout[3]
		};
	}).catch(() => {
		return pify(getos).then(res => {
			return {
				os: res.dist,
				name: `${res.dist} ${res.release}`,
				release: res.release,
				code: res.codename
			};
		});
	});
};
<|endoftext|>


<commit_before>let express = require('express');
let fs = require('fs');

let app = express();
let images = __dirname;

app.use('/images/:im_name', (req, res, next) => {
  let extensions = ['.png', '.jpg'];
  extensions.map((extension, index) => {
    fs.exists( images + '/images/' + req.params.im_name + extension, (exists) => {
      if(exists) {
        req.url += extension;
        next();
      } else if (index + 1 == extensions.length && !res.headerSent) {
        next();
      }
    });
  });
});

app.use(express.static(images));

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
<commit_msg>corrected header to headers sent<commit_after>let express = require('express');
let fs = require('fs');

let app = express();
let images = __dirname;

app.use('/images/:im_name', (req, res, next) => {
  let extensions = ['.png', '.jpg'];
  extensions.map((extension, index) => {
    fs.exists( images + '/images/' + req.params.im_name + extension, (exists) => {
      if(exists) {
        req.url += extension;
        next();
      } else if (index + 1 == extensions.length && !res.headersSent) {
        next();
      }
    });
  });
});

app.use(express.static(images));

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
<|endoftext|>


<commit_before>var User = require('./src/user');
var Brain = require('./src/brain');
var Robot = require('./src/robot');
var Adapter = require('./src/adapter');
var Response = require('./src/response');
var listener = require('./src/listener');
var message = require('./src/message');

module.exports = {
  User: User,
  Brain: Brain,
  Robot: Robot,
  Adapter: Adapter,
  Response: Response,
  Listener: listener.Listener,
  TextListener: listener.TextListener,
  Message: message.Message,
  TextMessage: message.TextMessage,
  EnterMessage: message.EnterMessage,
  LeaveMessage: message.LeaveMessage,
  TopicMessage: message.TopicMessage,
  CatchAllMessage: message.CatchAllMessage
};

module.exports.loadBot = function(adapterName, brainName, enableHttpd, botName) {
  return new Robot(adapterName, brainName, enableHttpd, botName);
};
<commit_msg>Add another `loadBot` param<commit_after>var User = require('./src/user');
var Brain = require('./src/brain');
var Robot = require('./src/robot');
var Adapter = require('./src/adapter');
var Response = require('./src/response');
var listener = require('./src/listener');
var message = require('./src/message');

module.exports = {
  User: User,
  Brain: Brain,
  Robot: Robot,
  Adapter: Adapter,
  Response: Response,
  Listener: listener.Listener,
  TextListener: listener.TextListener,
  Message: message.Message,
  TextMessage: message.TextMessage,
  EnterMessage: message.EnterMessage,
  LeaveMessage: message.LeaveMessage,
  TopicMessage: message.TopicMessage,
  CatchAllMessage: message.CatchAllMessage
};

module.exports.loadBot = function(scripts, adapterName, brainName, enableHttpd, botName) {
  return new Robot(scripts, adapterName, brainName, enableHttpd, botName);
};
<|endoftext|>


<commit_before>'use strict';
import React, {
	PropTypes,
	requireNativeComponent,
} from 'react-native';
const { processColor } = React;

/** A native reference to the chart view */
const CHART_REF = 'chart';

const processData = (chartData) => {
	return chartData.map(d => {
		return {
			...d,
			color: processColor(d.color),
			fillColor: processColor(d.fillColor),
			dataPointColor: processColor(d.dataPointColor),
			dataPointFillColor: processColor(d.dataPointFillColor),
			highlightColor: processColor(d.highlightColor),
			fillGradient: Array.isArray(d.fillGradient)
				? [processColor(d.fillGradient[0]), processColor(d.fillGradient[1])]
				: undefined,
		};
	});
};

/** Our bridge component */
export default class RNChart extends React.Component {
	static propTypes = {

		chartData: PropTypes.arrayOf(
			PropTypes.shape({
				data: PropTypes.arrayOf(PropTypes.number).isRequired,
				name: PropTypes.string,
				type: PropTypes.oneOf(['line', 'bar', 'pie']),
				fillColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				fillGradient: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])),
				cornerRadius: PropTypes.number,
				lineWidth: PropTypes.number,
				highlightColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				highlightIndices: PropTypes.arrayOf(PropTypes.number),
				highlightRadius: PropTypes.number,
				widthPercent: PropTypes.number,
				showDataPoint: PropTypes.bool,
				dataPointColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				dataPointFillColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				dataPointRadius: PropTypes.number,
				pieAngle: PropTypes.number,
				pieCenterRatio: PropTypes.number,
				sliceColors: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])),
			})
		).isRequired,

		animationDuration: PropTypes.number,
		axisColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		axisLineWidth: PropTypes.number,
		axisTitleColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		axisTitleFontSize: PropTypes.number,
		chartFontSize: PropTypes.number,
		chartTitle: PropTypes.string,
		chartTitleColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		gridColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		gridLineWidth: PropTypes.number,
		labelFontSize: PropTypes.number,
		labelTextColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		showAxis: PropTypes.bool,
		showGrid: PropTypes.bool,
		showXAxisLabels: PropTypes.bool,
		showYAxisLabels: PropTypes.bool,
		style: PropTypes.any,
		tightBounds: PropTypes.bool,
		verticalGridStep: PropTypes.number,
		xAxisTitle: PropTypes.string,
		xLabels: PropTypes.array.isRequired,
		yAxisTitle: PropTypes.string,
	};

	/** Render the native component with the correct props */
	render() {
		const convertedProps = {
			...this.props,
			axisColor: processColor(this.props.axisColor),
			axisTitleColor: processColor(this.props.axisTitleColor),
			chartTitleColor: processColor(this.props.chartTitleColor),
			gridColor: processColor(this.props.gridColor),
			labelTextColor: processColor(this.props.labelTextColor),
			chartData: (this.props.chartData) ? processData(this.props.chartData) : undefined,
		};
		return <RNChartView ref={CHART_REF} {...convertedProps} />;
	}
}

/** The native chart view */
const RNChartView = requireNativeComponent('RNChartView', RNChart);
<commit_msg>sliceColors processed<commit_after>'use strict';
import React, {
	PropTypes,
	requireNativeComponent,
} from 'react-native';
const { processColor } = React;

/** A native reference to the chart view */
const CHART_REF = 'chart';

const processData = (chartData) => {
	return chartData.map(d => {
		return {
			...d,
			color: processColor(d.color),
			fillColor: processColor(d.fillColor),
			dataPointColor: processColor(d.dataPointColor),
			dataPointFillColor: processColor(d.dataPointFillColor),
			highlightColor: processColor(d.highlightColor),
			fillGradient: Array.isArray(d.fillGradient)
				? [processColor(d.fillGradient[0]), processColor(d.fillGradient[1])]
				: undefined,
			sliceColors: Array.isArray(d.sliceColors)
				? d.sliceColors.map(processColor)
				: undefined,
		};
	});
};

/** Our bridge component */
export default class RNChart extends React.Component {
	static propTypes = {

		chartData: PropTypes.arrayOf(
			PropTypes.shape({
				data: PropTypes.arrayOf(PropTypes.number).isRequired,
				name: PropTypes.string,
				type: PropTypes.oneOf(['line', 'bar', 'pie']),
				fillColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				fillGradient: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])),
				cornerRadius: PropTypes.number,
				lineWidth: PropTypes.number,
				highlightColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				highlightIndices: PropTypes.arrayOf(PropTypes.number),
				highlightRadius: PropTypes.number,
				widthPercent: PropTypes.number,
				showDataPoint: PropTypes.bool,
				dataPointColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				dataPointFillColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
				dataPointRadius: PropTypes.number,
				pieAngle: PropTypes.number,
				pieCenterRatio: PropTypes.number,
				sliceColors: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])),
			})
		).isRequired,

		animationDuration: PropTypes.number,
		axisColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		axisLineWidth: PropTypes.number,
		axisTitleColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		axisTitleFontSize: PropTypes.number,
		chartFontSize: PropTypes.number,
		chartTitle: PropTypes.string,
		chartTitleColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		gridColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		gridLineWidth: PropTypes.number,
		labelFontSize: PropTypes.number,
		labelTextColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
		showAxis: PropTypes.bool,
		showGrid: PropTypes.bool,
		showXAxisLabels: PropTypes.bool,
		showYAxisLabels: PropTypes.bool,
		style: PropTypes.any,
		tightBounds: PropTypes.bool,
		verticalGridStep: PropTypes.number,
		xAxisTitle: PropTypes.string,
		xLabels: PropTypes.array.isRequired,
		yAxisTitle: PropTypes.string,
	};

	/** Render the native component with the correct props */
	render() {
		const convertedProps = {
			...this.props,
			axisColor: processColor(this.props.axisColor),
			axisTitleColor: processColor(this.props.axisTitleColor),
			chartTitleColor: processColor(this.props.chartTitleColor),
			gridColor: processColor(this.props.gridColor),
			labelTextColor: processColor(this.props.labelTextColor),
			chartData: (this.props.chartData) ? processData(this.props.chartData) : undefined,
		};
		return <RNChartView ref={CHART_REF} {...convertedProps} />;
	}
}

/** The native chart view */
const RNChartView = requireNativeComponent('RNChartView', RNChart);
<|endoftext|>


<commit_before>/**
 * hive.js
 * Copyright (C) 2013-2015 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
var shoe = require('shoe-bin')
  , dataplex = require('dataplex')
  , co = require('co')
  , gulf = require('gulf')
  , through = require('through2')

module.exports = setup
module.exports.consumes = ['hooks','sync', 'auth', 'broadcast']

function setup(plugin, imports, register) {
  var hooks = imports.hooks
    , sync = imports.sync
    , auth = imports.auth
    , broadcast = imports.broadcast

  hooks.on('http:listening', function*(server) {
    sock.install(server, '/socket')
  })

  var sock = shoe(function(stream) {
    var plex = dataplex()
    stream.pipe(plex).pipe(stream)

    plex.add('/document/:id/sync', function(opts) {
      // Set up link authorization
      var link = new gulf.Link({
        authorizeWrite: function(msg, credentials, cb) {
          co(function*() {
            var user = yield auth.authenticate('token', credentials)
              , allowed = false
            switch(msg[0]) {
              case 'edit':
                allowed = yield auth.authorize(user, 'document:write', {document: opts.id})
                break;
              case 'ack':
              case 'requestInit':
                allowed = yield auth.authorize(user, 'document:read', {document: opts.id})
                break;
            }
            return allowed
          })
          .then(function(allowed) {
            cb(null, allowed)
          })
          .catch(cb)
        }
      , authorizeRead:function(msg, credentials, cb) {
          co(function*() {
            var user = yield auth.authenticate('token', credentials)
              , allowed = false
            switch(msg[0]) {
              case 'edit':
                allowed = yield auth.authorize(user, 'document:read', {document: opts.id})
                break;
              case 'ack':
              case 'init':
                allowed = yield auth.authorize(user, 'document:read', {document: opts.id})
                break;
            }
            return allowed
          })
          .then(function(allowed) {
            cb(null, allowed)
          })
          .catch(cb)
        }
      })

      co(function*() {
        // load document and add slave link
        var doc = yield sync.getDocument(opts.id)
        doc.attachslaveLink(link)
      })
      .then(function() {})
      .catch(function(er) { throw er})

      return link
    })

    plex.add('/document/:id/broadcast', function(opts) {
      var b = broadcast.document(opts.id, plex.user)
      stream.on('close', function() {
        b.emit('close')
      })
      return b
    })

    plex.add('/authenticate', function() {
      return through(function(chunk, enc, cb) {
        var that = this
        co(function*() {
          plex.user = yield auth.authenticate('token', chunk.toString('utf8'))
          that.push(JSON.stringify(plex.user))
        })
        .then(cb)
        .catch(cb)
      })
    })

    co(function*() {
      yield hooks.callHook('shoe-interface:connect', plex)
    }).then(function() {})
  })

  register()
}
<commit_msg>Change document:write auth action to document:change<commit_after>/**
 * hive.js
 * Copyright (C) 2013-2015 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
var shoe = require('shoe-bin')
  , dataplex = require('dataplex')
  , co = require('co')
  , gulf = require('gulf')
  , through = require('through2')

module.exports = setup
module.exports.consumes = ['hooks','sync', 'auth', 'broadcast']

function setup(plugin, imports, register) {
  var hooks = imports.hooks
    , sync = imports.sync
    , auth = imports.auth
    , broadcast = imports.broadcast

  hooks.on('http:listening', function*(server) {
    sock.install(server, '/socket')
  })

  var sock = shoe(function(stream) {
    var plex = dataplex()
    stream.pipe(plex).pipe(stream)

    plex.add('/document/:id/sync', function(opts) {
      // Set up link authorization
      var link = new gulf.Link({
        authorizeWrite: function(msg, credentials, cb) {
          co(function*() {
            var user = yield auth.authenticate('token', credentials)
              , allowed = false
            switch(msg[0]) {
              case 'edit':
                allowed = yield auth.authorize(user, 'document:change', {document: opts.id})
                break;
              case 'ack':
              case 'requestInit':
                allowed = yield auth.authorize(user, 'document:read', {document: opts.id})
                break;
            }
            return allowed
          })
          .then(function(allowed) {
            cb(null, allowed)
          })
          .catch(cb)
        }
      , authorizeRead:function(msg, credentials, cb) {
          co(function*() {
            var user = yield auth.authenticate('token', credentials)
              , allowed = false
            switch(msg[0]) {
              case 'edit':
                allowed = yield auth.authorize(user, 'document:read', {document: opts.id})
                break;
              case 'ack':
              case 'init':
                allowed = yield auth.authorize(user, 'document:read', {document: opts.id})
                break;
            }
            return allowed
          })
          .then(function(allowed) {
            cb(null, allowed)
          })
          .catch(cb)
        }
      })

      co(function*() {
        // load document and add slave link
        var doc = yield sync.getDocument(opts.id)
        doc.attachslaveLink(link)
      })
      .then(function() {})
      .catch(function(er) { throw er})

      return link
    })

    plex.add('/document/:id/broadcast', function(opts) {
      var b = broadcast.document(opts.id, plex.user)
      stream.on('close', function() {
        b.emit('close')
      })
      return b
    })

    plex.add('/authenticate', function() {
      return through(function(chunk, enc, cb) {
        var that = this
        co(function*() {
          plex.user = yield auth.authenticate('token', chunk.toString('utf8'))
          that.push(JSON.stringify(plex.user))
        })
        .then(cb)
        .catch(cb)
      })
    })

    co(function*() {
      yield hooks.callHook('shoe-interface:connect', plex)
    }).then(function() {})
  })

  register()
}
<|endoftext|>


<commit_before>var http = require ('httpreq');
var config = {
  email: null,
  apikey: null,
  timeout: 5000
};

function talk (props, callback) {
  var options = {
    url: 'https://gtmetrix.com/api/0.1/' + props.path,
    parameters: props.params || null,
    method: props.method || 'GET',
    timeout: config.timeout || 5000,
    auth: config.email + ':' + config.apikey,
    binary: props.binary || false
  };

  http.doRequest (options, function (err, res) {
    var type = res && res.headers ['content-type'] .split (';') [0] || '';
    var size = res && res.headers ['content-length'] || null;
    var code = res && res.statusCode;
    var data = res && res.body || null;
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
      callback (error);
      return;
    }

    if (size && props.binary && type.match (/\/(pdf|jpeg|tar)$/)) {
      callback (null, data);
      return;
    }

    try {
      data = JSON.parse (data);
    } catch (e) {
      error = new Error ('invalid response');
      error.statusCode = code;
      error.contentType = type;
      error.error = e;
      data = null;
    }

    if (data && data.error) {
      error = new Error ('API error');
      error.statusCode = code;
      error.contentType = type;
      error.error = data.error;
      data = null;
    }

    callback (error, data);
  });
}

module.exports = function (props) {
  var key;

  for (key in props) {
    config [key] = props [key];
  }

  return {
    test: {
      create: function (params, callback) {
        talk ({ method: 'POST', path: 'test', params: params }, callback);
      },
      get: function (testId, resource, callback) {
        var params = {
          method: 'GET',
          path: 'test/' + testId
        };

        if (typeof resource === 'string') {
          params.path += '/' + resource;
          params.binary = resource.match (/(screenshot)/);
        } else {
          callback = resource;
        }

        talk (params, callback);
      }
    },
    locations: {
      list: function (callback) {
        talk ({ method: 'GET', path: 'locations' }, callback);
      }
    },
    browsers: {
      list: function (callback) {
        talk ({ method: 'GET', path: 'browsers' }, callback);
      },
      get: function (browserId, callback) {
        talk ({ method: 'GET', path: 'browsers/' + browserId }, callback);
      }
    },
    account: {
      status: function (callback) {
        talk ({ method: 'GET', path: 'status' }, callback);
      }
    }
  };
};
<commit_msg>Add User-Agent string<commit_after>var http = require ('httpreq');
var config = {
  email: null,
  apikey: null,
  timeout: 5000
};

function talk (props, callback) {
  var options = {
    url: 'https://gtmetrix.com/api/0.1/' + props.path,
    parameters: props.params || null,
    method: props.method || 'GET',
    headers: {
      'User-Agent': 'gtmetrix.js (https://www.npmjs.com/package/gtmetrix)'
    },
    timeout: config.timeout || 5000,
    auth: config.email + ':' + config.apikey,
    binary: props.binary || false
  };

  http.doRequest (options, function (err, res) {
    var type = res && res.headers ['content-type'] .split (';') [0] || '';
    var size = res && res.headers ['content-length'] || null;
    var code = res && res.statusCode;
    var data = res && res.body || null;
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
      callback (error);
      return;
    }

    if (size && props.binary && type.match (/\/(pdf|jpeg|tar)$/)) {
      callback (null, data);
      return;
    }

    try {
      data = JSON.parse (data);
    } catch (e) {
      error = new Error ('invalid response');
      error.statusCode = code;
      error.contentType = type;
      error.error = e;
      data = null;
    }

    if (data && data.error) {
      error = new Error ('API error');
      error.statusCode = code;
      error.contentType = type;
      error.error = data.error;
      data = null;
    }

    callback (error, data);
  });
}

module.exports = function (props) {
  var key;

  for (key in props) {
    config [key] = props [key];
  }

  return {
    test: {
      create: function (params, callback) {
        talk ({ method: 'POST', path: 'test', params: params }, callback);
      },
      get: function (testId, resource, callback) {
        var params = {
          method: 'GET',
          path: 'test/' + testId
        };

        if (typeof resource === 'string') {
          params.path += '/' + resource;
          params.binary = resource.match (/(screenshot)/);
        } else {
          callback = resource;
        }

        talk (params, callback);
      }
    },
    locations: {
      list: function (callback) {
        talk ({ method: 'GET', path: 'locations' }, callback);
      }
    },
    browsers: {
      list: function (callback) {
        talk ({ method: 'GET', path: 'browsers' }, callback);
      },
      get: function (browserId, callback) {
        talk ({ method: 'GET', path: 'browsers/' + browserId }, callback);
      }
    },
    account: {
      status: function (callback) {
        talk ({ method: 'GET', path: 'status' }, callback);
      }
    }
  };
};
<|endoftext|>


<commit_before>const net = require('net');

const getUnusedPort = exports.getUnusedPort = (options) => {
  options = options || {};

  let min = options.min || 1024;
  let port = options.port || min;
  let max = options.max;

  let promise = new Promise((resolve, reject) => {
    let server = net.createServer();

    if (port >= max) {
      let error = new Error('Could not find an unused port');
      error.code = 'NO_UNUSED';
      return reject(error);
    }

    server.listen(port, (err) => {
      if (err) {
        return reject(err);
      }

      server.once('close', () => resolve(port));
      server.close();
    });

    server.on('error', reject);
  });

  return promise.catch((err) => {
    if (err.code === 'NO_UNUSED') throw err;
    return getUnusedPort({ min, max, port: ++port });
  });
};
<commit_msg>Use strict mode<commit_after>'use strict';

const net = require('net');

const getUnusedPort = exports.getUnusedPort = (options) => {
  options = options || {};

  let min = options.min || 1024;
  let port = options.port || min;
  let max = options.max;

  let promise = new Promise((resolve, reject) => {
    let server = net.createServer();

    if (port >= max) {
      let error = new Error('Could not find an unused port');
      error.code = 'NO_UNUSED';
      return reject(error);
    }

    server.listen(port, (err) => {
      if (err) {
        return reject(err);
      }

      server.once('close', () => resolve(port));
      server.close();
    });

    server.on('error', reject);
  });

  return promise.catch((err) => {
    if (err.code === 'NO_UNUSED') throw err;
    return getUnusedPort({ min, max, port: ++port });
  });
};
<|endoftext|>


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

var server = http.createServer(function(request, response) {

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello World!");

});

var port = process.env.PORT || 1337;
server.listen(port);

console.log("Server running at http://localhost:%d", port);
<commit_msg>committing...<commit_after>var http = require('http');

var server = http.createServer(function(request, response) {

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello World!!");

});

var port = process.env.PORT || 1337;
server.listen(port);

console.log("Server running at http://localhost:%d", port);
<|endoftext|>


<commit_before>const cheerio = require('cheerio');
const express = require('express');
const http = require('http');
const path = require('path');
const fs = require('fs');

const app = express();
let template = '';
fs.readFile(path.resolve(__dirname, 'template.tpl'), 'utf8', (err, data) => {
  if (err) throw err; // we'll not consider error handling for now
  template = data;
});

const parseArticle = (res, url, images) => {
  http.get({
    host: 'www.clarin.com',
    path: url,
  }, (response) => {
    const contentType = response.headers['content-type'];
    if (
      (typeof contentType !== 'undefined') &&
      (contentType.indexOf('text/html') === 0)
    ) {
      let body = '';
      response.on('data', (d) => {
        body += d;
      });
      response.on('end', () => {
        body = body.replace(/"!=""\u00b7trueValue=/g, '')
                   .replace(/\}\}/g, '');
        const $ = cheerio.load(body);
        const onDemand = [];

        $('.on-demand').each((i, e) => {
          onDemand.push(new Promise((resolve) => {
            http.get({
              host: 'www.clarin.com',
              path: $(e).data('src'),
            }, (onDemandResp) => {
              let onDemandBody = '';
              onDemandResp.on('data', (d) => {
                onDemandBody += d;
              });
              onDemandResp.on('end', () => {
                resolve(
                  JSON.parse(
                    onDemandBody.substr(1, onDemandBody.length - 2)
                  ).data.replace(/"!=""\u00b7trueValue=/g, '')
                        .replace(/\}\}/g, '')
                );
              });
            });
          }));
        });

        Promise.all(onDemand).then((values) => {
          values.forEach((onDemandContent) => {
            $('body').append(onDemandContent);
          });

          $('header').remove();
          $('.share-bar').remove();
          $('.share').remove();
          $('.tags').remove();
          $('.banner').remove();
          $('.relacionadas').remove();
          $('.colDerecha').remove();
          $('.cxense-content').remove();
          $('#comments').remove();
          $('footer').remove();
          $('script').remove();
          $('.sticky-spacer:last-of-type').remove();
          $('.on-demand').remove();
          $('.mam').remove();

          if (!images) {
            // Las imágenes suelen venir adentro de un link en los articulos
            $('article > a').remove();
            $('img').remove();
          } else {
            $('.img-responsive').each((idx, node) => {
              const elem = $(node);
              elem.attr('src', elem.data('small'));
            });

            $('article').each((i, elem) => {
              if ($(elem).find('img').length > 0) {
                $(elem).append($(elem).find('a').first().remove());
              }
            });

            $('a').each((i, elem) => {
              $(elem).attr('href', `${$(elem).attr('href')}?img`);
            });
          }

          // Sacarle las clases a los artículos, que no quieren decir nada
          $('article, h5').removeAttr('class').removeAttr('id');

          const content = $('');
          let title = 'Clarin Limpio';
          if ($('.content.home').length > 0) {
            // Home
            const columnistas = $('.mod-columnistas-horizontal')
                                .find('h5, ul').remove();
            content.append($('article, h5').remove());
            content.append(columnistas);
          } else {
            // Artículo específico
            $('[id^=bannerId_]').remove();
            $('[id^=sas_]').remove();
            $('.breadcrumb li:first-of-type a').attr('href', '/');
            const outlinks = $('.box-content-new, .content-new').remove();
            outlinks.find('span').remove();

            content.append($('.nota-unica .title, .nota-unica .notas-content'));
            content.append($('
Mirá también
'));
            content.append(outlinks);

            title = $('title').text();
          }

          const htmlContent = template.replace('{{body}}', content.html())
                                      .replace('{{title}}', title);
          res.write(htmlContent);
          res.end();
        });
      });
    } else {
      res.write('');
      res.end();
    }
  });
};

app.use('/static', express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  if (req.url.indexOf('.js') >= 0 || req.url.indexOf('.css') >= 0) {
    res.write('');
    res.end();
  } else {
    next();
  }
});

app.get('/img*', (req, res) => {
  parseArticle(res, req.url.substring(4), true);
});

app.get('/*', (req, res) => {
  parseArticle(res, req.url, false);
});

const PORT = 5050;
http.createServer(app).listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
});
<commit_msg>Eliminar fix defectuoso a links.<commit_after>const cheerio = require('cheerio');
const express = require('express');
const http = require('http');
const path = require('path');
const fs = require('fs');

const app = express();
let template = '';
fs.readFile(path.resolve(__dirname, 'template.tpl'), 'utf8', (err, data) => {
  if (err) throw err; // we'll not consider error handling for now
  template = data;
});

const parseArticle = (res, url, images) => {
  http.get({
    host: 'www.clarin.com',
    path: url,
  }, (response) => {
    const contentType = response.headers['content-type'];
    if (
      (typeof contentType !== 'undefined') &&
      (contentType.indexOf('text/html') === 0)
    ) {
      let body = '';
      response.on('data', (d) => {
        body += d;
      });
      response.on('end', () => {
        body = body.replace(/"!=""\u00b7trueValue=/g, '')
                   .replace(/\}\}/g, '');
        const $ = cheerio.load(body);
        const onDemand = [];

        $('.on-demand').each((i, e) => {
          onDemand.push(new Promise((resolve) => {
            http.get({
              host: 'www.clarin.com',
              path: $(e).data('src'),
            }, (onDemandResp) => {
              let onDemandBody = '';
              onDemandResp.on('data', (d) => {
                onDemandBody += d;
              });
              onDemandResp.on('end', () => {
                resolve(
                  JSON.parse(
                    onDemandBody.substr(1, onDemandBody.length - 2)
                  ).data.replace(/"!=""\u00b7trueValue=/g, '')
                        .replace(/\}\}/g, '')
                );
              });
            });
          }));
        });

        Promise.all(onDemand).then((values) => {
          values.forEach((onDemandContent) => {
            $('body').append(onDemandContent);
          });

          $('header').remove();
          $('.share-bar').remove();
          $('.share').remove();
          $('.tags').remove();
          $('.banner').remove();
          $('.relacionadas').remove();
          $('.colDerecha').remove();
          $('.cxense-content').remove();
          $('#comments').remove();
          $('footer').remove();
          $('script').remove();
          $('.sticky-spacer:last-of-type').remove();
          $('.on-demand').remove();
          $('.mam').remove();

          if (!images) {
            // Las imágenes suelen venir adentro de un link en los articulos
            $('article > a').remove();
            $('img').remove();
          } else {
            $('.img-responsive').each((idx, node) => {
              const elem = $(node);
              elem.attr('src', elem.data('small'));
            });

            $('article').each((i, elem) => {
              if ($(elem).find('img').length > 0) {
                $(elem).append($(elem).find('a').first().remove());
              }
            });
          }

          // Sacarle las clases a los artículos, que no quieren decir nada
          $('article, h5').removeAttr('class').removeAttr('id');

          const content = $('');
          let title = 'Clarin Limpio';
          if ($('.content.home').length > 0) {
            // Home
            const columnistas = $('.mod-columnistas-horizontal')
                                .find('h5, ul').remove();
            content.append($('article, h5').remove());
            content.append(columnistas);
          } else {
            // Artículo específico
            $('[id^=bannerId_]').remove();
            $('[id^=sas_]').remove();
            $('.breadcrumb li:first-of-type a').attr('href', '/');
            const outlinks = $('.box-content-new, .content-new').remove();
            outlinks.find('span').remove();

            content.append($('.nota-unica .title, .nota-unica .notas-content'));
            content.append($('
Mirá también
'));
            content.append(outlinks);

            title = $('title').text();
          }

          const htmlContent = template.replace('{{body}}', content.html())
                                      .replace('{{title}}', title);
          res.write(htmlContent);
          res.end();
        });
      });
    } else {
      res.write('');
      res.end();
    }
  });
};

app.use('/static', express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  if (req.url.indexOf('.js') >= 0 || req.url.indexOf('.css') >= 0) {
    res.write('');
    res.end();
  } else {
    next();
  }
});

app.get('/img*', (req, res) => {
  parseArticle(res, req.url.substring(4), true);
});

app.get('/*', (req, res) => {
  parseArticle(res, req.url, false);
});

const PORT = 5050;
http.createServer(app).listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
});
<|endoftext|>


<commit_before>var net  = process.title === 'browser' ? require('tab-stream') : (require)('net')
var EventEmitter = require('events').EventEmitter

module.exports = inject(net)

function inject (net) {

  function autonode (handler) {

    var emitter = new EventEmitter()
    var server, client, _port
    emitter.listen =
      function listen (port) {
        //try and start a server on port.
        console.log('listening')
        emitter.isServer = true
        emitter.isClient = false

        server = net.createServer(onConnect).listen(port || _port)
        server.once('error', function (err) {
          //someone else has already started server.
          //connect to it.
          if('EADDRINUSE' == err.code) {
              emitter.isServer = false
              emitter.isClient = true

            function reconnect () {
              client.removeListener('error', reconnect)
              client.removeListener('close', reconnect)
              client.removeListener('end',   reconnect)
              setTimeout(listen, 50)
            }

            client = net.connect(port || _port)
              .once('connect', onConnect)
              .once('error',   reconnect)
              .once('end',     reconnect)
              .once('close',   reconnect)

            emitter.emit('connecting')
          }
        })
        server.once('listening', function () {
          emitter.emit('listening')
        })
        //remember the port for next time.
        _port = port || _port
        return this
      }

    function onConnect (stream) {
      //'connection', stream, isServer
      emitter.emit('connection', stream || client, stream ? true : false)
    }
    if(handler) emitter.on('connection', handler)

    emitter.close = function () {
      if(this.isServer)
        server.close()
      else {
        client.end()
        client.removeAllListeners()
      }
    }
    return emitter
  }

  autonode.inject = inject
  return autonode
}
<commit_msg>remove logging<commit_after>var net  = process.title === 'browser' ? require('tab-stream') : (require)('net')
var EventEmitter = require('events').EventEmitter

module.exports = inject(net)

function inject (net) {

  function autonode (handler) {

    var emitter = new EventEmitter()
    var server, client, _port
    emitter.listen =
      function listen (port) {
        //try and start a server on port.
        emitter.isServer = true
        emitter.isClient = false

        server = net.createServer(onConnect).listen(port || _port)
        server.once('error', function (err) {
          //someone else has already started server.
          //connect to it.
          if('EADDRINUSE' == err.code) {
              emitter.isServer = false
              emitter.isClient = true

            function reconnect () {
              client.removeListener('error', reconnect)
              client.removeListener('close', reconnect)
              client.removeListener('end',   reconnect)
              setTimeout(listen, 50)
            }

            client = net.connect(port || _port)
              .once('connect', onConnect)
              .once('error',   reconnect)
              .once('end',     reconnect)
              .once('close',   reconnect)

            emitter.emit('connecting')
          }
        })
        server.once('listening', function () {
          emitter.emit('listening')
        })
        //remember the port for next time.
        _port = port || _port
        return this
      }

    function onConnect (stream) {
      //'connection', stream, isServer
      emitter.emit('connection', stream || client, stream ? true : false)
    }
    if(handler) emitter.on('connection', handler)

    emitter.close = function () {
      if(this.isServer)
        server.close()
      else {
        client.end()
        client.removeAllListeners()
      }
    }
    return emitter
  }

  autonode.inject = inject
  return autonode
}
<|endoftext|>