<commit_before>import * as path from 'path';
import {childProcess, fs, promisify} from 'node-promise-es6';
import * as fse from 'fs-extra-promise-es6';
import {AwaitableObservable} from 'esnext-async';
import dedent from 'dedent';
import resolveModule from 'resolve';
import glob from 'glob';

export default class {
  constructor(basePath) {
    this.basePath = path.resolve(basePath);
  }

  contains(filePath) {
    return !path.relative(this.path(), this.path(filePath)).includes('..');
  }

  async create() {
    await fse.mkdirs(this.basePath);
  }

  async exec(command, params) {
    try {
      const {stdout} = await childProcess.execFile(command, params, {
        cwd: this.path()
      });
      return stdout.trim();
    } catch ({stderr}) {
      throw new Error(stderr.trim());
    }
  }

  execJs(code) {
    return new Promise((resolve, reject) => {
      const child = childProcess.spawn('dist-es6-run', {cwd: this.path()});
      child.stdin.write(code);
      child.stdin.end();

      let stdoutOutput = '';
      child.stdout.on('data', (output) => {
        stdoutOutput += output;
      });

      let stderrOutput = '';
      child.stderr.on('data', (output) => {
        stderrOutput += output;
      });

      child.on('close', (exitCode) => {
        if (exitCode === 0) {
          resolve(stdoutOutput.trim());
        } else {
          reject(stderrOutput.trim());
        }
      });
    });
  }

  async glob(pattern, options) {
    return await promisify(glob)(pattern, Object.assign({}, options, {
      cwd: this.path()
    }));
  }

  path(...components) {
    return path.resolve(this.basePath, ...components);
  }

  async read(filePath) {
    const contents = await fs.readFile(this.path(filePath), 'utf8');
    try {
      return JSON.parse(contents);
    } catch (error) {
      return contents;
    }
  }

  async remove(...pathComponents) {
    await fse.remove(this.path(...pathComponents));
  }

  async resolve(request) {
    return await new Promise((resolve, reject) => {
      resolveModule(request, {basedir: this.path()}, (error, result) => {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      });
    });
  }

  spawn(command, params) {
    const child = childProcess.spawn(command, params, {cwd: this.path()});
    const observable = new AwaitableObservable((observer) => {
      child.stdout.on('data', (data) => {
        observer.next(data.toString());
      });
      child.stderr.on('data', (data) => {
        observer.next(data.toString());
      });
    });
    observable.process = child;
    return observable;
  }

  async start(waitPattern = /^/) {
    this.server = this.spawn('sh', ['-c', 'npm start']);
    this.server.forEach((output) => {
      process.stderr.write(output);
    });
    await this.server.filter((output) => output.match(waitPattern));
  }

  async stat(filePath) {
    return await fs.stat(this.path(filePath));
  }

  async stop() {
    this.server.process.kill();
  }

  async symlink(source, destination) {
    await fse.ensureSymlink(this.path(source), this.path(destination));
  }

  async write(files) {
    for (const [filePath, fileContents] of Object.entries(files)) {
      const absoluteFilePath = this.path(filePath);

      await fse.ensureFile(absoluteFilePath);

      if (typeof fileContents === 'object') {
        await fse.writeJson(absoluteFilePath, fileContents);
      } else {
        await fs.writeFile(absoluteFilePath, `${dedent(fileContents)}\n`);
      }
    }
  }
}
<commit_msg>Wait until spawned process is fully exited<commit_after>import * as path from 'path';
import {childProcess, fs, promisify} from 'node-promise-es6';
import * as fse from 'fs-extra-promise-es6';
import {AwaitableObservable} from 'esnext-async';
import dedent from 'dedent';
import resolveModule from 'resolve';
import glob from 'glob';

export default class {
  constructor(basePath) {
    this.basePath = path.resolve(basePath);
  }

  contains(filePath) {
    return !path.relative(this.path(), this.path(filePath)).includes('..');
  }

  async create() {
    await fse.mkdirs(this.basePath);
  }

  async exec(command, params) {
    try {
      const {stdout} = await childProcess.execFile(command, params, {
        cwd: this.path()
      });
      return stdout.trim();
    } catch ({stderr}) {
      throw new Error(stderr.trim());
    }
  }

  execJs(code) {
    return new Promise((resolve, reject) => {
      const child = childProcess.spawn('dist-es6-run', {cwd: this.path()});
      child.stdin.write(code);
      child.stdin.end();

      let stdoutOutput = '';
      child.stdout.on('data', (output) => {
        stdoutOutput += output;
      });

      let stderrOutput = '';
      child.stderr.on('data', (output) => {
        stderrOutput += output;
      });

      child.on('close', (exitCode) => {
        if (exitCode === 0) {
          resolve(stdoutOutput.trim());
        } else {
          reject(stderrOutput.trim());
        }
      });
    });
  }

  async glob(pattern, options) {
    return await promisify(glob)(pattern, Object.assign({}, options, {
      cwd: this.path()
    }));
  }

  path(...components) {
    return path.resolve(this.basePath, ...components);
  }

  async read(filePath) {
    const contents = await fs.readFile(this.path(filePath), 'utf8');
    try {
      return JSON.parse(contents);
    } catch (error) {
      return contents;
    }
  }

  async remove(...pathComponents) {
    await fse.remove(this.path(...pathComponents));
  }

  async resolve(request) {
    return await new Promise((resolve, reject) => {
      resolveModule(request, {basedir: this.path()}, (error, result) => {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      });
    });
  }

  spawn(command, params) {
    const child = childProcess.spawn(command, params, {cwd: this.path()});
    const observable = new AwaitableObservable((observer) => {
      child.stdout.on('data', (data) => {
        observer.next(data.toString());
      });
      child.stderr.on('data', (data) => {
        observer.next(data.toString());
      });
    });
    observable.process = child;
    return observable;
  }

  async start(waitPattern = /^/) {
    this.server = this.spawn('sh', ['-c', 'npm start']);
    this.server.forEach((output) => {
      process.stderr.write(output);
    });
    await this.server.filter((output) => output.match(waitPattern));
  }

  async stat(filePath) {
    return await fs.stat(this.path(filePath));
  }

  async stop() {
    await new Promise((resolve) => {
      this.server.process.on('close', resolve);
      this.server.process.kill();
    });
  }

  async symlink(source, destination) {
    await fse.ensureSymlink(this.path(source), this.path(destination));
  }

  async write(files) {
    for (const [filePath, fileContents] of Object.entries(files)) {
      const absoluteFilePath = this.path(filePath);

      await fse.ensureFile(absoluteFilePath);

      if (typeof fileContents === 'object') {
        await fse.writeJson(absoluteFilePath, fileContents);
      } else {
        await fs.writeFile(absoluteFilePath, `${dedent(fileContents)}\n`);
      }
    }
  }
}
<|endoftext|>


<commit_before>import init from './init';
import help from './help';
import save from './save';
import cli from './cli';

export { init, cli, save, help };
<commit_msg>Remove CLI from index.js wrap<commit_after>import init from './init';
import help from './help';
import save from './save';

export { init, save, help };
<|endoftext|>


<commit_before>;(function(window, document, undefined){
  'use strict'

  var options = {
    searchInput: null,
    resultsContainer: null,
    json: [],
    searchResultTemplate: '
{title}
',
    templateMiddleware: function(){},
    noResultsText: 'No results found',
    limit: 10,
    fuzzy: false,
    exclude: []
  }

  var requiredOptions = ['searchInput','resultsContainer','json']

  var templater = require('./Templater')
  var repository = require('./Repository')
  var jsonLoader = require('./JSONLoader')
  var optionsValidator = require('./OptionsValidator')({
    required: requiredOptions
  })
  var utils = require('./utils')

  /*
    Public API
  */
  window.SimpleJekyllSearch = function SimpleJekyllSearch(_options){
    var errors = optionsValidator.validate(_options)
    if( errors.length > 0 ){
      throwError('You must specify the following required options: ' + requiredOptions)
    }

    options = utils.merge(options, _options)

    templater.setOptions({
      template: options.searchResultTemplate,
      middleware: options.templateMiddleware,
    })

    repository.setOptions({
      fuzzy: options.fuzzy,
      limit: options.limit,
    })

    if( utils.isJSON(options.json) ){
      initWithJSON(options.json)
    }else{
      initWithURL(options.json)
    }
  }

  // for backwards compatibility
  window.SimpleJekyllSearch.init = window.SimpleJekyllSearch

  if (typeof window.SimpleJekyllSearchInit === 'function') {
    window.SimpleJekyllSearchInit.call(this, window.SimpleJekyllSearch);
  }

  function initWithJSON(json){
    repository.put(json)
    registerInput()
  }

  function initWithURL(url){
    jsonLoader.load(url, function(err,json){
      if( err ){
        throwError('failed to get JSON (' + url + ')')
      }
      initWithJSON(json)
    })
  }

  function emptyResultsContainer(){
    options.resultsContainer.innerHTML = ''
  }

  function appendToResultsContainer(text){
    options.resultsContainer.innerHTML += text
  }

  function registerInput(){
    options.searchInput.addEventListener('keyup', function(e){
      var key = e.which
      var query = e.target.value
      if( isWhitelistedKey(key) && isValidQuery(query) ) {
        emptyResultsContainer();
        render( repository.search(query) );
      }
    })
  }

  function render(results) {
    if( results.length === 0 ){
      return appendToResultsContainer(options.noResultsText)
    }
    for (var i = 0; i < results.length; i++) {
      appendToResultsContainer( templater.compile(results[i]) )
    }
  }

  function isValidQuery(query) {
    return query && query.length > 0
  }

  function isWhitelistedKey(key) {
    return [13,16,20,37,38,39,40,91].indexOf(key) === -1
  }

  function throwError(message){ throw new Error('SimpleJekyllSearch --- '+ message) }
})(window, document);
<commit_msg>Clear container in any case (#62)<commit_after>;(function(window, document, undefined){
  'use strict'

  var options = {
    searchInput: null,
    resultsContainer: null,
    json: [],
    searchResultTemplate: '
{title}
',
    templateMiddleware: function(){},
    noResultsText: 'No results found',
    limit: 10,
    fuzzy: false,
    exclude: []
  }

  var requiredOptions = ['searchInput','resultsContainer','json']

  var templater = require('./Templater')
  var repository = require('./Repository')
  var jsonLoader = require('./JSONLoader')
  var optionsValidator = require('./OptionsValidator')({
    required: requiredOptions
  })
  var utils = require('./utils')

  /*
    Public API
  */
  window.SimpleJekyllSearch = function SimpleJekyllSearch(_options){
    var errors = optionsValidator.validate(_options)
    if( errors.length > 0 ){
      throwError('You must specify the following required options: ' + requiredOptions)
    }

    options = utils.merge(options, _options)

    templater.setOptions({
      template: options.searchResultTemplate,
      middleware: options.templateMiddleware,
    })

    repository.setOptions({
      fuzzy: options.fuzzy,
      limit: options.limit,
    })

    if( utils.isJSON(options.json) ){
      initWithJSON(options.json)
    }else{
      initWithURL(options.json)
    }
  }

  // for backwards compatibility
  window.SimpleJekyllSearch.init = window.SimpleJekyllSearch

  if (typeof window.SimpleJekyllSearchInit === 'function') {
    window.SimpleJekyllSearchInit.call(this, window.SimpleJekyllSearch);
  }

  function initWithJSON(json){
    repository.put(json)
    registerInput()
  }

  function initWithURL(url){
    jsonLoader.load(url, function(err,json){
      if( err ){
        throwError('failed to get JSON (' + url + ')')
      }
      initWithJSON(json)
    })
  }

  function emptyResultsContainer(){
    options.resultsContainer.innerHTML = ''
  }

  function appendToResultsContainer(text){
    options.resultsContainer.innerHTML += text
  }

  function registerInput(){
    options.searchInput.addEventListener('keyup', function(e){
      emptyResultsContainer();
      var key = e.which
      var query = e.target.value
      if( isWhitelistedKey(key) && isValidQuery(query) ) {
        render( repository.search(query) );
      }
    })
  }

  function render(results) {
    if( results.length === 0 ){
      return appendToResultsContainer(options.noResultsText)
    }
    for (var i = 0; i < results.length; i++) {
      appendToResultsContainer( templater.compile(results[i]) )
    }
  }

  function isValidQuery(query) {
    return query && query.length > 0
  }

  function isWhitelistedKey(key) {
    return [13,16,20,37,38,39,40,91].indexOf(key) === -1
  }

  function throwError(message){ throw new Error('SimpleJekyllSearch --- '+ message) }
})(window, document);
<|endoftext|>


<commit_before>import fs from 'fs'
import path from 'path'

const PLUGIN_NAME = 'module-roots'

export default function({ Plugin, types: t }) {

  function mapModule(context, mod) {
    let { paths, extensions } = context.state.opts.extra[PLUGIN_NAME] || {}

    if (paths == null) {
      paths = ['./src']
    }

    if (extensions == null) {
      extensions = ['.js', '/index.js']
    }

    for (const p of paths) {
      const potentialPath = path.join(p, mod)

      // check if potential path exists
      for (const ext of extensions) {
        const potentialPathWithExt = potentialPath + ext

        if (fs.existsSync(potentialPathWithExt)) {
          return path.relative(path.dirname(context.state.opts.filename), potentialPath)
        }
      }
    }
  }

  function transformImportCall(context, call) {
    const mod = call.source.value

    const newModule = mapModule(context, mod)
    if (newModule) {
      return t.importDeclaration(
        call.specifiers,
        t.literal(newModule),
      )
    }
  }

  return new Plugin(PLUGIN_NAME, {
    visitor: {
      ImportDeclaration: {
        exit(node) {
          return transformImportCall(this, node)
        }
      }
    }
  })

}
<commit_msg>fix relative path generation not working when in same directory<commit_after>import fs from 'fs'
import path from 'path'

const PLUGIN_NAME = 'module-roots'

export default function({ Plugin, types: t }) {

  function mapModule(context, mod) {
    let { paths, extensions } = context.state.opts.extra[PLUGIN_NAME] || {}

    if (paths == null) {
      paths = ['./src']
    }

    if (extensions == null) {
      extensions = ['.js', '/index.js']
    }

    for (const p of paths) {
      const potentialPath = path.join(p, mod)

      // check if potential path exists
      for (const ext of extensions) {
        const potentialPathWithExt = potentialPath + ext

        if (fs.existsSync(potentialPathWithExt)) {
          return './' + path.relative(path.dirname(context.state.opts.filename), potentialPath)
        }
      }
    }
  }

  function transformImportCall(context, call) {
    const mod = call.source.value

    const newModule = mapModule(context, mod)
    if (newModule) {
      return t.importDeclaration(
        call.specifiers,
        t.literal(newModule),
      )
    }
  }

  return new Plugin(PLUGIN_NAME, {
    visitor: {
      ImportDeclaration: {
        exit(node) {
          return transformImportCall(this, node)
        }
      }
    }
  })

}
<|endoftext|>


<commit_before>/*jslint node : true, nomen: true, plusplus: true, vars: true*/
"use strict";

var log4js = require('log4js');
var reqLogger = require('./request-logger');

module.exports = function (options, imports, register) {
    var hub = imports.hub;

    if (options.config) {
        log4js.configure(options.config);
    }

    log4js.requestLogger = reqLogger(options.request || {}, log4js);

    var logger = log4js.getLogger('app');

    hub.on('log.error', logger.error.bind(logger));
    hub.on('log.info', logger.info.bind(logger));

    register(null, {log: log4js});
};

module.exports.provides = ['log'];
module.exports.consumes = ['hub'];
<commit_msg>fixes #4 : call log4js.shutdown on destroy to flush logs<commit_after>/*jslint node : true, nomen: true, plusplus: true, vars: true*/
"use strict";

var log4js = require('log4js');
var reqLogger = require('./request-logger');

module.exports = function (options, imports, register) {
    var hub = imports.hub;

    if (options.config) {
        log4js.configure(options.config);
    }

    log4js.requestLogger = reqLogger(options.request || {}, log4js);

    var logger = log4js.getLogger('app');

    hub.on('log.error', logger.error.bind(logger));
    hub.on('log.info', logger.info.bind(logger));

    register(null, {
        onDestruct: function destroy(callback) {
            log4js.shutdown(function () {//flush on destroy
                callback();
            });
        },
        log: log4js
    });
};

module.exports.provides = ['log'];
module.exports.consumes = ['hub'];
<|endoftext|>


<commit_before>function defaultValuesEqual(a, b) {
    return a === b;
}

// TODO: Reintroduce comment, slightly rewritten
export function defaultMemoize(func, valuesEqual = defaultValuesEqual) {
    let lastArgs = null;
    let lastResult = null;
    return (...args) => {
        if (lastArgs !== null &&
            args.every((value, index) => valuesEqual(value, lastArgs[index]))) {
            return lastResult;
        }
        lastArgs = args;
        lastResult = func(...args);
        return lastResult;
    };
}

export function createSelectorCreator(memoize, ...memoizeOptions) {
    return (...selectors) => {
        const memoizedResultFunc = memoize(selectors.pop(), ...memoizeOptions);
        const dependencies = Array.isArray(selectors[0]) ?
            selectors[0] : selectors;
        return (state, props) => {
            const params = dependencies.map(dependency => dependency(state, props));
            return memoizedResultFunc(...params);
        };
    };
}

export function createSelector(...args) {
    return createSelectorCreator(defaultMemoize)(...args);
}
<commit_msg>add rest parameters to selector signature<commit_after>function defaultValuesEqual(a, b) {
    return a === b;
}

// TODO: Reintroduce comment, slightly rewritten
export function defaultMemoize(func, valuesEqual = defaultValuesEqual) {
    let lastArgs = null;
    let lastResult = null;
    return (...args) => {
        if (lastArgs !== null &&
            args.every((value, index) => valuesEqual(value, lastArgs[index]))) {
            return lastResult;
        }
        lastArgs = args;
        lastResult = func(...args);
        return lastResult;
    };
}

export function createSelectorCreator(memoize, ...memoizeOptions) {
    return (...selectors) => {
        const memoizedResultFunc = memoize(selectors.pop(), ...memoizeOptions);
        const dependencies = Array.isArray(selectors[0]) ?
            selectors[0] : selectors;
        return (state, props, ...args) => {
            const params = dependencies.map(
                dependency => dependency(state, props, ...args)
            );
            return memoizedResultFunc(...params);
        };
    };
}

export function createSelector(...args) {
    return createSelectorCreator(defaultMemoize)(...args);
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Pterodactyl - Daemon
 * Copyright (c) 2015 - 2016 Dane Everitt <dane@daneeveritt.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
const rfr = require('rfr');
const Async = require('async');
const Proc = require('child_process');
const Request = require('request');
const compareVersions = require('compare-versions');

const Log = rfr('src/helpers/logger.js');
const Package = rfr('package.json');

Log.info('+ ------------------------------------ +');
Log.info(`| Running Pterodactyl Daemon v${Package.version}    |`);
Log.info('|        https://pterodactyl.io        |');
Log.info('|  Copyright 2015 - 2016 Dane Everitt  |');
Log.info('+ ------------------------------------ +');
Log.info('Loading modules, this could take a few seconds.');

const NetworkController = rfr('src/controllers/network.js');
const Initializer = rfr('src/helpers/initialize.js').Initialize;
const SFTPController = rfr('src/controllers/sftp.js');
const LiveStats = rfr('src/http/stats.js');

const Network = new NetworkController();
const Initialize = new Initializer();
const SFTP = new SFTPController(true);
const Stats = new LiveStats();

Log.info('Modules loaded, starting Pterodactyl Daemon...');
Async.auto({
    check_version: callback => {
        Request.get('https://cdn.pterodactyl.io/releases/latest.json', {
            timeout: 5000,
        }, (err, response, body) => {
            if (err) {
                Log.warn('An error occurred while attempting to check the latest daemon release version.');
                return callback();
            }

            if (response.statusCode === 200) {
                const json = JSON.parse(body);

                if (compareVersions(Package.version, json.daemon) >= 0) {
                    Log.info('Pterodactyl Daemon is up-to-date!');
                    return callback();
                }

                Log.warn('+ ----- WARNING! ----- +');
                Log.warn(`Pterodactyl Daemon is not up-to-date! You are running version ${Package.version} and the latest version is ${json.daemon}.`);
                Log.warn(`Find out more here: https://github.com/Pterodactyl/Daemon/releases/v${json.daemon}`);
                Log.warn('+ -------------------- +');
                return callback();
            }

            Log.warn('Unable to check if this daemon is up to date! Invalid status code returned.');
            return callback();
        });
    },
    check_network: callback => {
        Log.info('Checking container networking environment...');
        Network.init(callback);
    },
    setup_network: ['check_network', (r, callback) => {
        Log.info('Checking pterodactyl0 interface and setting configuration values.');
        Network.interface(callback);
    }],
    start_sftp: callback => {
        Log.info('Attempting to start SFTP service container...');
        SFTP.startService(err => {
            if (err) return callback(err);
            Log.info('SFTP container successfully booted.');
            return callback();
        });
    },
    check_tar: callback => {
        Proc.exec('tar --help', {}, callback);
        Log.debug('Tar module found on server.');
    },
    check_zip: callback => {
        Proc.exec('unzip --help', {}, callback);
        Log.debug('Unzip module found on server.');
    },
    init_servers: ['setup_network', (r, callback) => {
        Log.info('Attempting to load servers and initialize daemon...');
        Initialize.init(callback);
    }],
    init_websocket: ['init_servers', (r, callback) => {
        Log.info('Configuring websocket for daemon stats...');
        Stats.init();
        return callback();
    }],
}, err => {
    if (err) {
        // Log a fatal error and exit.
        // We need this to initialize successfully without any errors.
        Log.fatal(err);
        process.exit(1);
    }
    rfr('src/http/routes.js');
    Log.info('Initialization Successful!');
});

process.on('uncaughtException', err => {
    Log.fatal(err, 'A fatal error occured during an operation.');
});

process.on('SIGUSR2', () => {
    Log.reopenFileStreams();
});
<commit_msg>Show canary as up-to-date<commit_after>'use strict';

/**
 * Pterodactyl - Daemon
 * Copyright (c) 2015 - 2016 Dane Everitt <dane@daneeveritt.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
const rfr = require('rfr');
const Async = require('async');
const Proc = require('child_process');
const Request = require('request');
const compareVersions = require('compare-versions');

const Log = rfr('src/helpers/logger.js');
const Package = rfr('package.json');

Log.info('+ ------------------------------------ +');
Log.info(`| Running Pterodactyl Daemon v${Package.version}    |`);
Log.info('|        https://pterodactyl.io        |');
Log.info('|  Copyright 2015 - 2016 Dane Everitt  |');
Log.info('+ ------------------------------------ +');
Log.info('Loading modules, this could take a few seconds.');

const NetworkController = rfr('src/controllers/network.js');
const Initializer = rfr('src/helpers/initialize.js').Initialize;
const SFTPController = rfr('src/controllers/sftp.js');
const LiveStats = rfr('src/http/stats.js');

const Network = new NetworkController();
const Initialize = new Initializer();
const SFTP = new SFTPController(true);
const Stats = new LiveStats();

Log.info('Modules loaded, starting Pterodactyl Daemon...');
Async.auto({
    check_version: callback => {
        Request.get('https://cdn.pterodactyl.io/releases/latest.json', {
            timeout: 5000,
        }, (err, response, body) => {
            if (err) {
                Log.warn('An error occurred while attempting to check the latest daemon release version.');
                return callback();
            }

            if (response.statusCode === 200) {
                const json = JSON.parse(body);

                if (compareVersions(Package.version, json.daemon) >= 0 || Package.version === '0.0.0-canary') {
                    Log.info('Pterodactyl Daemon is up-to-date!');
                    return callback();
                }

                Log.warn('+ ----- WARNING! ----- +');
                Log.warn(`Pterodactyl Daemon is not up-to-date! You are running version ${Package.version} and the latest version is ${json.daemon}.`);
                Log.warn(`Find out more here: https://github.com/Pterodactyl/Daemon/releases/v${json.daemon}`);
                Log.warn('+ -------------------- +');
                return callback();
            }

            Log.warn('Unable to check if this daemon is up to date! Invalid status code returned.');
            return callback();
        });
    },
    check_network: callback => {
        Log.info('Checking container networking environment...');
        Network.init(callback);
    },
    setup_network: ['check_network', (r, callback) => {
        Log.info('Checking pterodactyl0 interface and setting configuration values.');
        Network.interface(callback);
    }],
    start_sftp: callback => {
        Log.info('Attempting to start SFTP service container...');
        SFTP.startService(err => {
            if (err) return callback(err);
            Log.info('SFTP container successfully booted.');
            return callback();
        });
    },
    check_tar: callback => {
        Proc.exec('tar --help', {}, callback);
        Log.debug('Tar module found on server.');
    },
    check_zip: callback => {
        Proc.exec('unzip --help', {}, callback);
        Log.debug('Unzip module found on server.');
    },
    init_servers: ['setup_network', (r, callback) => {
        Log.info('Attempting to load servers and initialize daemon...');
        Initialize.init(callback);
    }],
    init_websocket: ['init_servers', (r, callback) => {
        Log.info('Configuring websocket for daemon stats...');
        Stats.init();
        return callback();
    }],
}, err => {
    if (err) {
        // Log a fatal error and exit.
        // We need this to initialize successfully without any errors.
        Log.fatal(err);
        process.exit(1);
    }
    rfr('src/http/routes.js');
    Log.info('Initialization Successful!');
});

process.on('uncaughtException', err => {
    Log.fatal(err, 'A fatal error occured during an operation.');
});

process.on('SIGUSR2', () => {
    Log.reopenFileStreams();
});
<|endoftext|>


<commit_before>import Matches from "./matches";

// Maps symbols to matches.
const SYMBOL_MATCHES = {
    "#": Matches.id,
    ".": Matches.className
};

// TODO: Use better variables names.
function ReactShallowQuery(object, query) {
    var fragments = query.split(" ");
    var results = [object];
    var recursive = true;

    // Loop through each fragement.
    // TODO: Use Array.reduce.
    fragments.forEach((fragment, index) => {
        var prefix = fragment.charAt(0);
        var newResults = [];
        var matcher;

        if (fragment == ">")
            return recursive = false;

        // Handle prefix symbols.
        if (SYMBOL_MATCHES[prefix]) {
            matcher = SYMBOL_MATCHES[prefix];
        } else {
            let upperCase = (prefix === prefix.toUpperCase());

            // Handle default and custom React component names.
            matcher = Matches[upperCase ? "displayName" : "type"];
        }

        results.forEach((result) => {
            var objects = (index ? result.props.children : [result]);
            var foundResults = findResults(objects, matcher, fragment, recursive);

            // Append the newly found results to the 'newResults' array.
            newResults.push.apply(newResults, foundResults);
        });

        results = newResults;
    });

    return results;
};

function findResults(objects = [], matcher, fragment, recursive) {
    var results = [];

    // TODO: Use Array.reduce.
    objects.forEach((object) => {
        var children, foundResults;

        // Ignore objects that aren't objects (e.g. text).
        if (typeof object != "object")
            return;

        ({children} = object.props);

        if (matcher(object, fragment))
            results.push(object);

        if (!children || !recursive)
            return;

        if (!Array.isArray(children))
            children = [children];

        foundResults = findResults(children, matcher, fragment, recursive);

        // Append the newly found results onto the 'results' array.
        results.push.apply(results, foundResults);
    });

    return results;
}

export default ReactShallowQuery;
<commit_msg>Fixed a couple of issues due to inconsistent data types.<commit_after>import Matches from "./matches";

// Maps symbols to matches.
const SYMBOL_MATCHES = {
    "#": Matches.id,
    ".": Matches.className
};

// TODO: Use better variables names.
function ReactShallowQuery(object, query) {
    var fragments = query.split(" ");
    var results = [object];
    var recursive = true;

    // Loop through each fragement.
    // TODO: Use Array.reduce.
    fragments.forEach((fragment, index) => {
        var prefix = fragment.charAt(0);
        var newResults = [];
        var matcher;

        if (fragment == ">")
            return recursive = false;

        // Handle prefix symbols.
        if (SYMBOL_MATCHES[prefix]) {
            matcher = SYMBOL_MATCHES[prefix];
        } else {
            let upperCase = (prefix === prefix.toUpperCase());

            // Handle default and custom React component names.
            matcher = Matches[upperCase ? "displayName" : "type"];
        }

        results.forEach((result) => {
            var objects = (index ? result.props.children : result);
            var foundResults;

            if (!Array.isArray(objects))
                objects = [objects];

            foundResults = findResults(objects, matcher, fragment, recursive);

            // Append the newly found results to the 'newResults' array.
            newResults.push.apply(newResults, foundResults);
        });

        results = newResults;
    });

    return results;
};

function findResults(objects = [], matcher, fragment, recursive) {
    var results = [];

    // TODO: Use Array.reduce.
    objects.forEach((object) => {
        var children, foundResults;

        // Ignore objects that aren't objects (e.g. text) or null values.
        if (!object || typeof object != "object")
            return;

        ({children} = object.props);

        if (matcher(object, fragment))
            results.push(object);

        if (!children || !recursive)
            return;

        if (!Array.isArray(children))
            children = [children];

        foundResults = findResults(children, matcher, fragment, recursive);

        // Append the newly found results onto the 'results' array.
        results.push.apply(results, foundResults);
    });

    return results;
}

export default ReactShallowQuery;
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

// The primary entry point into fulfilling a GraphQL request.
export { graphql } from './graphql';

// Produce a GraphQL type schema.
export { GraphQLSchema } from './type/schema';

export {
  GraphQLScalarType,
  GraphQLObjectType,
  GraphQLInterfaceType,
  GraphQLUnionType,
  GraphQLEnumType,
  GraphQLInputObjectType,
  GraphQLList,
  GraphQLNonNull
} from './type/definition';

export {
  GraphQLInt,
  GraphQLFloat,
  GraphQLString,
  GraphQLBoolean,
  GraphQLID
} from './type/scalars';
<commit_msg>export errors from primary module<commit_after>/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

// The primary entry point into fulfilling a GraphQL request.
export { graphql } from './graphql';

// Produce a GraphQL type schema.
export { GraphQLSchema } from './type/schema';

// Define Types.
export {
  GraphQLScalarType,
  GraphQLObjectType,
  GraphQLInterfaceType,
  GraphQLUnionType,
  GraphQLEnumType,
  GraphQLInputObjectType,
  GraphQLList,
  GraphQLNonNull
} from './type/definition';

// Use Pre-defined Scalar Types.
export {
  GraphQLInt,
  GraphQLFloat,
  GraphQLString,
  GraphQLBoolean,
  GraphQLID
} from './type/scalars';

// Produce and format errors.
export { GraphQLError, formatError } from './error';
<|endoftext|>


<commit_before>'use strict';

//////
// Imports
import React from 'react';
import ReactDOM from 'react-dom';
var request = require('request');
var settings = require('electron-settings');
var WebSocketClient = require('websocket').client;

//////
// Global variables
var active_connection = undefined;
var host = settings.get("host", "localhost")
var port = settings.get("port", "8080")
var client = new WebSocketClient();
var connectionCooldown = 0;
var connectionTimeout = undefined;

//////
// Components
const message = function(props){
  return (

{props.text}

{props.time}

  )
}

//////
// Functions
var displayMessage = function(message, sender){
  // Get conversation list
  var conversation = document.getElementById("conversation");

  // Append message to conversation
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(message));
  li.setAttribute("class", sender);
  conversation.appendChild(li);

  // Add a clearfix
  var clearfix = document.createElement("li");
  clearfix.setAttribute("class", "clearfix");
  conversation.appendChild(clearfix);

  // Add time
  if (sender != 'info'){
    var time = document.createElement("li");
    time.appendChild(document.createTextNode(
      new Date().toTimeString().replace(/.*(\d{2}:\d{2}):\d{2}.*/, "$1")
    ));
    time.setAttribute("class", sender + " time");
    conversation.appendChild(time);
  }

  // Add a clearfix
  var clearfix = document.createElement("li");
  clearfix.setAttribute("class", "clearfix");
  conversation.appendChild(clearfix);

  // Scroll down to show new messages
  window.scrollTo(0, document.body.scrollHeight);
}

var getUrl = function(host, port) {
  return `http://${host}:${port}/connector/websocket`
}

var updateStatusIndicator = function(status){
  var status_indicator = document.getElementById("status-indicator")
  status_indicator.setAttribute('class', status)
}

var updateTooltipText = function(text){
  var tooltip = document.getElementById("status-indicator-tooltip")
  tooltip.innerHTML = text
}

var flashTooltip = function(){
  document.getElementById("status-indicator-tooltip")
    .setAttribute('class', 'active')
  setTimeout(function(){
    document.getElementById("status-indicator-tooltip")
      .setAttribute('class', '')
  }, 1000);
}

var sendUserMessage = function(){
  document.getElementById("input").focus();
  var user_message = document.getElementById("input").value
  if (active_connection && active_connection.connected) {
    if (user_message != ""){
      document.getElementById("input").value = ""
      displayMessage(user_message, "user")
      sendMessageToSocket(active_connection, user_message);
    }
  } else {
    flashTooltip()
  }
}

var connectToWebsocket = function() {
  updateTooltipText('connecting')
  request.post(getUrl(host, port), function(error, response, body){
    if (error){
      console.log(error)
      updateTooltipText('disconnected')
      reconnectToWebSocket()
    } else {
      var socket = JSON.parse(body)["socket"]
      client.connect(`ws://${host}:${port}/connector/websocket/${socket}`);
    }
  })
}

var reconnectToWebSocket = function() {
  if (active_connection && active_connection.connected) {
    active_connection.close()
  }
  if (connectionTimeout){
    clearTimeout(connectionTimeout);
  }
  console.log(`Reconnecting in ${connectionCooldown} seconds.`)
  backoffCooldown()
  connectionTimeout = setTimeout(connectToWebsocket, connectionCooldown * 1000);
}

var reconnectToWebSocketImmediately = function() {
  resetCooldown();
  reconnectToWebSocket();
}

var resetCooldown = function() {
  connectionCooldown = 0;
}

var backoffCooldown = function(){
    if (connectionCooldown <1 ) {
      connectionCooldown = 1;
    } else if (connectionCooldown < 60){
      connectionCooldown = connectionCooldown * 2
    }
}

var sendMessageToSocket = function(connection, message) {
  if (connection.connected) {
      connection.sendUTF(message);
  } else {
      console.log("Unable to send message")
  }
}

var handleSocketConnection = function(connection) {
  active_connection = connection;
  resetCooldown();
  console.log('WebSocket Client Connected');
  hideConnectionSettings();
  updateStatusIndicator('active');
  updateTooltipText('connected');
  displayMessage('connected', 'info');

  connection.on('error', handleSocketError);
  connection.on('close', handleSocketClose);
  connection.on('message', handleSocketMessage);
}

var handleSocketFailedConnection = function(error) {
  console.log('Connect Error: ' + error.toString());
  reconnectToWebSocket();
}

var handleSocketMessage = function(message) {
  if (message.type === 'utf8') {
      displayMessage(message.utf8Data, "bot");
  }
}

var handleSocketClose = function() {
  console.log('echo-protocol Connection Closed');
  updateStatusIndicator('inactive')
  updateTooltipText('disconnected')
  reconnectToWebSocket()
  displayMessage('disconnected', 'info')
}

var handleSocketError = function(error) {
  console.log("Connection Error: " + error.toString());
  updateStatusIndicator('inactive')
  updateTooltipText('disconnected')
  displayMessage('connection error', 'info')
}

var checkForReturnInPrompt = function(event) {
  event.preventDefault();
  if (event.keyCode == 13) {
      sendUserMessage();
  }
}

var toggleConnectionSettings = function() {
  var connectionSettings = document.getElementById("connection-settings")
  connectionSettings.classList.toggle('active');
}

var hideConnectionSettings = function() {
  var connectionSettings = document.getElementById("connection-settings")
  connectionSettings.classList.remove('active');
}

var updateHost = function(event) {
  settings.set("host", event.target.value);
  host = settings.get("host", "localhost");
  reconnectToWebSocketImmediately();
}

var updatePort = function(event) {
  settings.set("port", event.target.value);
  host = settings.get("port", "localhost");
  reconnectToWebSocketImmediately();
}

var populateHostPort = function() {
  if (settings.get("host", false)){
    document.getElementById("host").value = settings.get("host");
  }
  if (settings.get("port", false)){
    document.getElementById("port").value = settings.get("port");
  }
}

//////
// Event listeners
client.on('connect', handleSocketConnection);
client.on('connectFailed', handleSocketFailedConnection);
document.getElementById("send").addEventListener("click", sendUserMessage);
document.getElementById("input").addEventListener("keyup", checkForReturnInPrompt);
document.getElementById("status-indicator").addEventListener("click", toggleConnectionSettings);
document.getElementById("host").addEventListener("input", updateHost);
document.getElementById("port").addEventListener("input", updatePort);
document.getElementById("connect").addEventListener("click", reconnectToWebSocketImmediately);

//////
// Start
populateHostPort();
connectToWebsocket();
document.getElementById("input").focus();

ReactDOM.render(

Hello, world!
,
  document.getElementById('conversation')
);
<commit_msg>Switch conversation to React<commit_after>'use strict';

//////
// Imports
import React from 'react';
import ReactDOM from 'react-dom';
var request = require('request');
var settings = require('electron-settings');
var WebSocketClient = require('websocket').client;

//////
// Global variables
var active_connection = undefined;
var host = settings.get("host", "localhost")
var port = settings.get("port", "8080")
var client = new WebSocketClient();
var connectionCooldown = 0;
var connectionTimeout = undefined;
var conversation = []

//////
// Components
const Message = function(props){
  return (

{props.text}

      {props.user != "info" &&

{props.time}

      }

  )
}

const Conversation = function(props){
  return (

        {props.items.map(item => (
          <Message text={item["text"]} user={item["user"]} time={item["time"]}></Message>
        ))}

  )
}

//////
// Functions
var displayMessage = function(message, sender){
  // Add new message to the conversation
  conversation.push({
    "text": message,
    "user": sender,
    "time": new Date().toTimeString().replace(/.*(\d{2}:\d{2}):\d{2}.*/, "$1")
  })

  // Render the conversation
  ReactDOM.render(
    <Conversation items={conversation}></Conversation>,
    document.getElementById("conversation")
  );

  // Scroll down to show new messages
  window.scrollTo(0, document.body.scrollHeight);
}

var getUrl = function(host, port) {
  return `http://${host}:${port}/connector/websocket`
}

var updateStatusIndicator = function(status){
  var status_indicator = document.getElementById("status-indicator")
  status_indicator.setAttribute('class', status)
}

var updateTooltipText = function(text){
  var tooltip = document.getElementById("status-indicator-tooltip")
  tooltip.innerHTML = text
}

var flashTooltip = function(){
  document.getElementById("status-indicator-tooltip")
    .setAttribute('class', 'active')
  setTimeout(function(){
    document.getElementById("status-indicator-tooltip")
      .setAttribute('class', '')
  }, 1000);
}

var sendUserMessage = function(){
  document.getElementById("input").focus();
  var user_message = document.getElementById("input").value
  if (active_connection && active_connection.connected) {
    if (user_message != ""){
      document.getElementById("input").value = ""
      displayMessage(user_message, "user")
      sendMessageToSocket(active_connection, user_message);
    }
  } else {
    flashTooltip()
  }
}

var connectToWebsocket = function() {
  updateTooltipText('connecting')
  request.post(getUrl(host, port), function(error, response, body){
    if (error){
      console.log(error)
      updateTooltipText('disconnected')
      reconnectToWebSocket()
    } else {
      var socket = JSON.parse(body)["socket"]
      client.connect(`ws://${host}:${port}/connector/websocket/${socket}`);
    }
  })
}

var reconnectToWebSocket = function() {
  if (active_connection && active_connection.connected) {
    active_connection.close()
  }
  if (connectionTimeout){
    clearTimeout(connectionTimeout);
  }
  console.log(`Reconnecting in ${connectionCooldown} seconds.`)
  backoffCooldown()
  connectionTimeout = setTimeout(connectToWebsocket, connectionCooldown * 1000);
}

var reconnectToWebSocketImmediately = function() {
  resetCooldown();
  reconnectToWebSocket();
}

var resetCooldown = function() {
  connectionCooldown = 0;
}

var backoffCooldown = function(){
    if (connectionCooldown <1 ) {
      connectionCooldown = 1;
    } else if (connectionCooldown < 60){
      connectionCooldown = connectionCooldown * 2
    }
}

var sendMessageToSocket = function(connection, message) {
  if (connection.connected) {
      connection.sendUTF(message);
  } else {
      console.log("Unable to send message")
  }
}

var handleSocketConnection = function(connection) {
  active_connection = connection;
  resetCooldown();
  console.log('WebSocket Client Connected');
  hideConnectionSettings();
  updateStatusIndicator('active');
  updateTooltipText('connected');
  displayMessage('connected', 'info');

  connection.on('error', handleSocketError);
  connection.on('close', handleSocketClose);
  connection.on('message', handleSocketMessage);
}

var handleSocketFailedConnection = function(error) {
  console.log('Connect Error: ' + error.toString());
  reconnectToWebSocket();
}

var handleSocketMessage = function(message) {
  if (message.type === 'utf8') {
      displayMessage(message.utf8Data, "bot");
  }
}

var handleSocketClose = function() {
  console.log('echo-protocol Connection Closed');
  updateStatusIndicator('inactive')
  updateTooltipText('disconnected')
  reconnectToWebSocket()
  displayMessage('disconnected', 'info')
}

var handleSocketError = function(error) {
  console.log("Connection Error: " + error.toString());
  updateStatusIndicator('inactive')
  updateTooltipText('disconnected')
  displayMessage('connection error', 'info')
}

var checkForReturnInPrompt = function(event) {
  event.preventDefault();
  if (event.keyCode == 13) {
      sendUserMessage();
  }
}

var toggleConnectionSettings = function() {
  var connectionSettings = document.getElementById("connection-settings")
  connectionSettings.classList.toggle('active');
}

var hideConnectionSettings = function() {
  var connectionSettings = document.getElementById("connection-settings")
  connectionSettings.classList.remove('active');
}

var updateHost = function(event) {
  settings.set("host", event.target.value);
  host = settings.get("host", "localhost");
  reconnectToWebSocketImmediately();
}

var updatePort = function(event) {
  settings.set("port", event.target.value);
  host = settings.get("port", "localhost");
  reconnectToWebSocketImmediately();
}

var populateHostPort = function() {
  if (settings.get("host", false)){
    document.getElementById("host").value = settings.get("host");
  }
  if (settings.get("port", false)){
    document.getElementById("port").value = settings.get("port");
  }
}

//////
// Event listeners
client.on('connect', handleSocketConnection);
client.on('connectFailed', handleSocketFailedConnection);
document.getElementById("send").addEventListener("click", sendUserMessage);
document.getElementById("input").addEventListener("keyup", checkForReturnInPrompt);
document.getElementById("status-indicator").addEventListener("click", toggleConnectionSettings);
document.getElementById("host").addEventListener("input", updateHost);
document.getElementById("port").addEventListener("input", updatePort);
document.getElementById("connect").addEventListener("click", reconnectToWebSocketImmediately);

//////
// Start
populateHostPort();
connectToWebsocket();
document.getElementById("input").focus();
<|endoftext|>


<commit_before>const express = require('express');
const fs = require('fs');
const helmet = require('helmet');
const morgan = require('morgan');
const uuid = require('uuid');
const config = require('./config');
const rfs = require('rotating-file-stream');

// App and loaded modules.
const app = express();

const HTTP_OK_CODE = 200;
const HTTP_ERROR_CODE = 400;
const HTTP_TOOLARGE_CODE = 413;
const HTTP_INTERNALERROR_CODE = 500;

// Enable cross-origin ressource sharing.
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  res.setHeader('Content-Type', 'application/json');
  next();
});

const args = config.cliArgs;
app.use(express.json({limit: args.limit}));
app.use(express.urlencoded({extended: true, limit: args.limit}));

const accessLogStream = rfs.createStream(args.logdir + '/access.log', {
  compress: 'gzip',
  size: args.logsize
});

app.use(morgan('combined', {stream: accessLogStream}));

app.use(helmet());

app.use((err, req, res, next) => {
  if (
    err instanceof SyntaxError &&
    err.status === HTTP_ERROR_CODE &&
    'body' in err
  ) {
    const message =
      'Invalid JSON object in request, please add vehicles and jobs or shipments to the object body';
    console.log(now() + ': ' + JSON.stringify(message));
    res.status(HTTP_ERROR_CODE);
    res.send({
      code: config.vroomErrorCodes.input,
      error: message
    });
  }
});

// Simple date generator for console output.
const now = function() {
  const date = new Date();
  return date.toUTCString();
};

const fileExists = function(filePath) {
  try {
    return fs.statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
};

// Callback for size and some input validity checks.
const sizeCheckCallback = function(maxLocationNumber, maxVehicleNumber) {
  return function(req, res, next) {
    const hasJobs = 'jobs' in req.body;
    const hasShipments = 'shipments' in req.body;

    const correctInput = (hasJobs || hasShipments) && 'vehicles' in req.body;
    if (!correctInput) {
      const message =
        'Invalid JSON object in request, please add vehicles and jobs or shipments to the object body';
      console.error(now() + ': ' + JSON.stringify(message));
      res.status(HTTP_ERROR_CODE);
      res.send({
        code: config.vroomErrorCodes.input,
        error: message
      });
      return;
    }

    let nbLocations = 0;
    if (hasJobs) {
      nbLocations += req.body.jobs.length;
    }
    if (hasShipments) {
      nbLocations += 2 * req.body.shipments.length;
    }

    if (nbLocations > maxLocationNumber) {
      const message = [
        'Too many locations (',
        nbLocations,
        ') in query, maximum is set to',
        maxLocationNumber
      ].join(' ');
      console.error(now() + ': ' + JSON.stringify(message));
      res.status(HTTP_TOOLARGE_CODE);
      res.send({
        code: config.vroomErrorCodes.tooLarge,
        error: message
      });
      return;
    }
    if (req.body.vehicles.length > maxVehicleNumber) {
      const vehicles = req.body.vehicles.length;
      const message = [
        'Too many vehicles (',
        vehicles,
        ') in query, maximum is set to',
        maxVehicleNumber
      ].join(' ');
      console.error(now() + ': ' + JSON.stringify(message));
      res.status(HTTP_TOOLARGE_CODE);
      res.send({
        code: config.vroomErrorCodes.tooLarge,
        error: message
      });
      return;
    }
    next();
  };
};

// Cli wrapper and associated callback.
const spawn = require('child_process').spawn;

const vroomCommand = args.path + 'vroom';
const options = [];
options.push('-r', args.router);
if (args.router !== 'libosrm') {
  const routingServers = config.routingServers;
  for (const profileName in routingServers[args.router]) {
    const profile = routingServers[args.router][profileName];
    if ('host' in profile && 'port' in profile) {
      options.push('-a', profileName + ':' + profile.host);
      options.push('-p', profileName + ':' + profile.port);
    } else {
      console.error(
        "Incomplete configuration: profile '" +
          profileName +
          "' requires 'host' and 'port'."
      );
    }
  }
}
if (args.geometry) {
  options.push('-g');
}

const execCallback = function(req, res) {
  const reqOptions = options.slice();

  // Geometry Retrieving
  if (
    !args.geometry &&
    args.override &&
    'options' in req.body &&
    'g' in req.body.options &&
    req.body.options.g
  ) {
    reqOptions.push('-g');
  }

  // ETA Mode Retrieving
  if (
    !args.etamode &&
    args.override &&
    'options' in req.body &&
    'c' in req.body.options &&
    req.body.options.c
  ) {
    reqOptions.push('-c');
  }

  // Threads Retrieving
  let nbThreads = args.threads;
  if (
    args.override &&
    'options' in req.body &&
    't' in req.body.options &&
    typeof req.body.options.t == 'number'
  ) {
    nbThreads = req.body.options.t;
  }
  reqOptions.push('-t ' + nbThreads);

  // Exploration Level Retrieving
  let explorationLevel = args.explore;
  if (
    args.override &&
    'options' in req.body &&
    'x' in req.body.options &&
    typeof req.body.options.x == 'number'
  ) {
    explorationLevel = req.body.options.x;
  }
  reqOptions.push('-x ' + explorationLevel);

  const timestamp = Math.floor(Date.now() / 1000); //eslint-disable-line
  const fileName = args.logdir + '/' + timestamp + '_' + uuid.v1() + '.json';
  try {
    fs.writeFileSync(fileName, JSON.stringify(req.body));
  } catch (err) {
    console.error(now() + ': ' + err);

    res.status(HTTP_INTERNALERROR_CODE);
    res.send({
      code: config.vroomErrorCodes.internal,
      error: 'Internal error'
    });
    return;
  }

  reqOptions.push('-i ' + fileName);

  const vroom = spawn(vroomCommand, reqOptions, {shell: true});

  // Handle errors.
  vroom.on('error', err => {
    const message = ['Unknown internal error', err].join(': ');
    console.error(now() + ': ' + JSON.stringify(message));
    res.status(HTTP_INTERNALERROR_CODE);
    res.send({
      code: config.vroomErrorCodes.internal,
      error: message
    });
  });

  vroom.stderr.on('data', data => {
    console.error(now() + ': ' + data.toString());
  });

  // Handle solution. The temporary solution variable is required as
  // we also want to adjust the status that is only retrieved with
  // 'exit', after data is written in stdout.
  let solution = '';

  vroom.stdout.on('data', data => {
    solution += data.toString();
  });

  vroom.on('close', (code, signal) => {
    switch (code) {
      case config.vroomErrorCodes.ok:
        res.status(HTTP_OK_CODE);
        break;
      case config.vroomErrorCodes.internal:
        // Internal error.
        res.status(HTTP_INTERNALERROR_CODE);
        break;
      case config.vroomErrorCodes.input:
        // Input error.
        res.status(HTTP_ERROR_CODE);
        break;
      case config.vroomErrorCodes.routing:
        // Routing error.
        res.status(HTTP_INTERNALERROR_CODE);
        break;
      default:
        // Required for e.g. vroom crash or missing command in $PATH.
        res.status(HTTP_INTERNALERROR_CODE);
        solution = {
          code: config.vroomErrorCodes.internal,
          error: 'Internal error'
        };
    }
    res.send(solution);

    if (fileExists(fileName)) {
      fs.unlinkSync(fileName);
    }
  });
};

app.post(args.baseurl, [
  sizeCheckCallback(args.maxlocations, args.maxvehicles),
  execCallback
]);

// set the health endpoint with some small problem
app.get(args.baseurl + 'health', (req, res) => {
  const vroom = spawn(
    vroomCommand,
    ['-i', './healthchecks/vroom_custom_matrix.json'],
    {shell: true}
  );

  let msg = 'healthy';
  let status = HTTP_OK_CODE;

  vroom.on('error', () => {
    // only called when vroom not in cliArgs.path or PATH
    msg = 'vroom is not in $PATH, check cliArgs.path in config.yml';
    status = HTTP_INTERNALERROR_CODE;
  });

  vroom.stderr.on('data', err => {
    // called when vroom throws an error and sends the error message back
    msg = err.toString();
    status = HTTP_INTERNALERROR_CODE;
  });

  vroom.on('close', code => {
    if (code !== config.vroomErrorCodes.ok) {
      console.error(`${now()}: ${msg}`);
    }
    res.status(status).send();
  });
});

const server = app.listen(args.port, () => {
  console.log('vroom-express listening on port ' + args.port + '!');
});

server.setTimeout(args.timeout);
<commit_msg>Adding possibility to add ETA Mode in option's arg (like -g, -x, -t)<commit_after>const express = require('express');
const fs = require('fs');
const helmet = require('helmet');
const morgan = require('morgan');
const uuid = require('uuid');
const config = require('./config');
const rfs = require('rotating-file-stream');

// App and loaded modules.
const app = express();

const HTTP_OK_CODE = 200;
const HTTP_ERROR_CODE = 400;
const HTTP_TOOLARGE_CODE = 413;
const HTTP_INTERNALERROR_CODE = 500;

// Enable cross-origin ressource sharing.
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  res.setHeader('Content-Type', 'application/json');
  next();
});

const args = config.cliArgs;
app.use(express.json({limit: args.limit}));
app.use(express.urlencoded({extended: true, limit: args.limit}));

const accessLogStream = rfs.createStream(args.logdir + '/access.log', {
  compress: 'gzip',
  size: args.logsize
});

app.use(morgan('combined', {stream: accessLogStream}));

app.use(helmet());

app.use((err, req, res, next) => {
  if (
    err instanceof SyntaxError &&
    err.status === HTTP_ERROR_CODE &&
    'body' in err
  ) {
    const message =
      'Invalid JSON object in request, please add vehicles and jobs or shipments to the object body';
    console.log(now() + ': ' + JSON.stringify(message));
    res.status(HTTP_ERROR_CODE);
    res.send({
      code: config.vroomErrorCodes.input,
      error: message
    });
  }
});

// Simple date generator for console output.
const now = function() {
  const date = new Date();
  return date.toUTCString();
};

const fileExists = function(filePath) {
  try {
    return fs.statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
};

// Callback for size and some input validity checks.
const sizeCheckCallback = function(maxLocationNumber, maxVehicleNumber) {
  return function(req, res, next) {
    const hasJobs = 'jobs' in req.body;
    const hasShipments = 'shipments' in req.body;

    const correctInput = (hasJobs || hasShipments) && 'vehicles' in req.body;
    if (!correctInput) {
      const message =
        'Invalid JSON object in request, please add vehicles and jobs or shipments to the object body';
      console.error(now() + ': ' + JSON.stringify(message));
      res.status(HTTP_ERROR_CODE);
      res.send({
        code: config.vroomErrorCodes.input,
        error: message
      });
      return;
    }

    let nbLocations = 0;
    if (hasJobs) {
      nbLocations += req.body.jobs.length;
    }
    if (hasShipments) {
      nbLocations += 2 * req.body.shipments.length;
    }

    if (nbLocations > maxLocationNumber) {
      const message = [
        'Too many locations (',
        nbLocations,
        ') in query, maximum is set to',
        maxLocationNumber
      ].join(' ');
      console.error(now() + ': ' + JSON.stringify(message));
      res.status(HTTP_TOOLARGE_CODE);
      res.send({
        code: config.vroomErrorCodes.tooLarge,
        error: message
      });
      return;
    }
    if (req.body.vehicles.length > maxVehicleNumber) {
      const vehicles = req.body.vehicles.length;
      const message = [
        'Too many vehicles (',
        vehicles,
        ') in query, maximum is set to',
        maxVehicleNumber
      ].join(' ');
      console.error(now() + ': ' + JSON.stringify(message));
      res.status(HTTP_TOOLARGE_CODE);
      res.send({
        code: config.vroomErrorCodes.tooLarge,
        error: message
      });
      return;
    }
    next();
  };
};

// Cli wrapper and associated callback.
const spawn = require('child_process').spawn;

const vroomCommand = args.path + 'vroom';
const options = [];
options.push('-r', args.router);
if (args.router !== 'libosrm') {
  const routingServers = config.routingServers;
  for (const profileName in routingServers[args.router]) {
    const profile = routingServers[args.router][profileName];
    if ('host' in profile && 'port' in profile) {
      options.push('-a', profileName + ':' + profile.host);
      options.push('-p', profileName + ':' + profile.port);
    } else {
      console.error(
        "Incomplete configuration: profile '" +
          profileName +
          "' requires 'host' and 'port'."
      );
    }
  }
}
if (args.geometry) {
  options.push('-g');
}

const execCallback = function(req, res) {
  const reqOptions = options.slice();

  // Geometry Retrieving
  if (
    !args.geometry &&
    args.override &&
    'options' in req.body &&
    'g' in req.body.options &&
    req.body.options.g
  ) {
    reqOptions.push('-g');
  }

  // ETA Mode Retrieving
  if (
    args.override &&
    'options' in req.body &&
    'c' in req.body.options &&
    req.body.options.c
  ) {
    reqOptions.push('-c');
  }

  // Threads Retrieving
  let nbThreads = args.threads;
  if (
    args.override &&
    'options' in req.body &&
    't' in req.body.options &&
    typeof req.body.options.t == 'number'
  ) {
    nbThreads = req.body.options.t;
  }
  reqOptions.push('-t ' + nbThreads);

  // Exploration Level Retrieving
  let explorationLevel = args.explore;
  if (
    args.override &&
    'options' in req.body &&
    'x' in req.body.options &&
    typeof req.body.options.x == 'number'
  ) {
    explorationLevel = req.body.options.x;
  }
  reqOptions.push('-x ' + explorationLevel);

  const timestamp = Math.floor(Date.now() / 1000); //eslint-disable-line
  const fileName = args.logdir + '/' + timestamp + '_' + uuid.v1() + '.json';
  try {
    fs.writeFileSync(fileName, JSON.stringify(req.body));
  } catch (err) {
    console.error(now() + ': ' + err);

    res.status(HTTP_INTERNALERROR_CODE);
    res.send({
      code: config.vroomErrorCodes.internal,
      error: 'Internal error'
    });
    return;
  }

  reqOptions.push('-i ' + fileName);

  const vroom = spawn(vroomCommand, reqOptions, {shell: true});

  // Handle errors.
  vroom.on('error', err => {
    const message = ['Unknown internal error', err].join(': ');
    console.error(now() + ': ' + JSON.stringify(message));
    res.status(HTTP_INTERNALERROR_CODE);
    res.send({
      code: config.vroomErrorCodes.internal,
      error: message
    });
  });

  vroom.stderr.on('data', data => {
    console.error(now() + ': ' + data.toString());
  });

  // Handle solution. The temporary solution variable is required as
  // we also want to adjust the status that is only retrieved with
  // 'exit', after data is written in stdout.
  let solution = '';

  vroom.stdout.on('data', data => {
    solution += data.toString();
  });

  vroom.on('close', (code, signal) => {
    switch (code) {
      case config.vroomErrorCodes.ok:
        res.status(HTTP_OK_CODE);
        break;
      case config.vroomErrorCodes.internal:
        // Internal error.
        res.status(HTTP_INTERNALERROR_CODE);
        break;
      case config.vroomErrorCodes.input:
        // Input error.
        res.status(HTTP_ERROR_CODE);
        break;
      case config.vroomErrorCodes.routing:
        // Routing error.
        res.status(HTTP_INTERNALERROR_CODE);
        break;
      default:
        // Required for e.g. vroom crash or missing command in $PATH.
        res.status(HTTP_INTERNALERROR_CODE);
        solution = {
          code: config.vroomErrorCodes.internal,
          error: 'Internal error'
        };
    }
    res.send(solution);

    if (fileExists(fileName)) {
      fs.unlinkSync(fileName);
    }
  });
};

app.post(args.baseurl, [
  sizeCheckCallback(args.maxlocations, args.maxvehicles),
  execCallback
]);

// set the health endpoint with some small problem
app.get(args.baseurl + 'health', (req, res) => {
  const vroom = spawn(
    vroomCommand,
    ['-i', './healthchecks/vroom_custom_matrix.json'],
    {shell: true}
  );

  let msg = 'healthy';
  let status = HTTP_OK_CODE;

  vroom.on('error', () => {
    // only called when vroom not in cliArgs.path or PATH
    msg = 'vroom is not in $PATH, check cliArgs.path in config.yml';
    status = HTTP_INTERNALERROR_CODE;
  });

  vroom.stderr.on('data', err => {
    // called when vroom throws an error and sends the error message back
    msg = err.toString();
    status = HTTP_INTERNALERROR_CODE;
  });

  vroom.on('close', code => {
    if (code !== config.vroomErrorCodes.ok) {
      console.error(`${now()}: ${msg}`);
    }
    res.status(status).send();
  });
});

const server = app.listen(args.port, () => {
  console.log('vroom-express listening on port ' + args.port + '!');
});

server.setTimeout(args.timeout);
<|endoftext|>


<commit_before>/* @flow */
import {
  curry,
  compose,
  Either,
  map,
  merge,
  prop,
  sequence,
  update
} from './utils/'

const { Right, Left } = Either

const makePredicate = ([predFn, e]) => a => predFn(a) ? Right(a) : Left(e)
const runPredicates = ([input, validations]) =>
  map(predFn => predFn(input), map(makePredicate, validations))

const validator = map(compose(sequence(Either.of), runPredicates))
const makeValidationObject = merge((k, l, r) => [l, r])
const Validate = compose(validator, makeValidationObject)

export default Validate
<commit_msg>Restructured validation handling<commit_after>/* @flow */
import {
  curry,
  compose,
  Either,
  map,
  merge,
  prop,
  sequence,
  update
} from './utils/'

const { Right, Left } = Either

const identity = r => r

const makePredicate = ([predFn, e]) => (a, all) => predFn(a, all) ? Right(a) : Left(e)
const runPredicates = ([input, validations, all]) =>
  map(predFn => predFn(input, all), map(makePredicate, validations))

const validator = transform => map(compose(transform, sequence(Either.of), runPredicates))
const makeValidationObject =(input, validations) => merge((k, l, r) => [l, r, input], input, validations)
const createValidation = (transform = identity) => compose(validator(transform), makeValidationObject)

export default createValidation
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: true }));
const HashMap = require('hashmap');
const dirname = fs.realpathSync('./');

var teams = new HashMap();
var ingredients = JSON.parse(fs.readFileSync(__dirname + '/data/ingredients.json', 'utf8'));

// build api endpoint for getting js files
fs.readdirSync(dirname + '/src/js').forEach(file => {
    app.get('/js/' + file, function (req, res) {
        res.status(200).sendFile(dirname + '/src/js/' + file);
    });
});

// build api endpoint for getting bootstrap files
fs.readdirSync(dirname + '/node_modules/bootstrap/dist/css').forEach(file => {
    app.get('/css/' + file, function (req, res) {
        res.status(200).sendFile(dirname + '/node_modules/bootstrap/dist/css/' + file);
    });
});

app.get('/', function (req, res) {
    res.status(200).sendFile(__dirname + "/index.htm");
});

app.get('/teams', function (req, res) {
    res.status(200).sendFile(__dirname + "/teamPage.html");
});

app.get('/pizzas/amount', function (req, res) {
    let teamname = req.body.teamname;
    if (teamname != undefined) {
        let amount = {
            amount: teams.get(teamname).pizza_count
        };
        res.status(200).end(JSON.stringify(amount));
    } else {
        res.sendStatus(400);
    }
});

app.get('pizzas/ingredients', function (req, res) {
    if (ingredients.length > 0) {
        res.status(200).end(JSON.stringify(ingredients));
    } else {
        res.sendStatus(404);
    }
});

app.get('/pizzas/suggestions', function (req, res) {
    let teamname = req.body.teamname;
    if (teamname != undefined) {
        // TODO
    } else {
        res.sendStatus(400);
    }
});

app.post('/sessioncreate/', function (req, res) {
    let teamname = req.body.teamname;
    if (teamname != undefined) {
        console.log('Creating team ' + teamname);
        let data = {
            teamsize: {
                number: 0,
                type: 'Not defined'
            },
            pizza_count: 0
        };
        teams.set(teamname, data);
        res.status(200).sendFile(__dirname + '/js/teamPage.js');
        res.redirect(302, '/teams/?teamname=' + teamname);
        res.status(200).end(JSON.stringify({ teamname: teamname }));
    } else {
        console.log('Creating Team: Failure because of undefined teamname!');
        res.sendStatus(400);
    }
});

app.post('/teams/teamsize/', function (req, res) {
    let count = req.body.count;
    let type = req.body.type;
    let teamname = req.body.teamname;
    if (count != undefined && type != undefined && teamname != undefined) {
        console.log('Update team size for team' + teamname);
        let pizza_count = computeNumberOfPizzas(count, type);
        let data = {
            teamsize: {
                number: count,
                type: type
            },
            pizza_count: pizza_count
        };
        teams.set(teamname, data);
        res.redirect(302, '/teams/?teamname=' + teamname);
        res.status(200).end(JSON.stringify({ teamname: teamname, data: data }));
    } else {
        console.log('Update team size failed');
        res.sendStatus(400);
    }
});

function computeNumberOfPizzas(count, type) {
    return 4; // TODO
};

function saveToFile(data, filename = "tfmap.log", exitOnWrite = false) {
    let folderName = "results";
    if (!fs.existsSync(folderName)) {
        fs.mkdirSync(folderName);
    }
    fs.writeFileSync('results/' + filename, data);
    console.log("The file was saved!");
    if (exitOnWrite) {
        process.exit(0);
    }
}

var server = app.listen(8081, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("REST server listening at http://%s:%s", host, port);
});<commit_msg>Bugfix for ingredients<commit_after>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
app.use(bodyParser.urlencoded({ extended: true }));
const HashMap = require('hashmap');
const dirname = fs.realpathSync('./');

var teams = new HashMap();
var ingredients = JSON.parse(fs.readFileSync(__dirname + '/data/ingredients.json', 'utf8'));
var suggestions = new HashMap();

// build api endpoint for getting js files
fs.readdirSync(dirname + '/src/js').forEach(file => {
    app.get('/js/' + file, function (req, res) {
        res.status(200).sendFile(dirname + '/src/js/' + file);
    });
});

// build api endpoint for getting bootstrap files
fs.readdirSync(dirname + '/node_modules/bootstrap/dist/css').forEach(file => {
    app.get('/css/' + file, function (req, res) {
        res.status(200).sendFile(dirname + '/node_modules/bootstrap/dist/css/' + file);
    });
});

app.get('/', function (req, res) {
    res.status(200).sendFile(__dirname + "/index.htm");
});

app.get('/teams', function (req, res) {
    res.status(200).sendFile(__dirname + "/teamPage.html");
});

app.get('/pizzas/amount', function (req, res) {
    let teamname = req.body.teamname;
    if (teamname != undefined) {
        let amount = {
            amount: teams.get(teamname).pizza_count
        };
        res.status(200).end(JSON.stringify(amount));
    } else {
        res.sendStatus(400);
    }
});

app.get('/pizzas/ingredients', function (req, res) {
    if (ingredients.length > 0) {
        res.status(200).end(JSON.stringify(ingredients));
    } else {
        res.sendStatus(404);
    }
});

app.get('/pizzas/suggestions', function (req, res) {
    let teamname = req.body.teamname;
    if (teamname != undefined) {
        // TODO
    } else {
        res.sendStatus(400);
    }
});

app.post('/sessioncreate/', function (req, res) {
    let teamname = req.body.teamname;
    if (teamname != undefined) {
        console.log('Creating team ' + teamname);
        let data = {
            teamsize: {
                number: 0,
                type: 'Not defined'
            },
            pizza_count: 0
        };
        teams.set(teamname, data);
        res.status(200).sendFile(__dirname + '/js/teamPage.js');
        res.redirect(302, '/teams/?teamname=' + teamname);
        res.status(200).end(JSON.stringify({ teamname: teamname }));
    } else {
        console.log('Creating Team: Failure because of undefined teamname!');
        res.sendStatus(400);
    }
});

app.post('/teams/teamsize/', function (req, res) {
    let count = req.body.count;
    let type = req.body.type;
    let teamname = req.body.teamname;
    if (count != undefined && type != undefined && teamname != undefined) {
        console.log('Update team size for team' + teamname);
        let pizza_count = computeNumberOfPizzas(count, type);
        let data = {
            teamsize: {
                number: count,
                type: type
            },
            pizza_count: pizza_count
        };
        teams.set(teamname, data);
        res.redirect(302, '/teams/?teamname=' + teamname);
        res.status(200).end(JSON.stringify({ teamname: teamname, data: data }));
    } else {
        console.log('Update team size failed');
        res.sendStatus(400);
    }
});

function computeNumberOfPizzas(count, type) {
    return 4; // TODO
};

function saveToFile(data, filename = "tfmap.log", exitOnWrite = false) {
    let folderName = "results";
    if (!fs.existsSync(folderName)) {
        fs.mkdirSync(folderName);
    }
    fs.writeFileSync('results/' + filename, data);
    console.log("The file was saved!");
    if (exitOnWrite) {
        process.exit(0);
    }
}

var server = app.listen(8081, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("REST server listening at http://%s:%s", host, port);
});<|endoftext|>


<commit_before>import getStatus from './lib/methods/getStatus.js';
import { droppedOffBySender, availableForPickup } from './lib/methods/events.js';
import {
  getPackageWeight,
  identifier,
  deliveryMethod,
  hasRetourOptions,
  receiver,
} from './lib/methods/packageInfo.js';
import {
  sourcePostalPoint,
  destinationPostalPoint,
  destinationAsAddress,
  openingHours,
  destinationCoordinate,
} from './lib/methods/postalPointOptions.js';
import {
  availableFrom,
  availableTo,
  availableFromTo,
  attemptedDelivery,
  actualDelivery,
} from './lib/methods/homeDeliveryOptions.js';

export default {
  getStatus,

  droppedOffBySender,
  availableForPickup,

  getPackageWeight,
  deliveryMethod,
  identifier,
  hasRetourOptions,
  receiver,

  sourcePostalPoint,
  destinationPostalPoint,
  destinationAsAddress,
  openingHours,
  destinationCoordinate,

  availableFrom,
  availableTo,
  availableFromTo,
  attemptedDelivery,
  actualDelivery,
};
<commit_msg>:hammer: Have module instantiate first, declare methods as properties  #7<commit_after>/* eslint-disable max-len */
import getStatus from './lib/methods/getStatus.js';
import { droppedOffBySender, availableForPickup } from './lib/methods/events.js';
import { getPackageWeight, identifier, deliveryMethod, hasRetourOptions, receiver } from './lib/methods/packageInfo.js';
import { sourcePostalPoint, destinationPostalPoint, destinationAsAddress, openingHours, destinationCoordinate } from './lib/methods/postalPointOptions.js';
import { availableFrom, availableTo, availableFromTo, attemptedDelivery, actualDelivery } from './lib/methods/homeDeliveryOptions.js';
/* eslint-enable max-len */

export default ID => {
  if (!ID) throw new TypeError(`An ID needs to be passed`);

  return {
    getStatus: () => getStatus(ID),

    droppedOffBySender: () => droppedOffBySender(ID),
    availableForPickup: () => availableForPickup(ID),

    getPackageWeight: () => getPackageWeight(ID),
    deliveryMethod: () => deliveryMethod(ID),
    identifier: () => identifier(ID),
    hasRetourOptions: () => hasRetourOptions(ID),
    receiver: () => receiver(ID),

    sourcePostalPoint: () => sourcePostalPoint(ID),
    destinationPostalPoint: () => destinationPostalPoint(ID),
    destinationAsAddress: () => destinationAsAddress(ID),
    openingHours: day => openingHours(ID, day),
    destinationCoordinate: () => destinationCoordinate(ID),

    availableFrom: () => availableFrom(ID),
    availableTo: () => availableTo(ID),
    availableFromTo: () => availableFromTo(ID),
    attemptedDelivery: () => attemptedDelivery(ID),
    actualDelivery: () => actualDelivery(ID),
  };
};
<|endoftext|>


<commit_before>$(function(){
	$('table.statistics-confusion').each(function(){
		var tableNode=$(this);
		var tbodyNode=tableNode.children('tbody');
		var rcDir=0; // outcome headers on top?
		var rcOrd=[0,0]; // outcomes swapped?, conditions swapped?
		var isExpanded=false;
		//function wikipedia(block,url) {
		//	if (url===undefined) url="https://en.wikipedia.org/wiki/"+block.replace(/ /g,'_');
		function wikipedia(block) {
			url="https://en.wikipedia.org/wiki/"+block.replace(/ /g,'_');
			return ""+block+"";
		}
		var TP="TP";
		var FP="FP";
		var FN="FN";
		var TN="TN";
		var expandData=[
			[ // new row
				"
("+FN+"+"+TN+")/("+TP+"+"+FP+"+"+FN+"+"+TN+")
",
				"
"+wikipedia("False negative rate")+"

FNR="+FN+"/("+TP+"+"+FN+")
",
				"
"+wikipedia("False positive rate")+"

FPR="+FP+"/("+FP+"+"+TN+")
",
				"
Overall error rate

("+FP+"+"+FN+")/("+TP+"+"+FP+"+"+FN+"+"+TN+")
",
				"" // not used
			],[ // new col
				"
("+FP+"+"+TN+")/("+TP+"+"+FP+"+"+FN+"+"+TN+")
",
				"
"+wikipedia("False discovery rate")+"

FDR="+FP+"/("+TP+"+"+FP+")
",
				"
"+wikipedia("False omission rate")+"

FOR="+FN+"/("+FN+"+"+TN+")
",
				"
"+wikipedia("Positive likelihood ratio")+"

(LR+)=TPR/FPR
",
				"
"+wikipedia("Negative likelihood ratio")+"

(LR-)=FNR/TNR
"
			]
		];
		function expandTable() {
			function addCell(callOrd,dir,i,insertNormal,insertSwapped) {
				function makeCell() {
					var j=i;
					if ((j==1 || j==2) && rcOrd[rcDir^dir^1]) {
						j^=1^2;
					} else if (callOrd && (j==3 || j==4) && rcOrd[rcDir^dir^1]) {
						j^=3^4;
					}
					var cellHtml=expandData[rcDir^dir][j];
					return $("").html(cellHtml);
				}
				var cell=makeCell();
				var swap=rcOrd[rcDir^dir]&1;
				if (i==1 || i==2) swap=((i-1)^rcOrd[0]^rcOrd[1])&1;
				if (swap) {
					insertSwapped(cell);
				} else {
					insertNormal(cell);
				}
			}
			function addCol(callOrd) {
				tbodyNode.children().each(function(i){
					var oldRow=$(this);
					addCell(callOrd,1,i,function(newCell){
						oldRow.append(newCell);
					},function(newCell){
						oldRow.children().eq(-1).before(newCell);
					});
				});
			}
			function addRow(callOrd) {
				var newRow=$("
");
				tbodyNode.append(newRow);
				tbodyNode.children().eq(-2).children().each(function(i){
					var oldCell=$(this);
					addCell(callOrd,0,i,function(newCell){
						newRow.append(newCell);
					},function(newCell){
						oldCell.before(newCell);
						newRow.append(oldCell);
					});
				});
			}
			if (rcDir) {
				addCol(0);
				addRow(1);
			} else {
				addRow(0);
				addCol(1);
			}
			isExpanded=true;
			tableNode.find('button.add-r, button.add-c').text('−').attr('title','contract table').off().click(contractTable);
		}
		function contractTable() {
			function removeCol(callOrd) {
				tbodyNode.children().each(function(i){
					var oldRow=$(this);
					oldRow.children().eq(-1).remove();
				});
			}
			function removeRow(callOrd) {
				tbodyNode.children().eq(-1).remove();
			}
			if (rcDir) {
				removeRow(1);
				removeCol(0);
			} else {
				removeCol(1);
				removeRow(0);
			}
			isExpanded=false;
			tableNode.find('button.add-r, button.add-c').text('−').attr('title','expand table').off().click(expandTable);
		}
		function swapChildren(node,i) {
			var c1=node.children().eq(i);
			var c2=node.children().eq(i+1);
			c1.before(c2);
		}
		tableNode.children('caption').append(
			$("<button type='button' class='swap-rc' title='swap rows and columns'>↻</button>").click(function(){
				rcDir^=1;
				var n=tbodyNode.children().length;
				for (var i=0;i<n;i++) {
					for (var j=0;j<i;j++) {
						var c1=tbodyNode.children().eq(i).children().eq(j);
						var c2=tbodyNode.children().eq(j).children().eq(i);
						var c2p=c2.prev();
						c1.after(c2);
						c2p.after(c1);
					}
				}
			})
		).append(
			$("<button type='button' class='swap-c' title='swap columns'>↔</button>").click(function(){
				rcOrd[rcDir^1]^=1;
				tbodyNode.children().each(function(){
					swapChildren($(this),1);
					if (!isExpanded) return;
					swapChildren($(this),3);
				});
			})
		).append(
			$("<button type='button' class='swap-r' title='swap rows'>↕</button>").click(function(){
				rcOrd[rcDir]^=1;
				swapChildren(tbodyNode,1);
				if (!isExpanded) return;
				swapChildren(tbodyNode,3);
			})
		).append(
			$("<button type='button' class='add-c' title='expand table'>+</button>").click(expandTable)
		).append(
			$("<button type='button' class='add-r' title='expand table'>+</button>").click(expandTable)
		)
	});
});
<commit_msg>correct table contraction<commit_after>$(function(){
	$('table.statistics-confusion').each(function(){
		var tableNode=$(this);
		var tbodyNode=tableNode.children('tbody');
		var rcDir=0; // outcome headers on top?
		var rcOrd=[0,0]; // outcomes swapped?, conditions swapped?
		var isExpanded=false;
		//function wikipedia(block,url) {
		//	if (url===undefined) url="https://en.wikipedia.org/wiki/"+block.replace(/ /g,'_');
		function wikipedia(block) {
			url="https://en.wikipedia.org/wiki/"+block.replace(/ /g,'_');
			return ""+block+"";
		}
		var TP="TP";
		var FP="FP";
		var FN="FN";
		var TN="TN";
		var expandData=[
			[ // new row
				"
("+FN+"+"+TN+")/("+TP+"+"+FP+"+"+FN+"+"+TN+")
",
				"
"+wikipedia("False negative rate")+"

FNR="+FN+"/("+TP+"+"+FN+")
",
				"
"+wikipedia("False positive rate")+"

FPR="+FP+"/("+FP+"+"+TN+")
",
				"
Overall error rate

("+FP+"+"+FN+")/("+TP+"+"+FP+"+"+FN+"+"+TN+")
",
				"" // not used
			],[ // new col
				"
("+FP+"+"+TN+")/("+TP+"+"+FP+"+"+FN+"+"+TN+")
",
				"
"+wikipedia("False discovery rate")+"

FDR="+FP+"/("+TP+"+"+FP+")
",
				"
"+wikipedia("False omission rate")+"

FOR="+FN+"/("+FN+"+"+TN+")
",
				"
"+wikipedia("Positive likelihood ratio")+"

(LR+)=TPR/FPR
",
				"
"+wikipedia("Negative likelihood ratio")+"

(LR-)=FNR/TNR
"
			]
		];
		function expandTable() {
			function addCell(callOrd,dir,i,insertNormal,insertSwapped) {
				function makeCell() {
					var j=i;
					if ((j==1 || j==2) && rcOrd[rcDir^dir^1]) {
						j^=1^2;
					} else if (callOrd && (j==3 || j==4) && rcOrd[rcDir^dir^1]) {
						j^=3^4;
					}
					var cellHtml=expandData[rcDir^dir][j];
					return $("").html(cellHtml);
				}
				var cell=makeCell();
				var swap=rcOrd[rcDir^dir]&1;
				if (i==1 || i==2) swap=((i-1)^rcOrd[0]^rcOrd[1])&1;
				if (swap) {
					insertSwapped(cell);
				} else {
					insertNormal(cell);
				}
			}
			function addCol(callOrd) {
				tbodyNode.children().each(function(i){
					var oldRow=$(this);
					addCell(callOrd,1,i,function(newCell){
						oldRow.append(newCell);
					},function(newCell){
						oldRow.children().eq(-1).before(newCell);
					});
				});
			}
			function addRow(callOrd) {
				var newRow=$("
");
				tbodyNode.append(newRow);
				tbodyNode.children().eq(-2).children().each(function(i){
					var oldCell=$(this);
					addCell(callOrd,0,i,function(newCell){
						newRow.append(newCell);
					},function(newCell){
						oldCell.before(newCell);
						newRow.append(oldCell);
					});
				});
			}
			if (rcDir) {
				addCol(0);
				addRow(1);
			} else {
				addRow(0);
				addCol(1);
			}
			isExpanded=true;
			tableNode.find('button.add-r, button.add-c').text('−').attr('title','contract table').off().click(contractTable);
		}
		function contractTable() {
			function removeCol(callOrd) {
				var dir=1;
				tbodyNode.children().each(function(i){
					var swap=rcOrd[rcDir^dir]&1;
					if (i==1 || i==2) swap=((i-1)^rcOrd[0]^rcOrd[1])&1;
					var oldRow=$(this);
					oldRow.children().eq(swap?-2:-1).remove();
				});
			}
			function removeRow(callOrd) {
				var dir=0;
				var oldRow=tbodyNode.children().eq(-2);
				var newRow=tbodyNode.children().eq(-1);
				newRow.children().each(function(i){
					var swap=rcOrd[rcDir^dir]&1;
					if (i==1 || i==2) swap=((i-1)^rcOrd[0]^rcOrd[1])&1;
					if (swap) {
						var oldCell=$(this);
						var newCell=oldRow.children().eq(i);
						newCell.after(oldCell).remove();
					}
				});
				newRow.remove();
			}
			if (rcDir) {
				removeRow(1);
				removeCol(0);
			} else {
				removeCol(1);
				removeRow(0);
			}
			isExpanded=false;
			tableNode.find('button.add-r, button.add-c').text('+').attr('title','expand table').off().click(expandTable);
		}
		function swapChildren(node,i) {
			var c1=node.children().eq(i);
			var c2=node.children().eq(i+1);
			c1.before(c2);
		}
		tableNode.children('caption').append(
			$("<button type='button' class='swap-rc' title='swap rows and columns'>↻</button>").click(function(){
				rcDir^=1;
				var n=tbodyNode.children().length;
				for (var i=0;i<n;i++) {
					for (var j=0;j<i;j++) {
						var c1=tbodyNode.children().eq(i).children().eq(j);
						var c2=tbodyNode.children().eq(j).children().eq(i);
						var c2p=c2.prev();
						c1.after(c2);
						c2p.after(c1);
					}
				}
			})
		).append(
			$("<button type='button' class='swap-c' title='swap columns'>↔</button>").click(function(){
				rcOrd[rcDir^1]^=1;
				tbodyNode.children().each(function(){
					swapChildren($(this),1);
					if (!isExpanded) return;
					swapChildren($(this),3);
				});
			})
		).append(
			$("<button type='button' class='swap-r' title='swap rows'>↕</button>").click(function(){
				rcOrd[rcDir]^=1;
				swapChildren(tbodyNode,1);
				if (!isExpanded) return;
				swapChildren(tbodyNode,3);
			})
		).append(
			$("<button type='button' class='add-c' title='expand table'>+</button>").click(expandTable)
		).append(
			$("<button type='button' class='add-r' title='expand table'>+</button>").click(expandTable)
		)
	});
});
<|endoftext|>


<commit_before>

import React from 'react';
import { Router, browserHistory } from 'react-router';

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import ReactDom from 'react-dom';

import thunk from 'redux-thunk';
import reducers from '../reducers';

import routes from './routes';

export const store = createStore(reducers,
    applyMiddleware(thunk)
  );

ReactDom.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>, document.querySelector('.app')
);

<commit_msg>new-file-app.json<commit_after>

import React from 'react';
import { Router, browserHistory } from 'react-router';

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import ReactDom from 'react-dom';

import thunk from 'redux-thunk';
import reducers from '../reducers';

import routes from './routes';

 const store = createStore(reducers,
    applyMiddleware(thunk)
  );

ReactDom.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>, document.querySelector('.app')
);

<|endoftext|>


<commit_before>import { NativeModules, Platform } from 'react-native'

const { RNBranch } = NativeModules

import createBranchUniversalObject from './branchUniversalObject'
import BranchEvent from './BranchEvent'
import BranchSubscriber from './BranchSubscriber'

const packageFile = require('./../package.json')
export const VERSION = packageFile.version

class Branch {
  key = null;
  _checkCachedEvents = true;
  _debug = false;

  constructor(options = {}) {
    if (options.debug) this._debug = true

    console.info('Initializing react-native-branch v. ' + VERSION)
  }

  subscribe(options) {
    if (typeof options === 'function') {
      /*
       * Support for legacy API, passing a single callback function:
       * branch.subscribe(({params, error, uri}) => { ... }). This is
       * the same as the onOpenComplete callback.
       */
      options = {
        onOpenComplete: options,
      }
    }

    /*
     * You can specify checkCachedEvents in the subscribe options to control
     * this per subscriber.
     */
    if (!('checkCachedEvents' in options)) {
      options.checkCachedEvents = this._checkCachedEvents
    }
    this._checkCachedEvents = false

    const subscriber = new BranchSubscriber(options)
    subscriber.subscribe()

    return subscriber.unsubscribe
  }

  skipCachedEvents() {
    /*** Sets to ignore cached events. ***/
    this._checkCachedEvents = false
  }

  /*** Tracking related methods ***/
  disableTracking = (disable) => RNBranch.disableTracking(disable)
  isTrackingDisabled = RNBranch.isTrackingDisabled

  /*** RNBranch singleton methods ***/
  setDebug = () => { throw 'setDebug() is not supported in the RN SDK. For other solutions, please see https://rnbranch.app.link/setDebug' }
  getLatestReferringParams = (synchronous = false) => RNBranch.getLatestReferringParams(synchronous)
  getFirstReferringParams = RNBranch.getFirstReferringParams
  setIdentity = (identity) => RNBranch.setIdentity(identity)
  setRequestMetadata = (key, value) => {
    console.info('[Branch] setRequestMetadata has limitations when called from JS.  Some network calls are made prior to the JS layer being available, those calls will not have the metadata.')
    return RNBranch.setRequestMetadataKey(key, value)
  }
  logout = RNBranch.logout
  userCompletedAction = (event, state = {}) => RNBranch.userCompletedAction(event, state)
  getShortUrl = RNBranch.getShortUrl
  sendCommerceEvent = (revenue, metadata) => {
    console.info('[Branch] sendCommerceEvent is deprecated. Please use the BranchEvent class instead.')
    return RNBranch.sendCommerceEvent('' + revenue, metadata)
  }
  openURL = (url, options = {}) => {
    return Platform.select({
      android: () => RNBranch.openURL(url, options),
      ios: () => RNBranch.openURL(url)
    })()
  }

  /*** Referral Methods ***/
  redeemRewards = (amount, bucket) => RNBranch.redeemRewards(amount, bucket)
  loadRewards = (bucket) => RNBranch.loadRewards(bucket)
  getCreditHistory = RNBranch.getCreditHistory

  /*** BranchUniversalObject ***/
  createBranchUniversalObject = createBranchUniversalObject
}

export { Branch, BranchEvent, BranchSubscriber }
export default new Branch()
<commit_msg>Return an appropriate function for unsubscribe.<commit_after>import { NativeModules, Platform } from 'react-native'

const { RNBranch } = NativeModules

import createBranchUniversalObject from './branchUniversalObject'
import BranchEvent from './BranchEvent'
import BranchSubscriber from './BranchSubscriber'

const packageFile = require('./../package.json')
export const VERSION = packageFile.version

class Branch {
  key = null;
  _checkCachedEvents = true;
  _debug = false;

  constructor(options = {}) {
    if (options.debug) this._debug = true

    console.info('Initializing react-native-branch v. ' + VERSION)
  }

  subscribe(options) {
    if (typeof options === 'function') {
      /*
       * Support for legacy API, passing a single callback function:
       * branch.subscribe(({params, error, uri}) => { ... }). This is
       * the same as the onOpenComplete callback.
       */
      options = {
        onOpenComplete: options,
      }
    }

    /*
     * You can specify checkCachedEvents in the subscribe options to control
     * this per subscriber.
     */
    if (!('checkCachedEvents' in options)) {
      options.checkCachedEvents = this._checkCachedEvents
    }
    this._checkCachedEvents = false

    const subscriber = new BranchSubscriber(options)
    subscriber.subscribe()

    return () => subscriber.unsubscribe()
  }

  skipCachedEvents() {
    /*** Sets to ignore cached events. ***/
    this._checkCachedEvents = false
  }

  /*** Tracking related methods ***/
  disableTracking = (disable) => RNBranch.disableTracking(disable)
  isTrackingDisabled = RNBranch.isTrackingDisabled

  /*** RNBranch singleton methods ***/
  setDebug = () => { throw 'setDebug() is not supported in the RN SDK. For other solutions, please see https://rnbranch.app.link/setDebug' }
  getLatestReferringParams = (synchronous = false) => RNBranch.getLatestReferringParams(synchronous)
  getFirstReferringParams = RNBranch.getFirstReferringParams
  setIdentity = (identity) => RNBranch.setIdentity(identity)
  setRequestMetadata = (key, value) => {
    console.info('[Branch] setRequestMetadata has limitations when called from JS.  Some network calls are made prior to the JS layer being available, those calls will not have the metadata.')
    return RNBranch.setRequestMetadataKey(key, value)
  }
  logout = RNBranch.logout
  userCompletedAction = (event, state = {}) => RNBranch.userCompletedAction(event, state)
  getShortUrl = RNBranch.getShortUrl
  sendCommerceEvent = (revenue, metadata) => {
    console.info('[Branch] sendCommerceEvent is deprecated. Please use the BranchEvent class instead.')
    return RNBranch.sendCommerceEvent('' + revenue, metadata)
  }
  openURL = (url, options = {}) => {
    return Platform.select({
      android: () => RNBranch.openURL(url, options),
      ios: () => RNBranch.openURL(url)
    })()
  }

  /*** Referral Methods ***/
  redeemRewards = (amount, bucket) => RNBranch.redeemRewards(amount, bucket)
  loadRewards = (bucket) => RNBranch.loadRewards(bucket)
  getCreditHistory = RNBranch.getCreditHistory

  /*** BranchUniversalObject ***/
  createBranchUniversalObject = createBranchUniversalObject
}

export { Branch, BranchEvent, BranchSubscriber }
export default new Branch()
<|endoftext|>