<commit_before>import { basename, dirname, extname, relative, resolve } from 'path';
import { readFile, Promise } from 'sander';
import MagicString from 'magic-string';
import { blank, keys } from './utils/object';
import Module from './Module';
import ExternalModule from './ExternalModule';
import finalisers from './finalisers/index';
import makeLegalIdentifier from './utils/makeLegalIdentifier';
import ensureArray from './utils/ensureArray';
import { defaultResolver, defaultExternalResolver } from './utils/resolvePath';
import { defaultLoader } from './utils/load';

function badExports ( option, keys ) {
	throw new Error( `'${option}' was specified for options.exports, but entry module has following exports: ${keys.join(', ')}` );
}

export default class Bundle {
	constructor ( options ) {
		this.entryPath = resolve( options.entry ).replace( /\.js$/, '' ) + '.js';
		this.base = dirname( this.entryPath );

		this.resolvePath = options.resolvePath || defaultResolver;
		this.load = options.load || defaultLoader;

		this.resolvePathOptions = {
			external: ensureArray( options.external ),
			resolveExternal: options.resolveExternal || defaultExternalResolver
		};

		this.loadOptions = {
			transform: ensureArray( options.transform )
		};

		this.entryModule = null;

		this.varExports = blank();
		this.toExport = null;

		this.modulePromises = blank();
		this.statements = [];
		this.externalModules = [];
		this.internalNamespaceModules = [];
	}

	fetchModule ( importee, importer ) {
		return Promise.resolve( importer === null ? importee : this.resolvePath( importee, importer, this.resolvePathOptions ) )
			.then( path => {
				if ( !path ) {
					// external module
					if ( !this.modulePromises[ importee ] ) {
						const module = new ExternalModule( importee );
						this.externalModules.push( module );
						this.modulePromises[ importee ] = Promise.resolve( module );
					}

					return this.modulePromises[ importee ];
				}

				if ( !this.modulePromises[ path ] ) {
					this.modulePromises[ path ] = Promise.resolve( this.load( path, this.loadOptions ) )
						.then( source => {
							const module = new Module({
								path,
								source,
								bundle: this
							});

							return module;
						});
				}

				return this.modulePromises[ path ];
			});
	}

	build () {
		// bring in top-level AST nodes from the entry module
		return this.fetchModule( this.entryPath, null )
			.then( entryModule => {
				this.entryModule = entryModule;

				if ( entryModule.exports.default ) {
					let defaultExportName = makeLegalIdentifier( basename( this.entryPath ).slice( 0, -extname( this.entryPath ).length ) );

					let topLevelNames = [];
					entryModule.statements.forEach( statement => {
						keys( statement.defines ).forEach( name => topLevelNames.push( name ) );
					});

					while ( ~topLevelNames.indexOf( defaultExportName ) ) {
						defaultExportName = `_${defaultExportName}`;
					}

					entryModule.suggestName( 'default', defaultExportName );
				}

				return entryModule.expandAllStatements( true );
			})
			.then( statements => {
				this.statements = statements;
				this.deconflict();
			});
	}

	deconflict () {
		let definers = blank();
		let conflicts = blank();

		// Discover conflicts (i.e. two statements in separate modules both define `foo`)
		this.statements.forEach( statement => {
			const module = statement.module;
			const names = keys( statement.defines );

			// with default exports that are expressions (`export default 42`),
			// we need to ensure that the name chosen for the expression does
			// not conflict
			if ( statement.node.type === 'ExportDefaultDeclaration' ) {
				const name = module.getCanonicalName( 'default' );

				const isProxy = statement.node.declaration && statement.node.declaration.type === 'Identifier';
				const shouldDeconflict = !isProxy || ( module.getCanonicalName( statement.node.declaration.name ) !== name );

				if ( shouldDeconflict && !~names.indexOf( name ) ) {
					names.push( name );
				}
			}

			names.forEach( name => {
				if ( definers[ name ] ) {
					conflicts[ name ] = true;
				} else {
					definers[ name ] = [];
				}

				// TODO in good js, there shouldn't be duplicate definitions
				// per module... but some people write bad js
				definers[ name ].push( module );
			});
		});

		// Assign names to external modules
		this.externalModules.forEach( module => {
			// TODO is this right?
			let name = makeLegalIdentifier( module.suggestedNames['*'] || module.suggestedNames.default || module.id );

			if ( definers[ name ] ) {
				conflicts[ name ] = true;
			} else {
				definers[ name ] = [];
			}

			definers[ name ].push( module );
			module.name = name;
		});

		// Rename conflicting identifiers so they can live in the same scope
		keys( conflicts ).forEach( name => {
			const modules = definers[ name ];

			modules.pop(); // the module closest to the entryModule gets away with keeping things as they are

			modules.forEach( module => {
				const replacement = getSafeName( name );
				module.rename( name, replacement );
			});
		});

		function getSafeName ( name ) {
			while ( conflicts[ name ] ) {
				name = `_${name}`;
			}

			conflicts[ name ] = true;
			return name;
		}
	}

	generate ( options = {} ) {
		let magicString = new MagicString.Bundle({ separator: '' });

		// Determine export mode - 'default', 'named', 'none'
		let exportMode = this.getExportMode( options.exports );

		let previousMargin = 0;

		// If we have named exports from the bundle, and those exports
		// are assigned to *within* the bundle, we may need to rewrite e.g.
		//
		//   export let count = 0;
		//   export function incr () { count++ }
		//
		// might become...
		//
		//   exports.count = 0;
		//   function incr () {
		//     exports.count += 1;
		//   }
		//   exports.incr = incr;
		//
		// TODO This doesn't apply if the bundle is exported as ES6!
		let allBundleExports = blank();

		keys( this.entryModule.exports ).forEach( key => {
			const exportDeclaration = this.entryModule.exports[ key ];

			const originalDeclaration = this.entryModule.findDeclaration( exportDeclaration.localName );

			if ( originalDeclaration && originalDeclaration.type === 'VariableDeclaration' ) {
				const canonicalName = this.entryModule.getCanonicalName( exportDeclaration.localName );

				allBundleExports[ canonicalName ] = `exports.${key}`;
				this.varExports[ key ] = true;
			}
		});

		// since we're rewriting variable exports, we want to
		// ensure we don't try and export them again at the bottom
		this.toExport = keys( this.entryModule.exports )
			.filter( key => !this.varExports[ key ] );

		// Apply new names and add to the output bundle
		this.statements.forEach( statement => {
			// skip `export { foo, bar, baz }`
			if ( statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length ) {
				return;
			}

			let replacements = blank();
			let bundleExports = blank();

			keys( statement.dependsOn )
				.concat( keys( statement.defines ) )
				.forEach( name => {
					const canonicalName = statement.module.getCanonicalName( name );

					if ( allBundleExports[ canonicalName ] ) {
						bundleExports[ name ] = replacements[ name ] = allBundleExports[ canonicalName ];
					} else if ( name !== canonicalName ) {
						replacements[ name ] = canonicalName;
					}
				});

			const source = statement.replaceIdentifiers( replacements, bundleExports );

			// modify exports as necessary
			if ( statement.isExportDeclaration ) {
				// remove `export` from `export var foo = 42`
				if ( statement.node.type === 'ExportNamedDeclaration' && statement.node.declaration.type === 'VariableDeclaration' ) {
					source.remove( statement.node.start, statement.node.declaration.start );
				}

				// remove `export` from `export class Foo {...}` or `export default Foo`
				// TODO default exports need different treatment
				else if ( statement.node.declaration.id ) {
					source.remove( statement.node.start, statement.node.declaration.start );
				}

				else if ( statement.node.type === 'ExportDefaultDeclaration' ) {
					const module = statement.module;
					const canonicalName = module.getCanonicalName( 'default' );

					if ( statement.node.declaration.type === 'Identifier' && canonicalName === module.getCanonicalName( statement.node.declaration.name ) ) {
						return;
					}

					source.overwrite( statement.node.start, statement.node.declaration.start, `var ${canonicalName} = ` );
				}

				else {
					throw new Error( 'Unhandled export' );
				}
			}

			// add leading comments
			if ( statement.leadingComments.length ) {
				const commentBlock = statement.leadingComments.map( comment => {
					return comment.block ?
						`/*${comment.text}*/` :
						`//${comment.text}`;
				}).join( '\n' );

				magicString.addSource( new MagicString( commentBlock ) );
			}

			// ensure there is always a newline between statements, and add
			// additional newlines as necessary to reflect original source
			const margin = Math.max( 2, statement.margin[0], previousMargin );
			const newLines = new Array( margin ).join( '\n' );

			// add the statement itself
			magicString.addSource({
				content: source,
				separator: newLines
			});

			// add trailing comments
			const comment = statement.trailingComment;
			if ( comment ) {
				const commentBlock = comment.block ?
					` /*${comment.text}*/` :
					` //${comment.text}`;

				magicString.append( commentBlock );
			}

			previousMargin = statement.margin[1];
		});

		// prepend bundle with internal namespaces
		const indentString = magicString.getIndentString();
		const namespaceBlock = this.internalNamespaceModules.map( module => {
			const exportKeys = keys( module.exports );

			return `var ${module.getCanonicalName('*')} = {\n` +
				exportKeys.map( key => `${indentString}get ${key} () { return ${module.getCanonicalName(key)}; }` ).join( ',\n' ) +
			`\n};\n\n`;
		}).join( '' );

		magicString.prepend( namespaceBlock );

		const finalise = finalisers[ options.format || 'es6' ];

		if ( !finalise ) {
			throw new Error( `You must specify an output type - valid options are ${keys( finalisers ).join( ', ' )}` );
		}

		magicString = finalise( this, magicString.trim(), exportMode, options );

		const code = magicString.toString();
		let map = null;

		if ( options.sourceMap ) {
			map = magicString.generateMap({
				includeContent: true,
				file: options.sourceMapFile || options.dest
				// TODO
			});

			// make sources relative. TODO fix this upstream?
			const dir = dirname( map.file );
			map.sources = map.sources.map( source => {
				return source ? relative( dir, source ) : null
			});
		}

		return { code, map };
	}

	getExportMode ( exportMode ) {
		const exportKeys = keys( this.entryModule.exports );

		if ( exportMode === 'default' ) {
			if ( exportKeys.length !== 1 || exportKeys[0] !== 'default' ) {
				badExports( 'default', exportKeys );
			}
		} else if ( exportMode === 'none' && exportKeys.length ) {
			badExports( 'none', exportKeys );
		}

		if ( !exportMode || exportMode === 'auto' ) {
			if ( exportKeys.length === 0 ) {
				exportMode = 'none';
			} else if ( exportKeys.length === 1 && exportKeys[0] === 'default' ) {
				exportMode = 'default';
			} else {
				exportMode = 'named';
			}
		}

		if ( !/(?:default|named|none)/.test( exportMode ) ) {
			throw new Error( `options.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')` );
		}

		return exportMode;
	}
}
<commit_msg>dont do export rewriting for es6 bundles<commit_after>import { basename, dirname, extname, relative, resolve } from 'path';
import { readFile, Promise } from 'sander';
import MagicString from 'magic-string';
import { blank, keys } from './utils/object';
import Module from './Module';
import ExternalModule from './ExternalModule';
import finalisers from './finalisers/index';
import makeLegalIdentifier from './utils/makeLegalIdentifier';
import ensureArray from './utils/ensureArray';
import { defaultResolver, defaultExternalResolver } from './utils/resolvePath';
import { defaultLoader } from './utils/load';

function badExports ( option, keys ) {
	throw new Error( `'${option}' was specified for options.exports, but entry module has following exports: ${keys.join(', ')}` );
}

export default class Bundle {
	constructor ( options ) {
		this.entryPath = resolve( options.entry ).replace( /\.js$/, '' ) + '.js';
		this.base = dirname( this.entryPath );

		this.resolvePath = options.resolvePath || defaultResolver;
		this.load = options.load || defaultLoader;

		this.resolvePathOptions = {
			external: ensureArray( options.external ),
			resolveExternal: options.resolveExternal || defaultExternalResolver
		};

		this.loadOptions = {
			transform: ensureArray( options.transform )
		};

		this.entryModule = null;

		this.varExports = blank();
		this.toExport = null;

		this.modulePromises = blank();
		this.statements = [];
		this.externalModules = [];
		this.internalNamespaceModules = [];
	}

	fetchModule ( importee, importer ) {
		return Promise.resolve( importer === null ? importee : this.resolvePath( importee, importer, this.resolvePathOptions ) )
			.then( path => {
				if ( !path ) {
					// external module
					if ( !this.modulePromises[ importee ] ) {
						const module = new ExternalModule( importee );
						this.externalModules.push( module );
						this.modulePromises[ importee ] = Promise.resolve( module );
					}

					return this.modulePromises[ importee ];
				}

				if ( !this.modulePromises[ path ] ) {
					this.modulePromises[ path ] = Promise.resolve( this.load( path, this.loadOptions ) )
						.then( source => {
							const module = new Module({
								path,
								source,
								bundle: this
							});

							return module;
						});
				}

				return this.modulePromises[ path ];
			});
	}

	build () {
		// bring in top-level AST nodes from the entry module
		return this.fetchModule( this.entryPath, null )
			.then( entryModule => {
				this.entryModule = entryModule;

				if ( entryModule.exports.default ) {
					let defaultExportName = makeLegalIdentifier( basename( this.entryPath ).slice( 0, -extname( this.entryPath ).length ) );

					let topLevelNames = [];
					entryModule.statements.forEach( statement => {
						keys( statement.defines ).forEach( name => topLevelNames.push( name ) );
					});

					while ( ~topLevelNames.indexOf( defaultExportName ) ) {
						defaultExportName = `_${defaultExportName}`;
					}

					entryModule.suggestName( 'default', defaultExportName );
				}

				return entryModule.expandAllStatements( true );
			})
			.then( statements => {
				this.statements = statements;
				this.deconflict();
			});
	}

	deconflict () {
		let definers = blank();
		let conflicts = blank();

		// Discover conflicts (i.e. two statements in separate modules both define `foo`)
		this.statements.forEach( statement => {
			const module = statement.module;
			const names = keys( statement.defines );

			// with default exports that are expressions (`export default 42`),
			// we need to ensure that the name chosen for the expression does
			// not conflict
			if ( statement.node.type === 'ExportDefaultDeclaration' ) {
				const name = module.getCanonicalName( 'default' );

				const isProxy = statement.node.declaration && statement.node.declaration.type === 'Identifier';
				const shouldDeconflict = !isProxy || ( module.getCanonicalName( statement.node.declaration.name ) !== name );

				if ( shouldDeconflict && !~names.indexOf( name ) ) {
					names.push( name );
				}
			}

			names.forEach( name => {
				if ( definers[ name ] ) {
					conflicts[ name ] = true;
				} else {
					definers[ name ] = [];
				}

				// TODO in good js, there shouldn't be duplicate definitions
				// per module... but some people write bad js
				definers[ name ].push( module );
			});
		});

		// Assign names to external modules
		this.externalModules.forEach( module => {
			// TODO is this right?
			let name = makeLegalIdentifier( module.suggestedNames['*'] || module.suggestedNames.default || module.id );

			if ( definers[ name ] ) {
				conflicts[ name ] = true;
			} else {
				definers[ name ] = [];
			}

			definers[ name ].push( module );
			module.name = name;
		});

		// Rename conflicting identifiers so they can live in the same scope
		keys( conflicts ).forEach( name => {
			const modules = definers[ name ];

			modules.pop(); // the module closest to the entryModule gets away with keeping things as they are

			modules.forEach( module => {
				const replacement = getSafeName( name );
				module.rename( name, replacement );
			});
		});

		function getSafeName ( name ) {
			while ( conflicts[ name ] ) {
				name = `_${name}`;
			}

			conflicts[ name ] = true;
			return name;
		}
	}

	generate ( options = {} ) {
		let magicString = new MagicString.Bundle({ separator: '' });

		// Determine export mode - 'default', 'named', 'none'
		let exportMode = this.getExportMode( options.exports );
		const format = options.format || 'es6';

		let previousMargin = 0;

		// If we have named exports from the bundle, and those exports
		// are assigned to *within* the bundle, we may need to rewrite e.g.
		//
		//   export let count = 0;
		//   export function incr () { count++ }
		//
		// might become...
		//
		//   exports.count = 0;
		//   function incr () {
		//     exports.count += 1;
		//   }
		//   exports.incr = incr;
		//
		// TODO This doesn't apply if the bundle is exported as ES6!
		let allBundleExports = blank();

		if ( format !== 'es6' ) {
			keys( this.entryModule.exports ).forEach( key => {
				const exportDeclaration = this.entryModule.exports[ key ];

				const originalDeclaration = this.entryModule.findDeclaration( exportDeclaration.localName );

				if ( originalDeclaration && originalDeclaration.type === 'VariableDeclaration' ) {
					const canonicalName = this.entryModule.getCanonicalName( exportDeclaration.localName );

					allBundleExports[ canonicalName ] = `exports.${key}`;
					this.varExports[ key ] = true;
				}
			});
		}

		// since we're rewriting variable exports, we want to
		// ensure we don't try and export them again at the bottom
		this.toExport = keys( this.entryModule.exports )
			.filter( key => !this.varExports[ key ] );

		// Apply new names and add to the output bundle
		this.statements.forEach( statement => {
			// skip `export { foo, bar, baz }`
			if ( statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length ) {
				return;
			}

			let replacements = blank();
			let bundleExports = blank();

			keys( statement.dependsOn )
				.concat( keys( statement.defines ) )
				.forEach( name => {
					const canonicalName = statement.module.getCanonicalName( name );

					if ( allBundleExports[ canonicalName ] ) {
						bundleExports[ name ] = replacements[ name ] = allBundleExports[ canonicalName ];
					} else if ( name !== canonicalName ) {
						replacements[ name ] = canonicalName;
					}
				});

			const source = statement.replaceIdentifiers( replacements, bundleExports );

			// modify exports as necessary
			if ( statement.isExportDeclaration ) {
				// remove `export` from `export var foo = 42`
				if ( statement.node.type === 'ExportNamedDeclaration' && statement.node.declaration.type === 'VariableDeclaration' ) {
					source.remove( statement.node.start, statement.node.declaration.start );
				}

				// remove `export` from `export class Foo {...}` or `export default Foo`
				// TODO default exports need different treatment
				else if ( statement.node.declaration.id ) {
					source.remove( statement.node.start, statement.node.declaration.start );
				}

				else if ( statement.node.type === 'ExportDefaultDeclaration' ) {
					const module = statement.module;
					const canonicalName = module.getCanonicalName( 'default' );

					if ( statement.node.declaration.type === 'Identifier' && canonicalName === module.getCanonicalName( statement.node.declaration.name ) ) {
						return;
					}

					source.overwrite( statement.node.start, statement.node.declaration.start, `var ${canonicalName} = ` );
				}

				else {
					throw new Error( 'Unhandled export' );
				}
			}

			// add leading comments
			if ( statement.leadingComments.length ) {
				const commentBlock = statement.leadingComments.map( comment => {
					return comment.block ?
						`/*${comment.text}*/` :
						`//${comment.text}`;
				}).join( '\n' );

				magicString.addSource( new MagicString( commentBlock ) );
			}

			// ensure there is always a newline between statements, and add
			// additional newlines as necessary to reflect original source
			const margin = Math.max( 2, statement.margin[0], previousMargin );
			const newLines = new Array( margin ).join( '\n' );

			// add the statement itself
			magicString.addSource({
				content: source,
				separator: newLines
			});

			// add trailing comments
			const comment = statement.trailingComment;
			if ( comment ) {
				const commentBlock = comment.block ?
					` /*${comment.text}*/` :
					` //${comment.text}`;

				magicString.append( commentBlock );
			}

			previousMargin = statement.margin[1];
		});

		// prepend bundle with internal namespaces
		const indentString = magicString.getIndentString();
		const namespaceBlock = this.internalNamespaceModules.map( module => {
			const exportKeys = keys( module.exports );

			return `var ${module.getCanonicalName('*')} = {\n` +
				exportKeys.map( key => `${indentString}get ${key} () { return ${module.getCanonicalName(key)}; }` ).join( ',\n' ) +
			`\n};\n\n`;
		}).join( '' );

		magicString.prepend( namespaceBlock );

		const finalise = finalisers[ format ];

		if ( !finalise ) {
			throw new Error( `You must specify an output type - valid options are ${keys( finalisers ).join( ', ' )}` );
		}

		magicString = finalise( this, magicString.trim(), exportMode, options );

		const code = magicString.toString();
		let map = null;

		if ( options.sourceMap ) {
			map = magicString.generateMap({
				includeContent: true,
				file: options.sourceMapFile || options.dest
				// TODO
			});

			// make sources relative. TODO fix this upstream?
			const dir = dirname( map.file );
			map.sources = map.sources.map( source => {
				return source ? relative( dir, source ) : null
			});
		}

		return { code, map };
	}

	getExportMode ( exportMode ) {
		const exportKeys = keys( this.entryModule.exports );

		if ( exportMode === 'default' ) {
			if ( exportKeys.length !== 1 || exportKeys[0] !== 'default' ) {
				badExports( 'default', exportKeys );
			}
		} else if ( exportMode === 'none' && exportKeys.length ) {
			badExports( 'none', exportKeys );
		}

		if ( !exportMode || exportMode === 'auto' ) {
			if ( exportKeys.length === 0 ) {
				exportMode = 'none';
			} else if ( exportKeys.length === 1 && exportKeys[0] === 'default' ) {
				exportMode = 'default';
			} else {
				exportMode = 'named';
			}
		}

		if ( !/(?:default|named|none)/.test( exportMode ) ) {
			throw new Error( `options.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')` );
		}

		return exportMode;
	}
}
<|endoftext|>


<commit_before>/*jslint browser:true */
var message = document.getElementById("message");
var messages = document.getElementById("messages");
var formid = document.getElementById("formid");
var textarea = document.getElementById("textarea");

function getResponse(query) {
    $.ajax({
        dataType: "jsonp",
        type: "GET",
        url: "https://api.susi.ai/susi/chat.json?timezoneOffset=-300&q=" + query,
        success: function (data) {
            var recQuery = data["answers"][0]["data"][0]["query"];
            if (query !== recQuery) {
                return getResponse(query);
            }
            var link = data["answers"][0]["data"][0]["link"];
            var image = data["answers"][0]["data"][0]["image"];
            var answer = data["answers"][0]["data"][0]["answer"];
            loading(false);
            var newDiv = messages.childNodes[messages.childElementCount];
            var newP = document.createElement("p");
            newP.appendChild(document.createTextNode(answer));
            newDiv.appendChild(newP);
            if (link) {
                var newA = document.createElement("a");
                newA.appendChild(document.createTextNode(link));
                newA.setAttribute("href", link);
                newA.setAttribute("target", "_blank");
                newDiv.appendChild(document.createElement("br"));
                newDiv.appendChild(newA);
            }
            if (image) {
                var newImg = document.createElement("img");
                newDiv.appendChild(document.createElement("br"));
                newImg.setAttribute("src", image);
                newImg.setAttribute("class", "susi-img");
                newDiv.appendChild(newImg);
            }
            newDiv.setAttribute("class", "susinewmessage");
            messages.appendChild(newDiv);
            messages.scrollTop = messages.scrollHeight;
        }
    });
}

function loading(condition=true){
    if(condition == true){
        var newDiv = document.createElement('div');
        var newImg = document.createElement('img');
        newImg.setAttribute("src","loading.gif");
        newImg.setAttribute("style","height:10px;width:auto");
        newDiv.appendChild(newImg);
        newDiv.setAttribute("class","susinewmessage");
        messages.appendChild(newDiv);
        messages.scrollTop = messages.scrollHeight;
    }
    else{
        messages.childNodes[messages.childElementCount].innerHTML = "";
    }
}

function submitForm() {
    var text = textarea.value;
    text = text.trim();
    if (text === "") {
        return console.log("Empty Query!");
    }
    var newP = document.createElement("p");
    var newDiv = document.createElement("div");
    newDiv.setAttribute("class", "mynewmessage");
    var myTextNode = document.createTextNode(text);
    newP.appendChild(myTextNode);
    newDiv.appendChild(newP);
    messages.appendChild(newDiv);
    textarea.value = "";
    loading();
    getResponse(text);
    messages.scrollTop = messages.scrollHeight;
}

textarea.onkeyup = function (e) {
    if (e.which === 13 && !e.shiftKey) {
        e.preventDefault();
        submitForm();
    }
};

formid.addEventListener("submit", function (e) {
    e.preventDefault();
    submitForm();
});

<commit_msg>Added checks for request error<commit_after>/*jslint browser:true */
var message = document.getElementById("message");
var messages = document.getElementById("messages");
var formid = document.getElementById("formid");
var textarea = document.getElementById("textarea");

function getResponse(query) {
    $.ajax({
        dataType: "jsonp",
        type: "GET",
        url: "https://api.susi.ai/susi/chat.json?timezoneOffset=-300&q=" + query,
        error: function(xhr,textStatus,errorThrown) {
            var newP = document.createElement("p");
            var newDiv = messages.childNodes[messages.childElementCount];
            loading(false);
            newDiv.setAttribute("class", "susinewmessage");
            var myTextNode = document.createTextNode("Sorry! request could not be made.");
            newP.appendChild(myTextNode);
            newDiv.appendChild(newP);
            messages.appendChild(newDiv);
        },
        success: function (data) {
            var recQuery = data["answers"][0]["data"][0]["query"];
            if (query !== recQuery) {
                return getResponse(query);
            }
            var link = data["answers"][0]["data"][0]["link"];
            var image = data["answers"][0]["data"][0]["image"];
            var answer = data["answers"][0]["data"][0]["answer"];
            loading(false);
            var newDiv = messages.childNodes[messages.childElementCount];
            var newP = document.createElement("p");
            newP.appendChild(document.createTextNode(answer));
            newDiv.appendChild(newP);
            if (link) {
                var newA = document.createElement("a");
                newA.appendChild(document.createTextNode(link));
                newA.setAttribute("href", link);
                newA.setAttribute("target", "_blank");
                newDiv.appendChild(document.createElement("br"));
                newDiv.appendChild(newA);
            }
            if (image) {
                var newImg = document.createElement("img");
                newDiv.appendChild(document.createElement("br"));
                newImg.setAttribute("src", image);
                newImg.setAttribute("class", "susi-img");
                newDiv.appendChild(newImg);
            }
            newDiv.setAttribute("class", "susinewmessage");
            messages.appendChild(newDiv);
            messages.scrollTop = messages.scrollHeight;
        }
    });
}

function loading(condition=true){
    if(condition == true){
        var newDiv = document.createElement('div');
        var newImg = document.createElement('img');
        newImg.setAttribute("src","loading.gif");
        newImg.setAttribute("style","height:10px;width:auto");
        newDiv.appendChild(newImg);
        newDiv.setAttribute("class","susinewmessage");
        messages.appendChild(newDiv);
        messages.scrollTop = messages.scrollHeight;
    }
    else{
        messages.childNodes[messages.childElementCount].innerHTML = "";
    }
}

function submitForm() {
    var text = textarea.value;
    text = text.trim();
    if (text === "") {
        return console.log("Empty Query!");
    }
    var newP = document.createElement("p");
    var newDiv = document.createElement("div");
    newDiv.setAttribute("class", "mynewmessage");
    var myTextNode = document.createTextNode(text);
    newP.appendChild(myTextNode);
    newDiv.appendChild(newP);
    messages.appendChild(newDiv);
    textarea.value = "";
    loading();
    if(window.navigator.onLine)
        getResponse(text);
    else {
        loading(false);
        var newP = document.createElement("p");
        var newDiv =  messages.childNodes[messages.childElementCount];
        newDiv.setAttribute("class", "susinewmessage");
        var myTextNode = document.createTextNode("Not connected to Internet!");
        newP.appendChild(myTextNode);
        newDiv.appendChild(newP);
        messages.appendChild(newDiv);
    }
    messages.scrollTop = messages.scrollHeight;
}

textarea.onkeyup = function (e) {
    if (e.which === 13 && !e.shiftKey) {
        e.preventDefault();
        submitForm();
    }
};

formid.addEventListener("submit", function (e) {
    e.preventDefault();
    submitForm();
});

<|endoftext|>


<commit_before>import runTransitionHook from './runTransitionHook'

function useBasename(createHistory) {
  return function (options={}) {
    let { basename, ...historyOptions } = options
    let history = createHistory(historyOptions)

    function stripBasename(location) {
      if (basename && location.basename == null) {
        if (location.pathname.indexOf(basename) === 0) {
          location.pathname = location.pathname.substring(basename.length)
          location.basename = basename
          if (location.pathname === '') {
            location.pathname = '/';
          }
        } else {
          location.basename = ''
        }
      }

      return location
    }

    function addBasename(path) {
      return basename ? basename + path : path
    }

    // Override all read methods with basename-aware versions.
    function listenBefore(hook) {
      return history.listenBefore(function (location, callback) {
        runTransitionHook(hook, stripBasename(location), callback)
      })
    }

    function listen(listener) {
      return history.listen(function (location) {
        listener(stripBasename(location))
      })
    }

    // Override all write methods with basename-aware versions.
    function pushState(state, path) {
      history.pushState(state, addBasename(path))
    }

    function replaceState(state, path) {
      history.replaceState(state, addBasename(path))
    }

    function createPath(path) {
      return history.createPath(addBasename(path))
    }

    function createHref(path) {
      return history.createHref(addBasename(path))
    }

    return {
      ...history,
      listenBefore,
      listen,
      pushState,
      replaceState,
      createPath,
      createHref
    }
  }
}

export default useBasename
<commit_msg>Fix syntax<commit_after>import runTransitionHook from './runTransitionHook'

function useBasename(createHistory) {
  return function (options={}) {
    let { basename, ...historyOptions } = options
    let history = createHistory(historyOptions)

    function stripBasename(location) {
      if (basename && location.basename == null) {
        if (location.pathname.indexOf(basename) === 0) {
          location.pathname = location.pathname.substring(basename.length)
          location.basename = basename

          if (location.pathname === '')
            location.pathname = '/'
        } else {
          location.basename = ''
        }
      }

      return location
    }

    function addBasename(path) {
      return basename ? basename + path : path
    }

    // Override all read methods with basename-aware versions.
    function listenBefore(hook) {
      return history.listenBefore(function (location, callback) {
        runTransitionHook(hook, stripBasename(location), callback)
      })
    }

    function listen(listener) {
      return history.listen(function (location) {
        listener(stripBasename(location))
      })
    }

    // Override all write methods with basename-aware versions.
    function pushState(state, path) {
      history.pushState(state, addBasename(path))
    }

    function replaceState(state, path) {
      history.replaceState(state, addBasename(path))
    }

    function createPath(path) {
      return history.createPath(addBasename(path))
    }

    function createHref(path) {
      return history.createHref(addBasename(path))
    }

    return {
      ...history,
      listenBefore,
      listen,
      pushState,
      replaceState,
      createPath,
      createHref
    }
  }
}

export default useBasename
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var semver = require('semver');
var EventEmitter = require('events').EventEmitter;
var util = require("util");
var ApplicationError = require('./ApplicationError.js');

// Bundle Context
var BundleContext = function BundleContext(bundle) {
	Object.defineProperty(this, 'bundle', {
		value: bundle,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'identity', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.identity;
		}
	});

	Object.defineProperty(this, 'options', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.options;
		}
	});

	Object.defineProperty(this, 'bundleId', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.bundleId;
		}
	});

	Object.defineProperty(this, 'version', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.version;
		}
	});

	Object.defineProperty(this, 'home', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.home;
		}
	});

	Object.defineProperty(this, 'workspace', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.workspace;
		}
	});

	Object.defineProperty(this, 'bundles', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.application.bundles;
		}
	});
};

BundleContext.prototype = {
	on: function(event, fn) {
		this.bundle.application.on(event, fn);
	},
	off: function(event, fn) {
		this.bundle.application.off(event, fn);
	},
	require: function(bundleId) {
		var caller = this.bundle;

		var bundle = caller.imports[bundleId];
		if( bundle ) {
			if( bundle.type == Bundle.TYPE_SERVICE ) {
				if( bundle.status !== Bundle.STATUS_STARTED ) bundle.start();

				var exports = bundle.exports;

				if( !exports ) return {};

				var result = {};
				for(var key in exports) {
					var o = exports[key];
					if( typeof(o) === 'function' ) {
						result[key] = (function(o) {
							return function() {
								return o.apply(caller, arguments);
							}
						})(o);
					} else {
						result[key] = o;
					}
				}

				return result;
			} else {
				return bundle.exports;
			}
		} else {
			throw new ApplicationError('import bundle [' + bundleId + '] is not defined in bundle [' + caller.bundleId + '-' + caller.version + '] manifest file');
		}

		return null;
	}
};

// Bundle Identity
var BundleIdentity = function BundleIdentity(name) {
	if( !name || typeof(name) !== 'string' ) throw new ApplicationError('invalid bundle identity:' + name);

	var pos = name.lastIndexOf('-');
	var bundleId = name;
	var version;

	if( pos > 0 ) {
		bundleId = name.substring(0, pos);
		version = semver.valid(name.substring(pos + 1));
	}

	if( !bundleId ) throw new ApplicationError('missing:bundleId:' + name);
	if( !version ) throw new ApplicationError('missing:version:' + name);

	Object.defineProperty(this, 'bundleId', {
		value: bundleId,
		enumerable: false,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'version', {
		value: version,
		enumerable: false,
		configurable: false,
		writable: false
	});
};

BundleIdentity.prototype = {
	is: function(match) {
		return semver.satisfies(this.version, match);
	},
	toString: function() {
		return this.bundleId + '(' + this.version + ')';
	}
};

var Bundle = function Bundle(application, dir) {
	var identity = new BundleIdentity(path.basename(dir));

	Object.defineProperty(this, 'application', {
		value: application,
		enumerable: false,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'identity', {
		value: identity,
		enumerable: false,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'bundleId', {
		value: identity.bundleId,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'version', {
		value: identity.version,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'home', {
		value: dir,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'workspace', {
		enumerable: false,
		configurable: false,
		get: function() {
			return application.getBundleWorkspace(this);
		}
	});

	var ee = new EventEmitter();
	Object.defineProperty(this, 'ee', {
		enumerable: false,
		configurable: false,
		get: function() {
			return ee;
		}
	});

	var ctx = new BundleContext(this);
	Object.defineProperty(this, 'ctx', {
		enumerable: false,
		configurable: false,
		get: function() {
			return ctx;
		}
	});

	this.detect();
};

Bundle.STATUS_DETECTED = 'detected';
Bundle.STATUS_STARTED = 'started';
Bundle.STATUS_STARTING = 'starting';
Bundle.STATUS_STOPPED = 'stopped';
Bundle.STATUS_STOPPING = 'stopping';
Bundle.STATUS_ERROR = 'error';
Bundle.TYPE_SERVICE = 'service';
Bundle.TYPE_LIBRARY = 'library';
Bundle.TYPE_INVALID = 'invalid';

Bundle.prototype = {
	path: function(f) {
		return path.join(this.home, f);
	},
	detect: function detect() {
		var manifest_file = path.join(this.home, 'package.json');

		if( fs.existsSync(manifest_file) ) {
			var manifest = fs.readFileSync(manifest_file, 'utf-8');
			if( !manifest )
				throw new ApplicationError('bundle_manifest_error:package_json_not_found:' + this.identity + ':' + manifest_file);

			try {
				manifest = JSON.parse(manifest);
			} catch(err) {
				throw new ApplicationError('bundle_manifest_error:package_json_parse_error:' + this.identity + ':' + manifest_file + ':' + err.message, err);
			}

			if( typeof(manifest.name) !== 'string' ) throw new ApplicationError('bundle_manifest_error:manifest.name(bundleId):' + this.identity.toString(), manifest);
			if( typeof(manifest.version) !== 'string' ) throw new ApplicationError('bundle_manifest_error:manifest.version:' + this.identity.toString(), manifest);
			if( typeof(manifest.activator) !== 'string' ) throw new ApplicationError('bundle_manifest_error:manifest.activator:' + this.identity.toString(), manifest);

			if( manifest.name != this.bundleId ) throw new ApplicationError('bundle_manifest_error:bundleId(name)_does_not_match:' + this.identity.toString(), manifest);
			if( manifest.version != this.version ) throw new ApplicationError('bundle_manifest_error:version_does_not_match:' + this.identity.toString(), manifest);

			var application = this.application;
			var options = this.application.getBundleOptions(this.bundleId, this.version) || {};
			var activator = null;
			var exports = {};
			var imports = manifest.imports || {};

			if( manifest.activator ) {
				activator = require(path.join(this.home, manifest.activator));

				if( typeof(activator) === 'function' ) {
					activator = {start:activator};
				} else if( typeof(activator) === 'object' ) {
					if( typeof(activator.start) !== 'function' ) {
						activator = null;
						console.error('activator.start must be a function', this.identity.toString());
					}

					if( activator.stop && typeof(activator.stop) !== 'function' ) {
						activator.stop = null;
						console.error('activator.stop must be a function', this.identity.toString());
					}
				} else {
					activator = null;
					console.error('activator not found. ignored', this.identity.toString());
				}
			}

			var type = activator ? Bundle.TYPE_SERVICE : Bundle.TYPE_LIBRARY;

			Object.defineProperty(this, 'activator', {
				value: activator,
				enumerable: true,
				configurable: false,
				writable: false
			});

			Object.defineProperty(this, 'manifest', {
				value: manifest,
				enumerable: true,
				configurable: false,
				writable: false
			});

			Object.defineProperty(this, 'options', {
				value: options,
				enumerable: true,
				configurable: false,
				writable: false
			});

			Object.defineProperty(this, 'exports', {
				enumerable: true,
				configurable: false,
				get: function() {
					return exports;
				},
				set: function(o) {
					//if( typeof(o) !== 'object' ) throw new ApplicationError('bundle.exports must be an object');
					exports = o;
				}
			});

			Object.defineProperty(this, 'imports', {
				enumerable: true,
				configurable: true,
				get: function() {
					var result = {};
					for( var k in imports ) {
						if( !imports.hasOwnProperty(k) ) continue;

						var v = imports[k];
						if( typeof(v) === 'string' ) {
							result[k] = application.bundles.get(k, v);
						}
					}
					return result;
				}
			});

			Object.defineProperty(this, 'type', {
				value: type,
				enumerable: true,
				configurable: true,
				writable: false
			});
		} else {
			Object.defineProperty(this, 'type', {
				value: Bundle.TYPE_INVALID,
				enumerable: true,
				configurable: true,
				writable: false
			});

			this.status = Bundle.STATUS_ERROR;
			return;
		}

		this.status = Bundle.STATUS_DETECTED;
	},
	start: function start() {
		if( this.status === Bundle.STATUS_STARTED ) {
			console.warn('cannot_start:already_started:' + this.identity + ':' + this.version);
			return;
		}

		console.log('* starting ' + this.identity + '...');

		var activator = this.activator;
		var result;
		if( activator && typeof(activator.start) === 'function' ) {
			result = activator.start.apply(this, [this.ctx]);

			if( typeof(result) === 'function' ) {
				this.status = Bundle.STATUS_STARTING;
				var self = this;
				result(function(err) {
					if( err ) {
						self.status = Bundle.STATUS_ERROR;
						self.error = err;
						console.error('bundle_start_error:' + this.identity + ':' + err.message, err);
						return;
					}

					self.status = Bundle.STATUS_STARTED;
				});
			} else {
				this.status = Bundle.STATUS_STARTED;
			}
		} else {
			this.status = Bundle.STATUS_STARTED;
		}

		console.log('* started ' + this.identity);

		return result;
	},
	stop: function stop() {
		if( this.status !== Bundle.STATUS_STARTED ) {
			console.warn('cannot_stop:not_started_yet:' + this.identity + ':' + this.status);
			return;
		}

		var activator = this.activator;
		var result;
		if( activator && typeof(activator.stop) === 'function' ) {
			result = activator.stop.apply(this, [this.ctx]);

			if( typeof(result) === 'function' ) {
				var self = this;
				result(function(err) {
					if( err ) {
						self.status = Bundle.STATUS_ERROR;
						self.error = err;
						console.error('bundle_stop_error:' + this.identity + ':' + err.message, err);
						return;
					}

					self.status = Bundle.STATUS_STOPPED;
				});
			} else {
				this.status = Bundle.STATUS_STOPPED;
			}
		} else {
			this.status = Bundle.STATUS_STOPPED;
		}

		return result;
	}
};

module.exports = Bundle;
<commit_msg>fix import plugin start<commit_after>var path = require('path');
var fs = require('fs');
var semver = require('semver');
var EventEmitter = require('events').EventEmitter;
var util = require("util");
var ApplicationError = require('./ApplicationError.js');

// Bundle Context
var BundleContext = function BundleContext(bundle) {
	Object.defineProperty(this, 'bundle', {
		value: bundle,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'identity', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.identity;
		}
	});

	Object.defineProperty(this, 'options', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.options;
		}
	});

	Object.defineProperty(this, 'bundleId', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.bundleId;
		}
	});

	Object.defineProperty(this, 'version', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.version;
		}
	});

	Object.defineProperty(this, 'home', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.home;
		}
	});

	Object.defineProperty(this, 'workspace', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.workspace;
		}
	});

	Object.defineProperty(this, 'bundles', {
		enumerable: true,
		configurable: false,
		get: function() {
			return bundle.application.bundles;
		}
	});
};

BundleContext.prototype = {
	on: function(event, fn) {
		this.bundle.application.on(event, fn);
	},
	off: function(event, fn) {
		this.bundle.application.off(event, fn);
	},
	require: function(bundleId) {
		var caller = this.bundle;

		var bundle = caller.imports[bundleId];
		if( bundle ) {
			if( bundle.type == Bundle.TYPE_SERVICE ) {
				if( bundle.status !== Bundle.STATUS_STARTED ) bundle.start();

				var exports = bundle.exports;

				if( !exports ) return {};

				var result = {};
				for(var key in exports) {
					var o = exports[key];
					if( typeof(o) === 'function' ) {
						result[key] = (function(o) {
							return function() {
								return o.apply(caller, arguments);
							}
						})(o);
					} else {
						result[key] = o;
					}
				}

				return result;
			} else {
				return bundle.exports;
			}
		} else {
			throw new ApplicationError('import bundle [' + bundleId + '] is not defined in bundle [' + caller.bundleId + '-' + caller.version + '] manifest file');
		}

		return null;
	}
};

// Bundle Identity
var BundleIdentity = function BundleIdentity(name) {
	if( !name || typeof(name) !== 'string' ) throw new ApplicationError('invalid bundle identity:' + name);

	var pos = name.lastIndexOf('-');
	var bundleId = name;
	var version;

	if( pos > 0 ) {
		bundleId = name.substring(0, pos);
		version = semver.valid(name.substring(pos + 1));
	}

	if( !bundleId ) throw new ApplicationError('missing:bundleId:' + name);
	if( !version ) throw new ApplicationError('missing:version:' + name);

	Object.defineProperty(this, 'bundleId', {
		value: bundleId,
		enumerable: false,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'version', {
		value: version,
		enumerable: false,
		configurable: false,
		writable: false
	});
};

BundleIdentity.prototype = {
	is: function(match) {
		return semver.satisfies(this.version, match);
	},
	toString: function() {
		return this.bundleId + '(' + this.version + ')';
	}
};

var Bundle = function Bundle(application, dir) {
	var identity = new BundleIdentity(path.basename(dir));

	Object.defineProperty(this, 'application', {
		value: application,
		enumerable: false,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'identity', {
		value: identity,
		enumerable: false,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'bundleId', {
		value: identity.bundleId,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'version', {
		value: identity.version,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'home', {
		value: dir,
		enumerable: true,
		configurable: false,
		writable: false
	});

	Object.defineProperty(this, 'workspace', {
		enumerable: false,
		configurable: false,
		get: function() {
			return application.getBundleWorkspace(this);
		}
	});

	var ee = new EventEmitter();
	Object.defineProperty(this, 'ee', {
		enumerable: false,
		configurable: false,
		get: function() {
			return ee;
		}
	});

	var ctx = new BundleContext(this);
	Object.defineProperty(this, 'ctx', {
		enumerable: false,
		configurable: false,
		get: function() {
			return ctx;
		}
	});

	this.detect();
};

Bundle.STATUS_DETECTED = 'detected';
Bundle.STATUS_STARTED = 'started';
Bundle.STATUS_STARTING = 'starting';
Bundle.STATUS_STOPPED = 'stopped';
Bundle.STATUS_STOPPING = 'stopping';
Bundle.STATUS_ERROR = 'error';
Bundle.TYPE_SERVICE = 'service';
Bundle.TYPE_LIBRARY = 'library';
Bundle.TYPE_INVALID = 'invalid';

Bundle.prototype = {
	path: function(f) {
		return path.join(this.home, f);
	},
	detect: function detect() {
		var manifest_file = path.join(this.home, 'package.json');

		if( fs.existsSync(manifest_file) ) {
			var manifest = fs.readFileSync(manifest_file, 'utf-8');
			if( !manifest )
				throw new ApplicationError('bundle_manifest_error:package_json_not_found:' + this.identity + ':' + manifest_file);

			try {
				manifest = JSON.parse(manifest);
			} catch(err) {
				throw new ApplicationError('bundle_manifest_error:package_json_parse_error:' + this.identity + ':' + manifest_file + ':' + err.message, err);
			}

			if( typeof(manifest.name) !== 'string' ) throw new ApplicationError('bundle_manifest_error:manifest.name(bundleId):' + this.identity.toString(), manifest);
			if( typeof(manifest.version) !== 'string' ) throw new ApplicationError('bundle_manifest_error:manifest.version:' + this.identity.toString(), manifest);
			if( typeof(manifest.activator) !== 'string' ) throw new ApplicationError('bundle_manifest_error:manifest.activator:' + this.identity.toString(), manifest);

			if( manifest.name != this.bundleId ) throw new ApplicationError('bundle_manifest_error:bundleId(name)_does_not_match:' + this.identity.toString(), manifest);
			if( manifest.version != this.version ) throw new ApplicationError('bundle_manifest_error:version_does_not_match:' + this.identity.toString(), manifest);

			var application = this.application;
			var options = this.application.getBundleOptions(this.bundleId, this.version) || {};
			var activator = null;
			var exports = {};
			var imports = manifest.imports || {};

			if( manifest.activator ) {
				activator = require(path.join(this.home, manifest.activator));

				if( typeof(activator) === 'function' ) {
					activator = {start:activator};
				} else if( typeof(activator) === 'object' ) {
					if( typeof(activator.start) !== 'function' ) {
						activator = null;
						console.error('activator.start must be a function', this.identity.toString());
					}

					if( activator.stop && typeof(activator.stop) !== 'function' ) {
						activator.stop = null;
						console.error('activator.stop must be a function', this.identity.toString());
					}
				} else {
					activator = null;
					console.error('activator not found. ignored', this.identity.toString());
				}
			}

			var type = activator ? Bundle.TYPE_SERVICE : Bundle.TYPE_LIBRARY;

			Object.defineProperty(this, 'activator', {
				value: activator,
				enumerable: true,
				configurable: false,
				writable: false
			});

			Object.defineProperty(this, 'manifest', {
				value: manifest,
				enumerable: true,
				configurable: false,
				writable: false
			});

			Object.defineProperty(this, 'options', {
				value: options,
				enumerable: true,
				configurable: false,
				writable: false
			});

			Object.defineProperty(this, 'exports', {
				enumerable: true,
				configurable: false,
				get: function() {
					return exports;
				},
				set: function(o) {
					//if( typeof(o) !== 'object' ) throw new ApplicationError('bundle.exports must be an object');
					exports = o;
				}
			});

			Object.defineProperty(this, 'imports', {
				enumerable: true,
				configurable: true,
				get: function() {
					var result = {};
					for( var k in imports ) {
						if( !imports.hasOwnProperty(k) ) continue;

						var v = imports[k];
						if( typeof(v) === 'string' ) {
							result[k] = application.bundles.get(k, v);
						}
					}
					return result;
				}
			});

			Object.defineProperty(this, 'type', {
				value: type,
				enumerable: true,
				configurable: true,
				writable: false
			});
		} else {
			Object.defineProperty(this, 'type', {
				value: Bundle.TYPE_INVALID,
				enumerable: true,
				configurable: true,
				writable: false
			});

			this.status = Bundle.STATUS_ERROR;
			return;
		}

		this.status = Bundle.STATUS_DETECTED;
	},
	start: function start() {
		if( this.status === Bundle.STATUS_STARTED ) {
			console.warn('cannot_start:already_started:' + this.identity + ':' + this.version);
			return;
		}

		console.log('* starting ' + this.identity + '...');

		var ctx = this.ctx;
		var imports = this.imports;
		for(var bundleId in imports) {
			if( bundleId === this.bundleId ) continue;
			ctx.require(bundleId);
		}

		var activator = this.activator;
		var result;
		if( activator && typeof(activator.start) === 'function' ) {
			result = activator.start.apply(this, [this.ctx]);

			if( typeof(result) === 'function' ) {
				this.status = Bundle.STATUS_STARTING;
				var self = this;
				result(function(err) {
					if( err ) {
						self.status = Bundle.STATUS_ERROR;
						self.error = err;
						console.error('bundle_start_error:' + this.identity + ':' + err.message, err);
						return;
					}

					self.status = Bundle.STATUS_STARTED;
				});
			} else {
				this.status = Bundle.STATUS_STARTED;
			}
		} else {
			this.status = Bundle.STATUS_STARTED;
		}

		console.log('* started ' + this.identity);

		return result;
	},
	stop: function stop() {
		if( this.status !== Bundle.STATUS_STARTED ) {
			console.warn('cannot_stop:not_started_yet:' + this.identity + ':' + this.status);
			return;
		}

		var activator = this.activator;
		var result;
		if( activator && typeof(activator.stop) === 'function' ) {
			result = activator.stop.apply(this, [this.ctx]);

			if( typeof(result) === 'function' ) {
				var self = this;
				result(function(err) {
					if( err ) {
						self.status = Bundle.STATUS_ERROR;
						self.error = err;
						console.error('bundle_stop_error:' + this.identity + ':' + err.message, err);
						return;
					}

					self.status = Bundle.STATUS_STOPPED;
				});
			} else {
				this.status = Bundle.STATUS_STOPPED;
			}
		} else {
			this.status = Bundle.STATUS_STOPPED;
		}

		return result;
	}
};

module.exports = Bundle;
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const volunteer = require('./model/volunteer');
const election = require('./model/election');
const training = require('./model/training');
const position = require('./model/position');
const CONFIG = require('./config.json');
const bluebird = require('bluebird');
const connection = mongoose.connect(CONFIG.MONGO_URL);
const csv = require('fast-csv');
var electionData = [];
var trainingData = [];
var positionData = [];
csv
 .fromPath("./csv/sites.csv")
 .on("data", function(data){
  electionData.push({
    district:data[0],
    site:data[1],
    address:data[2]});
});

csv
 .fromPath("./csv/training.csv")
 .on("data", function(data){
  trainingData.push({
    day: data[0],
    date: data[1],
    area: data[2],
    training: data[3],
    site: data[4],
    address: data[5],
    city: data[6],
    zip: data[7],
    time: data[8],
    district: data[9]
  });
});

csv
 .fromPath("./csv/position.csv")
 .on("data", function(data){
  positionData.push({
    position: data[0],
    volunteerSite: data[1],
    volunteerCount: data[2],
    trainingNeeded: data[3]
  });
});

mongoose.connection.once('open', function() {
  Promise.all([
  election.insertMany(electionData.map((element, index, array) =>{
    return {
      district: element.district,
      site:element.site,
      address: element.address
    }
  })),
  position.insertMany(positionData.map((element, index, array) =>{
    return {
      position: element.position,
      volunteerSite: element.volunteerSite,
      volunteerCount: element.volunteerCount,
      trainingNeeded: element.trainingNeeded
    }
  })),
  training.insertMany(trainingData.map((element, index, array) =>{
    return {
      day: element.day,
      date: element.date,
      county: element.county,
      position: element.position,
      location: element.location,
      address: element.address,
      city: element.city,
      zip: element.zip,
      time: element.time,
      district: element.district
    }
  }))
  ])
  .then(function() {
    mongoose.connection.close();
    process.exit();
  });
});
<commit_msg>Fixed missing fields<commit_after>const mongoose = require('mongoose');
const volunteer = require('./model/volunteer');
const election = require('./model/election');
const training = require('./model/training');
const position = require('./model/position');
const CONFIG = require('./config.json');
const bluebird = require('bluebird');
const connection = mongoose.connect(CONFIG.MONGO_URL);
const csv = require('fast-csv');
var electionData = [];
var trainingData = [];
var positionData = [];
csv
 .fromPath("./csv/sites.csv")
 .on("data", function(data){
  electionData.push({
    district:data[0],
    site:data[1],
    address:data[2]});
});

csv
 .fromPath("./csv/training.csv")
 .on("data", function(data){
  trainingData.push({
    day: data[0],
    date: data[1],
    area: data[2],
    training: data[3],
    site: data[4],
    address: data[5],
    city: data[6],
    zip: data[7],
    time: data[8],
    district: data[9]
  });
});

csv
 .fromPath("./csv/position.csv")
 .on("data", function(data){
  positionData.push({
    position: data[0],
    volunteerSite: data[1],
    volunteerCount: data[2],
    trainingNeeded: data[3]
  });
});

mongoose.connection.once('open', function() {
  Promise.all([
  election.insertMany(electionData.map((element, index, array) =>{
    return {
      district: element.district,
      site:element.site,
      address: element.address
    }
  })),
  position.insertMany(positionData.map((element, index, array) =>{
    return {
      position: element.position,
      volunteerSite: element.volunteerSite,
      volunteerCount: element.volunteerCount,
      trainingNeeded: element.trainingNeeded
    }
  })),
  training.insertMany(trainingData.map((element, index, array) =>{
    return {
      day: element.day,
      date: element.date,
      area: element.area,
      training: element.training,
      site: element.site,
      address: element.address,
      city: element.city,
      zip: element.zip,
      time: element.time,
      district: element.district
    }
  }))
  ])
  .then(function() {
    mongoose.connection.close();
    process.exit();
  });
});
<|endoftext|>


<commit_before>module.exports = function(myApp){
    var utils = {},
        path = require('path'),
        fs = require("fs");

    utils.console = {};

    utils.noop = function(){};

    utils.handlePromiseError = function(error){
        this.console.logLine();
        console.log(error.stack);
        this.console.logLine();
    };

    utils.console.logLine = function(){
        var line = "";
        if (!process.stdout.isTTY) {
            process.stdout.columns = 70;
        }
        while(line.length < process.stdout.columns){
            line += "#";
        }
        console.log(line);
    };

    utils.console.logLeft = function(whatToLog, outSideEdge){
        var emptyNeeded = (process.stdout.columns - (whatToLog.length + 1));

        if(outSideEdge) emptyNeeded += 2;
        var line = "";
        while(line.length < emptyNeeded){
            line += " ";
        }
        var output = whatToLog+line;
        if(outSideEdge) output = "# "+output+"#";
        console.log(output);
    };

    utils.console.logCenter = function(whatToLog, outSideEdge){
        var emptyNeeded = ((process.stdout.columns - whatToLog.length) / 2);
        if(outSideEdge){
            emptyNeeded = ((process.stdout.columns - (whatToLog.length + 2)) / 2);
        }
        var line = "";
        while(line.length < emptyNeeded){
            line += " ";
        }
        var output = line+whatToLog+line;
        if((output.length + 2) > process.stdout.columns){
            output = line+whatToLog;
            line = line.substring(0, line.length - 1);
            output += line;
        }
        if(outSideEdge){
            output = "#"+output+"#";
        }
        console.log(output);
    };

    utils.consoleOutput = function(whatToOutput, textAlign, outSideEdge){
        if(whatToOutput === "line") return this.console.logLine();
        if(textAlign === undefined) textAlign = "Left";
        if(outSideEdge === undefined) outSideEdge = false;
        this.console["log"+textAlign](whatToOutput, outSideEdge);
    };

    utils.mkdir = function(dir) {
        if (path.relative(myApp.root, dir).substring(0,2) == ".." ) {
            throw new RangeError("Directory out of scope. '" + dir + "'");
            // return false;
        }
        // TODO: Check the directory is within our scope.
        if ( !fs.existsSync(dir) ) {
            fs.mkdirSync(dir);
        }
    };

    utils.deleteFolderRecursive = function(dir) {
        if (path.relative(myApp.root, dir).substring(0,2) == ".." ) {
            throw new RangeError("Directory out of scope. '" + dir + "'");
            // return false;
        }
        if( fs.existsSync(dir) ) {
            fs.readdirSync(dir).forEach(function(file,index) {
                var curDir = dir + "/" + file;
                if(fs.statSync(curDir).isDirectory()) { // recurse
                    myApp.utils.deleteFolderRecursive(curDir);
                } else { // delete file
                    fs.unlinkSync(curDir);
                }
            });
            fs.rmdirSync(dir);
        }
    };

    utils.customSort = function(array, field, direction) {
        if(direction === undefined) direction = "desc";
        array.sort(function(a, b) {
            if (a[field] === undefined || b[field] === undefined)
                throw new Error('Invalid field to sort on');
            if (a[field] > b[field])
                return -1;
            if (a[field] < b[field])
                return 1;
            return 0;
        });
        if(direction === "asc") array.reverse();
    };

    utils.epoch = function(){
        var date = new Date();
        return Math.floor(date.getTime() / 1000);
    };

    utils.tryJSONParse = function(str) {
        if (str === null) {
            return {};
        }
        try {
            JSON.parse(str);
        } catch (e) {
            return str;
        }
        return JSON.parse(str);
    };

    /** underscore.js functions **/
    var ArrayProto    = Array.prototype,
        nativeForEach = ArrayProto.forEach,
        nativeKeys    = Object.keys,
        nativeEvery   = ArrayProto.every;

    var isArrayLike = function(collection) {
        var length = getLength(collection);
        return typeof length == 'number' && length >= 0 && length <= Math.pow(2, 53) - 1;
    };

    var property = function(key) {
        return function(obj) {
            return obj === null ? void 0 : obj[key];
        };
    };

    var getLength = property('length');

    utils.has = function(obj, key) {
        return obj !== null && hasOwnProperty.call(obj, key);
    };

    utils.identity = function(value) {
        return value;
    };

    utils.isArray = function(obj) {
        return toString.call(obj) == '[object Array]';
    };

    utils.isObject = function(obj) {
        var type = typeof obj;
        return type === 'function' || type === 'object' && !!obj;
    };

    utils.keys = function(obj) {
        if (!utils.isObject(obj)) return [];
        if (nativeKeys) return nativeKeys(obj);
        var keys = [];
        for (var key in obj) if (utils.has(obj, key)) keys.push(key);
            // if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
    };

    utils.values = function(obj) {
        var keys = utils.keys(obj);
        var length = keys.length;
        var values = Array(length);
        for (var i = 0; i < length; i++) {
            values[i] = obj[keys[i]];
        }
        return values;
    };

    utils.each = utils.forEach = function(obj, iterator, context) {
        var i, length;
        if (isArrayLike(obj)) {
          for (i = 0, length = obj.length; i < length; i++) {
            iterator(obj[i], i, obj);
          }
        } else {
          var keys = utils.keys(obj);
          for (i = 0, length = keys.length; i < length; i++) {
            iterator(obj[keys[i]], keys[i], obj);
          }
        }
        return obj;
    };

    utils.every = function(obj, predicate, context) {
        predicate || (predicate = utils.identity);                  // jshint ignore:line
        var result = true;
        if (obj === null) return result;
        if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
        utils.each(obj, function(value, index, list) {
            if (!(result = result && predicate.call(context, value, index, list))) return breaker;
        });
        return !!result;
    };

    utils.flatten = function(input, shallow, output) {
        if (output === undefined) { output = []; }
        if (shallow && utils.every(input, utils.isArray)) {
            return concat.apply(output, input);
        }
        utils.each(input, function(value) {
            if (utils.isArray(value)) {
                shallow ? push.apply(output, value) : utils.flatten(value, shallow, output);            // jshint ignore:line
            } else {
                output.push(value);
            }
        });
        return output;
    };

    utils.isEmpty = function(obj) {
        if (obj === null) return true;
        if (isArrayLike(obj) && (utils.isArray(obj)) ) return obj.length === 0;
        return utils.keys(obj).length === 0;
    };
    /** end underscore.js functions **/

    myApp.utils = utils;
};<commit_msg>Update index.js<commit_after>module.exports = function(myApp){
    var utils = {},
        path = require('path'),
        fs = require("fs");

    utils.console = {};

    utils.noop = function(){};

    utils.handlePromiseError = function(error){
        this.console.logLine();
        console.log(error.stack);
        this.console.logLine();
    };

    utils.console.logLine = function(){
        var line = "";
        if (!process.stdout.isTTY) {
            process.stdout.columns = 70;
        }
        while(line.length < process.stdout.columns){
            line += "#";
        }
        console.log(line);
    };

    utils.console.logLeft = function(whatToLog, outSideEdge){
        var emptyNeeded = (process.stdout.columns - (whatToLog.length + 1));

        if(outSideEdge) emptyNeeded += 2;
        var line = "";
        while(line.length < emptyNeeded){
            line += " ";
        }
        var output = whatToLog+line;
        if(outSideEdge) output = "# "+output+"#";
        console.log(output);
    };

    utils.console.logCenter = function(whatToLog, outSideEdge){
        var emptyNeeded = ((process.stdout.columns - whatToLog.length) / 2);
        if(outSideEdge){
            emptyNeeded = ((process.stdout.columns - (whatToLog.length + 2)) / 2);
        }
        var line = "";
        while(line.length < emptyNeeded){
            line += " ";
        }
        var output = line+whatToLog+line;
        if((output.length + 2) > process.stdout.columns){
            output = line+whatToLog;
            line = line.substring(0, line.length - 1);
            output += line;
        }
        if(outSideEdge){
            output = "#"+output+"#";
        }
        console.log(output);
    };

    utils.consoleOutput = function(whatToOutput, textAlign, outSideEdge){
        if(whatToOutput === "line") return this.console.logLine();
        if(textAlign === undefined) textAlign = "Left";
        if(outSideEdge === undefined) outSideEdge = false;
        this.console["log"+textAlign](whatToOutput, outSideEdge);
    };

    utils.mkdir = function(dir) {
        if (path.relative(myApp.root, dir).substring(0,2) == ".." ) {
            throw new RangeError("Directory out of scope. '" + dir + "'");
            // return false;
        }
        // TODO: Check the directory is within our scope.
        if ( !fs.existsSync(dir) ) {
            fs.mkdirSync(dir);
        }
    };

    utils.deleteFolderRecursive = function(dir) {
        if (path.relative(myApp.root, dir).substring(0,2) == ".." ) {
            throw new RangeError("Directory out of scope. '" + dir + "'");
            // return false;
        }
        if( fs.existsSync(dir) ) {
            fs.readdirSync(dir).forEach(function(file,index) {
                var curDir = dir + "/" + file;
                if(fs.statSync(curDir).isDirectory()) { // recurse
                    myApp.utils.deleteFolderRecursive(curDir);
                } else { // delete file
                    fs.unlinkSync(curDir);
                }
            });
            fs.rmdirSync(dir);
        }
    };

    utils.customSort = function(array, field, direction) {
        if(direction === undefined) direction = "desc";
        array.sort(function(a, b) {
            if (a[field] === undefined || b[field] === undefined)
                throw new Error('Invalid field to sort on');
            if (a[field] > b[field])
                return -1;
            if (a[field] < b[field])
                return 1;
            return 0;
        });
        if(direction === "asc") array.reverse();
    };

    utils.epoch = function(){
        var date = new Date();
        return Math.floor(date.getTime() / 1000);
    };

    utils.tryJSONParse = function(str) {
        if (str === null) {
            return {};
        }
        try {
            JSON.parse(str);
        } catch (e) {
            return str;
        }
        return JSON.parse(str);
    };

    /** underscore.js functions **/
    var ArrayProto    = Array.prototype,
        nativeForEach = ArrayProto.forEach,
        nativeKeys    = Object.keys,
        nativeEvery   = ArrayProto.every;

    var isArrayLike = function(collection) {
        var length = getLength(collection);
        return typeof length == 'number' && length >= 0 && length <= Math.pow(2, 53) - 1;
    };

    var property = function(key) {
        return function(obj) {
            return obj === null ? void 0 : obj[key];
        };
    };

    var getLength = property('length');

    utils.has = function(obj, key) {
        return obj !== null && hasOwnProperty.call(obj, key);
    };

    utils.identity = function(value) {
        return value;
    };

    utils.isArray = function(obj) {
        return toString.call(obj) == '[object Array]';
    };

    utils.isObject = function(obj) {
        var type = typeof obj;
        return type === 'function' || type === 'object' && !!obj;
    };

    utils.keys = function(obj) {
        if (!utils.isObject(obj)) return [];
        if (nativeKeys) return nativeKeys(obj);
        var keys = [];
        for (var key in obj) if (utils.has(obj, key)) keys.push(key);
            // if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
    };

    utils.values = function(obj) {
        var keys = utils.keys(obj);
        var length = keys.length;
        var values = Array(length);
        for (var i = 0; i < length; i++) {
            values[i] = obj[keys[i]];
        }
        return values;
    };

    utils.each = utils.forEach = function(obj, iterator, context) {
        var i, length;
        if (isArrayLike(obj)) {
          for (i = 0, length = obj.length; i < length; i++) {
            iterator(obj[i], i, obj);
          }
        } else {
          var keys = utils.keys(obj);
          for (i = 0, length = keys.length; i < length; i++) {
            iterator(obj[keys[i]], keys[i], obj);
          }
        }
        return obj;
    };

    utils.every = function(obj, predicate, context) {
        predicate || (predicate = utils.identity);                  // jshint ignore:line
        var result = true;
        if (obj === null) return result;
        if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
        utils.each(obj, function(value, index, list) {
            if (!(result = result && predicate.call(context, value, index, list))) return breaker;
        });
        return !!result;
    };

    utils.flatten = function(input, shallow, output) {
        if (output === undefined) { output = []; }
        if (shallow && utils.every(input, utils.isArray)) {
            return concat.apply(output, input);
        }
        utils.each(input, function(value) {
            if (utils.isArray(value)) {
                shallow ? push.apply(output, value) : utils.flatten(value, shallow, output);            // jshint ignore:line
            } else {
                output.push(value);
            }
        });
        return output;
    };

    utils.isEmpty = function(obj) {
        if (obj === null) return true;
        if (isArrayLike(obj) && (utils.isArray(obj)) ) return obj.length === 0;
        return utils.keys(obj).length === 0;
    };

    /**
     * Converts decimal number to hex with zero padding
     *
     * @private
     * @method decimalToHex
     * @param {Number} d Decimal number to convert
     * @param {Number} padding How many zeros to use for padding
     * @return {String} Decimal number converted to hex string
    */
    utils.decimalToHex = function(d, padding) {
        var hex = Number(d).toString(16);
        padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
        while (hex.length < padding) {
            hex = "0" + hex;
        }
        return hex;
    };

    /** end underscore.js functions **/

    myApp.utils = utils;
};
<|endoftext|>


<commit_before>'use strict';

const config = require('../../config/config').globalConfig;
const debug = require('../../util/debug')('zenodo');
const { RocZenodo } = require('../../roc-zenodo');

const decorateError = require('./decorateError');
const { composeWithError } = require('./util');

let rocZenodo = new RocZenodo({
  sandbox: config.zenodoSandbox,
  token: config.zenodoToken,
  name: config.zenodoName,
  visualizationUrl: config.zenodoVisualizationUrl,
  attachments: config.zenodoAttachments
});

exports.createEntry = composeWithError(async (ctx) => {
  const { entryId } = ctx.query;
  if (!entryId) {
    decorateError(ctx, 400, 'missing entryId query parameter');
    return;
  }
  const { couch, userEmail } = ctx.state;
  debug(`create Zenodo entry: ${entryId} (${userEmail})`);
  const zenodoEntry = await couch.getEntryWithRights(
    entryId,
    userEmail,
    'write'
  );
  const { $content: { meta, entries, doi, readme: entryReadme } } = zenodoEntry;
  if (!entries || entries.length === 0) {
    decorateError(ctx, 400, 'cannot publish on Zenodo without entries');
    return;
  }
  if (typeof doi === 'string' && doi.length > 1) {
    decorateError(ctx, 403, 'this entry has already been published');
    return;
  }
  const readme = config.zenodoReadme || entryReadme;
  if (!readme) {
    decorateError(ctx, 400, 'readme is mandatory');
    return;
  }

  let depositionMeta;
  try {
    depositionMeta = await rocZenodo.getZenodoDeposition(meta);
  } catch (e) {
    decorateError(ctx, 400, e.message);
    return;
  }

  // We first get entries in case there is an error
  const entryValues = await Promise.all(
    entries.map((entry) => {
      if (entry.rev) {
        return couch.getEntryWithRights(entry.id, userEmail, 'read', {
          rev: entry.rev
        });
      } else {
        return couch.getEntryWithRights(entry.id, userEmail, 'read');
      }
    })
  );

  const deposition = await rocZenodo.createEntry(depositionMeta);
  const newDoi = deposition.metadata.prereserve_doi.doi;
  zenodoEntry.$content.doi = newDoi;
  zenodoEntry.$content.status.unshift({
    epoch: Date.now(),
    value: 'Publishing'
  });

  {
    const suffix = rocZenodo.getDescriptionSuffix(deposition);
    if (suffix !== '') {
      deposition.metadata.description += suffix;
      await rocZenodo.updateEntry(deposition);
    }
  }

  const result = await couch.insertEntry(zenodoEntry, userEmail);
  zenodoEntry._rev = result.info.rev;

  uploadAttachments(
    deposition,
    zenodoEntry,
    entryValues,
    readme,
    couch,
    userEmail
  ).catch((e) => {
    debug.error('failed to upload attachments to Zenodo', e.message);
  });

  ctx.status = 202;
  ctx.body = {
    ok: true,
    doi: newDoi
  };
});

async function uploadAttachments(
  deposition,
  zenodoEntry,
  entries,
  readme,
  couch,
  userEmail
) {
  const toc = [];

  let entryCount = 0;

  try {
    /* eslint-disable no-await-in-loop */
    for (const entry of entries) {
      const { _id: id, $content: content, $kind: kind } = entry;
      const entryZenodoId = String(entryCount).padStart(3, '0');
      const filenamePrefix = `${kind}_${entryZenodoId}`;
      await rocZenodo.uploadFile(deposition, {
        filename: `${filenamePrefix}/index.json`,
        contentType: 'application/octet-stream',
        data: JSON.stringify(content, null, 2)
      });
      if (rocZenodo.attachments) {
        let customAttachments = rocZenodo.attachments(content);
        if (!Array.isArray(customAttachments)) {
          if (
            typeof customAttachments === 'object' &&
            customAttachments !== null
          ) {
            customAttachments = [customAttachments];
          } else {
            throw new TypeError(
              'custom attachments method must return an array'
            );
          }
        }
        for (const customAttachment of customAttachments) {
          if (!customAttachment.filename || !customAttachment.data) {
            throw new TypeError(
              'custom attachments must have a filename and data property'
            );
          }
          await rocZenodo.uploadFile(deposition, {
            filename: `${filenamePrefix}/${customAttachment.filename}`,
            contentType:
              customAttachment.contentType || 'application/octet-stream',
            data: customAttachment.data
          });
        }
      }
      for (const attachmentPath in entry._attachments) {
        const contentType = entry._attachments[attachmentPath].content_type;
        const attachmentStream = await couch.getAttachmentByName(
          id,
          attachmentPath,
          userEmail,
          true
        );
        await rocZenodo.uploadFile(deposition, {
          filename: `${filenamePrefix}/${attachmentPath}`,
          contentType,
          data: attachmentStream
        });
      }
      toc.push({ kind: entry.$kind, id: entryZenodoId });
      entryCount++;
    }
    /* eslint-enable */

    await rocZenodo.uploadFile(deposition, {
      filename: '_toc.json',
      contentType: 'application/octet-stream',
      data: JSON.stringify(toc, null, 2)
    });
    await rocZenodo.uploadFile(deposition, rocZenodo.getIndexMd(readme));
  } catch (e) {
    await rocZenodo.deleteEntry(deposition);
    zenodoEntry.$content.doi = '';
    zenodoEntry.$content.status.unshift({
      epoch: Date.now(),
      value: 'Error'
    });
    await couch.insertEntry(zenodoEntry, userEmail);
    throw e;
  }

  await rocZenodo.publish(deposition);

  zenodoEntry.$content.status.unshift({
    epoch: Date.now(),
    value: 'Published'
  });

  await couch.insertEntry(zenodoEntry, userEmail);
}
<commit_msg>fix: publish entry it try block (#110)<commit_after>'use strict';

const config = require('../../config/config').globalConfig;
const debug = require('../../util/debug')('zenodo');
const { RocZenodo } = require('../../roc-zenodo');

const decorateError = require('./decorateError');
const { composeWithError } = require('./util');

let rocZenodo = new RocZenodo({
  sandbox: config.zenodoSandbox,
  token: config.zenodoToken,
  name: config.zenodoName,
  visualizationUrl: config.zenodoVisualizationUrl,
  attachments: config.zenodoAttachments
});

exports.createEntry = composeWithError(async (ctx) => {
  const { entryId } = ctx.query;
  if (!entryId) {
    decorateError(ctx, 400, 'missing entryId query parameter');
    return;
  }
  const { couch, userEmail } = ctx.state;
  debug(`create Zenodo entry: ${entryId} (${userEmail})`);
  const zenodoEntry = await couch.getEntryWithRights(
    entryId,
    userEmail,
    'write'
  );
  const { $content: { meta, entries, doi, readme: entryReadme } } = zenodoEntry;
  if (!entries || entries.length === 0) {
    decorateError(ctx, 400, 'cannot publish on Zenodo without entries');
    return;
  }
  if (typeof doi === 'string' && doi.length > 1) {
    decorateError(ctx, 403, 'this entry has already been published');
    return;
  }
  const readme = config.zenodoReadme || entryReadme;
  if (!readme) {
    decorateError(ctx, 400, 'readme is mandatory');
    return;
  }

  let depositionMeta;
  try {
    depositionMeta = await rocZenodo.getZenodoDeposition(meta);
  } catch (e) {
    decorateError(ctx, 400, e.message);
    return;
  }

  // We first get entries in case there is an error
  const entryValues = await Promise.all(
    entries.map((entry) => {
      if (entry.rev) {
        return couch.getEntryWithRights(entry.id, userEmail, 'read', {
          rev: entry.rev
        });
      } else {
        return couch.getEntryWithRights(entry.id, userEmail, 'read');
      }
    })
  );

  const deposition = await rocZenodo.createEntry(depositionMeta);
  const newDoi = deposition.metadata.prereserve_doi.doi;
  zenodoEntry.$content.doi = newDoi;
  zenodoEntry.$content.status.unshift({
    epoch: Date.now(),
    value: 'Publishing'
  });

  {
    const suffix = rocZenodo.getDescriptionSuffix(deposition);
    if (suffix !== '') {
      deposition.metadata.description += suffix;
      await rocZenodo.updateEntry(deposition);
    }
  }

  const result = await couch.insertEntry(zenodoEntry, userEmail);
  zenodoEntry._rev = result.info.rev;

  uploadAttachments(
    deposition,
    zenodoEntry,
    entryValues,
    readme,
    couch,
    userEmail
  ).catch((e) => {
    debug.error('failed to upload attachments to Zenodo', e.message);
  });

  ctx.status = 202;
  ctx.body = {
    ok: true,
    doi: newDoi
  };
});

async function uploadAttachments(
  deposition,
  zenodoEntry,
  entries,
  readme,
  couch,
  userEmail
) {
  const toc = [];

  let entryCount = 0;

  try {
    /* eslint-disable no-await-in-loop */
    for (const entry of entries) {
      const { _id: id, $content: content, $kind: kind } = entry;
      const entryZenodoId = String(entryCount).padStart(3, '0');
      const filenamePrefix = `${kind}_${entryZenodoId}`;
      await rocZenodo.uploadFile(deposition, {
        filename: `${filenamePrefix}/index.json`,
        contentType: 'application/octet-stream',
        data: JSON.stringify(content, null, 2)
      });
      if (rocZenodo.attachments) {
        let customAttachments = rocZenodo.attachments(content);
        if (!Array.isArray(customAttachments)) {
          if (
            typeof customAttachments === 'object' &&
            customAttachments !== null
          ) {
            customAttachments = [customAttachments];
          } else {
            throw new TypeError(
              'custom attachments method must return an array'
            );
          }
        }
        for (const customAttachment of customAttachments) {
          if (!customAttachment.filename || !customAttachment.data) {
            throw new TypeError(
              'custom attachments must have a filename and data property'
            );
          }
          await rocZenodo.uploadFile(deposition, {
            filename: `${filenamePrefix}/${customAttachment.filename}`,
            contentType:
              customAttachment.contentType || 'application/octet-stream',
            data: customAttachment.data
          });
        }
      }
      for (const attachmentPath in entry._attachments) {
        const contentType = entry._attachments[attachmentPath].content_type;
        const attachmentStream = await couch.getAttachmentByName(
          id,
          attachmentPath,
          userEmail,
          true
        );
        await rocZenodo.uploadFile(deposition, {
          filename: `${filenamePrefix}/${attachmentPath}`,
          contentType,
          data: attachmentStream
        });
      }
      toc.push({ kind: entry.$kind, id: entryZenodoId });
      entryCount++;
    }
    /* eslint-enable */

    await rocZenodo.uploadFile(deposition, {
      filename: '_toc.json',
      contentType: 'application/octet-stream',
      data: JSON.stringify(toc, null, 2)
    });
    await rocZenodo.uploadFile(deposition, rocZenodo.getIndexMd(readme));
    await rocZenodo.publishEntry(deposition);
  } catch (e) {
    await rocZenodo.deleteEntry(deposition);
    zenodoEntry.$content.doi = '';
    zenodoEntry.$content.status.unshift({
      epoch: Date.now(),
      value: 'Error'
    });
    await couch.insertEntry(zenodoEntry, userEmail);
    throw e;
  }

  zenodoEntry.$content.status.unshift({
    epoch: Date.now(),
    value: 'Published'
  });

  await couch.insertEntry(zenodoEntry, userEmail);
}
<|endoftext|>


<commit_before>import React from 'react';
import Textfield from 'react-mdl/lib/Textfield';

var EditorInput = props => {
  return (

      <Textfield
        className="mdl-textfield--full-width"
        label={props.label}
        floatingLabel={true}
        {...props}
      />

  );
}

var EditorUrlInput = props => {
  var urlPattern = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i.source;
  return (
    <EditorInput error="This is not a valid url" pattern={urlPattern} {...props}/>
  );
}

var Editor = React.createClass({
  getInitialState: function() {
    return {
      name: this.props.name || 'ACME',
      url: this.props.url || 'http://www.acme.org',
      blog: '',
      facebook: '',
      twitter: '',
      yelp: '',
      foursquare: ''
    };
  },
  onChange: function (event) {
    var property = event.target.name;
    var value = event.target.value;
    this.setState({ [property]: value }, function () {
      this.props.onChange(this.state)
    });
  },
  generateJsonld: function () {
    var result = [];
    if (this.state.blog) {
      result.push({
        "@context" : "http://schema.org",
        "@type" : "Blog",
        url: this.state.blog
      });
    }
    var sameAs = [
      this.state.facebook,
      this.state.twitter,
      this.state.yelp,
      this.state.foursquare
    ].filter(x => x);
    if (sameAs.length > 0) {
      result.push({
        "@context" : "http://schema.org",
        "@type" : "Organization",
        name: this.state.name,
        url: this.state.url,
        sameAs: sameAs
      });
    }
    return result;
  },
  setProperty: function (name, value) {
    this.setState({ [name]: value }, function () {
      this.props.onChange(this.generateJsonld());
    });
  },
  render: function() {
    var bindProperty = property => ({
      value: this.state[property],
      onChange: e => this.setProperty(property, e.target.value)
    });

    return (
      <form className="mdl-grid">
        <EditorInput label="The name of your organization" {...bindProperty('name')}/>
        <EditorUrlInput label="The url of your website" {...bindProperty('url')}/>
        <EditorUrlInput label="The url of your blog" {...bindProperty('blog')}/>
        <EditorUrlInput label="The url of your Facebook page" {...bindProperty('facebook')}/>
        <EditorUrlInput label="The url of your Twitter page" {...bindProperty('twitter')}/>
        <EditorUrlInput label="The url of your Yelp page" {...bindProperty('yelp')}/>
        <EditorUrlInput label="The url of your Foursquare page" {...bindProperty('foursquare')}/>
      </form>
    );
  }
});

export default Editor;
<commit_msg>add google plus<commit_after>import React from 'react';
import Textfield from 'react-mdl/lib/Textfield';

var EditorInput = props => {
  return (

      <Textfield
        className="mdl-textfield--full-width"
        label={props.label}
        floatingLabel={true}
        {...props}
      />

  );
}

var EditorUrlInput = props => {
  var urlPattern = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i.source;
  return (
    <EditorInput error="This is not a valid url" pattern={urlPattern} {...props}/>
  );
}

var Editor = React.createClass({
  getInitialState: function() {
    return {
      name: this.props.name || 'ACME',
      url: this.props.url || 'http://www.acme.org',
      blog: '',
      facebook: '',
      googleplus: '',
      twitter: '',
      yelp: '',
      foursquare: ''
    };
  },
  onChange: function (event) {
    var property = event.target.name;
    var value = event.target.value;
    this.setState({ [property]: value }, function () {
      this.props.onChange(this.state)
    });
  },
  generateJsonld: function () {
    var result = [];
    if (this.state.blog) {
      result.push({
        "@context" : "http://schema.org",
        "@type" : "Blog",
        url: this.state.blog
      });
    }
    var sameAs = [
      this.state.facebook,
      this.state.googleplus,
      this.state.twitter,
      this.state.yelp,
      this.state.foursquare
    ].filter(x => x);
    if (sameAs.length > 0) {
      result.push({
        "@context" : "http://schema.org",
        "@type" : "Organization",
        name: this.state.name,
        url: this.state.url,
        sameAs: sameAs
      });
    }
    return result;
  },
  setProperty: function (name, value) {
    this.setState({ [name]: value }, function () {
      this.props.onChange(this.generateJsonld());
    });
  },
  render: function() {
    var bindProperty = property => ({
      value: this.state[property],
      onChange: e => this.setProperty(property, e.target.value)
    });

    return (
      <form className="mdl-grid">
        <EditorInput label="The name of your organization" {...bindProperty('name')}/>
        <EditorUrlInput label="The url of your website" {...bindProperty('url')}/>
        <EditorUrlInput label="The url of your blog" {...bindProperty('blog')}/>
        <EditorUrlInput label="The url of your Facebook page" {...bindProperty('facebook')}/>
        <EditorUrlInput label="The url of your Google+ page" {...bindProperty('googleplus')}/>
        <EditorUrlInput label="The url of your Twitter page" {...bindProperty('twitter')}/>
        <EditorUrlInput label="The url of your Yelp page" {...bindProperty('yelp')}/>
        <EditorUrlInput label="The url of your Foursquare page" {...bindProperty('foursquare')}/>
      </form>
    );
  }
});

export default Editor;
<|endoftext|>


<commit_before>// Available difficulties
const diff_enum = {
    EASY: 0,
    MEDIUM: 25,
    HARD: 50,
    EXTREME: 100,
};

//Setting difficulty from url
const url = new URL(window.location);
let difficulty_param = url.searchParams.get("difficulty");
difficulty_param = diff_enum[difficulty_param.toUpperCase()]

// Utility Functions
const mv_x = (what, x) => what.style.left = x + "px",
    mv_y = (what, y) => what.style.top = y + "px",
    rand = (limit) => Math.random() * limit,
    inRange = (lower, upper, what) => what >= lower && what <= upper;

// Selectors. Duh!
const catch_me = document.getElementById("catch_me"),
    counter = document.getElementById("counter"),
    body = document.querySelectorAll(".body")[0];

// Useful global values
const catch_height = 50,
    catch_width = 100,
    difficulty = typeof(difficulty_param) !== 'undefined' ? difficulty_param : diff_enum.HARD; // CHANGE THIS FOR MORE FUN
    alert(difficulty)
const incr_counter = () => counter.innerText = +counter.innerText + 1;
// Next positions should be within the visible portion of the window.
const rand_x = () => rand(window.innerWidth - catch_width),
    rand_y = () => rand(window.innerHeight - catch_height),
    mv_catch_x = () => mv_x(catch_me, rand_x()),
    mv_catch_y = () => mv_y(catch_me, rand_y());

// Initial State
catch_me.style.position = "absolute";
catch_me.style.height = catch_height + "px";
catch_me.style.width = catch_width + "px";
catch_me.style.backgroundColor = "#555";
mv_catch_x();
mv_catch_y();

// If you can get your mouse inside here you get a point.
// But the question is, can you? ;)
catch_me.addEventListener("mouseenter", () => {
    mv_catch_x();
    mv_catch_y();
    incr_counter();
});

// Track mouse movent inside body.
body.addEventListener("mousemove", e => {
    const delta_x = e.offsetX - catch_me.offsetLeft,
        delta_y = e.offsetY - catch_me.offsetTop,
        xInRange = inRange(-difficulty, difficulty + catch_width, delta_x),
        yInRange = inRange(-difficulty, difficulty + catch_height, delta_y);
    if (xInRange && yInRange) {
        mv_catch_x();
        mv_catch_y();
        // console.log(`x: ${delta_x} y: ${delta_y}`);
    }
});
<commit_msg>removed alert<commit_after>// Available difficulties
const diff_enum = {
    EASY: 0,
    MEDIUM: 25,
    HARD: 50,
    EXTREME: 100,
};

//Setting difficulty from url
const url = new URL(window.location);
let difficulty_param = url.searchParams.get("difficulty");
difficulty_param = diff_enum[difficulty_param.toUpperCase()]

// Utility Functions
const mv_x = (what, x) => what.style.left = x + "px",
    mv_y = (what, y) => what.style.top = y + "px",
    rand = (limit) => Math.random() * limit,
    inRange = (lower, upper, what) => what >= lower && what <= upper;

// Selectors. Duh!
const catch_me = document.getElementById("catch_me"),
    counter = document.getElementById("counter"),
    body = document.querySelectorAll(".body")[0];

// Useful global values
const catch_height = 50,
    catch_width = 100,
    difficulty = typeof(difficulty_param) !== 'undefined' ? difficulty_param : diff_enum.HARD; // CHANGE THIS FOR MORE FUN

const incr_counter = () => counter.innerText = +counter.innerText + 1;
// Next positions should be within the visible portion of the window.
const rand_x = () => rand(window.innerWidth - catch_width),
    rand_y = () => rand(window.innerHeight - catch_height),
    mv_catch_x = () => mv_x(catch_me, rand_x()),
    mv_catch_y = () => mv_y(catch_me, rand_y());

// Initial State
catch_me.style.position = "absolute";
catch_me.style.height = catch_height + "px";
catch_me.style.width = catch_width + "px";
catch_me.style.backgroundColor = "#555";
mv_catch_x();
mv_catch_y();

// If you can get your mouse inside here you get a point.
// But the question is, can you? ;)
catch_me.addEventListener("mouseenter", () => {
    mv_catch_x();
    mv_catch_y();
    incr_counter();
});

// Track mouse movent inside body.
body.addEventListener("mousemove", e => {
    const delta_x = e.offsetX - catch_me.offsetLeft,
        delta_y = e.offsetY - catch_me.offsetTop,
        xInRange = inRange(-difficulty, difficulty + catch_width, delta_x),
        yInRange = inRange(-difficulty, difficulty + catch_height, delta_y);
    if (xInRange && yInRange) {
        mv_catch_x();
        mv_catch_y();
        // console.log(`x: ${delta_x} y: ${delta_y}`);
    }
});
<|endoftext|>