<commit_before>// @flow
import ClientApi from 'daedalus-client-api';
import { action } from 'mobx';
import Wallet from '../domain/Wallet';
import WalletTransaction from '../domain/WalletTransaction';
import type {
  createWalletRequest,
  getTransactionsRequest,
  createTransactionRequest,
  walletRestoreRequest
} from './index';
import { user } from './fixtures';
import User from '../domain/User';
import Profile from '../domain/Profile';

const notYetImplemented = () => new Promise((resolve, reject) => reject(new Error('Api method not yet implemented')));

export default class CardanoClientApi {

  login() {
    // TODO: Implement when backend is ready for it
    return new Promise((resolve) => resolve(true));
  }

  getUser() {
    return new Promise((resolve) => {
      setTimeout(action(() => {
        resolve(new User(user.id, new Profile(user.profile)));
      }), 0);
    });
  }

  async getWallets() {
    const response = await ClientApi.getWallets();
    return response.map(data => this._createWalletFromData(data));
  }

  async getTransactions({ walletId, searchTerm, skip, limit }: getTransactionsRequest) {
    const history = await ClientApi.searchHistory(walletId, searchTerm, skip, limit);
    return new Promise((resolve) => resolve({
      transactions: history[0].map(data => this._createTransactionFromData(data, walletId)),
      total: history[1]
    }));
  }

  createUser() {
    return notYetImplemented();
  }

  async createWallet(request: createWalletRequest) {
    const response = await ClientApi.newWallet('CWTPersonal', 'ADA', request.name, request.mnemonic);
    return this._createWalletFromData(response);
  }

  async createTransaction(request: createTransactionRequest) {
    const { sender, receiver, amount, currency, title } = request;
    let { description } = request;
    if (!description) description = 'no description provided';
    const response = await ClientApi.sendExtended(sender, receiver, amount, currency, title, description);
    return this._createTransactionFromData(response);
  }

  isValidAddress(currency: string, address: string) {
    return ClientApi.isValidAddress(currency, address);
  }

  updateProfileField() {
    return notYetImplemented();
  }

  @action _createWalletFromData(data) {
    return new Wallet({
      id: data.cwAddress,
      address: data.cwAddress,
      amount: data.cwAmount.getCoin,
      type: data.cwMeta.cwType,
      currency: data.cwMeta.cwCurrency,
      name: data.cwMeta.cwName,
    });
  }

  @action _createTransactionFromData(data) {
    const isOutgoing = data.ctType.tag === 'CTOut';
    const coins = data.ctAmount.getCoin;
    let { ctmTitle, ctmDescription, ctmDate } = data.ctType.contents;
    if (!ctmTitle) ctmTitle = 'Incoming Money';
    return new WalletTransaction({
      id: data.ctId,
      title: ctmTitle,
      type: isOutgoing ? 'adaExpend' : 'adaIncome',
      currency: 'ada',
      amount: isOutgoing ? -1 * coins : coins,
      date: new Date(ctmDate * 1000),
      description: ctmDescription,
    });
  }

  getWalletRecoveryPhrase() {
    return new Promise((resolve) => resolve(ClientApi.generateMnemonic().split(' ')));
  }

  async restoreWallet({ recoveryPhrase }: walletRestoreRequest) {
    return await ClientApi.restoreWallet(recoveryPhrase);
  }
}
<commit_msg>WIP - add wallet name to wallet restore<commit_after>// @flow
import ClientApi from 'daedalus-client-api';
import { action } from 'mobx';
import Wallet from '../domain/Wallet';
import WalletTransaction from '../domain/WalletTransaction';
import type {
  createWalletRequest,
  getTransactionsRequest,
  createTransactionRequest,
  walletRestoreRequest
} from './index';
import { user } from './fixtures';
import User from '../domain/User';
import Profile from '../domain/Profile';

const notYetImplemented = () => new Promise((resolve, reject) => reject(new Error('Api method not yet implemented')));

export default class CardanoClientApi {

  login() {
    // TODO: Implement when backend is ready for it
    return new Promise((resolve) => resolve(true));
  }

  getUser() {
    return new Promise((resolve) => {
      setTimeout(action(() => {
        resolve(new User(user.id, new Profile(user.profile)));
      }), 0);
    });
  }

  async getWallets() {
    const response = await ClientApi.getWallets();
    return response.map(data => this._createWalletFromData(data));
  }

  async getTransactions({ walletId, searchTerm, skip, limit }: getTransactionsRequest) {
    const history = await ClientApi.searchHistory(walletId, searchTerm, skip, limit);
    return new Promise((resolve) => resolve({
      transactions: history[0].map(data => this._createTransactionFromData(data, walletId)),
      total: history[1]
    }));
  }

  createUser() {
    return notYetImplemented();
  }

  async createWallet(request: createWalletRequest) {
    const response = await ClientApi.newWallet('CWTPersonal', 'ADA', request.name, request.mnemonic);
    return this._createWalletFromData(response);
  }

  async createTransaction(request: createTransactionRequest) {
    const { sender, receiver, amount, currency, title } = request;
    let { description } = request;
    if (!description) description = 'no description provided';
    const response = await ClientApi.sendExtended(sender, receiver, amount, currency, title, description);
    return this._createTransactionFromData(response);
  }

  isValidAddress(currency: string, address: string) {
    return ClientApi.isValidAddress(currency, address);
  }

  updateProfileField() {
    return notYetImplemented();
  }

  @action _createWalletFromData(data) {
    return new Wallet({
      id: data.cwAddress,
      address: data.cwAddress,
      amount: data.cwAmount.getCoin,
      type: data.cwMeta.cwType,
      currency: data.cwMeta.cwCurrency,
      name: data.cwMeta.cwName,
    });
  }

  @action _createTransactionFromData(data) {
    const isOutgoing = data.ctType.tag === 'CTOut';
    const coins = data.ctAmount.getCoin;
    let { ctmTitle, ctmDescription, ctmDate } = data.ctType.contents;
    if (!ctmTitle) ctmTitle = 'Incoming Money';
    return new WalletTransaction({
      id: data.ctId,
      title: ctmTitle,
      type: isOutgoing ? 'adaExpend' : 'adaIncome',
      currency: 'ada',
      amount: isOutgoing ? -1 * coins : coins,
      date: new Date(ctmDate * 1000),
      description: ctmDescription,
    });
  }

  getWalletRecoveryPhrase() {
    return new Promise((resolve) => resolve(ClientApi.generateMnemonic().split(' ')));
  }

  async restoreWallet({ recoveryPhrase, walletName }: walletRestoreRequest) {
    return await ClientApi.restoreWallet('CWTPersonal', 'ADA', walletName, recoveryPhrase);
  }
}
<|endoftext|>


<commit_before>/**
 * editor_plugin_src.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function() {
	var JSONRequest = tinymce.util.JSONRequest, each = tinymce.each, DOM = tinymce.DOM;

	tinymce.create('tinymce.plugins.SpellcheckerPlugin', {
		getInfo : function() {
			return {
				longname : 'Spellchecker',
				author : 'Moxiecode Systems AB',
				authorurl : 'http://tinymce.moxiecode.com',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		},

		init : function(ed, url) {
			var t = this, cm;

			t.url = url;
			t.editor = ed;
			t.rpcUrl = ed.getParam("spellchecker_rpc_url", "{backend}");

			if (t.rpcUrl == '{backend}') {
				// Sniff if the browser supports native spellchecking (Don't know of a better way)
				if (tinymce.isIE)
					return;

				t.hasSupport = true;

				// Disable the context menu when spellchecking is active
				ed.onContextMenu.addToTop(function(ed, e) {
					if (t.active)
						return false;
				});
			}

			// Register commands
			ed.addCommand('mceSpellCheck', function() {
				if (t.rpcUrl == '{backend}') {
					// Enable/disable native spellchecker
					t.editor.getBody().spellcheck = t.active = !t.active;
					return;
				}

				if (!t.active) {
					ed.setProgressState(1);
					t._sendRPC('checkWords', [t.selectedLang, t._getWords()], function(r) {
						if (r.length > 0) {
							t.active = 1;
							t._markWords(r);
							ed.setProgressState(0);
							ed.nodeChanged();
						} else {
							ed.setProgressState(0);

							if (ed.getParam('spellchecker_report_no_misspellings', true))
								ed.windowManager.alert('spellchecker.no_mpell');
						}
					});
				} else
					t._done();
			});

			ed.onInit.add(function() {
				if (ed.settings.content_css !== false)
					ed.dom.loadCSS(url + '/css/content.css');
			});

			ed.onClick.add(t._showMenu, t);
			ed.onContextMenu.add(t._showMenu, t);
			ed.onBeforeGetContent.add(function() {
				if (t.active)
					t._removeWords();
			});

			ed.onNodeChange.add(function(ed, cm) {
				cm.setActive('spellchecker', t.active);
			});

			ed.onSetContent.add(function() {
				t._done();
			});

			ed.onBeforeGetContent.add(function() {
				t._done();
			});

			ed.onBeforeExecCommand.add(function(ed, cmd) {
				if (cmd == 'mceFullScreen')
					t._done();
			});

			// Find selected language
			t.languages = {};
			each(ed.getParam('spellchecker_languages', '+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv', 'hash'), function(v, k) {
				if (k.indexOf('+') === 0) {
					k = k.substring(1);
					t.selectedLang = v;
				}

				t.languages[k] = v;
			});
		},

		createControl : function(n, cm) {
			var t = this, c, ed = t.editor;

			if (n == 'spellchecker') {
				// Use basic button if we use the native spellchecker
				if (t.rpcUrl == '{backend}') {
					// Create simple toggle button if we have native support
					if (t.hasSupport)
						c = cm.createButton(n, {title : 'spellchecker.desc', cmd : 'mceSpellCheck', scope : t});

					return c;
				}

				c = cm.createSplitButton(n, {title : 'spellchecker.desc', cmd : 'mceSpellCheck', scope : t});

				c.onRenderMenu.add(function(c, m) {
					m.add({title : 'spellchecker.langs', 'class' : 'mceMenuItemTitle'}).setDisabled(1);
					each(t.languages, function(v, k) {
						var o = {icon : 1}, mi;

						o.onclick = function() {
							mi.setSelected(1);
							t.selectedItem.setSelected(0);
							t.selectedItem = mi;
							t.selectedLang = v;
						};

						o.title = k;
						mi = m.add(o);
						mi.setSelected(v == t.selectedLang);

						if (v == t.selectedLang)
							t.selectedItem = mi;
					})
				});

				return c;
			}
		},

		// Internal functions

		_walk : function(n, f) {
			var d = this.editor.getDoc(), w;

			if (d.createTreeWalker) {
				w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false);

				while ((n = w.nextNode()) != null)
					f.call(this, n);
			} else
				tinymce.walk(n, f, 'childNodes');
		},

		_getSeparators : function() {
			var re = '', i, str = this.editor.getParam('spellchecker_word_separator_chars', '\\s!"#$%&()*+,-./:;<=>?@[\]^_{|}\u201d\u201c');

			// Build word separator regexp
			for (i=0; i<str.length; i++)
				re += '\\' + str.charAt(i);

			return re;
		},

		_getWords : function() {
			var ed = this.editor, wl = [], tx = '', lo = {}, rawWords = [];

			// Get area text
			this._walk(ed.getBody(), function(n) {
				if (n.nodeType == 3)
					tx += n.nodeValue + ' ';
			});

			// split the text up into individual words
			if (ed.getParam('spellchecker_word_pattern')) {
				// look for words that match the pattern
				rawWords = tx.match('(' + ed.getParam('spellchecker_word_pattern') + ')', 'gi');
			} else {
				// Split words by separator
				tx = tx.replace(new RegExp('([0-9]|[' + this._getSeparators() + '])', 'g'), ' ');
				tx = tinymce.trim(tx.replace(/(\s+)/g, ' '));
				rawWords = tx.split(' ');
			}

			// Build word array and remove duplicates
			each(rawWords, function(v) {
				if (!lo[v]) {
					wl.push(v);
					lo[v] = 1;
				}
			});

			return wl;
		},

		_removeWords : function(w) {
			var ed = this.editor, dom = ed.dom, se = ed.selection, b = se.getBookmark();

			each(dom.select('span').reverse(), function(n) {
				if (n && (dom.hasClass(n, 'mceItemHiddenSpellWord') || dom.hasClass(n, 'mceItemHidden'))) {
					if (!w || dom.decode(n.innerHTML) == w)
						dom.remove(n, 1);
				}
			});

			se.moveToBookmark(b);
		},

		_markWords : function(wl) {
			var r1, r2, r3, r4, r5, w = '', ed = this.editor, re = this._getSeparators(), dom = ed.dom, nl = [];
			var se = ed.selection, b = se.getBookmark();

			each(wl, function(v) {
				w += (w ? '|' : '') + v;
			});

			r1 = new RegExp('([' + re + '])(' + w + ')([' + re + '])', 'g');
			r2 = new RegExp('^(' + w + ')', 'g');
			r3 = new RegExp('(' + w + ')([' + re + ']?)$', 'g');
			r4 = new RegExp('^(' + w + ')([' + re + ']?)$', 'g');
			r5 = new RegExp('(' + w + ')([' + re + '])', 'g');

			// Collect all text nodes
			this._walk(this.editor.getBody(), function(n) {
				if (n.nodeType == 3) {
					nl.push(n);
				}
			});

			// Wrap incorrect words in spans
			each(nl, function(n) {
				var v;

				if (n.nodeType == 3) {
					v = n.nodeValue;

					if (r1.test(v) || r2.test(v) || r3.test(v) || r4.test(v)) {
						v = dom.encode(v);
						v = v.replace(r5, '$1$2');
						v = v.replace(r3, '$1$2');

						dom.replace(dom.create('span', {'class' : 'mceItemHidden'}, v), n);
					}
				}
			});

			se.moveToBookmark(b);
		},

		_showMenu : function(ed, e) {
			var t = this, ed = t.editor, m = t._menu, p1, dom = ed.dom, vp = dom.getViewPort(ed.getWin());

			if (!m) {
				p1 = DOM.getPos(ed.getContentAreaContainer());
				//p2 = DOM.getPos(ed.getContainer());

				m = ed.controlManager.createDropMenu('spellcheckermenu', {
					offset_x : p1.x,
					offset_y : p1.y,
					'class' : 'mceNoIcons'
				});

				t._menu = m;
			}

			if (dom.hasClass(e.target, 'mceItemHiddenSpellWord')) {
				m.removeAll();
				m.add({title : 'spellchecker.wait', 'class' : 'mceMenuItemTitle'}).setDisabled(1);

				t._sendRPC('getSuggestions', [t.selectedLang, dom.decode(e.target.innerHTML)], function(r) {
					var ignoreRpc;

					m.removeAll();

					if (r.length > 0) {
						m.add({title : 'spellchecker.sug', 'class' : 'mceMenuItemTitle'}).setDisabled(1);
						each(r, function(v) {
							m.add({title : v, onclick : function() {
								dom.replace(ed.getDoc().createTextNode(v), e.target);
								t._checkDone();
							}});
						});

						m.addSeparator();
					} else
						m.add({title : 'spellchecker.no_sug', 'class' : 'mceMenuItemTitle'}).setDisabled(1);

					ignoreRpc = t.editor.getParam("spellchecker_enable_ignore_rpc", '');
					m.add({
						title : 'spellchecker.ignore_word',
						onclick : function() {
							var word = e.target.innerHTML;

							dom.remove(e.target, 1);
							t._checkDone();

							// tell the server if we need to
							if (ignore_rpc) {
								ed.setProgressState(1);
								t._sendRPC('ignoreWord', [t.selectedLang, word], function(r) {
									ed.setProgressState(0);
								});
							}
						}
					});

					m.add({
						title : 'spellchecker.ignore_words',
						onclick : function() {
							var word = e.target.innerHTML;

							t._removeWords(dom.decode(word));
							t._checkDone();

							// tell the server if we need to
							if (ignore_rpc) {
								ed.setProgressState(1);
								t._sendRPC('ignoreWords', [t.selectedLang, word], function(r) {
									ed.setProgressState(0);
								});
							}
						}
					});

					if (t.editor.getParam("spellchecker_enable_learn_rpc")) {
						m.add({
							title : 'spellchecker.learn_word',
							onclick : function() {
								var word = e.target.innerHTML;

								dom.remove(e.target, 1);
								t._checkDone();

								ed.setProgressState(1);
								t._sendRPC('learnWord', [t.selectedLang, word], function(r) {
									ed.setProgressState(0);
								});
							}
						});
					}

					m.update();
				});

				ed.selection.select(e.target);
				p1 = dom.getPos(e.target);
				m.showMenu(p1.x, p1.y + e.target.offsetHeight - vp.y);

				return tinymce.dom.Event.cancel(e);
			} else
				m.hideMenu();
		},

		_checkDone : function() {
			var t = this, ed = t.editor, dom = ed.dom, o;

			each(dom.select('span'), function(n) {
				if (n && dom.hasClass(n, 'mceItemHiddenSpellWord')) {
					o = true;
					return false;
				}
			});

			if (!o)
				t._done();
		},

		_done : function() {
			var t = this, la = t.active;

			if (t.active) {
				t.active = 0;
				t._removeWords();

				if (t._menu)
					t._menu.hideMenu();

				if (la)
					t.editor.nodeChanged();
			}
		},

		_sendRPC : function(m, p, cb) {
			var t = this;

			JSONRequest.sendRPC({
				url : t.rpcUrl,
				method : m,
				params : p,
				success : cb,
				error : function(e, x) {
					t.editor.setProgressState(0);
					t.editor.windowManager.alert(e.errstr || ('Error response: ' + x.responseText));
				}
			});
		}
	});

	// Register plugin
	tinymce.PluginManager.add('spellchecker', tinymce.plugins.SpellcheckerPlugin);
})();
<commit_msg>Fixed issue with ignore_rpc not being defined.<commit_after>/**
 * editor_plugin_src.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function() {
	var JSONRequest = tinymce.util.JSONRequest, each = tinymce.each, DOM = tinymce.DOM;

	tinymce.create('tinymce.plugins.SpellcheckerPlugin', {
		getInfo : function() {
			return {
				longname : 'Spellchecker',
				author : 'Moxiecode Systems AB',
				authorurl : 'http://tinymce.moxiecode.com',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		},

		init : function(ed, url) {
			var t = this, cm;

			t.url = url;
			t.editor = ed;
			t.rpcUrl = ed.getParam("spellchecker_rpc_url", "{backend}");

			if (t.rpcUrl == '{backend}') {
				// Sniff if the browser supports native spellchecking (Don't know of a better way)
				if (tinymce.isIE)
					return;

				t.hasSupport = true;

				// Disable the context menu when spellchecking is active
				ed.onContextMenu.addToTop(function(ed, e) {
					if (t.active)
						return false;
				});
			}

			// Register commands
			ed.addCommand('mceSpellCheck', function() {
				if (t.rpcUrl == '{backend}') {
					// Enable/disable native spellchecker
					t.editor.getBody().spellcheck = t.active = !t.active;
					return;
				}

				if (!t.active) {
					ed.setProgressState(1);
					t._sendRPC('checkWords', [t.selectedLang, t._getWords()], function(r) {
						if (r.length > 0) {
							t.active = 1;
							t._markWords(r);
							ed.setProgressState(0);
							ed.nodeChanged();
						} else {
							ed.setProgressState(0);

							if (ed.getParam('spellchecker_report_no_misspellings', true))
								ed.windowManager.alert('spellchecker.no_mpell');
						}
					});
				} else
					t._done();
			});

			ed.onInit.add(function() {
				if (ed.settings.content_css !== false)
					ed.dom.loadCSS(url + '/css/content.css');
			});

			ed.onClick.add(t._showMenu, t);
			ed.onContextMenu.add(t._showMenu, t);
			ed.onBeforeGetContent.add(function() {
				if (t.active)
					t._removeWords();
			});

			ed.onNodeChange.add(function(ed, cm) {
				cm.setActive('spellchecker', t.active);
			});

			ed.onSetContent.add(function() {
				t._done();
			});

			ed.onBeforeGetContent.add(function() {
				t._done();
			});

			ed.onBeforeExecCommand.add(function(ed, cmd) {
				if (cmd == 'mceFullScreen')
					t._done();
			});

			// Find selected language
			t.languages = {};
			each(ed.getParam('spellchecker_languages', '+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv', 'hash'), function(v, k) {
				if (k.indexOf('+') === 0) {
					k = k.substring(1);
					t.selectedLang = v;
				}

				t.languages[k] = v;
			});
		},

		createControl : function(n, cm) {
			var t = this, c, ed = t.editor;

			if (n == 'spellchecker') {
				// Use basic button if we use the native spellchecker
				if (t.rpcUrl == '{backend}') {
					// Create simple toggle button if we have native support
					if (t.hasSupport)
						c = cm.createButton(n, {title : 'spellchecker.desc', cmd : 'mceSpellCheck', scope : t});

					return c;
				}

				c = cm.createSplitButton(n, {title : 'spellchecker.desc', cmd : 'mceSpellCheck', scope : t});

				c.onRenderMenu.add(function(c, m) {
					m.add({title : 'spellchecker.langs', 'class' : 'mceMenuItemTitle'}).setDisabled(1);
					each(t.languages, function(v, k) {
						var o = {icon : 1}, mi;

						o.onclick = function() {
							mi.setSelected(1);
							t.selectedItem.setSelected(0);
							t.selectedItem = mi;
							t.selectedLang = v;
						};

						o.title = k;
						mi = m.add(o);
						mi.setSelected(v == t.selectedLang);

						if (v == t.selectedLang)
							t.selectedItem = mi;
					})
				});

				return c;
			}
		},

		// Internal functions

		_walk : function(n, f) {
			var d = this.editor.getDoc(), w;

			if (d.createTreeWalker) {
				w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false);

				while ((n = w.nextNode()) != null)
					f.call(this, n);
			} else
				tinymce.walk(n, f, 'childNodes');
		},

		_getSeparators : function() {
			var re = '', i, str = this.editor.getParam('spellchecker_word_separator_chars', '\\s!"#$%&()*+,-./:;<=>?@[\]^_{|}\u201d\u201c');

			// Build word separator regexp
			for (i=0; i<str.length; i++)
				re += '\\' + str.charAt(i);

			return re;
		},

		_getWords : function() {
			var ed = this.editor, wl = [], tx = '', lo = {}, rawWords = [];

			// Get area text
			this._walk(ed.getBody(), function(n) {
				if (n.nodeType == 3)
					tx += n.nodeValue + ' ';
			});

			// split the text up into individual words
			if (ed.getParam('spellchecker_word_pattern')) {
				// look for words that match the pattern
				rawWords = tx.match('(' + ed.getParam('spellchecker_word_pattern') + ')', 'gi');
			} else {
				// Split words by separator
				tx = tx.replace(new RegExp('([0-9]|[' + this._getSeparators() + '])', 'g'), ' ');
				tx = tinymce.trim(tx.replace(/(\s+)/g, ' '));
				rawWords = tx.split(' ');
			}

			// Build word array and remove duplicates
			each(rawWords, function(v) {
				if (!lo[v]) {
					wl.push(v);
					lo[v] = 1;
				}
			});

			return wl;
		},

		_removeWords : function(w) {
			var ed = this.editor, dom = ed.dom, se = ed.selection, b = se.getBookmark();

			each(dom.select('span').reverse(), function(n) {
				if (n && (dom.hasClass(n, 'mceItemHiddenSpellWord') || dom.hasClass(n, 'mceItemHidden'))) {
					if (!w || dom.decode(n.innerHTML) == w)
						dom.remove(n, 1);
				}
			});

			se.moveToBookmark(b);
		},

		_markWords : function(wl) {
			var r1, r2, r3, r4, r5, w = '', ed = this.editor, re = this._getSeparators(), dom = ed.dom, nl = [];
			var se = ed.selection, b = se.getBookmark();

			each(wl, function(v) {
				w += (w ? '|' : '') + v;
			});

			r1 = new RegExp('([' + re + '])(' + w + ')([' + re + '])', 'g');
			r2 = new RegExp('^(' + w + ')', 'g');
			r3 = new RegExp('(' + w + ')([' + re + ']?)$', 'g');
			r4 = new RegExp('^(' + w + ')([' + re + ']?)$', 'g');
			r5 = new RegExp('(' + w + ')([' + re + '])', 'g');

			// Collect all text nodes
			this._walk(this.editor.getBody(), function(n) {
				if (n.nodeType == 3) {
					nl.push(n);
				}
			});

			// Wrap incorrect words in spans
			each(nl, function(n) {
				var v;

				if (n.nodeType == 3) {
					v = n.nodeValue;

					if (r1.test(v) || r2.test(v) || r3.test(v) || r4.test(v)) {
						v = dom.encode(v);
						v = v.replace(r5, '$1$2');
						v = v.replace(r3, '$1$2');

						dom.replace(dom.create('span', {'class' : 'mceItemHidden'}, v), n);
					}
				}
			});

			se.moveToBookmark(b);
		},

		_showMenu : function(ed, e) {
			var t = this, ed = t.editor, m = t._menu, p1, dom = ed.dom, vp = dom.getViewPort(ed.getWin());

			if (!m) {
				p1 = DOM.getPos(ed.getContentAreaContainer());
				//p2 = DOM.getPos(ed.getContainer());

				m = ed.controlManager.createDropMenu('spellcheckermenu', {
					offset_x : p1.x,
					offset_y : p1.y,
					'class' : 'mceNoIcons'
				});

				t._menu = m;
			}

			if (dom.hasClass(e.target, 'mceItemHiddenSpellWord')) {
				m.removeAll();
				m.add({title : 'spellchecker.wait', 'class' : 'mceMenuItemTitle'}).setDisabled(1);

				t._sendRPC('getSuggestions', [t.selectedLang, dom.decode(e.target.innerHTML)], function(r) {
					var ignoreRpc;

					m.removeAll();

					if (r.length > 0) {
						m.add({title : 'spellchecker.sug', 'class' : 'mceMenuItemTitle'}).setDisabled(1);
						each(r, function(v) {
							m.add({title : v, onclick : function() {
								dom.replace(ed.getDoc().createTextNode(v), e.target);
								t._checkDone();
							}});
						});

						m.addSeparator();
					} else
						m.add({title : 'spellchecker.no_sug', 'class' : 'mceMenuItemTitle'}).setDisabled(1);

					ignoreRpc = t.editor.getParam("spellchecker_enable_ignore_rpc", '');
					m.add({
						title : 'spellchecker.ignore_word',
						onclick : function() {
							var word = e.target.innerHTML;

							dom.remove(e.target, 1);
							t._checkDone();

							// tell the server if we need to
							if (ignoreRpc) {
								ed.setProgressState(1);
								t._sendRPC('ignoreWord', [t.selectedLang, word], function(r) {
									ed.setProgressState(0);
								});
							}
						}
					});

					m.add({
						title : 'spellchecker.ignore_words',
						onclick : function() {
							var word = e.target.innerHTML;

							t._removeWords(dom.decode(word));
							t._checkDone();

							// tell the server if we need to
							if (ignoreRpc) {
								ed.setProgressState(1);
								t._sendRPC('ignoreWords', [t.selectedLang, word], function(r) {
									ed.setProgressState(0);
								});
							}
						}
					});

					if (t.editor.getParam("spellchecker_enable_learn_rpc")) {
						m.add({
							title : 'spellchecker.learn_word',
							onclick : function() {
								var word = e.target.innerHTML;

								dom.remove(e.target, 1);
								t._checkDone();

								ed.setProgressState(1);
								t._sendRPC('learnWord', [t.selectedLang, word], function(r) {
									ed.setProgressState(0);
								});
							}
						});
					}

					m.update();
				});

				ed.selection.select(e.target);
				p1 = dom.getPos(e.target);
				m.showMenu(p1.x, p1.y + e.target.offsetHeight - vp.y);

				return tinymce.dom.Event.cancel(e);
			} else
				m.hideMenu();
		},

		_checkDone : function() {
			var t = this, ed = t.editor, dom = ed.dom, o;

			each(dom.select('span'), function(n) {
				if (n && dom.hasClass(n, 'mceItemHiddenSpellWord')) {
					o = true;
					return false;
				}
			});

			if (!o)
				t._done();
		},

		_done : function() {
			var t = this, la = t.active;

			if (t.active) {
				t.active = 0;
				t._removeWords();

				if (t._menu)
					t._menu.hideMenu();

				if (la)
					t.editor.nodeChanged();
			}
		},

		_sendRPC : function(m, p, cb) {
			var t = this;

			JSONRequest.sendRPC({
				url : t.rpcUrl,
				method : m,
				params : p,
				success : cb,
				error : function(e, x) {
					t.editor.setProgressState(0);
					t.editor.windowManager.alert(e.errstr || ('Error response: ' + x.responseText));
				}
			});
		}
	});

	// Register plugin
	tinymce.PluginManager.add('spellchecker', tinymce.plugins.SpellcheckerPlugin);
})();
<|endoftext|>


<commit_before>'use strict';

const inlinedHostConfigs = require('../shared/inlinedHostConfigs');

// When testing the custom renderer code path through `react-reconciler`,
// turn the export into a function, and use the argument as host config.
const shimHostConfigPath = 'react-reconciler/src/ReactFiberHostConfig';
jest.mock('react-reconciler', () => {
  return config => {
    jest.mock(shimHostConfigPath, () => config);
    return require.requireActual('react-reconciler');
  };
});
jest.mock('react-reconciler/persistent', () => {
  return config => {
    jest.mock(shimHostConfigPath, () => config);
    return require.requireActual('react-reconciler/persistent');
  };
});

// But for inlined host configs (such as React DOM, Native, etc), we
// mock their named entry points to establish a host config mapping.
inlinedHostConfigs.forEach(rendererInfo => {
  if (rendererInfo.shortName === 'custom') {
    // There is no inline entry point for the custom renderers.
    // Instead, it's handled by the generic `react-reconciler` entry point above.
    return;
  }
  jest.mock(`react-reconciler/inline.${rendererInfo.shortName}`, () => {
    jest.mock(shimHostConfigPath, () =>
      require.requireActual(
        `react-reconciler/src/forks/ReactFiberHostConfig.${
          rendererInfo.shortName
        }.js`
      )
    );
    return require.requireActual('react-reconciler');
  });
});
<commit_msg>Add a clear error when renderers clash in tests (#12867)<commit_after>'use strict';

const inlinedHostConfigs = require('../shared/inlinedHostConfigs');

// When testing the custom renderer code path through `react-reconciler`,
// turn the export into a function, and use the argument as host config.
const shimHostConfigPath = 'react-reconciler/src/ReactFiberHostConfig';
jest.mock('react-reconciler', () => {
  return config => {
    jest.mock(shimHostConfigPath, () => config);
    return require.requireActual('react-reconciler');
  };
});
jest.mock('react-reconciler/persistent', () => {
  return config => {
    jest.mock(shimHostConfigPath, () => config);
    return require.requireActual('react-reconciler/persistent');
  };
});

// But for inlined host configs (such as React DOM, Native, etc), we
// mock their named entry points to establish a host config mapping.
inlinedHostConfigs.forEach(rendererInfo => {
  if (rendererInfo.shortName === 'custom') {
    // There is no inline entry point for the custom renderers.
    // Instead, it's handled by the generic `react-reconciler` entry point above.
    return;
  }
  jest.mock(`react-reconciler/inline.${rendererInfo.shortName}`, () => {
    let hasImportedShimmedConfig = false;

    // We want the reconciler to pick up the host config for this renderer.
    jest.mock(shimHostConfigPath, () => {
      hasImportedShimmedConfig = true;
      return require.requireActual(
        `react-reconciler/src/forks/ReactFiberHostConfig.${
          rendererInfo.shortName
        }.js`
      );
    });

    const renderer = require.requireActual('react-reconciler');
    // If the shimmed config factory function above has not run,
    // it means this test file loads more than one renderer
    // but doesn't reset modules between them. This won't work.
    if (!hasImportedShimmedConfig) {
      throw new Error(
        `Could not import the "${rendererInfo.shortName}" renderer ` +
          `in this suite because another renderer has already been ` +
          `loaded earlier. Call jest.resetModules() before importing any ` +
          `of the following entry points:\n\n` +
          rendererInfo.entryPoints.map(entry => `  * ${entry}`)
      );
    }

    return renderer;
  });
});
<|endoftext|>


<commit_before>var path = process.cwd();
var Yelp = require('yelp');
var multer  = require('multer');
var upload = multer({ dest: 'uploads/' });
var handlebars  = require('handlebars');
var fs = require('fs');
var session = require('express-session');
var Users = require('../models/users.js');
var Nightclubs = require('../models/nightlife.js');

module.exports = function (app, passport) {

function isLoggedIn (req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {
            res.redirect('/login');
        }
    }

app.route('/checkin/:checkinID')
  .get(isLoggedIn, function (req, res) {
    //  console.log(req.user);

       Users.findOne({ 'id': req.id }, function (err, User) {
            if (err) throw err;
            if(User){
                User.nightclub.nightclub = req.params.checkinID;
            } else{
                console.log ("err no user");
            }
        });

        Nightclubs.findOne({'id':req.params.checkinID}, function(err,Nightclub){
            if (err) throw err;
        });

       res.sendFile(path + '/public/checkin.html');

  })
}<commit_msg>saving location<commit_after>var path = process.cwd();
var Yelp = require('yelp');
var multer  = require('multer');
var upload = multer({ dest: 'uploads/' });
var handlebars  = require('handlebars');
var fs = require('fs');
var session = require('express-session');
var Users = require('../models/users.js');
var Nightclubs = require('../models/nightlife.js');

module.exports = function (app, passport) {

function isLoggedIn (req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {
            res.redirect('/login');
        }
    }

function removeFromClub(checkinID){
           Nightclubs.findOne({'id':checkinID}, function(err,Nightclub){
            if (err) throw err;
            if(Nightclub){

            } else {

            }
        });

}

function addtoClub(checkinID, userID){

}

app.route('/checkin/:checkinID')
  .get(isLoggedIn, function (req, res) {
    //  console.log(req.user);

       Users.findOne({ 'id': req.id }, function (err, User) {
            if (err) throw err;
            if(User){
                console.log("Old location:" + User.nightclub.nightclub);
                User.nightclub.nightclub = req.params.checkinID;
                console.log("New location:" + User.nightclub.nightclub);
                User.save();
            } else{
                console.log ("err no user");
            }
        });

       res.sendFile(path + '/public/checkin.html');

  })
}
<|endoftext|>


<commit_before>(function($) {
  bootAsyncLoader = function(){
    //extra login with ajax request is needed
    if(urlParam('viewer_pane') === '1' && !window.alreadyChecked==true){
      window.alreadyChecked=true;
      console.log('*********************** AJAX MODE ***********************');
      window.stayLoggedIn = function(){
        var creds = "username="+decodeURIComponent(urlParam('username'))+"&password=" + decodeURIComponent(urlParam("password"))
        if(urlParam("username")!=null && !window.loggedIn){
          return $.ajax({
              type: 'POST',
              url: '/rstudio_login',
              data: creds,
              contentType:"application/x-www-form-urlencoded",
              xhrFields: {
                withCredentials: true
              },
              crossDomain:true,
              success: function(data, textStatus, xhr) {
              },
              error: function(jqXHR, textStatus, errorThrown) {
              }
          })
        }
      }
      window.stayLoggedIn()
      var $pageBody = $('body');
      window.loggedIn = false;
      // Intercept all link clicks
      window.asyncClickHandler = function(e) {
        e.preventDefault();
        // Grab the url from the anchor tag
        var url = $(this).attr('href');
        return window.replacePage(url,true,true);
      }

      var rerenderBody = function(html,rebind, url){
        var body = html.replace(/^[\S\s]*]*?>/i, "");
        body = body.replace(/<\/body[\S\s]*$/i, "");
        //apparently the rule below refires document.ready after replacing, thus the alreadyChecked boolean
        $('body').attr("url", url);
        $pageBody.html(body);
        window.boot()
        if(rebind){
          window.classifyLinks();
          window.bindGlobalClickHandler();
        }
        window.bindButtonAndForms();
        window.searchHandler(jQuery);
        window.launchFullSearch();
        window.bindHistoryNavigation();
        window.scrollTo(0,0);
        $('.search--results').hide();
        window.packageVersionControl();
      };

      /************************************************************************************************************************************************
      rebinding and executing trough ajax requests
      ************************************************************************************************************************************************/

      window.bindGlobalClickHandler = function(){        //unbinding seems to fail a lot in the Rstudio browser?!->be sure not to bind twice
        $('a:not(.js-external)').each(function(){
          $(this).unbind('click').bind('click', window.asyncClickHandler);
        })
      };
      window.bindSearchPaneClickHandler=function(){
        $('.search--results').find('a:not(.js-external)').unbind('click').bind('click',window.asyncClickHandler);
      };

      window.bindButtonAndForms= function(){
        $('#js-examples').unbind('click').bind('click',window.runExamples);
        $('#js-install').unbind('click').bind('click',window.installpackage);
        $('#js-hideviewer').unbind('click').bind('click',window.hideViewer);
        $('#js-makedefault').unbind('click').bind('click',window.setDefault);
        $( "form" ).each(function(){
          $(this).unbind('submit').bind('submit',function(event) {
            event.preventDefault();
            var action = $(this)[0].action;
            var dataToWrite= $(this).serialize();
            var type = "GET";
            var history = action + "?"+dataToWrite
            if (!(action.indexOf("search")>-1)){
              type = "POST";
              var history=action
            }
            else{
              window.queryTime=new Date();
            }
            dataToWrite= dataToWrite+'&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port")
            window.pushHistory(history)
            $.ajax({
              type: type,
              url: action,
              headers: {
                Accept : "text/html; charset=utf-8",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
              },
              data: dataToWrite,
              contentType:"application/x-www-form-urlencoded",
              xhrFields: {
                withCredentials: true
              },
              crossDomain:true
            }).then(function(html,textData,xhr){
              var url = type === 'GET' ? action + '?' + dataToWrite : action;
              if(action.indexOf("/login")>-1 && !window.loggedIn){
                _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
                  ["write('"+dataToWrite+"', file = paste0(find.package('Rdocumentation'),'/config/creds.txt')) \n Rdocumentation::login()"])
                .then(function(){
                  window.stayLoggedIn().then(function(){
                     rerenderBody(html,true, url)
                  })
                })
              }
              else{
                rerenderBody(html,true, url);
              }
            });
          });
        });
      }

      // Helper function to grab new HTML
      // and replace the content
      window.replacePage = function(url,rebind,addToHistory) {
        if(addToHistory){
          window.pushHistory(url)
        }
        if(url.indexOf('#')>=0){
          url = url.substring(url.indexOf('#'),url.length);
          document.getElementById(url).scrollIntoView();
        }
        else{
          url = url.replace("../","");
          if(url.charAt(0)!="/"){
            url="/"+url;
          }
          var base = $('base').attr('href');
          if(url.indexOf('?')>-1){
            url = url + '&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          else{
            url=url+'?viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          return $.ajax({
            url : base +url,
            type: 'GET',
            dataType:"html",
            Accept:"text/html",
            cache: false,
            xhrFields: {
              withCredentials: true
            },
            crossDomain:true,
            success: function(data, textStatus, xhr) {
              rerenderBody(data,rebind, url);
            }
          })
          .fail(function(error) {console.log(error.responseJSON) });
        }

      };

            /************************************************************************************************************************************************
      button press functions (running examples, installing packages);
      ************************************************************************************************************************************************/
      window.runExamples=function(e){
        e.preventDefault();
        var package = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        window.checkPackageVersion(package,version).then(function(installed){
          if(installed==0|| installed==-1){
            var examples= $('.topic').find('.topic--title').filter(function(i,el){
              return $(this).text()=="Examples";
            }).parent().find('.R').text();
            _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+examples])
          }
        });
        return false;
      };

      window.setDefault=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::makeDefault()"]);
        return false;
      };
      window.hideViewer=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::hideViewer()"]);
        return false;
      };
      /************************************************************************************************************************************************
      checking installation of package and package version
      ************************************************************************************************************************************************/
      window.checkPackageVersion=function(package,version){
        return _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["check_package('"+package+"','"+version+"')"])
        .then(function(result){
            return parseInt(result.result)
        });
      };

      window.packageVersionControl=function(){
        var packageName = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        if(packageName){
          window.checkPackageVersion(packageName,version).then(function(installed){
            if(installed==1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Install</button>');
              $('.visible-installed').hide()
            }
            else if(installed==-1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Update</button>');
            }
            else{
              $('.versionCheck').html('You have the latest version');
            }
            $('#js-install').unbind('click',window.installpackage);
            $('#js-install').bind('click',window.installpackage);
          });
        }
      };

      window.installpackage=function(e){
        e.preventDefault();
        var packageName = $(".packageData").data("package-name");
        var packageSource= $(".packageData").data("type-id");
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
                  ["install_package('"+packageName+"',"+packageSource+")"])
        return false;
      };

      window.setTab=function(e,ui){
        $('ul.tabs').find('a').each(function(){
          $(this.hash).hide();
        });
        var link = ui.tab[0].innerHTML
        link = link.substring(link.indexOf('#'),link.indexOf('" class'));
        $(link).show();
        e.preventDefault();
      };

      window.classifyLinks=function(){
        var base = $('base').attr('href');
        $('a:not(.js-external)').map(function(){
          var link =$(this).attr("href")
          if(!link.indexOf(base)>-1 && (link.indexOf("www")==0  || link.indexOf("http://")==0 || link.indexOf("https://") == 0)){
            $(this).addClass("js-external");
          }
        });
      };

      window.executePackageCode=function(code){
        var package = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        window.checkPackageVersion(package,version).then(function(installed){
          if(installed==0|| installed==-1){
            _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+code])
          }
        });
      }
      //check the packageversion
      window.packageVersionControl();
      window.classifyLinks();
      window.bindGlobalClickHandler();
      window.bindButtonAndForms();
      window.scrollTo(0,0);
    }
  };

  _rStudioRequest=function(url,method,shared_secret,port,params){
    var data={};
    data.method = method;
    //data.params = [$('.R').text()];
    data.params = params;
    data.clientId = '33e600bb-c1b1-46bf-b562-ab5cba070b0e';
    data.clientVersion = "";

    return $.ajax({
      url: 'http://127.0.0.1:'+port+url,
      headers:
      {
          'Accept':'application/json',
          'Content-Type':'application/json',
          'X-Shared-Secret':shared_secret
      },
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      processData: false,
      crossDomain:true,
      xhrFields: {
        withCredentials: true
      }
    });
  };
})($jq);
<commit_msg>added parameter for ajax requests<commit_after>(function($) {
  bootAsyncLoader = function(){
    //extra login with ajax request is needed
    if(urlParam('viewer_pane') === '1' && !window.alreadyChecked==true){
      window.alreadyChecked=true;
      console.log('*********************** AJAX MODE ***********************');
      window.stayLoggedIn = function(){
        var creds = "username="+decodeURIComponent(urlParam('username'))+"&password=" + decodeURIComponent(urlParam("password"))
        if(urlParam("username")!=null && !window.loggedIn){
          return $.ajax({
              type: 'POST',
              url: '/rstudio_login',
              data: creds,
              contentType:"application/x-www-form-urlencoded",
              xhrFields: {
                withCredentials: true
              },
              crossDomain:true,
              success: function(data, textStatus, xhr) {
              },
              error: function(jqXHR, textStatus, errorThrown) {
              }
          })
        }
      }
      window.stayLoggedIn()
      var $pageBody = $('body');
      window.loggedIn = false;
      // Intercept all link clicks
      window.asyncClickHandler = function(e) {
        e.preventDefault();
        // Grab the url from the anchor tag
        var url = $(this).attr('href');
        return window.replacePage(url,true,true);
      }

      var rerenderBody = function(html,rebind, url){
        var body = html.replace(/^[\S\s]*]*?>/i, "");
        body = body.replace(/<\/body[\S\s]*$/i, "");
        //apparently the rule below refires document.ready after replacing, thus the alreadyChecked boolean
        $('body').attr("url", url);
        $pageBody.html(body);
        window.boot()
        if(rebind){
          window.classifyLinks();
          window.bindGlobalClickHandler();
        }
        window.bindButtonAndForms();
        window.searchHandler(jQuery);
        window.launchFullSearch();
        window.bindHistoryNavigation();
        window.scrollTo(0,0);
        $('.search--results').hide();
        window.packageVersionControl();
      };

      /************************************************************************************************************************************************
      rebinding and executing trough ajax requests
      ************************************************************************************************************************************************/

      window.bindGlobalClickHandler = function(){        //unbinding seems to fail a lot in the Rstudio browser?!->be sure not to bind twice
        $('a:not(.js-external)').each(function(){
          $(this).unbind('click').bind('click', window.asyncClickHandler);
        })
      };
      window.bindSearchPaneClickHandler=function(){
        $('.search--results').find('a:not(.js-external)').unbind('click').bind('click',window.asyncClickHandler);
      };

      window.bindButtonAndForms= function(){
        $('#js-examples').unbind('click').bind('click',window.runExamples);
        $('#js-install').unbind('click').bind('click',window.installpackage);
        $('#js-hideviewer').unbind('click').bind('click',window.hideViewer);
        $('#js-makedefault').unbind('click').bind('click',window.setDefault);
        $( "form" ).each(function(){
          $(this).unbind('submit').bind('submit',function(event) {
            event.preventDefault();
            var action = $(this)[0].action;
            var dataToWrite= $(this).serialize();
            var type = "GET";
            var history = action + "?"+dataToWrite
            if (!(action.indexOf("search")>-1)){
              type = "POST";
              var history=action
            }
            else{
              window.queryTime=new Date();
            }
            dataToWrite= dataToWrite+'&rstudio_layout=1&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port")
            window.pushHistory(history)
            $.ajax({
              type: type,
              url: action,
              headers: {
                Accept : "text/html; charset=utf-8",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
              },
              data: dataToWrite,
              contentType:"application/x-www-form-urlencoded",
              xhrFields: {
                withCredentials: true
              },
              crossDomain:true
            }).then(function(html,textData,xhr){
              var url = type === 'GET' ? action + '?' + dataToWrite : action;
              if(action.indexOf("/login")>-1 && !window.loggedIn){
                _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
                  ["write('"+dataToWrite+"', file = paste0(find.package('Rdocumentation'),'/config/creds.txt')) \n Rdocumentation::login()"])
                .then(function(){
                  window.stayLoggedIn().then(function(){
                     rerenderBody(html,true, url)
                  })
                })
              }
              else{
                rerenderBody(html,true, url);
              }
            });
          });
        });
      }

      // Helper function to grab new HTML
      // and replace the content
      window.replacePage = function(url,rebind,addToHistory) {
        if(addToHistory){
          window.pushHistory(url)
        }
        if(url.indexOf('#')>=0){
          url = url.substring(url.indexOf('#'),url.length);
          document.getElementById(url).scrollIntoView();
        }
        else{
          url = url.replace("../","");
          if(url.charAt(0)!="/"){
            url="/"+url;
          }
          var base = $('base').attr('href');
          if(url.indexOf('?')>-1){
            url = url + '&rstudio_layout=1&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          else{
            url=url+'?rstudio_layout=1&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          return $.ajax({
            url : base +url,
            type: 'GET',
            dataType:"html",
            Accept:"text/html",
            cache: false,
            xhrFields: {
              withCredentials: true
            },
            crossDomain:true,
            success: function(data, textStatus, xhr) {
              rerenderBody(data,rebind, url);
            }
          })
          .fail(function(error) {console.log(error.responseJSON) });
        }

      };

            /************************************************************************************************************************************************
      button press functions (running examples, installing packages);
      ************************************************************************************************************************************************/
      window.runExamples=function(e){
        e.preventDefault();
        var package = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        window.checkPackageVersion(package,version).then(function(installed){
          if(installed==0|| installed==-1){
            var examples= $('.topic').find('.topic--title').filter(function(i,el){
              return $(this).text()=="Examples";
            }).parent().find('.R').text();
            _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+examples])
          }
        });
        return false;
      };

      window.setDefault=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::makeDefault()"]);
        return false;
      };
      window.hideViewer=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::hideViewer()"]);
        return false;
      };
      /************************************************************************************************************************************************
      checking installation of package and package version
      ************************************************************************************************************************************************/
      window.checkPackageVersion=function(package,version){
        return _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["check_package('"+package+"','"+version+"')"])
        .then(function(result){
            return parseInt(result.result)
        });
      };

      window.packageVersionControl=function(){
        var packageName = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        if(packageName){
          window.checkPackageVersion(packageName,version).then(function(installed){
            if(installed==1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Install</button>');
              $('.visible-installed').hide()
            }
            else if(installed==-1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Update</button>');
            }
            else{
              $('.versionCheck').html('You have the latest version');
            }
            $('#js-install').unbind('click',window.installpackage);
            $('#js-install').bind('click',window.installpackage);
          });
        }
      };

      window.installpackage=function(e){
        e.preventDefault();
        var packageName = $(".packageData").data("package-name");
        var packageSource= $(".packageData").data("type-id");
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
                  ["install_package('"+packageName+"',"+packageSource+")"])
        return false;
      };

      window.setTab=function(e,ui){
        $('ul.tabs').find('a').each(function(){
          $(this.hash).hide();
        });
        var link = ui.tab[0].innerHTML
        link = link.substring(link.indexOf('#'),link.indexOf('" class'));
        $(link).show();
        e.preventDefault();
      };

      window.classifyLinks=function(){
        var base = $('base').attr('href');
        $('a:not(.js-external)').map(function(){
          var link =$(this).attr("href")
          if(!link.indexOf(base)>-1 && (link.indexOf("www")==0  || link.indexOf("http://")==0 || link.indexOf("https://") == 0)){
            $(this).addClass("js-external");
          }
        });
      };

      window.executePackageCode=function(code){
        var package = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        window.checkPackageVersion(package,version).then(function(installed){
          if(installed==0|| installed==-1){
            _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+code])
          }
        });
      }
      //check the packageversion
      window.packageVersionControl();
      window.classifyLinks();
      window.bindGlobalClickHandler();
      window.bindButtonAndForms();
      window.scrollTo(0,0);
    }
  };

  _rStudioRequest=function(url,method,shared_secret,port,params){
    var data={};
    data.method = method;
    //data.params = [$('.R').text()];
    data.params = params;
    data.clientId = '33e600bb-c1b1-46bf-b562-ab5cba070b0e';
    data.clientVersion = "";

    return $.ajax({
      url: 'http://127.0.0.1:'+port+url,
      headers:
      {
          'Accept':'application/json',
          'Content-Type':'application/json',
          'X-Shared-Secret':shared_secret
      },
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      processData: false,
      crossDomain:true,
      xhrFields: {
        withCredentials: true
      }
    });
  };
})($jq);
<|endoftext|>


<commit_before>function addProjectWidget(id, projectName, projectVersion, projectIcon, projectDir) {
    console.log("addProjectWidget");

    var widgetId = "projectWidget_" + id.toString();
    var iconId = "icon_" + id.toString();

    var widgetDOM = "";
    widgetDOM += "
";

    widgetDOM += "
";
    widgetDOM += "

";
    widgetDOM += "
";
    widgetDOM += projectName + "
";
    widgetDOM += projectVersion + "

";
    widgetDOM += "
arrowright
";
    widgetDOM += "
";  // row 1

    widgetDOM += "
";
    widgetDOM += "
" + projectDir + "
";
    widgetDOM += "
";  // row 2

    widgetDOM += "
";  // table

    global.jQuery("#drop_zone").append(widgetDOM);

    global.jQuery("#" + widgetId).on("click", function() {
        var temp = global.jQuery("#" + widgetId).attr("id").split("_");
        var id = temp[1];

        // only allow setting of active widget if another project widget is selected
        if (id != global.activeWidget.projectId) {
            setActiveWidget(id, projectDir);
        }
    });
}

function setActiveWidget(id, projDir) {
    console.log("setActiveWidget - id: " + id);

    var previousActiveWidget = global.activeWidget;

    var activeWidget = {};
    activeWidget.widgetId = "projectWidget_" + id.toString();
    activeWidget.projectId = id;
    global.activeWidget = activeWidget;
    localStorage.projDir = projDir;

    // update GUI to display details of the active widget
    var iconId = "icon_" + id.toString();
    global.jQuery("#" + activeWidget.widgetId).css("background-color", "#C4C4C4");
    global.jQuery("#" + iconId).text("rectangleoutline");

    // turn on the server
    global.jQuery("#server-status").prop("checked", true);
    toggleServerStatus();

    // reset the previous active widget
    if (previousActiveWidget) {
        var prevIconId = "icon_" + previousActiveWidget.projectId.toString();
        global.jQuery("#" + previousActiveWidget.widgetId).css("background-color", "");
        global.jQuery("#" + prevIconId).text("arrowright");
    }
}

function removeProjectWidget() {
    console.log("removeProjectWidget - id: " + global.activeWidget.projectId);
    global.jQuery("#" + global.activeWidget.widgetId).remove();
    removeProjectById(global.activeWidget.projectId);
}

function toggleServerStatus() {
    console.log("toggleServerStatus");

    if (global.isServerRunning) {
        global.server.close();
        global.isServerRunning = false;
    }

    if (global.jQuery("#server-status").is(":checked")) {
        fs.exists(localStorage.projDir + "/www", function(exists) {
            if (exists) {
                process.chdir(localStorage.projDir);

                console.log("server started");
                console.log("project opened at: " + localStorage.projDir);

                global.pgServer.listen({ port: localStorage.portNumber })
                .on("complete", function(data) {
                    console.log("server started at: " + data.address + ":" + data.port);
                    global.server = data.server;
                    global.isServerRunning = true;
                    global.jQuery("#server-status-label").text("http://" + data.address + ":" + data.port);
                    global.jQuery("#log").prop("disabled", false);
                })
                .on("error", function(e) {
                    console.log(e.message);
                })
                .on("log", function(status, url) {
                    console.log(status, url);
                    global.jQuery("#serverLog").append(status + " " + url + "\n");
                });
            } else {
                var errMsg = "an existing project doesn't exist in this folder";
                console.log(errMsg);
                global.jQuery("#server-status").prop("checked", false);
                global.jQuery("#log").prop("disabled", true);
            }
        });

     } else {
         //console.log("server stopped");
         if (global.isServerRunning) {
             global.server.close();
             global.isServerRunning = false;
         }

         global.jQuery("#server-status-label").text("server is offline");
         global.jQuery("#log").prop("disabled", true);
     }
}<commit_msg>[#49] added the checkbox to the project widget<commit_after>function addProjectWidget(id, projectName, projectVersion, projectIcon, projectDir) {
    console.log("addProjectWidget");

    var widgetId = "projectWidget_" + id.toString();
    var iconId = "icon_" + id.toString();
    var projectStatusId = "project-status_" + id.toString();

    var widgetDOM = "";
    widgetDOM += "
";

    widgetDOM += "
";
    widgetDOM += "

";
    widgetDOM += "
";
    widgetDOM += projectName + "
";
    widgetDOM += projectVersion + "

";

    widgetDOM += "
";
    widgetDOM += "<input type='checkbox' disabled='true' id='" + projectStatusId + "' />";
    widgetDOM += " ";
    widgetDOM += "
";

    //widgetDOM += "
arrowright
";
    widgetDOM += "
";  // row 1

    widgetDOM += "
";
    widgetDOM += "
" + projectDir + "
";
    widgetDOM += "
";  // row 2

    widgetDOM += "
";  // table

    global.jQuery("#drop_zone").append(widgetDOM);

    global.jQuery("#" + widgetId).on("click", function() {
        var temp = global.jQuery("#" + widgetId).attr("id").split("_");
        var id = temp[1];

        // only allow setting of active widget if another project widget is selected
        if (id != global.activeWidget.projectId) {
            setActiveWidget(id, projectDir);
        }
    });
}

function setActiveWidget(id, projDir) {
    console.log("setActiveWidget - id: " + id);

    var previousActiveWidget = global.activeWidget;

    var activeWidget = {};
    activeWidget.widgetId = "projectWidget_" + id.toString();
    activeWidget.projectId = id;
    global.activeWidget = activeWidget;
    localStorage.projDir = projDir;

    // update GUI to display details of the active widget
    var iconId = "icon_" + id.toString();
    var projectStatusId = "project-status_" + id.toString();
    global.jQuery("#" + activeWidget.widgetId).css("background-color", "#C4C4C4");
    global.jQuery("#" + iconId).text("rectangleoutline");
    global.jQuery("#" + projectStatusId).prop("checked", true);

    // turn on the server
    global.jQuery("#server-status").prop("checked", true);
    toggleServerStatus();

    // reset the previous active widget
    if (previousActiveWidget) {
        var prevIconId = "icon_" + previousActiveWidget.projectId.toString();
        var prevProjectStatusId = "project-status_" + previousActiveWidget.projectId.toString();
        global.jQuery("#" + prevProjectStatusId).prop("checked", false);
        global.jQuery("#" + previousActiveWidget.widgetId).css("background-color", "");
        global.jQuery("#" + prevIconId).text("arrowright");
    }
}

function removeProjectWidget() {
    console.log("removeProjectWidget - id: " + global.activeWidget.projectId);
    global.jQuery("#" + global.activeWidget.widgetId).remove();
    removeProjectById(global.activeWidget.projectId);
}

function toggleServerStatus() {
    console.log("toggleServerStatus");

    if (global.isServerRunning) {
        global.server.close();
        global.isServerRunning = false;
    }

    if (global.jQuery("#server-status").is(":checked")) {
        fs.exists(localStorage.projDir + "/www", function(exists) {
            if (exists) {
                process.chdir(localStorage.projDir);

                console.log("server started");
                console.log("project opened at: " + localStorage.projDir);

                global.pgServer.listen({ port: localStorage.portNumber })
                .on("complete", function(data) {
                    console.log("server started at: " + data.address + ":" + data.port);
                    global.server = data.server;
                    global.isServerRunning = true;
                    global.jQuery("#server-status-label").text("http://" + data.address + ":" + data.port);
                    global.jQuery("#log").prop("disabled", false);
                })
                .on("error", function(e) {
                    console.log(e.message);
                })
                .on("log", function(status, url) {
                    console.log(status, url);
                    global.jQuery("#serverLog").append(status + " " + url + "\n");
                });
            } else {
                var errMsg = "an existing project doesn't exist in this folder";
                console.log(errMsg);
                global.jQuery("#server-status").prop("checked", false);
                global.jQuery("#log").prop("disabled", true);
            }
        });

     } else {
         //console.log("server stopped");
         if (global.isServerRunning) {
             global.server.close();
             global.isServerRunning = false;
         }

         global.jQuery("#server-status-label").text("server is offline");
         global.jQuery("#log").prop("disabled", true);
     }
}<|endoftext|>


<commit_before>/*! pathfinding-visualiser | (c) 2014 Daniel Imms | https://github.com/Tyriar/pathfinding-visualiser/blob/master/LICENSE */
// UMD pattern: https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['core'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('./core'));
  } else {
    root.canvasHelper = factory(core);
  }
}(this, function (core) {
  'use strict';

  var module = {};

  var PATH_WIDTH        = 4;
  var BACKGROUND_COLOUR = '#EEE';
  var OBSTACLE_COLOUR   = '#2D2D30';
  var PATH_COLOUR       = '#0C0';
  var VISITED_COLOUR    = '#44F';
  var OPEN_LIST_COLOUR  = '#88F';

  var canvas;
  var context;

  module.setCanvas = function (canvasElement) {
    canvas = canvasElement;
    if (canvas && canvas.getContext) {
      context = canvas.getContext('2d');
    }
  };

  module.drawObstacles = function (map) {
    for (var x = 0; x < core.MAP_WIDTH; x++) {
      for (var y = 0; y < core.MAP_HEIGHT; y++) {
        if (!map[x][y]) {
          module.drawObstacle(x, y);
        }
      }
    }
  };

  module.drawObstacle = function (x, y) {
    module.drawNode(x, y, OBSTACLE_COLOUR);
  };

  module.clearObstacle = function (x, y) {
    module.drawNode(x, y, BACKGROUND_COLOUR);
  };

  module.drawVisited = function (x, y) {
    module.drawNode(x, y, VISITED_COLOUR);
  };

  module.drawOpenListNode = function (x, y) {
    module.drawNode(x, y, OPEN_LIST_COLOUR);
  };

  module.drawStartGoal = function (x, y) {
    module.drawNode(x, y, PATH_COLOUR);
  };

  module.drawNode = function (x, y, COLOUR) {
    context.fillStyle = COLOUR;
    context.fillRect(x * core.MAP_SCALE, y * core.MAP_SCALE, core.MAP_SCALE, core.MAP_SCALE);
  };

  module.clearCanvas = function () {
    context.fillStyle = BACKGROUND_COLOUR;
    context.fillRect(0, 0, core.CANVAS_WIDTH, core.CANVAS_HEIGHT);
  };

  module.draw = function (closedList, openList, startNode, goalNode) {
    module.drawStartGoal(goalNode.x, goalNode.y);
    module.drawStartGoal(startNode.x, startNode.y);

    context.beginPath();
    context.moveTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);

    while (goalNode.parent) {
      goalNode = goalNode.parent;
      context.lineTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);
    }

    for (var i = 0; i < openList.length; i++) {
      module.drawOpenListNode(openList[i].x, openList[i].y);
    }

    context.strokeStyle = PATH_COLOUR;
    context.lineWidth = PATH_WIDTH;
    context.stroke();
    context.closePath();
  };

  module.getCanvasWidth = function () {
    canvas.setAttribute('width', canvas.clientWidth);
    return canvas.clientWidth;
  };

  module.getCanvasHeight = function () {
    canvas.setAttribute('height', canvas.clientHeight);
    return canvas.clientHeight;
  };

  return module;
}));
<commit_msg>Draw the goal node after the open list<commit_after>/*! pathfinding-visualiser | (c) 2014 Daniel Imms | https://github.com/Tyriar/pathfinding-visualiser/blob/master/LICENSE */
// UMD pattern: https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['core'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('./core'));
  } else {
    root.canvasHelper = factory(core);
  }
}(this, function (core) {
  'use strict';

  var module = {};

  var PATH_WIDTH        = 4;
  var BACKGROUND_COLOUR = '#EEE';
  var OBSTACLE_COLOUR   = '#2D2D30';
  var PATH_COLOUR       = '#0C0';
  var VISITED_COLOUR    = '#44F';
  var OPEN_LIST_COLOUR  = '#88F';

  var canvas;
  var context;

  module.setCanvas = function (canvasElement) {
    canvas = canvasElement;
    if (canvas && canvas.getContext) {
      context = canvas.getContext('2d');
    }
  };

  module.drawObstacles = function (map) {
    for (var x = 0; x < core.MAP_WIDTH; x++) {
      for (var y = 0; y < core.MAP_HEIGHT; y++) {
        if (!map[x][y]) {
          module.drawObstacle(x, y);
        }
      }
    }
  };

  module.drawObstacle = function (x, y) {
    module.drawNode(x, y, OBSTACLE_COLOUR);
  };

  module.clearObstacle = function (x, y) {
    module.drawNode(x, y, BACKGROUND_COLOUR);
  };

  module.drawVisited = function (x, y) {
    module.drawNode(x, y, VISITED_COLOUR);
  };

  module.drawOpenListNode = function (x, y) {
    module.drawNode(x, y, OPEN_LIST_COLOUR);
  };

  module.drawStartGoal = function (x, y) {
    module.drawNode(x, y, PATH_COLOUR);
  };

  module.drawNode = function (x, y, COLOUR) {
    context.fillStyle = COLOUR;
    context.fillRect(x * core.MAP_SCALE, y * core.MAP_SCALE, core.MAP_SCALE, core.MAP_SCALE);
  };

  module.clearCanvas = function () {
    context.fillStyle = BACKGROUND_COLOUR;
    context.fillRect(0, 0, core.CANVAS_WIDTH, core.CANVAS_HEIGHT);
  };

  module.draw = function (closedList, openList, startNode, goalNode) {
    module.drawStartGoal(goalNode.x, goalNode.y);
    module.drawStartGoal(startNode.x, startNode.y);

    context.beginPath();
    context.moveTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);

    for (var i = 0; i < openList.length; i++) {
      module.drawOpenListNode(openList[i].x, openList[i].y);
    }

    while (goalNode.parent) {
      goalNode = goalNode.parent;
      context.lineTo((goalNode.x + 0.5) * core.MAP_SCALE, (goalNode.y + 0.5) * core.MAP_SCALE);
    }

    context.strokeStyle = PATH_COLOUR;
    context.lineWidth = PATH_WIDTH;
    context.stroke();
    context.closePath();
  };

  module.getCanvasWidth = function () {
    canvas.setAttribute('width', canvas.clientWidth);
    return canvas.clientWidth;
  };

  module.getCanvasHeight = function () {
    canvas.setAttribute('height', canvas.clientHeight);
    return canvas.clientHeight;
  };

  return module;
}));
<|endoftext|>


<commit_before>/**
 *
 * View for user-submitted feedback.
 *
 */
Atmo.Views.FeedbackLink = Backbone.View.extend({
	initialize: function() {
		var self = this;
		this.$el.popover({
			placement : 'top',
			title: 'Feedback Form &times',
            html: true,
			trigger: 'click',
            content: _.template(Atmo.Templates.feedback_form),
		}).click(function() {
			$('a[data-dismiss="popover"]').click(_.bind(self.cancel_popover, self));
			$('#cancel_popover').click(_.bind(self.cancel_popover, self));
			$('#submit_feedback').click(_.bind(self.submit_feedback, self));
		});
	},
	cancel_popover: function(e) {
		e.preventDefault();
		this.$el.popover('hide');
	},
	submit_feedback: function(e) {
		e.preventDefault();

		var data = {
            'user-interface': 'airport',
			'location': window.location.href,
			'resolution': {
				'viewport': {
					'width': $(window).width(),
					'height': $(window).height()
				},
		   		'screen': {
					'width':  screen.width,
					'height': screen.height
				}
			}
		};

		data["message"] = $('#feedback').val();

		// Create a list of user's instances and volumes to make support easier
		data["message"] += '\n---\n\n';
		data["message"] += 'Provider ID: ' + Atmo.profile.get('selected_identity').get('provider_id') + '\n\n';
		data["message"] += '\n\n' + Atmo.profile.get('id') + "'s Instances:";
		data["message"] += '\n---\n';
		for (var i = 0; i < Atmo.instances.length; i++) {
			var instance = Atmo.instances.models[i];
			data["message"] += '\nInstance id:\n\t' + instance.get('id') + '\nEMI Number:\n\t' + instance.get('image_id') + '\nIP Address:\n\t' + instance.get('public_dns_name') + '\n';
		}
		data["message"] += '\n\n' + Atmo.profile.get('id') + "'s Volumes:";
		data["message"] += '\n---\n';
		for (var i = 0; i < Atmo.volumes.length; i++) {
			var volume = Atmo.volumes.models[i];
			data["message"] += '\nVolume id:\n\t' + volume.get('id') + '\nVolume Name:\n\t' + volume.get('name');
		}
		data["message"] += '\n\n';

		data['location'] = window.location.href,
		data['resolution'] = {
			'viewport': {
				'width': $(window).width(),
				'height': $(window).height()
			},
			'screen': {
				'width':  screen.width,
				'height': screen.height
			}
		};

		data["user-interface"] = 'airport';

		var self = this;

		if ($('#feedback').val().length > 0) {

			$('#submit_feedback').html(' Sending...').attr('disabled', 'disabled');

			$.ajax(Atmo.API_ROOT + '/email/feedback', {
				type: 'POST',
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json',
				success: function(data) {

					// setTimeout to prevent loader gif from flashing on fast responses
					setTimeout(function() {

						$('#feedback_link').popover('hide');

						Atmo.Utils.notify("Thanks for your feedback!", "Support has been notified.");

						self.$el.popover({
							placement : 'top',
							title: 'Thanks for your feedback! &times',
							html: true,
							trigger: 'click',
							content: function() {
								var form = $('<form>');
								form.append($('', {
									'class': 'help-block',
									html: 'Feel free to submit additional comments.'
								}));
								var textarea = $('<textarea/>', {
									rows: '5',
									id: 'feedback'
								});
								form.append(textarea);
								form.append($('<button>', {
									'class': 'btn btn-primary',
									html: 'Send',
									id: 'submit_feedback',
									type: 'submit',
								}));
								form.append($('', {
									'class': 'btn',
									href: '#',
									html: 'Cancel',
									id: 'cancel_popover',
								}));
								return form;
							}
						}).click(function() {
							$('a[data-dismiss="popover"]').click(_.bind(self.cancel_popover, self));
							$('#cancel_popover').click(_.bind(self.cancel_popover, self));
							$('#submit_feedback').click(_.bind(self.submit_feedback, self));
						});

						setTimeout(function() {
							$('#feedback_link').popover('hide');
						}, 5*1000);
					}, 2*1000);
				},
				error: function(response_text) {
					Atmo.Utils.notify("An error occured", 'Your feedback could not be submitted. If you\'d like to send it directly to support, email support@iplantcollaborative.org.');
				}
			});
		}
	}
});
<commit_msg>Clean up fields, in feedback email<commit_after>/**
 *
 * View for user-submitted feedback.
 *
 */
Atmo.Views.FeedbackLink = Backbone.View.extend({
    initialize: function() {
        var self = this;
        this.$el.popover({
            placement : 'top',
            title: 'Feedback Form &times',
            html: true,
            trigger: 'click',
            content: _.template(Atmo.Templates.feedback_form),
        }).click(function() {
            $('a[data-dismiss="popover"]').click(_.bind(self.cancel_popover, self));
            $('#cancel_popover').click(_.bind(self.cancel_popover, self));
            $('#submit_feedback').click(_.bind(self.submit_feedback, self));
        });
    },
    cancel_popover: function(e) {
        e.preventDefault();
        this.$el.popover('hide');
    },
    submit_feedback: function(e) {
        e.preventDefault();

        // TODO: Send json to the feedback api rather than a string. That way
        // on the server side we can take advantage of templates. Right now
        // the feedback email is ugly. Because we use a combination of
        // templates, and a raw string.

        var data = {
            'user-interface': 'airport',
            'location': window.location.href,
            'resolution': {
                'viewport': {
                    'width': $(window).width(),
                    'height': $(window).height()
                },
                'screen': {
                    'width':  screen.width,
                    'height': screen.height
                }
            }
        };

        data["message"] = $('#feedback').val();

        // Create a list of user's instances and volumes to make support easier
        var username = Atmo.profile.get('id');
        data["message"] += '\nUsername: ' + username +
                           '\n---\n\n' +
                           'Provider: ' + Atmo.profile.get('selected_identity').get('provider_id') + '\n\n' +
                           '\n\n' + username + "'s Instances:" +
                           '\n---\n';

        for (var i = 0; i < Atmo.instances.length; i++) {
            var instance = Atmo.instances.models[i];
            data["message"] += '\nName:\n\t' + instance.get('image_name') +
                               '\nID:\n\t' + instance.get('id') +
                               '\nImage:\n\t' + instance.get('image_id') +
                               '\nIP Address:\n\t' + instance.get('public_dns_name') + '\n';
        }
        data["message"] += '\n\n' + username + "'s Volumes:" +
                           '\n---\n';

        if (Atmo.volumes.length > 0) {
            for (var i = 0; i < Atmo.volumes.length; i++) {
                var volume = Atmo.volumes.models[i];
                data["message"] += '\nID:\n\t' + volume.get('id') + '\nName:\n\t' + volume.get('name');
            }
            data["message"] += '\n\n';
        }

        var self = this;

        if ($('#feedback').val().length > 0) {

            $('#submit_feedback').html(' Sending...').attr('disabled', 'disabled');
            glob = data;
            console.log("data",data);

            $.ajax(Atmo.API_ROOT + '/email/feedback', {
                type: 'POST',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: 'application/json',
                success: function(data) {

                    // setTimeout to prevent loader gif from flashing on fast responses
                    setTimeout(function() {

                        $('#feedback_link').popover('hide');

                        Atmo.Utils.notify("Thanks for your feedback!", "Support has been notified.");

                    }, 2*1000);
                },
                error: function(response_text) {
                    Atmo.Utils.notify("An error occured", 'Your feedback could not be submitted. If you\'d like to send it directly to support, email support@iplantcollaborative.org.');
                }
            });
        }
    }
});
<|endoftext|>


<commit_before>'use strict';

app.controller('party/profile', [
  '$scope', 'displayService', 'party', 'pageService','constantService',
  function ($scope, display, party, page, constants) {

    var getUsers = function(volumes){

      var users = {};

      users.sponsors = [];
      users.labGroupMembers = [];
      users.nonGroupAffiliates = [];
      users.otherCollaborators = [];

      _(volumes).pluck('access').flatten().each(function(v){
        if(v.children > 0 ){
          users.sponsors.push(v);
        } else if(v.parents && v.parents.length > 0 && v.party.members && v.party.members.length > 0) {
          users.labGroupMembers.push(v);
        } else if(v.parents && v.parents.length > 0){
          users.nonGroupAffiliates.push(v);
        } else {
          users.otherCollaborators.push(v);
        }

      }).value();

      return users;
    };

    $scope.clickVolume = function(volume) {

      // This is a quick helper function to make sure that the isSelected
      // class is set to empty and to avoid repeating code.
      var unSetSelected = function(v){
        v.isSelected = '';
        return v;
      };

      $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);
      $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);
      $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);

      for(var i = 0; i < volume.access.length; i += 1 ){
        for (var j = 0; j < $scope.users.sponsors.length; j += 1){
          if($scope.users.sponsors[j].id === volume.access[i].party.id){
            $scope.users.sponsors[j].isSelected = 'userSelected';
            return;
          }
        }
        for (var j = 0; j < $scope.users.labGroupMembers.length; j += 1){
          if($scope.users.labGroupMembers[j].id === volume.access[i].party.id){
            $scope.users.labGroupMembers[j].isSelected = 'userSelected';
            return;
          }
        }
        for (var j = 0; j < $scope.users.nonGroupAffiliates.length; j += 1){
          if($scope.users.nonGroupAffiliates[j].id === volume.access[i].party.id){
            $scope.users.nonGroupAffiliates[j].isSelected = 'userSelected';
            return;
          }
        }
        for (var j = 0; j < $scope.users.otherCollaborators.length; j += 1){
          if($scope.users.otherCollaborators[j].id === volume.access[i].party.id){
            $scope.users.otherCollaborators[j].isSelected = 'userSelected';
            return;
          }
        }
      }

      for(var i = 0; i < $scope.users.sponsors.length; i += 1){
        $scope.users.sponsors[i].isSelected = '';
        $scope.users.labGroupMembers[i].isSelected = '';
        $scope.users.nonGroupAffiliates[i] = '';
        $scope.users.otherCollaborators[i] = '';
        for(var j = 0; j < volume.access.length; j += 1){
          if($scope.users.sponsors[i].id === volume.access[j].party.id){
            $scope.users.sponsors[i].isSelected = 'userSelected';
            return;
          }
        }

        for(var j = 0; j < volume.access.length; j += 1){

        }
      }
    };

    // This should take in a user, then select volumes on each thing.
    $scope.clickUser = function(user){
      for(var i = 0; i < $scope.volumes.length; i += 1) {
        $scope.volumes[i].isSelected = '';
        for(var j = 0; j < $scope.volumes[i].access.length; j += 1){
          if($scope.volumes[i].access[j].id == user.party.id){
            $scope.volumes[i].isSelected = 'volumeSelected';
          }
        }
      }
    };

    var getVolumes = function(volumes) {
      var tempVolumes = {};
      tempVolumes.individual = [];
      tempVolumes.collaborator = [];
      tempVolumes.inherited = [];

      _.each(volumes, function(v){
        if(v.isIndividual){
          tempVolumes.individual.push(v);
	} else if(tempVolumes.isCollaborator){
          tempVolumes.collaborator.push(v);
	} else{
          tempVolumes.inherited.push(v);
	}
      });
      return tempVolumes;
    };

    $scope.party = party;
    $scope.volumes = getVolumes(party.volumes);
    console.log(party.volumes);
    $scope.users = getUsers(party.volumes);
    console.log($scope.users);
    $scope.page = page;
    $scope.profile = page.$location.path() === '/profile';
    display.title = party.name;
  }
]);
<commit_msg>Get rid of bad for loop<commit_after>'use strict';

app.controller('party/profile', [
  '$scope', 'displayService', 'party', 'pageService','constantService',
  function ($scope, display, party, page, constants) {

    var getUsers = function(volumes){

      var users = {};

      users.sponsors = [];
      users.labGroupMembers = [];
      users.nonGroupAffiliates = [];
      users.otherCollaborators = [];

      _(volumes).pluck('access').flatten().each(function(v){
        if(v.children > 0 ){
          users.sponsors.push(v);
        } else if(v.parents && v.parents.length > 0 && v.party.members && v.party.members.length > 0) {
          users.labGroupMembers.push(v);
        } else if(v.parents && v.parents.length > 0){
          users.nonGroupAffiliates.push(v);
        } else {
          users.otherCollaborators.push(v);
        }

      }).value();

      return users;
    };

    $scope.clickVolume = function(volume) {

      // This is a quick helper function to make sure that the isSelected
      // class is set to empty and to avoid repeating code.
      var unSetSelected = function(v){
        v.isSelected = '';
        return v;
      };

      $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);
      $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);
      $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);

      for(var i = 0; i < volume.access.length; i += 1 ){
        for (var j = 0; j < $scope.users.sponsors.length; j += 1){
          if($scope.users.sponsors[j].id === volume.access[i].party.id){
            $scope.users.sponsors[j].isSelected = 'userSelected';
            return;
          }
        }
        for (var j = 0; j < $scope.users.labGroupMembers.length; j += 1){
          if($scope.users.labGroupMembers[j].id === volume.access[i].party.id){
            $scope.users.labGroupMembers[j].isSelected = 'userSelected';
            return;
          }
        }
        for (var j = 0; j < $scope.users.nonGroupAffiliates.length; j += 1){
          if($scope.users.nonGroupAffiliates[j].id === volume.access[i].party.id){
            $scope.users.nonGroupAffiliates[j].isSelected = 'userSelected';
            return;
          }
        }
        for (var j = 0; j < $scope.users.otherCollaborators.length; j += 1){
          if($scope.users.otherCollaborators[j].id === volume.access[i].party.id){
            $scope.users.otherCollaborators[j].isSelected = 'userSelected';
            return;
          }
        }
      }
    };

    // This should take in a user, then select volumes on each thing.
    $scope.clickUser = function(user){
      for(var i = 0; i < $scope.volumes.length; i += 1) {
        $scope.volumes[i].isSelected = '';
        for(var j = 0; j < $scope.volumes[i].access.length; j += 1){
          if($scope.volumes[i].access[j].id == user.party.id){
            $scope.volumes[i].isSelected = 'volumeSelected';
          }
        }
      }
    };

    var getVolumes = function(volumes) {
      var tempVolumes = {};
      tempVolumes.individual = [];
      tempVolumes.collaborator = [];
      tempVolumes.inherited = [];

      _.each(volumes, function(v){
        if(v.isIndividual){
          tempVolumes.individual.push(v);
	} else if(tempVolumes.isCollaborator){
          tempVolumes.collaborator.push(v);
	} else{
          tempVolumes.inherited.push(v);
	}
      });
      return tempVolumes;
    };

    $scope.party = party;
    $scope.volumes = getVolumes(party.volumes);
    console.log(party.volumes);
    $scope.users = getUsers(party.volumes);
    console.log($scope.users);
    $scope.page = page;
    $scope.profile = page.$location.path() === '/profile';
    display.title = party.name;
  }
]);
<|endoftext|>


<commit_before>'use strict';

const config = require('../../config');
const Facebook = require('../../app/services/facebook');
const sessions = require('../../app/services/sessions');

module.exports = {
  get: (req, reply) => {
    if (req.query['hub.verify_token'] === config.Facebook.verifyToken) {
      return reply(req.query['hub.challenge']);
    }
    return reply('Error, wrong validation token');
  },
  post: (req, reply) => {
    const witClient = req.server.plugins['keepr-bot'].witClient;
    const messaging = Facebook.getFirstMessagingEntry(req.payload);

    console.log(messaging);

    if (messaging && messaging.message) {
      const msg = messaging.message.text;
      console.log('Message: ' + msg);
      const sender = messaging.sender.id;
      const sessionId = sessions.findOrCreateSession(sender);

      witClient.runActions(sessionId, msg, sessions.getSessions()[sessionId].context,
        (error, context) => {
          if (error) {
            console.log(error);
          }
          console.log(context);

          sessions.getSessions()[sessionId].context = context;
        });
    }
    reply('Accepted').code(200)
  }
};
<commit_msg>Change to promise for Wit runactions<commit_after>'use strict';

const config = require('../../config');
const Facebook = require('../../app/services/facebook');
const sessions = require('../../app/services/sessions');

module.exports = {
  get: (req, reply) => {
    if (req.query['hub.verify_token'] === config.Facebook.verifyToken) {
      return reply(req.query['hub.challenge']);
    }
    return reply('Error, wrong validation token');
  },
  post: (req, reply) => {
    const witClient = req.server.plugins['keepr-bot'].witClient;
    const messaging = Facebook.getFirstMessagingEntry(req.payload);

    console.log(messaging);

    if (messaging && messaging.message) {
      const msg = messaging.message.text;
      console.log('Message: ' + msg);
      const sender = messaging.sender.id;
      const sessionId = sessions.findOrCreateSession(sender);
      const session = sessions.getSessions()[sessionId];

      witClient.runActions(sessionId, msg, session.context).then((context) => {
        console.log(context);
        session.context = context;
      }).catch((err) => {
        console.log(err);
      });
    }
    reply('Accepted').code(200)
  }
};
<|endoftext|>