<commit_before>/*
	----------------------------------------------------------
	FileInfo : 0.1.1 : 2015-08-21 : https://mudcu.be
	----------------------------------------------------------
	references
	----------------------------------------------------------
		http://en.wikipedia.org/wiki/List_of_file_bySignature
		http://www.filebySignature.net/
	----------------------------------------------------------
*/

var FileInfo = (function() {

	var DEBUG = false;
	///
	var byExtension = (function() {
		var res = {
			/* text */
			json: {mime: 'application/json', type: 'text'},
			txt: {mime: 'text/plain', type: 'text'},

			/* image */
			bmp: {mime: 'image/bmp', type: 'image'},
			gif: {mime: 'image/gif', type: 'image'},
			icns: {mime: 'image/icns', type: 'image'},
			ico: {mime: 'image/x-icon', type: 'image'},
			jpeg: {mime: 'image/jpg', type: 'image'},
			jpg: {mime: 'image/jpg', type: 'image'},
			png: {mime: 'image/png', type: 'image'},
			tiff: {mime: 'image/tiff', type: 'image'},
			webp: {mime: 'image/webp', type: 'image'},

			/* audio */
			aiff: {mime: 'audio/aiff', type: 'audio'},
			mid: {mime: 'audio/mid', type: 'audio'},
			mp3: {mime: 'audio/mpeg', type: 'audio'},
			ogg: {mime: 'audio/ogg', type: 'audio'},
			wav: {mime: 'audio/wav', type: 'audio'},

			/* video */
			mp4: {mime: 'video/mp4', type: 'video'},
			mpeg: {mime: 'video/mpeg', type: 'video'},
			webm: {mime: 'video/webm', type: 'video'},

			/* clipart */
			svg: {mime: 'image/svg+xml', type: 'clipart'},

			/* font */
			eot: {mime: 'application/vnd.ms-fontobject', type: 'font'}, // http://en.wikipedia.org/wiki/Embedded_OpenType
			otf: {mime: 'application/font-sfnt', type: 'font'},
			ttf: {mime: 'application/font-sfnt', type: 'font'},
			woff: {mime: 'application/font-woff', type: 'font'},
			woff2: {mime: 'application/font-woff', type: 'font'},

			/* package */
			pdf: {mime: 'application/pdf', type: 'package'},
			ps: {mime: 'application/postscript', type: 'package'},
			psd: {mime: 'image/vnd.adobe.photoshop', type: 'package'},
			rtf: {mime: 'application/rtf', type: 'package'},
			zip: {mime: 'application/zip', type: 'package'}
		};
		for (var ext in res) {
			res[ext].extension = ext;
		}
		return res;
	})();

	var byMime = (function() {
		var res = {};
		for (var ext in byExtension) {
			var item = byExtension[ext];
			res[item.mime] = item;
		}
		return res;
	})();

	var bySignature = {
		/* image */
		'424d'    : 'bmp',
		'47494638': 'gif',
			// 47 49 46 38 37 61 (GIF87a)
			// 47 49 46 38 39 61 (GIF89a)
		'69636e73': 'icns', // http://en.wikipedia.org/wiki/Apple_Icon_Image_format
		'00000100': 'ico',
		'ffd8ff'  : 'jpg',
		'89504e47': 'png',
			// 89 50 4E 47 0D 0A 1A 0A
		'4d4d002a': 'tiff', // big endian format
		'49492a00': 'tiff', // little endian format
		'57454250': 'webp',

		/* audio */
		'464f524d': 'aiff',
			// 46 4F 52 4D nn nn nn nn 41 49 46 46
		'4d546864': 'mid', // 'MThd'
		'fffb'    : 'mp3',
		'494433'  : 'mp3',
		'4f676753': 'ogg',
		'52494646': 'wav',
			// 52 49 46 46 nn nn nn nn 57 41 56 45

		/* video */
		'000001b3': 'mpeg', // elementary stream (ES) // http://en.wikipedia.org/wiki/Elementary_stream
		'000001ba': 'mpeg', // program stream (PS) // http://en.wikipedia.org/wiki/MPEG_program_stream
		'1a45dfa3': 'webm',

		/* font */
		'4c50'    : 'eot',
		'00010000': 'ttf', // windows
			// 00 01 00 00 00
		'74727565': 'ttf', // mac
		'4f54544f': 'otf',
			// 4F 54 54 4F 00
		'774f4646': 'woff',
			// 77 4F 46 46 00 01 00 00
		'774f4646': 'woff',
		'774f4632': 'woff2',
			// 77 4F 46 32 00 01 00 00

		/* package */
		'25504446': 'pdf', // '%PDF'
		'25215053': 'ps',  // '%!PS-Ado'
		'38425053': 'psd', // '8BPS'
		'7b5c7274': 'rtf', // '{\rtf1'
			// 7b 5c 72 74 66 31
		'504b3414': 'zip', // zip.js
		'504b0304': 'zip', // 'PK..' - archive
		'504b0506': 'zip', // 'PK..' - empty archive
		'504b0708': 'zip', // 'PK..' - spanned archive

		/* loose detection - keep at end of object */
		'7b'      : 'json' // '{'
	};

	function FileInfo(input, onsuccess, onerror) {
		return wrap(function(onsuccess, onerror) {
			if (typeof input === 'string') {
				var res = fromString(input);
				if (res) {
					onsuccess(res);
				} else {
					onsuccess(byExtension.png); //- fix me
					warn(input, 1);
				}
			} else {
				if (isBlob(input)) {
					fromBlob(input, onsuccess, handleError);
				} else {
					handleError();
					warn(input, 2);
				}
			}
		}, arguments);

		function handleError() {
			onerror && onerror({
				message: 'blobFromBuffer: format could not be determined'
			});
		};
	};
	///
	FileInfo.fromBlob = fromBlob;
	FileInfo.fromBuffer = fromBuffer;
	FileInfo.fromString = fromString;
	FileInfo.fromExtension = fromExtension;
	FileInfo.fromMime = fromMime;
	///
	FileInfo.is = function(input, targetType, onsuccess, onerror) {
		return wrap(function(onsuccess, onerror) {
			FileInfo(input, function(fileInfo) {
				for (var key in fileInfo) {
					if (targetType === fileInfo[key]) {
						onsuccess(true);
						break;
					}
				}
				onsuccess(false);
			}, onerror);
		}, arguments);
	};
	///
	FileInfo.isBlob = isBlob;
	FileInfo.isSVGString = isSVGString;
	///
	return FileInfo;

	function wrap(fn, args) {
		if (typeof args[1] === 'function') {
			fn(args[1], args[2], args[3]);
		} else {
			return new Promise(function(resolve, revoke) {
				fn(resolve, revoke);
			});
		}
	};

	/* log */
	function warn(input, idx) {
		DEBUG && console.warn('could not detect format', input, idx);
	};

	/* detect */
	function isBlob(input) {
		var type = Object.prototype.toString.call(input);
		return type === '[object Blob]' || type === '[object File]';
	};

	function isSVGString(input) { // via vector.SVG.detect
		return input.startsWith('data:image/svg') ||
			   input.startsWith('<?xml') && input.includes('<svg') ||
			   input.startsWith('<svg');
	};

	/* detect via Blob */
	function fromBlob(blob, onsuccess, onerror) {
		var slice = blob.slice(0, Math.min(4, blob.size));
		var reader = new FileReader();
		reader.onload = function(event) {
			var buffer = reader.result;
			var res = fromBuffer(buffer) || byMime[blob.type];
			if (res) {
				onsuccess(res);
			} else {
				onerror && onerror();
				warn(blob, 3);
			}
		};
		reader.readAsArrayBuffer(slice);
	};

	/* detect via ArrayBuffer */
	function fromBuffer(buffer) {
		if (buffer.byteLength > 4)
			buffer = buffer.slice(0, 5);
		var signature = bufferToHex(buffer);
		for (var sig in bySignature) {
			if (sig === signature.slice(0, sig.length)) {
				var ext = bySignature[sig];
				return byExtension[ext];
			}
		}
	};

	function bufferToHex(buffer) {
		var array = new Uint8Array(buffer);
		var hex = '';
		for (var i = 0; i < array.length; i ++) {
			hex += array[i].toString(16);
		}
		return hex;
	};

	/* detect via String */
	function fromString(string) {
		var lower = string.toLowerCase();
		if (string.startsWith('data:')) {
			var mime = lower.substr(5).split(';').shift();
			return byMime[mime];
		} else {
			var ext = lower.split('.').pop();
			if (byExtension[ext]) {
				return byExtension[ext];
			} else {
				if (isSVGString(string)) {
					return byExtension.svg;
				}
			}
		}
	};

	function fromExtension(ext) {
		return byExtension[ext];
	};

	function fromMime(mime) {
		return byMime[mime];
	};
})();
<commit_msg>fix for magic number parser<commit_after>/*
	----------------------------------------------------------
	FileInfo : 0.1.2 : 2016-02-02 : https://mudcu.be
	----------------------------------------------------------
	references
	----------------------------------------------------------
		http://en.wikipedia.org/wiki/List_of_file_bySignature
		http://www.filebySignature.net/
	----------------------------------------------------------
*/

var FileInfo = (function () {

	var DEBUG = false;

	var byExtension = (function () {
		var res = {
			/* text */
			json: {mime: 'application/json', type: 'text'},
			txt: {mime: 'text/plain', type: 'text'},

			/* image */
			bmp: {mime: 'image/bmp', type: 'image'},
			gif: {mime: 'image/gif', type: 'image'},
			icns: {mime: 'image/icns', type: 'image'},
			ico: {mime: 'image/x-icon', type: 'image'},
			jpeg: {mime: 'image/jpg', type: 'image'},
			jpg: {mime: 'image/jpg', type: 'image'},
			png: {mime: 'image/png', type: 'image'},
			tiff: {mime: 'image/tiff', type: 'image'},
			webp: {mime: 'image/webp', type: 'image'},

			/* audio */
			aiff: {mime: 'audio/aiff', type: 'audio'},
			mid: {mime: 'audio/mid', type: 'audio'},
			mp3: {mime: 'audio/mpeg', type: 'audio'},
			ogg: {mime: 'audio/ogg', type: 'audio'},
			wav: {mime: 'audio/wav', type: 'audio'},

			/* video */
			mp4: {mime: 'video/mp4', type: 'video'},
			mpeg: {mime: 'video/mpeg', type: 'video'},
			webm: {mime: 'video/webm', type: 'video'},

			/* clipart */
			svg: {mime: 'image/svg+xml', type: 'clipart'},

			/* font */
			eot: {mime: 'application/vnd.ms-fontobject', type: 'font'}, // http://en.wikipedia.org/wiki/Embedded_OpenType
			otf: {mime: 'application/font-sfnt', type: 'font'},
			ttf: {mime: 'application/font-sfnt', type: 'font'},
			woff: {mime: 'application/font-woff', type: 'font'},
			woff2: {mime: 'application/font-woff', type: 'font'},

			/* package */
			pdf: {mime: 'application/pdf', type: 'package'},
			ps: {mime: 'application/postscript', type: 'package'},
			psd: {mime: 'image/vnd.adobe.photoshop', type: 'package'},
			rtf: {mime: 'application/rtf', type: 'package'},
			zip: {mime: 'application/zip', type: 'package'}
		};
		for (var ext in res) {
			res[ext].extension = ext;
		}
		return res;
	})();

	var byMime = (function () {
		var res = {};
		for (var ext in byExtension) {
			var item = byExtension[ext];
			res[item.mime] = item;
		}
		return res;
	})();

	var bySignature = {
		/* image */
		'424d'    : 'bmp',
		'47494638': 'gif',
			// 47 49 46 38 37 61 (GIF87a)
			// 47 49 46 38 39 61 (GIF89a)
		'69636e73': 'icns', // http://en.wikipedia.org/wiki/Apple_Icon_Image_format
		'00000100': 'ico',
		'ffd8ff'  : 'jpg',
		'89504e47': 'png',
			// 89 50 4E 47 0D 0A 1A 0A
		'4d4d002a': 'tiff', // big endian format
		'49492a00': 'tiff', // little endian format
		'57454250': 'webp',

		/* audio */
		'464f524d': 'aiff',
			// 46 4F 52 4D nn nn nn nn 41 49 46 46
		'4d546864': 'mid', // 'MThd'
		'fffb'    : 'mp3',
		'494433'  : 'mp3',
		'4f676753': 'ogg',
		'52494646': 'wav',
			// 52 49 46 46 nn nn nn nn 57 41 56 45

		/* video */
		'000001b3': 'mpeg', // elementary stream (ES) // http://en.wikipedia.org/wiki/Elementary_stream
		'000001ba': 'mpeg', // program stream (PS) // http://en.wikipedia.org/wiki/MPEG_program_stream
		'1a45dfa3': 'webm',

		/* font */
		'4c50'    : 'eot',
		'00010000': 'ttf', // windows
			// 00 01 00 00 00
		'74727565': 'ttf', // mac
		'4f54544f': 'otf',
			// 4F 54 54 4F 00
		'774f4646': 'woff',
			// 77 4F 46 46 00 01 00 00
		'774f4646': 'woff',
		'774f4632': 'woff2',
			// 77 4F 46 32 00 01 00 00

		/* package */
		'25504446': 'pdf', // '%PDF'
		'25215053': 'ps',  // '%!PS-Ado'
		'38425053': 'psd', // '8BPS'
		'7b5c7274': 'rtf', // '{\rtf1'
			// 7b 5c 72 74 66 31
		'504b0304': 'zip', // 'PK..' - archive
		'504b0506': 'zip', // 'PK..' - empty archive
		'504b0708': 'zip', // 'PK..' - spanned archive

		/* loose detection - keep at end of object */
		'7b'      : 'json' // '{'
	};

	function FileInfo(input, onsuccess, onerror) {
		return wrap(function (onsuccess, onerror) {
			if (typeof input === 'string') {
				var res = fromString(input);
				if (res) {
					onsuccess(res);
				} else {
					onsuccess(byExtension.png); //- fix me
					warn(input, 1);
				}
			} else {
				if (isBlob(input)) {
					fromBlob(input, onsuccess, handleError);
				} else {
					handleError();
					warn(input, 2);
				}
			}
		}, arguments);

		function handleError() {
			onerror && onerror({
				message: 'blobFromBuffer: format could not be determined'
			});
		};
	}

	FileInfo.fromBlob = fromBlob;
	FileInfo.fromBuffer = fromBuffer;
	FileInfo.fromString = fromString;
	FileInfo.fromExtension = fromExtension;
	FileInfo.fromMime = fromMime;

	FileInfo.is = function (input, targetType, onsuccess, onerror) {
		return wrap(function (onsuccess, onerror) {
			FileInfo(input, function (fileInfo) {
				for (var key in fileInfo) {
					if (targetType === fileInfo[key]) {
						onsuccess(true);
						break;
					}
				}
				onsuccess(false);
			}, onerror);
		}, arguments);
	};

	FileInfo.isBlob = isBlob;
	FileInfo.isFile = isFile;
	FileInfo.isSVGString = isSVGString;

	return FileInfo;

	function wrap(fn, args) {
		if (typeof args[1] === 'function') {
			fn(args[1], args[2], args[3]);
		} else {
			return new Promise(function (resolve, revoke) {
				fn(resolve, revoke);
			});
		}
	}

	/* log */
	function warn(input, idx) {
		DEBUG && console.warn('could not detect format', input, idx);
	}

	/* detect */
	function isBlob(input) {
		var type = Object.prototype.toString.call(input);
		return type === '[object Blob]' || type === '[object File]';
	}

	function isFile(input) {
		var type = Object.prototype.toString.call(input);
		return type === '[object File]';
	}

	function isSVGString(input) { // via vector.SVG.detect
		return input.startsWith('data:image/svg') ||
			   input.startsWith('<?xml') && input.includes('<svg') ||
			   input.startsWith('<svg');
	}

	/* detect via Blob */
	function fromBlob(blob, onsuccess, onerror) {
		var length = Math.min(5, blob.size);
		var slice = blob.slice(0, length);
		var reader = new FileReader();
		reader.onload = function (event) {
			var buffer = reader.result;
			var res = fromBuffer(buffer) || byMime[blob.type];
			if (res) {
				onsuccess(res);
			} else {
				onerror && onerror();
				warn(blob, 3);
			}
		};
		reader.readAsArrayBuffer(slice);
	}

	/* detect via ArrayBuffer */
	function fromBuffer(buffer) {
		if (buffer.byteLength > 4) {
			buffer = buffer.slice(0, 5);
		}

		var signature = bufferToHex(buffer);
		for (var sig in bySignature) {
			if (sig === signature.slice(0, sig.length)) {
				var ext = bySignature[sig];
				return byExtension[ext];
			}
		}
	}

	function bufferToHex(buffer) {
		var array = new Uint8Array(buffer);
		var hex = '';
		for (var i = 0; i < array.length; i ++) {
			var code = array[i].toString(16);
			if (code.length === 1) {
				hex += '0' + code;
			} else {
				hex += code;
			}
		}
		return hex;
	}

	/* detect via String */
	function fromString(string) {
		var lower = string.toLowerCase();
		if (string.startsWith('data:')) {
			var mime = lower.substr(5).split(';').shift();
			return byMime[mime];
		} else {
			var ext = lower.split('.').pop();
			if (byExtension[ext]) {
				return byExtension[ext];
			} else {
				if (isSVGString(string)) {
					return byExtension.svg;
				}
			}
		}
	}

	function fromExtension(ext) {
		return byExtension[ext];
	}

	function fromMime(mime) {
		return byMime[mime];
	}
})();
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Apigee Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var urlParse = require('url').parse;
var clone = require('lodash.clonedeep');

if (typeof window === 'undefined') {
  module.exports = convert;
} else {
  window.SwaggerConverter = window.SwaggerConverter || {
    convert: convert
  };
}

/*
 * Converts Swagger 1.2 specs file to Swagger 2.0 specs.
 * @param resourceListing {object} - root Swagger 1.2 document where it has a
 *  list of all paths
 * @param apiDeclarations {array} - a list of all resources listed in
 * resourceListing. Array of objects
 * @returns {object} - Fully converted Swagger 2.0 document
*/
function convert(resourceListing, apiDeclarations) {
  if (typeof resourceListing !== 'object') {
    throw new Error('resourceListing must be an object');
  }
  if (!Array.isArray(apiDeclarations)) {
    apiDeclarations = [];
  }

  var convertedSecurityNames = {};
  var models = {};
  var result = {
    swagger: '2.0',
    info: buildInfo(resourceListing),
    paths: {}
  };

  if (resourceListing.authorizations) {
    result.securityDefinitions = buildSecurityDefinitions(resourceListing,
      convertedSecurityNames);
  }

  if (resourceListing.basePath) {
    assignPathComponents(resourceListing.basePath, result);
  }

  extend(models, resourceListing.models);

  // Handle embedded documents
  if (Array.isArray(resourceListing.apis)) {
    resourceListing.apis.forEach(function(api) {
      if (Array.isArray(api.operations)) {
        result.paths[api.path] = buildPath(api, resourceListing);
      }
    });
  }

  apiDeclarations.forEach(function(apiDeclaration) {

    // For each apiDeclaration if there is a basePath, assign path components
    // This might override previous assignments
    if (apiDeclaration.basePath) {
      assignPathComponents(apiDeclaration.basePath, result);
    }

    if (!Array.isArray(apiDeclaration.apis)) { return; }
    apiDeclaration.apis.forEach(function(api) {
      result.paths[api.path] = buildPath(api, apiDeclaration);

    });
    if (apiDeclaration.models && Object.keys(apiDeclaration.models).length) {
      extend(models, transformAllModels(apiDeclaration.models));
    }
  });

  result.definitions = {};
  if (Object.keys(models).length) {
    result.definitions = transformAllModels(models);
  }

  return result;
}

/*
 * Builds "info" section of Swagger 2.0 document
 * @param source {object} - Swagger 1.2 document object
 * @returns {object} - "info" section of Swagger 2.0 document
*/
function buildInfo(source) {
  var info = {
    version: source.apiVersion,
    title: 'Title was not specified',
    version: '1.0.0'
  };

  if (typeof source.info === 'object') {

    if (source.info.title) {
      info.title = source.info.title;
    }

    if (source.info.description) {
      info.description = source.info.description;
    }

    if (source.info.contact) {
      info.contact = {
        email: source.info.contact
      };
    }

    if (source.info.license) {
      info.license = {
        name: source.info.license,
        url: source.info.licenseUrl
      };
    }

    if (source.info.termsOfServiceUrl) {
      info.termsOfService = source.info.termsOfServiceUrl;
    }
  }

  return info;
}

/*
 * Assigns host, basePath and schemes for Swagger 2.0 result document from
 * Swagger 1.2 basePath.
 * @param basePath {string} - the base path from Swagger 1.2
 * @param result {object} - Swagger 2.0 document
*/
function assignPathComponents(basePath, result) {
  var url = urlParse(basePath);
  result.host = url.host;
  result.basePath = url.path;
  result.schemes = [url.protocol.substr(0, url.protocol.length - 1)];
}

/*
 * Process a data type object.
 *
 * @see {@link https://github.com/swagger-api/swagger-spec/blob/master/versions/
 *  1.2.md#433-data-type-fields}
 *
 * @param field {object} - A data type field
 *
 * @returns {object} - Swagger 2.0 equivalent
 */
function processDataType(field) {
  field = clone(field);

  // Checking for the existence of '#/definitions/' is related to this bug:
  //   https://github.com/apigee-127/swagger-converter/issues/6
  if (field.$ref && field.$ref.indexOf('#/definitions/') === -1) {
    field.$ref = '#/definitions/' + field.$ref;
  } else if (field.items && field.items.$ref &&
             field.items.$ref.indexOf('#/definitions/') === -1) {
    field.items.$ref = '#/definitions/' + field.items.$ref;
  }

  if (field.type === 'integer') {
    if (field.minimum) {
      field.minimum = parseInt(field.minimum, 10);
    }

    if (field.maximum) {
      field.maximum = parseInt(field.maximum, 10);
    }
  } else {
    if (field.minimum) {
      field.minimum = parseFloat(field.minimum);
    }

    if (field.maximum) {
      field.maximum = parseFloat(field.maximum);
    }
  }

  if (field.defaultValue) {
    if (field.type === 'integer') {
      field.default = parseInt(field.defaultValue, 10);
    } else if (field.type === 'number') {
      field.default = parseFloat(field.defaultValue);
    } else {
      field.default = field.defaultValue;
    }

    delete field.defaultValue;
  }

  return field;
}

/*
 * Builds a Swagger 2.0 path object form a Swagger 1.2 path object
 * @param api {object} - Swagger 1.2 path object
 * @param apiDeclaration {object} - parent apiDeclaration
 * @returns {object} - Swagger 2.0 path object
*/
function buildPath(api, apiDeclaration) {
  var path = {};

  api.operations.forEach(function(oldOperation) {
    var method = oldOperation.method.toLowerCase();
    path[method] = buildOperation(oldOperation, apiDeclaration.produces,
      apiDeclaration.consumes);
  });

  return path;
}

/*
 * Builds a Swagger 2.0 operation object form a Swagger 1.2 operation object
 * @param oldOperation {object} - Swagger 1.2 operation object
 * @param produces {array} - from containing apiDeclaration
 * @param consumes {array} - from containing apiDeclaration
 * @returns {object} - Swagger 2.0 operation object
*/
function buildOperation(oldOperation, produces, consumes) {
  var operation = {
    responses: {},
    description: oldOperation.description || ''
  };

  if (oldOperation.summary) {
    operation.summary = oldOperation.summary;
  }

  if (oldOperation.nickname) {
    operation.operationId = oldOperation.nickname;
  }

  if (produces) { operation.produces = produces; }
  if (consumes) { operation.consumes = consumes; }

  if (Array.isArray(oldOperation.parameters) &&
      oldOperation.parameters.length) {
    operation.parameters = oldOperation.parameters.map(function(parameter) {
      return buildParameter(processDataType(parameter));
    });
  }

  if (Array.isArray(oldOperation.responseMessages)) {
    oldOperation.responseMessages.forEach(function(oldResponse) {
      operation.responses[oldResponse.code] = buildResponse(oldResponse);
    });
  }

  if (!Object.keys(operation.responses).length) {
    operation.responses = {
      '200': {
        description: 'No response was specified'
      }
    };
  }

  var primitiveTypes = [
    'string',
    'number',
    'boolean',
    'integer',
    'array',
    'void',
    'File'
  ];
  var copyProperties = [
    'format',
    'default',
    'maximum',
    'minimum',
    'items'
  ];

  if(oldOperation.type != 'void'){
      if(!('200' in operation.responses)) {
          operation.responses['200'] = {
              description: 'No response was specified'
          }
      }

      success_obj = operation.responses['200']
      if (primitiveTypes.indexOf(oldOperation.type) === -1) {
        success_obj.schema = {$ref: '#/definitions/' + oldOperation.type};
      } else {
        success_obj.schema = {};
        success_obj.schema.type = oldOperation.type.toLowerCase();

        copyProperties.forEach(function(name) {
          if (typeof oldOperation[name] !== 'undefined') {
            success_obj.schema[name] = oldOperation[name];
          }
        });

        if(oldOperation.items && '$ref' in oldOperation.items) {
            success_obj.schema.items['$ref'] = '#/definitions/' +
                oldOperation.items['$ref'];
        }
      }
  }

  return operation;
}

/*
 * Builds a Swagger 2.0 response object form a Swagger 1.2 response object
 * @param oldResponse {object} - Swagger 1.2 response object
 * @returns {object} - Swagger 2.0 response object
*/
function buildResponse(oldResponse) {
  var response = {};

  // TODO: Confirm this is correct
  response.description = oldResponse.message;

  return response;
}

/*
 * Converts Swagger 1.2 parameter object to Swagger 2.0 parameter object
 * @param oldParameter {object} - Swagger 1.2 parameter object
 * @returns {object} - Swagger 2.0 parameter object
*/
function buildParameter(oldParameter) {
  var parameter = {
    in: oldParameter.paramType,
    description: oldParameter.description,
    name: oldParameter.name,
    required: !!oldParameter.required
  };
  var primitiveTypes = [
    'string',
    'number',
    'boolean',
    'integer',
    'array',
    'void',
    'File'
  ];
  var copyProperties = [
    'format',
    'default',
    'maximum',
    'minimum',
    'items'
  ];

  if (primitiveTypes.indexOf(oldParameter.type) === -1) {
    parameter.schema = {$ref: '#/definitions/' + oldParameter.type};
  } else {
      if (oldParameter.paramType == 'body') {
        parameter.schema = {};
        obj = parameter.schema;
      } else {
        obj = parameter;
      }

    obj.type = oldParameter.type.toLowerCase();

    copyProperties.forEach(function(name) {
      if (typeof oldParameter[name] !== 'undefined') {
        obj[name] = oldParameter[name];
      }
    });

    if (typeof oldParameter.defaultValue !== 'undefined') {
      obj.default = oldParameter.defaultValue;
    }
  }

  // form was changed to formData in Swagger 2.0
  if (parameter.in === 'form') {
    parameter.in = 'formData';
  }

  return parameter;
}

/*
 * Convertes Swagger 1.2 authorization definitions to Swagger 2.0 security
 *   definitions
 *
 * @param resourceListing {object} - The Swagger 1.2 Resource Listing document
 * @param convertedSecurityNames {object} - A list of original Swagger 1.2
 * authorization names and the new Swagger 2.0
 *  security names associated with it (This is required because Swagger 2.0 only
 *  supports one oauth2 flow per security definition but in Swagger 1.2 you
 *  could describe two (implicit and authorization_code).  To support this, we
 *  will create a per-flow version of each oauth2 definition, where necessary,
 *  and keep track of the new names so that when we handle security references
 *  we reference things properly.)
 *
 * @returns {object} - Swagger 2.0 security definitions
 */
function buildSecurityDefinitions(resourceListing, convertedSecurityNames) {
  var securityDefinitions = {};

  Object.keys(resourceListing.authorizations).forEach(function(name) {
    var authorization = resourceListing.authorizations[name];
    var createDefinition = function createDefinition(oName) {
      var securityDefinition = securityDefinitions[oName || name] = {
        type: authorization.type
      };

      if (authorization.passAs) {
        securityDefinition.in = authorization.passAs;
      }

      if (authorization.keyname) {
        securityDefinition.name = authorization.keyname;
      }

      return securityDefinition;
    };

    // For oauth2 types, 1.2 describes multiple "flows" in one auth and for 2.0,
    // that is not an option so we need to
    // create one security definition per flow and keep track of this mapping.
    if (authorization.grantTypes) {
      convertedSecurityNames[name] = [];

      Object.keys(authorization.grantTypes).forEach(function(gtName) {
        var grantType = authorization.grantTypes[gtName];
        var oName = name + '_' + gtName;
        var securityDefinition = createDefinition(oName);

        convertedSecurityNames[name].push(oName);

        if (gtName === 'implicit') {
          securityDefinition.flow = 'implicit';
        } else {
          securityDefinition.flow = 'accessCode';
        }

        switch (gtName) {
        case 'implicit':
          securityDefinition.authorizationUrl = grantType.loginEndpoint.url;
          break;

        case 'authorization_code':
          securityDefinition.authorizationUrl =
            grantType.tokenRequestEndpoint.url;
          securityDefinition.tokenUrl = grantType.tokenEndpoint.url;
          break;
        }

        if (authorization.scopes) {
          securityDefinition.scopes = {};

          authorization.scopes.forEach(function(scope) {
            securityDefinition.scopes[scope.scope] = scope.description ||
              ('Undescribed ' + scope.scope);
          });
        }
      });
    } else {
      createDefinition();
    }
  });

  return securityDefinitions;
}

/*
 * Transforms a Swagger 1.2 model object to a Swagger 2.0 model object
 * @param model {object} - (mutable) Swagger 1.2 model object
*/
function transformModel(model) {
  if (typeof model.properties === 'object') {
    Object.keys(model.properties).forEach(function(propertieName) {
      model.properties[propertieName] =
        processDataType(model.properties[propertieName]);
    });
  }
}

/*
 * Transfers the "models" object of Swagger 1.2 specs to Swagger 2.0 definitions
 * object
 * @param models {object} - (mutable) an object containing Swagger 1.2 objects
 * @returns {object} - transformed modles object
*/
function transformAllModels(models) {
  var modelsClone = clone(models);

  if (typeof models !== 'object') {
    throw new Error('models must be object');
  }

  var hierarchy = {};

  Object.keys(modelsClone).forEach(function(modelId) {
    var model = modelsClone[modelId];
    delete model['id'];

    transformModel(model);

    if (model.subTypes) {
      hierarchy[modelId] = model.subTypes;

      delete model.subTypes;
    }
  });

  Object.keys(hierarchy).forEach(function(parent) {
    hierarchy[parent].forEach(function(childId) {
      var childModel = modelsClone[childId];

      if (childModel) {
        childModel.allOf = (childModel.allOf || []).concat({
          $ref: '#/definitions/' + parent
        });
      }
    });
  });

  return modelsClone;
}

/*
 * Extends an object with another
 * @param source {object} - object that will get extended
 * @parma distention {object} - object the will used to extend source
*/
function extend(source, distention) {
  if (typeof source !== 'object') {
    throw new Error('source must be objects');
  }

  if (typeof distention === 'object') {
    Object.keys(distention).forEach(function(key) {
      source[key] = distention[key];
    });
  }
}
<commit_msg>Revert "Assign empty result definitions"<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Apigee Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var urlParse = require('url').parse;
var clone = require('lodash.clonedeep');

if (typeof window === 'undefined') {
  module.exports = convert;
} else {
  window.SwaggerConverter = window.SwaggerConverter || {
    convert: convert
  };
}

/*
 * Converts Swagger 1.2 specs file to Swagger 2.0 specs.
 * @param resourceListing {object} - root Swagger 1.2 document where it has a
 *  list of all paths
 * @param apiDeclarations {array} - a list of all resources listed in
 * resourceListing. Array of objects
 * @returns {object} - Fully converted Swagger 2.0 document
*/
function convert(resourceListing, apiDeclarations) {
  if (typeof resourceListing !== 'object') {
    throw new Error('resourceListing must be an object');
  }
  if (!Array.isArray(apiDeclarations)) {
    apiDeclarations = [];
  }

  var convertedSecurityNames = {};
  var models = {};
  var result = {
    swagger: '2.0',
    info: buildInfo(resourceListing),
    paths: {}
  };

  if (resourceListing.authorizations) {
    result.securityDefinitions = buildSecurityDefinitions(resourceListing,
      convertedSecurityNames);
  }

  if (resourceListing.basePath) {
    assignPathComponents(resourceListing.basePath, result);
  }

  extend(models, resourceListing.models);

  // Handle embedded documents
  if (Array.isArray(resourceListing.apis)) {
    resourceListing.apis.forEach(function(api) {
      if (Array.isArray(api.operations)) {
        result.paths[api.path] = buildPath(api, resourceListing);
      }
    });
  }

  apiDeclarations.forEach(function(apiDeclaration) {

    // For each apiDeclaration if there is a basePath, assign path components
    // This might override previous assignments
    if (apiDeclaration.basePath) {
      assignPathComponents(apiDeclaration.basePath, result);
    }

    if (!Array.isArray(apiDeclaration.apis)) { return; }
    apiDeclaration.apis.forEach(function(api) {
      result.paths[api.path] = buildPath(api, apiDeclaration);

    });
    if (apiDeclaration.models && Object.keys(apiDeclaration.models).length) {
      extend(models, transformAllModels(apiDeclaration.models));
    }
  });

  if (Object.keys(models).length) {
    result.definitions = transformAllModels(models);
  }

  return result;
}

/*
 * Builds "info" section of Swagger 2.0 document
 * @param source {object} - Swagger 1.2 document object
 * @returns {object} - "info" section of Swagger 2.0 document
*/
function buildInfo(source) {
  var info = {
    version: source.apiVersion,
    title: 'Title was not specified',
    version: '1.0.0'
  };

  if (typeof source.info === 'object') {

    if (source.info.title) {
      info.title = source.info.title;
    }

    if (source.info.description) {
      info.description = source.info.description;
    }

    if (source.info.contact) {
      info.contact = {
        email: source.info.contact
      };
    }

    if (source.info.license) {
      info.license = {
        name: source.info.license,
        url: source.info.licenseUrl
      };
    }

    if (source.info.termsOfServiceUrl) {
      info.termsOfService = source.info.termsOfServiceUrl;
    }
  }

  return info;
}

/*
 * Assigns host, basePath and schemes for Swagger 2.0 result document from
 * Swagger 1.2 basePath.
 * @param basePath {string} - the base path from Swagger 1.2
 * @param result {object} - Swagger 2.0 document
*/
function assignPathComponents(basePath, result) {
  var url = urlParse(basePath);
  result.host = url.host;
  result.basePath = url.path;
  result.schemes = [url.protocol.substr(0, url.protocol.length - 1)];
}

/*
 * Process a data type object.
 *
 * @see {@link https://github.com/swagger-api/swagger-spec/blob/master/versions/
 *  1.2.md#433-data-type-fields}
 *
 * @param field {object} - A data type field
 *
 * @returns {object} - Swagger 2.0 equivalent
 */
function processDataType(field) {
  field = clone(field);

  // Checking for the existence of '#/definitions/' is related to this bug:
  //   https://github.com/apigee-127/swagger-converter/issues/6
  if (field.$ref && field.$ref.indexOf('#/definitions/') === -1) {
    field.$ref = '#/definitions/' + field.$ref;
  } else if (field.items && field.items.$ref &&
             field.items.$ref.indexOf('#/definitions/') === -1) {
    field.items.$ref = '#/definitions/' + field.items.$ref;
  }

  if (field.type === 'integer') {
    if (field.minimum) {
      field.minimum = parseInt(field.minimum, 10);
    }

    if (field.maximum) {
      field.maximum = parseInt(field.maximum, 10);
    }
  } else {
    if (field.minimum) {
      field.minimum = parseFloat(field.minimum);
    }

    if (field.maximum) {
      field.maximum = parseFloat(field.maximum);
    }
  }

  if (field.defaultValue) {
    if (field.type === 'integer') {
      field.default = parseInt(field.defaultValue, 10);
    } else if (field.type === 'number') {
      field.default = parseFloat(field.defaultValue);
    } else {
      field.default = field.defaultValue;
    }

    delete field.defaultValue;
  }

  return field;
}

/*
 * Builds a Swagger 2.0 path object form a Swagger 1.2 path object
 * @param api {object} - Swagger 1.2 path object
 * @param apiDeclaration {object} - parent apiDeclaration
 * @returns {object} - Swagger 2.0 path object
*/
function buildPath(api, apiDeclaration) {
  var path = {};

  api.operations.forEach(function(oldOperation) {
    var method = oldOperation.method.toLowerCase();
    path[method] = buildOperation(oldOperation, apiDeclaration.produces,
      apiDeclaration.consumes);
  });

  return path;
}

/*
 * Builds a Swagger 2.0 operation object form a Swagger 1.2 operation object
 * @param oldOperation {object} - Swagger 1.2 operation object
 * @param produces {array} - from containing apiDeclaration
 * @param consumes {array} - from containing apiDeclaration
 * @returns {object} - Swagger 2.0 operation object
*/
function buildOperation(oldOperation, produces, consumes) {
  var operation = {
    responses: {},
    description: oldOperation.description || ''
  };

  if (oldOperation.summary) {
    operation.summary = oldOperation.summary;
  }

  if (oldOperation.nickname) {
    operation.operationId = oldOperation.nickname;
  }

  if (produces) { operation.produces = produces; }
  if (consumes) { operation.consumes = consumes; }

  if (Array.isArray(oldOperation.parameters) &&
      oldOperation.parameters.length) {
    operation.parameters = oldOperation.parameters.map(function(parameter) {
      return buildParameter(processDataType(parameter));
    });
  }

  if (Array.isArray(oldOperation.responseMessages)) {
    oldOperation.responseMessages.forEach(function(oldResponse) {
      operation.responses[oldResponse.code] = buildResponse(oldResponse);
    });
  }

  if (!Object.keys(operation.responses).length) {
    operation.responses = {
      '200': {
        description: 'No response was specified'
      }
    };
  }

  var primitiveTypes = [
    'string',
    'number',
    'boolean',
    'integer',
    'array',
    'void',
    'File'
  ];
  var copyProperties = [
    'format',
    'default',
    'maximum',
    'minimum',
    'items'
  ];

  if(oldOperation.type != 'void'){
      if(!('200' in operation.responses)) {
          operation.responses['200'] = {
              description: 'No response was specified'
          }
      }

      success_obj = operation.responses['200']
      if (primitiveTypes.indexOf(oldOperation.type) === -1) {
        success_obj.schema = {$ref: '#/definitions/' + oldOperation.type};
      } else {
        success_obj.schema = {};
        success_obj.schema.type = oldOperation.type.toLowerCase();

        copyProperties.forEach(function(name) {
          if (typeof oldOperation[name] !== 'undefined') {
            success_obj.schema[name] = oldOperation[name];
          }
        });

        if(oldOperation.items && '$ref' in oldOperation.items) {
            success_obj.schema.items['$ref'] = '#/definitions/' +
                oldOperation.items['$ref'];
        }
      }
  }

  return operation;
}

/*
 * Builds a Swagger 2.0 response object form a Swagger 1.2 response object
 * @param oldResponse {object} - Swagger 1.2 response object
 * @returns {object} - Swagger 2.0 response object
*/
function buildResponse(oldResponse) {
  var response = {};

  // TODO: Confirm this is correct
  response.description = oldResponse.message;

  return response;
}

/*
 * Converts Swagger 1.2 parameter object to Swagger 2.0 parameter object
 * @param oldParameter {object} - Swagger 1.2 parameter object
 * @returns {object} - Swagger 2.0 parameter object
*/
function buildParameter(oldParameter) {
  var parameter = {
    in: oldParameter.paramType,
    description: oldParameter.description,
    name: oldParameter.name,
    required: !!oldParameter.required
  };
  var primitiveTypes = [
    'string',
    'number',
    'boolean',
    'integer',
    'array',
    'void',
    'File'
  ];
  var copyProperties = [
    'format',
    'default',
    'maximum',
    'minimum',
    'items'
  ];

  if (primitiveTypes.indexOf(oldParameter.type) === -1) {
    parameter.schema = {$ref: '#/definitions/' + oldParameter.type};
  } else {
      if (oldParameter.paramType == 'body') {
        parameter.schema = {};
        obj = parameter.schema;
      } else {
        obj = parameter;
      }

    obj.type = oldParameter.type.toLowerCase();

    copyProperties.forEach(function(name) {
      if (typeof oldParameter[name] !== 'undefined') {
        obj[name] = oldParameter[name];
      }
    });

    if (typeof oldParameter.defaultValue !== 'undefined') {
      obj.default = oldParameter.defaultValue;
    }
  }

  // form was changed to formData in Swagger 2.0
  if (parameter.in === 'form') {
    parameter.in = 'formData';
  }

  return parameter;
}

/*
 * Convertes Swagger 1.2 authorization definitions to Swagger 2.0 security
 *   definitions
 *
 * @param resourceListing {object} - The Swagger 1.2 Resource Listing document
 * @param convertedSecurityNames {object} - A list of original Swagger 1.2
 * authorization names and the new Swagger 2.0
 *  security names associated with it (This is required because Swagger 2.0 only
 *  supports one oauth2 flow per security definition but in Swagger 1.2 you
 *  could describe two (implicit and authorization_code).  To support this, we
 *  will create a per-flow version of each oauth2 definition, where necessary,
 *  and keep track of the new names so that when we handle security references
 *  we reference things properly.)
 *
 * @returns {object} - Swagger 2.0 security definitions
 */
function buildSecurityDefinitions(resourceListing, convertedSecurityNames) {
  var securityDefinitions = {};

  Object.keys(resourceListing.authorizations).forEach(function(name) {
    var authorization = resourceListing.authorizations[name];
    var createDefinition = function createDefinition(oName) {
      var securityDefinition = securityDefinitions[oName || name] = {
        type: authorization.type
      };

      if (authorization.passAs) {
        securityDefinition.in = authorization.passAs;
      }

      if (authorization.keyname) {
        securityDefinition.name = authorization.keyname;
      }

      return securityDefinition;
    };

    // For oauth2 types, 1.2 describes multiple "flows" in one auth and for 2.0,
    // that is not an option so we need to
    // create one security definition per flow and keep track of this mapping.
    if (authorization.grantTypes) {
      convertedSecurityNames[name] = [];

      Object.keys(authorization.grantTypes).forEach(function(gtName) {
        var grantType = authorization.grantTypes[gtName];
        var oName = name + '_' + gtName;
        var securityDefinition = createDefinition(oName);

        convertedSecurityNames[name].push(oName);

        if (gtName === 'implicit') {
          securityDefinition.flow = 'implicit';
        } else {
          securityDefinition.flow = 'accessCode';
        }

        switch (gtName) {
        case 'implicit':
          securityDefinition.authorizationUrl = grantType.loginEndpoint.url;
          break;

        case 'authorization_code':
          securityDefinition.authorizationUrl =
            grantType.tokenRequestEndpoint.url;
          securityDefinition.tokenUrl = grantType.tokenEndpoint.url;
          break;
        }

        if (authorization.scopes) {
          securityDefinition.scopes = {};

          authorization.scopes.forEach(function(scope) {
            securityDefinition.scopes[scope.scope] = scope.description ||
              ('Undescribed ' + scope.scope);
          });
        }
      });
    } else {
      createDefinition();
    }
  });

  return securityDefinitions;
}

/*
 * Transforms a Swagger 1.2 model object to a Swagger 2.0 model object
 * @param model {object} - (mutable) Swagger 1.2 model object
*/
function transformModel(model) {
  if (typeof model.properties === 'object') {
    Object.keys(model.properties).forEach(function(propertieName) {
      model.properties[propertieName] =
        processDataType(model.properties[propertieName]);
    });
  }
}

/*
 * Transfers the "models" object of Swagger 1.2 specs to Swagger 2.0 definitions
 * object
 * @param models {object} - (mutable) an object containing Swagger 1.2 objects
 * @returns {object} - transformed modles object
*/
function transformAllModels(models) {
  var modelsClone = clone(models);

  if (typeof models !== 'object') {
    throw new Error('models must be object');
  }

  var hierarchy = {};

  Object.keys(modelsClone).forEach(function(modelId) {
    var model = modelsClone[modelId];
    delete model['id'];

    transformModel(model);

    if (model.subTypes) {
      hierarchy[modelId] = model.subTypes;

      delete model.subTypes;
    }
  });

  Object.keys(hierarchy).forEach(function(parent) {
    hierarchy[parent].forEach(function(childId) {
      var childModel = modelsClone[childId];

      if (childModel) {
        childModel.allOf = (childModel.allOf || []).concat({
          $ref: '#/definitions/' + parent
        });
      }
    });
  });

  return modelsClone;
}

/*
 * Extends an object with another
 * @param source {object} - object that will get extended
 * @parma distention {object} - object the will used to extend source
*/
function extend(source, distention) {
  if (typeof source !== 'object') {
    throw new Error('source must be objects');
  }

  if (typeof distention === 'object') {
    Object.keys(distention).forEach(function(key) {
      source[key] = distention[key];
    });
  }
}
<|endoftext|>


<commit_before>var express = require('express'),
	fs = require('fs'),
	config = require('./config/config.json'),
	path = require('path'),
	serveStatic = require('serve-static'),
	exif = require('exif'),
	multiparty = require('multiparty');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(serveStatic(path.join(__dirname, '/views/static')));

app.get('/', function (req, res) {
	res.render('index', {});
});

app.get('/upload', function (req, res) {
	res.render('upload', {});
});

app.get('/map', function (req, res) {
	res.render('map', {apiKey: config.google.maps.key});
});

app.post('/upload', function (req, res) {
	var form = new multiparty.Form();
	var dest = path.join(__dirname, 'files');

	form.on('error', function (err) {
		throw err;
	});

	form.on('close', function () {
		res.send('file uploaded');
	});

	form.on("file", function (name, file) {
		var new_file = path.join(dest, file.originalFilename);
		fs.rename(file.path, new_file, function (err) {
			if (err) {
				throw err;
			}
			console.log('file has been moved: ' + file.path + ' -> ' + new_file);
			new exif.ExifImage({
				image: new_file
			}, function (err, data) {
				if (err) {
					throw err;
				}
				console.dir(data);
				if (data.gps) {
					var lat = convert(data.gps.GPSLatitude[0], data.gps.GPSLatitude[1], data.gps.GPSLatitude[2]);
					var lon = convert(data.gps.GPSLongitude[0], data.gps.GPSLongitude[1], data.gps.GPSLongitude[2]);
					if (data.gps.GPSLongitudeRef === 'W') {
						lon = lon * -1;
					}
					console.log('GPSLatitude', lat);
					console.log('GPSLongitude', lon);
				}
			});
		});
	});

	form.parse(req);
});

app.listen(3000);

function convert(deg, min, sec) {
	var azi;
	if (deg < 0) {
		azi = -1.0 * deg + 1.0 * min / 60.0 + 1.0 * sec / 3600.0;
		return -1.0 * azi;
	} else {
		azi = 1.0 * deg + 1.0 * min / 60.0 + 1.0 * sec / 3600.0;
		return azi;
	}
}

<commit_msg>Moving routes from index.js file<commit_after>var express = require('express'),
	fs = require('fs'),
	config = require('./config/config.json'),
	path = require('path'),
	serveStatic = require('serve-static'),
	exif = require('exif'),
	multiparty = require('multiparty');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

// load up the main router!
var Router = express.Router();
var router = require('./routes/index')(Router);
app.use('/', router);

app.use(serveStatic(path.join(__dirname, '/views/static')));

// app.get('/', function (req, res) {
// 	res.render('index', {});
// });

// app.get('/upload', function (req, res) {
// 	res.render('upload', {});
// });

// app.get('/map', function (req, res) {
// 	res.render('map', {apiKey: config.google.maps.key});
// });

// app.post('/upload', function (req, res) {
// 	var form = new multiparty.Form();
// 	var dest = path.join(__dirname, 'files');

// 	form.on('error', function (err) {
// 		throw err;
// 	});

// 	form.on('close', function () {
// 		res.send('file uploaded');
// 	});

// 	form.on("file", function (name, file) {
// 		var new_file = path.join(dest, file.originalFilename);
// 		fs.rename(file.path, new_file, function (err) {
// 			if (err) {
// 				throw err;
// 			}
// 			console.log('file has been moved: ' + file.path + ' -> ' + new_file);
// 			new exif.ExifImage({
// 				image: new_file
// 			}, function (err, data) {
// 				if (err) {
// 					throw err;
// 				}
// 				console.dir(data);
// 				if (data.gps) {
// 					var lat = convert(data.gps.GPSLatitude[0], data.gps.GPSLatitude[1], data.gps.GPSLatitude[2]);
// 					var lon = convert(data.gps.GPSLongitude[0], data.gps.GPSLongitude[1], data.gps.GPSLongitude[2]);
// 					if (data.gps.GPSLongitudeRef === 'W') {
// 						lon = lon * -1;
// 					}
// 					console.log('GPSLatitude', lat);
// 					console.log('GPSLongitude', lon);
// 				} else {
// 					console.log("couldn't locate GPS data from image");
// 				}
// 			});
// 		});
// 	});

// 	form.parse(req);
// });

app.listen(3000, function () {
	console.log("listening on port: 3000");
});

function convert(deg, min, sec) {
	var azi;
	if (deg < 0) {
		azi = -1.0 * deg + 1.0 * min / 60.0 + 1.0 * sec / 3600.0;
		return -1.0 * azi;
	} else {
		azi = 1.0 * deg + 1.0 * min / 60.0 + 1.0 * sec / 3600.0;
		return azi;
	}
}

<|endoftext|>


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

const randomIntInc = (low, high) => Math.floor((Math.random() * ((high - low) + 1)) + low);

const firstHalfStartInMinutes = () => {
  const TenMinutesToEigthInMinutes = (7 * 60) + 50;
  const TenMinutesPastEigthInMinutes = (8 * 60) + 10;

  return randomIntInc(TenMinutesToEigthInMinutes, TenMinutesPastEigthInMinutes);
};

const secondHalfStartInMinutes = (endOfTheMorning) => {
  const OneHourFiftyMinutesInMinutes = 60 + 50;
  const TwoHoursInMinutes = 2 * 60;

  return endOfTheMorning + randomIntInc(OneHourFiftyMinutesInMinutes, TwoHoursInMinutes);
};

const halfEndInMinutes = (halfStart) => {
  const ThreeHoursFiftyFiveMinutesInMinutes = (3 * 60) + 55;
  const FourHoursFiveMinutesInMinutes = (4 * 60) + 5;

  return halfStart
    + randomIntInc(ThreeHoursFiftyFiveMinutesInMinutes, FourHoursFiveMinutesInMinutes);
};

for (let day = 1; day <= 31; day += 1) {
  const date = new Date();
  date.setHours(0, 0, 0);

  const morningStart = firstHalfStartInMinutes();
  date.setHours(Math.floor(morningStart / 60), morningStart % 60);
  process.stdout.write(dateformat(date, 'HH:MM'));

  const morningEnd = halfEndInMinutes(morningStart);
  date.setHours(Math.floor(morningEnd / 60), morningEnd % 60);
  process.stdout.write(`\t${dateformat(date, 'HH:MM')}`);

  const afternoonStart = secondHalfStartInMinutes(morningEnd);
  date.setHours(Math.floor(afternoonStart / 60), afternoonStart % 60);
  process.stdout.write(`\t${dateformat(date, 'HH:MM')}`);

  const afternoonEnd = halfEndInMinutes(afternoonStart);
  date.setHours(Math.floor(afternoonEnd / 60), afternoonEnd % 60);
  process.stdout.write(`\t${dateformat(date, 'HH:MM')}`);

  process.stdout.write('\n');
}
<commit_msg>Removes the time from weekends and holidays (configured in .env file)<commit_after>require('dotenv').config();

const dateformat = require('dateformat');

const randomIntInc = (low, high) => Math.floor((Math.random() * ((high - low) + 1)) + low);

const firstHalfStartInMinutes = () => {
  const TenMinutesToEigthInMinutes = (7 * 60) + 50;
  const TenMinutesPastEigthInMinutes = (8 * 60) + 10;

  return randomIntInc(TenMinutesToEigthInMinutes, TenMinutesPastEigthInMinutes);
};

const secondHalfStartInMinutes = (endOfTheMorning) => {
  const OneHourFiftyMinutesInMinutes = 60 + 50;
  const TwoHoursInMinutes = 2 * 60;

  return endOfTheMorning + randomIntInc(OneHourFiftyMinutesInMinutes, TwoHoursInMinutes);
};

const halfEndInMinutes = (halfStart) => {
  const ThreeHoursFiftyFiveMinutesInMinutes = (3 * 60) + 55;
  const FourHoursFiveMinutesInMinutes = (4 * 60) + 5;

  return halfStart
    + randomIntInc(ThreeHoursFiftyFiveMinutesInMinutes, FourHoursFiveMinutesInMinutes);
};

const noWorkDays = process.env.NO_WORK_DAYS.split(',');

let day = 1;
while (day <= process.env.TOTAL_DAYS) {
  if (!noWorkDays.includes(day.toString())) {
    const date = new Date();
    date.setHours(0, 0, 0);

    const morningStart = firstHalfStartInMinutes();
    date.setHours(Math.floor(morningStart / 60), morningStart % 60);
    process.stdout.write(dateformat(date, 'HH:MM'));

    const morningEnd = halfEndInMinutes(morningStart);
    date.setHours(Math.floor(morningEnd / 60), morningEnd % 60);
    process.stdout.write(`\t${dateformat(date, 'HH:MM')}`);

    const afternoonStart = secondHalfStartInMinutes(morningEnd);
    date.setHours(Math.floor(afternoonStart / 60), afternoonStart % 60);
    process.stdout.write(`\t${dateformat(date, 'HH:MM')}`);

    const afternoonEnd = halfEndInMinutes(afternoonStart);
    date.setHours(Math.floor(afternoonEnd / 60), afternoonEnd % 60);
    process.stdout.write(`\t${dateformat(date, 'HH:MM')}`);
  }

  process.stdout.write('\n');
  day += 1;
}
<|endoftext|>


<commit_before>const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

const recipepuppyHost = 'http://www.recipepuppy.com/api/?q=';

app.get('/dummyget', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ 'speech': 'dummy speech', 'displayText': 'dummy get works!' }));
});

app.post('/webhook', function (req, res) {
    if (req.body.result.parameters['recipeitem']) {
        recipeitem = req.body.result.parameters['recipeitem'];
        callRecipePuppy(recipeitem)
            .then((output) => {
                res.setHeader('Content-Type', 'application/json');
                res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
            })
            .catch((error) => {
                res.setHeader('Content-Type', 'application/json');
                res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
            });
    } else {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({ 'speech': "No Proper hook found", 'displayText': "No Proper hook found" }));
    }
});

function callRecipePuppy(recipeitem) {
    return new Promise((resolve, reject) => {
        http.get(recipepuppyHost + recipeitem, (res) => {
            let body = '';
            res.on('data', (d) => body += d);
            res.on('end', () => {
                let jO = JSON.parse(body);
                let firstItem = jO.results[0];

                let output = firstItem.title + " using " + firstItem.href;
                resolve(output);
            });

            res.on('error', (error) => {
                reject(error);
            });
        });
    });
}

app.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<commit_msg>changed recipeitem to fooditem<commit_after>const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

const recipepuppyHost = 'http://www.recipepuppy.com/api/?q=';

app.get('/dummyget', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ 'speech': 'dummy speech', 'displayText': 'dummy get works!' }));
});

app.post('/webhook', function (req, res) {
    if (req.body.result.parameters['fooditem']) {
        var fooditem = req.body.result.parameters['fooditem'];
        callRecipePuppy(fooditem)
            .then((output) => {
                res.setHeader('Content-Type', 'application/json');
                res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
            })
            .catch((error) => {
                res.setHeader('Content-Type', 'application/json');
                res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
            });
    } else {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({ 'speech': "No Proper hook found", 'displayText': "No Proper hook found" }));
    }
});

function callRecipePuppy(fooditem) {
    return new Promise((resolve, reject) => {
        http.get(recipepuppyHost + fooditem, (res) => {
            let body = '';
            res.on('data', (d) => body += d);
            res.on('end', () => {
                let jO = JSON.parse(body);
                let firstItem = jO.results[0];

                let output = firstItem.title + " using " + firstItem.href;
                resolve(output);
            });

            res.on('error', (error) => {
                reject(error);
            });
        });
    });
}

app.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<|endoftext|>


<commit_before>"use strict";

var Router  = require('./lib/Router');
var Route   = require('./lib/Route');
var Link    = require('./lib/Link');

module.exports = {
  Locations: Router.Locations,
  Pages: Router.Pages,

  Location: Route.Route,
  Page: Route.Route,
  NotFound: Route.NotFound,

  Link: Link
}
<commit_msg>Gardening<commit_after>"use strict";

var Router  = require('./lib/Router');
var Route   = require('./lib/Route');
var Link    = require('./lib/Link');

module.exports = {
  Locations: Router.Locations,
  Pages: Router.Pages,

  Location: Route.Route,
  Page: Route.Route,
  NotFound: Route.NotFound,

  Link: Link
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

var co = require('co');

co(function* () {

	var	request = require('co-request'),
		pkg = require('./package.json'),
		colors = require('colors'),
		argv = process.argv.slice(2),
		params = {};

	if(argv.indexOf("--help") !== -1){
		console.log([
		'',
		pkg.description,
		'Example:',
		'broken-links -s http://kuesty.com -404 http://kuesty.com/error/404'
		].join("\n"));
		return;
	}

	for(var i=0; i<argv.length;i+=2){
		params[argv[i]] = argv[i+1];
	}
	if(params["-s"] == undefined) {
		console.log("You must provide the site name".red);
		return;
	}
	if(params["-404"] == undefined) {
		console.log("You must provide your 404 page to compare".red);
		return;
	}

	var base_uri = params["-s"];
			base_uri = base_uri.indexOf("http") === -1 ? "http://"+base_uri : base_uri;

	var uri = params["-404"];
			uri = uri.indexOf("http") === -1 ? "http://"+uri : uri;

	console.log("Getting 404 source: ".white+ params["-404"].yellow);
	var result = yield request(uri);
	var body404 = result.body;
			body404 = body404.replace(/\s+/g,"");

	console.log("Getting page source: ".white+params["-s"].yellow);
	var result = yield request(base_uri);
	var response = result.body;

	console.log("Getting page links".white);
	var allLinks = response.match(/href="[a-zA-Z\:\/\.\-0-9\@\#\&\;]+/g);
	var links = {};

	var relative_uri = base_uri.match(/https?:\/\/[a-zA-Z\.\-0-9]+/)[0];

	for(var i=0;i<allLinks.length;i++) {
		var a = allLinks[i].replace(/href="/,"");
		if(a.indexOf(".css") !== -1) continue;
		if(a.indexOf(".ico") !== -1) continue;
		if(a.indexOf("#") == 0) continue;
		if(a == "/") continue;
		if(a.match(/https?:/)) continue;
		if(links[a] != undefined) continue;

		links[a] = relative_uri + a;
		var result = yield request(links[a]);
		console.log(result.statusCode);
		if(result.statusCode == 404) {
			console.log("|_ "+links[a].yellow + " -> BROKEN".red);
			continue;
		}
		var body = result.body;
		    body = body.replace(/\s+/g,"");

		if(body == body404){
			console.log("|_ "+links[a].yellow + " -> BROKEN".red);
		}else{
			console.log("|_ " +links[a].yellow + " -> OK".cyan);
		}
	}

})();
<commit_msg>remove statusCode console.log<commit_after>#!/usr/bin/env node
'use strict'

var co = require('co');

co(function* () {

	var	request = require('co-request'),
		pkg = require('./package.json'),
		colors = require('colors'),
		argv = process.argv.slice(2),
		params = {};

	if(argv.indexOf("--help") !== -1){
		console.log([
		'',
		pkg.description,
		'Example:',
		'broken-links -s http://kuesty.com -404 http://kuesty.com/error/404'
		].join("\n"));
		return;
	}

	for(var i=0; i<argv.length;i+=2){
		params[argv[i]] = argv[i+1];
	}
	if(params["-s"] == undefined) {
		console.log("You must provide the site name".red);
		return;
	}
	if(params["-404"] == undefined) {
		console.log("You must provide your 404 page to compare".red);
		return;
	}

	var base_uri = params["-s"];
			base_uri = base_uri.indexOf("http") === -1 ? "http://"+base_uri : base_uri;

	var uri = params["-404"];
			uri = uri.indexOf("http") === -1 ? "http://"+uri : uri;

	console.log("Getting 404 source: ".white+ params["-404"].yellow);
	var result = yield request(uri);
	var body404 = result.body;
			body404 = body404.replace(/\s+/g,"");

	console.log("Getting page source: ".white+params["-s"].yellow);
	var result = yield request(base_uri);
	var response = result.body;

	console.log("Getting page links".white);
	var allLinks = response.match(/href="[a-zA-Z\:\/\.\-0-9\@\#\&\;]+/g);
	var links = {};

	var relative_uri = base_uri.match(/https?:\/\/[a-zA-Z\.\-0-9]+/)[0];

	for(var i=0;i<allLinks.length;i++) {
		var a = allLinks[i].replace(/href="/,"");
		if(a.indexOf(".css") !== -1) continue;
		if(a.indexOf(".ico") !== -1) continue;
		if(a.indexOf("#") == 0) continue;
		if(a == "/") continue;
		if(a.match(/https?:/)) continue;
		if(links[a] != undefined) continue;

		links[a] = relative_uri + a;
		var result = yield request(links[a]);
		if(result.statusCode == 404) {
			console.log("|_ "+links[a].yellow + " -> BROKEN".red);
			continue;
		}
		var body = result.body;
		    body = body.replace(/\s+/g,"");

		if(body == body404){
			console.log("|_ "+links[a].yellow + " -> BROKEN".red);
		}else{
			console.log("|_ " +links[a].yellow + " -> OK".cyan);
		}
	}

})();
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var css = require('dom-css')
var marked = require('marked')
var camelcase = require('camelcase')
var isobject = require('lodash.isobject')
var foreach = require('lodash.foreach')
var insertcss = require('insert-css')

module.exports = function (opts) {
  if (!opts.contents) throw new Error('contents option is required')
  if (!opts.markdown) throw new Error('markdown option is required')

  var contents = opts.contents
  var documents = opts.markdown
  var logo = opts.logo
  var styles = opts.styles
  var initial = opts.initial
  var title = opts.title
  var node = opts.node || document.body

  if (!title) {
    console.log(process.cwd())
    title = process.cwd().split('/')
    title = title[title.length - 1]
  }

  marked.setOptions({
    highlight: function (code) {
      return require('highlight.js').highlightAuto(code).value
    }
  })

  var parsed = {}
  foreach(documents, function (value, key) {
    parsed[key] = marked(value)
  })

  var lookup = {}
  var first
  function iterate (data) {
    foreach(data, function (value, key) {
      if (isobject(data[key])) iterate(value)
      else {
        if (!first) first = key
        lookup[key] = value
      }
    })
  }

  iterate(contents)

  var container = document.createElement('div')
  container.className = 'minidocs'
  node.appendChild(container)
  css(node, {margin: '0px', padding: '0px'})
  css(container, {width: '90%', marginLeft: '5%', marginRight: '5%'})

  if (styles) insertcss(styles)

  var basecss = fs.readFileSync(path.join(__dirname, './components/styles/base.css'))
  var fontcss = fs.readFileSync(path.join(__dirname, './components/styles/fonts.css'))
  var githubcss = fs.readFileSync(path.join(__dirname, './components/styles/github-markdown.css'))
  var highlightcss = fs.readFileSync(path.join(__dirname, './components/styles/highlighting/tomorrow.css'))
  insertcss(basecss)
  insertcss(fontcss)
  insertcss(githubcss)
  insertcss(highlightcss)

  require('./components/header')(container, logo, title)
  var sidebar = require('./components/sidebar')(container, contents)
  var main = require('./components/main')(container)

  sidebar.on('selected', function (key) {
    var name = lookup[key]
    var fileid = camelcase(name.replace('.md', ''))
    main.show(parsed[fileid])
  })

  if (initial) sidebar.select(initial)
  else sidebar.select(first)
}
<commit_msg>use empty title if not defined in modoule<commit_after>var fs = require('fs')
var path = require('path')
var css = require('dom-css')
var marked = require('marked')
var camelcase = require('camelcase')
var isobject = require('lodash.isobject')
var foreach = require('lodash.foreach')
var insertcss = require('insert-css')

module.exports = function (opts) {
  if (!opts.contents) throw new Error('contents option is required')
  if (!opts.markdown) throw new Error('markdown option is required')

  var contents = opts.contents
  var documents = opts.markdown
  var logo = opts.logo
  var styles = opts.styles
  var initial = opts.initial
  var title = opts.title || ''
  var node = opts.node || document.body

  marked.setOptions({
    highlight: function (code) {
      return require('highlight.js').highlightAuto(code).value
    }
  })

  var parsed = {}
  foreach(documents, function (value, key) {
    parsed[key] = marked(value)
  })

  var lookup = {}
  var first
  function iterate (data) {
    foreach(data, function (value, key) {
      if (isobject(data[key])) iterate(value)
      else {
        if (!first) first = key
        lookup[key] = value
      }
    })
  }

  iterate(contents)

  var container = document.createElement('div')
  container.className = 'minidocs'
  node.appendChild(container)
  css(node, {margin: '0px', padding: '0px'})
  css(container, {width: '90%', marginLeft: '5%', marginRight: '5%'})

  if (styles) insertcss(styles)

  var basecss = fs.readFileSync(path.join(__dirname, './components/styles/base.css'))
  var fontcss = fs.readFileSync(path.join(__dirname, './components/styles/fonts.css'))
  var githubcss = fs.readFileSync(path.join(__dirname, './components/styles/github-markdown.css'))
  var highlightcss = fs.readFileSync(path.join(__dirname, './components/styles/highlighting/tomorrow.css'))
  insertcss(basecss)
  insertcss(fontcss)
  insertcss(githubcss)
  insertcss(highlightcss)

  require('./components/header')(container, logo, title)
  var sidebar = require('./components/sidebar')(container, contents)
  var main = require('./components/main')(container)

  sidebar.on('selected', function (key) {
    var name = lookup[key]
    var fileid = camelcase(name.replace('.md', ''))
    main.show(parsed[fileid])
  })

  if (initial) sidebar.select(initial)
  else sidebar.select(first)
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var https = require('https');
var http = require('http');
var config = require('./config');

module.exports = function(options) {
	var interval = options.interval || config.options.interval;
}<commit_msg>Including default initial values<commit_after>var _ = require('lodash');
var https = require('https');
var http = require('http');
var config = require('./config');

module.exports = function(options) {
	var interval = options.interval || config.options.interval;
	var url = options.url;
	var onData = options.onData || _.noop();
	var onEnd = options.onEnd || _.noop();
	var onError = options.onError || _.noop();
}<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const parseArgs = require('minimist');

module.exports = {
  name: require('./package').name,

  /**
   * NOTE: dotenv needs to be invoked before the app config is materialized
   * so that the process.env's are set appropriately.  Previously this was done
   * within the `config` hook.  As of 2.15.x, that is too late in the process
   * and needed to be moved into `init`.
   */
  init() {
    this._super.init && this._super.init.apply(this, arguments);

    let root = this.project.root;
    let configFactory = path.join(root, 'config', 'dotenv.js');
    let options = {
      path: path.join(root, '.env'),
      clientAllowedKeys: [],
      failOnMissingKey: false,
    };

    if (fs.existsSync(configFactory)) {
      this._config = Object.assign(options, require(configFactory)(this._resolveEnvironment()));
    }

    let loadedConfig = dotenv.config({path: options.path});
    this._envConfig = loadedConfig.parsed;

    // It might happen that environment config is missing or corrupted
    if (loadedConfig.error) {
      let loadingErrMsg = `[ember-cli-dotenv]: ${loadedConfig.error.message}`;
      if (options.failOnMissingKey) {
        throw new Error(loadingErrMsg);
      } else {
        console.warn(loadingErrMsg); // eslint-disable-line no-console
      }
    }
  },

  _resolveEnvironment() {
    if (process.env.EMBER_ENV) {
      return process.env.EMBER_ENV;
    }

    let args = parseArgs(process.argv);
    let env = args.e || args.env || args.environment;

    // Is it "ember b -prod" command?
    if (!env && process.argv.indexOf('-prod') > -1) {
      env = 'production'
    }

    // Is it "ember test" or "ember t" command without explicit env specified?
    if (!env && (process.argv.indexOf('test') > -1 || process.argv.indexOf('t') > -1)) {
      env = 'test'
    }

    return env || 'development';
  },

  config() {
    let allowedKeys = this._config.clientAllowedKeys || [];

    return this._pickConfigKeys(allowedKeys);
  },

  /**
   * Reset values listed in `clientAllowedKeys` to null and
   * add values from `fastbootAllowedKeys` to FastBoot manifest in package.json.
   *
   * Users may list in same keys both in `clientAllowedKeys` and
   * `fastbootAllowedKeys`
   *
   * @returns {Object}
   */
  fastbootConfigTree() {
    let allowedKeys = this._config.fastbootAllowedKeys || [];

    // `fastbootConfigTree` expects key name as app/engine name
    return {
      [this.app.name]: this._pickConfigKeys(allowedKeys)
    };
  },

  _pickConfigKeys(keys) {
    let envConfig = this._envConfig || {};

    return keys.reduce((accumulator, key) => {
      if (envConfig[key] === undefined) {
        let errMsg = '[ember-cli-dotenv]: Required environment variable \'' + key + '\' is missing.';
        if (this._config.failOnMissingKey) {
          throw new Error(errMsg);
        } else {
          this.ui.writeWarnLine(errMsg);
        }
      }

      accumulator[key] = envConfig[key];

      return accumulator;
    }, {});
  }
};
<commit_msg>Fix addon installation<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const parseArgs = require('minimist');

module.exports = {
  name: require('./package').name,

  /**
   * NOTE: dotenv needs to be invoked before the app config is materialized
   * so that the process.env's are set appropriately.  Previously this was done
   * within the `config` hook.  As of 2.15.x, that is too late in the process
   * and needed to be moved into `init`.
   */
  init() {
    this._super.init && this._super.init.apply(this, arguments);

    let root = this.project.root;
    let configFactory = path.join(root, 'config', 'dotenv.js');
    let options = {
      path: path.join(root, '.env'),
      clientAllowedKeys: [],
      failOnMissingKey: false,
    };

    if (fs.existsSync(configFactory)) {
      this._config = Object.assign(options, require(configFactory)(this._resolveEnvironment()));
    } else {
      this._config = {};
    }

    let loadedConfig = dotenv.config({path: options.path});
    this._envConfig = loadedConfig.parsed;

    // It might happen that environment config is missing or corrupted
    if (loadedConfig.error) {
      let loadingErrMsg = `[ember-cli-dotenv]: ${loadedConfig.error.message}`;
      if (options.failOnMissingKey) {
        throw new Error(loadingErrMsg);
      } else {
        console.warn(loadingErrMsg); // eslint-disable-line no-console
      }
    }
  },

  _resolveEnvironment() {
    if (process.env.EMBER_ENV) {
      return process.env.EMBER_ENV;
    }

    let args = parseArgs(process.argv);
    let env = args.e || args.env || args.environment;

    // Is it "ember b -prod" command?
    if (!env && process.argv.indexOf('-prod') > -1) {
      env = 'production'
    }

    // Is it "ember test" or "ember t" command without explicit env specified?
    if (!env && (process.argv.indexOf('test') > -1 || process.argv.indexOf('t') > -1)) {
      env = 'test'
    }

    return env || 'development';
  },

  config() {
    let allowedKeys = this._config.clientAllowedKeys || [];

    return this._pickConfigKeys(allowedKeys);
  },

  /**
   * Reset values listed in `clientAllowedKeys` to null and
   * add values from `fastbootAllowedKeys` to FastBoot manifest in package.json.
   *
   * Users may list in same keys both in `clientAllowedKeys` and
   * `fastbootAllowedKeys`
   *
   * @returns {Object}
   */
  fastbootConfigTree() {
    let allowedKeys = this._config.fastbootAllowedKeys || [];

    // `fastbootConfigTree` expects key name as app/engine name
    return {
      [this.app.name]: this._pickConfigKeys(allowedKeys)
    };
  },

  _pickConfigKeys(keys) {
    let envConfig = this._envConfig || {};

    return keys.reduce((accumulator, key) => {
      if (envConfig[key] === undefined) {
        let errMsg = '[ember-cli-dotenv]: Required environment variable \'' + key + '\' is missing.';
        if (this._config.failOnMissingKey) {
          throw new Error(errMsg);
        } else {
          this.ui.writeWarnLine(errMsg);
        }
      }

      accumulator[key] = envConfig[key];

      return accumulator;
    }, {});
  }
};
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var path = require('path');

module.exports = {
  name: 'ember-solr',

  config: function(environment, appConfig) {
    if (!appConfig.solrBaseURL || appConfig.solrBaseURL.indexOf(':') === -1) {
      return;
    }

    var solrSchemeAndHost = appConfig.solrBaseURL;
    var solrHostEnd = solrSchemeAndHost.indexOf('/', solrSchemeAndHost.indexOf('://') + 3);
    if (solrHostEnd > 0) {
      solrSchemeAndHost = solrSchemeAndHost.substring(0, solrHostEnd);
    }

    var ENV = {
      contentSecurityPolicy: {
        'script-src': "'self' " + solrSchemeAndHost
      }
    }

    return ENV;
  },

  included: function json_bignum_included(app) {
    this._super.included(app);

    app.import(path.join(app.bowerDirectory, 'json-bignum', 'lib', 'json-bignum.js'));
  }
};
<commit_msg>Include solrBaseURL in 'connect-src' content security policy too.<commit_after>/* jshint node: true */
'use strict';

var path = require('path');

module.exports = {
  name: 'ember-solr',

  _appendPolicy: function(csp, key, value) {
    var v = csp[key] || '';
    if (v) {
      v += ' ';
    }
    csp[key] = v + value;
  },

  config: function(environment, appConfig) {
    if (!appConfig.solrBaseURL || appConfig.solrBaseURL.indexOf(':') === -1) {
      return;
    }

    var solrSchemeAndHost = appConfig.solrBaseURL;
    var solrHostEnd = solrSchemeAndHost.indexOf('/', solrSchemeAndHost.indexOf('://') + 3);
    if (solrHostEnd > 0) {
      solrSchemeAndHost = solrSchemeAndHost.substring(0, solrHostEnd);
    }

    var csp = appConfig.contentSecurityPolicy || {};

    this._appendPolicy(csp, 'connect-src', solrSchemeAndHost);
    this._appendPolicy(csp, 'script-src', solrSchemeAndHost);

    var ENV = {
      contentSecurityPolicy: csp
    };

    return ENV;
  },

  included: function json_bignum_included(app) {
    this._super.included(app);

    app.import(path.join(app.bowerDirectory, 'json-bignum', 'lib', 'json-bignum.js'));
  }
};
<|endoftext|>


<commit_before>var Botkit = require('botkit')
var Witbot = require('node-wit')

var token = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN

var controller = Botkit .slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}<commit_msg>Added wit console.log test<commit_after>var Botkit = require('botkit')
var Witbot = require('node-wit')

var token = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN

var controller = Botkit .slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

wit.captureTextIntent(witToken, "hello", function (err, res) {
    console.log("Response from Wit for text input: ");
    if (err) console.log("Error: ", err);
    console.log(JSON.stringify(res, null, " "));
});<|endoftext|>


<commit_before>'use strict'

const moment =   require('moment')
const esc =      require('ansi-escapes')
const chalk =    require('chalk')
const ui =       require('cli-styles')

const digits = [
	  {unit: 'day',    method: 'day',    length: 2, format: 'ddd', offset: 1}
	, {unit: 'day',    method: 'date',   length: 2, format: 'DD'}
	, {unit: 'month',  method: 'month',  length: 2, format: 'MMM', offset: 1}
	, {unit: 'year',   method: 'year',   length: 4, format: 'YYYY'}
	, {unit: 'hour',   method: 'hour',   length: 2, format: 'HH',  separator: ':'}
	, {unit: 'minute', method: 'minute', length: 2, format: 'mm',  separator: ''}
]

const DatePrompt = {

	  question: null
	, moment:   null   // moment.js object
	, value:    null   // promise

	, cursor:   null   // current index for `digits`

	, stdin:    null   // stdin
	, stdout:   null   // stdout

	// _resolve, _reject

	, cache:    null   // typed be used
	, pressed:  null   // when a number key was pressed the last time
	, done:     false
	, aborted:  false

	, init: function (question, options) {
		options = options || {}
		if ('string' !== typeof question)
			throw new Error('`question` must be a string.')

		this.question = question
		this.moment = options.value ? moment(options.value) : moment()
		const self = this
		this.value = new Promise(function (resolve, reject) {
			self.resolve = resolve
			self.reject =  reject
		})

		if (0 < options.cursor <= (digits.length - 1))
			this.cursor = parseInt(options.cursor)
		else this.cursor = 0

		this.stdin = options.stdin || process.stdin
		this.stdin.setRawMode(true)
		this.stdin.resume()

		this.onKey = DatePrompt.onKey.bind(this)
		this.stdin.on('data', this.onKey)

		this.stdout = options.stdout || process.stdout
		this.stdout.write(esc.cursorHide)

		this.cache = ''
		this.pressed = Date.now()

		this.stdout.write('\n')
		this.render()
		return this
	}

	, reset: function () {
		this.moment = moment()
		this.aborted = this.done = false
		this.render()
	}

	, abort: function () {
		this.reject()
		this.stdin.removeListener('data', this.onKey)
		this.stdin.setRawMode(false)
		this.stdin.pause()
		this.aborted = this.done = true
		this.render()
	}

	, submit: function () {
		this.resolve(this.moment)

		this.stdin.removeListener('data', this.onKey)
		this.stdin.setRawMode(false)
		this.stdin.pause()

		this.done = true
		this.render()
	}

	, onKey: function (key) {
		key = key.toString('utf8')
		const code = key.charCodeAt(0)

		if(/\x1b\[+[A-Z]/.test(key)) {
			key = key.charAt(key.length - 1)
			if (key === 'A')	return this.up()
			if (key === 'B')	return this.down()
			if (key === 'C')	return this.right()
			if (key === 'D')	return this.left()
			if (key === 'F')	return this.first()
			if (key === 'H')	return this.pressed()
		}

		// see https://en.wikipedia.org/wiki/GNU_Readline#Keyboard_shortcuts
		if (code === 1)			return this.first(); // ctrl + A
		if (code === 3)			return this.abort(); // ctrl + C
		if (code === 4)			return process.exit(); // ctrl + D
		if (code === 5)			return this.last(); // ctrl + E
		if (code === 7)			return this.reset(); // ctrl + G
		if (code === 9)			return this.right(); // ctrl + I / tab
		if (code === 10)		return this.submit(); // ctrl + J
		if (code === 13)		return this.submit(); // return
		if (code === 27)		return this.abort(); // escape
		if (code === 8747)		return this.left(); // alt + B
		if (code === 402)		return this.right(); // alt + F

		if (/[0-9]/.test(key))	return this.onNumber(parseInt(key)); // number key
	}

	, onNumber: function (n) {
		let now = Date.now()
		if ((now - this.pressed) > 1000) this.cache = '' + n; // 1s elapsed
		else {
			this.cache += n
			if (this.cache.length >= digits[this.cursor].length) { // got all digits
				let v = this.cache - (digits[this.cursor].offset || 0)
				this.moment[digits[this.cursor].method](v)
				this.cache = ''
				if (this.cursor < digits.length - 1) this.cursor++
			}
		}
		this.pressed = now
		this.render()
	}

	// arrow key handling

	, first: function () {
		if (this.cursor !== 0) this.cache = ''
		this.cursor = 0
		this.render()
	}
	, last: function () {
		if (this.cursor !== digits.length - 1) this.cache = ''
		this.cursor = digits.length - 1
		this.render()
	}

	, left: function () {
		if (this.cursor > 0) {
			this.cursor--
			this.cache = ''
		} else this.stdout.write(esc.beep)
		this.render()
	}
	, right: function () {
		if (this.cursor < digits.length - 1) {
			this.cursor++
			this.cache = ''
		} else this.stdout.write(esc.beep)
		this.render()
	}

	, up: function () {
		this.moment.add(1, digits[this.cursor].unit)
		this.cache = ''
		this.render()
	}
	, down: function () {
		this.moment.subtract(1, digits[this.cursor].unit)
		this.cache = ''
		this.render()
	}

	, renderDigits: function (moment, cursor, done) {
		let str = ''
		for (let i = 0; i < digits.length; i++) {
			let digit = digits[i]
			if (!done && i === cursor)
				str += chalk.cyan.underline(moment.format(digit.format))
			else str += moment.format(digit.format)
			str += digit.separator || ' '
		}
		return str
	}

	, render: function () {
		this.stdout.write(
		  esc.cursorDown(1)
		+ esc.eraseLines(2)
		+ [
			ui.symbol(this.done, this.aborted),
			chalk.bold(this.question),
			ui.delimiter,
			this.renderDigits(this.moment, this.cursor, this.done)
		].join(' ') + '\n')
	}

}

const create = (question, options) =>
	Object.create(DatePrompt).init(question, options).value

module.exports = Object.assign(create, {DatePrompt})
<commit_msg>hardcode default stdio<commit_after>'use strict'

const moment =   require('moment')
const esc =      require('ansi-escapes')
const chalk =    require('chalk')
const ui =       require('cli-styles')

const digits = [
	  {unit: 'day',    method: 'day',    length: 2, format: 'ddd', offset: 1}
	, {unit: 'day',    method: 'date',   length: 2, format: 'DD'}
	, {unit: 'month',  method: 'month',  length: 2, format: 'MMM', offset: 1}
	, {unit: 'year',   method: 'year',   length: 4, format: 'YYYY'}
	, {unit: 'hour',   method: 'hour',   length: 2, format: 'HH',  separator: ':'}
	, {unit: 'minute', method: 'minute', length: 2, format: 'mm',  separator: ''}
]

const DatePrompt = {

	  question: null
	, moment:   null   // moment.js object
	, value:    null   // promise

	, cursor:   null   // current index for `digits`

	, stdin:    null   // stdin
	, stdout:   null   // stdout

	// _resolve, _reject

	, cache:    null   // typed be used
	, pressed:  null   // when a number key was pressed the last time
	, done:     false
	, aborted:  false

	, init: function (question, options) {
		options = options || {}
		if ('string' !== typeof question)
			throw new Error('`question` must be a string.')

		this.question = question
		this.moment = options.value ? moment(options.value) : moment()
		const self = this
		this.value = new Promise(function (resolve, reject) {
			self.resolve = resolve
			self.reject =  reject
		})

		if (0 < options.cursor <= (digits.length - 1))
			this.cursor = parseInt(options.cursor)
		else this.cursor = 0

		process.stdin.setRawMode(true)
		process.stdin.resume()

		this.onKey = DatePrompt.onKey.bind(this)
		process.stdin.on('data', this.onKey)

		process.stdout.write(esc.cursorHide)

		this.cache = ''
		this.pressed = Date.now()

		process.stdout.write('\n')
		this.render()
		return this
	}

	, reset: function () {
		this.moment = moment()
		this.aborted = this.done = false
		this.render()
	}

	, abort: function () {
		this.reject()
		process.stdin.removeListener('data', this.onKey)
		process.stdin.setRawMode(false)
		process.stdin.pause()
		this.aborted = this.done = true
		this.render()
	}

	, submit: function () {
		this.resolve(this.moment)

		process.stdin.removeListener('data', this.onKey)
		process.stdin.setRawMode(false)
		process.stdin.pause()

		this.done = true
		this.render()
	}

	, onKey: function (key) {
		key = key.toString('utf8')
		const code = key.charCodeAt(0)

		if(/\x1b\[+[A-Z]/.test(key)) {
			key = key.charAt(key.length - 1)
			if (key === 'A')	return this.up()
			if (key === 'B')	return this.down()
			if (key === 'C')	return this.right()
			if (key === 'D')	return this.left()
			if (key === 'F')	return this.first()
			if (key === 'H')	return this.pressed()
		}

		// see https://en.wikipedia.org/wiki/GNU_Readline#Keyboard_shortcuts
		if (code === 1)			return this.first(); // ctrl + A
		if (code === 3)			return this.abort(); // ctrl + C
		if (code === 4)			return process.exit(); // ctrl + D
		if (code === 5)			return this.last(); // ctrl + E
		if (code === 7)			return this.reset(); // ctrl + G
		if (code === 9)			return this.right(); // ctrl + I / tab
		if (code === 10)		return this.submit(); // ctrl + J
		if (code === 13)		return this.submit(); // return
		if (code === 27)		return this.abort(); // escape
		if (code === 8747)		return this.left(); // alt + B
		if (code === 402)		return this.right(); // alt + F

		if (/[0-9]/.test(key))	return this.onNumber(parseInt(key)); // number key
	}

	, onNumber: function (n) {
		let now = Date.now()
		if ((now - this.pressed) > 1000) this.cache = '' + n; // 1s elapsed
		else {
			this.cache += n
			if (this.cache.length >= digits[this.cursor].length) { // got all digits
				let v = this.cache - (digits[this.cursor].offset || 0)
				this.moment[digits[this.cursor].method](v)
				this.cache = ''
				if (this.cursor < digits.length - 1) this.cursor++
			}
		}
		this.pressed = now
		this.render()
	}

	// arrow key handling

	, first: function () {
		if (this.cursor !== 0) this.cache = ''
		this.cursor = 0
		this.render()
	}
	, last: function () {
		if (this.cursor !== digits.length - 1) this.cache = ''
		this.cursor = digits.length - 1
		this.render()
	}

	, left: function () {
		if (this.cursor > 0) {
			this.cursor--
			this.cache = ''
		} else process.stdout.write(esc.beep)
		this.render()
	}
	, right: function () {
		if (this.cursor < digits.length - 1) {
			this.cursor++
			this.cache = ''
		} else process.stdout.write(esc.beep)
		this.render()
	}

	, up: function () {
		this.moment.add(1, digits[this.cursor].unit)
		this.cache = ''
		this.render()
	}
	, down: function () {
		this.moment.subtract(1, digits[this.cursor].unit)
		this.cache = ''
		this.render()
	}

	, renderDigits: function (moment, cursor, done) {
		let str = ''
		for (let i = 0; i < digits.length; i++) {
			let digit = digits[i]
			if (!done && i === cursor)
				str += chalk.cyan.underline(moment.format(digit.format))
			else str += moment.format(digit.format)
			str += digit.separator || ' '
		}
		return str
	}

	, render: function () {
		process.stdout.write(
		  esc.cursorDown(1)
		+ esc.eraseLines(2)
		+ [
			ui.symbol(this.done, this.aborted),
			chalk.bold(this.question),
			ui.delimiter,
			this.renderDigits(this.moment, this.cursor, this.done)
		].join(' ') + '\n')
	}

}

const create = (question, options) =>
	Object.create(DatePrompt).init(question, options).value

module.exports = Object.assign(create, {DatePrompt})
<|endoftext|>


<commit_before>function describe () {
  return null
}

module.exports = {
  Application: {
    id: 'lacona-phrases:Application',
    describe: describe
  },
  PreferencePane: {
    id: 'lacona-phrases:PreferencePane',
    describe: describe
  },
  RunningApplication: {
    id: 'lacona-phrases:RunningApplication',
    describe: describe
  },
  ContentArea: {
    id: 'lacona-phrases:ContentArea',
    describe: describe
  },
  MountedVolume: {
    id: 'lacona-phrases:MountedVolume',
    describe: describe
  },
  File: {
    id: 'lacona-phrases:File',
    describe: describe
  },
  ContactCard: {
    id: 'lacona-phrases:ContactCard',
    describe: describe
  },
  EmailAddress: {
    id: 'lacona-phrases:EmailAddress',
    describe: describe
  },
  PhoneNumber: {
    id: 'lacona-phrases:PhoneNumber',
    describe: describe
  },
  URL: {
    id: 'lacona-phrases:URL',
    describe: describe
  },
  Integer: {
    id: 'lacona-phrases:Integer',
    describe: describe
  },
  Decimal: {
    id: 'lacona-phrases:Decimal',
    describe: describe
  },
  Ordinal: {
    id: 'lacona-phrases:Ordinal',
    describe: describe
  },
  DigitString: {
    id: 'lacona-phrases:DigitString',
    describe: describe
  },
  String: {
    id: 'lacona-phrases:String',
    describe: describe
  },
  DateTime: {
    id: 'lacona-phrases:DateTime',
    describe: describe
  },
  Date: {
    id: 'lacona-phrases:Date',
    describe: describe
  },
  Time: {
    id: 'lacona-phrases:Time',
    describe: describe
  },
  Range: {
    id: 'lacona-phrases:Range',
    describe: describe
  },
  Day: {
    id: 'lacona-phrases:Day',
    describe: describe
  },
  Duration: {
    id: 'lacona-phrases:Duration',
    describe: describe
  },
  TimeDuration: {
    id: 'lacona-phrases:TimeDuration',
    describe: describe
  },
  DateDuration: {
    id: 'lacona-phrases:DateDuration',
    describe: describe
  },
  Command: {
    id: 'lacona-phrases:Command',
    describe: describe
  },
  BooleanSetting: {
    id: 'lacona-phrases: BooleanSetting',
    describe: describe
  }
}
<commit_msg>Add mapResult to Command<commit_after>function describe () {
  return null
}

module.exports = {
  Application: {
    id: 'lacona-phrases:Application',
    describe: describe
  },
  PreferencePane: {
    id: 'lacona-phrases:PreferencePane',
    describe: describe
  },
  RunningApplication: {
    id: 'lacona-phrases:RunningApplication',
    describe: describe
  },
  ContentArea: {
    id: 'lacona-phrases:ContentArea',
    describe: describe
  },
  MountedVolume: {
    id: 'lacona-phrases:MountedVolume',
    describe: describe
  },
  File: {
    id: 'lacona-phrases:File',
    describe: describe
  },
  ContactCard: {
    id: 'lacona-phrases:ContactCard',
    describe: describe
  },
  EmailAddress: {
    id: 'lacona-phrases:EmailAddress',
    describe: describe
  },
  PhoneNumber: {
    id: 'lacona-phrases:PhoneNumber',
    describe: describe
  },
  URL: {
    id: 'lacona-phrases:URL',
    describe: describe
  },
  Integer: {
    id: 'lacona-phrases:Integer',
    describe: describe
  },
  Decimal: {
    id: 'lacona-phrases:Decimal',
    describe: describe
  },
  Ordinal: {
    id: 'lacona-phrases:Ordinal',
    describe: describe
  },
  DigitString: {
    id: 'lacona-phrases:DigitString',
    describe: describe
  },
  String: {
    id: 'lacona-phrases:String',
    describe: describe
  },
  DateTime: {
    id: 'lacona-phrases:DateTime',
    describe: describe
  },
  Date: {
    id: 'lacona-phrases:Date',
    describe: describe
  },
  Time: {
    id: 'lacona-phrases:Time',
    describe: describe
  },
  Range: {
    id: 'lacona-phrases:Range',
    describe: describe
  },
  Day: {
    id: 'lacona-phrases:Day',
    describe: describe
  },
  Duration: {
    id: 'lacona-phrases:Duration',
    describe: describe
  },
  TimeDuration: {
    id: 'lacona-phrases:TimeDuration',
    describe: describe
  },
  DateDuration: {
    id: 'lacona-phrases:DateDuration',
    describe: describe
  },
  Command: {
    id: 'lacona-phrases:Command',
    describe: describe,
    mapResult: function mapResult (result, element) {
      return {result: result, element: element}
    }
  },
  BooleanSetting: {
    id: 'lacona-phrases: BooleanSetting',
    describe: describe
  }
}
<|endoftext|>