<commit_before>/**
*
*	STREAM: min
*
*
*
*	DESCRIPTION:
*		-
*
*
*	API:
*		-
*
*
*	NOTES:
*		[1]
*
*
*	TODO:
*		[1]
*
*
*	HISTORY:
*		- 2014/05/23: Created. [AReines].
*
*
*	DEPENDENCIES:
*		[1]
*
*
*	LICENSE:
*		MIT
*
*	Copyright (c) 2014. Athan Reines.
*
*
*	AUTHOR:
*		Athan Reines. athan@nodeprime.com. 2014.
*
*/

(function() {
	'use strict';

	// MODULES //

	var // Stream reduce:
		reducer = require( './../../reduce' );

	// STREAM //

	/**
	* FUNCTION: Stream()
	*	Stream constructor.
	*
	* @returns {object} Stream instance
	*/
	function Stream() {
		// Default accumulator value:
		this._value = Number.POSITIVE_INFINITY;

		return this;
	} // end FUNCTION stream()

	/**
	* METHOD: value( value )
	*	Setter and getter for initial value from which to begin reduction. If a value is provided, sets the initial min value. If no value is provided, returns the initial min value.
	*
	* @param {number} value - initial min value
	* @returns {object|number} instance object or initial value
	*/
	Stream.prototype.value = function( value ) {
		if ( !arguments.length ) {
			return this._value;
		}
		this._value = value;
		return this;
	}; // end METHOD value()

	/**
	* METHOD: _reduce()
	*	Returns a data reduction function.
	*
	* @returns {function} data reduction function
	*/
	Stream.prototype._reduce = function() {
		/**
		* FUNCTION: reduce( min, data )
		*	Defines the data reduction.
		*
		* @param {number} min - current min value
		* @param {number} data - numeric stream data
		* @returns {number} reduced data
		*/
		return function reduce( min, x ) {
			if ( x < min ) {
				min = x;
			}
			return min;
		};
	}; // end METHOD _reduce()

	/**
	* METHOD: stream()
	*	Returns a JSON data reduction stream for calculating the statistic.
	*/
	Stream.prototype.stream = function() {
		// Get the reduction stream:
		return reducer( this._reduce(), this._value );
	}; // end METHOD stream()

	// EXPORTS //

	module.exports = function createStream() {
		return new Stream();
	};

})();<commit_msg>[UPDATE] min stream prototype.<commit_after>/**
*
*	STREAM: min
*
*
*
*	DESCRIPTION:
*		-
*
*
*	API:
*		-
*
*
*	NOTES:
*		[1]
*
*
*	TODO:
*		[1]
*
*
*	HISTORY:
*		- 2014/05/23: Created. [AReines].
*
*
*	DEPENDENCIES:
*		[1]
*
*
*	LICENSE:
*		MIT
*
*	Copyright (c) 2014. Athan Reines.
*
*
*	AUTHOR:
*		Athan Reines. athan@nodeprime.com. 2014.
*
*/

(function() {
	'use strict';

	// MODULES //

	var // Stream reduce:
		reducer = require( './../../reduce' );

	// FUNCTIONS //

	/**
	* FUNCTION: reduce( min, data )
	*	Defines the data reduction.
	*
	* @param {number} min - current min value
	* @param {number} data - numeric stream data
	* @returns {number} reduced data
	*/
	function reduce( min, x ) {
		if ( x < min ) {
			min = x;
		}
		return min;
	} // end FUNCTIIN reduce()

	// STREAM //

	/**
	* FUNCTION: Stream()
	*	Stream constructor.
	*
	* @returns {object} Stream instance
	*/
	function Stream() {
		// Default accumulator value:
		this._value = Number.POSITIVE_INFINITY;

		return this;
	} // end FUNCTION stream()

	/**
	* METHOD: value( value )
	*	Setter and getter for initial value from which to begin reduction. If a value is provided, sets the initial min value. If no value is provided, returns the initial min value.
	*
	* @param {number} value - initial min value
	* @returns {object|number} instance object or initial value
	*/
	Stream.prototype.value = function( value ) {
		if ( !arguments.length ) {
			return this._value;
		}
		this._value = value;
		return this;
	}; // end METHOD value()

	/**
	* METHOD: stream()
	*	Returns a JSON data reduction stream for calculating the statistic.
	*/
	Stream.prototype.stream = function() {
		// Get the reduction stream:
		return reducer( reduce, this._value );
	}; // end METHOD stream()

	// EXPORTS //

	module.exports = function createStream() {
		return new Stream();
	};

})();<|endoftext|>


<commit_before>/**
 * Cache trees from pixels to transit stops, including an index for where a particular pixel is located.
 * @author mattwigway
 */

/**
 * Construct a stop tree cache from a typed array
 *
 * @param {ArrayBuffer} data
 * @param {Number} size
 */
export function create (data, size) {
  const stopTreeCache = {}

  stopTreeCache.data = data
  stopTreeCache.index = new Int32Array(size)

  // build the index and de-delta-code
  for (let i = 0, pixel = 0, stopId = 0, time = 0; i < data.length; pixel++) {
    stopTreeCache.index[pixel] = i
    const nStops = data[i++]
    for (let stopIdx = 0; stopIdx < nStops; stopIdx++) {
      stopId += data[i]
      data[i++] = stopId
      time += data[i]
      data[i++] = time
    }
  }

  return stopTreeCache
}
<commit_msg>feat(stop-tree-cache): Add bounds checks to stop tree cache :tree:<commit_after>/**
 * Cache trees from pixels to transit stops, including an index for where a particular pixel is located.
 * @author mattwigway
 */

/**
 * Construct a stop tree cache from a typed array
 *
 * @param {ArrayBuffer} data
 * @param {Number} size
 */
export function create (data, size) {
  const stopTreeCache = {}

  stopTreeCache.data = data
  stopTreeCache.index = new Int32Array(size)

  // function that reads from array performing bounds checks
  const read = (idx) => {
    if (idx >= data.length) {
      throw new Error('attempted to read past end of stop tree cache!')
    } else {
      return data[idx]
    }
  }

  // build the index and de-delta-code
  let pixelsRead = 0
  for (let i = 0, pixel = 0, stopId = 0, time = 0; i < data.length; pixel++) {
    stopTreeCache.index[pixel] = i
    const nStops = read(i++)

    for (let stopIdx = 0; stopIdx < nStops; stopIdx++) {
      stopId += read(i)
      data[i++] = stopId
      time += read(i)
      data[i++] = time
    }

    pixelsRead++
  }

  if (pixelsRead !== size) {
    throw new Error(`Expected to read ${size} pixels but read only ${pixelsRead}`)
  }

  return stopTreeCache
}
<|endoftext|>


<commit_before>ManageIQ.angular.app.controller('mwAddDataSourceController', MwAddDataSourceCtrl);

DATASOURCE_EVENT = 'mwAddDatasourceEvent';

MwAddDataSourceCtrl.$inject = ['$scope', '$rootScope', 'miqService', 'mwAddDataSourceService'];

function MwAddDataSourceCtrl($scope, $rootScope, miqService, mwAddDataSourceService) {

  $scope.dsModel = {};
  $scope.dsModel.step = 'CHOOSE_DS';

  $scope.chooseDsModel = {};
  $scope.chooseDsModel.selectedDatasource = undefined;
  $scope.chooseDsModel.datasources = undefined;

  $scope.step1DsModel = {};
  $scope.step1DsModel.datasourceName = '';
  $scope.step1DsModel.jndiName = '';

  $scope.step2DsModel = {};
  $scope.step2DsModel.jdbcDriverName = '';
  $scope.step2DsModel.jdbcModuleName = '';
  $scope.step2DsModel.driverClass = '';

  $scope.step3DsModel = {};
  $scope.step3DsModel.validationRegex = /^jdbc:\S+$/;
  $scope.step3DsModel.connectionUrl = '';
  $scope.step3DsModel.userName = '';
  $scope.step3DsModel.password = '';
  $scope.step3DsModel.securityDomain = '';

  this.$onInit = function () {
    $scope.chooseDsModel.datasources = mwAddDataSourceService.getDatasources();
  };

  $scope.$on(DATASOURCE_EVENT, function(event, payload) {
    mwAddDataSourceService.sendAddDatasource(payload);
    angular.element("#modal_ds_div").modal('hide');
    miqService.sparkleOff();
  });

  $scope.addDatasourceChooseNext = function() {
    var dsSelection = $scope.chooseDsModel.selectedDatasource;
    $scope.dsModel.step = 'STEP1';
    $scope.step1DsModel.datasourceName = dsSelection.name;
    $scope.step1DsModel.jndiName = dsSelection.jndiName;
  };

  $scope.addDatasourceStep1Next = function() {
    var dsSelection = $scope.chooseDsModel.selectedDatasource;
    $scope.dsModel.step = 'STEP2';

    $scope.step2DsModel.jdbcDriverName = dsSelection.driverName;
    $scope.step2DsModel.jdbcModuleName = dsSelection.driverModuleName;
    $scope.step2DsModel.driverClass = dsSelection.driverClass;
  };

  $scope.addDatasourceStep1Back = function() {
    $scope.dsModel.step = 'CHOOSE_DS';
  };

  $scope.addDatasourceStep2Next = function() {
    var dsSelection = $scope.chooseDsModel.selectedDatasource;
    $scope.dsModel.step = 'STEP3';
    $scope.step3DsModel.connectionUrl = mwAddDataSourceService.determineConnectionUrl(dsSelection);
  };

  $scope.addDatasourceStep2Back = function() {
    $scope.dsModel.step = 'STEP1';
  };

  $scope.finishAddDatasource = function () {
    var payload = Object.assign({},getPayload());
    $rootScope.$broadcast(DATASOURCE_EVENT, payload);
  };

  $scope.finishAddDatasourceBack = function () {
    $scope.dsModel.step = 'STEP2';
  };

  $scope.reset = function() {
    angular.element("#modal_ds_div").modal('hide');
    $scope.dsAddForm.$setPristine();

    $scope.dsModel.step = 'CHOOSE_DS';

    $scope.chooseDsModel.selectedDatasource = '';

    $scope.step1DsModel.datasourceName = '';
    $scope.step1DsModel.jndiName = '';

    $scope.step2DsModel.jdbcDriverName = '';
    $scope.step2DsModel.jdbcModuleName = '';
    $scope.step2DsModel.driverClass = '';
    $scope.step3DsModel.connectionUrl = '';
    $scope.step3DsModel.userName = '';
    $scope.step3DsModel.password = '';
    $scope.step3DsModel.securityDomain = '';
  };

  var getPayload = function () {
    return {
      'id': angular.element('#server_id').val(),
      'xaDatasource': false,
      'datasourceName': $scope.step1DsModel.datasourceName,
      'jndiName': $scope.step1DsModel.jndiName,
      'driverName': $scope.step2DsModel.jdbcDriverName,
      'driverClass': $scope.step2DsModel.driverClass,
      'connectionUrl': $scope.step3DsModel.connectionUrl,
      'userName': $scope.step3DsModel.userName,
      'password': $scope.step3DsModel.password,
      'securityDomain': $scope.step3DsModel.securityDomain
    };
  };
}
<commit_msg>Simplify js property  initalizations making it less verbose (and less repeating $scope). (transferred from ManageIQ/manageiq@f9e65f5d291506996455181c80343dc5b1ee59e6)<commit_after>ManageIQ.angular.app.controller('mwAddDataSourceController', MwAddDataSourceCtrl);

DATASOURCE_EVENT = 'mwAddDatasourceEvent';

MwAddDataSourceCtrl.$inject = ['$scope', '$rootScope', 'miqService', 'mwAddDataSourceService'];

function MwAddDataSourceCtrl($scope, $rootScope, miqService, mwAddDataSourceService) {

  $scope.dsModel = {};
  $scope.dsModel.step = 'CHOOSE_DS';

  $scope.chooseDsModel = {
    selectedDatasource : undefined,
    datasources : undefined
  };

  $scope.step1DsModel = {
    datasourceName : '',
    jndiName : ''
  };

  $scope.step2DsModel = {
    jdbcDriverName : '',
    jdbcModuleName : '',
    driverClass : ''
  };

  $scope.step3DsModel = {
    validationRegex : /^jdbc:\S+$/,
    connectionUrl : '',
    userName : '',
    password : '',
    securityDomain : ''
  };

  this.$onInit = function () {
    $scope.chooseDsModel.datasources = mwAddDataSourceService.getDatasources();
  };

  $scope.$on(DATASOURCE_EVENT, function(event, payload) {
    mwAddDataSourceService.sendAddDatasource(payload);
    angular.element("#modal_ds_div").modal('hide');
    miqService.sparkleOff();
  });

  $scope.addDatasourceChooseNext = function() {
    var dsSelection = $scope.chooseDsModel.selectedDatasource;
    $scope.dsModel.step = 'STEP1';
    $scope.step1DsModel.datasourceName = dsSelection.name;
    $scope.step1DsModel.jndiName = dsSelection.jndiName;
  };

  $scope.addDatasourceStep1Next = function() {
    var dsSelection = $scope.chooseDsModel.selectedDatasource;
    $scope.dsModel.step = 'STEP2';

    $scope.step2DsModel.jdbcDriverName = dsSelection.driverName;
    $scope.step2DsModel.jdbcModuleName = dsSelection.driverModuleName;
    $scope.step2DsModel.driverClass = dsSelection.driverClass;
  };

  $scope.addDatasourceStep1Back = function() {
    $scope.dsModel.step = 'CHOOSE_DS';
  };

  $scope.addDatasourceStep2Next = function() {
    var dsSelection = $scope.chooseDsModel.selectedDatasource;
    $scope.dsModel.step = 'STEP3';
    $scope.step3DsModel.connectionUrl = mwAddDataSourceService.determineConnectionUrl(dsSelection);
  };

  $scope.addDatasourceStep2Back = function() {
    $scope.dsModel.step = 'STEP1';
  };

  $scope.finishAddDatasource = function () {
    var payload = Object.assign({},getPayload());
    $rootScope.$broadcast(DATASOURCE_EVENT, payload);
  };

  $scope.finishAddDatasourceBack = function () {
    $scope.dsModel.step = 'STEP2';
  };

  $scope.reset = function() {
    angular.element("#modal_ds_div").modal('hide');
    $scope.dsAddForm.$setPristine();

    $scope.dsModel.step = 'CHOOSE_DS';

    $scope.chooseDsModel.selectedDatasource = '';

    $scope.step1DsModel.datasourceName = '';
    $scope.step1DsModel.jndiName = '';

    $scope.step2DsModel.jdbcDriverName = '';
    $scope.step2DsModel.jdbcModuleName = '';
    $scope.step2DsModel.driverClass = '';
    $scope.step3DsModel.connectionUrl = '';
    $scope.step3DsModel.userName = '';
    $scope.step3DsModel.password = '';
    $scope.step3DsModel.securityDomain = '';
  };

  var getPayload = function () {
    return {
      'id': angular.element('#server_id').val(),
      'xaDatasource': false,
      'datasourceName': $scope.step1DsModel.datasourceName,
      'jndiName': $scope.step1DsModel.jndiName,
      'driverName': $scope.step2DsModel.jdbcDriverName,
      'driverClass': $scope.step2DsModel.driverClass,
      'connectionUrl': $scope.step3DsModel.connectionUrl,
      'userName': $scope.step3DsModel.userName,
      'password': $scope.step3DsModel.password,
      'securityDomain': $scope.step3DsModel.securityDomain
    };
  };
}
<|endoftext|>


<commit_before>'use babel';

/* @flow */

import globToRegex from 'glob-to-regexp';
import { Emitter, CompositeDisposable } from 'atom';
import { convertWindowsPathToUnixPath } from './helpers';
/* flow-include
import type { TextEditor, Disposable } from 'atom'
import EditorTester from './editor-tester';
import type { Tester } from './types'
*/

export default class TesterRegistry {
    /* ::
    emitter: Emitter;
    testers: Set<Tester>;
    locks: Set<EditorTester>;
    testOnChange: boolean;
    subscriptions: CompositeDisposable;
    */

  constructor() {
    this.emitter = new Emitter();
    this.testers = new Set();
    this.locks = new Set();
    this.subscriptions = new CompositeDisposable();

    this.subscriptions.add(atom.config.observe('tester.testOnChange', (testOnChange) => {
      this.testOnChange = testOnChange;
    }));
  }

  hasTester(tester /* : Tester*/) /* : boolean*/ {
    return this.testers.has(tester);
  }

  addTester(tester /* : Tester*/) {
    this.testers.add(tester);
  }

  deleteTester(tester /* : Tester*/) {
    this.testers.delete(tester);
  }

  onShouldTriggerTester(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('should-trigger-tester', callback);
  }
  onDidUpdateMessages(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-update-messages', callback);
  }
  onDidBeginTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-begin-testing', callback);
  }
  onDidFinishTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-finish-testing', callback);
  }
  dispose() {
    this.testers.clear();
    this.subscriptions.dispose();
  }
  async test(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const editor = editorTester.editor;
    if (!editor.getPath() || this.locks.has(editorTester) ||
      (editor.isModified() && !this.testOnChange)) {
      return Promise.resolve(true);
    }

    this.emitter.emit('did-begin-testing', { editorTester });
    this.locks.add(editorTester);

    const promises = [];
    this.testers.forEach((tester) => {
      let shouldTriggerTester = false;
      try {
        shouldTriggerTester = tester.scopes.some(scope =>
          globToRegex(scope).test(convertWindowsPathToUnixPath(editor.getPath())));
      } catch (error) {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
      }
      if (!shouldTriggerTester) {
        return;
      }
      this.emitter.emit('should-trigger-tester', { shouldTriggerTester });
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.test(editor));
      })
      .then(({ messages, output }) => {
        if (messages) {
          this.emitter.emit('did-update-messages', { tester, editor, messages, output });
        }
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }

  async stop(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const promises = [];
    this.testers.forEach((tester) => {
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.stop(editorTester));
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }
}
<commit_msg>refactoring<commit_after>'use babel';

/* @flow */

import globToRegex from 'glob-to-regexp';
import { Emitter, CompositeDisposable } from 'atom';
import { convertWindowsPathToUnixPath } from './helpers';
/* flow-include
import type { TextEditor, Disposable } from 'atom'
import EditorTester from './editor-tester';
import type { Tester } from './types'
*/

export default class TesterRegistry {
    /* ::
    emitter: Emitter;
    testers: Set<Tester>;
    locks: Set<EditorTester>;
    testOnChange: boolean;
    subscriptions: CompositeDisposable;
    */

  constructor() {
    this.emitter = new Emitter();
    this.testers = new Set();
    this.locks = new Set();
    this.subscriptions = new CompositeDisposable();

    this.subscriptions.add(atom.config.observe('tester.testOnChange', (testOnChange) => {
      this.testOnChange = testOnChange;
    }));
  }

  hasTester(tester /* : Tester*/) /* : boolean*/ {
    return this.testers.has(tester);
  }

  addTester(tester /* : Tester*/) {
    this.testers.add(tester);
  }

  deleteTester(tester /* : Tester*/) {
    this.testers.delete(tester);
  }

  onShouldTriggerTester(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('should-trigger-tester', callback);
  }
  onDidUpdateMessages(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-update-messages', callback);
  }
  onDidBeginTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-begin-testing', callback);
  }
  onDidFinishTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-finish-testing', callback);
  }
  dispose() {
    this.testers.clear();
    this.subscriptions.dispose();
  }
  async test(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const editor = editorTester.editor;
    if (!editor.getPath() || this.locks.has(editorTester) ||
      (editor.isModified() && !this.testOnChange)) {
      return Promise.resolve(true);
    }

    this.emitter.emit('did-begin-testing', { editorTester });
    this.locks.add(editorTester);

    const promises = [];
    this.testers.forEach((tester) => {
      let shouldTriggerTester = false;
      try {
        shouldTriggerTester = tester.scopes.some(scope =>
          globToRegex(scope).test(convertWindowsPathToUnixPath(editor.getPath())));
      } catch (error) {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
      }
      if (!shouldTriggerTester) {
        return;
      }
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.test(editor));
      })
      .then(({ messages, output }) => {
        if (messages) {
          this.emitter.emit('did-update-messages', { tester, editor, messages, output });
        }
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }

  async stop(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const promises = [];
    this.testers.forEach((tester) => {
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.stop(editorTester));
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }
}
<|endoftext|>


<commit_before>module.exports = {
  "1":"Ɩ",
  "2":"ᄅ",
  "3":"Ɛ",
  "4":"ㄣ",
  "5":"ϛ",
  "6":"9",
  "7":"ㄥ",
  "8":"8",
  "9":"6",
  "0":"0",
  ".":"˙",
  ",":"'",
  "'":",",
  '"':",,",
  "`":",",
  "?":"¿",
  "!":"¡",
  "[":"]",
  "]":"[",
  "(":")",
  ")":"(",
  "{":"}",
  "}":"{",
  "<":">",
  ">":"<",
  "&":"⅋",
  "_":"‾",
  "a":"ɐ",
  "b":"q",
  "c":"ɔ",
  "d":"p",
  "e":"ǝ",
  "f":"ɟ",
  "g":"ƃ",
  "h":"ɥ",
  "i":"ᴉ",
  "j":"ɾ",
  "k":"ʞ",
  "m":"ɯ",
  "n":"u",
  "r":"ɹ",
  "t":"ʇ",
  "u":"n",
  "v":"ʌ",
  "w":"ʍ",
  "y":"ʎ",
  "A":"∀",
  "C":"Ɔ",
  "E":"Ǝ",
  "F":"Ⅎ",
  "G":"פ",
  "H":"H",
  "I":"I",
  "J":"ſ",
  "L":"˥",
  "M":"W",
  "N":"N",
  "P":"Ԁ",
  "T":"┴",
  "U":"∩",
  "V":"Λ",
  "Y":"⅄"
};
<commit_msg>Fixed p and q transforms<commit_after>module.exports = {
  "1":"Ɩ",
  "2":"ᄅ",
  "3":"Ɛ",
  "4":"ㄣ",
  "5":"ϛ",
  "6":"9",
  "7":"ㄥ",
  "8":"8",
  "9":"6",
  "0":"0",
  ".":"˙",
  ",":"'",
  "'":",",
  '"':",,",
  "`":",",
  "?":"¿",
  "!":"¡",
  "[":"]",
  "]":"[",
  "(":")",
  ")":"(",
  "{":"}",
  "}":"{",
  "<":">",
  ">":"<",
  "&":"⅋",
  "_":"‾",
  "a":"ɐ",
  "b":"q",
  "c":"ɔ",
  "d":"p",
  "e":"ǝ",
  "f":"ɟ",
  "g":"ƃ",
  "h":"ɥ",
  "i":"ᴉ",
  "j":"ɾ",
  "k":"ʞ",
  "m":"ɯ",
  "n":"u",
  "p":"d",
  "q":"b",
  "r":"ɹ",
  "t":"ʇ",
  "u":"n",
  "v":"ʌ",
  "w":"ʍ",
  "y":"ʎ",
  "A":"∀",
  "C":"Ɔ",
  "E":"Ǝ",
  "F":"Ⅎ",
  "G":"פ",
  "H":"H",
  "I":"I",
  "J":"ſ",
  "L":"˥",
  "M":"W",
  "N":"N",
  "P":"Ԁ",
  "T":"┴",
  "U":"∩",
  "V":"Λ",
  "Y":"⅄"
};
<|endoftext|>


<commit_before>/*
 * This file is part of the Sulu CMS.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

define(function() {

    'use strict';

    return {

        view: true,

        fullSize: {
            width: true
        },

        layout: {
            content: {
                width: 'max',
                leftSpace: false,
                rightSpace: false
            }
        },

        header: function() {
            return {
                title: 'pim.products.title',
                noBack: true,

                breadcrumb: [
                    {title: 'navigation.pim'},
                    {title: 'pim.products.title'}
                ]
            };
        },

        templates: ['/admin/product/template/product/list'],

        initialize: function() {
            this.render();
        },

        render: function() {
            this.sandbox.dom.html(this.$el, this.renderTemplate('/admin/product/template/product/list'));

            // init list-toolbar and datagrid
            this.sandbox.sulu.initListToolbarAndList.call(this, 'productsFields', '/admin/api/products/fields',
                {
                    el: this.$find('#list-toolbar-container'),
                    instanceName: 'productsToolbar',
                    inHeader: true
                },
                {
                    el: this.sandbox.dom.find('#products-list', this.$el),
                    url: '/admin/api/products?flat=true',
                    resultKey: 'products',
                    viewOptions: {
                        table: {
                            fullWidth: true
                        }
                    }
                }
            );
        }
    };
});
<commit_msg>added multiple add options to product list<commit_after>/*
 * This file is part of the Sulu CMS.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

define(function () {

    'use strict';
    var TYPE_PRODUCT = 'product',
        TYPE_PRODUCT_VARIANT = 'product-with-variant',
        TYPE_PRODUCT_ADDON = 'product-addon',
        TYPE_PRODUCT_SET = 'product-set',

        addProduct = function(type) {
            this.sandbox.emit('sulu.products.products.new', type);
        };

    return {

        view: true,

        fullSize: {
            width: true
        },

        layout: {
            content: {
                width: 'max',
                leftSpace: false,
                rightSpace: false
            }
        },

        header: function () {
            return {
                title: 'pim.products.title',
                noBack: true,

                breadcrumb: [
                    {title: 'navigation.pim'},
                    {title: 'pim.products.title'}
                ]
            };
        },

        templates: ['/admin/product/template/product/list'],

        initialize: function () {
            this.render();
        },

        render: function () {
            this.sandbox.dom.html(this.$el, this.renderTemplate('/admin/product/template/product/list'));

            // init list-toolbar and datagrid
            this.sandbox.sulu.initListToolbarAndList.call(this, 'productsFields', '/admin/api/products/fields',
                {
                    el: this.$find('#list-toolbar-container'),
                    instanceName: 'productsToolbar',
                    parentTemplate: 'default',
                    inHeader: true,
                    template: function () {
                        return [
                            {
                                id: 'add',
                                icon: 'plus-circle',
                                class: 'highlight-white',
                                position: 1,
                                title: this.sandbox.translate('sulu.list-toolbar.add'),
                                items: [
                                    {
                                        id: 'add-basic',
                                        title: this.sandbox.translate('products.add-product'),
                                        callback: addProduct.bind(this, TYPE_PRODUCT)
                                    },
                                    {
                                        id: 'add-lead',
                                        title: this.sandbox.translate('products.add-product-with-variant'),
                                        callback: addProduct.bind(this, TYPE_PRODUCT_VARIANT)
                                    },
                                    {
                                        id: 'add-customer',
                                        title: this.sandbox.translate('products.add-product-addon'),
                                        callback: addProduct.bind(this, TYPE_PRODUCT_ADDON)
                                    },
                                    {
                                        id: 'add-supplier',
                                        title: this.sandbox.translate('products.add-product-set'),
                                        callback: addProduct.bind(this, TYPE_PRODUCT_SET)
                                    }
                                ]
                            }
                        ];
                    }.bind(this)
                },
                {
                    el: this.sandbox.dom.find('#products-list', this.$el),
                    url: '/admin/api/products?flat=true',
                    resultKey: 'products',
                    viewOptions: {
                        table: {
                            fullWidth: true
                        }
                    }
                }
            );
        }
    };
});
<|endoftext|>


<commit_before>function isObject(o) {
    return (typeof o === 'object') && Object.prototype.toString.call(o) === '[object Object]';
}

exports.isObject = isObject;<commit_msg>add isArray; simpler isObject<commit_after>function smartType(o) {
    return Object.prototype.toString.call(o).replace(/\[object (\w+)\]/, '$1');
}
exports.smartType = smartType;

function isObject(o) {
    return !!o && smartType(o) === 'Object';
}
exports.isObject = isObject;

var nativeIsArray = Array.isArray;
function isArray(a) {
    return !!a && (nativeIsArray ? nativeIsArray(a) : smartType(a) === 'Array');
}
exports.isArray = isArray;<|endoftext|>


<commit_before>"use strict";

class PathRegexp {
    constructor(path, sensitive, strict) {
        if (path == "[object RegExp]") return path;
        if (Array.isArray(path)) path = "(" + path.join("|") + ")";
        let keys = [];

        path = path
            .concat(strict ? "" : "/?")
            .replace(/\/\(/g, "(?:/")
            .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, (_, slash, format, key, capture, optional, star) => {
                keys.push({ name: key, optional: !!optional });
                slash = slash || "";
                return ""
                + (optional ? "" : slash)
                + "(?:"
                + (optional ? slash : "")
                + (format || "") + (capture || (format && "([^/.]+?)" || "([^/]+?)")) + ")"
                + (optional || "")
                + (star ? "(/*)?" : "");
            })
            .replace(/([\/.])/g, "\\$1")
            .replace(/\*/g, "(.*)");

        this.keys = keys;
        this.regexp = new RegExp("^" + path + "$", sensitive ? "" : "i");
    };

    match(path) {
        let result = {
            match: false,
            params: {}
        };

        let m = this.regexp.exec(path);
        if (!m) return result;

        result.match = true;

        let count = m.length;
        for (let i = 1; i < count; i++) {
            let key = this.keys[i - 1];
            let val = m[i];

            if (key) result.params[key.name] = val;
            else {
                key = Object.keys(result.params).length;
                result.params[key] = val;
            }
        }
        return result;
    };
};

exports = module.exports = PathRegexp;<commit_msg>Fix bug in case of empty param in url ex: /api//test for /api/:name/test :name could be empty.<commit_after>"use strict";

class PathRegexp {
    constructor(path, sensitive, strict) {
        if (path == "[object RegExp]") return path;
        if (Array.isArray(path)) path = "(" + path.join("|") + ")";
        let keys = [];

        path = path
            .concat(strict ? "" : "/?")
            .replace(/\/\(/g, "(?:/")
            .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, (_, slash, format, key, capture, optional, star) => {
                keys.push({ name: key, optional: !!optional });
                slash = slash || "";
                return ""
                + (optional ? "" : slash)
                + "(?:"
                + (optional ? slash : "")
                + (format || "") + (capture || (format && "([^/.]+?)" || "([^/]+?)")) + ")"
                + (optional || "")
                + (star ? "(/*)?" : "");
            })
            .replace(/([\/.])/g, "\\$1")
            .replace(/\*/g, "(.*)");

        this.keys = keys;
        this.regexp = new RegExp("^" + path + "$", sensitive ? "" : "i");
    };

    match(path) {
        let result = {
            match: false,
            params: {}
        };

        let m = this.regexp.exec(path);
        if (!m) {
            if (path == "" && this.regexp.exec(" ")) /*if path == "" this.regexp.exec("") return false. We test it with this.regexp.exec(" ")*/
                m = ["dummy", ""];
            else
                return result;
        }

        result.match = true;

        let count = m.length;
        for (let i = 1; i < count; i++) {
            let key = this.keys[i - 1];
            let val = m[i];

            if (key) result.params[key.name] = val;
            else {
                key = Object.keys(result.params).length;
                result.params[key] = val;
            }
        }
        return result;
    };
};

exports = module.exports = PathRegexp;<|endoftext|>


<commit_before>
module.exports = readJson
readJson.processJson = processJson

var fs = require("./graceful-fs")
  , semver = require("./semver")
  , path = require("path")
  , log = require("./log")
  , cache = {}
  , timers = {}
function readJson (jsonFile, opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (cache.hasOwnProperty(jsonFile)) {
    log.verbose(jsonFile, "from cache")
    return cb(null, cache[jsonFile])
  }
  fs.readFile(path.join(path.dirname(jsonFile), "wscript"), function (er, data) {
    opts.file = jsonFile
    if (er) opts.wscript = false
    else opts.wscript = data.toString().match(/(^|\n)def build\b/)
                      && data.toString().match(/(^|\n)def configure\b/)
    fs.readFile(jsonFile, processJson(opts, cb))
  })
}
function processJson (opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (typeof cb !== "function") {
    var thing = cb, cb = null
    return P(null, thing)
  } else return P

  function P (er, thing) {
    if (er) {
      if (cb) return cb(er, thing)
      throw er
    }
    if (typeof thing === "object" && !Buffer.isBuffer(thing)) {
      return processObject(opts, cb)(er, thing)
    } else {
      return processJsonString(opts, cb)(er, thing)
    }
  }
}
function processJsonString (opts, cb) { return function (er, jsonString) {
  jsonString += ""
  if (er) return cb(er, jsonString)
  var json
  try {
    json = JSON.parse(jsonString)
  } catch (ex2) { try {
    json = process.binding("evals").Script.runInNewContext("(\n"+jsonString+"\n)")
  } catch (ex) {
    var e = new Error(
      "Failed to parse json\n"+ex.message+"\n"+ex2.message+"\n"+jsonString)
    if (cb) return cb(e)
    throw e
  }}
  return processObject(opts, cb)(er, json)
}}
function processObject (opts, cb) { return function (er, json) {
  if (json.overlay) {
    ;["node", "npm"].forEach(function (k) {
      if (!json.overlay[k]) return undefined
      for (var i in json.overlay[k]) json[i] = json.overlay[k][i]
    })
  }

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  if (json.name.charAt(0) === "." || json.name.match(/[\/@]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain '/' or '@'"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  var tag = opts.tag
  if (tag && tag.indexOf(json.version) === 0) {
    tag = tag.substr(json.version.length)
  }
  if (tag && tag.indexOf("-1-LINK") !== -1) {
    tag = tag.substr(tag.indexOf("-1-LINK"))
  }
  if (tag && semver.valid(json.version + tag)) {
    json.version += tag
  }

  // FIXME: uncomment in 0.3.0, once it's not likely that people will
  // have a bunch of main.js files kicking around any more, and remove
  // this functionality from lib/build.js
  //
  // if (json.main) {
  //   if (!json.modules) json.modules = {}
  //   json.modules.index = json.main
  //   delete json.main
  // }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version)
    if (cb) return cb(e)
    throw e
  }

  if (json.main) json.main = json.main.replace(/(\.js|\.node)$/, '')

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ path.basename( json.bin ) ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })

  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(json)
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // just in case this is a long-running process...
    clearTimeout(timers[opts.file])
    timers[opts.file] = setTimeout(function () {
      delete cache[opts.file]
      delete timers[opts.file]
    }, 1000 * 60 * 60 * 24)
  }
  if (cb) cb(null,json)
  return json
}}
function depObjectify (deps) {
  if (!Array.isArray(deps)) return deps
  var o = {}
  deps.forEach(function (d) { o[d] = "*" })
  return o
}
function testEngine (json) {
  if (!json.engines) json.engines = { "node" : "*" }

  var nodeVer = process.version.replace(/\+$/, '')
    , ok = false
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim()
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4)
        break
      }
    }
  }
  if (json.engines.node === "") json.engines.node = "*"
  json._nodeSupported = semver.satisfies(nodeVer, json.engines.node || "undefined")
  return json
}

function parsePeople (json) {
  if (json.author) json.author = parsePerson(json.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (Array.isArray(json[set])) json[set] = json[set].map(parsePerson)
  })
  return json
}
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
    , url = person.match(/\(([^\)]+)\)/)
    , email = person.match(/<([^>]+)>/)
    , obj = { "name" : (name && name[0] || person).trim() }
  if (email) obj.email = email[1]
  if (url) obj.url = url[1]
  return obj
}
<commit_msg>Don't allow spaces in names, and trim before checking<commit_after>
module.exports = readJson
readJson.processJson = processJson

var fs = require("./graceful-fs")
  , semver = require("./semver")
  , path = require("path")
  , log = require("./log")
  , cache = {}
  , timers = {}
function readJson (jsonFile, opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (cache.hasOwnProperty(jsonFile)) {
    log.verbose(jsonFile, "from cache")
    return cb(null, cache[jsonFile])
  }
  fs.readFile(path.join(path.dirname(jsonFile), "wscript"), function (er, data) {
    opts.file = jsonFile
    if (er) opts.wscript = false
    else opts.wscript = data.toString().match(/(^|\n)def build\b/)
                      && data.toString().match(/(^|\n)def configure\b/)
    fs.readFile(jsonFile, processJson(opts, cb))
  })
}
function processJson (opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (typeof cb !== "function") {
    var thing = cb, cb = null
    return P(null, thing)
  } else return P

  function P (er, thing) {
    if (er) {
      if (cb) return cb(er, thing)
      throw er
    }
    if (typeof thing === "object" && !Buffer.isBuffer(thing)) {
      return processObject(opts, cb)(er, thing)
    } else {
      return processJsonString(opts, cb)(er, thing)
    }
  }
}
function processJsonString (opts, cb) { return function (er, jsonString) {
  jsonString += ""
  if (er) return cb(er, jsonString)
  var json
  try {
    json = JSON.parse(jsonString)
  } catch (ex2) { try {
    json = process.binding("evals").Script.runInNewContext("(\n"+jsonString+"\n)")
  } catch (ex) {
    var e = new Error(
      "Failed to parse json\n"+ex.message+"\n"+ex2.message+"\n"+jsonString)
    if (cb) return cb(e)
    throw e
  }}
  return processObject(opts, cb)(er, json)
}}
function processObject (opts, cb) { return function (er, json) {
  if (json.overlay) {
    ;["node", "npm"].forEach(function (k) {
      if (!json.overlay[k]) return undefined
      for (var i in json.overlay[k]) json[i] = json.overlay[k][i]
    })
  }

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  json.name = json.name.trim()
  if (json.name.charAt(0) === "." || json.name.match(/[\/@\s]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain '/' or '@'"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  var tag = opts.tag
  if (tag && tag.indexOf(json.version) === 0) {
    tag = tag.substr(json.version.length)
  }
  if (tag && tag.indexOf("-1-LINK") !== -1) {
    tag = tag.substr(tag.indexOf("-1-LINK"))
  }
  if (tag && semver.valid(json.version + tag)) {
    json.version += tag
  }

  // FIXME: uncomment in 0.3.0, once it's not likely that people will
  // have a bunch of main.js files kicking around any more, and remove
  // this functionality from lib/build.js
  //
  // if (json.main) {
  //   if (!json.modules) json.modules = {}
  //   json.modules.index = json.main
  //   delete json.main
  // }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version)
    if (cb) return cb(e)
    throw e
  }

  if (json.main) json.main = json.main.replace(/(\.js|\.node)$/, '')

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ path.basename( json.bin ) ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })

  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(json)
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // just in case this is a long-running process...
    clearTimeout(timers[opts.file])
    timers[opts.file] = setTimeout(function () {
      delete cache[opts.file]
      delete timers[opts.file]
    }, 1000 * 60 * 60 * 24)
  }
  if (cb) cb(null,json)
  return json
}}
function depObjectify (deps) {
  if (!Array.isArray(deps)) return deps
  var o = {}
  deps.forEach(function (d) { o[d] = "*" })
  return o
}
function testEngine (json) {
  if (!json.engines) json.engines = { "node" : "*" }

  var nodeVer = process.version.replace(/\+$/, '')
    , ok = false
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim()
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4)
        break
      }
    }
  }
  if (json.engines.node === "") json.engines.node = "*"
  json._nodeSupported = semver.satisfies(nodeVer, json.engines.node || "undefined")
  return json
}

function parsePeople (json) {
  if (json.author) json.author = parsePerson(json.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (Array.isArray(json[set])) json[set] = json[set].map(parsePerson)
  })
  return json
}
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
    , url = person.match(/\(([^\)]+)\)/)
    , email = person.match(/<([^>]+)>/)
    , obj = { "name" : (name && name[0] || person).trim() }
  if (email) obj.email = email[1]
  if (url) obj.url = url[1]
  return obj
}
<|endoftext|>


<commit_before>
module.exports = readJson
readJson.processJson = processJson
readJson.unParsePeople = unParsePeople
readJson.parsePeople = parsePeople

var fs = require("./graceful-fs")
  , semver = require("./semver")
  , path = require("path")
  , log = require("./log")
  , npm = require("../../npm")
  , cache = {}
  , timers = {}
  , loadPackageDefaults = require("./load-package-defaults")

function readJson (jsonFile, opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (cache.hasOwnProperty(jsonFile)) {
    log.verbose(jsonFile, "from cache")
    return cb(null, cache[jsonFile])
  }
  opts.file = jsonFile
  if (!opts.tag) {
    var parsedPath = jsonFile.indexOf(npm.dir) === 0 && jsonFile.match(
      /\/([^\/]+)\/([^\/]+)\/package\/package\.json$/)
    if (parsedPath && semver.valid(parsedPath[2])) {
      // this is a package.json in some installed package.
      // infer the opts.tag so that linked packages behave right.
      opts.tag = parsedPath[2]
    }
  }

  fs.readFile( path.join(path.dirname(jsonFile), "wscript")
             , function (er, data) {
    if (er) opts.wscript = false
    else opts.wscript = data.toString().match(/(^|\n)def build\b/)
                      && data.toString().match(/(^|\n)def configure\b/)
    fs.readFile(jsonFile, processJson(opts, function (er, data) {
      if (er) return cb(er)
      var doLoad = !(jsonFile.indexOf(npm.cache) === 0 &&
                     path.basename(path.dirname(jsonFile)) !== "package")
      if (!doLoad) return cb(er, data)
      loadPackageDefaults(data, path.dirname(jsonFile), cb)
    }))
  })
}
function processJson (opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (typeof cb !== "function") {
    var thing = cb, cb = null
    return P(null, thing)
  } else return P

  function P (er, thing) {
    if (er) {
      if (cb) return cb(er, thing)
      throw er
    }
    if (typeof thing === "object" && !Buffer.isBuffer(thing)) {
      return processObject(opts, cb)(er, thing)
    } else {
      return processJsonString(opts, cb)(er, thing)
    }
  }
}
function processJsonString (opts, cb) { return function (er, jsonString) {
  jsonString += ""
  if (er) return cb(er, jsonString)
  var json
  try {
    json = JSON.parse(jsonString)
  } catch (ex2) { try {
    json = process.binding("evals").Script.runInNewContext(
      "(\n"+jsonString+"\n)")
  } catch (ex) {
    var e = new Error(
      "Failed to parse json\n"+ex.message+"\n"+ex2.message+"\n"+jsonString)
    if (cb) return cb(e)
    throw e
  }}
  return processObject(opts, cb)(er, json)
}}
function processObject (opts, cb) { return function (er, json) {
  if (json.overlay) {
    ;["node", "npm"].forEach(function (k) {
      if (!json.overlay[k]) return undefined
      for (var i in json.overlay[k]) json[i] = json.overlay[k][i]
    })
  }

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  json.name = json.name.trim()
  if (json.name.charAt(0) === "." || json.name.match(/[\/@\s\+%:]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain %/@+: or whitespace"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  if (json.name === "favicon.ico") {
    var msg = "Sorry, favicon.ico is a picture, not a package."
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  var tag = opts.tag
  if (tag) json.version = tag//+"-"+json.version

  // FIXME: uncomment in 0.3.0, once it's not likely that people will
  // have a bunch of main.js files kicking around any more, and remove
  // this functionality from lib/build.js
  //
  // if (json.main) {
  //   if (!json.modules) json.modules = {}
  //   json.modules.index = json.main
  //   delete json.main
  // }
  if (json.modules) {
    if (typeof json.modules !== "object") {
      var e = new Error("Invalid modules object")
      if (cb) return cb(e)
      throw e
    }
    Object.keys(json.modules).forEach(function (mod) {
      if (typeof json.modules[mod] !== "string") {
        var e = new Error("Invalid module "+mod+", not a string: "
                         +JSON.stringify(json.modules[mod]))
        if (cb) return cb(e)
        throw e
      }
    })
  }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf clean configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version+"\n"
                     +"Must be X.Y.Z, with an optional trailing tag.\n"
                     +"See the section on 'version' in `npm help json`"
                     )
    if (cb) return cb(e)
    throw e
  }
  json.version = semver.clean(json.version)

  if (json.main) json.main = json.main.replace(/(\.js|\.node)$/, '')

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ path.basename( json.bin ) ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })

  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(unParsePeople(json))
  if ( json.bugs ) json.bugs = parsePerson(unParsePerson(json.bugs))
  json._npmVersion = npm.version
  json._nodeVersion = process.version
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // arbitrary
    var keys = Object.keys(cache)
      , l = keys.length
    if (l > 10000) for (var i = 0; i < l - 5000; i ++) {
      delete cache[keys[i]]
    }
  }
  if (cb) cb(null,json)
  return json
}}
function depObjectify (deps) {
  if (!Array.isArray(deps)) return deps
  var o = {}
  deps.forEach(function (d) {
    d = d.trim().split(/(:?[@\s><=])/)
    o[d.shift()] = d.join("").trim().replace(/^@/, "")
  })
  return o
}
function testEngine (json) {
  // if engines is empty, then assume that node is allowed.
  log.silly(json, "testEngine")
  if ( !json.engines
      || Array.isArray(json.engines)
        && !json.engines.length
      || typeof json.engines === "object"
        && !Object.keys(json.engines).length
      ) {
    json.engines = { "node" : "*" }
  }
  if (typeof json.engines === "string") {
    if (semver.validRange(json.engines) !== null) {
      json.engines = { "node" : json.engines }
    } else json.engines = [ json.engines ]
  }

  var nodeVer = npm.config.get("node-version")
    , ok = false
  if (nodeVer) nodeVer = nodeVer.replace(/\+$/, '')
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim()
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4)
      } else if (e.substr(0, 3) === "npm") {
        json.engines.npm = e.substr(3)
      }
    }
  }
  if (json.engines.node === "") json.engines.node = "*"
  if (json.engines.node && null === semver.validRange(json.engines.node)) {
    log.warn( json.engines.node
            , "Invalid range in engines.node.  Please see `npm help json`" )
  }

  if (nodeVer) {
    json._engineSupported = semver.satisfies( nodeVer
                                            , json.engines.node || "null" )
  }
  if (json.engines.hasOwnProperty("npm") && json._engineSupported) {
    json._engineSupported = semver.satisfies(npm.version, json.engines.npm)
  }
  return json
}

function unParsePeople (json) { return parsePeople(json, true) }
function parsePeople (json, un) {
  var fn = un ? unParsePerson : parsePerson
  if (json.author) json.author = fn(json.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (Array.isArray(json[set])) json[set] = json[set].map(fn)
  })
  return json
}
function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name || ""
    , u = person.url || person.web
    , url = u ? (" ("+u+")") : ""
    , e = person.email || person.mail
    , email = e ? (" <"+e+">") : ""
  return name+email+url
}
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
    , url = person.match(/\(([^\)]+)\)/)
    , email = person.match(/<([^>]+)>/)
    , obj = {}
  if (name && name[0].trim()) obj.name = name[0].trim()
  if (email) obj.email = email[1]
  if (url) obj.url = url[1]
  return obj
}
<commit_msg>Don't allow a package to be named 'node_modules'<commit_after>
module.exports = readJson
readJson.processJson = processJson
readJson.unParsePeople = unParsePeople
readJson.parsePeople = parsePeople

var fs = require("./graceful-fs")
  , semver = require("./semver")
  , path = require("path")
  , log = require("./log")
  , npm = require("../../npm")
  , cache = {}
  , timers = {}
  , loadPackageDefaults = require("./load-package-defaults")

function readJson (jsonFile, opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (cache.hasOwnProperty(jsonFile)) {
    log.verbose(jsonFile, "from cache")
    return cb(null, cache[jsonFile])
  }
  opts.file = jsonFile
  if (!opts.tag) {
    var parsedPath = jsonFile.indexOf(npm.dir) === 0 && jsonFile.match(
      /\/([^\/]+)\/([^\/]+)\/package\/package\.json$/)
    if (parsedPath && semver.valid(parsedPath[2])) {
      // this is a package.json in some installed package.
      // infer the opts.tag so that linked packages behave right.
      opts.tag = parsedPath[2]
    }
  }

  fs.readFile( path.join(path.dirname(jsonFile), "wscript")
             , function (er, data) {
    if (er) opts.wscript = false
    else opts.wscript = data.toString().match(/(^|\n)def build\b/)
                      && data.toString().match(/(^|\n)def configure\b/)
    fs.readFile(jsonFile, processJson(opts, function (er, data) {
      if (er) return cb(er)
      var doLoad = !(jsonFile.indexOf(npm.cache) === 0 &&
                     path.basename(path.dirname(jsonFile)) !== "package")
      if (!doLoad) return cb(er, data)
      loadPackageDefaults(data, path.dirname(jsonFile), cb)
    }))
  })
}
function processJson (opts, cb) {
  if (typeof cb !== "function") cb = opts, opts = {}
  if (typeof cb !== "function") {
    var thing = cb, cb = null
    return P(null, thing)
  } else return P

  function P (er, thing) {
    if (er) {
      if (cb) return cb(er, thing)
      throw er
    }
    if (typeof thing === "object" && !Buffer.isBuffer(thing)) {
      return processObject(opts, cb)(er, thing)
    } else {
      return processJsonString(opts, cb)(er, thing)
    }
  }
}
function processJsonString (opts, cb) { return function (er, jsonString) {
  jsonString += ""
  if (er) return cb(er, jsonString)
  var json
  try {
    json = JSON.parse(jsonString)
  } catch (ex2) { try {
    json = process.binding("evals").Script.runInNewContext(
      "(\n"+jsonString+"\n)")
  } catch (ex) {
    var e = new Error(
      "Failed to parse json\n"+ex.message+"\n"+ex2.message+"\n"+jsonString)
    if (cb) return cb(e)
    throw e
  }}
  return processObject(opts, cb)(er, json)
}}
function processObject (opts, cb) { return function (er, json) {
  if (json.overlay) {
    ;["node", "npm"].forEach(function (k) {
      if (!json.overlay[k]) return undefined
      for (var i in json.overlay[k]) json[i] = json.overlay[k][i]
    })
  }

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  json.name = json.name.trim()
  if (json.name.charAt(0) === "." || json.name.match(/[\/@\s\+%:]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain %/@+: or whitespace"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  if (json.name.toLowerCase() === "node_modules") {
    var msg = "Invalid package name: node_modules"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  if (json.name.toLowerCase() === "favicon.ico") {
    var msg = "Sorry, favicon.ico is a picture, not a package."
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  var tag = opts.tag
  if (tag) json.version = tag//+"-"+json.version

  // FIXME: uncomment in 0.3.0, once it's not likely that people will
  // have a bunch of main.js files kicking around any more, and remove
  // this functionality from lib/build.js
  //
  // if (json.main) {
  //   if (!json.modules) json.modules = {}
  //   json.modules.index = json.main
  //   delete json.main
  // }
  if (json.modules) {
    if (typeof json.modules !== "object") {
      var e = new Error("Invalid modules object")
      if (cb) return cb(e)
      throw e
    }
    Object.keys(json.modules).forEach(function (mod) {
      if (typeof json.modules[mod] !== "string") {
        var e = new Error("Invalid module "+mod+", not a string: "
                         +JSON.stringify(json.modules[mod]))
        if (cb) return cb(e)
        throw e
      }
    })
  }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf clean configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version+"\n"
                     +"Must be X.Y.Z, with an optional trailing tag.\n"
                     +"See the section on 'version' in `npm help json`"
                     )
    if (cb) return cb(e)
    throw e
  }
  json.version = semver.clean(json.version)

  if (json.main) json.main = json.main.replace(/(\.js|\.node)$/, '')

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ path.basename( json.bin ) ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })

  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(unParsePeople(json))
  if ( json.bugs ) json.bugs = parsePerson(unParsePerson(json.bugs))
  json._npmVersion = npm.version
  json._nodeVersion = process.version
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // arbitrary
    var keys = Object.keys(cache)
      , l = keys.length
    if (l > 10000) for (var i = 0; i < l - 5000; i ++) {
      delete cache[keys[i]]
    }
  }
  if (cb) cb(null,json)
  return json
}}
function depObjectify (deps) {
  if (!Array.isArray(deps)) return deps
  var o = {}
  deps.forEach(function (d) {
    d = d.trim().split(/(:?[@\s><=])/)
    o[d.shift()] = d.join("").trim().replace(/^@/, "")
  })
  return o
}
function testEngine (json) {
  // if engines is empty, then assume that node is allowed.
  log.silly(json, "testEngine")
  if ( !json.engines
      || Array.isArray(json.engines)
        && !json.engines.length
      || typeof json.engines === "object"
        && !Object.keys(json.engines).length
      ) {
    json.engines = { "node" : "*" }
  }
  if (typeof json.engines === "string") {
    if (semver.validRange(json.engines) !== null) {
      json.engines = { "node" : json.engines }
    } else json.engines = [ json.engines ]
  }

  var nodeVer = npm.config.get("node-version")
    , ok = false
  if (nodeVer) nodeVer = nodeVer.replace(/\+$/, '')
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim()
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4)
      } else if (e.substr(0, 3) === "npm") {
        json.engines.npm = e.substr(3)
      }
    }
  }
  if (json.engines.node === "") json.engines.node = "*"
  if (json.engines.node && null === semver.validRange(json.engines.node)) {
    log.warn( json.engines.node
            , "Invalid range in engines.node.  Please see `npm help json`" )
  }

  if (nodeVer) {
    json._engineSupported = semver.satisfies( nodeVer
                                            , json.engines.node || "null" )
  }
  if (json.engines.hasOwnProperty("npm") && json._engineSupported) {
    json._engineSupported = semver.satisfies(npm.version, json.engines.npm)
  }
  return json
}

function unParsePeople (json) { return parsePeople(json, true) }
function parsePeople (json, un) {
  var fn = un ? unParsePerson : parsePerson
  if (json.author) json.author = fn(json.author)
  ;["maintainers", "contributors"].forEach(function (set) {
    if (Array.isArray(json[set])) json[set] = json[set].map(fn)
  })
  return json
}
function unParsePerson (person) {
  if (typeof person === "string") return person
  var name = person.name || ""
    , u = person.url || person.web
    , url = u ? (" ("+u+")") : ""
    , e = person.email || person.mail
    , email = e ? (" <"+e+">") : ""
  return name+email+url
}
function parsePerson (person) {
  if (typeof person !== "string") return person
  var name = person.match(/^([^\(<]+)/)
    , url = person.match(/\(([^\)]+)\)/)
    , email = person.match(/<([^>]+)>/)
    , obj = {}
  if (name && name[0].trim()) obj.name = name[0].trim()
  if (email) obj.email = email[1]
  if (url) obj.url = url[1]
  return obj
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {CompositeDisposable} from 'event-kit';

import Portal from './portal';

/**
 * `PaneItem` adds its child to the current Atom pane when rendered.
 * When the pane is closed, the component's `onDidCloseItem` is called.
 * You should use this callback to set state so that the `PaneItem` is no
 * longer rendered; you will get an error in your console if you forget.
 *
 * You may pass a `getItem` function that takes an object with `portal` and
 * `subtree` properties. `getItem` should return an item to be added to the
 * Panel. `portal` is an instance of th Portal component, and `subtree` is the
 * rendered subtree component built from the `children` prop. The default
 * implementation simply returns the Portal instance, which contains a
 * `getElement` method (to be compatible with Atom's view system).
 *
 * Unmounting the component when the item is open will close the item.
 */
export default class PaneItem extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    children: PropTypes.element.isRequired,
    getItem: PropTypes.func,
    onDidCloseItem: PropTypes.func,
    stubItem: PropTypes.object,
  }

  static defaultProps = {
    getItem: ({portal, subtree}) => portal.getView(),
    onDidCloseItem: paneItem => {},
  }

  componentDidMount() {
    this.setupPaneItem();
  }

  componentWillReceiveProps() {
    if (this.didCloseItem) {
      // eslint-disable-next-line no-console
      console.error('Unexpected update in `PaneItem`: the contained item has been closed');
    }
  }

  render() {
    let getDOMNode;
    if (this.props.stubItem) {
      getDOMNode = () => this.props.stubItem.getElement();
    }

    return <Portal ref={c => { this.portal = c; }} getDOMNode={getDOMNode}>{this.props.children}</Portal>;
  }

  setupPaneItem() {
    if (this.paneItem) { return; }

    const itemToAdd = this.props.getItem({portal: this.portal, subtree: this.portal.getRenderedSubtree()});
    this.subscriptions = new CompositeDisposable();
    if (itemToAdd.wasActivated) {
      this.subscriptions.add(
        this.props.workspace.onDidChangeActivePaneItem(activeItem => {
          if (activeItem === this.paneItem) {
            itemToAdd.wasActivated();
          }
        }),
      );
    }

    let stub;
    if (this.props.stubItem) {
      stub = this.props.stubItem;
    }

    if (stub) {
      stub.setRealItem(itemToAdd);
      this.paneItem = stub;
    } else {
      const paneContainer = this.props.workspace;
      this.paneItem = paneContainer.getActivePane().addItem(itemToAdd, {pending: true});
    }

    this.subscriptions = this.props.workspace.onDidDestroyPaneItem(({item}) => {
      if (item === this.paneItem) {
        this.didCloseItem = true;
        this.props.onDidCloseItem(this.paneItem);
      }
    });
  }

  getPaneItem() {
    return this.paneItem;
  }

  componentWillUnmount() {
    this.subscriptions && this.subscriptions.dispose();
    if (this.paneItem && !this.didCloseItem) {
      this.paneItem.destroy();
    }
  }
}
<commit_msg>Add back PaneItem#activate<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {CompositeDisposable} from 'event-kit';

import Portal from './portal';

/**
 * `PaneItem` adds its child to the current Atom pane when rendered.
 * When the pane is closed, the component's `onDidCloseItem` is called.
 * You should use this callback to set state so that the `PaneItem` is no
 * longer rendered; you will get an error in your console if you forget.
 *
 * You may pass a `getItem` function that takes an object with `portal` and
 * `subtree` properties. `getItem` should return an item to be added to the
 * Panel. `portal` is an instance of th Portal component, and `subtree` is the
 * rendered subtree component built from the `children` prop. The default
 * implementation simply returns the Portal instance, which contains a
 * `getElement` method (to be compatible with Atom's view system).
 *
 * Unmounting the component when the item is open will close the item.
 */
export default class PaneItem extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    children: PropTypes.element.isRequired,
    getItem: PropTypes.func,
    onDidCloseItem: PropTypes.func,
    stubItem: PropTypes.object,
  }

  static defaultProps = {
    getItem: ({portal, subtree}) => portal.getView(),
    onDidCloseItem: paneItem => {},
  }

  componentDidMount() {
    this.setupPaneItem();
  }

  componentWillReceiveProps() {
    if (this.didCloseItem) {
      // eslint-disable-next-line no-console
      console.error('Unexpected update in `PaneItem`: the contained item has been closed');
    }
  }

  render() {
    let getDOMNode;
    if (this.props.stubItem) {
      getDOMNode = () => this.props.stubItem.getElement();
    }

    return <Portal ref={c => { this.portal = c; }} getDOMNode={getDOMNode}>{this.props.children}</Portal>;
  }

  setupPaneItem() {
    if (this.paneItem) { return; }

    const itemToAdd = this.props.getItem({portal: this.portal, subtree: this.portal.getRenderedSubtree()});
    this.subscriptions = new CompositeDisposable();
    if (itemToAdd.wasActivated) {
      this.subscriptions.add(
        this.props.workspace.onDidChangeActivePaneItem(activeItem => {
          if (activeItem === this.paneItem) {
            itemToAdd.wasActivated();
          }
        }),
      );
    }

    let stub;
    if (this.props.stubItem) {
      stub = this.props.stubItem;
    }

    if (stub) {
      stub.setRealItem(itemToAdd);
      this.paneItem = stub;
    } else {
      const paneContainer = this.props.workspace;
      this.paneItem = paneContainer.getActivePane().addItem(itemToAdd, {pending: true});
    }

    this.subscriptions = this.props.workspace.onDidDestroyPaneItem(({item}) => {
      if (item === this.paneItem) {
        this.didCloseItem = true;
        this.props.onDidCloseItem(this.paneItem);
      }
    });
  }

  getPaneItem() {
    return this.paneItem;
  }

  componentWillUnmount() {
    this.subscriptions && this.subscriptions.dispose();
    if (this.paneItem && !this.didCloseItem) {
      this.paneItem.destroy();
    }
  }

  activate() {
    setTimeout(() => {
      if (!this.paneItem) { return; }

      const pane = this.props.workspace.paneForItem(this.paneItem);
      if (pane) {
        pane.activateItem(this.paneItem);
      } else {
        throw new Error('Cannot find pane for item in `PaneItem#activate`');
      }
    });
  }
}
<|endoftext|>


<commit_before>'use strict'
var fs = require('fs')
var url = require('url')
var path = require('path')

const Router = require('express').Router
const formidable = require('formidable')
var imgur = require('imgur')

const config = require('../config')
const logger = require('../logger')
const response = require('../response')

const imageRouter = module.exports = Router()

// upload image
imageRouter.post('/uploadimage', function (req, res) {
  var form = new formidable.IncomingForm()

  form.keepExtensions = true

  if (config.imageUploadType === 'filesystem') {
    form.uploadDir = 'public/uploads'
  }

  form.parse(req, function (err, fields, files) {
    if (err || !files.image || !files.image.path) {
      response.errorForbidden(res)
    } else {
      if (config.debug) { logger.info('SERVER received uploadimage: ' + JSON.stringify(files.image)) }

      try {
        switch (config.imageUploadType) {
          case 'filesystem':
            res.send({
              link: url.resolve(config.serverurl + '/', files.image.path.match(/^public\/(.+$)/)[1])
            })

            break

          case 's3':
            var AWS = require('aws-sdk')
            var awsConfig = new AWS.Config(config.s3)
            var s3 = new AWS.S3(awsConfig)
            const {getImageMimeType} = require('../utils')
            fs.readFile(files.image.path, function (err, buffer) {
              if (err) {
                logger.error(err)
                res.status(500).end('upload image error')
                return
              }
              var params = {
                Bucket: config.s3bucket,
                Key: path.join('uploads', path.basename(files.image.path)),
                Body: buffer
              }

              var mimeType = getImageMimeType(files.image.path)
              if (mimeType) { params.ContentType = mimeType }

              s3.putObject(params, function (err, data) {
                if (err) {
                  logger.error(err)
                  res.status(500).end('upload image error')
                  return
                }
                res.send({
                  link: `https://s3-${config.s3.region}.amazonaws.com/${config.s3bucket}/${params.Key}`
                })
              })
            })
            break
          case 'imgur':
          default:
            imgur.setClientId(config.imgur.clientID)
            imgur.uploadFile(files.image.path)
              .then(function (json) {
                if (config.debug) { logger.info('SERVER uploadimage success: ' + JSON.stringify(json)) }
                res.send({
                  link: json.data.link.replace(/^http:\/\//i, 'https://')
                })
              })
              .catch(function (err) {
                logger.error(err)
                return res.status(500).end('upload image error')
              })
            break
        }
      } catch (err) {
        logger.error(err)
        return res.status(500).end('upload image error')
      }
    }
  })
})
<commit_msg>fix s3 us-east-1 region endpoint<commit_after>'use strict'
var fs = require('fs')
var url = require('url')
var path = require('path')

const Router = require('express').Router
const formidable = require('formidable')
var imgur = require('imgur')

const config = require('../config')
const logger = require('../logger')
const response = require('../response')

const imageRouter = module.exports = Router()

// upload image
imageRouter.post('/uploadimage', function (req, res) {
  var form = new formidable.IncomingForm()

  form.keepExtensions = true

  if (config.imageUploadType === 'filesystem') {
    form.uploadDir = 'public/uploads'
  }

  form.parse(req, function (err, fields, files) {
    if (err || !files.image || !files.image.path) {
      response.errorForbidden(res)
    } else {
      if (config.debug) { logger.info('SERVER received uploadimage: ' + JSON.stringify(files.image)) }

      try {
        switch (config.imageUploadType) {
          case 'filesystem':
            res.send({
              link: url.resolve(config.serverurl + '/', files.image.path.match(/^public\/(.+$)/)[1])
            })

            break

          case 's3':
            var AWS = require('aws-sdk')
            var awsConfig = new AWS.Config(config.s3)
            var s3 = new AWS.S3(awsConfig)
            const {getImageMimeType} = require('../utils')
            fs.readFile(files.image.path, function (err, buffer) {
              if (err) {
                logger.error(err)
                res.status(500).end('upload image error')
                return
              }
              var params = {
                Bucket: config.s3bucket,
                Key: path.join('uploads', path.basename(files.image.path)),
                Body: buffer
              }

              var mimeType = getImageMimeType(files.image.path)
              if (mimeType) { params.ContentType = mimeType }

              s3.putObject(params, function (err, data) {
                if (err) {
                  logger.error(err)
                  res.status(500).end('upload image error')
                  return
                }

                var s3Endpoint = 's3.amazonaws.com'
                if (config.s3.region && config.s3.region !== 'us-east-1') { s3Endpoint = `s3-${config.s3.region}.amazonaws.com` }
                res.send({
                  link: `https://${s3Endpoint}/${config.s3bucket}/${params.Key}`
                })
              })
            })
            break
          case 'imgur':
          default:
            imgur.setClientId(config.imgur.clientID)
            imgur.uploadFile(files.image.path)
              .then(function (json) {
                if (config.debug) { logger.info('SERVER uploadimage success: ' + JSON.stringify(json)) }
                res.send({
                  link: json.data.link.replace(/^http:\/\//i, 'https://')
                })
              })
              .catch(function (err) {
                logger.error(err)
                return res.status(500).end('upload image error')
              })
            break
        }
      } catch (err) {
        logger.error(err)
        return res.status(500).end('upload image error')
      }
    }
  })
})
<|endoftext|>


<commit_before>/*
 * To use this mixin, a component needs:
 * - A computed property called "items" containing items we want to filter.
 * - A data/computed property called "filters", which is an array of strings
 *   that represent the nested props to filter by.
 *
 * To use the filter, you simply need to update the "searchInput" property.
 */
import _ from 'lodash';

export default {

	created() {
		if(!this.items || !Array.isArray(this.items)) {
			throw new Error(
				'[filterableMixin] "items" must exist in your data object and be an array'
			);
		}
	},

	data() {
		return {
			// these are just generic filters to be replaced
			filters: ['name', 'username', 'email'],
			searchInput: ''
		};
	},

	computed: {
		filteredItems() {
			return (
				this.searchInput.length > 1 ?
					this.items.filter(
						this.createFilter(
							this.filters,
							this.searchInput.toLowerCase()
						)
					) :
					this.items
			);
		}
	},

	methods: {
		createFilter(searchKeys, searchTerm) {
			return user => searchKeys.some(
				key => {
					const value = _.get(user, key);
					return value && value.toLowerCase().indexOf(searchTerm) !== -1;
				}
			);
		}
	}

};
<commit_msg>Update filterable mixin so multiple terms (separated by a space) can be used to filter data.<commit_after>/*
 * To use this mixin, a component needs:
 * - A computed property called "items" containing items we want to filter.
 * - A data/computed property called "filters", which is an array of strings
 *   that represent the nested props to filter by.
 *
 * To use the filter, you simply need to update the "searchInput" property.
 */
import _ from 'lodash';

export default {

	created() {
		if(!this.items || !Array.isArray(this.items)) {
			throw new Error(
				'[filterableMixin] "items" must exist in your data object and be an array'
			);
		}
	},

	data() {
		return {
			// these are just generic filters to be replaced
			filters: ['name', 'username', 'email'],
			searchInput: ''
		};
	},

	computed: {
		filteredItems() {
			return (
				this.searchInput.length > 1 ?
					this.items.filter(
						this.createFilter(
							this.filters,
							this.searchInput.toLowerCase()
						)
					) :
					this.items
			);
		}
	},

	methods: {
		createFilter(searchKeys, searchTerm) {
			const searchTerms = searchTerm.toLowerCase().split(' ');

			return item => searchKeys.some(
				key => {
					const value = _.get(item, key);

					return value && searchTerms.some(
						term => (
							term.length > 1 &&
							value.toLowerCase().indexOf(term) !== -1
						)
					)
				}
			);
		}
	}

};
<|endoftext|>


<commit_before>var nroonga = require('nroonga');
var Deferred = require('jsdeferred').Deferred;
var path = require('path');
var mkdirp = require('mkdirp');

var ShortText =
      exports.ShortText = 'ShortText';
var UInt32 =
      exports.UInt32 = 'UInt32';

var TABLE_HASH_KEY =
      exports.TABLE_HASH_KEY = 'TABLE_HASH_KEY';
var TABLE_PAT_KEY =
      exports.TABLE_PAT_KEY = 'TABLE_PAT_KEY';
var KEY_NORMALIZE =
      exports.KEY_NORMALIZE = 'KEY_NORMALIZE';

var COLUMN_SCALAR =
      exports.COLUMN_SCALAR = 'COLUMN_SCALAR';
var COLUMN_INDEX =
      exports.COLUMN_INDEX = 'COLUMN_INDEX';
var COLUMN_VECTOR =
      exports.COLUMN_VECTOR = 'COLUMN_VECTOR';
var WITH_POSITION =
      exports.WITH_POSITION = 'WITH_POSITION';

var INDEX_COLUMN_DEFAULT_FLAGS =
      exports.INDEX_COLUMN_DEFAULT_FLAGS = COLUMN_INDEX + '|' + WITH_POSITION;

var TokenBigram =
      exports.TokenBigram = 'TokenBigram';

function Context(source) {
  if (typeof source == 'string') { // path
    mkdirp.sync(path.dirname(source));
    this._path = source;
    this._context = new nroonga.Database(source);
  } else if (source instanceof nroonga.Database)
    this._context = source;
  else
    return source;
}

Context.prototype = {
  command: function() {
    return this._context.command.apply(this._context, arguments);
  },
  commandSync: function() {
    return this._context.commandSync.apply(this._context, arguments);
  },
  commandString: function() {
    return this._context.commandString.apply(this._context, arguments);
  },
  commandSyncString: function() {
    return this._context.commandSyncString.apply(this._context, arguments);
  },
  commandDeferred: function(command, options) {
    var deferred = new Deferred();
    var callback = function(error, data) {
          if (error)
            deferred.fail(error);
          else
            deferred.call(data);
        };

    if (options)
      this._context.command(command, options, callback);
    else
      this._context.command(command, callback);

    return deferred;
  },
  commandDeferredString: function(command) {
    var deferred = new Deferred();
    this._context.commandString(command, function(error, data) {
      if (error)
        deferred.fail(error);
      else
        deferred.call(data);
    });
    return deferred;
  },

  tableListSync: function(tableName) {
    var result =  this.commandSync('table_list');
    return formatResults(result);
  },

  columnListSync: function(tableName) {
    var result =  this.commandSync('column_list', { table: tableName });
    return formatResults(result);
  },
  ordinalColumnsSync: function(tableName) {
    var columns = this.columnListSync(tableName);
    var ordinalColumns = columns.filter(function(column) {
      return column.name.charAt(0) !== '_';
    });
    return ordinalColumns;
  },

  close: function() {
    this._context.close();
    this._context = undefined;
  },

  reopen: function() {
    if (!this._path)
      throw new Error('cannot reopen');
    this._context = new nroonga.Database(this._path);
    return this;
  }
};

exports.Database = exports.Context = Context;

function formatResults(results) {
  if (!results || !results.length)
    return [];

  var columns = {};
  results[0].forEach(function(column, index) {
    columns[index] = column[0];
  });

  var hashResults = [];
  results.slice(1).forEach(function(result) {
    var hashResult = {};
    result.forEach(function(column, index) {
      hashResult[columns[index]] = column;
    });
    hashResults.push(hashResult);
  });
  return hashResults;
}
exports.formatResults = formatResults;

function formatSelectResult(result) {
  return {
    count: result[0][0],
    results: formatResults(result.slice(1))
  };
}
exports.formatSelectResult = formatSelectResult;
<commit_msg>Format results to a hash if "_key" column is used<commit_after>var nroonga = require('nroonga');
var Deferred = require('jsdeferred').Deferred;
var path = require('path');
var mkdirp = require('mkdirp');

var ShortText =
      exports.ShortText = 'ShortText';
var UInt32 =
      exports.UInt32 = 'UInt32';

var TABLE_HASH_KEY =
      exports.TABLE_HASH_KEY = 'TABLE_HASH_KEY';
var TABLE_PAT_KEY =
      exports.TABLE_PAT_KEY = 'TABLE_PAT_KEY';
var KEY_NORMALIZE =
      exports.KEY_NORMALIZE = 'KEY_NORMALIZE';

var COLUMN_SCALAR =
      exports.COLUMN_SCALAR = 'COLUMN_SCALAR';
var COLUMN_INDEX =
      exports.COLUMN_INDEX = 'COLUMN_INDEX';
var COLUMN_VECTOR =
      exports.COLUMN_VECTOR = 'COLUMN_VECTOR';
var WITH_POSITION =
      exports.WITH_POSITION = 'WITH_POSITION';

var INDEX_COLUMN_DEFAULT_FLAGS =
      exports.INDEX_COLUMN_DEFAULT_FLAGS = COLUMN_INDEX + '|' + WITH_POSITION;

var TokenBigram =
      exports.TokenBigram = 'TokenBigram';

function Context(source) {
  if (typeof source == 'string') { // path
    mkdirp.sync(path.dirname(source));
    this._path = source;
    this._context = new nroonga.Database(source);
  } else if (source instanceof nroonga.Database)
    this._context = source;
  else
    return source;
}

Context.prototype = {
  command: function() {
    return this._context.command.apply(this._context, arguments);
  },
  commandSync: function() {
    return this._context.commandSync.apply(this._context, arguments);
  },
  commandString: function() {
    return this._context.commandString.apply(this._context, arguments);
  },
  commandSyncString: function() {
    return this._context.commandSyncString.apply(this._context, arguments);
  },
  commandDeferred: function(command, options) {
    var deferred = new Deferred();
    var callback = function(error, data) {
          if (error)
            deferred.fail(error);
          else
            deferred.call(data);
        };

    if (options)
      this._context.command(command, options, callback);
    else
      this._context.command(command, callback);

    return deferred;
  },
  commandDeferredString: function(command) {
    var deferred = new Deferred();
    this._context.commandString(command, function(error, data) {
      if (error)
        deferred.fail(error);
      else
        deferred.call(data);
    });
    return deferred;
  },

  tableListSync: function(tableName) {
    var result =  this.commandSync('table_list');
    return formatResults(result);
  },

  columnListSync: function(tableName) {
    var result =  this.commandSync('column_list', { table: tableName });
    return formatResults(result);
  },
  ordinalColumnsSync: function(tableName) {
    var columns = this.columnListSync(tableName);
    var ordinalColumns = columns.filter(function(column) {
      return column.name.charAt(0) !== '_';
    });
    return ordinalColumns;
  },

  close: function() {
    this._context.close();
    this._context = undefined;
  },

  reopen: function() {
    if (!this._path)
      throw new Error('cannot reopen');
    this._context = new nroonga.Database(this._path);
    return this;
  }
};

exports.Database = exports.Context = Context;

function formatResults(results) {
  if (!results || !results.length)
    return [];

  var columns = {};
  var keyColumnIndex = -1;
  results[0].forEach(function(column, index) {
    columns[index] = column[0];
    if (column[0] == '_key')
      keyColumnIndex = index;
  });

  var hashResults;
  if (keyColumnIndex > -1) {
    hashResults = {};
    results.slice(1).forEach(function(result) {
      var hashResult = {};
      result.forEach(function(column, index) {
        if (index == keyColumnIndex) return;
        hashResult[columns[index]] = column;
      });
      hashResults[result[keyColumnIndex]] = hashResult;
    });
    return hashResults;
  } else {
    hashResults = [];
    results.slice(1).forEach(function(result) {
      var hashResult = {};
      result.forEach(function(column, index) {
        hashResult[columns[index]] = column;
      });
      hashResults.push(hashResult);
    });
    return hashResults;
  }
}
exports.formatResults = formatResults;

function formatSelectResult(result) {
  return {
    count: result[0][0][0],
    results: formatResults(result[0].slice(1))
  };
}
exports.formatSelectResult = formatSelectResult;
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

/**
 * The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
 *  3 kinds of errors: prediction errors, failed predicate errors, and
 *  mismatched input errors. In each case, the parser knows where it is
 *  in the input, where it is in the ATN, the rule invocation stack,
 *  and what kind of problem occurred.
 */

const {PredicateTransition} = require('./../atn/Transition')

class RecognitionException extends Error {
    constructor(params) {
        super(params.message);
        if (!!Error.captureStackTrace) {
            Error.captureStackTrace(this, RecognitionException);
        } else {
            var stack = new Error().stack;
        }
        this.message = params.message;
        this.recognizer = params.recognizer;
        this.input = params.input;
        this.ctx = params.ctx;
        /**
         * The current {@link Token} when an error occurred. Since not all streams
         * support accessing symbols by index, we have to track the {@link Token}
         * instance itself
        */
        this.offendingToken = null;
        /**
         * Get the ATN state number the parser was in at the time the error
         * occurred. For {@link NoViableAltException} and
         * {@link LexerNoViableAltException} exceptions, this is the
         * {@link DecisionState} number. For others, it is the state whose outgoing
         * edge we couldn't match.
         */
        this.offendingState = -1;
        if (this.recognizer!==null) {
            this.offendingState = this.recognizer.state;
        }
    }

    /**
     * Gets the set of input symbols which could potentially follow the
     * previously matched symbol at the time this exception was thrown.
     *
     *
If the set of expected tokens is not known and could not be computed,
     * this method returns {@code null}.

     *
     * @return The set of token types that could potentially follow the current
     * state in the ATN, or {@code null} if the information is not available.
     */
    getExpectedTokens() {
        if (this.recognizer!==null) {
            return this.recognizer.atn.getExpectedTokens(this.offendingState, this.ctx);
        } else {
            return null;
        }
    }

    //
If the state number is not known, this method returns -1.

    toString() {
        return this.message;
    }
}

class LexerNoViableAltException extends RecognitionException {
    constructor(lexer, input, startIndex, deadEndConfigs) {
        super({message: "", recognizer: lexer, input: input, ctx: null});
        this.startIndex = startIndex;
        this.deadEndConfigs = deadEndConfigs;
    }

    toString() {
        let symbol = ""
        if (this.startIndex >= 0 && this.startIndex < this.input.size) {
            symbol = this.input.getText((this.startIndex,this.startIndex));
        }
        return "LexerNoViableAltException" + symbol;
    }
}

/**
 * Indicates that the parser could not decide which of two or more paths
 * to take based upon the remaining input. It tracks the starting token
 * of the offending input and also knows where the parser was
 * in the various paths when the error. Reported by reportNoViableAlternative()
 */
class NoViableAltException extends RecognitionException {
    constructor(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) {
        ctx = ctx || recognizer._ctx;
        offendingToken = offendingToken || recognizer.getCurrentToken();
        startToken = startToken || recognizer.getCurrentToken();
        input = input || recognizer.getInputStream();
        super({message: "", recognizer: recognizer, input: input, ctx: ctx});
        // Which configurations did we try at input.index() that couldn't match
        // input.LT(1)?//
        this.deadEndConfigs = deadEndConfigs;
        // The token object at the start index; the input stream might
        // not be buffering tokens so get a reference to it. (At the
        // time the error occurred, of course the stream needs to keep a
        // buffer all of the tokens but later we might not have access to those.)
        this.startToken = startToken;
        this.offendingToken = offendingToken;
    }
}

/**
 * This signifies any kind of mismatched input exceptions such as
 * when the current input does not match the expected token.
*/
class InputMismatchException extends RecognitionException {
    constructor(recognizer) {
        super({message: "", recognizer: recognizer, input: recognizer.getInputStream(), ctx: recognizer._ctx});
        this.offendingToken = recognizer.getCurrentToken();
    }
}

function formatMessage(predicate, message) {
    if (message !==null) {
        return message;
    } else {
        return "failed predicate: {" + predicate + "}?";
    }
}

/**
 * A semantic predicate failed during validation. Validation of predicates
 * occurs when normally parsing the alternative just like matching a token.
 * Disambiguating predicate evaluation occurs when we test a predicate during
 * prediction.
*/
class FailedPredicateException extends RecognitionException {
    constructor(recognizer, predicate, message) {
        super({
            message: formatMessage(predicate, message || null), recognizer: recognizer,
            input: recognizer.getInputStream(), ctx: recognizer._ctx
        });
        var s = recognizer._interp.atn.states[recognizer.state];
        var trans = s.transitions[0];
        if (trans instanceof PredicateTransition) {
            this.ruleIndex = trans.ruleIndex;
            this.predicateIndex = trans.predIndex;
        } else {
            this.ruleIndex = 0;
            this.predicateIndex = 0;
        }
        this.predicate = predicate;
        this.offendingToken = recognizer.getCurrentToken();
        return this;
    }
}

class ParseCancellationException extends Error{
    constructor() {
        super()
        Error.captureStackTrace(this, ParseCancellationException);
    }
}

module.exports = {
    RecognitionException,
    NoViableAltException,
    LexerNoViableAltException,
    InputMismatchException,
    FailedPredicateException,
    ParseCancellationException};
<commit_msg>missing const<commit_after>/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

/**
 * The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
 *  3 kinds of errors: prediction errors, failed predicate errors, and
 *  mismatched input errors. In each case, the parser knows where it is
 *  in the input, where it is in the ATN, the rule invocation stack,
 *  and what kind of problem occurred.
 */

const {PredicateTransition} = require('./../atn/Transition')

class RecognitionException extends Error {
    constructor(params) {
        super(params.message);
        if (!!Error.captureStackTrace) {
            Error.captureStackTrace(this, RecognitionException);
        } else {
            var stack = new Error().stack;
        }
        this.message = params.message;
        this.recognizer = params.recognizer;
        this.input = params.input;
        this.ctx = params.ctx;
        /**
         * The current {@link Token} when an error occurred. Since not all streams
         * support accessing symbols by index, we have to track the {@link Token}
         * instance itself
        */
        this.offendingToken = null;
        /**
         * Get the ATN state number the parser was in at the time the error
         * occurred. For {@link NoViableAltException} and
         * {@link LexerNoViableAltException} exceptions, this is the
         * {@link DecisionState} number. For others, it is the state whose outgoing
         * edge we couldn't match.
         */
        this.offendingState = -1;
        if (this.recognizer!==null) {
            this.offendingState = this.recognizer.state;
        }
    }

    /**
     * Gets the set of input symbols which could potentially follow the
     * previously matched symbol at the time this exception was thrown.
     *
     *
If the set of expected tokens is not known and could not be computed,
     * this method returns {@code null}.

     *
     * @return The set of token types that could potentially follow the current
     * state in the ATN, or {@code null} if the information is not available.
     */
    getExpectedTokens() {
        if (this.recognizer!==null) {
            return this.recognizer.atn.getExpectedTokens(this.offendingState, this.ctx);
        } else {
            return null;
        }
    }

    //
If the state number is not known, this method returns -1.

    toString() {
        return this.message;
    }
}

class LexerNoViableAltException extends RecognitionException {
    constructor(lexer, input, startIndex, deadEndConfigs) {
        super({message: "", recognizer: lexer, input: input, ctx: null});
        this.startIndex = startIndex;
        this.deadEndConfigs = deadEndConfigs;
    }

    toString() {
        let symbol = ""
        if (this.startIndex >= 0 && this.startIndex < this.input.size) {
            symbol = this.input.getText((this.startIndex,this.startIndex));
        }
        return "LexerNoViableAltException" + symbol;
    }
}

/**
 * Indicates that the parser could not decide which of two or more paths
 * to take based upon the remaining input. It tracks the starting token
 * of the offending input and also knows where the parser was
 * in the various paths when the error. Reported by reportNoViableAlternative()
 */
class NoViableAltException extends RecognitionException {
    constructor(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) {
        ctx = ctx || recognizer._ctx;
        offendingToken = offendingToken || recognizer.getCurrentToken();
        startToken = startToken || recognizer.getCurrentToken();
        input = input || recognizer.getInputStream();
        super({message: "", recognizer: recognizer, input: input, ctx: ctx});
        // Which configurations did we try at input.index() that couldn't match
        // input.LT(1)?//
        this.deadEndConfigs = deadEndConfigs;
        // The token object at the start index; the input stream might
        // not be buffering tokens so get a reference to it. (At the
        // time the error occurred, of course the stream needs to keep a
        // buffer all of the tokens but later we might not have access to those.)
        this.startToken = startToken;
        this.offendingToken = offendingToken;
    }
}

/**
 * This signifies any kind of mismatched input exceptions such as
 * when the current input does not match the expected token.
*/
class InputMismatchException extends RecognitionException {
    constructor(recognizer) {
        super({message: "", recognizer: recognizer, input: recognizer.getInputStream(), ctx: recognizer._ctx});
        this.offendingToken = recognizer.getCurrentToken();
    }
}

function formatMessage(predicate, message) {
    if (message !==null) {
        return message;
    } else {
        return "failed predicate: {" + predicate + "}?";
    }
}

/**
 * A semantic predicate failed during validation. Validation of predicates
 * occurs when normally parsing the alternative just like matching a token.
 * Disambiguating predicate evaluation occurs when we test a predicate during
 * prediction.
*/
class FailedPredicateException extends RecognitionException {
    constructor(recognizer, predicate, message) {
        super({
            message: formatMessage(predicate, message || null), recognizer: recognizer,
            input: recognizer.getInputStream(), ctx: recognizer._ctx
        });
        const s = recognizer._interp.atn.states[recognizer.state]
        const trans = s.transitions[0]
        if (trans instanceof PredicateTransition) {
            this.ruleIndex = trans.ruleIndex;
            this.predicateIndex = trans.predIndex;
        } else {
            this.ruleIndex = 0;
            this.predicateIndex = 0;
        }
        this.predicate = predicate;
        this.offendingToken = recognizer.getCurrentToken();
    }
}

class ParseCancellationException extends Error{
    constructor() {
        super()
        Error.captureStackTrace(this, ParseCancellationException);
    }
}

module.exports = {
    RecognitionException,
    NoViableAltException,
    LexerNoViableAltException,
    InputMismatchException,
    FailedPredicateException,
    ParseCancellationException};
<|endoftext|>