<commit_before>{
	"translatorID":"e7e01cac-1e37-4da6-b078-a0e8343b0e98",
	"translatorType":4,
	"label":"unAPI",
	"creator":"Simon Kornblith",
	"target":null,
	"minVersion":"2.1",
	"maxVersion":"",
	"priority":200,
	"inRepository":true,
	"detectXPath":"//link[@rel='unapi-server']",
	"lastUpdated":"2011-04-19 19:40:07"
}

var RECOGNIZABLE_FORMATS = ["rdf_zotero", "rdf_bibliontology", "mods", "marc", "unimarc", "ris",
	"refer", "bibtex", "rdf_dc"];
var FORMAT_GUIDS = {
	"rdf_zotero":"5e3ad958-ac79-463d-812b-a86a9235c28f",
	"rdf_bibliontology":"14763d25-8ba0-45df-8f52-b8d1108e7ac9",
	"mods":"0e2235e7-babf-413c-9acf-f27cce5f059c",
	"marc":"a6ee60df-1ddc-4aae-bb25-45e0537be973",
	"unimarc":"a6ee60df-1ddc-4aae-bb25-45e0537be973",
	"ris":"32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7",
	"refer":"881f60f2-0802-411a-9228-ce5f47b64c7d",
	"bibtex":"9cb70025-a888-4a29-a210-93ec52da40d4",
	"rdf_dc":"5e3ad958-ac79-463d-812b-a86a9235c28f"
};

var unAPIResolver = false;
var defaultFormat, unAPIIDs;

/**
 * A class to describe an unAPI format description
 * @property isSupported {Boolean} Whether Zotero supports a format contained in this description
 * @property name {String} The unAPI format name, used to retrieve item descriptions
 * @property translatorID {String} The ID of the translator used to read this format
 *
 * @constructor
 * @param {String} aXML unAPI format description XML
 */
UnAPIFormat = function(aXML) {
	var parser = new DOMParser();
	var doc = parser.parseFromString(aXML.replace(/<!DOCTYPE[^>]*>/, "").replace(/<\?xml[^>]*\?>/, ""), "text/xml");

	var foundFormat = new Object();

	// Loop through to determine format name
	var nodes = doc.documentElement.getElementsByTagName("format");
	var nNodes = nodes.length;
	var node, name, lowerName, format;
	for(var i=0; i<nNodes; i++) {
		node = nodes[i];
		name = node.getAttribute("name");
		lowerName = name.toLowerCase();
		format = false;

		// Look for formats we can recognize
		if(["rdf_zotero", "rdf_bibliontology", "bibtex", "endnote", "rdf_dc"].indexOf(lowerName) != -1) {
			format = lowerName;
		} else if(lowerName == "rdf_bibliontology") {
			format = "rdf_bibliontology";
		} else if(lowerName === "mods"
				|| node.getAttribute("namespace_uri") === "http://www.loc.gov/mods/v3"
				|| node.getAttribute("docs") === "http://www.loc.gov/standards/mods/"
				|| node.getAttribute("type") === "application/mods+xml") {
			format = "mods";
		} else if(lowerName.match(/^marc\b/)
				|| node.getAttribute("type") === "application/marc") {
			format = "marc";
		} else if(lowerName.match(/^unimarc\b/)
				|| node.getAttribute("type") === "application/unimarc") {
			format = "unimarc";
		} else if(node.getAttribute("docs") == "http://www.refman.com/support/risformat_intro.asp"
				|| lowerName.match(/^ris\b/)) {
			format = "ris";
		}

		if(format) foundFormat[format] = name;
	}

	// Loop through again to determine optimal supported format
	for(var i=0; i<RECOGNIZABLE_FORMATS.length; i++) {
		if(foundFormat[RECOGNIZABLE_FORMATS[i]]) {
			this.isSupported = true;
			this.name = foundFormat[RECOGNIZABLE_FORMATS[i]];
			this.translatorID = FORMAT_GUIDS[RECOGNIZABLE_FORMATS[i]];
			return;
		}
	}

	this.isSupported = false;
}

/**
 * A class encapsulating an UnAPI ID
 * @property format {UnAPIFormat} Information regarding the format
 * @property items {Zotero.Item[]} Items corresponding to this ID
 *
 * @constructor
 * @param {String} id The ID contained in an abbr tag
 */
UnAPIID = function(id) {
	this.id = id;
	unAPIIDs[id] = this;
}

UnAPIID.prototype = {
	/**
	 * Gets the item type for this item
	 * @param {Function} callback Callback to be passed itemType when it is known
	 */
	"getItemType":function(callback) {
		var me = this;
		this.getItems(function(items) {
			if(items.length === 0) {
				callback(false);
			} else if(items.length === 1) {
				callback(items[0].itemType);
			} else {
				callback("multiple");
			}
		});
	},

	/**
	 * Gets items associated with this ID
	 * @param {Function} callback Callback to be passed items when they have been retrieved
	 */
	"getItems":function(callback) {
		if(this.items) {
			callback(me.items);
			return;
		}

		var me = this;
		this.items = [];
		this.isSupported(function(isSupported) {
			if(!isSupported) {
				callback([]);
				return;
			}

			Zotero.Utilities.HTTP.doGet(unAPIResolver+"?id="+me.id+"&format="+me.format.name, function(text) {
				var translator = Zotero.loadTranslator("import");
				translator.setTranslator(me.format.translatorID);
				translator.setString(text);
				translator.setHandler("itemDone", function(obj, item) {
					// add item to array
					me.items.push(item);
				});
				translator.setHandler("done", function(obj) {
					// run callback on item array
					callback(me.items);
				});
				translator.translate();
			});
		});
	},

	/**
	 * Determines whether Zotero can handle this ID
	 * @param {Function} callback Callback to be passed isSupported when it is known
	 */
	"isSupported":function(callback) {
		if(this.hasOwnProperty("format")) {
			callback(me.format.isSupported);
			return;
		}

		var me = this;

		getDefaultFormat(function() {
			// first try default format, since this won't require >1 HTTP request
			if(defaultFormat.isSupported) {
				me.format = defaultFormat;
				callback(true);
			} else {
				// if no supported default format, try format for this item
				Zotero.Utilities.HTTP.doGet(unAPIResolver+"?id="+me.id, function(text) {
					me.format = UnAPIFormat(text);
					callback(!!me.format.isSupported);
				});
			}
		});
	}
}

/**
 * This and the x: prefix in the XPath are to work around an issue with pages
 * served as application/xhtml+xml
 *
 * https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript#Implementing_a_default_namespace_for_XML_documents
 */
function nsResolver() {
	return 'http://www.w3.org/1999/xhtml';
}

/**
 * Extracts UnAPIIDs from a document
 * @param {document} A document object from which to extract unAPIIds
 * @return {UnAPIID[]} The unAPI ID objects extracted from the document
 */
function getUnAPIIDs(doc) {
	// look for a resolver
	var newUnAPIResolver = doc.evaluate('//x:link[@rel="unapi-server"]', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
	if(!newUnAPIResolver) return [];
	newUnAPIResolver = newUnAPIResolver.getAttribute("href");
	if(unAPIResolver !== newUnAPIResolver) {
		// if unAPI resolver has changed, clear
		defaultFormat = false;
		unAPIResolver = newUnAPIResolver;
		unAPIIDs = [];
	}

	// look for abbrs
	var abbrs = doc.evaluate('//x:abbr[contains(@class, " unapi-id") or contains(@class, "unapi-id ") or @class="unapi-id"][@title]',
		doc, nsResolver, XPathResult.ANY_TYPE, null);
	var abbr;
	var ids = [];
	while(abbr = abbrs.iterateNext()) {
		var id = abbr.getAttribute("title");
		ids.push(unAPIIDs[id] ? unAPIIDs[id] : new UnAPIID(id));
	}

	return ids;
}

/**
 * Retrieves the list of formats available for all items accessible through this unAPI resolver
 * @param {Function} callback A callback to be passed the format when it is available
 */
function getDefaultFormat(callback) {
	if(defaultFormat) {
		callback(defaultFormat);
	} else {
		Zotero.Utilities.HTTP.doGet(unAPIResolver, function(text) {
			// determine format of this item
			defaultFormat = new UnAPIFormat(text);
			callback(defaultFormat);
		});
	}
}
/**
 * Determines itemType for detection
 */
function determineDetectItemType(ids, supportedId) {
	var id = ids.shift();
	id.isSupported(function(isSupported) {
		if(isSupported && supportedId !== undefined) {
			// If there are multiple items with valid itemTypes, use "multiple"
			Zotero.done("multiple");
		} else if(ids.length) {
			// If IDs remain to be handled, handle the next one
			determineDetectItemType(ids, (isSupported ? id : supportedId));
		} else {
			// If all IDs have been handled, get foundItemType for only supported ID
			supportedId.getItemType(Zotero.done);
		}
	});
}

/**
 * Get all items
 * @param {UnAPIID[]} ids List of UnAPI IDs
 * @param {Function} callback Function to pass item array to when items have been retrieved
 * @param {Zotero.Item[]} items Item array; used for recursive calls
 **/
function getAllItems(ids, callback, items) {
	var id = ids.shift();
	id.getItems(function(retrievedItems) {
		var collectedItems = (items ? items.concat(retrievedItems) : retrievedItems);

		if(ids.length) {
			getAllItems(ids, callback, collectedItems);
		} else {
			callback(collectedItems);
		}
	});
}

function detectWeb(doc, url) {
	// get unAPI IDs
	var ids = getUnAPIIDs(doc);
	if(!ids.length) return false;

	// now we need to see if the server actually gives us bibliographic metadata, and determine the
	// type
	Zotero.wait();

	if(!ids.length === 1) {
		// Only one item, so we will just get its item type
		ids[0].getItemType(Zotero.done);
	} else {
		// Several items. We will need to call determineDetectItemType
		determineDetectItemType(ids);
	}
}

function doWeb(doc, url) {
	var ids = getUnAPIIDs(doc);

	Zotero.wait();

	getAllItems(ids, function(items) {
		// get the domain we're scraping, so we can use it for libraryCatalog
		domain = doc.location.href.match(/https?:\/\/([^/]+)/);

		if(items.length == 1) {
			// If only one item, just complete it
			items[0].libraryCatalog = domain[1];
			items[0].complete();
		} else if(items.length > 0) {
			// If multiple items, extract their titles
			var itemTitles = [];
			for(var i in items) {
				itemTitles[i] = items[i].title;
			}

			// Show item selection dialog
			var chosenItems = Zotero.selectItems(itemTitles);
			if(!chosenItems) Zotero.done(true);

			// Complete items
			for(var i in chosenItems) {
				items[i].libraryCatalog = domain[1];
				items[i].complete();
			}
		}

		Zotero.done();
		return;
	});
}
<commit_msg>- fix typo - log a message and don't fail due to invalid metadata for a single item<commit_after>{
	"translatorID":"e7e01cac-1e37-4da6-b078-a0e8343b0e98",
	"translatorType":4,
	"label":"unAPI",
	"creator":"Simon Kornblith",
	"target":null,
	"minVersion":"2.1",
	"maxVersion":"",
	"priority":200,
	"inRepository":true,
	"detectXPath":"//link[@rel='unapi-server']",
	"lastUpdated":"2011-06-09 01:57:14"
}

var RECOGNIZABLE_FORMATS = ["rdf_zotero", "rdf_bibliontology", "mods", "marc", "unimarc", "ris",
	"refer", "bibtex", "rdf_dc"];
var FORMAT_GUIDS = {
	"rdf_zotero":"5e3ad958-ac79-463d-812b-a86a9235c28f",
	"rdf_bibliontology":"14763d25-8ba0-45df-8f52-b8d1108e7ac9",
	"mods":"0e2235e7-babf-413c-9acf-f27cce5f059c",
	"marc":"a6ee60df-1ddc-4aae-bb25-45e0537be973",
	"unimarc":"a6ee60df-1ddc-4aae-bb25-45e0537be973",
	"ris":"32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7",
	"refer":"881f60f2-0802-411a-9228-ce5f47b64c7d",
	"bibtex":"9cb70025-a888-4a29-a210-93ec52da40d4",
	"rdf_dc":"5e3ad958-ac79-463d-812b-a86a9235c28f"
};

var unAPIResolver = false;
var defaultFormat, unAPIIDs;

/**
 * A class to describe an unAPI format description
 * @property isSupported {Boolean} Whether Zotero supports a format contained in this description
 * @property name {String} The unAPI format name, used to retrieve item descriptions
 * @property translatorID {String} The ID of the translator used to read this format
 *
 * @constructor
 * @param {String} aXML unAPI format description XML
 */
UnAPIFormat = function(aXML) {
	var parser = new DOMParser();
	var doc = parser.parseFromString(aXML.replace(/<!DOCTYPE[^>]*>/, "").replace(/<\?xml[^>]*\?>/, ""), "text/xml");

	var foundFormat = new Object();

	// Loop through to determine format name
	var nodes = doc.documentElement.getElementsByTagName("format");
	var nNodes = nodes.length;
	var node, name, lowerName, format;
	for(var i=0; i<nNodes; i++) {
		node = nodes[i];
		name = node.getAttribute("name");
		lowerName = name.toLowerCase();
		format = false;

		// Look for formats we can recognize
		if(["rdf_zotero", "rdf_bibliontology", "bibtex", "endnote", "rdf_dc"].indexOf(lowerName) != -1) {
			format = lowerName;
		} else if(lowerName == "rdf_bibliontology") {
			format = "rdf_bibliontology";
		} else if(lowerName === "mods"
				|| node.getAttribute("namespace_uri") === "http://www.loc.gov/mods/v3"
				|| node.getAttribute("docs") === "http://www.loc.gov/standards/mods/"
				|| node.getAttribute("type") === "application/mods+xml") {
			format = "mods";
		} else if(lowerName.match(/^marc\b/)
				|| node.getAttribute("type") === "application/marc") {
			format = "marc";
		} else if(lowerName.match(/^unimarc\b/)
				|| node.getAttribute("type") === "application/unimarc") {
			format = "unimarc";
		} else if(node.getAttribute("docs") == "http://www.refman.com/support/risformat_intro.asp"
				|| lowerName.match(/^ris\b/)) {
			format = "ris";
		}

		if(format) foundFormat[format] = name;
	}

	// Loop through again to determine optimal supported format
	for(var i=0; i<RECOGNIZABLE_FORMATS.length; i++) {
		if(foundFormat[RECOGNIZABLE_FORMATS[i]]) {
			this.isSupported = true;
			this.name = foundFormat[RECOGNIZABLE_FORMATS[i]];
			this.translatorID = FORMAT_GUIDS[RECOGNIZABLE_FORMATS[i]];
			return;
		}
	}

	this.isSupported = false;
}

/**
 * A class encapsulating an UnAPI ID
 * @property format {UnAPIFormat} Information regarding the format
 * @property items {Zotero.Item[]} Items corresponding to this ID
 *
 * @constructor
 * @param {String} id The ID contained in an abbr tag
 */
UnAPIID = function(id) {
	this.id = id;
	unAPIIDs[id] = this;
}

UnAPIID.prototype = {
	/**
	 * Gets the item type for this item
	 * @param {Function} callback Callback to be passed itemType when it is known
	 */
	"getItemType":function(callback) {
		var me = this;
		this.getItems(function(items) {
			if(items.length === 0) {
				callback(false);
			} else if(items.length === 1) {
				callback(items[0].itemType);
			} else {
				callback("multiple");
			}
		});
	},

	/**
	 * Gets items associated with this ID
	 * @param {Function} callback Callback to be passed items when they have been retrieved
	 */
	"getItems":function(callback) {
		if(this.items) {
			callback(me.items);
			return;
		}

		var me = this;
		this.items = [];
		this.isSupported(function(isSupported) {
			if(!isSupported) {
				callback([]);
				return;
			}

			Zotero.Utilities.HTTP.doGet(unAPIResolver+"?id="+me.id+"&format="+me.format.name, function(text) {
				var translator = Zotero.loadTranslator("import");
				translator.setTranslator(me.format.translatorID);
				translator.setString(text);
				translator.setHandler("itemDone", function(obj, item) {
					// add item to array
					me.items.push(item);
				});
				translator.setHandler("done", function(obj) {
					// run callback on item array
					callback(me.items);
				});
				try {
					translator.translate();
				} catch(e) {
					Zotero.debug("unAPI: Could not parse "+me.format.name+" metadata for ID "+me.id+": "+e);
					callback(me.items);
				}
			});
		});
	},

	/**
	 * Determines whether Zotero can handle this ID
	 * @param {Function} callback Callback to be passed isSupported when it is known
	 */
	"isSupported":function(callback) {
		if(this.hasOwnProperty("format")) {
			callback(me.format.isSupported);
			return;
		}

		var me = this;

		getDefaultFormat(function() {
			// first try default format, since this won't require >1 HTTP request
			if(defaultFormat.isSupported) {
				me.format = defaultFormat;
				callback(true);
			} else {
				// if no supported default format, try format for this item
				Zotero.Utilities.HTTP.doGet(unAPIResolver+"?id="+me.id, function(text) {
					me.format = new UnAPIFormat(text);
					callback(!!me.format.isSupported);
				});
			}
		});
	}
}

/**
 * This and the x: prefix in the XPath are to work around an issue with pages
 * served as application/xhtml+xml
 *
 * https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript#Implementing_a_default_namespace_for_XML_documents
 */
function nsResolver() {
	return 'http://www.w3.org/1999/xhtml';
}

/**
 * Extracts UnAPIIDs from a document
 * @param {document} A document object from which to extract unAPIIds
 * @return {UnAPIID[]} The unAPI ID objects extracted from the document
 */
function getUnAPIIDs(doc) {
	// look for a resolver
	var newUnAPIResolver = doc.evaluate('//x:link[@rel="unapi-server"]', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
	if(!newUnAPIResolver) return [];
	newUnAPIResolver = newUnAPIResolver.getAttribute("href");
	if(unAPIResolver !== newUnAPIResolver) {
		// if unAPI resolver has changed, clear
		defaultFormat = false;
		unAPIResolver = newUnAPIResolver;
		unAPIIDs = [];
	}

	// look for abbrs
	var abbrs = doc.evaluate('//x:abbr[contains(@class, " unapi-id") or contains(@class, "unapi-id ") or @class="unapi-id"][@title]',
		doc, nsResolver, XPathResult.ANY_TYPE, null);
	var abbr;
	var ids = [];
	while(abbr = abbrs.iterateNext()) {
		var id = abbr.getAttribute("title");
		ids.push(unAPIIDs[id] ? unAPIIDs[id] : new UnAPIID(id));
	}

	return ids;
}

/**
 * Retrieves the list of formats available for all items accessible through this unAPI resolver
 * @param {Function} callback A callback to be passed the format when it is available
 */
function getDefaultFormat(callback) {
	if(defaultFormat) {
		callback(defaultFormat);
	} else {
		Zotero.Utilities.HTTP.doGet(unAPIResolver, function(text) {
			// determine format of this item
			defaultFormat = new UnAPIFormat(text);
			callback(defaultFormat);
		});
	}
}
/**
 * Determines itemType for detection
 */
function determineDetectItemType(ids, supportedId) {
	var id = ids.shift();
	id.isSupported(function(isSupported) {
		if(isSupported && supportedId !== undefined) {
			// If there are multiple items with valid itemTypes, use "multiple"
			Zotero.done("multiple");
		} else if(ids.length) {
			// If IDs remain to be handled, handle the next one
			determineDetectItemType(ids, (isSupported ? id : supportedId));
		} else {
			// If all IDs have been handled, get foundItemType for only supported ID
			supportedId.getItemType(Zotero.done);
		}
	});
}

/**
 * Get all items
 * @param {UnAPIID[]} ids List of UnAPI IDs
 * @param {Function} callback Function to pass item array to when items have been retrieved
 * @param {Zotero.Item[]} items Item array; used for recursive calls
 **/
function getAllItems(ids, callback, items) {
	var id = ids.shift();
	id.getItems(function(retrievedItems) {
		var collectedItems = (items ? items.concat(retrievedItems) : retrievedItems);

		if(ids.length) {
			getAllItems(ids, callback, collectedItems);
		} else {
			callback(collectedItems);
		}
	});
}

function detectWeb(doc, url) {
	// get unAPI IDs
	var ids = getUnAPIIDs(doc);
	if(!ids.length) return false;

	// now we need to see if the server actually gives us bibliographic metadata, and determine the
	// type
	Zotero.wait();

	if(!ids.length === 1) {
		// Only one item, so we will just get its item type
		ids[0].getItemType(Zotero.done);
	} else {
		// Several items. We will need to call determineDetectItemType
		determineDetectItemType(ids);
	}
}

function doWeb(doc, url) {
	var ids = getUnAPIIDs(doc);

	Zotero.wait();

	getAllItems(ids, function(items) {
		// get the domain we're scraping, so we can use it for libraryCatalog
		domain = doc.location.href.match(/https?:\/\/([^/]+)/);

		if(items.length == 1) {
			// If only one item, just complete it
			items[0].libraryCatalog = domain[1];
			items[0].complete();
		} else if(items.length > 0) {
			// If multiple items, extract their titles
			var itemTitles = [];
			for(var i in items) {
				itemTitles[i] = items[i].title;
			}

			// Show item selection dialog
			var chosenItems = Zotero.selectItems(itemTitles);
			if(!chosenItems) Zotero.done(true);

			// Complete items
			for(var i in chosenItems) {
				items[i].libraryCatalog = domain[1];
				items[i].complete();
			}
		}

		Zotero.done();
		return;
	});
}
<|endoftext|>


<commit_before>
'use strict';

var test             = require('selenium-webdriver/testing'),
    application_host = 'http://localhost:3000/',
    By               = require('selenium-webdriver').By,
    expect           = require('chai').expect,
    _                = require('underscore'),
    Promise          = require("bluebird"),
    login_user_func        = require('../lib/login_with_user'),
    register_new_user_func = require('../lib/register_new_user'),
    logout_user_func       = require('../lib/logout_user'),
    open_page_func         = require('../lib/open_page'),
    submit_form_func       = require('../lib/submit_form'),
    add_new_user_func      = require('../lib/add_new_user');

/*
  At this moment there is a bug when anyone can hijack acount if primary email
  is known.

  Scenario to check:
    * create new account
    * make sure we are not login
    * try create new acount for the same email as used in first step
    * System should report that such email address could not be used
      and suggest using forget password feature.

*/

describe('Reuse email from existing acount when creating new company', function(){

  this.timeout(90000);

  test.it('Go', function(done){

    var admin_email;

    // Create new company
    return register_new_user_func({
        application_host : application_host,
    })
    // Login with newly created admin user
    .then(function(data){
        admin_email = data.email;

        console.log('    Login with newly created account '+admin_email);

        return login_user_func({
            application_host : application_host,
            user_email       : admin_email,
        });
    })
    .then(function(data){
      return logout_user_func({
        application_host : application_host,
        driver           : data.driver,
      });
    })
    .then(function(data){
        data.driver.quit().then(function(){ done(); });
        return Promise.resolve(1);
    })
    .then(function(){
        console.log('    Try to create another account with the same email '
          + admin_email);

        return register_new_user_func({
          application_host      : application_host,
          user_email            : admin_email,
          failing_error_message : 'Failed to register user please contact customer service',
        });
    })

    // Close browser;
    .then(function(data){
      done();
//        data.driver.quit().then(function(){ done(); });
    });

  });

});
<commit_msg>Remove dead code<commit_after>
'use strict';

var test             = require('selenium-webdriver/testing'),
    application_host = 'http://localhost:3000/',
    By               = require('selenium-webdriver').By,
    expect           = require('chai').expect,
    _                = require('underscore'),
    Promise          = require("bluebird"),
    login_user_func        = require('../lib/login_with_user'),
    register_new_user_func = require('../lib/register_new_user'),
    logout_user_func       = require('../lib/logout_user'),
    open_page_func         = require('../lib/open_page'),
    submit_form_func       = require('../lib/submit_form'),
    add_new_user_func      = require('../lib/add_new_user');

/*
  At this moment there is a bug when anyone can hijack acount if primary email
  is known.

  Scenario to check:
    * create new account
    * make sure we are not login
    * try create new acount for the same email as used in first step
    * System should report that such email address could not be used
      and suggest using forget password feature.

*/

describe('Reuse email from existing acount when creating new company', function(){

  this.timeout(90000);

  test.it('Go', function(done){

    var admin_email;

    // Create new company
    return register_new_user_func({
        application_host : application_host,
    })
    // Login with newly created admin user
    .then(function(data){
        admin_email = data.email;

        console.log('    Login with newly created account '+admin_email);

        return login_user_func({
            application_host : application_host,
            user_email       : admin_email,
        });
    })
    .then(function(data){
      return logout_user_func({
        application_host : application_host,
        driver           : data.driver,
      });
    })
    .then(function(data){
        data.driver.quit().then(function(){ done(); });
        return Promise.resolve(1);
    })
    .then(function(){
        console.log('    Try to create another account with the same email '
          + admin_email);

        return register_new_user_func({
          application_host      : application_host,
          user_email            : admin_email,
          failing_error_message : 'Failed to register user please contact customer service',
        });
    })

    // Close browser;
    .then(function(data){
      done();
    });

  });

});
<|endoftext|>


<commit_before>export const name = 'urb'
export const version = '9.0.0.26'
<commit_msg>Update version<commit_after>export const name = 'urb'
export const version = '9.0.0.27'
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Viewport = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();
	container.setId( 'viewport' );
	container.setPosition( 'absolute' );

	container.add( new Viewport.Info( editor ) );

	//

	var renderer = null;

	var camera = editor.camera;
	var scene = editor.scene;
	var sceneHelpers = editor.sceneHelpers;

	var objects = [];

	// helpers

	var grid = new THREE.GridHelper( 30, 30, 0x444444, 0x888888 );
	sceneHelpers.add( grid );

	var array = grid.geometry.attributes.color.array;

	for ( var i = 0; i < array.length; i += 60 ) {

		for ( var j = 0; j < 12; j ++ ) {

			array[ i + j ] = 0.26;

		}

	}

	//

	var box = new THREE.Box3();

	var selectionBox = new THREE.BoxHelper();
	selectionBox.material.depthTest = false;
	selectionBox.material.transparent = true;
	selectionBox.visible = false;
	sceneHelpers.add( selectionBox );

	var objectPositionOnDown = null;
	var objectRotationOnDown = null;
	var objectScaleOnDown = null;

	var transformControls = new THREE.TransformControls( camera, container.dom );
	transformControls.addEventListener( 'change', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

			if ( editor.helpers[ object.id ] !== undefined ) {

				editor.helpers[ object.id ].update();

			}

			signals.refreshSidebarObject3D.dispatch( object );

		}

		render();

	} );
	transformControls.addEventListener( 'mouseDown', function () {

		var object = transformControls.object;

		objectPositionOnDown = object.position.clone();
		objectRotationOnDown = object.rotation.clone();
		objectScaleOnDown = object.scale.clone();

		controls.enabled = false;

	} );
	transformControls.addEventListener( 'mouseUp', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			switch ( transformControls.getMode() ) {

				case 'translate':

					if ( ! objectPositionOnDown.equals( object.position ) ) {

						editor.execute( new SetPositionCommand( object, object.position, objectPositionOnDown ) );

					}

					break;

				case 'rotate':

					if ( ! objectRotationOnDown.equals( object.rotation ) ) {

						editor.execute( new SetRotationCommand( object, object.rotation, objectRotationOnDown ) );

					}

					break;

				case 'scale':

					if ( ! objectScaleOnDown.equals( object.scale ) ) {

						editor.execute( new SetScaleCommand( object, object.scale, objectScaleOnDown ) );

					}

					break;

			}

		}

		controls.enabled = true;

	} );

	sceneHelpers.add( transformControls );

	// object picking

	var raycaster = new THREE.Raycaster();
	var mouse = new THREE.Vector2();

	// events

	function getIntersects( point, objects ) {

		mouse.set( ( point.x * 2 ) - 1, - ( point.y * 2 ) + 1 );

		raycaster.setFromCamera( mouse, camera );

		return raycaster.intersectObjects( objects );

	}

	var onDownPosition = new THREE.Vector2();
	var onUpPosition = new THREE.Vector2();
	var onDoubleClickPosition = new THREE.Vector2();

	function getMousePosition( dom, x, y ) {

		var rect = dom.getBoundingClientRect();
		return [ ( x - rect.left ) / rect.width, ( y - rect.top ) / rect.height ];

	}

	function handleClick() {

		if ( onDownPosition.distanceTo( onUpPosition ) === 0 ) {

			var intersects = getIntersects( onUpPosition, objects );

			if ( intersects.length > 0 ) {

				var object = intersects[ 0 ].object;

				if ( object.userData.object !== undefined ) {

					// helper

					editor.select( object.userData.object );

				} else {

					editor.select( object );

				}

			} else {

				editor.select( null );

			}

			render();

		}

	}

	function onMouseDown( event ) {

		event.preventDefault();

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'mouseup', onMouseUp, false );

	}

	function onMouseUp( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'mouseup', onMouseUp, false );

	}

	function onTouchStart( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'touchend', onTouchEnd, false );

	}

	function onTouchEnd( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'touchend', onTouchEnd, false );

	}

	function onDoubleClick( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDoubleClickPosition.fromArray( array );

		var intersects = getIntersects( onDoubleClickPosition, objects );

		if ( intersects.length > 0 ) {

			var intersect = intersects[ 0 ];

			signals.objectFocused.dispatch( intersect.object );

		}

	}

	container.dom.addEventListener( 'mousedown', onMouseDown, false );
	container.dom.addEventListener( 'touchstart', onTouchStart, false );
	container.dom.addEventListener( 'dblclick', onDoubleClick, false );

	// controls need to be added *after* main logic,
	// otherwise controls.enabled doesn't work.

	var controls = new THREE.EditorControls( camera, container.dom );
	controls.addEventListener( 'change', function () {

		signals.cameraChanged.dispatch( camera );

	} );

	// signals

	signals.editorCleared.add( function () {

		controls.center.set( 0, 0, 0 );
		render();

	} );

	signals.transformModeChanged.add( function ( mode ) {

		transformControls.setMode( mode );

	} );

	signals.snapChanged.add( function ( dist ) {

		transformControls.setTranslationSnap( dist );

	} );

	signals.spaceChanged.add( function ( space ) {

		transformControls.setSpace( space );

	} );

	signals.rendererChanged.add( function ( newRenderer ) {

		if ( renderer !== null ) {

			container.dom.removeChild( renderer.domElement );

		}

		renderer = newRenderer;

		renderer.autoClear = false;
		renderer.autoUpdateScene = false;
		renderer.setPixelRatio( window.devicePixelRatio );
		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		container.dom.appendChild( renderer.domElement );

		render();

	} );

	signals.sceneGraphChanged.add( function () {

		render();

	} );

	signals.cameraChanged.add( function () {

		render();

	} );

	signals.objectSelected.add( function ( object ) {

		selectionBox.visible = false;
		transformControls.detach();

		if ( object !== null && object !== scene && object !== camera ) {

			box.setFromObject( object );

			if ( box.isEmpty() === false ) {

				selectionBox.setFromObject( object );
				selectionBox.visible = true;

			}

			transformControls.attach( object );

		}

		render();

	} );

	signals.objectFocused.add( function ( object ) {

		controls.focus( object );

	} );

	signals.geometryChanged.add( function ( object ) {

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

		}

		render();

	} );

	signals.objectAdded.add( function ( object ) {

		object.traverse( function ( child ) {

			objects.push( child );

		} );

	} );

	signals.objectChanged.add( function ( object ) {

		if ( editor.selected === object ) {

			selectionBox.setFromObject( object );

		}

		if ( object instanceof THREE.PerspectiveCamera ) {

			object.updateProjectionMatrix();

		}

		if ( editor.helpers[ object.id ] !== undefined ) {

			editor.helpers[ object.id ].update();

		}

		render();

	} );

	signals.objectRemoved.add( function ( object ) {

		if(object === transformControls.object){
			transformControls.detach();
		}

		object.traverse( function ( child ) {

			objects.splice( objects.indexOf( child ), 1 );

		} );

	} );

	signals.helperAdded.add( function ( object ) {

		objects.push( object.getObjectByName( 'picker' ) );

	} );

	signals.helperRemoved.add( function ( object ) {

		objects.splice( objects.indexOf( object.getObjectByName( 'picker' ) ), 1 );

	} );

	signals.materialChanged.add( function ( material ) {

		render();

	} );

	// fog

	signals.sceneBackgroundChanged.add( function ( backgroundColor ) {

		scene.background.setHex( backgroundColor );

		render();

	} );

	var currentFogType = null;

	signals.sceneFogChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) {

		if ( currentFogType !== fogType ) {

			switch ( fogType ) {

				case 'None':
					scene.fog = null;
					break;
				case 'Fog':
					scene.fog = new THREE.Fog();
					break;
				case 'FogExp2':
					scene.fog = new THREE.FogExp2();
					break;

			}

			currentFogType = fogType;

		}

		if ( scene.fog instanceof THREE.Fog ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.near = fogNear;
			scene.fog.far = fogFar;

		} else if ( scene.fog instanceof THREE.FogExp2 ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.density = fogDensity;

		}

		render();

	} );

	//

	signals.windowResize.add( function () {

		// TODO: Move this out?

		editor.DEFAULT_CAMERA.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		editor.DEFAULT_CAMERA.updateProjectionMatrix();

		camera.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		camera.updateProjectionMatrix();

		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		render();

	} );

	signals.showGridChanged.add( function ( showGrid ) {

		grid.visible = showGrid;
		render();

	} );

	//

	function render() {

		sceneHelpers.updateMatrixWorld();
		scene.updateMatrixWorld();

		renderer.render( scene, camera );

		if ( renderer instanceof THREE.RaytracingRenderer === false ) {

			renderer.render( sceneHelpers, camera );

		}

	}

	return container;

};
<commit_msg>Clean up.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Viewport = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();
	container.setId( 'viewport' );
	container.setPosition( 'absolute' );

	container.add( new Viewport.Info( editor ) );

	//

	var renderer = null;

	var camera = editor.camera;
	var scene = editor.scene;
	var sceneHelpers = editor.sceneHelpers;

	var objects = [];

	// helpers

	var grid = new THREE.GridHelper( 30, 30, 0x444444, 0x888888 );
	sceneHelpers.add( grid );

	var array = grid.geometry.attributes.color.array;

	for ( var i = 0; i < array.length; i += 60 ) {

		for ( var j = 0; j < 12; j ++ ) {

			array[ i + j ] = 0.26;

		}

	}

	//

	var box = new THREE.Box3();

	var selectionBox = new THREE.BoxHelper();
	selectionBox.material.depthTest = false;
	selectionBox.material.transparent = true;
	selectionBox.visible = false;
	sceneHelpers.add( selectionBox );

	var objectPositionOnDown = null;
	var objectRotationOnDown = null;
	var objectScaleOnDown = null;

	var transformControls = new THREE.TransformControls( camera, container.dom );
	transformControls.addEventListener( 'change', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

			if ( editor.helpers[ object.id ] !== undefined ) {

				editor.helpers[ object.id ].update();

			}

			signals.refreshSidebarObject3D.dispatch( object );

		}

		render();

	} );
	transformControls.addEventListener( 'mouseDown', function () {

		var object = transformControls.object;

		objectPositionOnDown = object.position.clone();
		objectRotationOnDown = object.rotation.clone();
		objectScaleOnDown = object.scale.clone();

		controls.enabled = false;

	} );
	transformControls.addEventListener( 'mouseUp', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			switch ( transformControls.getMode() ) {

				case 'translate':

					if ( ! objectPositionOnDown.equals( object.position ) ) {

						editor.execute( new SetPositionCommand( object, object.position, objectPositionOnDown ) );

					}

					break;

				case 'rotate':

					if ( ! objectRotationOnDown.equals( object.rotation ) ) {

						editor.execute( new SetRotationCommand( object, object.rotation, objectRotationOnDown ) );

					}

					break;

				case 'scale':

					if ( ! objectScaleOnDown.equals( object.scale ) ) {

						editor.execute( new SetScaleCommand( object, object.scale, objectScaleOnDown ) );

					}

					break;

			}

		}

		controls.enabled = true;

	} );

	sceneHelpers.add( transformControls );

	// object picking

	var raycaster = new THREE.Raycaster();
	var mouse = new THREE.Vector2();

	// events

	function getIntersects( point, objects ) {

		mouse.set( ( point.x * 2 ) - 1, - ( point.y * 2 ) + 1 );

		raycaster.setFromCamera( mouse, camera );

		return raycaster.intersectObjects( objects );

	}

	var onDownPosition = new THREE.Vector2();
	var onUpPosition = new THREE.Vector2();
	var onDoubleClickPosition = new THREE.Vector2();

	function getMousePosition( dom, x, y ) {

		var rect = dom.getBoundingClientRect();
		return [ ( x - rect.left ) / rect.width, ( y - rect.top ) / rect.height ];

	}

	function handleClick() {

		if ( onDownPosition.distanceTo( onUpPosition ) === 0 ) {

			var intersects = getIntersects( onUpPosition, objects );

			if ( intersects.length > 0 ) {

				var object = intersects[ 0 ].object;

				if ( object.userData.object !== undefined ) {

					// helper

					editor.select( object.userData.object );

				} else {

					editor.select( object );

				}

			} else {

				editor.select( null );

			}

			render();

		}

	}

	function onMouseDown( event ) {

		event.preventDefault();

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'mouseup', onMouseUp, false );

	}

	function onMouseUp( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'mouseup', onMouseUp, false );

	}

	function onTouchStart( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'touchend', onTouchEnd, false );

	}

	function onTouchEnd( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'touchend', onTouchEnd, false );

	}

	function onDoubleClick( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDoubleClickPosition.fromArray( array );

		var intersects = getIntersects( onDoubleClickPosition, objects );

		if ( intersects.length > 0 ) {

			var intersect = intersects[ 0 ];

			signals.objectFocused.dispatch( intersect.object );

		}

	}

	container.dom.addEventListener( 'mousedown', onMouseDown, false );
	container.dom.addEventListener( 'touchstart', onTouchStart, false );
	container.dom.addEventListener( 'dblclick', onDoubleClick, false );

	// controls need to be added *after* main logic,
	// otherwise controls.enabled doesn't work.

	var controls = new THREE.EditorControls( camera, container.dom );
	controls.addEventListener( 'change', function () {

		signals.cameraChanged.dispatch( camera );

	} );

	// signals

	signals.editorCleared.add( function () {

		controls.center.set( 0, 0, 0 );
		render();

	} );

	signals.transformModeChanged.add( function ( mode ) {

		transformControls.setMode( mode );

	} );

	signals.snapChanged.add( function ( dist ) {

		transformControls.setTranslationSnap( dist );

	} );

	signals.spaceChanged.add( function ( space ) {

		transformControls.setSpace( space );

	} );

	signals.rendererChanged.add( function ( newRenderer ) {

		if ( renderer !== null ) {

			container.dom.removeChild( renderer.domElement );

		}

		renderer = newRenderer;

		renderer.autoClear = false;
		renderer.autoUpdateScene = false;
		renderer.setPixelRatio( window.devicePixelRatio );
		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		container.dom.appendChild( renderer.domElement );

		render();

	} );

	signals.sceneGraphChanged.add( function () {

		render();

	} );

	signals.cameraChanged.add( function () {

		render();

	} );

	signals.objectSelected.add( function ( object ) {

		selectionBox.visible = false;
		transformControls.detach();

		if ( object !== null && object !== scene && object !== camera ) {

			box.setFromObject( object );

			if ( box.isEmpty() === false ) {

				selectionBox.setFromObject( object );
				selectionBox.visible = true;

			}

			transformControls.attach( object );

		}

		render();

	} );

	signals.objectFocused.add( function ( object ) {

		controls.focus( object );

	} );

	signals.geometryChanged.add( function ( object ) {

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

		}

		render();

	} );

	signals.objectAdded.add( function ( object ) {

		object.traverse( function ( child ) {

			objects.push( child );

		} );

	} );

	signals.objectChanged.add( function ( object ) {

		if ( editor.selected === object ) {

			selectionBox.setFromObject( object );

		}

		if ( object instanceof THREE.PerspectiveCamera ) {

			object.updateProjectionMatrix();

		}

		if ( editor.helpers[ object.id ] !== undefined ) {

			editor.helpers[ object.id ].update();

		}

		render();

	} );

	signals.objectRemoved.add( function ( object ) {

		if ( object === transformControls.object ) {

			transformControls.detach();

		}

		object.traverse( function ( child ) {

			objects.splice( objects.indexOf( child ), 1 );

		} );

	} );

	signals.helperAdded.add( function ( object ) {

		objects.push( object.getObjectByName( 'picker' ) );

	} );

	signals.helperRemoved.add( function ( object ) {

		objects.splice( objects.indexOf( object.getObjectByName( 'picker' ) ), 1 );

	} );

	signals.materialChanged.add( function ( material ) {

		render();

	} );

	// fog

	signals.sceneBackgroundChanged.add( function ( backgroundColor ) {

		scene.background.setHex( backgroundColor );

		render();

	} );

	var currentFogType = null;

	signals.sceneFogChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) {

		if ( currentFogType !== fogType ) {

			switch ( fogType ) {

				case 'None':
					scene.fog = null;
					break;
				case 'Fog':
					scene.fog = new THREE.Fog();
					break;
				case 'FogExp2':
					scene.fog = new THREE.FogExp2();
					break;

			}

			currentFogType = fogType;

		}

		if ( scene.fog instanceof THREE.Fog ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.near = fogNear;
			scene.fog.far = fogFar;

		} else if ( scene.fog instanceof THREE.FogExp2 ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.density = fogDensity;

		}

		render();

	} );

	//

	signals.windowResize.add( function () {

		// TODO: Move this out?

		editor.DEFAULT_CAMERA.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		editor.DEFAULT_CAMERA.updateProjectionMatrix();

		camera.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		camera.updateProjectionMatrix();

		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		render();

	} );

	signals.showGridChanged.add( function ( showGrid ) {

		grid.visible = showGrid;
		render();

	} );

	//

	function render() {

		sceneHelpers.updateMatrixWorld();
		scene.updateMatrixWorld();

		renderer.render( scene, camera );

		if ( renderer instanceof THREE.RaytracingRenderer === false ) {

			renderer.render( sceneHelpers, camera );

		}

	}

	return container;

};
<|endoftext|>


<commit_before>var async = require("async");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var join = function() {
  return path.join.apply(path, arguments).replace(/\\/g, "/");
}

var aws = require("aws-sdk");
var walk = function(dir) {
  var list = [];
  var files = fs.readdirSync(dir);
  files.forEach(function(f) {
    f = join(dir, f);
    var stat = fs.statSync(f);
    if (stat.isDirectory()) {
      list.push.apply(list, walk(f));
    } else {
      var buffer = fs.readFileSync(f);
      list.push({
        path: f,
        buffer: buffer
      });
    }
  });
  return list;
};

module.exports = function(grunt) {

  var creds = require("../auth.json");
  var config = require("../project.json");

  grunt.config.merge({
    publish: config.s3
  });

  grunt.registerTask("publish", "Pushes the build folder to S3", function(deploy) {

    deploy = deploy || "stage";
    var c = this.async();

    var bucketConfig = config.s3[deploy];
    aws.config.update(creds.s3);

    var s3 = new aws.S3();
    s3.createBucket({
      Bucket: bucketConfig.bucket
    }, function(err) {
      if (err && err.code != "BucketAlreadyOwnedByYou") {
        return console.log(err);
      }
      var uploads = walk("./build");
      async.each(uploads, function(upload, c) {
        var obj = {
          Bucket: bucketConfig.bucket,
          Key: join(bucketConfig.path, upload.path.replace(/^\\?build/, "")),
          Body: upload.buffer,
          ACL: "public-read",
          ContentType: mime.lookup(upload.path)
        };
        //console.log(obj), c();
        console.info("Uploading", obj.Key);
        s3.putObject(obj, c);
      }, function(err) {
        if (err) return console.log(err);
        console.log("All files uploaded successfully");
      })
    });
  });

}<commit_msg>Add GZip and Cache-Control to S3 publish.<commit_after>var async = require("async");
var fs = require("fs");
var path = require("path");
var gzip = require("zlib").gzip;
var mime = require("mime");
var join = function() {
  return path.join.apply(path, arguments).replace(/\\/g, "/");
}

var aws = require("aws-sdk");
var walk = function(dir) {
  var list = [];
  var files = fs.readdirSync(dir);
  files.forEach(function(f) {
    f = join(dir, f);
    var stat = fs.statSync(f);
    if (stat.isDirectory()) {
      list.push.apply(list, walk(f));
    } else {
      var buffer = fs.readFileSync(f);
      list.push({
        path: f,
        buffer: buffer
      });
    }
  });
  return list;
};

module.exports = function(grunt) {

  var creds = require("../auth.json");
  var config = require("../project.json");

  grunt.config.merge({
    publish: config.s3
  });

  grunt.registerTask("publish", "Pushes the build folder to S3", function(deploy) {

    deploy = deploy || "stage";
    var c = this.async();

    var bucketConfig = config.s3[deploy];
    aws.config.update(creds.s3);

    var s3 = new aws.S3();
    s3.createBucket({
      Bucket: bucketConfig.bucket
    }, function(err) {
      if (err && err.code != "BucketAlreadyOwnedByYou") {
        return console.log(err);
      }
      var uploads = walk("./build");
      var gzippable = ["js", "html", "json", "map", "csv", "txt"];
      async.each(uploads, function(upload, c) {
        var obj = {
          Bucket: bucketConfig.bucket,
          Key: join(bucketConfig.path, upload.path.replace(/^\\?build/, "")),
          Body: upload.buffer,
          ACL: "public-read",
          ContentType: mime.lookup(upload.path),
          CacheControl: "public,max-age=3000"
        };
        //if this matches GZip support, compress them before uploading to S3
        var extension = upload.path.split(".").pop();
        if (gzippable.indexOf(extension) > -1) {
          return gzip(upload.buffer, function(err, zipped) {
            if (!err) {
              obj.Body = zipped;
              obj.ContentEncoding = "gzip";
              console.info("Uploading gzipped", obj.Key);
              s3.putObject(obj, c);
            }
          });
        }
        console.info("Uploading", obj.Key);
        s3.putObject(obj, c);
      }, function(err) {
        if (err) return console.log(err);
        console.log("All files uploaded successfully");
      })
    });
  });

}<|endoftext|>


<commit_before>ManageIQ.angular.app.directive('selectpickerForSelectTag', function() {
  return {
    require: 'ngModel',
    link: function (scope, elem, attr, ctrl) {
      scope['form_' + ctrl.$name] = elem[0];

      scope.$watch(attr.ngModel, function() {
        if((ctrl.$modelValue != undefined)) {
          $(scope['form_' + ctrl.$name]).selectpicker({
            dropupAuto: false
          });
          $(scope['form_' + ctrl.$name]).selectpicker('show');
          $(scope['form_' + ctrl.$name]).selectpicker('refresh');
          $(scope['form_' + ctrl.$name]).addClass('span12').selectpicker('setStyle');
        }
      });
      scope.$watch('loaded.bs.select', function() {
        $('.bootstrap-select button').removeAttr('title');
      });
    }
  }
});
<commit_msg>destroy the selectpicker div when it should no longer exist (transferred from ManageIQ/manageiq@d0d988ecf5ba71eb4eadd0d59968a518655c8a8a)<commit_after>ManageIQ.angular.app.directive('selectpickerForSelectTag', function() {
  return {
    require: 'ngModel',
    link: function (scope, elem, attr, ctrl) {
      scope['form_' + ctrl.$name] = elem[0];

      scope.$watch(attr.ngModel, function() {
        if((ctrl.$modelValue != undefined)) {
          $(scope['form_' + ctrl.$name]).selectpicker({
            dropupAuto: false
          });
          $(scope['form_' + ctrl.$name]).selectpicker('show');
          $(scope['form_' + ctrl.$name]).selectpicker('refresh');
          $(scope['form_' + ctrl.$name]).addClass('span12').selectpicker('setStyle');
        }
      });
      scope.$watch('loaded.bs.select', function() {
        $('.bootstrap-select button').removeAttr('title');
      });

      scope.$on('$destroy', function () {
        elem.selectpicker('destroy');
      });
    }
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/hold-button';

export default Ember.Component.extend({
  layout: layout,
  tagName: 'button',
  classNames: ['ember-hold-button'],
  classNameBindings: ['isHolding', 'isComplete', 'type'],

  delay: 500,
  action: null,
  type: 'rectangle',

  timer: null,
  isHolding: false,
  isComplete: false,

  transitionStyle: Ember.computed('delay', function() {
    let delay = this.get('delay');
    let durations = Ember.EnumerableUtils.map([
      '-webkit-transition-duration',
      '-moz-transition-duration',
      'transition-duration'
    ], function(property) {
      return property + ': ' + delay + 'ms';
    }).join(';');

    return Ember.String.htmlSafe(durations);
  }),

  setup: Ember.on('willInsertElement', function() {
    this.registerHandler();
  }),

  registerHandler() {
    this.on('mouseDown', this, this.startTimer);
  },

  startTimer() {
    if (!this.get('timer')) {
      console.log("Starting timer");
      this.set('isComplete', false);
      this.set('isHolding', true);

      this.off('mouseDown');
      this.on('mouseUp', this, this.cancelTimer);
      this.on('mouseLeave', this, this.cancelTimer);

      let timer = Ember.run.later(this, this.timerFinished, this.get('delay'));
      this.set('timer', timer);
    }
  },

  cancelTimer() {
    console.log("Cancelling");
    this.set('isHolding', false);
    Ember.run.cancel(this.get('timer'));
    this.set('timer', null);
    this.off('mouseUp');
    this.off('mouseLeave');
    this.registerHandler();
  },

  timerFinished() {
    console.log("Done");
    if (this.get('isHolding') && !this.get('isComplete')) {
      console.log("Performing action");
      this.sendAction();
      this.set('isComplete', true);
      this.registerHandler();
    }
  }
});
<commit_msg>Remove logging<commit_after>import Ember from 'ember';
import layout from '../templates/components/hold-button';

export default Ember.Component.extend({
  layout: layout,
  tagName: 'button',
  classNames: ['ember-hold-button'],
  classNameBindings: ['isHolding', 'isComplete', 'type'],

  delay: 500,
  action: null,
  type: 'rectangle',

  timer: null,
  isHolding: false,
  isComplete: false,

  transitionStyle: Ember.computed('delay', function() {
    let delay = this.get('delay');
    let durations = Ember.EnumerableUtils.map([
      '-webkit-transition-duration',
      '-moz-transition-duration',
      'transition-duration'
    ], function(property) {
      return property + ': ' + delay + 'ms';
    }).join(';');

    return Ember.String.htmlSafe(durations);
  }),

  setup: Ember.on('willInsertElement', function() {
    this.registerHandler();
  }),

  registerHandler() {
    this.on('mouseDown', this, this.startTimer);
  },

  startTimer() {
    if (!this.get('timer')) {
      this.set('isComplete', false);
      this.set('isHolding', true);

      this.off('mouseDown');
      this.on('mouseUp', this, this.cancelTimer);
      this.on('mouseLeave', this, this.cancelTimer);

      let timer = Ember.run.later(this, this.timerFinished, this.get('delay'));
      this.set('timer', timer);
    }
  },

  cancelTimer() {
    this.set('isHolding', false);
    Ember.run.cancel(this.get('timer'));
    this.set('timer', null);
    this.off('mouseUp');
    this.off('mouseLeave');
    this.registerHandler();
  },

  timerFinished() {
    if (this.get('isHolding') && !this.get('isComplete')) {
      this.sendAction();
      this.set('isComplete', true);
      this.registerHandler();
    }
  }
});
<|endoftext|>


<commit_before><commit_msg>add instructions<commit_after>// Problem: Quicksort                                                *
//   *                                                                    *
//   *  Prompt: Given an unsorted array of numbers,                       *
//   *          return a sorted array using Quicksort sort.               *
//   *                                                                    *
//   *  Input:  An unsorted array                                         *
//   *  Output: A sorted array                                            *
//   *                                                                    *
//   *  Example: input = [3,9,1,4,7] , output = [1,3,4,7,9]               *

<|endoftext|>


<commit_before>scratchpad.modules.define("research", {
	getImages: function(query) {
		var imageSearch;
		function searchComplete() {
			var contentDiv = document.querySelector(".images-results");
			contentDiv.innerHTML = '';
			if (!imageSearch.results && imageSearch.results.length < 0) {
				return;
			}
			var results = imageSearch.results;
			for (var i = 0; i < results.length; i++) {
				var result = results[i];
				var imgContainer = document.createElement('div');
				var title = document.createElement('div');
				imgContainer.classList.add("gimage-result-container");
				title.classList.add("gimage-result-title");
				title.classList.add("themeable");
				title.innerHTML = result.titleNoFormatting;
				var newImg = document.createElement('img');
				// a lot of the images don't exist any more, get rid of them
				newImg.onerror = function(e) {
					newImg.src = result.url;
					imgContainer.appendChild(title);
					imgContainer.appendChild(newImg);
					contentDiv.appendChild(imgContainer);
				}
			}
		}
		imageSearch = new google.search.ImageSearch();
		imageSearch.setSearchCompleteCallback(this, searchComplete, null);
		imageSearch.execute(query);
	},
	show: function(data) {
		var _ = this;
		$(".infocard-content").html("");
		var infocard = new InfoCard({
			query: data,
			container: document.querySelector(".infocard-content"),
			onEmpty: function(container) {
				container.innerHTML="
No results found.
"
			},
			onError: function(container) {
				container.innerHTML="
An error occured
"
			},
			appReferName: "scratchpad",
			onHeadingClick: function(e) {
				if (e.target.tagName == "H2") { //category names for meanings
					_.show(e.target.innerHTML);
				} else { //headers that will just show the same results when clicked
					window.open("https://duckduckgo.com/?q=" + encodeURIComponent(e.target.innerHTML),'_blank');
				}
			},
			horizontalScrolling: ".InfoCard-tabs",
			classNames: {
				"category-item": "themeable",
			},
			protocol: window.location.protocol.replace(":","")
		});
		$(".infocard-shell").show();
		this.getImages(data);
	},
	generateImage: function(input) {
		var imagetemplate = ""
		scratchpad.caret.pasteHtmlAtCaret(imagetemplate, false);
	},
	imageInsertFlow: function(e) {
		if(e.target.hasAttribute("noinsert")) {
			return;
		}
		var _ = this;
		var position = $(e.target).offset();
		var shellposition = $(".infocard-shell").offset();
		var scroll = $(".infocard-shell").scrollTop();
		$(".research-insert-button").css({left: position.left - shellposition.left, top: position.top - shellposition.top + scroll });
		$(".research-insert-button").show();
		$(".research-insert-button").off();
		$(".research-insert-button").on("mousedown", function() {
			_.generateImage(e.target.src);
		});
	},
	init: function() {
		var _ = this;
		this.imageInsertFlow = this.imageInsertFlow.bind(this);
		$(".infocard-shell").append('

');
		$(".infocard-shell").on("mouseover", "img", function(e) {
			_.imageInsertFlow(e);
		});
		$(document.body).on("click", function() {
			$(".research-insert-button").hide();
		});
		$("#research-close-button").on("click", function() {
			$('.infocard-shell').hide();
		})
		scratchpad.keybindings.addBinding("mod+option+shift+i", function() {
			scratchpad.research.show(window.getSelection());
		});
		scratchpad.keybindings.addBinding("esc", function() {
			$(".infocard-shell").hide();
		});
	}
});
<commit_msg>bug fix<commit_after>scratchpad.modules.define("research", {
	getImages: function(query) {
		var imageSearch;
		function searchComplete() {
			var contentDiv = document.querySelector(".images-results");
			contentDiv.innerHTML = '';
			if (!imageSearch.results && imageSearch.results.length < 0) {
				return;
			}
			var results = imageSearch.results;
			for (var i = 0; i < results.length; i++) {
				var result = results[i];
				var imgContainer = document.createElement('div');
				var title = document.createElement('div');
				imgContainer.classList.add("gimage-result-container");
				title.classList.add("gimage-result-title");
				title.classList.add("themeable");
				title.innerHTML = result.titleNoFormatting;
				var newImg = document.createElement('img');
				// a lot of the images don't exist any more, get rid of them
				newImg.onerror = function(e) {
					newImg.remove();
				}
				newImg.src = result.url;
				imgContainer.appendChild(title);
				imgContainer.appendChild(newImg);
				contentDiv.appendChild(imgContainer);
			}
		}
		imageSearch = new google.search.ImageSearch();
		imageSearch.setSearchCompleteCallback(this, searchComplete, null);
		imageSearch.execute(query);
	},
	show: function(data) {
		var _ = this;
		$(".infocard-content").html("");
		var infocard = new InfoCard({
			query: data,
			container: document.querySelector(".infocard-content"),
			onEmpty: function(container) {
				container.innerHTML="
No results found.
"
			},
			onError: function(container) {
				container.innerHTML="
An error occured
"
			},
			appReferName: "scratchpad",
			onHeadingClick: function(e) {
				if (e.target.tagName == "H2") { //category names for meanings
					_.show(e.target.innerHTML);
				} else { //headers that will just show the same results when clicked
					window.open("https://duckduckgo.com/?q=" + encodeURIComponent(e.target.innerHTML),'_blank');
				}
			},
			horizontalScrolling: ".InfoCard-tabs",
			classNames: {
				"category-item": "themeable",
			},
			protocol: window.location.protocol.replace(":","")
		});
		$(".infocard-shell").show();
		this.getImages(data);
	},
	generateImage: function(input) {
		var imagetemplate = ""
		scratchpad.caret.pasteHtmlAtCaret(imagetemplate, false);
	},
	imageInsertFlow: function(e) {
		if(e.target.hasAttribute("noinsert")) {
			return;
		}
		var _ = this;
		var position = $(e.target).offset();
		var shellposition = $(".infocard-shell").offset();
		var scroll = $(".infocard-shell").scrollTop();
		$(".research-insert-button").css({left: position.left - shellposition.left, top: position.top - shellposition.top + scroll });
		$(".research-insert-button").show();
		$(".research-insert-button").off();
		$(".research-insert-button").on("mousedown", function() {
			_.generateImage(e.target.src);
		});
	},
	init: function() {
		var _ = this;
		this.imageInsertFlow = this.imageInsertFlow.bind(this);
		$(".infocard-shell").append('

');
		$(".infocard-shell").on("mouseover", "img", function(e) {
			_.imageInsertFlow(e);
		});
		$(document.body).on("click", function() {
			$(".research-insert-button").hide();
		});
		$("#research-close-button").on("click", function() {
			$('.infocard-shell').hide();
		})
		scratchpad.keybindings.addBinding("mod+option+shift+i", function() {
			scratchpad.research.show(window.getSelection());
		});
		scratchpad.keybindings.addBinding("esc", function() {
			$(".infocard-shell").hide();
		});
	}
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var draw;

/**
 *
 * @type {*|exports|module.exports}
 */
var advancedInfo;

/**
 *
 * @type {*|exports|module.exports}
 */
var cloud;

/**
 *
 * @type {*|exports|module.exports}
 */
var print;

/**
 *
 * @type {*|exports|module.exports}
 */
var switchLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var setBaseLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var legend;

/**
 *
 * @type {*|exports|module.exports}
 */
var meta;

/**
 *
 * @type {array}
 */
var metaDataKeys;

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 *
 * @type {array}
 */
var urlVars = urlparser.urlVars;

/**
 *
 * @type {showdown.Converter}
 */
var toHtml = require('showdown').Converter();

require('arrive');

var backboneEvents;

var pushState;
var layerTree;
var layers;
var infoClick;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        draw = o.draw;
        advancedInfo = o.advancedInfo;
        cloud = o.cloud;
        print = o.print;
        switchLayer = o.switchLayer;
        setBaseLayer = o.setBaseLayer;
        legend = o.legend;
        meta = o.meta;
        pushState = o.pushState;
        layerTree = o.layerTree;
        layers = o.layers;
        infoClick = o.infoClick;
        backboneEvents = o.backboneEvents;
        return this;
    },
    init: function (str) {
        metaDataKeys = meta.getMetaDataKeys();

        cloud.get().on("dragend", function () {
            pushState.init();
        });
        cloud.get().on("moveend", function () {
            pushState.init();
        });

        $("#draw-btn").on("click", function () {
            draw.control();
        });

        $("#advanced-info-btn").on("click", function () {
            advancedInfo.control();
        });

        $("#info-modal button").on("click", function () {
            $("#info-modal").hide();
        });

        backboneEvents.get().on("ready:meta", function () {
            if ($(document).width() > 767) {
                setTimeout(
                    function () {
                        $(".navbar-toggle").trigger("click");
                    }, 50
                );
            }
            layerTree.init();
            layers.init();
            $("#loadscreen").hide();
        });

        backboneEvents.get().on("off:advancedInfo on:drawing", function () {
            console.info("Stopping advanced info");
            advancedInfo.off();
        });

        backboneEvents.get().on("off:drawing on:advancedInfo", function () {
            console.info("Stopping drawing");
            draw.off();
        });

        // Info click
        backboneEvents.get().on("on:infoClick", function () {
            console.info("Activating infoClick");
            infoClick.active(true);
        });

        backboneEvents.get().on("off:infoClick", function () {
            console.info("Deactivating infoClick");
            infoClick.active(false);
        });

        backboneEvents.get().on("reset:infoClick", function () {
            console.info("Resetting infoClick");
            infoClick.reset();
        });

        // Print
        $("#print-btn").on("click", function () {
            print.activate();
            $("#get-print-fieldset").prop("disabled", true);
        });

        $("#start-print-btn").on("click", function () {
            print.print();
            $(this).button('loading');
            $("#get-print-fieldset").prop("disabled", true);
        });

        backboneEvents.get().on("off:print", function () {
            print.off();
        });

        backboneEvents.get().on("end:print", function (response) {
            $("#get-print-fieldset").prop("disabled", false);
            $("#download-pdf, #open-pdf").attr("href", "/static/tmp/print/pdf/" + response.key + ".pdf");
            $("#download-pdf").attr("download", response.key);
            $("#open-html").attr("href", response.url);
            $("#start-print-btn").button('reset');
        });

        // HACK. Arrive.js seems to mess up Wkhtmltopdf, so we don't bind events on print HTML page.
        if (!urlVars.px && !urlVars.py) {
            $(document).arrive('[data-gc2-id]', function () {
                $(this).change(function (e) {
                    switchLayer.init($(this).data('gc2-id'), $(this).context.checked);
                    e.stopPropagation();
                });
            });
            $(document).arrive('[data-gc2-base-id]', function () {
                $(this).on("click", function (e) {
                    setBaseLayer.init($(this).data('gc2-base-id'));
                    e.stopPropagation();
                    $(this).css("background-color", "white");
                });
            });
            $(document).arrive('[data-toggle="tooltip"]', function () {
                $(this).tooltip()
            });
            $(document).arrive('.info-label', function () {
                $(this).on("click", function (e) {
                    var t = ($(this).prev().children("input").data('gc2-id')), html;
                    html = (metaDataKeys[t].meta !== null && typeof $.parseJSON(metaDataKeys[t].meta) !== null && typeof $.parseJSON(metaDataKeys[t].meta).meta_desc !== "undefined" && $.parseJSON(metaDataKeys[t].meta).meta_desc !== "") ? toHtml.makeHtml($.parseJSON(metaDataKeys[t].meta).meta_desc) : metaDataKeys[t].f_table_abstract;
                    $("#info-modal").show();
                    $("#info-modal .modal-title").html(metaDataKeys[t].f_table_title || metaDataKeys[t].f_table_name);
                    $("#info-modal .modal-body").html(html);
                    legend.init([t], "#info-modal-legend");
                    e.stopPropagation();
                });

            });
        }
    }
};<commit_msg>no message<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var draw;

/**
 *
 * @type {*|exports|module.exports}
 */
var advancedInfo;

/**
 *
 * @type {*|exports|module.exports}
 */
var cloud;

/**
 *
 * @type {*|exports|module.exports}
 */
var print;

/**
 *
 * @type {*|exports|module.exports}
 */
var switchLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var setBaseLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var legend;

/**
 *
 * @type {*|exports|module.exports}
 */
var meta;

/**
 *
 * @type {array}
 */
var metaDataKeys;

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 *
 * @type {array}
 */
var urlVars = urlparser.urlVars;

/**
 *
 * @type {showdown.Converter}
 */
var showdown = require('showdown');
var converter = new showdown.Converter();

require('arrive');

var backboneEvents;

var pushState;
var layerTree;
var layers;
var infoClick;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        draw = o.draw;
        advancedInfo = o.advancedInfo;
        cloud = o.cloud;
        print = o.print;
        switchLayer = o.switchLayer;
        setBaseLayer = o.setBaseLayer;
        legend = o.legend;
        meta = o.meta;
        pushState = o.pushState;
        layerTree = o.layerTree;
        layers = o.layers;
        infoClick = o.infoClick;
        backboneEvents = o.backboneEvents;
        return this;
    },
    init: function (str) {
        metaDataKeys = meta.getMetaDataKeys();

        cloud.get().on("dragend", function () {
            pushState.init();
        });
        cloud.get().on("moveend", function () {
            pushState.init();
        });

        $("#draw-btn").on("click", function () {
            draw.control();
        });

        $("#advanced-info-btn").on("click", function () {
            advancedInfo.control();
        });

        $("#info-modal button").on("click", function () {
            $("#info-modal").hide();
        });

        backboneEvents.get().on("ready:meta", function () {
            if ($(document).width() > 767) {
                setTimeout(
                    function () {
                        $(".navbar-toggle").trigger("click");
                    }, 50
                );
            }
            layerTree.init();
            layers.init();
            $("#loadscreen").hide();
        });

        backboneEvents.get().on("off:advancedInfo on:drawing", function () {
            console.info("Stopping advanced info");
            advancedInfo.off();
        });

        backboneEvents.get().on("off:drawing on:advancedInfo", function () {
            console.info("Stopping drawing");
            draw.off();
        });

        // Info click
        backboneEvents.get().on("on:infoClick", function () {
            console.info("Activating infoClick");
            infoClick.active(true);
        });

        backboneEvents.get().on("off:infoClick", function () {
            console.info("Deactivating infoClick");
            infoClick.active(false);
        });

        backboneEvents.get().on("reset:infoClick", function () {
            console.info("Resetting infoClick");
            infoClick.reset();
        });

        // Print
        $("#print-btn").on("click", function () {
            print.activate();
            $("#get-print-fieldset").prop("disabled", true);
        });

        $("#start-print-btn").on("click", function () {
            print.print();
            $(this).button('loading');
            $("#get-print-fieldset").prop("disabled", true);
        });

        backboneEvents.get().on("off:print", function () {
            print.off();
        });

        backboneEvents.get().on("end:print", function (response) {
            $("#get-print-fieldset").prop("disabled", false);
            $("#download-pdf, #open-pdf").attr("href", "/static/tmp/print/pdf/" + response.key + ".pdf");
            $("#download-pdf").attr("download", response.key);
            $("#open-html").attr("href", response.url);
            $("#start-print-btn").button('reset');
        });

        // HACK. Arrive.js seems to mess up Wkhtmltopdf, so we don't bind events on print HTML page.
        if (!urlVars.px && !urlVars.py) {
            $(document).arrive('[data-gc2-id]', function () {
                $(this).change(function (e) {
                    switchLayer.init($(this).data('gc2-id'), $(this).context.checked);
                    e.stopPropagation();
                });
            });
            $(document).arrive('[data-gc2-base-id]', function () {
                $(this).on("click", function (e) {
                    setBaseLayer.init($(this).data('gc2-base-id'));
                    e.stopPropagation();
                    $(this).css("background-color", "white");
                });
            });
            $(document).arrive('[data-toggle="tooltip"]', function () {
                $(this).tooltip()
            });
            $(document).arrive('.info-label', function () {
                $(this).on("click", function (e) {
                    var t = ($(this).prev().children("input").data('gc2-id')), html;
                    html = (metaDataKeys[t].meta !== null && $.parseJSON(metaDataKeys[t].meta) !== null && typeof $.parseJSON(metaDataKeys[t].meta).meta_desc !== "undefined" && $.parseJSON(metaDataKeys[t].meta).meta_desc !== "") ? converter.makeHtml($.parseJSON(metaDataKeys[t].meta).meta_desc) : metaDataKeys[t].f_table_abstract;
                    $("#info-modal").show();
                    $("#info-modal .modal-title").html(metaDataKeys[t].f_table_title || metaDataKeys[t].f_table_name);
                    $("#info-modal .modal-body").html(html);
                    legend.init([t], "#info-modal-legend");
                    e.stopPropagation();
                });

            });
        }
    }
};<|endoftext|>


<commit_before>/* global angular */
'use strict';

var traverson = require('traverson');

var ng;
if (typeof angular !== 'undefined') {
  // angular is defined globally, use this
  ng = angular;
} else {
  // angular is not defined globally, try to require it
  ng = require('angular');
  if (typeof ng.module !== 'function') {
    throw new Error('angular has either to be provided globally or made ' +
        'available as a shim for browserify. (Also, if the angular module on ' +
        'npm would actually be a proper CommonJS module, this error ' +
        'wouldn\'t be a thing.)');
  }
}

var traversonAngular = ng.module('traverson', []);

traversonAngular.factory('traverson', function traversonFactory($q) {
  var Builder = traverson._Builder;
  var originalMethods = {
    get: Builder.prototype.get,
    getResource: Builder.prototype.getResource,
    getUri: Builder.prototype.getUri,
    post: Builder.prototype.post,
    put: Builder.prototype.put,
    patch: Builder.prototype.patch,
    del: Builder.prototype.del,
  };

  function promisify(that, originalMethod, callback) {
    var deferred = $q.defer();
    originalMethod.call(that, function(err, result, uri) {
      if (err) {
        err.result = result;
        err.uri = uri;
        deferred.reject(err);
      } else {
        deferred.resolve(result);
      }
    });
    return deferred.promise;
  }

  Builder.prototype.get = function(callback) {
    return promisify(this, originalMethods.get, callback);
  };

  Builder.prototype.getResource = function(callback) {
    return promisify(this, originalMethods.getResource, callback);
  };

  Builder.prototype.getUri = function(callback) {
    return promisify(this, originalMethods.getUri, callback);
  };

  Builder.prototype.post = function(callback) {
    return promisify(this, originalMethods.post, callback);
  };

  Builder.prototype.put = function(callback) {
    return promisify(this, originalMethods.put, callback);
  };

  Builder.prototype.patch = function(callback) {
    return promisify(this, originalMethods.patch, callback);
  };

  Builder.prototype.del = function(callback) {
    return promisify(this, originalMethods.del, callback);
  };

  return traverson;
});

module.exports = traversonAngular;
<commit_msg>fix post/put calls and adjust promises to accept parameters<commit_after>/* global angular */
'use strict';

var traverson = require('traverson');

var ng;
if (typeof angular !== 'undefined') {
  // angular is defined globally, use this
  ng = angular;
} else {
  // angular is not defined globally, try to require it
  ng = require('angular');
  if (typeof ng.module !== 'function') {
    throw new Error('angular has either to be provided globally or made ' +
        'available as a shim for browserify. (Also, if the angular module on ' +
        'npm would actually be a proper CommonJS module, this error ' +
        'wouldn\'t be a thing.)');
  }
}

var traversonAngular = ng.module('traverson', []);

traversonAngular.factory('traverson', function traversonFactory($q) {
  var Builder = traverson._Builder;
  var originalMethods = {
    get: Builder.prototype.get,
    getResource: Builder.prototype.getResource,
    getUri: Builder.prototype.getUri,
    post: Builder.prototype.post,
    put: Builder.prototype.put,
    patch: Builder.prototype.patch,
    del: Builder.prototype.del,
  };

  function promisify(that, originalMethod, argsArray) {
    var deferred = $q.defer();
    var argsArray = argsArray || [];

    var callback = function(err, result, uri) {
      if (err) {
        err.result = result;
        err.uri = uri;
        deferred.reject(err);
      } else {
        deferred.resolve(result);
      }
    };

    argsArray.push(callback);

    originalMethod.apply(that, argsArray);
    return deferred.promise;
  }

  Builder.prototype.get = function() {
    return promisify(this, originalMethods.get);
  };

  Builder.prototype.getResource = function() {
    return promisify(this, originalMethods.getResource);
  };

  Builder.prototype.getUri = function() {
    return promisify(this, originalMethods.getUri);
  };

  Builder.prototype.post = function(body) {
    return promisify(this, originalMethods.post, [body]);
  };

  Builder.prototype.put = function(body) {
    return promisify(this, originalMethods.put, [body]);
  };

  Builder.prototype.patch = function(body) {
    return promisify(this, originalMethods.patch, [body]);
  };

  Builder.prototype.del = function() {
    return promisify(this, originalMethods.del);
  };

  return traverson;
});

module.exports = traversonAngular;
<|endoftext|>


<commit_before>/**
  This addition handles auto linking of text. When included, it will parse out links and create
  a hrefs for them.
**/
var urlReplacerArgs = {
  matcher: /^((?:https?:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/gm,
  spaceOrTagBoundary: true,

  emitter: function(matches) {
    var url = matches[1],
        displayUrl = url;

    // Don't autolink a markdown link to something
    if (url.match(/\]\[\d$/)) { return; }

    // If we improperly caught a markdown link abort
    if (url.match(/\(http/)) { return; }

    if (url.match(/^www/)) { url = "http://" + url; }
    return ['a', {href: url}, displayUrl];
  }
};

Discourse.Dialect.inlineRegexp(_.merge({start: 'http'}, urlReplacerArgs));
Discourse.Dialect.inlineRegexp(_.merge({start: 'www'}, urlReplacerArgs));
<commit_msg>FIX: Remove g and m flags from autolink regex<commit_after>/**
  This addition handles auto linking of text. When included, it will parse out links and create
  a hrefs for them.
**/
var urlReplacerArgs = {
  matcher: /^((?:https?:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.])(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/,
  spaceOrTagBoundary: true,

  emitter: function(matches) {
    var url = matches[1],
        displayUrl = url;

    // Don't autolink a markdown link to something
    if (url.match(/\]\[\d$/)) { return; }

    // If we improperly caught a markdown link abort
    if (url.match(/\(http/)) { return; }

    if (url.match(/^www/)) { url = "http://" + url; }
    return ['a', {href: url}, displayUrl];
  }
};

Discourse.Dialect.inlineRegexp(_.merge({start: 'http'}, urlReplacerArgs));
Discourse.Dialect.inlineRegexp(_.merge({start: 'www'}, urlReplacerArgs));
<|endoftext|>


<commit_before>import {parseVariables} from 'bunsen-core/utils'
import Ember from 'ember'
const {get} = Ember
import computed from 'ember-computed-decorators'
import _ from 'lodash'
import AbstractInput from './abstract-input'
import layout from 'ember-frost-bunsen/templates/components/frost-bunsen-input-link'

function getAttr (attrs, name) {
  if (!attrs) {
    return undefined
  }

  if (name.indexOf('.') === -1) {
    return get(attrs, `${name}.value`)
  }

  const segments = name.split('.')
  const firstSegment = segments.splice(0, 1)
  const remainingPath = segments.join('.')

  return get(attrs, `${firstSegment}.value.${remainingPath}`)
}

function getOption (attrs, optionName, formValue, fallback = '') {
  if (!attrs) {
    return undefined
  }

  const bunsenId = getAttr(attrs, 'bunsenId')
  const configOption = getAttr(attrs, `cellConfig.renderer.${optionName}`)
  const value = getAttr(attrs, 'value')

  if (!configOption) {
    return value
  }

  const mutableFormValue = formValue ? formValue.asMutable({deep: true}) : {}

  return parseVariables(mutableFormValue, configOption, bunsenId, true) || fallback
}

export default AbstractInput.extend({
  // == Component Properties ===================================================

  classNames: [
    'frost-bunsen-input-link',
    'frost-field'
  ],

  layout,

  // == Computed Properties ====================================================

  @computed('cellConfig', 'value')
  route (cellConfig) {
    return _.get(cellConfig, 'renderer.route')
  },

  // == Functions ==============================================================

  formValueChanged (newValue) {
    if (this.get('isDestroyed') || this.get('isDestroying')) {
      return
    }

    const cellConfig = this.get('cellConfig')
    const rendererLabel = _.get(cellConfig, 'renderer.label')
    const rendererUrl = _.get(cellConfig, 'renderer.url')
    const labelContainsReferences = rendererLabel && rendererLabel.indexOf('${') !== -1
    const urlContainsReferences = rendererUrl && rendererUrl.indexOf('${') !== -1

    if (!labelContainsReferences && !urlContainsReferences) {
      return
    }

    this.set('formValue', newValue)
  },

  // == Events ================================================================

  init () {
    this._super(...arguments)
    this.registerForFormValueChanges(this)
  },

  didReceiveAttrs ({newAttrs, oldAttrs}) {
    const formValue = this.get('formValue')
    const props = {}
    const newDefaultLabel = getAttr(newAttrs, 'cellConfig.renderer.defaultLabel')
    const newLabel = getOption(newAttrs, 'label', formValue, newDefaultLabel)
    const newUrl = getOption(newAttrs, 'url', formValue)
    const oldDefaultLabel = getAttr(oldAttrs, 'cellConfig.renderer.defaultLabel')
    const oldLabel = getOption(oldAttrs, 'label', formValue, oldDefaultLabel)
    const oldUrl = getOption(oldAttrs, 'url', formValue)
    const newLinkLabel = newLabel || 'Link'

    if (this.get('linkLabel') !== newLinkLabel) {
      props.linkLabel = newLinkLabel
    }

    if (this.get('url') !== newUrl) {
      props.url = newUrl
    }

    if (Object.keys(props).length !== 0) {
      this.setProperties(props)
    }
  },

  // == Actions ===============================================================

  actions: {
    handleClick (e) {
      // Prevent link click event from bubbling which causes problems when it is
      // rendered in certain parent components such as a frost-list
      e.stopPropagation()
    }
  }
})
<commit_msg>Update link.js<commit_after>import {parseVariables} from 'bunsen-core/utils'
import Ember from 'ember'
const {get} = Ember
import computed from 'ember-computed-decorators'
import _ from 'lodash'
import AbstractInput from './abstract-input'
import layout from 'ember-frost-bunsen/templates/components/frost-bunsen-input-link'

function getAttr (attrs, name) {
  if (!attrs) {
    return undefined
  }

  if (name.indexOf('.') === -1) {
    return get(attrs, `${name}.value`)
  }

  const segments = name.split('.')
  const firstSegment = segments.splice(0, 1)
  const remainingPath = segments.join('.')

  return get(attrs, `${firstSegment}.value.${remainingPath}`)
}

function getOption (attrs, optionName, formValue, fallback = '') {
  if (!attrs) {
    return undefined
  }

  const bunsenId = getAttr(attrs, 'bunsenId')
  const configOption = getAttr(attrs, `cellConfig.renderer.${optionName}`)
  const value = getAttr(attrs, 'value')

  if (!configOption) {
    return value
  }

  const mutableFormValue = formValue ? formValue.asMutable({deep: true}) : {}

  return parseVariables(mutableFormValue, configOption, bunsenId, true) || fallback
}

export default AbstractInput.extend({
  // == Component Properties ===================================================

  classNames: [
    'frost-bunsen-input-link',
    'frost-field'
  ],

  layout,

  // == Computed Properties ====================================================

  @computed('cellConfig', 'value')
  route (cellConfig) {
    return _.get(cellConfig, 'renderer.route')
  },

  // == Functions ==============================================================

  formValueChanged (newValue) {
    if (this.get('isDestroyed') || this.get('isDestroying')) {
      return
    }

    const cellConfig = this.get('cellConfig')
    const rendererLabel = _.get(cellConfig, 'renderer.label')
    const rendererUrl = _.get(cellConfig, 'renderer.url')
    const labelContainsReferences = rendererLabel && rendererLabel.indexOf('${') !== -1
    const urlContainsReferences = rendererUrl && rendererUrl.indexOf('${') !== -1

    if (!labelContainsReferences && !urlContainsReferences) {
      return
    }

    this.set('formValue', newValue)
  },

  // == Events ================================================================

  init () {
    this._super(...arguments)
    this.registerForFormValueChanges(this)
  },

  didReceiveAttrs ({newAttrs, oldAttrs}) {
    const formValue = this.get('formValue')
    const props = {}
    const newDefaultLabel = getAttr(newAttrs, 'cellConfig.renderer.defaultLabel')
    const newLabel = getOption(newAttrs, 'label', formValue, newDefaultLabel)
    const newUrl = getOption(newAttrs, 'url', formValue)
    const newLinkLabel = newLabel || 'Link'

    if (this.get('linkLabel') !== newLinkLabel) {
      props.linkLabel = newLinkLabel
    }

    if (this.get('url') !== newUrl) {
      props.url = newUrl
    }

    if (Object.keys(props).length !== 0) {
      this.setProperties(props)
    }
  },

  // == Actions ===============================================================

  actions: {
    handleClick (e) {
      // Prevent link click event from bubbling which causes problems when it is
      // rendered in certain parent components such as a frost-list
      e.stopPropagation()
    }
  }
})
<|endoftext|>