<commit_before>import Immutable from 'immutable';
import React, { createElement } from 'react';
import { Field } from 'redux-form';

/**
 * Renderer for a react-redux (v6) form via an Immutable JSON Schema
 *
 * Basic HTML is generated; Style yourself!
 */
export default class Renderer {

  constructor (options) {
    this.options = options || Immutable.Map({
      path: []
    });
  }

  renderObject = (schema, path, data) => {
    var chunkPromises = [];
    data = data || {};

    if (!schema.get('properties')) {
      if (schema.get('allOf') || schema.get('extends')) {
        return <fieldset key={path} />;
      }
      if (schema.get('oneOf')) {
        return <fieldset key={path} />;
      }
      if (schema.get('$ref')) {
        return this.getRef(schema.get('$ref')).then((subSchema) => {
          if (subSchema.get('properties')) {
            return this.renderObject(subSchema, path, data);
          } else {
            return this.renderChunk(path, subSchema, data);
          }
        });
      }

      if (schema.get('type') && schema.get('type') === 'array' && schema.get('items')) {
        chunkPromises.push(this.renderChunk(path, schema, data));
      }
    }

    let container = {
      key: path,
      disabled: schema.get('disabled'),
      children: []
    };

    if (schema.get('title')) {
      container.children.push(createElement('legend', {
        className: 'legend', children: [schema.get('title')]
      }));
    }

    if (schema.get('description')) {
      container.children.push(createElement('p', {
        children: [schema.get('description')]
      }));
    }

    schema.get('properties').map((propSchema, propName) => {
      if (schema.get('required') && schema.get('required').findEntry && schema.get('required').findEntry((prop) => {
        return prop === propName;
      })) {
        if (propSchema.get('type') !== 'object') {
          propSchema = propSchema.set('required', true);
        }
      }

      path.slice(0);
      path.push(propName);
      container.children.push(this.renderChunk(path, propSchema/*, data.get(propName)*/));
    });

    return createElement('fieldset', container);
  };

  /**
   * @param {Array} path
   * @param {Object} schema
   * @param {*} value
   */
  renderChunk = (path, schema, value) => {
    let propName = path.pop();
    let className = propName;
    if (!isNaN(parseInt(propName, 10))) {
      // singular class name from assumed multiple
      className = path[path.length - 1].slice(0, -1);
    }
    let id = 'root-' + (path.length ? path.join('-') + '-' : '') + propName;

    let classNames = ['schema-property', 'schema-property-' + className, 'schema-datatype-' + schema.get('type')];
    if (this.options.get('groupClass') && schema.get('type') !== 'object') {
      classNames.push(this.options.get('groupClass'));
    }

    let subPath = path.slice(0);
    let name = 'root' + (path.length ? '[' + path.join('][') + ']' : '') + '[' + propName + ']';
    subPath.push(propName);

    if ((value === undefined) && (schema['default'] !== undefined)) {
      value = schema['default'];
    }

    if (schema.get('renderer') === 'hidden') {
      return this.renderInput('hidden', schema, subPath, value, id, name);
    }

    let container = {className: classNames.join(' '), children: [], key: id};

    switch (schema.get('type')) {
      case undefined: // complex type
      case 'object':
        container.children.push(this.renderObject(schema, subPath, value));
        break;
      default:

        if (this.options.get('hasLabels') || this.options.get('hasLabels') === undefined) {
          container.children.push(createElement('label', {
            className: this.options.get('labelClass'),
            htmlFor: id, key: subPath.concat('label'),
            children: [schema.get('title') ? schema.get('title') : schema.get('description')]
          }));
        }

        container.children.push(this.renderType(schema, subPath, value, id, name));
        break;
    }

    return createElement('div', container);
  };

  renderType = (schema, subPath, value, id, name) => {
    if (schema.get('enum')) {
      return this.renderEnum(schema, subPath, value, id, name);
    }

    let type = 'text';
    switch (schema.get('type')) {
      case 'string':
        if (schema.get('format') === 'date') {
          type = 'date';
        }
        if (schema.get('format') === 'datetime') {
          type = 'datetime-local';
        }
        if (schema.get('format') === 'email') {
          type = 'email';
        }
        if (schema.get('renderer') === 'textarea') {
          type = 'textarea';
        }
        if (schema.get('renderer') === 'password') {
          type = 'password';
        }
        break;
      case 'integer':
      case 'number':
        type = 'number';
        break;
      case 'boolean':
        type = 'checkbox';
        break;
      default:
        throw new Error('Schema item "' + subPath.join('.') + '" is not valid');
    }
    if (schema.get('renderer') === 'display') {
      type = 'display';
    }
    return this.renderInput(type, schema, subPath, value, id, name);
  };

  renderInput = (type, schema, path, value, id, name) => {
    let component = this.renderInputComponent;
    if (type === 'textarea') {
      component = this.renderTextareaComponent;
    }
    if (type === 'hidden') {
      component = 'input';
    }
    if (type === 'display') {
      component = this.renderDisplayComponent;
    }

    return createElement(Field, {
      key: path,
      id: id,
      component: component,
      type: type,
      name: name,
      required: schema.get('required') ? 'required' : '',
      minLength: schema.get('minLength'),
      maxLength: schema.get('maxLength'),
      min: schema.get('min'),
      max: schema.get('max'),
      pattern: schema.get('pattern'),
      placeholder: schema.get('description'),
      autoComplete: schema.get('autocomplete')
    });
  };

  renderEnum = (schema, path, value, id, name) => {
    if (schema.get('renderer') === 'radiogroup') {
      return this.renderBooleanEnum(schema, path, value, id, name);
    }

    return createElement(Field, {
      component: this.renderSelectComponent,
      key: path,
      id: id,
      name: name,
      required: schema.get('required') ? 'required' : '',
      multiple: schema.get('multiple'),
      pattern: schema.get('pattern'),
      placeholder: schema.get('description'),
      autoComplete: schema.get('autocomplete'),
      children: schema.get('enum').map((value, idx) => {
        return createElement('option', {
          key: value + idx,
          value: value,
          children: [
            schema.get('enum_titles') &&
            schema.get('enum_titles').get(idx) ? schema.get('enum_titles').get(idx) : value
          ]
        });
      })
    });
  };

  renderBooleanEnum = (schema, path, value, id, name) => {
    return createElement('div', {
      className: 'radiogroup ' + this.options.get('inputWrapperClass'),
      children: schema.get('enum').map((itemValue, idx) => {
        return createElement('label', {
          key: idx + itemValue,
          className: this.options.get('radioGroupInlineClass'),
          children: [
            createElement(Field, {
              key: name + itemValue,
              component: this.renderInputComponent,
              id: id + '-' + idx,
              type: 'radio',
              name: name,
              required: schema.get('required') ? 'required' : '',
              autoComplete: schema.get('autocomplete'),
              value: itemValue
            }),
            schema.get('enum_titles') &&
            schema.get('enum_titles').get(idx) ? schema.get('enum_titles').get(idx) : itemValue
          ]
        });
      })
    });
  };

  renderDisplayComponent = (field) => {
    return this.renderFieldComponent('div', field);
  };

  renderSelectComponent = (field) => {
    return this.renderFieldComponent('select', field);
  };

  renderTextareaComponent = (field) => {
    return this.renderFieldComponent('textarea', field);
  };

  renderInputComponent = (field) => {
    return this.renderFieldComponent('input', field);
  };

  renderFieldComponent = (type, field) => {
    if (field.type === 'radio') {
      return this.renderFieldInputComponent(type, field);
    }

    let children = [
      this.renderFieldInputComponent(type, field),
      field.touched && field.error ? createElement('span', {className: 'error', children: [field.error]}) : null
    ];

    return createElement('div', {
      className: this.options.get('inputWrapperClass'),
      key: field.id,
      children: field.type === 'checkbox' ? createElement('div', {
        className: 'checkbox',
        children: children
      }) : children
    });
  };

  renderFieldInputComponent (type, field) {
    if (type === 'div') {
      return createElement(type, {
        className: this.options.get('inputClass') + ' form-control-display',
        children: [field.input.value]
      });
    }
    return createElement(type, {
      className: (['checkbox', 'radio'].indexOf(field.type) !== -1 ? '' : this.options.get('inputClass')) +
        (field.error ? 'user-error' : ''),
      ... field.input
    });
  }

}
<commit_msg>fix for schema "type" as an array<commit_after>import Immutable from 'immutable';
import React, { createElement } from 'react';
import { Field } from 'redux-form';

/**
 * Renderer for a react-redux (v6) form via an Immutable JSON Schema
 *
 * Basic HTML is generated; Style yourself!
 */
export default class Renderer {

  constructor (options) {
    this.options = options || Immutable.Map({
      path: []
    });
  }

  renderObject = (schema, path, data) => {
    var chunkPromises = [];
    data = data || {};

    if (!schema.get('properties')) {
      if (schema.get('allOf') || schema.get('extends')) {
        return <fieldset key={path} />;
      }
      if (schema.get('oneOf')) {
        return <fieldset key={path} />;
      }
      if (schema.get('$ref')) {
        return this.getRef(schema.get('$ref')).then((subSchema) => {
          if (subSchema.get('properties')) {
            return this.renderObject(subSchema, path, data);
          } else {
            return this.renderChunk(path, subSchema, data);
          }
        });
      }

      if (schema.get('type') && schema.get('type') === 'array' && schema.get('items')) {
        chunkPromises.push(this.renderChunk(path, schema, data));
      }
    }

    let container = {
      key: path,
      disabled: schema.get('disabled'),
      children: []
    };

    if (schema.get('title')) {
      container.children.push(createElement('legend', {
        className: 'legend', children: [schema.get('title')]
      }));
    }

    if (schema.get('description')) {
      container.children.push(createElement('p', {
        children: [schema.get('description')]
      }));
    }

    schema.get('properties').map((propSchema, propName) => {
      if (schema.get('required') && schema.get('required').findEntry && schema.get('required').findEntry((prop) => {
        return prop === propName;
      })) {
        if (propSchema.get('type') !== 'object') {
          propSchema = propSchema.set('required', true);
        }
      }

      path.slice(0);
      path.push(propName);
      container.children.push(this.renderChunk(path, propSchema/*, data.get(propName)*/));
    });

    return createElement('fieldset', container);
  };

  /**
   * @param {Array} path
   * @param {Object} schema
   * @param {*} value
   */
  renderChunk = (path, schema, value) => {
    let propName = path.pop();
    let className = propName;
    if (!isNaN(parseInt(propName, 10))) {
      // singular class name from assumed multiple
      className = path[path.length - 1].slice(0, -1);
    }
    let id = 'root-' + (path.length ? path.join('-') + '-' : '') + propName;

    let classNames = ['schema-property', 'schema-property-' + className, 'schema-datatype-' + schema.get('type')];
    if (this.options.get('groupClass') && schema.get('type') !== 'object') {
      classNames.push(this.options.get('groupClass'));
    }

    let subPath = path.slice(0);
    let name = 'root' + (path.length ? '[' + path.join('][') + ']' : '') + '[' + propName + ']';
    subPath.push(propName);

    if ((value === undefined) && (schema['default'] !== undefined)) {
      value = schema['default'];
    }

    if (schema.get('renderer') === 'hidden') {
      return this.renderInput('hidden', schema, subPath, value, id, name);
    }

    let container = {className: classNames.join(' '), children: [], key: id};

    switch (schema.get('type')) {
      case undefined: // complex type
      case 'object':
        container.children.push(this.renderObject(schema, subPath, value));
        break;
      default:

        if (this.options.get('hasLabels') || this.options.get('hasLabels') === undefined) {
          container.children.push(createElement('label', {
            className: this.options.get('labelClass'),
            htmlFor: id, key: subPath.concat('label'),
            children: [schema.get('title') ? schema.get('title') : schema.get('description')]
          }));
        }

        container.children.push(this.renderType(schema, subPath, value, id, name));
        break;
    }

    return createElement('div', container);
  };

  renderType = (schema, subPath, value, id, name) => {
    if (schema.get('enum')) {
      return this.renderEnum(schema, subPath, value, id, name);
    }

    let type = 'text';

    // could not be a string (array of types is allowed). .in this case wew render a "string" input
    if (typeof schema.get('type') !== 'string') {
      schema = schema.set('type', 'string');
    }

    switch (schema.get('type')) {
      case 'string':
        if (schema.get('format') === 'date') {
          type = 'date';
        }
        if (schema.get('format') === 'datetime') {
          type = 'datetime-local';
        }
        if (schema.get('format') === 'email') {
          type = 'email';
        }
        if (schema.get('renderer') === 'textarea') {
          type = 'textarea';
        }
        if (schema.get('renderer') === 'password') {
          type = 'password';
        }
        break;
      case 'integer':
      case 'number':
        type = 'number';
        break;
      case 'boolean':
        type = 'checkbox';
        break;
      default:
        throw new Error('Schema item "' + subPath.join('.') + '" is not valid');
    }
    if (schema.get('renderer') === 'display') {
      type = 'display';
    }
    return this.renderInput(type, schema, subPath, value, id, name);
  };

  renderInput = (type, schema, path, value, id, name) => {
    let component = this.renderInputComponent;
    if (type === 'textarea') {
      component = this.renderTextareaComponent;
    }
    if (type === 'hidden') {
      component = 'input';
    }
    if (type === 'display') {
      component = this.renderDisplayComponent;
    }

    return createElement(Field, {
      key: path,
      id: id,
      component: component,
      type: type,
      name: name,
      required: schema.get('required') ? 'required' : '',
      minLength: schema.get('minLength'),
      maxLength: schema.get('maxLength'),
      min: schema.get('min'),
      max: schema.get('max'),
      pattern: schema.get('pattern'),
      placeholder: schema.get('description'),
      autoComplete: schema.get('autocomplete')
    });
  };

  renderEnum = (schema, path, value, id, name) => {
    if (schema.get('renderer') === 'radiogroup') {
      return this.renderBooleanEnum(schema, path, value, id, name);
    }

    return createElement(Field, {
      component: this.renderSelectComponent,
      key: path,
      id: id,
      name: name,
      required: schema.get('required') ? 'required' : '',
      multiple: schema.get('multiple'),
      pattern: schema.get('pattern'),
      placeholder: schema.get('description'),
      autoComplete: schema.get('autocomplete'),
      children: schema.get('enum').map((value, idx) => {
        return createElement('option', {
          key: value + idx,
          value: value,
          children: [
            schema.get('enum_titles') &&
            schema.get('enum_titles').get(idx) ? schema.get('enum_titles').get(idx) : value
          ]
        });
      })
    });
  };

  renderBooleanEnum = (schema, path, value, id, name) => {
    return createElement('div', {
      className: 'radiogroup ' + this.options.get('inputWrapperClass'),
      children: schema.get('enum').map((itemValue, idx) => {
        return createElement('label', {
          key: idx + itemValue,
          className: this.options.get('radioGroupInlineClass'),
          children: [
            createElement(Field, {
              key: name + itemValue,
              component: this.renderInputComponent,
              id: id + '-' + idx,
              type: 'radio',
              name: name,
              required: schema.get('required') ? 'required' : '',
              autoComplete: schema.get('autocomplete'),
              value: itemValue
            }),
            schema.get('enum_titles') &&
            schema.get('enum_titles').get(idx) ? schema.get('enum_titles').get(idx) : itemValue
          ]
        });
      })
    });
  };

  renderDisplayComponent = (field) => {
    return this.renderFieldComponent('div', field);
  };

  renderSelectComponent = (field) => {
    return this.renderFieldComponent('select', field);
  };

  renderTextareaComponent = (field) => {
    return this.renderFieldComponent('textarea', field);
  };

  renderInputComponent = (field) => {
    return this.renderFieldComponent('input', field);
  };

  renderFieldComponent = (type, field) => {
    if (field.type === 'radio') {
      return this.renderFieldInputComponent(type, field);
    }

    let children = [
      this.renderFieldInputComponent(type, field),
      field.touched && field.error ? createElement('span', {className: 'error', children: [field.error]}) : null
    ];

    return createElement('div', {
      className: this.options.get('inputWrapperClass'),
      key: field.id,
      children: field.type === 'checkbox' ? createElement('div', {
        className: 'checkbox',
        children: children
      }) : children
    });
  };

  renderFieldInputComponent (type, field) {
    if (type === 'div') {
      return createElement(type, {
        className: this.options.get('inputClass') + ' form-control-display',
        children: [field.input.value]
      });
    }
    return createElement(type, {
      className: (['checkbox', 'radio'].indexOf(field.type) !== -1 ? '' : this.options.get('inputClass')) +
        (field.error ? 'user-error' : ''),
      ... field.input
    });
  }

}
<|endoftext|>


<commit_before>/* global describe, it */

import 'should';
import yaml from 'js-yaml';
import eslintSpecialParser from '../../src/special/eslint';

const testCases = [
  {
    name: 'ignore when user not extends any config in `.eslintrc`',
    content: {},
    expected: [],
  },
  {
    name: 'detect specific parser',
    content: {
      parser: 'babel-eslint',
    },
    expected: [
      'babel-eslint',
    ],
  },
  {
    name: 'detect specific plugins',
    content: {
      plugins: ['mocha'],
    },
    expected: [
      'eslint-plugin-mocha',
    ],
  },
  {
    name: 'handle eslint config with short name',
    content: {
      extends: 'preset',
    },
    expected: [
      'eslint-config-preset',
    ],
  },
  {
    name: 'handle eslint config with full name',
    content: {
      extends: 'eslint-config-preset',
    },
    expected: [
      'eslint-config-preset',
    ],
  },
  {
    name: 'handle eslint config from package module',
    content: {
      extends: 'airbnb/base',
    },
    expected: [
      'eslint-config-airbnb',
    ],
  },
  {
    name: 'handle eslint config with undeclared plugins',
    content: {
      extends: 'airbnb/react',
    },
    expected: [
      'eslint-config-airbnb',
      'eslint-plugin-react',
    ],
  },
  {
    name: 'handle eslint config with nested extends',
    content: {
      extends: 'airbnb',
    },
    expected: [
      'eslint-config-airbnb',
      'eslint-plugin-react',
    ],
  },
  {
    name: 'skip eslint recommended config',
    content: {
      extends: 'eslint:recommended',
    },
    expected: [],
  },
  {
    name: 'handle config of absolute local path',
    content: {
      extends: '/path/to/config',
    },
    expected: [],
  },
  {
    name: 'handle config of relative local path',
    content: {
      extends: './config',
    },
    expected: [],
  },
  {
    name: 'handle config of scoped module',
    content: {
      extends: '@my-org/short-customized',
    },
    expected: [
      '@my-org/eslint-config-short-customized',
    ],
  },
  {
    name: 'handle config of scoped module with full name',
    content: {
      extends: '@my-org/eslint-config-long-customized',
    },
    expected: [
      '@my-org/eslint-config-long-customized',
    ],
  },
];

function testEslint(deps, content) {
  [
    '/path/to/.eslintrc',
    '/path/to/.eslintrc.js',
    '/path/to/.eslintrc.json',
    '/path/to/.eslintrc.yml',
    '/path/to/.eslintrc.yaml',
  ].forEach((pathToEslintrc) => {
    const result = eslintSpecialParser(
      content, pathToEslintrc, deps, __dirname);

    result.should.deepEqual(deps);
  });
}

describe('eslint special parser', () => {
  it('should ignore when filename is not `.eslintrc`', () => {
    const result = eslintSpecialParser('content', '/a/file');
    result.should.deepEqual([]);
  });

  it('should handle parse error', () =>
    testEslint([], '{ this is an invalid JSON string'));

  it('should handle non-standard JSON content', () =>
    testEslint(
      testCases[1].expected,
      `${JSON.stringify(testCases[1].content)}\n// this is ignored`));

  describe('with JSON format', () =>
    testCases.forEach(testCase =>
      it(`should ${testCase.name}`, () =>
        testEslint(testCase.expected, JSON.stringify(testCase.content)))));

  describe('with YAML format', () =>
    testCases.forEach(testCase =>
      it(`should ${testCase.name}`, () =>
        testEslint(testCase.expected, yaml.safeDump(testCase.content)))));
});
<commit_msg>Add test cases for eslint’s ‘plugin:’ prefixed presets<commit_after>/* global describe, it */

import 'should';
import yaml from 'js-yaml';
import eslintSpecialParser from '../../src/special/eslint';

const testCases = [
  {
    name: 'ignore when user not extends any config in `.eslintrc`',
    content: {},
    expected: [],
  },
  {
    name: 'detect specific parser',
    content: {
      parser: 'babel-eslint',
    },
    expected: [
      'babel-eslint',
    ],
  },
  {
    name: 'detect specific plugins',
    content: {
      plugins: ['mocha'],
    },
    expected: [
      'eslint-plugin-mocha',
    ],
  },
  {
    name: 'handle eslint config with short name',
    content: {
      extends: 'preset',
    },
    expected: [
      'eslint-config-preset',
    ],
  },
  {
    name: 'handle eslint config with full name',
    content: {
      extends: 'eslint-config-preset',
    },
    expected: [
      'eslint-config-preset',
    ],
  },
  {
    name: 'handle eslint config from package module',
    content: {
      extends: 'airbnb/base',
    },
    expected: [
      'eslint-config-airbnb',
    ],
  },
  {
    name: 'handle eslint config with undeclared plugins',
    content: {
      extends: 'airbnb/react',
    },
    expected: [
      'eslint-config-airbnb',
      'eslint-plugin-react',
    ],
  },
  {
    name: 'handle eslint config with nested extends',
    content: {
      extends: 'airbnb',
    },
    expected: [
      'eslint-config-airbnb',
      'eslint-plugin-react',
    ],
  },
  {
    name: 'skip eslint recommended config',
    content: {
      extends: 'eslint:recommended',
    },
    expected: [],
  },
  {
    name: 'handle config of absolute local path',
    content: {
      extends: '/path/to/config',
    },
    expected: [],
  },
  {
    name: 'handle config of relative local path',
    content: {
      extends: './config',
    },
    expected: [],
  },
  {
    name: 'handle config of scoped module',
    content: {
      extends: '@my-org/short-customized',
    },
    expected: [
      '@my-org/eslint-config-short-customized',
    ],
  },
  {
    name: 'handle config of scoped module with full name',
    content: {
      extends: '@my-org/eslint-config-long-customized',
    },
    expected: [
      '@my-org/eslint-config-long-customized',
    ],
  },
  {
    name: 'handle config from plugin with short name',
    content: {
      extends: 'plugin:node/recommended',
    },
    expected: [
      'eslint-plugin-node',
    ],
  },
  {
    name: 'handle config from plugin with full name',
    content: {
      extends: 'plugin:eslint-plugin-node/recommended',
    },
    expected: [
      'eslint-plugin-node',
    ],
  },
  {
    name: 'handle config from scoped plugin with short name',
    content: {
      extends: 'plugin:@my-org/short-customized/recommended',
    },
    expected: [
      '@my-org/eslint-plugin-short-customized',
    ],
  },
  {
    name: 'handle config from scoped plugin with full name',
    content: {
      extends: 'plugin:@my-org/eslint-plugin-long-customized/recommended',
    },
    expected: [
      '@my-org/eslint-plugin-long-customized',
    ],
  },
];

function testEslint(deps, content) {
  [
    '/path/to/.eslintrc',
    '/path/to/.eslintrc.js',
    '/path/to/.eslintrc.json',
    '/path/to/.eslintrc.yml',
    '/path/to/.eslintrc.yaml',
  ].forEach((pathToEslintrc) => {
    const result = eslintSpecialParser(
      content, pathToEslintrc, deps, __dirname);

    result.should.deepEqual(deps);
  });
}

describe('eslint special parser', () => {
  it('should ignore when filename is not `.eslintrc`', () => {
    const result = eslintSpecialParser('content', '/a/file');
    result.should.deepEqual([]);
  });

  it('should handle parse error', () =>
    testEslint([], '{ this is an invalid JSON string'));

  it('should handle non-standard JSON content', () =>
    testEslint(
      testCases[1].expected,
      `${JSON.stringify(testCases[1].content)}\n// this is ignored`));

  describe('with JSON format', () =>
    testCases.forEach(testCase =>
      it(`should ${testCase.name}`, () =>
        testEslint(testCase.expected, JSON.stringify(testCase.content)))));

  describe('with YAML format', () =>
    testCases.forEach(testCase =>
      it(`should ${testCase.name}`, () =>
        testEslint(testCase.expected, yaml.safeDump(testCase.content)))));
});
<|endoftext|>


<commit_before>/*
* @Author: mjreich
* @Date:   2015-05-18 17:03:15
* @Last Modified 2016-08-25
* @Last Modified time: 2016-08-25 11:12:35
*/

import _ from 'underscore'
import util from 'util'
import fs from 'fs'
import domain from 'domain'
import path from 'path'

import Dispatcher from './Dispatcher'
import ModuleProxy from './ModuleProxy'
import PluginManager from './PluginManager'
import ConfigurationManager from './ConfigurationManager'
import Watcher from './Watcher'
import {logger} from './Logger'

var _defaultConfig = {
  siteName: 'Nxus App',
  host: 'localhost',
  baseUrl: 'localhost:3001',
  appName: 'App',
  namespace: 'nxus',
  appDir: process.cwd()
}

_.mixin(require('underscore.deep'))

var startupBanner = " _______ _______ __    _ __   __ __   __ _______ __  \n"+
    "|       |       |  |  | |  |_|  |  | |  |       |  | \n"+
    "|    ___|   _   |   |_| |       |  | |  |  _____|  | \n"+
    "|   | __|  | |  |       |       |  |_|  | |_____|  | \n"+
    "|   ||  |  |_|  |  _    ||     ||       |_____  |__| \n"+
    "|   |_| |       | | |   |   _   |       |_____| |__  \n"+
    "|_______|_______|_|  |__|__| |__|_______|_______|__| \n"

/**
 *
 * The Core Application class.
 *
 * ### Configuration Options
 *
 * Available options are:
 *
 * | Name | Description |
 * | --- | --- |
 * | appName | the name of your app. Will be used for console logging. |
 * | appDir | the location to use to load the default 'package.json' file. |
 * | namespace | any additional namespaces to use to load modules in the node\_modules folder. Can be a string or array of strings. |
 * | modules | an array of paths to require into the application |
 * | debug | Boolean to display debug messages, including startup banner |
 * | script | Boolean to indicate the application is a CLI script, silences all logging/output messages except for explicit console.log calls |
 * | silent | Don't show any console output. Useful for CLI scripts. |
 *
 * @param {Object} opts the configuration options
 * @extends Dispatcher
 * @example
 * import {Application} from 'nxus-core'
 *
 * let app = new Application()
 *
 * app.start()
 *
 * export default app
 *
 *
 */

export default class Application extends Dispatcher {

  constructor(opts = {}) {
    super()
    this._opts = opts
    this._modules = {}
    this._moduleProxies = {}
    this._pluginInfo = {}
    this._pluginInstances = {}
    this._currentStage = null
    this._banner = opts.banner || startupBanner
    this._defaultConfig = {};
    this.config = {};

    this._bootEvents = [
      'init',
      'load',
      'startup',
      'launch'
    ]

    this._setupConfig()
    this._setupLog()

    this.after('launch', () => {
      this._writeConfig()
    })

    this.registeredModules = {}
    this.on('registeredModule', (name) => {
      this.registeredModules[name] = true
    })
  }

  _showBanner() {
      console.log(" \n"+this._banner)
  }

  /**
   * Sets up the internal config
   *
   * @private
   */
  _setupConfig() {
    this.writeDefaultConfig(null, _defaultConfig)

    this.config = Object.assign(this.config, this._opts, new ConfigurationManager(this.config).getConfig())
    if(typeof this.config.debug === 'undefined') this.config.debug = (!process.env.NODE_ENV || process.env.NODE_ENV == 'development')
  }

  /**
   * Sets up the internal log object. Falls back to console.log.
   *
   * @private
   */
  _setupLog() {
    if(this.config.silent) {
      this.log = function() {}
      Object.assign(this.log, {
        debug: () => {},
        info: () => {},
        warn: () => {},
        error: () => {}
      })
    } else {
      this.log = logger
    }
  }

  /**
   * Loads the internal _modules object by instantiating the PluginManager class.
   *
   * @private
   */
  _setupPluginManager() {
    this._modules = new PluginManager(this, this.config)
    _.each(this._modules, (plugin) => {
      this._pluginInfo[plugin._pluginInfo.name] = plugin._pluginInfo
    })
  }

  /**
   * Returns an internal ModuleProxy object for the given name.
   *
   * @param  {string} name The name of the module to return
   * @return {ModuleProxy}
   */
  get(name) {
    if(!this._moduleProxies[name]) {
      this._moduleProxies[name] = new ModuleProxy(this, name)
    }
    return this._moduleProxies[name]
  }

  /**
   * Initializes the application by loading plugins, then booting the application.
   *
   * **Note**: this should rarely be called directly. Instead use #start
   *
   * @return {Promise}
   */
  init() {
    this._pluginInstances = {}
    return this._loadPlugins().then(this.boot.bind(this)).then(() => {
      if (!this.config.script && this.config.NODE_ENV != 'production') {
        this.log.debug('Setting up App watcher')
        this.appWatcher = new Watcher(this, this._getWatchPaths(), 'change', this._getAppIgnorePaths())
      }
    });
  }

  /**
   * Boots the application, cycling through the internal boot stages.
   *
   * **Note**: Should rarely be called directly. Instead use #start
   *
   * @return {Promise}
   */
  boot() {
    if (this.config.debug) this.log.info('Booting Application')
    return new Promise.mapSeries(this._bootEvents, (e) => {
      this._currentStage = e
      if (this.config.debug) this.log.info(`Booting Stage: ${e}`)
      return this.emit(e)
    })
  }

  /**
   * Stops the currently running application, removing all event listeners.
   *
   * @return {Promise}
   */
  stop() {
    if (this.config.debug) this.log.info('Stopping')
    return this.emit("stop").then(() => {
      return Promise.resolve().then(() => {
        Object.keys(this._events).map((event) =>  this.removeAllListeners(event) );
      })
    })
  }

  /**
   * Starts the Nxus application.
   *
   * @return {Promise}
   */
  start() {
    if(!this.config.silent) this._showBanner()
<<<<<<< HEAD
    this.log.info(this.config.appName+' Starting at', new Date())
=======
    this.log.info(this.config.appName+' Starting')
>>>>>>> f86c4b5d628c22151c54ee4580458f3bab0cc430
    return this.init()
  }

  /**
   * Restarts the Nxus application.
   *
   * @return {Promise}
   */
  restart() {
    this._currentStage = 'restarting'
    this.log.info("Restarting App");
    return this._invalidatePluginsInRequireCache()
    .then(this.stop.bind(this))
    .then(this._setupConfig.bind(this))
    .then(this.start.bind(this))
  }

  writeDefaultConfig(name, opts) {
    if(name && name != "") {
      this._defaultConfig[name] = _.deepClone(opts)
      if(!this.config[name]) this.config[name] = opts
    } else {
      Object.assign(this._defaultConfig, opts)
      Object.assign(this.config, opts)
    }
  }

  _writeConfig() {
    if(!this.config.config) return
    var configFile = this.config.config
    var config = {}
    if(fs.existsSync(configFile)) config = JSON.parse(fs.readFileSync(configFile))
    _.each(this._defaultConfig, (value, key) => {
      if(!config[key]) {
        config[key] = value
      }
    })
    fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
  }

  /**
   * Invalidates the internal require plugin cache, ensuring all plugins are reloaded from the files.
   *
   * @private
   * @return {Promise}
   */
  _invalidatePluginsInRequireCache() {
    let nxusModules = this._modules.map((x) => { return x._pluginInfo.modulePath })

    return new Promise((resolve) => {
      let invalid = new RegExp("^.*("+nxusModules.join("|")+").*.js")
      _.each(require.cache, (v, k) => {
        if (invalid.test(k)) {
          delete require.cache[k]
        }
      })
      resolve()
    })
  }

  /**
   * Returns an array of watch paths, either as defined by `config.watch` or the default paths
   * `/node_modules` and `/modules`
   *
   * @private
   * @return {Array}
   */
  _getWatchPaths() {
    let watch = ["**/node_modules/**", "**/modules/**"]
    if(_.isString(this.config.watch)) this.config.watch = [this.config.watch]
    return watch.concat(this.config.watch || [])
  }

  /**
   * Returns an array of paths to ignore, used by the watcher.
   *
   * @private
   * @return {Array}
   */
  _getAppIgnorePaths() {
    var opts = this.config.ignore || [];
    return opts.concat([
      '**/.git/**',
      '**.ejs'
    ]);
  }

  /**
   * Loads the plugins, then boots them and handles any errors.
   *
   * @private
   * @return {Promise}
   */
  _loadPlugins() {
    this.log.info('Loading modules')
    this._setupPluginManager()
    return this._bootPlugins().catch((err) => {
      if (err) {
        this.log.error(err)
      }
    })
  }

  /**
   * Iterates through all loaded plugins, instantiating them and returning a promise once every plugin has successfully started.
   *
   * @private
   * @return {Promise}
   */
  _bootPlugins() {
    return Promise.map(
      this._modules,
      this._bootPlugin.bind(this)
    ).catch((e) => {
      this.log.error('Error booting module', e)
      this.log.error(e.stack);
    })
  }

  /**
   * Accepts an instantiable object (function or class) as a plugin, then boots it.
   *
   * @private
   * @param  {Function|Class} plugin the instantiable plugin
   * @return {[type]}
   */
  _bootPlugin(plugin) {
    var name = plugin._pluginInfo.name
    let pluginInstance = null
    //if (this.config.debug) console.log(' ------- ', plugin)
    if (this._pluginInstances[name] !== undefined) {
      this.log.error('Duplicate module found', name)
      process.exit()
    }
    try {
      this.log.debug('Booting Module', name)
      if(plugin.default)
        plugin = plugin.default
      pluginInstance = new plugin(this);
      this._pluginInstances[name] = pluginInstance
    } catch(e) {
      this.log.error('Error booting module '+name, e)
      this.log.error(e.stack)
      process.exit()
    }
    return Promise.resolve(pluginInstance)
  }

}

export let application = new Application()
<commit_msg>For real now, fixing merge conflicts<commit_after>/*
* @Author: mjreich
* @Date:   2015-05-18 17:03:15
* @Last Modified 2016-08-25
* @Last Modified time: 2016-08-25 14:30:57
*/

import _ from 'underscore'
import util from 'util'
import fs from 'fs'
import domain from 'domain'
import path from 'path'

import Dispatcher from './Dispatcher'
import ModuleProxy from './ModuleProxy'
import PluginManager from './PluginManager'
import ConfigurationManager from './ConfigurationManager'
import Watcher from './Watcher'
import {logger} from './Logger'

var _defaultConfig = {
  siteName: 'Nxus App',
  host: 'localhost',
  baseUrl: 'localhost:3001',
  appName: 'App',
  namespace: 'nxus',
  appDir: process.cwd()
}

_.mixin(require('underscore.deep'))

var startupBanner = " _______ _______ __    _ __   __ __   __ _______ __  \n"+
    "|       |       |  |  | |  |_|  |  | |  |       |  | \n"+
    "|    ___|   _   |   |_| |       |  | |  |  _____|  | \n"+
    "|   | __|  | |  |       |       |  |_|  | |_____|  | \n"+
    "|   ||  |  |_|  |  _    ||     ||       |_____  |__| \n"+
    "|   |_| |       | | |   |   _   |       |_____| |__  \n"+
    "|_______|_______|_|  |__|__| |__|_______|_______|__| \n"

/**
 *
 * The Core Application class.
 *
 * ### Configuration Options
 *
 * Available options are:
 *
 * | Name | Description |
 * | --- | --- |
 * | appName | the name of your app. Will be used for console logging. |
 * | appDir | the location to use to load the default 'package.json' file. |
 * | namespace | any additional namespaces to use to load modules in the node\_modules folder. Can be a string or array of strings. |
 * | modules | an array of paths to require into the application |
 * | debug | Boolean to display debug messages, including startup banner |
 * | script | Boolean to indicate the application is a CLI script, silences all logging/output messages except for explicit console.log calls |
 * | silent | Don't show any console output. Useful for CLI scripts. |
 *
 * @param {Object} opts the configuration options
 * @extends Dispatcher
 * @example
 * import {Application} from 'nxus-core'
 *
 * let app = new Application()
 *
 * app.start()
 *
 * export default app
 *
 *
 */

export default class Application extends Dispatcher {

  constructor(opts = {}) {
    super()
    this._opts = opts
    this._modules = {}
    this._moduleProxies = {}
    this._pluginInfo = {}
    this._pluginInstances = {}
    this._currentStage = null
    this._banner = opts.banner || startupBanner
    this._defaultConfig = {};
    this.config = {};

    this._bootEvents = [
      'init',
      'load',
      'startup',
      'launch'
    ]

    this._setupConfig()
    this._setupLog()

    this.after('launch', () => {
      this._writeConfig()
    })

    this.registeredModules = {}
    this.on('registeredModule', (name) => {
      this.registeredModules[name] = true
    })
  }

  _showBanner() {
      console.log(" \n"+this._banner)
  }

  /**
   * Sets up the internal config
   *
   * @private
   */
  _setupConfig() {
    this.writeDefaultConfig(null, _defaultConfig)

    this.config = Object.assign(this.config, this._opts, new ConfigurationManager(this.config).getConfig())
    if(typeof this.config.debug === 'undefined') this.config.debug = (!process.env.NODE_ENV || process.env.NODE_ENV == 'development')
  }

  /**
   * Sets up the internal log object. Falls back to console.log.
   *
   * @private
   */
  _setupLog() {
    if(this.config.silent) {
      this.log = function() {}
      Object.assign(this.log, {
        debug: () => {},
        info: () => {},
        warn: () => {},
        error: () => {}
      })
    } else {
      this.log = logger
    }
  }

  /**
   * Loads the internal _modules object by instantiating the PluginManager class.
   *
   * @private
   */
  _setupPluginManager() {
    this._modules = new PluginManager(this, this.config)
    _.each(this._modules, (plugin) => {
      this._pluginInfo[plugin._pluginInfo.name] = plugin._pluginInfo
    })
  }

  /**
   * Returns an internal ModuleProxy object for the given name.
   *
   * @param  {string} name The name of the module to return
   * @return {ModuleProxy}
   */
  get(name) {
    if(!this._moduleProxies[name]) {
      this._moduleProxies[name] = new ModuleProxy(this, name)
    }
    return this._moduleProxies[name]
  }

  /**
   * Initializes the application by loading plugins, then booting the application.
   *
   * **Note**: this should rarely be called directly. Instead use #start
   *
   * @return {Promise}
   */
  init() {
    this._pluginInstances = {}
    return this._loadPlugins().then(this.boot.bind(this)).then(() => {
      if (!this.config.script && this.config.NODE_ENV != 'production') {
        this.log.debug('Setting up App watcher')
        this.appWatcher = new Watcher(this, this._getWatchPaths(), 'change', this._getAppIgnorePaths())
      }
    });
  }

  /**
   * Boots the application, cycling through the internal boot stages.
   *
   * **Note**: Should rarely be called directly. Instead use #start
   *
   * @return {Promise}
   */
  boot() {
    if (this.config.debug) this.log.info('Booting Application')
    return new Promise.mapSeries(this._bootEvents, (e) => {
      this._currentStage = e
      if (this.config.debug) this.log.info(`Booting Stage: ${e}`)
      return this.emit(e)
    })
  }

  /**
   * Stops the currently running application, removing all event listeners.
   *
   * @return {Promise}
   */
  stop() {
    if (this.config.debug) this.log.info('Stopping')
    return this.emit("stop").then(() => {
      return Promise.resolve().then(() => {
        Object.keys(this._events).map((event) =>  this.removeAllListeners(event) );
      })
    })
  }

  /**
   * Starts the Nxus application.
   *
   * @return {Promise}
   */
  start() {
    if(!this.config.silent) this._showBanner()
    this.log.info(this.config.appName+' Starting at', new Date())
    return this.init()
  }

  /**
   * Restarts the Nxus application.
   *
   * @return {Promise}
   */
  restart() {
    this._currentStage = 'restarting'
    this.log.info("Restarting App");
    return this._invalidatePluginsInRequireCache()
    .then(this.stop.bind(this))
    .then(this._setupConfig.bind(this))
    .then(this.start.bind(this))
  }

  writeDefaultConfig(name, opts) {
    if(name && name != "") {
      this._defaultConfig[name] = _.deepClone(opts)
      if(!this.config[name]) this.config[name] = opts
    } else {
      Object.assign(this._defaultConfig, opts)
      Object.assign(this.config, opts)
    }
  }

  _writeConfig() {
    if(!this.config.config) return
    var configFile = this.config.config
    var config = {}
    if(fs.existsSync(configFile)) config = JSON.parse(fs.readFileSync(configFile))
    _.each(this._defaultConfig, (value, key) => {
      if(!config[key]) {
        config[key] = value
      }
    })
    fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
  }

  /**
   * Invalidates the internal require plugin cache, ensuring all plugins are reloaded from the files.
   *
   * @private
   * @return {Promise}
   */
  _invalidatePluginsInRequireCache() {
    let nxusModules = this._modules.map((x) => { return x._pluginInfo.modulePath })

    return new Promise((resolve) => {
      let invalid = new RegExp("^.*("+nxusModules.join("|")+").*.js")
      _.each(require.cache, (v, k) => {
        if (invalid.test(k)) {
          delete require.cache[k]
        }
      })
      resolve()
    })
  }

  /**
   * Returns an array of watch paths, either as defined by `config.watch` or the default paths
   * `/node_modules` and `/modules`
   *
   * @private
   * @return {Array}
   */
  _getWatchPaths() {
    let watch = ["**/node_modules/**", "**/modules/**"]
    if(_.isString(this.config.watch)) this.config.watch = [this.config.watch]
    return watch.concat(this.config.watch || [])
  }

  /**
   * Returns an array of paths to ignore, used by the watcher.
   *
   * @private
   * @return {Array}
   */
  _getAppIgnorePaths() {
    var opts = this.config.ignore || [];
    return opts.concat([
      '**/.git/**',
      '**.ejs'
    ]);
  }

  /**
   * Loads the plugins, then boots them and handles any errors.
   *
   * @private
   * @return {Promise}
   */
  _loadPlugins() {
    this.log.info('Loading modules')
    this._setupPluginManager()
    return this._bootPlugins().catch((err) => {
      if (err) {
        this.log.error(err)
      }
    })
  }

  /**
   * Iterates through all loaded plugins, instantiating them and returning a promise once every plugin has successfully started.
   *
   * @private
   * @return {Promise}
   */
  _bootPlugins() {
    return Promise.map(
      this._modules,
      this._bootPlugin.bind(this)
    ).catch((e) => {
      this.log.error('Error booting module', e)
      this.log.error(e.stack);
    })
  }

  /**
   * Accepts an instantiable object (function or class) as a plugin, then boots it.
   *
   * @private
   * @param  {Function|Class} plugin the instantiable plugin
   * @return {[type]}
   */
  _bootPlugin(plugin) {
    var name = plugin._pluginInfo.name
    let pluginInstance = null
    //if (this.config.debug) console.log(' ------- ', plugin)
    if (this._pluginInstances[name] !== undefined) {
      this.log.error('Duplicate module found', name)
      process.exit()
    }
    try {
      this.log.debug('Booting Module', name)
      if(plugin.default)
        plugin = plugin.default
      pluginInstance = new plugin(this);
      this._pluginInstances[name] = pluginInstance
    } catch(e) {
      this.log.error('Error booting module '+name, e)
      this.log.error(e.stack)
      process.exit()
    }
    return Promise.resolve(pluginInstance)
  }

}

export let application = new Application()
<|endoftext|>


<commit_before>require('dotenv').load(); // Load env vars
const http             = require('http');
const querystring      = require('querystring');
const Discord          = require('discord.js'); // Discord API
const ytdl             = require('ytdl-core');  // Stream youtube mp3s
const bot              = new Discord.Client();  // Sets up bot discord client API
const youtube          = require('./youtube');
const hostname         = 'localhost';
const port             = 9999;
const token            = process.env.TOKEN;
const streamOptions    = { seek: 0, volume: .07 };
const dispatcher       = {}; // Stores reference to the mp3 stream
const yt               = youtube(process.env.YOUTUBE_API_KEY, querystring);
const getSearchResults = require('./getSearchResults');
const { parseCommand,
        parseVoiceChannelName,
        parseSong,
        playSong,
        volumeLevel,
        joinChannel,
        isConductor,
        formatHelpMessage }  = require('./helpers');

// Basic web server
const server = http.createServer( ( req, res ) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World \n');
});

// Log when a connection is made
server.listen( port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

bot.on('ready', () => {
  console.log(`Login in as ${ bot.user.username }`);
});

const Commands = ({ bot, ytdl, streamOptions, dispatcher, message }) => {
  return {
    '$join': function() {
      joinChannel(bot, parseVoiceChannelName(message), message);
    },
    '$play': function() {
      let song = parseSong(message.content);
      getSearchResults(
        playSong,
        yt.generateSearchUri(song),
        yt.generateVideoLink,
        message,
        dispatcher,
        bot.channels,
        ytdl,
        streamOptions
      );
    },
    '$stop': function() {
      if (dispatcher.stream) {
        dispatcher.stream.end();
      }
    },
    '$volume': function() {
      const newLevel = volumeLevel(message.content);

      if (newLevel > 1) {
        message.reply(`${ newLevel } is far too loud. 0-1 is a good range.`);
        return;
      } else if (isNaN(newLevel)) {
        message.reply(`Your volume level wasn't a number. Try again!`);
        return;
      }

      if (dispatcher.stream) {
        // Sets the volume relative to the input stream
        // 1 is normal, 0.5 is half, 2 is double.
        dispatcher.stream.setVolume(newLevel);
      }
    },
    '$pause': function() {
      if (dispatcher.stream) {
        dispatcher.stream.pause();
        message.reply('Song paused. Use $resume to resume playback');
      }
    },
    '$resume': function() {
      if (dispatcher.stream) {
        dispatcher.stream.resume();
        message.reply('Resuming playback!');
      }
    },
    '$help': function() {
      const commands = [
        '$play [songname] | play a song or video (audio only)',
        '$stop | stops playback of the current song',
        '$pause | pauses playback of the current song',
        '$resume | resumes playback of the current song',
        '$join [channelname] | join the specified channel (be sure to check your spelling - damn lazy programmer...)',
        '$volume [volumelevel - ex. 1 (full volume), ex. .5 (half volume)] | sets the volume of the current song'
      ]
      message.reply(formatHelpMessage(commands));
    }
  };
};

bot.on('message', message => {
  const theMatrix  = bot.guilds.get(process.env.MATRIX_GUILD_ID);
  const conductors = theMatrix.roles.get(process.env.CONDUCTOR_ID).members;
  const command    = parseCommand(message.content);
  const channels   = bot.channels;

  if (!conductors.find(conductor => conductor.user.username === message.author.username)) {
    return;
  }

  // TODO: use a generator function to update the command API
  // instead of instantiating the class on every message event.
  const commands = Commands({
    bot,
    ytdl,
    streamOptions,
    dispatcher,
    message
  });

  if (typeof commands[command] === 'function') {
    commands[command](channels);
  } else if (!commands[command] && command[0] === '$') {
    message.reply('Command not found. Use $help to list available commands.');
  }

});

bot.login(token);
<commit_msg>Use generator to take new message everytime<commit_after>require('dotenv').load(); // Load env vars
const http             = require('http');
const querystring      = require('querystring');
const Discord          = require('discord.js'); // Discord API
const ytdl             = require('ytdl-core');  // Stream youtube mp3s
const client              = new Discord.Client();  // Sets up client discord client API
const youtube          = require('./youtube');
const hostname         = 'localhost';
const port             = 9999;
const token            = process.env.TOKEN;
const streamOptions    = { seek: 0, volume: .07 };
const dispatcher       = {}; // Stores reference to the mp3 stream
const yt               = youtube(process.env.YOUTUBE_API_KEY, querystring);
const getSearchResults = require('./getSearchResults');
const { parseCommand,
        parseVoiceChannelName,
        parseSong,
        playSong,
        volumeLevel,
        joinChannel,
        isConductor,
        formatHelpMessage }  = require('./helpers');

// Basic web server
const server = http.createServer( ( req, res ) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World \n');
});

// Log when a connection is made
server.listen( port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

client.on('ready', () => {
  console.log(`Login in as ${ client.user.username }`);
});

const BotGenerator = ({ client, ytdl, streamOptions, dispatcher }) => {
  return message => {
    return {
      '$join': function() {
        joinChannel(client, parseVoiceChannelName(message), message);
      },
      '$play': function() {
        let song = parseSong(message.content);
        getSearchResults(
          playSong,
          yt.generateSearchUri(song),
          yt.generateVideoLink,
          message,
          dispatcher,
          client.channels,
          ytdl,
          streamOptions
        );
      },
      '$stop': function() {
        if (dispatcher.stream) {
          dispatcher.stream.end();
        }
      },
      '$volume': function() {
        const newLevel = volumeLevel(message.content);

        if (newLevel > 1) {
          message.reply(`${ newLevel } is far too loud. 0-1 is a good range.`);
          return;
        } else if (isNaN(newLevel)) {
          message.reply(`Your volume level wasn't a number. Try again!`);
          return;
        }

        if (dispatcher.stream) {
          // Sets the volume relative to the input stream
          // 1 is normal, 0.5 is half, 2 is double.
          dispatcher.stream.setVolume(newLevel);
        }
      },
      '$pause': function() {
        if (dispatcher.stream) {
          dispatcher.stream.pause();
          message.reply('Song paused. Use $resume to resume playback');
        }
      },
      '$resume': function() {
        if (dispatcher.stream) {
          dispatcher.stream.resume();
          message.reply('Resuming playback!');
        }
      },
      '$help': function() {
        const commands = [
          '$play [songname] | play a song or video (audio only)',
          '$stop | stops playback of the current song',
          '$pause | pauses playback of the current song',
          '$resume | resumes playback of the current song',
          '$join [channelname] | join the specified channel (be sure to check your spelling - damn lazy programmer...)',
          '$volume [volumelevel - ex. 1 (full volume), ex. .5 (half volume)] | sets the volume of the current song'
        ]
        message.reply(formatHelpMessage(commands));
      }
    };
  };
};

const botGenerator = BotGenerator({
  client,
  ytdl,
  streamOptions,
  dispatcher
});

client.on('message', message => {
  const theMatrix  = client.guilds.get(process.env.MATRIX_GUILD_ID);
  const conductors = theMatrix.roles.get(process.env.CONDUCTOR_ID).members;
  const command    = parseCommand(message.content);
  const channels   = client.channels;

  if (!conductors.find(conductor => conductor.user.username === message.author.username)) {
    message.reply('Ah ah ah... you didn\'t say the magic word!');
    return;
  }

  const bot = botGenerator(message);

  if (typeof bot[command] === 'function') {
    bot[command](channels);
  } else if (!bot[command] && command[0] === '$') {
    message.reply('Command not found. Use $help to list available commands.');
  }

});

client.login(token);
<|endoftext|>


<commit_before>import Board from '../../frontend/src/shogi/board';
import Piece from '../../frontend/src/shogi/piece';
import Turn from '../../frontend/src/shogi/turn';
import memo from 'memo-is';
import _ from 'lodash';

describe('isTakenKing', () => {
  context("if take the piece, king is taken", () => {
    var board = memo().is(() => {
      var _board = new Board;
      _board.setBoard(position());
      return(_board);
    });

    var position = memo().is(() => {
      return (
        [
          ['*', 'p+', '*'],
          ['*', 'g', '*'],
          ['*', 'K', '*'],
        ]
      );
    });

    it('returns true', () => {
      board.isTakenKing(new Turn).should.eql(true);
    });
  });

  context("if moves the piece, king is taken", () => {
  });
});
<commit_msg>Skip test. for priority is low<commit_after>import Board from '../../frontend/src/shogi/board';
import Piece from '../../frontend/src/shogi/piece';
import Turn from '../../frontend/src/shogi/turn';
import memo from 'memo-is';
import _ from 'lodash';

describe('isTakenKing', () => {
  context.skip("if take the piece, king is taken", () => {
    var board = memo().is(() => {
      var _board = new Board;
      _board.setBoard(position());
      return(_board);
    });

    var position = memo().is(() => {
      return (
        [
          ['*', 'p+', '*'],
          ['*', 'g', '*'],
          ['*', 'K', '*'],
        ]
      );
    });

    it('returns true', () => {
      board.isTakenKing(new Turn).should.eql(true);
    });
  });

  context.skip("if moves the piece, king is taken", () => {
  });
});
<|endoftext|>


<commit_before>// Import dependencies
var express = require('express');
var favicon = require('serve-favicon');
var path = require('path');

// Initialize Express App
var app = express();
var port = process.env.PORT || 8080;

// Local database
var database = [];

// Middleware
app.use(favicon(__dirname + '/favicon.ico'));

// Route handling
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/:shortCode', function(req, res) {
  res.end();
});

app.get('/new/:url*', function(req, res) {
  var object = {
    'original_url': req.params.url + req.params[0],
    'short_url': 'https://aqueous-sierra-2642.herokuapp.com/' + database.length()
  };
  database.push(object);
  res.json(object);
});

// Server initialization
app.listen(port);
console.log('Listening on port ' + port);
<commit_msg>Redirect on short link<commit_after>// Import dependencies
var express = require('express');
var favicon = require('serve-favicon');
var path = require('path');

// Initialize Express App
var app = express();
var port = process.env.PORT || 8080;

// Local database
var database = [];

// Middleware
app.use(favicon(__dirname + '/favicon.ico'));

// Route handling
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/:shortCode', function(req, res) {
  res.redirect(database[req.params.shortCode].original_url);
});

app.get('/new/:url*', function(req, res) {
  var object = {
    'original_url': req.params.url + req.params[0],
    'short_url': 'https://aqueous-sierra-2642.herokuapp.com/' + database.length()
  };
  database.push(object);
  res.json(object);
});

// Server initialization
app.listen(port);
console.log('Listening on port ' + port);
<|endoftext|>


<commit_before>'use strict';

var errorCodes = require('../app/postgresql/error_codes').codeToCondition;

function getNextQuery(job) {
    if (!Array.isArray(job.query)) {
        return {
            query: job.query
        };
    }

    for (var i = 0; i < job.query.length; i++) {
        if (job.query[i].status === 'pending') {
            return {
                index: i,
                query: job.query[i].query
            };
        }
    }
}

function isLastQuery(job, index) {
    if (!Array.isArray(job.query)) {
        return true;
    }

    if (index >= (job.query.length -1)) {
        return true;
    }

    return false;
}

function JobRunner(jobBackend, jobQueue, queryRunner,userDatabaseMetadataService) {
    this.jobBackend = jobBackend;
    this.jobQueue = jobQueue;
    this.queryRunner = queryRunner;
    this.userDatabaseMetadataService = userDatabaseMetadataService;
}

JobRunner.prototype.run = function (job_id, callback) {
    var self = this;

    self.jobBackend.get(job_id, function (err, job) {
        if (err) {
            return callback(err);
        }

        if (job.status !== 'pending') {
            var invalidJobStatusError = new Error([
                'Cannot run job',
                job.job_id,
                'due to its status is',
                job.status
            ].join(' '));
            invalidJobStatusError.name = 'InvalidJobStatus';
            return callback(invalidJobStatusError);
        }

        var query = getNextQuery(job);

        if (!query) {
            var queryNotFoundError = new Error([
                'Cannot run job',
                job.job_id,
                ', there is no query to run'
            ].join(' '));
            queryNotFoundError.name = 'QueryNotFound';
            return callback(queryNotFoundError);
        }

        self.jobBackend.setRunning(job, query.index, function (err, job) {
            if (err) {
                return callback(err);
            }

            self._run(job, query, callback);
        });
    });
};

JobRunner.prototype._run = function (job, query, callback) {
    var self = this;
    self.userDatabaseMetadataService.getUserMetadata(job.user, function (err, userDatabaseMetadata) {
        if (err) {
            return callback(err);
        }

        self.queryRunner.run(job.job_id, query.query, userDatabaseMetadata, function (err /*, result */) {
            if (err) {
                // if query has been cancelled then it's going to get the current
                // job status saved by query_canceller
                if (errorCodes[err.code.toString()] === 'query_canceled') {
                    return self.jobBackend.get(job.job_id, callback);
                }

                return self.jobBackend.setFailed(job, err, callback);
            }

            if (isLastQuery(job, query.index)) {
                console.log('set done', query.index);
                return self.jobBackend.setDone(job, query.index, callback);
            }

            self.jobBackend.setJobPendingAndQueryDone(job, query.index, function (err, job) {
                if (err) {
                    return callback(err);
                }

                self.jobQueue.enqueue(job.job_id, userDatabaseMetadata.host, function (err){
                    if (err) {
                        return callback(err);
                    }

                    callback(null, job);
                });
            });
        });
    });
};

module.exports = JobRunner;
<commit_msg>Fixed job status when failing<commit_after>'use strict';

var errorCodes = require('../app/postgresql/error_codes').codeToCondition;

function getNextQuery(job) {
    if (!Array.isArray(job.query)) {
        return {
            query: job.query
        };
    }

    for (var i = 0; i < job.query.length; i++) {
        if (job.query[i].status === 'pending') {
            return {
                index: i,
                query: job.query[i].query
            };
        }
    }
}

function isLastQuery(job, index) {
    if (!Array.isArray(job.query)) {
        return true;
    }

    if (index >= (job.query.length -1)) {
        return true;
    }

    return false;
}

function JobRunner(jobBackend, jobQueue, queryRunner,userDatabaseMetadataService) {
    this.jobBackend = jobBackend;
    this.jobQueue = jobQueue;
    this.queryRunner = queryRunner;
    this.userDatabaseMetadataService = userDatabaseMetadataService;
}

JobRunner.prototype.run = function (job_id, callback) {
    var self = this;

    self.jobBackend.get(job_id, function (err, job) {
        if (err) {
            return callback(err);
        }

        if (job.status !== 'pending') {
            var invalidJobStatusError = new Error([
                'Cannot run job',
                job.job_id,
                'due to its status is',
                job.status
            ].join(' '));
            invalidJobStatusError.name = 'InvalidJobStatus';
            return callback(invalidJobStatusError);
        }

        var query = getNextQuery(job);

        if (!query) {
            var queryNotFoundError = new Error([
                'Cannot run job',
                job.job_id,
                ', there is no query to run'
            ].join(' '));
            queryNotFoundError.name = 'QueryNotFound';
            return callback(queryNotFoundError);
        }

        self.jobBackend.setRunning(job, query.index, function (err, job) {
            if (err) {
                return callback(err);
            }

            self._run(job, query, callback);
        });
    });
};

JobRunner.prototype._run = function (job, query, callback) {
    var self = this;
    self.userDatabaseMetadataService.getUserMetadata(job.user, function (err, userDatabaseMetadata) {
        if (err) {
            return callback(err);
        }

        self.queryRunner.run(job.job_id, query.query, userDatabaseMetadata, function (err /*, result */) {
            if (err) {
                // if query has been cancelled then it's going to get the current
                // job status saved by query_canceller
                if (errorCodes[err.code.toString()] === 'query_canceled') {
                    return self.jobBackend.get(job.job_id, callback);
                }

                return self.jobBackend.setFailed(job, err, query.index, callback);
            }

            if (isLastQuery(job, query.index)) {
                console.log('set done', query.index);
                return self.jobBackend.setDone(job, query.index, callback);
            }

            self.jobBackend.setJobPendingAndQueryDone(job, query.index, function (err, job) {
                if (err) {
                    return callback(err);
                }

                self.jobQueue.enqueue(job.job_id, userDatabaseMetadata.host, function (err){
                    if (err) {
                        return callback(err);
                    }

                    callback(null, job);
                });
            });
        });
    });
};

module.exports = JobRunner;
<|endoftext|>


<commit_before>var assert = require('assert');
var numbers = require('../index.js');
var statistic = numbers.statistic;
var basic = numbers.basic;

suite('numbers', function () {

  console.log('\n\n\033[34mTesting Statistics Mathematics\033[0m');

  test('mean should return average value amongst integers in an array', function (done) {
    var res = statistic.mean([0, 1, 2]);
    assert.equal(res, 1);
    done();
  });

  test('median should return middle value in array for a sorted array with an odd number of values', function (done) {
    var res1 = statistic.median([0, 2, 15]);
    assert.equal(res1, 2);
    done();
  });

  test('median should return middle value in array for an unsorted array with an odd number of values', function (done) {
    var res1 = statistic.median([1, 0, 2]);
    assert.equal(res1, 1);
    done();
  });

  test('median should return average of two middle values in array for a sorted array with an even number of values', function (done) {
    var res2 = statistic.median([0, 1, 2, 3]);
    assert.equal(res2, 1.5);
    done();
  });

  test('median should return average of two middle values in array for an unsorted array with an even number of values', function (done) {
    var res2 = statistic.median([1, 3, 2, 0]);
    assert.equal(res2, 1.5);
    done();
  });

  test('mode should return most common value in array', function (done) {
    var res = statistic.mode([0, 1, 1, 1, 2, 4, 6]);
    assert.equal(res, 1);
    done();
  });

  test('quantile should return lowest value in array for 0th q-quantile of an unsorted array', function (done) {
    var arr = [5, 2, 4];
    var res = statistic.quantile(arr, 0, 1);
    assert.equal(res, 2);
    done();
  });

  test('quantile should return highest value in array for qth q-quantile of an unsorted array', function (done) {
    var arr = [5, 2, 4];
    var res = statistic.quantile(arr, 6, 6);
    assert.equal(res, 5);
    done();
  });

  test('quantile should return average of two values in array for an unsorted array\'s length is a multiple of (k / q)', function (done) {
    var res = statistic.quantile([9, 1, 1, 9], 2, 4);
    assert.equal(res, 5);
    done();
  });

  test('quantile should return value at 0-based index floor(k/q) in array for an unsorted array\'s length is not a multiple of (k/q)', function (done) {
    var res = statistic.quantile([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 1, 4);
    assert.equal(res, 7);
    done();
  });

  test('should return the standard deviation of an array of numbers', function (done) {
    var res = statistic.standardDev([-5, -4, -1, 0, 5, 100]);
    assert.equal(res - numbers.EPSILON < 37.777 < res + numbers.EPSILON, true);
    done();
  });

  test('should return correlation between two arrays', function (done) {
    var arr1 = [-5, -4, -1, 0, 5, 100];
    var arr2 = [-6, 5, 2, 5, 2, 6];

    var res = statistic.correlation(arr1, arr2);

    assert.equal(res, 0.43413125731182334);
    done();
  });

  test('should return a function to calculate the linear regression of a set of points', function (done) {
    var arrX = [1, 2, 3, 4, 5, 7, 8, 9];
    var arrY = [1, 2, 3, 4, 5, 7, 7, 9];

    var regression_function = statistic.linearRegression(arrX, arrY);

    assert.equal(regression_function(20), 19.07218683651805);
    done();
  });

  test('should return a function to calculate the exponential regression of an array of numbers', function (done) {
    var input = [10, 9, 8, 8, 7, 7, 6, 6.5, 6.4, 6.3, 6.2];
    var output = [
      9.077131929916444, 8.66937771538526, 8.279940244595563, 7.907996710352883,
      7.552761266818376, 7.213483369166244, 6.8894461878255076, 6.579965093955639,
      6.284386212956255, 6.002085042954625, 5.732465135352174
    ];

    var regression_function = statistic.exponentialRegression(input);

    assert.equal(regression_function.rSquared, 0.8491729985314136);

    assert.deepEqual(regression_function(basic.range(1, input.length)), output);
    assert.equal(regression_function(1), 9.077131929916444);
    assert.equal(regression_function(15), 4.769782016165231);
    done();
  });

  test('should return an appropriate Coefficient of Determination for a given dataset and regression', function (done) {
    var input = [10, 9, 8, 8, 7, 7, 6, 6.5, 6.4, 6.3, 6.2];
    var output = [
      9.077131929916444, 8.66937771538526, 8.279940244595563, 7.907996710352883,
      7.552761266818376, 7.213483369166244, 6.8894461878255076, 6.579965093955639,
      6.284386212956255, 6.002085042954625, 5.732465135352174
    ];

    assert.equal(statistic.rSquared(input, output), 0.8491729985314136);
    done();
  });

  test('should return covariance between two arrays', function (done) {
    var arr1 = [-5, -4, -1, 0, 5, 100];
    var arr2 = [-6, 5, 2, 5, 2, 6];

    var res = statistic.covariance(arr1, arr2);

    assert.equal(res, 66.05555555555556);
    done();
  });

});
<commit_msg>fix broken tests<commit_after>var assert = require('assert');
var numbers = require('../index.js');
var statistic = numbers.statistic;
var basic = numbers.basic;

suite('numbers', function () {

  console.log('\n\n\033[34mTesting Statistics Mathematics\033[0m');

  test('mean should return average value amongst integers in an array', function (done) {
    var res = statistic.mean([0, 1, 2]);
    assert.equal(res, 1);
    done();
  });

  test('median should return middle value in array for a sorted array with an odd number of values', function (done) {
    var res1 = statistic.median([0, 2, 15]);
    assert.equal(res1, 2);
    done();
  });

  test('median should return middle value in array for an unsorted array with an odd number of values', function (done) {
    var res1 = statistic.median([1, 0, 2]);
    assert.equal(res1, 1);
    done();
  });

  test('median should return average of two middle values in array for a sorted array with an even number of values', function (done) {
    var res2 = statistic.median([0, 1, 2, 3]);
    assert.equal(res2, 1.5);
    done();
  });

  test('median should return average of two middle values in array for an unsorted array with an even number of values', function (done) {
    var res2 = statistic.median([1, 3, 2, 0]);
    assert.equal(res2, 1.5);
    done();
  });

  test('mode should return most common value in array', function (done) {
    var res = statistic.mode([0, 1, 1, 1, 2, 4, 6]);
    assert.equal(res, 1);
    done();
  });

  test('quantile should return lowest value in array for 0th q-quantile of an unsorted array', function (done) {
    var arr = [5, 2, 4];
    var res = statistic.quantile(arr, 0, 1);
    assert.equal(res, 2);
    done();
  });

  test('quantile should return highest value in array for qth q-quantile of an unsorted array', function (done) {
    var arr = [5, 2, 4];
    var res = statistic.quantile(arr, 6, 6);
    assert.equal(res, 5);
    done();
  });

  test('quantile should return average of two values in array for an unsorted array\'s length is a multiple of (k / q)', function (done) {
    var res = statistic.quantile([9, 1, 1, 9], 2, 4);
    assert.equal(res, 5);
    done();
  });

  test('quantile should return value at 0-based index floor(k/q) in array for an unsorted array\'s length is not a multiple of (k/q)', function (done) {
    var res = statistic.quantile([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 1, 4);
    assert.equal(res, 7);
    done();
  });

  test('should return the standard deviation of an array of numbers', function (done) {
    var res = statistic.standardDev([-5, -4, -1, 0, 5, 100]);
    assert.equal(res - numbers.EPSILON < 37.777 < res + numbers.EPSILON, true);
    done();
  });

  test('should return correlation between two arrays', function (done) {
    var arr1 = [-5, -4, -1, 0, 5, 100];
    var arr2 = [-6, 5, 2, 5, 2, 6];

    var res = statistic.correlation(arr1, arr2);

    assert.equal(res, 0.43413125731182334);
    done();
  });

  test('should return a function to calculate the linear regression of a set of points', function (done) {
    var arrX = [1, 2, 3, 4, 5, 7, 8, 9];
    var arrY = [1, 2, 3, 4, 5, 7, 7, 9];

    var regression_function = statistic.linearRegression(arrX, arrY);

    assert.equal(regression_function(20), 19.07218683651805);
    done();
  });

  test('should return a function to calculate the exponential regression of an array of numbers', function (done) {
    var input = [10, 9, 8, 8, 7, 7, 6, 6.5, 6.4, 6.3, 6.2];
    var output = [
      9.077131929916444, 8.66937771538526, 8.279940244595563, 7.907996710352884,
      7.552761266818374, 7.213483369166245, 6.8894461878255076, 6.579965093955639,
      6.284386212956255, 6.002085042954625, 5.732465135352174
    ];

    var regression_function = statistic.exponentialRegression(input);
    assert.equal(regression_function.rSquared, 0.8491729985314137);

    assert.deepEqual(regression_function(basic.range(1, input.length)), output);
    assert.equal(regression_function(1), 9.077131929916444);
    assert.equal(regression_function(15), 4.769782016165231);
    done();
  });

  test('should return an appropriate Coefficient of Determination for a given dataset and regression', function (done) {
    var input = [10, 9, 8, 8, 7, 7, 6, 6.5, 6.4, 6.3, 6.2];
    var output = [
      9.077131929916444, 8.66937771538526, 8.279940244595563, 7.907996710352883,
      7.552761266818376, 7.213483369166244, 6.8894461878255076, 6.579965093955639,
      6.284386212956255, 6.002085042954625, 5.732465135352174
    ];

    assert.equal(statistic.rSquared(input, output), 0.8491729985314136);
    done();
  });

  test('should return covariance between two arrays', function (done) {
    var arr1 = [-5, -4, -1, 0, 5, 100];
    var arr2 = [-6, 5, 2, 5, 2, 6];

    var res = statistic.covariance(arr1, arr2);

    assert.equal(res, 66.05555555555556);
    done();
  });

});
<|endoftext|>


<commit_before>var express = require( 'express' );
var path = require( 'path' );
var logger = require( 'morgan' );
var bodyParser = require( 'body-parser' );
var mongoose = require( 'mongoose' );
var expressJwt = require( 'express-jwt' );

var routes = require( './routes/index' );

var app = express();

app.use( logger( 'dev' ) );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() );
app.use( express.static( path.join( __dirname, 'public' ) ) );
app.use( expressJwt( {
    secret: process.env.JWT_SECRET,
    skip: [
        '/api/authenticate',
        '/api/admin/authenticate'
    ]
} ) );

// Use routes.index to map URLs to handlers in ./api
app.use( '/', routes );

/// catch 404 and forwarding to error handler
app.use( function ( req, res, next ) {
    var err = new Error( 'Not Found' );
    err.status = 404;
    next( err );
} );

/// error handlers

// development error handler
// will print stacktrace
if ( app.get( 'env' ) === 'development' ) {
    app.use( function ( err, req, res, next ) {
        res.status( err.status || 500 );
        res.render( 'error', {
            message: err.message,
            error: err
        } );
    } );
}

// production error handler
// no stacktraces leaked to user
app.use( function ( err, req, res, next ) {
    res.status( err.status || 500 );
    res.render( 'error', {
        message: err.message,
        error: {}
    } );
} );

// connect to the db
var MONGO_DB;
var FIG_DB = process.env.DB_1_PORT;
if ( FIG_DB ) {
  MONGO_DB = FIG_DB.replace( "tcp", "mongodb" ) + "/dev_db";
} else {
  MONGO_DB = process.env.MONGO_URL;
}
mongoose.connect(MONGO_DB);
var db = mongoose.connection;

module.exports = app;
<commit_msg>Add signup route to skip for JWT middleware<commit_after>var express = require( 'express' );
var path = require( 'path' );
var logger = require( 'morgan' );
var bodyParser = require( 'body-parser' );
var mongoose = require( 'mongoose' );
var expressJwt = require( 'express-jwt' );

var routes = require( './routes/index' );

var app = express();

app.use( logger( 'dev' ) );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() );
app.use( express.static( path.join( __dirname, 'public' ) ) );
app.use( expressJwt( {
    secret: process.env.JWT_SECRET,
    skip: [
        '/api/signup',
        '/api/authenticate',
        '/api/admin/authenticate'
    ]
} ) );

// Use routes.index to map URLs to handlers in ./api
app.use( '/', routes );

/// catch 404 and forwarding to error handler
app.use( function ( req, res, next ) {
    var err = new Error( 'Not Found' );
    err.status = 404;
    next( err );
} );

/// error handlers

// development error handler
// will print stacktrace
if ( app.get( 'env' ) === 'development' ) {
    app.use( function ( err, req, res, next ) {
        res.status( err.status || 500 );
        res.render( 'error', {
            message: err.message,
            error: err
        } );
    } );
}

// production error handler
// no stacktraces leaked to user
app.use( function ( err, req, res, next ) {
    res.status( err.status || 500 );
    res.render( 'error', {
        message: err.message,
        error: {}
    } );
} );

// connect to the db
var MONGO_DB;
var FIG_DB = process.env.DB_1_PORT;
if ( FIG_DB ) {
  MONGO_DB = FIG_DB.replace( "tcp", "mongodb" ) + "/dev_db";
} else {
  MONGO_DB = process.env.MONGO_URL;
}
mongoose.connect(MONGO_DB);
var db = mongoose.connection;

module.exports = app;
<|endoftext|>


<commit_before>
var http = require('http');
var util = require('util');
var MrIssueDriver = require('./driver');
var MrIssueConfig = require('./config');

var config = new MrIssueConfig();
var driver = new MrIssueDriver(config, function(err) {
  if(err) {
    console.log("Could not initialize Mr. Issue driver: " + err);
    return;
  }

  http.createServer(function(req, res) {
      // req.url == "/endpoint"

      var data = "";
      req.on('data', function(chunk) {
          data += chunk;
      });

      req.on('end', function() {
          var body = null;
          try {
              body = JSON.parse(data);
          } catch(e) {
          }

          if(body) {

          }

          console.log(req.url);
          console.log(util.inspect(body, false, null, true));
          console.log("\n");

          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end('{"ok": true}');

          driver.handleWebHook(req.url, body);
      });
  }).listen(8080, "0.0.0.0");
});
<commit_msg>added error handling and logging<commit_after>///
/// @copyright 2015 Adam Meily <meily.adam@gmail.com>
///

var http = require('http');
var util = require('util');
var MrIssueDriver = require('./driver');
var config = require('./config');
var logger = require('./logger');

var driver = new MrIssueDriver(config, function(err) {
  if(err) {
    logger.error("failed to initialize mr-issue: %s", err.message);
    return;
  }

  http.createServer(function(req, res) {
    // req.url == "/endpoint"

    var data = "";
    req.on('data', function(chunk) {
      data += chunk;
    });

    req.on('end', function() {
      var body;

      try {
        body = JSON.parse(data);
      } catch(e) {
        body = null;
      }

      if(body) {
        logger.info(
          "received webhook request: %s [action: %s]", req.url,
          body.object_attributes.action
        );

        driver.handleWebHook(req.url, body);
      } else {
        logger.warn("received invalid JSON request: " + req.url);
      }

      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end('{"ok": true}');
    });
  }).listen(8080, "0.0.0.0");
});
<|endoftext|>


<commit_before>export default (entityData = []) => (_, entity) => {
    const newId =
        entityData.length > 0 ? entityData[entityData.length - 1].id + 1 : 1;
    const newEntity = Object.assign(entity, { id: newId });
    entityData.push(newEntity);
    return newEntity;
};
<commit_msg>Create create.js<commit_after>export default (entityData = []) => (_, entity) => {
    const newId =
        entityData.length > 0 ? entityData[entityData.length - 1].id + 1 : 0;
    const newEntity = Object.assign(entity, { id: newId });
    entityData.push(newEntity);
    return newEntity;
};
<|endoftext|>


<commit_before>const col = {
  name: 'Denumirea instantei in clar (cu diactritice)',
  code: 'Codul informatic al instantei (din portal)',
  population: 'Populația',
  judges: 'Numar de judecatori',
  //x: 'Stoc (total volum de activitate al instantei)',
  //x: 'Dosare solutionate',
  //x: 'Operativitate (procent solutionate din stoc)',
  //x: 'Incarcatura pe schema',
  //x: 'Incarcatura pe judecator',
  //x: 'Indice de atacabilitate (procent atacate din solutionate)',
  //x: 'Indice de casare/desfiintare',
  //x: 'Indicator de "siguranta" (100%-Desfiintare*Atacare)',
  //x: 'Durata in zile',
  //x: 'Performanta pentru gogoasa',
  //x: 'Operativitatea relativa',
  //x: 'Incarcatura relativa',
  //x: 'Siguranta relativa',
}

const judeteUrl = 'https://dl.dropboxusercontent.com/u/103063/static/MapData/judete.topojson'

const width = 960
const height = 400
var projection = d3.geo.mercator()
var path = d3.geo.path()
    .projection(projection)

var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')

d3.csv('data/instante-2013.csv', (data) => {
  for(let row of data) {
    let name = row[col.name]
    let m = name.match(/^Tribunalul (.*)$/)
    if(m) {
      //console.log(m[1])
    }
  }

  d3.json('map/judete.topojson', (error, res) => {
    let layer = topojson.feature(res, res.objects.judete)
    let [[bx0, by0], [bx1, by1]] = d3.geo.bounds(layer)
    projection.center([(bx1+bx0)/2, (by1+by0)/2])

    let [px0, py0] = projection.invert([0, height])
    let [px1, py1] = projection.invert([width, 0])
    let s = d3.min([(px1-px0)/(bx1-bx0), (py1-py0)/(by1-by0)])
    projection.scale(s * projection.scale())

    svg.selectAll('.county')
        .data(layer.features)
      .enter().append('path')
        .attr('class', 'county')
        .attr('d', path)
  })
})
<commit_msg>bring the map a bit higher<commit_after>const col = {
  name: 'Denumirea instantei in clar (cu diactritice)',
  code: 'Codul informatic al instantei (din portal)',
  population: 'Populația',
  judges: 'Numar de judecatori',
  //x: 'Stoc (total volum de activitate al instantei)',
  //x: 'Dosare solutionate',
  //x: 'Operativitate (procent solutionate din stoc)',
  //x: 'Incarcatura pe schema',
  //x: 'Incarcatura pe judecator',
  //x: 'Indice de atacabilitate (procent atacate din solutionate)',
  //x: 'Indice de casare/desfiintare',
  //x: 'Indicator de "siguranta" (100%-Desfiintare*Atacare)',
  //x: 'Durata in zile',
  //x: 'Performanta pentru gogoasa',
  //x: 'Operativitatea relativa',
  //x: 'Incarcatura relativa',
  //x: 'Siguranta relativa',
}

const judeteUrl = 'https://dl.dropboxusercontent.com/u/103063/static/MapData/judete.topojson'

const width = 960
const height = 400
var projection = d3.geo.mercator()
var path = d3.geo.path()
    .projection(projection)

var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')

d3.csv('data/instante-2013.csv', (data) => {
  for(let row of data) {
    let name = row[col.name]
    let m = name.match(/^Tribunalul (.*)$/)
    if(m) {
      //console.log(m[1])
    }
  }

  d3.json('map/judete.topojson', (error, res) => {
    let layer = topojson.feature(res, res.objects.judete)
    let [[bx0, by0], [bx1, by1]] = d3.geo.bounds(layer)
    projection.center([(bx1+bx0)/2, (by1+by0)/2 - .8])

    let [px0, py0] = projection.invert([0, height])
    let [px1, py1] = projection.invert([width, 0])
    let s = d3.min([(px1-px0)/(bx1-bx0), (py1-py0)/(by1-by0)])
    projection.scale(s * projection.scale())

    svg.selectAll('.county')
        .data(layer.features)
      .enter().append('path')
        .attr('class', 'county')
        .attr('d', path)
  })
})
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var config = require('./config');
var compression = require('compression');
var timeout = require('connect-timeout')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(timeout('5s'));
app.use(logger('dev'));
app.use(haltOnTimedout);
app.use(bodyParser.json());
app.use(haltOnTimedout);
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(haltOnTimedout);
app.use(compression());
app.use(haltOnTimedout);
app.use(express.static(path.join(__dirname, 'public'), {
  maxAge: config.oneYear
}));
app.use(haltOnTimedout);

/*app.use(session({
    secret: config.secret,
    resave: false,
    saveUninitialized: true,
    duration: config.oneYear,
    cookie: {
        maxAge: config.oneYear,
        secure: false
    }
}));*/

//redirects to https
app.use(function(req, res, next) {
    var newURL;

    // If not on HTTPS, or not on the main domain, redirect
    if (config.environment === 'production' &&
        (req.headers['x-forwarded-proto'] !== 'https' || req.headers.host !== config.apiHost)) {

        newURL = ['https://' + config.apiHost, req.url].join('');
        return res.redirect(newURL);
    }

    return next();
});
app.use(haltOnTimedout);

app.use('/', require('./routes/index'));
app.use('/api', require('./routes/api'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err,
      year: new Date().getFullYear() + ""
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {},
    year: new Date().getFullYear() + ""
  });
});

function haltOnTimedout(req, res, next) {
  if (!req.timedout) next()
}

module.exports = app;
<commit_msg>removed https enforcement<commit_after>var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var config = require('./config');
var compression = require('compression');
var timeout = require('connect-timeout')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(timeout('5s'));
app.use(logger('dev'));
app.use(haltOnTimedout);
app.use(bodyParser.json());
app.use(haltOnTimedout);
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(haltOnTimedout);
app.use(compression());
app.use(haltOnTimedout);
app.use(express.static(path.join(__dirname, 'public'), {
  maxAge: config.oneYear
}));
app.use(haltOnTimedout);

/*app.use(session({
    secret: config.secret,
    resave: false,
    saveUninitialized: true,
    duration: config.oneYear,
    cookie: {
        maxAge: config.oneYear,
        secure: false
    }
}));*/

//redirects to https
app.use(function(req, res, next) {
    var newURL;

    // If not on HTTPS, or not on the main domain, redirect
    if (config.environment === 'production' &&
        (req.headers['x-forwarded-proto'] !== 'https' || req.headers.host !== config.apiHost)) {

        /*
          will not force https as we are now on free heroku dyno
          newURL = ['https://' + config.apiHost, req.url].join('');

        */
        return res.redirect(newURL);
    }

    return next();
});
app.use(haltOnTimedout);

app.use('/', require('./routes/index'));
app.use('/api', require('./routes/api'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err,
      year: new Date().getFullYear() + ""
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {},
    year: new Date().getFullYear() + ""
  });
});

function haltOnTimedout(req, res, next) {
  if (!req.timedout) next()
}

module.exports = app;
<|endoftext|>


<commit_before>var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({
    port: 3000,
    routes: {
        cors: true
    }
});

server.app.base_url = process.env['VIRTUAL_HOST'] ? ('http://' + process.env['VIRTUAL_HOST']) : 'http://localhost:3000';
server.app.content_path = process.env['CONTENT_PATH'] || 'content';

server.app.ignoreFromList = ['contents', 'mode'];
server.app.content = {};

server.start(function () {
    console.log('Server running at:', server.info.uri);
});

var start = require('./start')(server);
var methods = require('./methods')(server);
var backend = require('./backend')(server);

module.exports = server;
<commit_msg>fixed:5<commit_after>var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({
    port: 3000,
    router: {
        stripTrailingSlash: true
    },
    routes: {
        cors: true
    }
});

server.app.base_url = process.env['VIRTUAL_HOST'] ? ('http://' + process.env['VIRTUAL_HOST']) : 'http://localhost:3000';
server.app.content_path = process.env['CONTENT_PATH'] || 'content';

server.app.ignoreFromList = ['contents', 'mode'];
server.app.content = {};

server.start(function () {
    console.log('Server running at:', server.info.uri);
});

var start = require('./start')(server);
var methods = require('./methods')(server);
var backend = require('./backend')(server);

module.exports = server;
<|endoftext|>