<commit_before>import parser from 'posthtml-parser';
import render from 'posthtml-render';
import rules from './rules.js';
import attrs from './attrs.js';
import tags from './tags.js';
import deepmerge from 'deepmerge';
import {js} from 'js-beautify';

const optionsDefault = {
  rules,
  attrs,
  tags,
  sync: false,
  mini: {
    removeAttribute: false
  },
  jsBeautifyOptions: {
    indent_size: 2, // eslint-disable-line camelcase
    jslint_happy: true // eslint-disable-line camelcase
  }
};

const nodeHasContent = (node, callback) => {
  if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'content')) {
    node.content = callback(node.content);
  }
};

const nodeHasAttrs = (node, callback) => {
  if (
    typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'attrs')
  ) {
    node.attrs = Object.keys(node.attrs).reduce(callback, {});
  }
};

const getIndent = (level, {indent, eol}) => {
  const indentString = typeof indent === 'number' ? ' '.repeat(indent) : '\t';

  return `${eol}${indentString.repeat(level)}`;
};

const clean = tree => parser(render(tree))
  .filter(node => {
    return typeof node === 'object' || (typeof node === 'string' && (node.trim().length !== 0 || /doctype/gi.test(node)));
  })
  .map(node => {
    if (Object.prototype.hasOwnProperty.call(node, 'content')) {
      node.content = clean(node.content);
    }

    return typeof node === 'string' ? node.trim() : node;
  });

const parseConditional = tree => {
  return tree.map(node => {
    nodeHasContent(node, parseConditional);

    if (typeof node === 'string' && /<!(?:--)?\[[\s\S]*?]>/.test(node)) {
      const conditional = /^((?:<[^>]+>)?<!(?:--)?\[[\s\S]*?]>(?:<!)?(?:-->)?)([\s\S]*?)(<!(?:--<!)?\[[\s\S]*?](?:--)?>)$/
        .exec(node)
        .slice(1)
        .map((node, index) => index === 1 ? {tag: 'conditional-content', content: clean(parser(node))} : node);

      return {
        tag: 'conditional',
        content: conditional
      };
    }

    return node;
  });
};

const renderConditional = tree => {
  return tree.reduce((previousValue, node) => {
    if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'content')) {
      node.content = renderConditional(node.content);
    }

    if (typeof node === 'object' && node.tag === 'conditional') {
      return [...previousValue, ...node.content];
    }

    if (typeof node === 'object' && node.tag === 'conditional-content') {
      node.tag = false;
      return [...previousValue, node];
    }

    return [...previousValue, node];
  }, []);
};

const indent = (tree, {rules: {indent, eol, blankLines}}) => {
  const setIndent = (tree, level = 0) => tree.reduce((previousValue, node, index) => {
    if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'content')) {
      node.content = setIndent(node.content, ++level);
      --level;
    }

    if (tree.length === 1 && typeof tree[index] === 'string') {
      return [...previousValue, node];
    }

    if (level === 0 && (tree.length - 1) === index && tree.length > 1) {
      return [...previousValue, getIndent(level, {indent, eol}), node];
    }

    if (level === 0 && (tree.length - 1) === index && tree.length === 1) {
      return [...previousValue, node];
    }

    if (level === 0 && index === 0) {
      return [...previousValue, node, blankLines];
    }

    if (level === 0) {
      return [...previousValue, getIndent(level, {indent, eol}), node, blankLines];
    }

    if ((tree.length - 1) === index) {
      return [...previousValue, getIndent(level, {indent, eol}), node, getIndent(--level, {indent, eol})];
    }

    if (typeof node === 'string' && /<!(?:--)?\[endif]*?]>/.test(node)) {
      return [...previousValue, getIndent(level, {indent, eol}), node, blankLines];
    }

    if (typeof node === 'string' && /<!(?:--)?\[[\s\S]*?]>/.test(node)) {
      return [...previousValue, getIndent(level, {indent, eol}), node];
    }

    if (node.tag === false) {
      return [...previousValue, ...node.content.slice(0, -1)];
    }

    return [...previousValue, getIndent(level, {indent, eol}), node, blankLines];
  }, []);

  return setIndent(tree);
};

const attributesBoolean = (tree, {attrs: {boolean}}) => {
  const removeAttributeValue = tree => tree.map(node => {
    nodeHasContent(node, removeAttributeValue);

    if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'attrs')) {
      Object.keys(node.attrs).forEach(key => {
        node.attrs[key] = boolean.includes(key) ||
                    node.attrs[key]
                      .trim()
                      .split(' ')
                      .filter(value => value.length)
                      .join(' ');
      });
    }

    return node;
  });

  return removeAttributeValue(tree);
};

const lowerElementName = (tree, {tags}) => {
  tags = tags.map(({name}) => name);

  const bypass = tree => tree.map(node => {
    nodeHasContent(node, bypass);

    if (
      typeof node === 'object' &&
            Object.prototype.hasOwnProperty.call(node, 'tag') &&
            tags.includes(node.tag.toLowerCase())
    ) {
      node.tag = node.tag.toLowerCase();
    }

    return node;
  });

  return bypass(tree);
};

const lowerAttributeName = tree => {
  const bypass = tree => tree.map(node => {
    nodeHasContent(node, bypass);

    nodeHasAttrs(node, (previousValue, key) => Object.assign(previousValue, {[key.toLowerCase()]: node.attrs[key]}));

    return node;
  });

  return bypass(tree);
};

const eof = (tree, {rules: {eof}}) => eof ? [...tree, eof] : tree;

const mini = (tree, {mini}) => {
  const bypass = tree => tree.map(node => {
    nodeHasContent(node, bypass);

    nodeHasAttrs(node, (previousValue, key) => {
      if (
        mini.removeAttribute &&
        mini.removeAttribute === 'empty' &&
        node.attrs[key].length === 0
      ) {
        return previousValue;
      }

      return Object.assign(previousValue, {[key.toLowerCase()]: node.attrs[key]});
    });

    return node;
  });

  return bypass(tree);
};

const jsPrettier = (tree, {rules: {indent, eol}, jsBeautifyOptions}) => {
  let level = 0;
  const prettier = tree => tree.map(node => {
    ++level;
    nodeHasContent(node, prettier);

    if (node.tag === 'script') {
      node.content = ['\n', js(node.content.join(''), {
        ...jsBeautifyOptions,
        indent_level: level // eslint-disable-line camelcase
      }), getIndent(--level, {indent, eol})];
    }

    --level;
    return node;
  });

  return prettier(tree);
};

const beautify = (tree, options) => [
  clean,
  parseConditional,
  renderConditional,
  indent,
  jsPrettier,
  lowerElementName,
  lowerAttributeName,
  attributesBoolean,
  eof,
  mini
].reduce((previousValue, module) => typeof module === 'function' ? module(previousValue, options) : previousValue, tree);

const normalize = (node, options) => {
  let {tree, api} = Object.keys(node).reduce(
    (scope, key) => {
      scope[Number.isNaN(Number(key)) ? 'api' : 'tree'][key] = node[key];

      return scope;
    },
    {tree: [], api: []}
  );

  tree = beautify(tree, deepmerge(optionsDefault, options));

  for (const [key, value] of Object.entries(api)) {
    tree[key] = value;
  }

  return tree;
};

export default (options = {}) => node => {
  if (!Array.isArray(node)) {
    throw new TypeError('tree is not Array');
  }

  if (node.length === 0) {
    return node;
  }

  return normalize(node, options);
};
<commit_msg>fix: script witchout content, close #237<commit_after>import parser from 'posthtml-parser';
import render from 'posthtml-render';
import rules from './rules.js';
import attrs from './attrs.js';
import tags from './tags.js';
import deepmerge from 'deepmerge';
import {js} from 'js-beautify';

const optionsDefault = {
  rules,
  attrs,
  tags,
  sync: false,
  mini: {
    removeAttribute: false
  },
  jsBeautifyOptions: {
    indent_size: 2, // eslint-disable-line camelcase
    jslint_happy: true // eslint-disable-line camelcase
  }
};

const nodeHasContent = (node, callback) => {
  if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'content')) {
    node.content = callback(node.content);
  }
};

const nodeHasAttrs = (node, callback) => {
  if (
    typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'attrs')
  ) {
    node.attrs = Object.keys(node.attrs).reduce(callback, {});
  }
};

const getIndent = (level, {indent, eol}) => {
  const indentString = typeof indent === 'number' ? ' '.repeat(indent) : '\t';

  return `${eol}${indentString.repeat(level)}`;
};

const clean = tree => parser(render(tree))
  .filter(node => {
    return typeof node === 'object' || (typeof node === 'string' && (node.trim().length !== 0 || /doctype/gi.test(node)));
  })
  .map(node => {
    if (Object.prototype.hasOwnProperty.call(node, 'content')) {
      node.content = clean(node.content);
    }

    return typeof node === 'string' ? node.trim() : node;
  });

const parseConditional = tree => {
  return tree.map(node => {
    nodeHasContent(node, parseConditional);

    if (typeof node === 'string' && /<!(?:--)?\[[\s\S]*?]>/.test(node)) {
      const conditional = /^((?:<[^>]+>)?<!(?:--)?\[[\s\S]*?]>(?:<!)?(?:-->)?)([\s\S]*?)(<!(?:--<!)?\[[\s\S]*?](?:--)?>)$/
        .exec(node)
        .slice(1)
        .map((node, index) => index === 1 ? {tag: 'conditional-content', content: clean(parser(node))} : node);

      return {
        tag: 'conditional',
        content: conditional
      };
    }

    return node;
  });
};

const renderConditional = tree => {
  return tree.reduce((previousValue, node) => {
    if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'content')) {
      node.content = renderConditional(node.content);
    }

    if (typeof node === 'object' && node.tag === 'conditional') {
      return [...previousValue, ...node.content];
    }

    if (typeof node === 'object' && node.tag === 'conditional-content') {
      node.tag = false;
      return [...previousValue, node];
    }

    return [...previousValue, node];
  }, []);
};

const indent = (tree, {rules: {indent, eol, blankLines}}) => {
  const setIndent = (tree, level = 0) => tree.reduce((previousValue, node, index) => {
    if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'content')) {
      node.content = setIndent(node.content, ++level);
      --level;
    }

    if (tree.length === 1 && typeof tree[index] === 'string') {
      return [...previousValue, node];
    }

    if (level === 0 && (tree.length - 1) === index && tree.length > 1) {
      return [...previousValue, getIndent(level, {indent, eol}), node];
    }

    if (level === 0 && (tree.length - 1) === index && tree.length === 1) {
      return [...previousValue, node];
    }

    if (level === 0 && index === 0) {
      return [...previousValue, node, blankLines];
    }

    if (level === 0) {
      return [...previousValue, getIndent(level, {indent, eol}), node, blankLines];
    }

    if ((tree.length - 1) === index) {
      return [...previousValue, getIndent(level, {indent, eol}), node, getIndent(--level, {indent, eol})];
    }

    if (typeof node === 'string' && /<!(?:--)?\[endif]*?]>/.test(node)) {
      return [...previousValue, getIndent(level, {indent, eol}), node, blankLines];
    }

    if (typeof node === 'string' && /<!(?:--)?\[[\s\S]*?]>/.test(node)) {
      return [...previousValue, getIndent(level, {indent, eol}), node];
    }

    if (node.tag === false) {
      return [...previousValue, ...node.content.slice(0, -1)];
    }

    return [...previousValue, getIndent(level, {indent, eol}), node, blankLines];
  }, []);

  return setIndent(tree);
};

const attributesBoolean = (tree, {attrs: {boolean}}) => {
  const removeAttributeValue = tree => tree.map(node => {
    nodeHasContent(node, removeAttributeValue);

    if (typeof node === 'object' && Object.prototype.hasOwnProperty.call(node, 'attrs')) {
      Object.keys(node.attrs).forEach(key => {
        node.attrs[key] = boolean.includes(key) ||
                    node.attrs[key]
                      .trim()
                      .split(' ')
                      .filter(value => value.length)
                      .join(' ');
      });
    }

    return node;
  });

  return removeAttributeValue(tree);
};

const lowerElementName = (tree, {tags}) => {
  tags = tags.map(({name}) => name);

  const bypass = tree => tree.map(node => {
    nodeHasContent(node, bypass);

    if (
      typeof node === 'object' &&
            Object.prototype.hasOwnProperty.call(node, 'tag') &&
            tags.includes(node.tag.toLowerCase())
    ) {
      node.tag = node.tag.toLowerCase();
    }

    return node;
  });

  return bypass(tree);
};

const lowerAttributeName = tree => {
  const bypass = tree => tree.map(node => {
    nodeHasContent(node, bypass);

    nodeHasAttrs(node, (previousValue, key) => Object.assign(previousValue, {[key.toLowerCase()]: node.attrs[key]}));

    return node;
  });

  return bypass(tree);
};

const eof = (tree, {rules: {eof}}) => eof ? [...tree, eof] : tree;

const mini = (tree, {mini}) => {
  const bypass = tree => tree.map(node => {
    nodeHasContent(node, bypass);

    nodeHasAttrs(node, (previousValue, key) => {
      if (
        mini.removeAttribute &&
        mini.removeAttribute === 'empty' &&
        node.attrs[key].length === 0
      ) {
        return previousValue;
      }

      return Object.assign(previousValue, {[key.toLowerCase()]: node.attrs[key]});
    });

    return node;
  });

  return bypass(tree);
};

const jsPrettier = (tree, {rules: {indent, eol}, jsBeautifyOptions}) => {
  let level = 0;
  const prettier = tree => tree.map(node => {
    ++level;
    nodeHasContent(node, prettier);

    if (node.tag === 'script') {
      const content = node.content ?
        ['\n', js(node.content.join(''), {
          ...jsBeautifyOptions,
          indent_level: level // eslint-disable-line camelcase
        }), getIndent(--level, {indent, eol})] :
        [''];
      node.content = content;
    }

    --level;
    return node;
  });

  return prettier(tree);
};

const beautify = (tree, options) => [
  clean,
  parseConditional,
  renderConditional,
  indent,
  jsPrettier,
  lowerElementName,
  lowerAttributeName,
  attributesBoolean,
  eof,
  mini
].reduce((previousValue, module) => typeof module === 'function' ? module(previousValue, options) : previousValue, tree);

const normalize = (node, options) => {
  let {tree, api} = Object.keys(node).reduce(
    (scope, key) => {
      scope[Number.isNaN(Number(key)) ? 'api' : 'tree'][key] = node[key];

      return scope;
    },
    {tree: [], api: []}
  );

  tree = beautify(tree, deepmerge(optionsDefault, options));

  for (const [key, value] of Object.entries(api)) {
    tree[key] = value;
  }

  return tree;
};

export default (options = {}) => node => {
  if (!Array.isArray(node)) {
    throw new TypeError('tree is not Array');
  }

  if (node.length === 0) {
    return node;
  }

  return normalize(node, options);
};
<|endoftext|>


<commit_before>export function register ( tagName, Component, props = [] ) {
	class SvelteElement extends HTMLElement {
		constructor () {
			super();

			this.target = this;
			this.data = {};
		}

		connectedCallback () {
			props.forEach( prop => {
				const value = this[ prop ];
				if ( value !== undefined ) {
					this.data[ prop ] = this[ prop ];
				}
			});

			this.instance = new Component({
				target: this.target,
				data: this.data
			});

			props.forEach( prop => {
				this.instance.observe( prop, value => {
					this.setAttribute( prop, value );
				});
			});
		}

		detachedCallback () {
			this.instance.destroy();
			this.instance = null;
		}

		attributeChangedCallback ( attr, oldValue, newValue ) {
			const value = isNaN( newValue ) ? newValue : +newValue;
			this.data[ attr ] = value;
			if ( this.instance ) this.instance.set({ [ attr ]: value });
		}
	}

	Object.defineProperty( SvelteElement, 'observedAttributes', {
		get () {
			return props;
		}
	});

	props.forEach( prop => {
		Object.defineProperty( SvelteElement.prototype, prop, {
			get () {
				return this.instance ? this.instance.get( prop ) : this.data[ prop ];
			},

			set ( value ) {
				this.data[ prop ] = value;
				if ( this.instance ) this.instance.set({ [ prop ]: value });
			}
		});
	});

	customElements.define( tagName, SvelteElement );
	return SvelteElement;
}<commit_msg> re-enable ShadowDOM, use open<commit_after>export function register ( tagName, Component, props = [] ) {
	class SvelteElement extends HTMLElement {
		constructor () {
			super();

			this.target = this.attachShadow({ mode: 'open' });
			this.data = {};
		}

		connectedCallback () {
			props.forEach( prop => {
				const value = this[ prop ];
				if ( value !== undefined ) {
					this.data[ prop ] = this[ prop ];
				}
			});

			this.instance = new Component({
				target: this.target,
				data: this.data
			});

			props.forEach( prop => {
				this.instance.observe( prop, value => {
					this.setAttribute( prop, value );
				});
			});
		}

		detachedCallback () {
			this.instance.destroy();
			this.instance = null;
		}

		attributeChangedCallback ( attr, oldValue, newValue ) {
			const value = isNaN( newValue ) ? newValue : +newValue;
			this.data[ attr ] = value;
			if ( this.instance ) this.instance.set({ [ attr ]: value });
		}
	}

	Object.defineProperty( SvelteElement, 'observedAttributes', {
		get () {
			return props;
		}
	});

	props.forEach( prop => {
		Object.defineProperty( SvelteElement.prototype, prop, {
			get () {
				return this.instance ? this.instance.get( prop ) : this.data[ prop ];
			},

			set ( value ) {
				this.data[ prop ] = value;
				if ( this.instance ) this.instance.set({ [ prop ]: value });
			}
		});
	});

	customElements.define( tagName, SvelteElement );
	return SvelteElement;
}<|endoftext|>


<commit_before>import {
  join as joinPath,
} from "path";

import {
  default as glob,
} from "glob";

export class UnusedFilesWebpackPlugin {
  constructor(options = {}) {
    this.options = {
      pattern: `**/*.*`,
      ...options,
      failOnUnused: options.failOnUnused === true,
    };

    this.globOptions = {
      ignore: `node_modules/**/*`,
      ...options.globOptions,
    };
  }

  apply(compiler) {
    compiler.plugin(`after-emit`, (compilation, done) =>
      this._applyAfterEmit(compiler, compilation, done)
    );
  }

  _applyAfterEmit(compiler, compilation, done) {
    const globOptions = this._getGlobOptions(compiler);
    const fileDepsMap = this._getFileDepsMap(compilation);
    const absolutePathResolver = it => joinPath(globOptions.cwd, it);

    glob(this.options.pattern, globOptions, (err, files) => {
      if (err) {
        compilation.errors.push(err);
        done();
        return;
      }
      const unused = files.filter(filepath =>
        !(absolutePathResolver(filepath) in fileDepsMap)
      );
      if (unused.length === 0) {
        done();
        return;
      }
      const error = new Error(`
UnusedFilesWebpackPlugin found some unused files:
${unused.join(`\n`)}`);

      if (this.options.failOnUnused) {
        compilation.errors.push(error);
      } else {
        compilation.warnings.push(error);
      }
      done();
    });
  }

  _getGlobOptions(compiler) {
    return {
      cwd: compiler.context,
      ...this.globOptions,
    };
  }

  _getFileDepsMap(compilation) {
    const fileDepsBy = compilation.fileDependencies.reduce((acc, usedFilepath) => ({
      ...acc,
      [usedFilepath]: usedFilepath,
    }), {});

    const { assets } = compilation;
    Object.keys(assets).forEach(assetRelpath => {
      const existsAt = assets[assetRelpath].existsAt;
      fileDepsBy[existsAt] = existsAt;
    });
    return fileDepsBy;
  }
}

export default UnusedFilesWebpackPlugin;
<commit_msg>fix(index.js): if bail is set, callback with error (#11)<commit_after>import {
  join as joinPath,
} from "path";

import {
  default as glob,
} from "glob";

export class UnusedFilesWebpackPlugin {
  constructor(options = {}) {
    this.options = {
      pattern: `**/*.*`,
      ...options,
      failOnUnused: options.failOnUnused === true,
    };

    this.globOptions = {
      ignore: `node_modules/**/*`,
      ...options.globOptions,
    };
  }

  apply(compiler) {
    compiler.plugin(`after-emit`, (compilation, done) =>
      this._applyAfterEmit(compiler, compilation, done)
    );
  }

  _applyAfterEmit(compiler, compilation, done) {
    const globOptions = this._getGlobOptions(compiler);
    const fileDepsMap = this._getFileDepsMap(compilation);
    const absolutePathResolver = it => joinPath(globOptions.cwd, it);

    const handleError = err => {
      if (compilation.bail) {
        done(err);
      } else {
        compilation.errors.push(err);
      }
    };

    glob(this.options.pattern, globOptions, (err, files) => {
      if (err) {
        handleError(err);
        return;
      }
      const unused = files.filter(filepath =>
        !(absolutePathResolver(filepath) in fileDepsMap)
      );
      if (unused.length === 0) {
        done();
        return;
      }
      const error = new Error(`
UnusedFilesWebpackPlugin found some unused files:
${unused.join(`\n`)}`);

      if (this.options.failOnUnused) {
        handleError(error);
      } else {
        compilation.warnings.push(error);
        done();
      }
    });
  }

  _getGlobOptions(compiler) {
    return {
      cwd: compiler.context,
      ...this.globOptions,
    };
  }

  _getFileDepsMap(compilation) {
    const fileDepsBy = compilation.fileDependencies.reduce((acc, usedFilepath) => ({
      ...acc,
      [usedFilepath]: usedFilepath,
    }), {});

    const { assets } = compilation;
    Object.keys(assets).forEach(assetRelpath => {
      const existsAt = assets[assetRelpath].existsAt;
      fileDepsBy[existsAt] = existsAt;
    });
    return fileDepsBy;
  }
}

export default UnusedFilesWebpackPlugin;
<|endoftext|>


<commit_before>var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var helmet = require('helmet');

// Config variables.
var VROOM_PATH = '';
var MAX_LOCATION_NUMBER = 50;
var ROUTE_GEOMETRY = false;
var USE_OSRM_V5 = true;
var ALLOW_OPTIONS_OVERRIDE = true; // -g only so far.

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

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

app.use(bodyParser.json());
app.use(morgan('combined'));
app.use(helmet());

// Callback for size and some input validity checks.
var cb_size_check = function (req, res, next){
  res.setHeader('Content-Type', 'application/json');

  var correct_input = ('jobs' in req.body)
      && ('vehicles' in req.body)
      && (req.body['vehicles'].length >= 1);

  if(!correct_input){
    res.send({code: 1, error: 'Invalid query.'});
    return;
  }

  var nb_locs = req.body['jobs'].length;
  if('start' in req.body['vehicles'][0]){
    nb_locs += 1;
  }
  if('end' in req.body['vehicles'][0]){
    nb_locs += 1;
  }
  if(nb_locs > MAX_LOCATION_NUMBER){
    console.log('Too many locs in query (' + nb_locs + ')');
    res.send({code: 1, error: 'Too many locations.'});
    return;
  }
  next();
}

// Cli wrapper and associated callback.
var exec = require('child_process').exec;

var command = VROOM_PATH + 'vroom ';
var options = '';
if(ROUTE_GEOMETRY){
  options += '-g ';
}
if(USE_OSRM_V5){
  // As of v5.1.0, profile name doesn't matter, so car will do until
  // it should be made into a variable.
  options += '-m car ';
}

var cb_exec = function (req, res){
  var req_options = '';
  if(!ROUTE_GEOMETRY && ALLOW_OPTIONS_OVERRIDE
     && 'options' in req.body && 'g' in req.body['options']
     && req.body['options']['g']){
    req_options = '-g ';
  }
  exec(command + options + req_options + '\'' + JSON.stringify(req.body) + '\'',
       // TODO find a better way to deal with big outputs.
       {'maxBuffer': 5000*1024},
       function(error, stdout, stderr){
         res.send(stdout);
         if(error !== null){
           console.log(error);
         }
       }
      );
}

app.post('/', [cb_size_check, cb_exec]);

app.listen(3000, function (){
  console.log('vroom-express listening on port 3000!');
});
<commit_msg>Add options for OSRM server address and port.<commit_after>var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var helmet = require('helmet');

// Config variables.
var VROOM_PATH = '';
var MAX_LOCATION_NUMBER = 50;
var ROUTE_GEOMETRY = false;
var USE_OSRM_V5 = true;
var OSRM_ADDRESS = "0.0.0.0";
var OSRM_PORT = "5000";
var ALLOW_OPTIONS_OVERRIDE = true; // -g only so far.

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

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

app.use(bodyParser.json());
app.use(morgan('combined'));
app.use(helmet());

// Callback for size and some input validity checks.
var cb_size_check = function (req, res, next){
  res.setHeader('Content-Type', 'application/json');

  var correct_input = ('jobs' in req.body)
      && ('vehicles' in req.body)
      && (req.body['vehicles'].length >= 1);

  if(!correct_input){
    res.send({code: 1, error: 'Invalid query.'});
    return;
  }

  var nb_locs = req.body['jobs'].length;
  if('start' in req.body['vehicles'][0]){
    nb_locs += 1;
  }
  if('end' in req.body['vehicles'][0]){
    nb_locs += 1;
  }
  if(nb_locs > MAX_LOCATION_NUMBER){
    console.log('Too many locs in query (' + nb_locs + ')');
    res.send({code: 1, error: 'Too many locations.'});
    return;
  }
  next();
}

// Cli wrapper and associated callback.
var exec = require('child_process').exec;

var command = VROOM_PATH + 'vroom ';
var options = '-a ' + OSRM_ADDRESS + ' -p ' + OSRM_PORT + ' ';
if(ROUTE_GEOMETRY){
  options += '-g ';
}
if(USE_OSRM_V5){
  // As of v5.1.0, profile name doesn't matter, so car will do until
  // it should be made into a variable.
  options += '-m car ';
}

var cb_exec = function (req, res){
  var req_options = '';
  if(!ROUTE_GEOMETRY && ALLOW_OPTIONS_OVERRIDE
     && 'options' in req.body && 'g' in req.body['options']
     && req.body['options']['g']){
    req_options = '-g ';
  }
  exec(command + options + req_options + '\'' + JSON.stringify(req.body) + '\'',
       // TODO find a better way to deal with big outputs.
       {'maxBuffer': 5000*1024},
       function(error, stdout, stderr){
         res.send(stdout);
         if(error !== null){
           console.log(error);
         }
       }
      );
}

app.post('/', [cb_size_check, cb_exec]);

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


<commit_before>'use strict';

module.exports = function () {
    // returns true
    return true;
};
<commit_msg>Update index.js<commit_after>'use strict';

module.exports = function () {
    // returns true
    // comment
    return true;
};
<|endoftext|>


<commit_before>import {asyncReplace, isArray, isString} from 'stc-helper';
import {isMaster} from 'cluster';
import PluginInvoke from 'stc-plugin-invoke';
import path from 'path';
/**
 * stc plugin abstract class
 */
export default class StcPlugin {
  /**
   * constructor
   */
  constructor(file, opts = {}){
    this.file = file;
    this.options = opts.options || {};
    this.stc = opts.stc;
    this.TokenType = this.stc.TokenType;
    //can not use ext in sub plugins
    this.ext = opts.ext || {};
  }
  /**
   * get file content
   */
  getContent(encoding){
    if(isMaster){
      return this.file.getContent(encoding);
    }
    return this.stc.cluster.invoke({
      method: 'getContent',
      args: [encoding],
      file: this.file.path,
      options: this.options
    });
  }
  /**
   * set file content
   */
  setContent(content){
    if(!isMaster){
      throw new Error('setContent method must be invoked in master');
    }
    this.file.setContent(content);
    return this;
  }
  /**
   * get file ast
   */
  async getAst(){

    if(isMaster){
      let clusterOpt = this.stc.config.cluster;
      if(this.file.hasAst() || clusterOpt === false){
        return this.file.getAst();
      }
      let content = await this.getContent('utf8');
      //get ast in worker parsed
      let ret = await this.stc.cluster.doTask({
        type: 'getAst',
        content,
        file: this.file.path
      });
      this.file.setAst(ret);
      return ret;
    }

    //get ast from master
    return this.stc.cluster.invoke({
      method: 'getAst',
      file: this.file.path,
      options: this.options
    });
  }
  /**
   * set ast
   */
  setAst(ast){
    if(!isMaster){
      throw new Error('setAst must be invoked in master');
    }
    this.file.setAst(ast);
    return this;
  }
  /**
   * add file dependence
   */
  addDependence(dependencies){
    if(!isMaster){
      throw new Error('addDependence must be invoked in master');
    }
    if(!isArray(dependencies)){
      dependencies = [dependencies];
    }
    dependencies = dependencies.map(item => {
      if(!isString(item)){
        return item;
      }
      let filepath = this.getResolvePath(item);
      let file = this.stc.resource.lookFile(filepath, this.file.path);
      if(!file){
        throw new Error(`file ${item} is not exist in ${this.file.path}`);
      }
      return file;
    });
    this.file.dependence.add(dependencies);
    return dependencies;
  }
  /**
   * get file dependence
   */
  getDependence(file = this.file){
    return file.dependence.get();
  }
  /**
   * add file
   */
  addFile(filepath, content){
    if(!isMaster){
      throw new Error('addFile must be invoked in master');
    }
    let resolvePath = this.getResolvePath(filepath);
    return this.stc.resource.addFile(resolvePath, content);
  }

  /**
   * get resolve path
   */
  getResolvePath(filepath){
    let currentFilePath = path.dirname(this.file.path);
    let resolvePath = path.resolve(currentFilePath, filepath);
    let currentPath = process.cwd() + path.sep;
    if(resolvePath.indexOf(currentPath) === 0){
      resolvePath = resolvePath.slice(currentPath.length);
    }
    return resolvePath;
  }

  /**
   * invoke self plugin
   */
  invokeSelf(file){
    return this.invokePlugin(this.constructor, file);
  }

  /**
   * invoke plugin
   */
  invokePlugin(plugin, file){
    let instance = new PluginInvoke(plugin, file, {
      stc: this.stc,
      options: this.options,
      ext: this.ext
    });
    return instance.run();
  }

  /**
   * async content replace
   * must be use RegExp
   */
  asyncReplace(content = '', replace, callback){
    return asyncReplace(content, replace, callback);
  }

  /**
   * run
   */
  run(){

  }
  /**
   * update
   */
  update(){

  }
}<commit_msg>set file default value in invokeSelf method<commit_after>import {asyncReplace, isArray, isString} from 'stc-helper';
import {isMaster} from 'cluster';
import PluginInvoke from 'stc-plugin-invoke';
import path from 'path';
/**
 * stc plugin abstract class
 */
export default class StcPlugin {
  /**
   * constructor
   */
  constructor(file, opts = {}){
    this.file = file;
    this.options = opts.options || {};
    this.stc = opts.stc;
    this.TokenType = this.stc.TokenType;
    //can not use ext in sub plugins
    this.ext = opts.ext || {};
  }
  /**
   * get file content
   */
  getContent(encoding){
    if(isMaster){
      return this.file.getContent(encoding);
    }
    return this.stc.cluster.invoke({
      method: 'getContent',
      args: [encoding],
      file: this.file.path,
      options: this.options
    });
  }
  /**
   * set file content
   */
  setContent(content){
    if(!isMaster){
      throw new Error('setContent method must be invoked in master');
    }
    this.file.setContent(content);
    return this;
  }
  /**
   * get file ast
   */
  async getAst(){

    if(isMaster){
      let clusterOpt = this.stc.config.cluster;
      if(this.file.hasAst() || clusterOpt === false){
        return this.file.getAst();
      }
      let content = await this.getContent('utf8');
      //get ast in worker parsed
      let ret = await this.stc.cluster.doTask({
        type: 'getAst',
        content,
        file: this.file.path
      });
      this.file.setAst(ret);
      return ret;
    }

    //get ast from master
    return this.stc.cluster.invoke({
      method: 'getAst',
      file: this.file.path,
      options: this.options
    });
  }
  /**
   * set ast
   */
  setAst(ast){
    if(!isMaster){
      throw new Error('setAst must be invoked in master');
    }
    this.file.setAst(ast);
    return this;
  }
  /**
   * add file dependence
   */
  addDependence(dependencies){
    if(!isMaster){
      throw new Error('addDependence must be invoked in master');
    }
    if(!isArray(dependencies)){
      dependencies = [dependencies];
    }
    dependencies = dependencies.map(item => {
      if(!isString(item)){
        return item;
      }
      let filepath = this.getResolvePath(item);
      let file = this.stc.resource.lookFile(filepath, this.file.path);
      if(!file){
        throw new Error(`file ${item} is not exist in ${this.file.path}`);
      }
      return file;
    });
    this.file.dependence.add(dependencies);
    return dependencies;
  }
  /**
   * get file dependence
   */
  getDependence(file = this.file){
    return file.dependence.get();
  }
  /**
   * add file
   */
  addFile(filepath, content){
    if(!isMaster){
      throw new Error('addFile must be invoked in master');
    }
    let resolvePath = this.getResolvePath(filepath);
    return this.stc.resource.addFile(resolvePath, content);
  }

  /**
   * get resolve path
   */
  getResolvePath(filepath){
    let currentFilePath = path.dirname(this.file.path);
    let resolvePath = path.resolve(currentFilePath, filepath);
    let currentPath = process.cwd() + path.sep;
    if(resolvePath.indexOf(currentPath) === 0){
      resolvePath = resolvePath.slice(currentPath.length);
    }
    return resolvePath;
  }

  /**
   * invoke self plugin
   */
  invokeSelf(file = this.file){
    return this.invokePlugin(this.constructor, file);
  }

  /**
   * invoke plugin
   */
  invokePlugin(plugin, file = this.file){
    let instance = new PluginInvoke(plugin, file, {
      stc: this.stc,
      options: this.options,
      ext: this.ext
    });
    return instance.run();
  }

  /**
   * async content replace
   * must be use RegExp
   */
  asyncReplace(content = '', replace, callback){
    return asyncReplace(content, replace, callback);
  }

  /**
   * run
   */
  run(){

  }
  /**
   * update
   */
  update(){

  }
}<|endoftext|>


<commit_before>import { createApp } from 'vue'
import { createRouter, createWebHistory, RouterView } from 'vue-router'
import store from './store'
import App from './App.vue'
// import Download from './components/pages/download'
import { createI18n } from 'vue-i18n-lite'

import localeRu from '@/assets/locales/ru'
import localeEn from '@/assets/locales/en'

const Index = () => import(/* webpackChunkName: "index" */'./components/pages/index/index')
const Converter = () => import(/* webpackChunkName: "converter" */'./components/pages/converter')

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/', component: Index,
    },
    // {
    // path: '/download', component: Download,
    // },
    {
      path: '/converter', component: Converter,
    },
    {
      path: '/converter/:raw', component: Converter,
    },
    {
      path: '/:lang',
      component: RouterView,
      children: [
        {
          path: '', component: Index,
        },
        // {
        // path: 'download', component: Download,
        // },
        {
          path: 'converter', component: Converter,
        },
        {
          path: 'converter/:raw', component: Converter,
        },
        {
          path: '*', component: Index,
        },
      ],
    },
  ],
})

const i18n = createI18n({
  // legacy: false, // you must specify 'legacy: false' option

  locale: (navigator.language || navigator.userLanguage).split('-')[0],
  messages: {
    ru: localeRu,
    en: localeEn,
  },
})

router.beforeEach((to, from, next) => {
  const lang = to.params.lang

  if (!['en', 'ru'].includes(lang)) {
    return next()
  }

  if (i18n.locale !== lang) {
    i18n.changeLocale(lang)
  }

  return next()
})

const app = createApp(App)

app.use(store)
app.use(router)
app.use(i18n)

app.mount('#app')
<commit_msg>Add fallback locale<commit_after>import { createApp } from 'vue'
import { createRouter, createWebHistory, RouterView } from 'vue-router'
import store from './store'
import App from './App.vue'
// import Download from './components/pages/download'
import { createI18n } from 'vue-i18n-lite'

import localeRu from '@/assets/locales/ru'
import localeEn from '@/assets/locales/en'

const Index = () => import(/* webpackChunkName: "index" */'./components/pages/index/index')
const Converter = () => import(/* webpackChunkName: "converter" */'./components/pages/converter')

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/', component: Index,
    },
    // {
    // path: '/download', component: Download,
    // },
    {
      path: '/converter', component: Converter,
    },
    {
      path: '/converter/:raw', component: Converter,
    },
    {
      path: '/:lang',
      component: RouterView,
      children: [
        {
          path: '', component: Index,
        },
        // {
        // path: 'download', component: Download,
        // },
        {
          path: 'converter', component: Converter,
        },
        {
          path: 'converter/:raw', component: Converter,
        },
        {
          path: '*', component: Index,
        },
      ],
    },
  ],
})

const i18n = createI18n({
  // legacy: false, // you must specify 'legacy: false' option

  locale: (navigator.language || navigator.userLanguage).split('-')[0],
  fallbackLocale: 'en',

  messages: {
    ru: localeRu,
    en: localeEn,
  },
})

router.beforeEach((to, from, next) => {
  const lang = to.params.lang

  if (!['en', 'ru'].includes(lang)) {
    return next()
  }

  if (i18n.locale !== lang) {
    i18n.changeLocale(lang)
  }

  return next()
})

const app = createApp(App)

app.use(store)
app.use(router)
app.use(i18n)

app.mount('#app')
<|endoftext|>


<commit_before>var isFunction = require("is_function"),
    isObjectLike = require("is_object_like"),
    isNative = require("is_native");

var defineProperty;

if (!isNative(Object.defineProperty)) {
    defineProperty = function defineProperty(object, name, value) {
        if (!isObjectLike(object)) {
            throw new TypeError("defineProperty called on non-object");
        }
        object[name] = isObjectLike(value) ? (isFunction(value.get) ? value.get : value.value) : value;
    };
} else {
    defineProperty = Object.defineProperty;
}

module.exports = defineProperty;
<commit_msg>updates<commit_after>var isFunction = require("is_function"),
    isObjectLike = require("is_object_like"),
    isNative = require("is_native");

var defineProperty;

if (!isNative(Object.defineProperty) || (function() {
        try {
            Object.defineProperty({}, "key", {});
        } catch (e) {
            return true;
        }
        return false;
    }())) {
    defineProperty = function defineProperty(object, name, value) {
        if (!isObjectLike(object)) {
            throw new TypeError("defineProperty called on non-object");
        }
        object[name] = isObjectLike(value) ? (isFunction(value.get) ? value.get : value.value) : value;
    };
} else {
    defineProperty = Object.defineProperty;
}

module.exports = defineProperty;
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import './stylesheets/ui.scss'
import { SkiDayList } from './components/SkiDayList'

window.React = React

render(
	<SkiDayList days="plenty of days"/>,
	document.getElementById('react-container')
)
<commit_msg>Check for error message when an empty array is passed.<commit_after>import React from 'react'
import { render } from 'react-dom'
import './stylesheets/ui.scss'
import { SkiDayList } from './components/SkiDayList'

window.React = React

render(
	<SkiDayList days={[]}/>,
	document.getElementById('react-container')
)
<|endoftext|>


<commit_before>import postcss from 'postcss';
import parser from 'postcss-selector-parser';

function normalizeAttributes(selector) {
  selector.walkAttributes(node => {
    if (node.value) {
      // remove quotes
      node.value = node.value.replace(/'|\\'|"|\\"/g, '');
    }
  });
}

function sortGroups(selector) {
  selector.each(subSelector => {
    subSelector.nodes.sort((a, b) => {
      // different types cannot be sorted
      if (a.type !== b.type) {
        return 0;
      }

      // sort alphabetically
      return a.value < b.value ? -1 : 1;
    });
  });
}

const uniformStyle = parser(
  selector => {
    normalizeAttributes(selector);
    sortGroups(selector);
  }
);

export default postcss.plugin('postcss-combine-duplicated-selectors', () => {
  return css => {
    // Create a map to store maps
    const mapTable = new Map();
    // root map to store root selectors
    mapTable.set('root', new Map());

    // Walk at rules to look for media queries
    css.walkRules(rule => {
      let map;
      if (rule.parent.type === 'atrule' &&
          rule.parent.name === 'media') {
        // Use the query params as the key
        const query = rule.parent.params.replace(/\s+/g, '');
        // See if this query key is already in the map table
        map = mapTable.has(query) ?
          // If it is use it
          mapTable.get(query) :
          // if not set it and get it
          mapTable.set(query, new Map()).get(query);
      } else {
        // Otherwise we are dealing with a selector in the root
        map = mapTable.get('root');
      }

      const selector = uniformStyle.process(
        rule.selector,
        {lossless: false}
      ).result;

      if (map.has(selector)) {
        // store original rule as destination
        const destination = map.get(selector);
        // move declarations to original rule
        while (rule.nodes.length > 0) {
          rule.nodes[0].moveTo(destination);
        }
        // remove duplicated rule
        rule.remove();
      } else {
        // add new selector to symbol table
        map.set(selector, rule);
      }
    });
  };
});
<commit_msg>Patch strips whitespace from query params to avoid duplicate keys edge case.<commit_after>import postcss from 'postcss';
import parser from 'postcss-selector-parser';

function normalizeAttributes(selector) {
  selector.walkAttributes(node => {
    if (node.value) {
      // remove quotes
      node.value = node.value.replace(/'|\\'|"|\\"/g, '');
    }
  });
}

function sortGroups(selector) {
  selector.each(subSelector => {
    subSelector.nodes.sort((a, b) => {
      // different types cannot be sorted
      if (a.type !== b.type) {
        return 0;
      }

      // sort alphabetically
      return a.value < b.value ? -1 : 1;
    });
  });
}

const uniformStyle = parser(
  selector => {
    normalizeAttributes(selector);
    sortGroups(selector);
  }
);

export default postcss.plugin('postcss-combine-duplicated-selectors', () => {
  return css => {
    // Create a map to store maps
    const mapTable = new Map();
    // root map to store root selectors
    mapTable.set('root', new Map());

    // Walk at rules to look for media queries
    css.walkRules(rule => {
      let map;
      // Check selector parent for a media query
      if (rule.parent.type === 'atrule' &&
          rule.parent.name === 'media') {
        // Use the query params as the key
        const query = rule.parent.params.replace(/\s+/g, '');
        // See if this query key is already in the map table
        map = mapTable.has(query) ?
          // If it is use it
          mapTable.get(query) :
          // if not set it and get it
          mapTable.set(query, new Map()).get(query);
      } else {
        // Otherwise we are dealing with a selector in the root
        map = mapTable.get('root');
      }

      const selector = uniformStyle.process(
        rule.selector,
        {lossless: false}
      ).result;

      if (map.has(selector)) {
        // store original rule as destination
        const destination = map.get(selector);
        // move declarations to original rule
        while (rule.nodes.length > 0) {
          rule.nodes[0].moveTo(destination);
        }
        // remove duplicated rule
        rule.remove();
      } else {
        // add new selector to symbol table
        map.set(selector, rule);
      }
    });
  };
});
<|endoftext|>


<commit_before>
import { uuid } from './util';
import * as chartFns from './chart';

const FORMAT_YAML = 'yaml';

let chartScriptFn = () => {};

module.exports = {
    book: {
        assets: './assets'
    },
    hooks: {
        init: function () {
            let pluginConfig = this.config.get('pluginsConfig.chart');
            let type = pluginConfig.type;
            chartScriptFn = chartFns[type];
        }
    },
    blocks: {
        chart: {
            process: function (blk) {
                let id = uuid();
                let body = {};
                try {
                    // get string in {% chart %}
                    let bodyString = blk.body.trim();
                    if (blk.kwargs.format === FORMAT_YAML) {
                        // load yaml into body:
                        body = require('js-yaml').safeLoad(bodyString);
                    } else {
                        // just think it as json:
                        // TODO: Avoiding `eval`
                        // https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval
                        eval('body=' + bodyString);
                    }
                } catch (e) {
                    console.error(e);
                }
                let scripts = chartScriptFn(id, body);
                return `

`;
            }
        }
    }
};
<commit_msg>Parse block body as pure JSON to prevent using eval<commit_after>
import { uuid } from './util';
import * as chartFns from './chart';

const FORMAT_YAML = 'yaml';

let chartScriptFn = () => {};

module.exports = {
    book: {
        assets: './assets'
    },
    hooks: {
        init: function () {
            let pluginConfig = this.config.get('pluginsConfig.chart');
            let type = pluginConfig.type;
            chartScriptFn = chartFns[type];
        }
    },
    blocks: {
        chart: {
            process: function (blk) {
                let id = uuid();
                let body = {};
                try {
                    // get string in {% chart %}
                    let bodyString = blk.body.trim();
                    if (blk.kwargs.format === FORMAT_YAML) {
                        // load yaml into body:
                        body = require('js-yaml').safeLoad(bodyString);
                    } else {
                        // this is pure JSON
                        body = JSON.parse(bodyString);
                    }
                } catch (e) {
                    console.error(e);
                }
                let scripts = chartScriptFn(id, body);
                return `

`;
            }
        }
    }
};
<|endoftext|>


<commit_before>module.exports = require('./validator')
module.exports.extend = require('./extends')
<commit_msg>fix: Rename import in index<commit_after>module.exports = require('./validator')
module.exports.extend = require('./extend')
<|endoftext|>


<commit_before>"use strict"

var crypto = require('crypto')
var request = require('request')
var fs = require('fs')

function acr(props) {
    this.defaultOptions = {
        host: props.host,
        endpoint: '/v1/identify',
        signature_version: '1',
        data_type: props.data_type || 'audio',
        access_key: props.access_key,
        access_secret: props.access_secret,
        audio_format: props.audio_format || '',
        sample_rate: props.sample_rate || '',
        audio_channels: props.audio_channels || ''
    }
}

acr.prototype.buildStringToSign = function(method, uri, accessKey, dataType, signatureVersion, timestamp) {
    return [method, uri, accessKey, dataType, signatureVersion, timestamp].join('\n')
}
acr.prototype.sign = function(signString, accessSecret) {
    return crypto.createHmac('sha1', accessSecret)
        .update(new Buffer(signString, 'utf-8'))
        .digest().toString('base64')
}

acr.prototype.identify = function(path, callback) {
    let current_date = new Date()
    let timestamp = current_date.getTime()/1000

    let stringToSign = this.buildStringToSign('POST',
        this.defaultOptions.endpoint,
        this.defaultOptions.access_key,
        this.defaultOptions.data_type,
        this.defaultOptions.signature_version,
        timestamp)

    let signature = this.sign(stringToSign, this.defaultOptions.access_secret)

    let sampleData = new Buffer(fs.readFileSync(path))

    let formData = {
        sample: sampleData,
        access_key:this.defaultOptions.access_key,
        data_type:this.defaultOptions.data_type,
        signature_version:this.defaultOptions.signature_version,
        signature:signature,
        sample_bytes:sampleData.length,
        timestamp:timestamp,
    }

    console.log("Posting track to "+this.defaultOptions.host)

    request.post({
        url: "http://"+this.defaultOptions.host + this.defaultOptions.endpoint,
        method: 'POST',
        formData: formData
    }, function(err, httpResponse, body) {
        if (err) console.log(err);

        let JSONBody = JSON.parse(body)
        let code = JSONBody.status.code
        switch (code) {
            case 0:
                callback(body)
                break;
            default:
                console.log(`Houston, we have a problem... ${JSONBody.status.msg}`)
        }
    })
}

module.exports = acr
<commit_msg>identify() function now returns only meta data and not httpresponsebody. Fixed: Broken endpoint.<commit_after>"use strict"

var crypto = require('crypto')
var request = require('request')
var fs = require('fs')

function acr(props) {
    this.defaultOptions = {
        host: props.host,
        signature_version: '1',
        endpoint: '/v1/identify',
        data_type: props.data_type || 'audio',
        access_key: props.access_key,
        access_secret: props.access_secret,
        audio_format: props.audio_format || '',
        sample_rate: props.sample_rate || '',
        audio_channels: props.audio_channels || ''
    }
}

acr.prototype.buildStringToSign = function(method, uri, accessKey, dataType, signatureVersion, timestamp) {
    return [method, uri, accessKey, dataType, signatureVersion, timestamp].join('\n')
}
acr.prototype.sign = function(signString, accessSecret) {
    return crypto.createHmac('sha1', accessSecret)
        .update(new Buffer(signString, 'utf-8'))
        .digest().toString('base64')
}

acr.prototype.identify = function(path, callback) {
    let current_date = new Date()
    let timestamp = current_date.getTime()/1000

    let stringToSign = this.buildStringToSign('POST',
        this.defaultOptions.endpoint,
        this.defaultOptions.access_key,
        this.defaultOptions.data_type,
        this.defaultOptions.signature_version,
        timestamp)

    let signature = this.sign(stringToSign, this.defaultOptions.access_secret)
    let sampleData = new Buffer(fs.readFileSync(path))

    let formData = {
        sample: sampleData,
        access_key:this.defaultOptions.access_key,
        data_type:this.defaultOptions.data_type,
        signature_version:this.defaultOptions.signature_version,
        signature:signature,
        sample_bytes:sampleData.length,
        timestamp:timestamp,
    }

    console.log("Posting track to "+this.defaultOptions.host)

    request.post({
        url: "http://"+this.defaultOptions.host+this.defaultOptions.endpoint,
        method: 'POST',
        formData: formData
    }, function(err, httpResponse, body) {
        if (err) console.log(err);

        let JSONBody = JSON.parse(body)
        let code = JSONBody.status.code

        switch (code) {
            case 0:
                callback(JSONBody.metadata)
                break;
            default:
                console.log(`Houston, we have a problem... ${JSONBody.status.msg}`)
        }
    })
}

module.exports = acr
<|endoftext|>


<commit_before>import dotenv from 'dotenv-defaults'
import fs from 'fs'
import { DefinePlugin } from 'webpack'

// Mostly taken from here: https://github.com/motdotla/dotenv-expand/blob/master/lib/main.js#L4
const interpolate = (env, vars) => {
  const matches = env.match(/\$([a-zA-Z0-9_]+)|\${([a-zA-Z0-9_]+)}/g) || []

  matches.forEach((match) => {
    const key = match.replace(/\$|{|}/g, '')
    let variable = vars[key] || ''
    variable = interpolate(variable, vars)
    env = env.replace(match, variable)
  })

  return env
}

class Dotenv {
  /**
   * The dotenv-webpack plugin.
   * @param {Object} options - The parameters.
   * @param {String} [options.path=./.env] - The location of the environment variable.
   * @param {Boolean|String} [options.safe=false] - If false ignore safe-mode, if true load `'./.env.example'`, if a string load that file as the sample.
   * @param {Boolean} [options.systemvars=false] - If true, load system environment variables.
   * @param {Boolean} [options.silent=false] - If true, suppress warnings, if false, display warnings.
   * @returns {webpack.DefinePlugin}
   */
  constructor (config = {}) {
    this.config = Object.assign({}, {
      path: './.env'
    }, config)

    this.checkDeprecation()

    return new DefinePlugin(this.formatData(this.gatherVariables()))
  }

  checkDeprecation () {
    const { sample, safe, silent } = this.config
    // Catch older packages, but hold their hand (just for a bit)
    if (sample) {
      if (safe) {
        this.config.safe = sample
      }
      this.warn('dotenv-webpack: "options.sample" is a deprecated property. Please update your configuration to use "options.safe" instead.', silent)
    }
  }

  gatherVariables () {
    const { safe, allowEmptyValues } = this.config
    const vars = this.initializeVars()

    const { env, blueprint } = this.getEnvs()

    Object.keys(blueprint).forEach(key => {
      const value = Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : env[key]

      const isMissing = typeof value === 'undefined' || value === null ||
        (!allowEmptyValues && value === '')

      if (safe && isMissing) {
        throw new Error(`Missing environment variable: ${key}`)
      } else {
        vars[key] = value
      }
    })

    // add the leftovers
    if (safe) {
      Object.keys(env).forEach((key) => {
        if (!Object.prototype.hasOwnProperty.call(vars, key)) {
          vars[key] = env[key]
        }
      })
    }

    return vars
  }

  initializeVars () {
    return (this.config.systemvars) ? Object.assign({}, process.env) : {}
  }

  getEnvs () {
    const { path, silent, safe } = this.config

    const env = dotenv.parse(this.loadFile({
      file: path,
      silent
    }), this.getDefaults())

    let blueprint = env
    if (safe) {
      let file = './.env.example'
      if (safe !== true) {
        file = safe
      }
      blueprint = dotenv.parse(this.loadFile({
        file,
        silent
      }))
    }

    return {
      env,
      blueprint
    }
  }

  getDefaults () {
    const { silent, defaults } = this.config

    if (defaults) {
      return this.loadFile({
        file: defaults === true ? './.env.defaults' : defaults,
        silent
      })
    }

    return ''
  }

  formatData (vars = {}) {
    const { expand } = this.config
    const formatted = Object.keys(vars).reduce((obj, key) => {
      const v = vars[key]
      const vKey = `process.env.${key}`
      let vValue
      if (expand) {
        if (v.substring(0, 2) === '\\$') {
          vValue = v.substring(1)
        } else if (v.indexOf('\\$') > 0) {
          vValue = v.replace(/\\\$/g, '$')
        } else {
          vValue = interpolate(v, vars)
        }
      } else {
        vValue = v
      }

      obj[vKey] = JSON.stringify(vValue)

      return obj
    }, {})

    // fix in case of missing
    formatted['process.env'] = '{}'

    return formatted
  }

  /**
   * Load a file.
   * @param {String} config.file - The file to load.
   * @param {Boolean} config.silent - If true, suppress warnings, if false, display warnings.
   * @returns {Object}
   */
  loadFile ({ file, silent }) {
    try {
      return fs.readFileSync(file, 'utf8')
    } catch (err) {
      this.warn(`Failed to load ${file}.`, silent)
      return {}
    }
  }

  /**
   * Displays a console message if 'silent' is falsey
   * @param {String} msg - The message.
   * @param {Boolean} silent - If true, display the message, if false, suppress the message.
   */
  warn (msg, silent) {
    !silent && console.warn(msg)
  }
}

export default Dotenv
<commit_msg>chore: breaking lint<commit_after>import dotenv from 'dotenv-defaults'
import fs from 'fs'
import { DefinePlugin } from 'webpack'

// Mostly taken from here: https://github.com/motdotla/dotenv-expand/blob/master/lib/main.js#L4
const interpolate = (env, vars) => {
  const matches = env.match(/\$([a-zA-Z0-9_]+)|\${([a-zA-Z0-9_]+)}/g) || []

  matches.forEach((match) => {
    const key = match.replace(/\$|{|}/g, '')
    let variable = vars[key] || ''
    variable = interpolate(variable, vars)
    env = env.replace(match, variable)
  })

  return env;
}

class Dotenv {
  /**
   * The dotenv-webpack plugin.
   * @param {Object} options - The parameters.
   * @param {String} [options.path=./.env] - The location of the environment variable.
   * @param {Boolean|String} [options.safe=false] - If false ignore safe-mode, if true load `'./.env.example'`, if a string load that file as the sample.
   * @param {Boolean} [options.systemvars=false] - If true, load system environment variables.
   * @param {Boolean} [options.silent=false] - If true, suppress warnings, if false, display warnings.
   * @returns {webpack.DefinePlugin}
   */
  constructor (config = {}) {
    this.config = Object.assign({}, {
      path: './.env'
    }, config)

    this.checkDeprecation()

    return new DefinePlugin(this.formatData(this.gatherVariables()))
  }

  checkDeprecation () {
    const { sample, safe, silent } = this.config
    // Catch older packages, but hold their hand (just for a bit)
    if (sample) {
      if (safe) {
        this.config.safe = sample
      }
      this.warn('dotenv-webpack: "options.sample" is a deprecated property. Please update your configuration to use "options.safe" instead.', silent)
    }
  }

  gatherVariables () {
    const { safe, allowEmptyValues } = this.config
    const vars = this.initializeVars()

    const { env, blueprint } = this.getEnvs()

    Object.keys(blueprint).forEach(key => {
      const value = Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : env[key]

      const isMissing = typeof value === 'undefined' || value === null ||
        (!allowEmptyValues && value === '')

      if (safe && isMissing) {
        throw new Error(`Missing environment variable: ${key}`)
      } else {
        vars[key] = value
      }
    })

    // add the leftovers
    if (safe) {
      Object.keys(env).forEach((key) => {
        if (!Object.prototype.hasOwnProperty.call(vars, key)) {
          vars[key] = env[key]
        }
      })
    }

    return vars
  }

  initializeVars () {
    return (this.config.systemvars) ? Object.assign({}, process.env) : {}
  }

  getEnvs () {
    const { path, silent, safe } = this.config

    const env = dotenv.parse(this.loadFile({
      file: path,
      silent
    }), this.getDefaults())

    let blueprint = env
    if (safe) {
      let file = './.env.example'
      if (safe !== true) {
        file = safe
      }
      blueprint = dotenv.parse(this.loadFile({
        file,
        silent
      }))
    }

    return {
      env,
      blueprint
    }
  }

  getDefaults () {
    const { silent, defaults } = this.config

    if (defaults) {
      return this.loadFile({
        file: defaults === true ? './.env.defaults' : defaults,
        silent
      })
    }

    return ''
  }

  formatData (vars = {}) {
    const { expand } = this.config
    const formatted = Object.keys(vars).reduce((obj, key) => {
      const v = vars[key]
      const vKey = `process.env.${key}`
      let vValue
      if (expand) {
        if (v.substring(0, 2) === '\\$') {
          vValue = v.substring(1)
        } else if (v.indexOf('\\$') > 0) {
          vValue = v.replace(/\\\$/g, '$')
        } else {
          vValue = interpolate(v, vars)
        }
      } else {
        vValue = v
      }

      obj[vKey] = JSON.stringify(vValue)

      return obj
    }, {})

    // fix in case of missing
    formatted['process.env'] = '{}'

    return formatted
  }

  /**
   * Load a file.
   * @param {String} config.file - The file to load.
   * @param {Boolean} config.silent - If true, suppress warnings, if false, display warnings.
   * @returns {Object}
   */
  loadFile ({ file, silent }) {
    try {
      return fs.readFileSync(file, 'utf8')
    } catch (err) {
      this.warn(`Failed to load ${file}.`, silent)
      return {}
    }
  }

  /**
   * Displays a console message if 'silent' is falsey
   * @param {String} msg - The message.
   * @param {Boolean} silent - If true, display the message, if false, suppress the message.
   */
  warn (msg, silent) {
    !silent && console.warn(msg)
  }
}

export default Dotenv
<|endoftext|>


<commit_before>/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////             /////    /////
/////             /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
         /////    /////
         /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////

/*!
 * ScrollReveal
 * ------------
 * Website : https://scrollreveal.com
 * Support : https://github.com/jlmakes/scrollreveal/issues
 * Author  : https://twitter.com/jlmakes
 *
 * Licensed under the GNU General Public License 3.0 for
 * compatible open source projects and non-commercial use.
 *
 * For commercial sites, themes, projects, and applications,
 * keep your source code proprietary and please purchase a
 * commercial license from https://scrollreveal.com
 *
 * Copyright (c) 2014–2017 Julian Lloyd. All rights reserved.
 */
import Constructor from './instance/constructor'

export default Constructor
<commit_msg>update urls in source comment banner<commit_after>/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////             /////    /////
/////             /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
         /////    /////
         /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////
/////    /////    /////    /////

/*!
 * ScrollReveal
 * ------------
 * Website : https://scrollrevealjs.org
 * Support : https://github.com/jlmakes/scrollreveal/issues
 * Author  : https://twitter.com/jlmakes
 *
 * Licensed under the GNU General Public License 3.0 for
 * compatible open source projects and non-commercial use.
 *
 * For commercial sites, themes, projects, and applications,
 * keep your source code proprietary and please purchase a
 * commercial license from https://scrollrevealjs.org
 *
 * Copyright (c) 2014–2017 Julian Lloyd. All rights reserved.
 */
import Constructor from './instance/constructor'

export default Constructor
<|endoftext|>


<commit_before>"use strict";
/**
 * `directory` type prompt
 */
var rx = require('rx-lite');
var util = require("util");
var chalk = require("chalk");
var figures = require("figures");
var cliCursor = require("cli-cursor");
var Base = require("inquirer/lib/prompts/base");
var observe = require("inquirer/lib/utils/events");
var Paginator = require("inquirer/lib/utils/paginator");
var Choices = require('inquirer/lib/objects/choices');
var Separator = require('inquirer/lib/objects/separator');

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

/**
 * Module exports
 */

module.exports = Prompt;

/**
 * Constants
 */
var CHOOSE = "choose this directory";
var BACK = "go back a directory";

/**
 * Constructor
 */

function Prompt() {
    Base.apply(this, arguments);

    if (!this.opt.basePath) {
        this.throwParamError("basePath");
    }

    this.depth = 0;
    this.currentPath = path.isAbsolute(this.opt.basePath) ? path.resolve(this.opt.basePath) : path.resolve(process.cwd(), this.opt.basePath);
    this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
    this.selected = 0;

    this.firstRender = true;

    // Make sure no default is set (so it won't be printed)
    this.opt.default = null;

    this.searchTerm = '';

    this.paginator = new Paginator();
}
util.inherits(Prompt, Base);

/**
 * Start the Inquiry session
 * @param  {Function} cb      Callback when prompt is done
 * @return {this}
 */

Prompt.prototype._run = function(cb) {
    var self = this;
    self.searchMode = false;
    this.done = cb;
    var alphaNumericRegex = /\w|\.|\-/i;
    var events = observe(this.rl);

    var keyUps = events.keypress.filter(function(e) {
        return e.key.name === 'up' || (!self.searchMode && e.key.name === 'k');
    }).share();

    var keyDowns = events.keypress.filter(function(e) {
        return e.key.name === 'down' || (!self.searchMode && e.key.name === 'j');
    }).share();

    var keySlash = events.keypress.filter(function(e) {
        return e.value === '/';
    }).share();

    var keyMinus = events.keypress.filter(function(e) {
        return e.value === '-';
    }).share();

    var alphaNumeric = events.keypress.filter(function(e) {
        return e.key.name === 'backspace' || alphaNumericRegex.test(e.value);
    }).share();

    var searchTerm = keySlash.flatMap(function(md) {
        self.searchMode = true;
        self.searchTerm = '';
        self.render();
        var end$ = new rx.Subject();
        var done$ = rx.Observable.merge(events.line, end$);
        return alphaNumeric.map(function(e) {
                if (e.key.name === 'backspace' && self.searchTerm.length) {
                    self.searchTerm = self.searchTerm.slice(0, -1);
                } else if (e.value) {
                    self.searchTerm += e.value;
                }
                if (self.searchTerm === '') {
                    end$.onNext(true);
                }
                return self.searchTerm;
            })
            .takeUntil(done$)
            .doOnCompleted(function() {
                self.searchMode = false;
                self.render();
                return false;
            });
    }).share();

    var outcome = this.handleSubmit(events.line);
    outcome.drill.forEach(this.handleDrill.bind(this));
    outcome.back.forEach(this.handleBack.bind(this));
    keyUps.takeUntil(outcome.done).forEach(this.onUpKey.bind(this));
    keyDowns.takeUntil(outcome.done).forEach(this.onDownKey.bind(this));
    keyMinus.takeUntil(outcome.done).forEach(this.handleBack.bind(this));
    events.keypress.takeUntil(outcome.done).forEach(this.hideKeyPress.bind(this));
    searchTerm.takeUntil(outcome.done).forEach(this.onKeyPress.bind(this));
    outcome.done.forEach(this.onSubmit.bind(this));

    // Init the prompt
    cliCursor.hide();
    this.render();

    return this;
};

/**
 * Render the prompt to screen
 * @return {Prompt} self
 */

Prompt.prototype.render = function() {
    // Render question
    var message = this.getQuestion();

    if (this.firstRender) {
        message += chalk.dim("(Use arrow keys)");
    }

    // Render choices or answer depending on the state
    if (this.status === "answered") {
        message += chalk.cyan(path.relative(this.opt.basePath, this.currentPath));
    } else {
        message += chalk.bold("\n Current directory: ") + this.opt.basePath + "/" + chalk.cyan(path.relative(this.opt.basePath, this.currentPath));
        var choicesStr = listRender(this.opt.choices, this.selected);
        message += "\n" + this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize);
    }
    if (this.searchMode) {
        message += ("\nSearch: " + this.searchTerm);
    } else {
        message += "\n(Use \"/\" key to search this directory)";
    }

    this.firstRender = false;

    this.screen.render(message);
};

/**
 * When user press `enter` key
 */
Prompt.prototype.handleSubmit = function(e) {
    var self = this;
    var obx = e.map(function() {
        return self.opt.choices.getChoice(self.selected).value;
    }).share();

    var done = obx.filter(function(choice) {
        return choice === CHOOSE;
    }).take(1);

    var back = obx.filter(function(choice) {
        return choice === BACK;
    }).takeUntil(done);

    var drill = obx.filter(function(choice) {
        return choice !== BACK && choice !== CHOOSE;
    }).takeUntil(done);

    return {
        done: done,
        back: back,
        drill: drill
    };
};

/**
 *  when user selects to drill into a folder (by selecting folder name)
 */
Prompt.prototype.handleDrill = function() {
    var choice = this.opt.choices.getChoice(this.selected);
    this.depth++;
    this.currentPath = path.join(this.currentPath, choice.value);
    this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
    this.selected = 0;
    this.render();
};

/**
 * when user selects ".. back"
 */
Prompt.prototype.handleBack = function() {
    if (this.depth > 0) {
        var choice = this.opt.choices.getChoice(this.selected);
        this.depth--;
        this.currentPath = path.dirname(this.currentPath);
        this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
        this.selected = 0;
        this.render();
    }
};

/**
 * when user selects "choose this folder"
 */
Prompt.prototype.onSubmit = function(value) {
    this.status = "answered";

    // Rerender prompt
    this.render();

    this.screen.done();
    cliCursor.show();
    this.done(path.relative(this.opt.basePath, this.currentPath));
};

/**
 * When user press a key
 */
Prompt.prototype.hideKeyPress = function() {
    if (!this.searchMode) {
        this.render();
    }
};

Prompt.prototype.onUpKey = function() {
    var len = this.opt.choices.realLength;
    this.selected = (this.selected > 0) ? this.selected - 1 : len - 1;
    this.render();
};

Prompt.prototype.onDownKey = function() {
    var len = this.opt.choices.realLength;
    this.selected = (this.selected < len - 1) ? this.selected + 1 : 0;
    this.render();
};

Prompt.prototype.onSlashKey = function(e) {
    this.render();
};

Prompt.prototype.onKeyPress = function(e) {
    var index = findIndex.call(this, this.searchTerm);
    if (index >= 0) {
        this.selected = index;
    }
    this.render();
};

function findIndex(term) {
    var item;
    for (var i = 0; i < this.opt.choices.realLength; i++) {
        item = this.opt.choices.realChoices[i].name.toLowerCase();
        if (item.indexOf(term) === 0) {
            return i;
        }
    }
    return -1;
}

/**
 * Helper to create new choices based on previous selection.
 */
Prompt.prototype.createChoices = function(basePath) {
    var choices = getDirectories(basePath);
    if (choices.length > 0) {
        choices.push(new Separator());
    }
    choices.push(CHOOSE);
    if (this.depth > 0) {
        choices.push(new Separator());
        choices.push(BACK);
        choices.push(new Separator());
    }
    return choices;
};

/**
 * Function for rendering list choices
 * @param  {Number} pointer Position of the pointer
 * @return {String}         Rendered content
 */
function listRender(choices, pointer) {
    var output = '';
    var separatorOffset = 0;

    choices.forEach(function(choice, i) {
        if (choice.type === 'separator') {
            separatorOffset++;
            output += '  ' + choice + '\n';
            return;
        }

        var isSelected = (i - separatorOffset === pointer);
        var line = (isSelected ? figures.pointer + ' ' : '  ') + choice.name;
        if (isSelected) {
            line = chalk.cyan(line);
        }
        output += line + ' \n';
    });

    return output.replace(/\n$/, '');
}

/**
 * Function for getting list of folders in directory
 * @param  {String} basePath the path the folder to get a list of containing folders
 * @return {Array}           array of folder names inside of basePath
 */
function getDirectories(basePath) {
    return fs
        .readdirSync(basePath)
        .filter(function(file) {
            var stats = fs.lstatSync(path.join(basePath, file));
            if (stats.isSymbolicLink()) {
                return false;
            }
            var isDir = stats.isDirectory();
            var isNotDotFile = path.basename(file).indexOf('.') !== 0;
            return isDir && isNotDotFile;
        })
        .sort();
}<commit_msg>FullNavigation feature<commit_after>"use strict";
/**
 * `directory` type prompt
 */
var rx = require('rx-lite');
var util = require("util");
var chalk = require("chalk");
var figures = require("figures");
var cliCursor = require("cli-cursor");
var Base = require("inquirer/lib/prompts/base");
var observe = require("inquirer/lib/utils/events");
var Paginator = require("inquirer/lib/utils/paginator");
var Choices = require('inquirer/lib/objects/choices');
var Separator = require('inquirer/lib/objects/separator');

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

/**
 * Constants
 */
var CHOOSE = "choose this directory";
var BACK = "..";

/**
 * Constructor
 */

function Prompt() {
    Base.apply(this, arguments);
    if (!this.opt.basePath) {
        this.throwParamError("basePath");
    }
    this.currentPath = path.isAbsolute(this.opt.basePath) ? path.resolve(this.opt.basePath) : path.resolve(process.cwd(), this.opt.basePath);
    this.root = path.parse(this.currentPath).root;
    this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
    this.selected = 0;

    this.firstRender = true;

    // Make sure no default is set (so it won't be printed)
    this.opt.default = null;

    this.searchTerm = '';

    this.paginator = new Paginator();
}
util.inherits(Prompt, Base);

/**
 * Start the Inquiry session
 * @param  {Function} cb      Callback when prompt is done
 * @return {this}
 */

Prompt.prototype._run = function(cb) {
    var self = this;
    self.searchMode = false;
    this.done = cb;
    var alphaNumericRegex = /\w|\.|\-/i;
    var events = observe(this.rl);

    var keyUps = events.keypress.filter(function(e) {
        return e.key.name === 'up' || (!self.searchMode && e.key.name === 'k');
    }).share();

    var keyDowns = events.keypress.filter(function(e) {
        return e.key.name === 'down' || (!self.searchMode && e.key.name === 'j');
    }).share();

    var keySlash = events.keypress.filter(function(e) {
        return e.value === '/';
    }).share();

    var keyMinus = events.keypress.filter(function(e) {
        return e.value === '-';
    }).share();

    var alphaNumeric = events.keypress.filter(function(e) {
        return e.key.name === 'backspace' || alphaNumericRegex.test(e.value);
    }).share();

    var searchTerm = keySlash.flatMap(function(md) {
        self.searchMode = true;
        self.searchTerm = '';
        self.render();
        var end$ = new rx.Subject();
        var done$ = rx.Observable.merge(events.line, end$);
        return alphaNumeric.map(function(e) {
                if (e.key.name === 'backspace' && self.searchTerm.length) {
                    self.searchTerm = self.searchTerm.slice(0, -1);
                } else if (e.value) {
                    self.searchTerm += e.value;
                }
                if (self.searchTerm === '') {
                    end$.onNext(true);
                }
                return self.searchTerm;
            })
            .takeUntil(done$)
            .doOnCompleted(function() {
                self.searchMode = false;
                self.render();
                return false;
            });
    }).share();

    var outcome = this.handleSubmit(events.line);
    outcome.drill.forEach(this.handleDrill.bind(this));
    outcome.back.forEach(this.handleBack.bind(this));
    keyUps.takeUntil(outcome.done).forEach(this.onUpKey.bind(this));
    keyDowns.takeUntil(outcome.done).forEach(this.onDownKey.bind(this));
    keyMinus.takeUntil(outcome.done).forEach(this.handleBack.bind(this));
    events.keypress.takeUntil(outcome.done).forEach(this.hideKeyPress.bind(this));
    searchTerm.takeUntil(outcome.done).forEach(this.onKeyPress.bind(this));
    outcome.done.forEach(this.onSubmit.bind(this));

    // Init the prompt
    cliCursor.hide();
    this.render();

    return this;
};

/**
 * Render the prompt to screen
 * @return {Prompt} self
 */

Prompt.prototype.render = function() {
    // Render question
    var message = this.getQuestion();

    if (this.firstRender) {
        message += chalk.dim("(Use arrow keys)");
    }

    // Render choices or answer depending on the state
    if (this.status === "answered") {
        message += chalk.cyan(this.currentPath);
    } else {
        // message += chalk.bold("\n Current directory: ") + path.resolve(this.opt.basePath) + path.sep + chalk.cyan(path.relative(this.opt.basePath, this.currentPath));
        message += chalk.bold("\n Current directory: ") + chalk.cyan(path.resolve(this.opt.basePath, this.currentPath));
        var choicesStr = listRender(this.opt.choices, this.selected);
        message += "\n" + this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize);
    }
    if (this.searchMode) {
        message += ("\nSearch: " + this.searchTerm);
    } else {
        message += "\n(Use \"/\" key to search this directory)";
    }

    this.firstRender = false;
    this.screen.render(message);
};

/**
 * When user press `enter` key
 */
Prompt.prototype.handleSubmit = function(e) {
    var self = this;
    var obx = e.map(function() {
        return self.opt.choices.getChoice(self.selected).value;
    }).share();

    var done = obx.filter(function(choice) {
        return choice === CHOOSE;
    }).take(1);

    var back = obx.filter(function(choice) {
        return choice === BACK;
    }).takeUntil(done);

    var drill = obx.filter(function(choice) {
        return choice !== BACK && choice !== CHOOSE;
    }).takeUntil(done);

    return {
        done: done,
        back: back,
        drill: drill
    };
};

/**
 *  when user selects to drill into a folder (by selecting folder name)
 */
Prompt.prototype.handleDrill = function() {
    var choice = this.opt.choices.getChoice(this.selected);
    this.currentPath = path.join(this.currentPath, choice.value);
    this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
    this.selected = 0;
    this.render();
};

/**
 * when user selects ".. back"
 */
Prompt.prototype.handleBack = function() {
    var choice = this.opt.choices.getChoice(this.selected);
    this.currentPath = path.dirname(this.currentPath);
    this.opt.choices = new Choices(this.createChoices(this.currentPath), this.answers);
    this.selected = 0;
    this.render();
};

/**
 * when user selects "choose this folder"
 */
Prompt.prototype.onSubmit = function(/*value*/) {
    this.status = "answered";

    // Rerender prompt
    this.render();

    this.screen.done();
    cliCursor.show();
    this.done(path.resolve(this.opt.basePath, this.currentPath));
};

/**
 * When user press a key
 */
Prompt.prototype.hideKeyPress = function() {
    if (!this.searchMode) {
        this.render();
    }
};

Prompt.prototype.onUpKey = function() {
    var len = this.opt.choices.realLength;
    this.selected = (this.selected > 0) ? this.selected - 1 : len - 1;
    this.render();
};

Prompt.prototype.onDownKey = function() {
    var len = this.opt.choices.realLength;
    this.selected = (this.selected < len - 1) ? this.selected + 1 : 0;
    this.render();
};

Prompt.prototype.onSlashKey = function(e) {
    this.render();
};

Prompt.prototype.onKeyPress = function(e) {
    var index = findIndex.call(this, this.searchTerm);
    if (index >= 0) {
        this.selected = index;
    }
    this.render();
};

function findIndex(term) {
    var item;
    for (var i = 0; i < this.opt.choices.realLength; i++) {
        item = this.opt.choices.realChoices[i].name.toLowerCase();
        if (item.indexOf(term) === 0) {
            return i;
        }
    }
    return -1;
}

/**
 * Helper to create new choices based on previous selection.
 */
Prompt.prototype.createChoices = function(basePath) {
    var choices = getDirectories(basePath);
    if (basePath !== this.root) {
      choices.unshift(BACK);
    }
    if (choices.length > 0) {
        choices.push(new Separator());
    }
    choices.push(CHOOSE);
    choices.push(new Separator());
    return choices;
};

/**
 * Function for rendering list choices
 * @param  {Number} pointer Position of the pointer
 * @return {String}         Rendered content
 */
function listRender(choices, pointer) {
    var output = '';
    var separatorOffset = 0;

    choices.forEach(function(choice, i) {
        if (choice.type === 'separator') {
            separatorOffset++;
            output += '  ' + choice + '\n';
            return;
        }

        var isSelected = (i - separatorOffset === pointer);
        var line = (isSelected ? figures.pointer + ' ' : '  ') + choice.name;
        if (isSelected) {
            line = chalk.cyan(line);
        }
        output += line + ' \n';
    });

    return output.replace(/\n$/, '');
}

/**
 * Function for getting list of folders in directory
 * @param  {String} basePath the path the folder to get a list of containing folders
 * @return {Array}           array of folder names inside of basePath
 */
function getDirectories(basePath) {
    return fs
        .readdirSync(basePath)
        .filter(function(file) {
           try {
                var stats = fs.lstatSync(path.join(basePath, file));
                if (stats.isSymbolicLink()) {
                    return false;
                }
                var isDir = stats.isDirectory();
                var isNotDotFile = path.basename(file).indexOf('.') !== 0;
                return isDir && isNotDotFile;
            } catch (e) {
                return false;
            }
        })
        .sort();
}

/**
 * Module exports
 */

module.exports = Prompt;<|endoftext|>


<commit_before>import configureUrlQuery from './configureUrlQuery';

import * as Serialize from './serialize';
import {
  replaceInUrlQuery,
  replaceUrlQuery,
  pushInUrlQuery,
  pushUrlQuery,
} from './updateUrlQuery';
import UrlQueryParamTypes from './UrlQueryParamTypes';
import UrlUpdateTypes from './UrlUpdateTypes';

/** React */
import addUrlProps from './react/addUrlProps';
import RouterToUrlQuery from './react/RouterToUrlQuery';

/** Redux */
import {
  replaceInUrlQueryFromAction,
  replaceUrlQueryFromAction,
  pushInUrlQueryFromAction,
  pushUrlQueryFromAction,
} from './redux/updateUrlQueryFromAction';
import urlAction, {
  urlReplaceAction,
  urlPushAction,
  urlReplaceInAction,
  urlPushInAction,
} from './redux/urlAction';
import urlQueryMiddleware from './redux/urlQueryMiddleware';
import urlQueryReducer from './redux/urlQueryReducer';

/** Utils */
import subquery from './utils/subquery';
import subqueryOmit from './utils/subqueryOmit';

// for convenience export these two directly
const decode = Serialize.decode;
const encode = Serialize.encode;

export {
  configureUrlQuery,

  Serialize,
  decode,
  encode,
  pushInUrlQuery,
  pushUrlQuery,
  replaceInUrlQuery,
  replaceUrlQuery,
  UrlQueryParamTypes,
  UrlUpdateTypes,

  addUrlProps,
  RouterToUrlQuery,

  urlAction,
  urlReplaceInAction,
  urlReplaceAction,
  urlPushInAction,
  urlPushAction,
  pushInUrlQueryFromAction,
  pushUrlQueryFromAction,
  replaceInUrlQueryFromAction,
  replaceUrlQueryFromAction,
  urlQueryMiddleware,
  urlQueryReducer,

  subquery,
  subqueryOmit,
};
<commit_msg>Switch to using export statements<commit_after>export configureUrlQuery from './configureUrlQuery';

export * as Serialize, { encode, decode } from './serialize';
export {
  replaceInUrlQuery,
  replaceUrlQuery,
  pushInUrlQuery,
  pushUrlQuery,
} from './updateUrlQuery';
export UrlQueryParamTypes from './UrlQueryParamTypes';
export UrlUpdateTypes from './UrlUpdateTypes';

/** React */
export addUrlProps from './react/addUrlProps';
export RouterToUrlQuery from './react/RouterToUrlQuery';

/** Redux */
export {
  replaceInUrlQueryFromAction,
  replaceUrlQueryFromAction,
  pushInUrlQueryFromAction,
  pushUrlQueryFromAction,
} from './redux/updateUrlQueryFromAction';
export urlAction, {
  urlReplaceAction,
  urlPushAction,
  urlReplaceInAction,
  urlPushInAction,
} from './redux/urlAction';
export urlQueryMiddleware from './redux/urlQueryMiddleware';
export urlQueryReducer from './redux/urlQueryReducer';

/** Utils */
export subquery from './utils/subquery';
export subqueryOmit from './utils/subqueryOmit';
<|endoftext|>


<commit_before>import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';

//test222
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
<commit_msg>test333<commit_after>import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';

//test333
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
<|endoftext|>


<commit_before>var locations = {
  agol: require('./AgolLocation'),
  datasciencetoolkit: require('./DataScienceToolkitLocation'),
  freegeoip: require('./FreeGeoIpLocation'),
  geocodio: require('./GeoCodioLocation'),
  google: require('./GoogleLocation'),
  mapquest: require('./MapQuestLocation'),
  nominatimmapquest: require('./NominatimMapQuestLocation'),
  opencage: require('./OpenCageLocation'),
  openmapquest: require('./OpenMapQuestLocation'),
  openstreetmap: require('./OpenStreetMapLocation'),
  smartystreets: require('./SmartyStreetsLocation'),
  tomtom: require('./TomTomLocation'),
  yandex: require('./YandexLocation')
};

module.exports = {
  /**
   * Create specified location instance
   * @param {String} type
   * @param {Object} config
   * @returns {*}
   */
  create: function (type, config) {
    if (locations[type.toLowerCase()] instanceof Function) {
      return new locations[type.toLowerCase()](config);
    } else {
      throw new Error('Unrecognized type -> ' + type);
    }
  },

  AgolLocation: locations.agol,
  DataScienceToolkitLocation: locations.datasciencetoolkit,
  FreeGeoIpLocation: locations.freegeoip,
  GeoCodioLocation: locations.geocodio,
  GoogleLocation: locations.google,
  MapQuestLocation: locations.mapquest,
  NominatimMapQuestLocation: locations.nominatimmapquest,
  OpenCageLocation: locations.opencage,
  OpenMapQuestLocation: locations.openmapquest,
  OpenStreetMapLocation: locations.openstreetmap,
  SmartyStreetsLocation: locations.smartystreets,
  TomTomLocation: locations.tomtom,
  YandexLocation: locations.yandex
};
<commit_msg>Rewrite LocationService with ES6<commit_after>import AgolLocation from './AgolLocation';
import DataScienceToolkitLocation from './DataScienceToolkitLocation';
import FreeGeoIpLocation from './FreeGeoIpLocation';
import GeoCodioLocation from './GeoCodioLocation';
import GoogleLocation from './GoogleLocation';
import MapQuestLocation from './MapQuestLocation';
import NominatimMapQuestLocation from './NominatimMapQuestLocation';
import OpenCageLocation from './OpenCageLocation';
import OpenMapQuestLocation from './OpenMapQuestLocation';
import OpenStreetMapLocation from './OpenStreetMapLocation';
import SmartyStreetsLocation from './SmartyStreetsLocation';
import TomTomLocation from './TomTomLocation';
import YandexLocation from './YandexLocation';

const location = {
  agol: AgolLocation,
  datasciencetoolkit: DataScienceToolkitLocation,
  freegeoip: FreeGeoIpLocation,
  geocodio: GeoCodioLocation,
  google: GoogleLocation,
  mapquest: MapQuestLocation,
  nominatimmapquest: NominatimMapQuestLocation,
  opencage: OpenCageLocation,
  openmapquest: OpenMapQuestLocation,
  openstreetmap: OpenStreetMapLocation,
  smartystreets: SmartyStreetsLocation,
  tomtom: TomTomLocation,
  yandex: YandexLocation
};

/**
 * Create specified location instance
 * @param {String} type
 * @param {Object} config
 * @returns {*}
 */
export default function (type, config) {
  if (location[type.toLowerCase()] instanceof Function) {
    return new location[type.toLowerCase()](config);
  } else {
    throw new Error('Unrecognized type -> ' + type);
  }
}
<|endoftext|>


<commit_before>import assign from 'object-assign';
import pascalCase from 'pascal-case';

const defaults = {
  React: window.React,
  ReactDOM: window.ReactDOM,
};

function syncEvent(node, eventName, newEventHandler) {
  const eventNameLc = eventName[0].toLowerCase() + eventName.substring(1);
  const eventStore = node.__events || (node.__events = {});
  const oldEventHandler = eventStore[eventNameLc];

  // Remove old listener so they don't double up.
  if (oldEventHandler) {
    node.removeEventListener(eventNameLc, oldEventHandler);
  }

  // Bind new listener.
  if (newEventHandler) {
    node.addEventListener(eventNameLc, eventStore[eventNameLc] = function handler(e) {
      newEventHandler.call(this, e);
    });
  }
}

export default function (CustomElement, opts) {
  opts = assign(defaults, opts);
  const tagName = (new CustomElement()).tagName;
  const displayName = pascalCase(tagName);
  const { React, ReactDOM } = opts;

  if (!React || !ReactDOM) {
    throw new Error('React and ReactDOM must be globally available or passed via opts.');
  }

  return class extends React.Component {
    static get displayName() {
      return displayName;
    }
    static get propTypes() {
      return {
        children: React.PropTypes.any,
        style: React.PropTypes.any,
      };
    }
    componentDidMount() {
      this.componentWillReceiveProps(this.props);
    }
    componentWillReceiveProps(props) {
      const node = ReactDOM.findDOMNode(this);
      Object.keys(props).forEach(name => {
        if (name === 'children' || name === 'style') {
          return;
        }

        if (name.indexOf('on') === 0) {
          syncEvent(node, name.substring(2), props[name]);
        } else {
          node[name] = props[name];
        }
      });
    }
    render() {
      return React.createElement(tagName, { style: this.props.style }, this.props.children);
    }
  };
}
<commit_msg>feat(proto): expose web component proto props onto react component<commit_after>import assign from 'object-assign';
import pascalCase from 'pascal-case';

const defaults = {
  React: window.React,
  ReactDOM: window.ReactDOM,
};

function syncEvent(node, eventName, newEventHandler) {
  const eventNameLc = eventName[0].toLowerCase() + eventName.substring(1);
  const eventStore = node.__events || (node.__events = {});
  const oldEventHandler = eventStore[eventNameLc];

  // Remove old listener so they don't double up.
  if (oldEventHandler) {
    node.removeEventListener(eventNameLc, oldEventHandler);
  }

  // Bind new listener.
  if (newEventHandler) {
    node.addEventListener(eventNameLc, eventStore[eventNameLc] = function handler(e) {
      newEventHandler.call(this, e);
    });
  }
}

export default function (CustomElement, opts) {
  opts = assign(defaults, opts);
  const tagName = (new CustomElement()).tagName;
  const displayName = pascalCase(tagName);
  const { React, ReactDOM } = opts;

  if (!React || !ReactDOM) {
    throw new Error('React and ReactDOM must be globally available or passed via opts.');
  }

  return class extends React.Component {
    static get displayName() {
      return displayName;
    }
    static get propTypes() {
      return {
        children: React.PropTypes.any,
        style: React.PropTypes.any,
      };
    }
    componentDidMount() {
      this.componentWillReceiveProps(this.props);
    }
    componentWillReceiveProps(props) {
      const node = ReactDOM.findDOMNode(this);
      for (var name in props) {
        if (name === 'children' || name === 'style') {
          continue;
        }

        if (name.indexOf('on') === 0) {
          syncEvent(node, name.substring(2), props[name]);
        } else {
          node[name] = props[name];
        }
      }
    }
    render() {
      return React.createElement(tagName, { style: this.props.style }, this.props.children);
    }
  };
}
<|endoftext|>