<commit_before>
function createViewBuilderFactory(filterFactory, sortFactory) {

    const _createBuilder = function(itemType, viewHandler) {

        let _view = null;

        let _eagerType = 'full';

        let _offset = 0;

        let _count = 0;

        let _pageSize = 0;

        const _filters = [];

        const _sorts = [];

        return {

            hasView: function() {
                return !!_view;
            },

            view: function() {
                if (!this.hasView())
                {
                    _view = viewHandler.createView(itemType, this);
                }
                return _view;
            },

            get viewId() {
                return view().viewId;
            },

            get ready() {
                return view().ready;
            },

            get outdated() {
                return view().outdated;
            },

            get itemType() {
                return viewHandler.itemType;
            },

            get loading() {
                return view().loading;
            },

            get loadingFailed() {
                return view().loadingFailed;
            },

            get loadingMetaOffset() {
                return view().loadingMetaOffset;
            },

            get loadingMetaCount() {
                return view().loadingMetaCount;
            },

            get loadingMetaPage() {
                return view().loadingMetaPage;
            },

            get loadingMetaPageSize() {
                return view().loadingMetaPageSize;
            },

            get loadingMetaTotalCount() {
                return view().loadingMetaTotalCount;
            },

            get itemsHash() {
                return view().itemsHash;
            },

            get items() {
                return view().items;
            },

            get first() {
                return view().first;
            },

            get last() {
                return view().last;
            },

            get eagerType() {
                return _eagerType;
            },

            get offset() {
                return _offset;
            },

            get count() {
                return _count;
            },

            get pageSize() {
                return _pageSize;
            },

            get filters() {
                return _filters;
            },

            get sorts() {
                return _sorts;
            },

            addFilter: function(filter) {
                if (!this.hasView()) {
                    _filters[] = filter;
                }
                return this;
            },

            filterId: function(id) {
                return this.addFilter(filterFactory.createFilterId(id))
            },

            filterIds: function(ids) {
                return this.addFilter(filterFactory.createFilterIds(ids))
            },

            filterExp: function(key, operator, value) {
                return this.addFilter(filterFactory.createFilterExp(key, operator, value))
            },

            filterIn: function(key, values) {
                return this.addFilter(filterFactory.createFilterIn(key, values))
            },

            addSort: function(sort) {
                if (!this.hasView()) {
                    _sorts[] = sort;
                }
                return this;
            },

            sort: function(key, order) {
                return this.addSort(sortFactory.createSort(key, order));
            },

            setEagerType: function(eagerType) {
                if (!this.hasView()) {
                    _eagerType = eagerType;
                }
                return this;
            },

            setPagination: function(page, pageSize) {
                if (!this.hasView()) {
                    _offset = (page * pageSize) - pageSize;
                    _count = pageSize;
                    _pageSize = pageSize;
                }
                return this;
            },

            setLimit: function(offset, count) {
                if (!this.hasView()) {
                    _offset = offset;
                    _count = count;
                    _pageSize = 0;
                }
                return this;
            },

            buildEagerHash: function() {
                return this.eagerType ? 'eager=' + this.eagerType : '';
            },

            buildOffsetHash: function() {
                return this.offset ? 'offs=' + this.offset : '';
            },

            buildCountHash: function() {
                return this.count ? 'cnt=' + this.count : '';
            },

            buildPageSizeHash: function() {
                return this.pageSize ? 'psz=' + this.pageSize : '';
            },

            buildFiltersHash: function() {
                const filterHashes = this.filters.map(filter => filter.hash());
                return filterHashes.length ? 'filters=' + filterHashes.join(',') : '';
            },

            buildSortsHash: function() {
                const sortHashes = this.sorts.map(sort => sort.hash());
                return sortHashes.length ? 'sorts=' + sortHashes.join(',') : '';
            },

            buildHash = function() {
                const hashes = [
                    this.buildEagerHash(),
                    this.buildOffsetHash(),
                    this.buildCountHash(),
                    this.buildPageSizeHash(),
                    this.buildFiltersHash(),
                    this.buildSortsHash()
                ];
                return hashes.join('&');
            };

            load: function() {
                view().load();
            },
        }
    }

    return {

        createBuilder: _createBuilder,

    };
}

export default createViewBuilderFactory;
<commit_msg>added Views setter<commit_after>
function createViewBuilderFactory(filterFactory, sortFactory) {

    const _createBuilder = function(itemType, viewHandler) {

        let _view = null;

        let _eagerType = 'full';

        let _offset = 0;

        let _count = 0;

        let _pageSize = 0;

        const _filters = [];

        const _sorts = [];

        return {

            hasView: function() {
                return !!_view;
            },

            view: function() {
                if (!this.hasView())
                {
                    _view = viewHandler.createView(itemType, this);
                }
                return _view;
            },

            get viewId() {
                return this.view().viewId;
            },

            get ready() {
                return this.view().ready;
            },

            get outdated() {
                return this.view().outdated;
            },

            get itemType() {
                return viewHandler.itemType;
            },

            get loading() {
                return this.view().loading;
            },

            get loadingFailed() {
                return this.view().loadingFailed;
            },

            get loadingMetaOffset() {
                return this.view().loadingMetaOffset;
            },

            get loadingMetaCount() {
                return this.view().loadingMetaCount;
            },

            get loadingMetaPage() {
                return this.view().loadingMetaPage;
            },

            get loadingMetaPageSize() {
                return this.view().loadingMetaPageSize;
            },

            get loadingMetaTotalCount() {
                return this.view().loadingMetaTotalCount;
            },

            get itemsHash() {
                return this.view().itemsHash;
            },

            get items() {
                return this.view().items;
            },

            get first() {
                return this.view().first;
            },

            get last() {
                return this.view().last;
            },

            setReady: function(ready) {
                this.view().setReady(ready);
                return this;
            },

            setOutdated: function(outdated) {
                this.view().setOutdated(outdated);
                return this;
            },

            setLoading: function(loading) {
                this.view().setLoading(loading);
                return this;
            },

            setLoadingFailed: function(loadingFailed) {
                this.view().setLoadingFailed(loadingFailed);
                return this;
            },

            updateLoadingMeta: function(loadingMeta) {
                this.view().updateLoadingMeta(loadingMeta);
                return this;
            },

            setItemsHash: function(itemsHash) {
                this.view().setItemsHash(itemsHash);
                return this;
            },

            setItems: function(items) {
                this.view().setItems(items);
                return this;
            },

            handleLoadingReady: function(items, itemsHash, meta) {
                this.view().handleLoadingReady(items, itemsHash, meta);
                return this;
            },

            handleLoadingCanceled: function() {
                this.view().handleLoadingReady();
                return this;
            },

            handleLoadingFailed: function(errors) {
                this.view().handleLoadingFailed(errors);
                return this;
            },

            load: function() {
                this.view().load();
                return this;
            },

            markAsOutdated: function() {
                this.view().setOutdated(true);
                return this;
            },

            get eagerType() {
                return _eagerType;
            },

            get offset() {
                return _offset;
            },

            get count() {
                return _count;
            },

            get pageSize() {
                return _pageSize;
            },

            get filters() {
                return _filters;
            },

            get sorts() {
                return _sorts;
            },

            addFilter: function(filter) {
                if (!this.hasView()) {
                    _filters[] = filter;
                }
                return this;
            },

            filterId: function(id) {
                return this.addFilter(filterFactory.createFilterId(id))
            },

            filterIds: function(ids) {
                return this.addFilter(filterFactory.createFilterIds(ids))
            },

            filterExp: function(key, operator, value) {
                return this.addFilter(filterFactory.createFilterExp(key, operator, value))
            },

            filterIn: function(key, values) {
                return this.addFilter(filterFactory.createFilterIn(key, values))
            },

            addSort: function(sort) {
                if (!this.hasView()) {
                    _sorts[] = sort;
                }
                return this;
            },

            sort: function(key, order) {
                return this.addSort(sortFactory.createSort(key, order));
            },

            setEagerType: function(eagerType) {
                if (!this.hasView()) {
                    _eagerType = eagerType;
                }
                return this;
            },

            setPagination: function(page, pageSize) {
                if (!this.hasView()) {
                    _offset = (page * pageSize) - pageSize;
                    _count = pageSize;
                    _pageSize = pageSize;
                }
                return this;
            },

            setLimit: function(offset, count) {
                if (!this.hasView()) {
                    _offset = offset;
                    _count = count;
                    _pageSize = 0;
                }
                return this;
            },

            buildEagerHash: function() {
                return this.eagerType ? 'eager=' + this.eagerType : '';
            },

            buildOffsetHash: function() {
                return this.offset ? 'offs=' + this.offset : '';
            },

            buildCountHash: function() {
                return this.count ? 'cnt=' + this.count : '';
            },

            buildPageSizeHash: function() {
                return this.pageSize ? 'psz=' + this.pageSize : '';
            },

            buildFiltersHash: function() {
                const filterHashes = this.filters.map(filter => filter.hash());
                return filterHashes.length ? 'filters=' + filterHashes.join(',') : '';
            },

            buildSortsHash: function() {
                const sortHashes = this.sorts.map(sort => sort.hash());
                return sortHashes.length ? 'sorts=' + sortHashes.join(',') : '';
            },

            buildHash = function() {
                const hashes = [
                    this.buildEagerHash(),
                    this.buildOffsetHash(),
                    this.buildCountHash(),
                    this.buildPageSizeHash(),
                    this.buildFiltersHash(),
                    this.buildSortsHash()
                ];
                return hashes.join('&');
            };

            load: function() {
                view().load();
            },
        }
    }

    return {

        createBuilder: _createBuilder,

    };
}

export default createViewBuilderFactory;
<|endoftext|>


<commit_before>/** Called automatically by JsDoc Toolkit. */
load(JSDOC.opt.t + 'src/Symbol.js');
load(JSDOC.opt.t + 'src/Utils.js');
load(JSDOC.opt.t + 'src/Operator.js');
load(JSDOC.opt.t + 'src/Render.js');

function publish(symbolSet) {
	var renderMode = JSDOC.opt.D.renderMode;
	publish.conf = {  // trailing slash expected for dirs
		ext: renderMode == 'docs' ? '.html' : '.jstl',
		outDir: JSDOC.opt.d || SYS.pwd + '../out/jsdoc/',
		templateDir: JSDOC.opt.t || SYS.pwd + '../templates/jsdoc/',
		staticDir: (JSDOC.opt.t || SYS.pwd + '../templates/jsdoc/') + 'static/',
		symbolsDir: renderMode == 'docs' ? 'packages/' : 'paper/',
		srcDir: 'symbols/src/',
		renderMode: renderMode,
		globalName: 'Global Scope'
	};
	publish.conf.packagesDir = publish.conf.outDir + publish.conf.symbolsDir;

	if (renderMode == 'docs') {
		// Copy over the static files
		Utils.copyDirectory(
			new java.io.File(publish.conf.staticDir),
			new java.io.File(publish.conf.outDir)
		);
	} else {
		Utils.deleteFiles(new File(publish.conf.outDir));
		new java.io.File(publish.conf.outDir + 'paper/').mkdirs();
	}

	// used to allow Link to check the details of things being linked to
	Link.symbolSet = symbolSet;

	// get an array version of the symbolset, useful for filtering
	var symbols = symbolSet.toArray(),
		files = JSDOC.opt.srcFiles,
		aliasSort = Utils.makeSortby('alias'),
 		classes = symbols.filter(Utils.isaClass).sort(aliasSort);

	// create a filemap in which outfiles must be to be named uniquely, ignoring case
	if (JSDOC.opt.u) {
		var filemapCounts = {};
		Link.filemap = {};
		for (var i = 0, l = classes.length; i < l; i++) {
			var lcAlias = classes[i].alias.toLowerCase();

			if (!filemapCounts[lcAlias]) {
				filemapCounts[lcAlias] = 1;
			} else {
				filemapCounts[lcAlias]++;
			}

			Link.filemap[classes[i].alias] =  (filemapCounts[lcAlias] > 1) ?
				lcAlias + '_' + filemapCounts[lcAlias] : lcAlias;
		}
	}

	Link.base = '../';

	// create each of the class pages
	for (var i = 0, l = classes.length; i < l; i++) {
		var symbol = classes[i];

		symbol.events = symbol.getEvents();   // 1 order matters
		symbol.methods = symbol.getMethods(); // 2
		for (var j = 0; j < symbol.methods.length; j++) {
			var method = symbol.methods[j];
			method.isOperator = Operator.isOperator(method);
		}

		Link.currentSymbol= symbol;
		var html = Render._class(symbol);
		var name = ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias)
				+ publish.conf.ext;
		if (renderMode == 'docs') {
			html = Render.html({
				content: html,
				title: symbol.alias
			});
		}
		IO.saveFile(publish.conf.packagesDir, name, html);
	}
	if (renderMode == 'docs')
		Utils.publishMenu();
	if (renderMode == 'templatedocs') {
		IO.saveFile(publish.conf.outDir, 'packages.js', Render.packagesjs());
	}
}<commit_msg>JSDocs: Have templatedocs generate lowercased links through the use of Link.filemap.<commit_after>/** Called automatically by JsDoc Toolkit. */
load(JSDOC.opt.t + 'src/Symbol.js');
load(JSDOC.opt.t + 'src/Utils.js');
load(JSDOC.opt.t + 'src/Operator.js');
load(JSDOC.opt.t + 'src/Render.js');

function publish(symbolSet) {
	var renderMode = JSDOC.opt.D.renderMode;
	publish.conf = {  // trailing slash expected for dirs
		ext: renderMode == 'docs' ? '.html' : '.jstl',
		outDir: JSDOC.opt.d || SYS.pwd + '../out/jsdoc/',
		templateDir: JSDOC.opt.t || SYS.pwd + '../templates/jsdoc/',
		staticDir: (JSDOC.opt.t || SYS.pwd + '../templates/jsdoc/') + 'static/',
		symbolsDir: renderMode == 'docs' ? 'packages/' : 'paper/',
		srcDir: 'symbols/src/',
		renderMode: renderMode,
		globalName: 'Global Scope'
	};
	publish.conf.packagesDir = publish.conf.outDir + publish.conf.symbolsDir;

	if (renderMode == 'docs') {
		// Copy over the static files
		Utils.copyDirectory(
			new java.io.File(publish.conf.staticDir),
			new java.io.File(publish.conf.outDir)
		);
	} else {
		Utils.deleteFiles(new File(publish.conf.outDir));
		new java.io.File(publish.conf.outDir + 'paper/').mkdirs();
	}

	// used to allow Link to check the details of things being linked to
	Link.symbolSet = symbolSet;

	// get an array version of the symbolset, useful for filtering
	var symbols = symbolSet.toArray(),
		files = JSDOC.opt.srcFiles,
		aliasSort = Utils.makeSortby('alias'),
 		classes = symbols.filter(Utils.isaClass).sort(aliasSort);

	// create a filemap in which outfiles must be to be named uniquely, ignoring case
	// Since we want lowercase links in templatedocs, we always use this
	if (JSDOC.opt.u || templatedocs) {
		var filemapCounts = {};
		Link.filemap = {};
		for (var i = 0, l = classes.length; i < l; i++) {
			var alias = classes[i].alias,
				lcAlias = alias.toLowerCase();

			if (!filemapCounts[lcAlias]) {
				filemapCounts[lcAlias] = 1;
			} else {
				filemapCounts[lcAlias]++;
			}
			// Use lowercase links for templatedocs
			var linkAlias = templatedocs ? lcAlias : alias;
			Link.filemap[alias] = filemapCounts[lcAlias] > 1
					? linkAlias + '_' + filemapCounts[lcAlias] : linkAlias;
		}
	}

	Link.base = '../';

	// create each of the class pages
	for (var i = 0, l = classes.length; i < l; i++) {
		var symbol = classes[i];

		symbol.events = symbol.getEvents();   // 1 order matters
		symbol.methods = symbol.getMethods(); // 2
		for (var j = 0; j < symbol.methods.length; j++) {
			var method = symbol.methods[j];
			method.isOperator = Operator.isOperator(method);
		}

		Link.currentSymbol= symbol;
		var html = Render._class(symbol);
		var name = ((JSDOC.opt.u)? Link.filemap[symbol.alias] : symbol.alias)
				+ publish.conf.ext;
		if (renderMode == 'docs') {
			html = Render.html({
				content: html,
				title: symbol.alias
			});
		}
		IO.saveFile(publish.conf.packagesDir, name, html);
	}
	if (renderMode == 'docs')
		Utils.publishMenu();
	if (renderMode == 'templatedocs') {
		IO.saveFile(publish.conf.outDir, 'packages.js', Render.packagesjs());
	}
}<|endoftext|>


<commit_before>/*
import dependencies
*/

import Vue from 'vue'
import Chat from '@/components/Chat'
import ElementUI from 'element-ui'
import VueResource from 'vue-resource'
import VueLocalStorage from 'vue-localstorage'
import VueUpload from 'vue-upload-component'
import VueRouter from 'vue-router'

/*
inject dependencies
*/

Vue.use(ElementUI)
Vue.use(VueLocalStorage)
Vue.use(VueResource)
Vue.use(VueRouter)
Vue.component('file-upload', VueUpload)

/*
test
*/

describe('Chat.vue', () => {

    it('should resume chat session if conversation id exists', () => {
    	Vue.localStorage.set('zeusId', 1)
    	const spy = sinon.spy(Chat.methods, 'getChatHistory')
        const vm = new Vue(Chat).$mount()
        expect(spy.called).to.be.true
        Chat.methods.getChatHistory.restore()
        Vue.localStorage.remove('zeusId')
    })

    it('should init new chat session if conversation id doesn\'t exist', () => {
    	const spy = sinon.spy(Chat.methods, 'getChatHistory')
        const vm = new Vue(Chat).$mount()
        expect(spy.called).to.be.false
        Chat.methods.getChatHistory.restore()
    })

    it('should successfully init new session', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			conversation_id: 1
    		}
    	})
    	const spy = sinon.spy(Chat.methods, 'sendUserMessage')
    	const vm = new Vue(Chat).$mount()
    	vm.initChatSession()
    	expect(Vue.localStorage.get('zeusId')).to.be.equal('1')
    	expect(vm.user.input).to.be.equal('')
        expect(spy.called).to.be.true
        expect(vm.uploadUrl).to.be.equal(vm.api_url + 'conversation/1/files')
        expect(vm.connectionError).to.be.false
        Chat.methods.sendUserMessage.restore()
        Vue.http.post.restore()
        Vue.localStorage.remove('zeusId')
    })

    it('should fail to init new session', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.initChatSession()
        expect(vm.connectionError).to.be.true
        Vue.http.post.restore()
    })

    it('should successfully send message and config chat (1)', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			message: 'mock',
    			file_request: ['yes'],
    			possible_answers: '["yes"]',
    			enforce_possible_answer: true
    		}
    	})
    	const clock = sinon.useFakeTimers();
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	clock.tick(1500);
    	expect(spy.called).to.be.true
    	Chat.methods.configChat.restore()
    	Vue.http.post.restore()
    	clock.restore();
    })

    it('should successfully send message and config chat (2)', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			html: 'mock',
    			file_request: ['yes'],
    			enforce_possible_answer: true
    		}
    	})
    	const clock = sinon.useFakeTimers();
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	clock.tick(1500);
    	expect(spy.called).to.be.true
    	Chat.methods.configChat.restore()
    	Vue.http.post.restore()
    	clock.restore();
    })

    it('should successfully send message and config chat (3)', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			text: 'mock',
    			file_request: ['yes'],
    			enforce_possible_answer: true,
    			possible_answers: 'null'
    		}
    	})
    	const clock = sinon.useFakeTimers();
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	clock.tick(1500);
    	expect(spy.called).to.be.true
    	Chat.methods.configChat.restore()
    	Vue.http.post.restore()
    	clock.restore();
    })

    it('should fail to send message', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	expect(vm.connectionError).to.be.true
    	Vue.http.post.restore()
    })

    it('should successfully get chat history', () => {
    	const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			messages: ['mock'],
    			name: 'Bruce Wayne'
    		}
    	})
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.zeus.input = 'mock'
    	vm.getChatHistory()
    	expect(spy.called).to.be.true
    	expect(vm.chatHistory[0]).to.be.equal('mock')
    	expect(vm.user.name).to.be.equal('Bruce Wayne')
    	Chat.methods.configChat.restore()
    	Vue.http.get.restore()
    })

    it('should fail to get chat history', () => {
    	const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.getChatHistory()
    	expect(vm.connectionError).to.be.true
    	Vue.http.get.restore()
    })

    it('should reset chat', () => {
    	const Component = Vue.extend(Chat)
    	const vm = new Component({
    		router: new VueRouter({
    			routes: [
    				{
    					path: '/'
    				}
    			]
    		})
    	}).$mount()
    	Vue.localStorage.set('zeusId', 1)
    	Vue.localStorage.set('username', 'Bruce Wayne')
    	Vue.localStorage.set('usertype', 'tenant')
    	vm.resetChat()
    	expect(Vue.localStorage.get('zeusId')).to.be.equal(null)
    	expect(Vue.localStorage.get('username')).to.be.equal(null)
    	expect(Vue.localStorage.get('usertype')).to.be.equal(null)
    })

    it('should logout', () => {
    	const Component = Vue.extend(Chat)
    	const vm = new Component({
    		router: new VueRouter({
    			routes: [
    				{
    					path: '/'
    				}
    			]
    		})
    	}).$mount()
    	vm.isLoggedIn = true
    	vm.resetChat()
    })

})
<commit_msg>[#46] Adds unit tests for setEnableUserConfirmation and confirmBotResponse functions<commit_after>/*
import dependencies
*/

import Vue from 'vue'
import Chat from '@/components/Chat'
import ElementUI from 'element-ui'
import VueResource from 'vue-resource'
import VueLocalStorage from 'vue-localstorage'
import VueUpload from 'vue-upload-component'
import VueRouter from 'vue-router'

/*
inject dependencies
*/

Vue.use(ElementUI)
Vue.use(VueLocalStorage)
Vue.use(VueResource)
Vue.use(VueRouter)
Vue.component('file-upload', VueUpload)

/*
test
*/

describe('Chat.vue', () => {

    it('should enable user confirmation prompt once chat contains questions regarding facts', () => {
        const vm = new Vue(Chat).$mount()
        expect(vm.zeus.enableUserConfirmation).to.be.false

        vm.numMessageSinceChatHistory = 10
        vm.chatHistory = []
        vm.setEnableUserConfirmation()
        expect(vm.zeus.enableUserConfirmation).to.be.true

        vm.numMessageSinceChatHistory = 0
        vm.chatHistory = [{}, {}, {}, {}, {}]
        vm.setEnableUserConfirmation()
        expect(vm.zeus.enableUserConfirmation).to.be.true
    })

    it('should disable user confirmation prompt before chat contains questions regarding facts', () => {
        const vm = new Vue(Chat).$mount()
        expect(vm.zeus.enableUserConfirmation).to.be.false
        vm.numMessageSinceChatHistory = 0
        vm.chatHistory = []
        vm.setEnableUserConfirmation()
        expect(vm.zeus.enableUserConfirmation).to.be.false
    })

    it('should resume chat session if conversation id exists', () => {
    	Vue.localStorage.set('zeusId', 1)
    	const spy = sinon.spy(Chat.methods, 'getChatHistory')
        const vm = new Vue(Chat).$mount()
        expect(spy.called).to.be.true
        Chat.methods.getChatHistory.restore()
        Vue.localStorage.remove('zeusId')
    })

    it('should init new chat session if conversation id doesn\'t exist', () => {
    	const spy = sinon.spy(Chat.methods, 'getChatHistory')
        const vm = new Vue(Chat).$mount()
        expect(spy.called).to.be.false
        Chat.methods.getChatHistory.restore()
    })

    it('should successfully init new session', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			conversation_id: 1
    		}
    	})
    	const spy = sinon.spy(Chat.methods, 'sendUserMessage')
    	const vm = new Vue(Chat).$mount()
    	vm.initChatSession()
    	expect(Vue.localStorage.get('zeusId')).to.be.equal('1')
    	expect(vm.user.input).to.be.equal('')
        expect(spy.called).to.be.true
        expect(vm.uploadUrl).to.be.equal(vm.api_url + 'conversation/1/files')
        expect(vm.connectionError).to.be.false
        Chat.methods.sendUserMessage.restore()
        Vue.http.post.restore()
        Vue.localStorage.remove('zeusId')
    })

    it('should fail to init new session', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.initChatSession()
        expect(vm.connectionError).to.be.true
        Vue.http.post.restore()
    })

    it('should successfully send user confirmation of bot repsonse ', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({})
    	const vm = new Vue(Chat).$mount()
    	vm.confirmBotResponse(true)
        expect(vm.zeus.enableUserConfirmation).to.be.false
        Vue.http.post.restore()
    })

    it('should handle the failure of sending of user confirmation of bot repsonse ', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.confirmBotResponse(true)
        expect(vm.connectionError).to.be.true
        Vue.http.post.restore()
    })

    it('should successfully send message and config chat (1)', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			message: 'mock',
    			file_request: ['yes'],
    			possible_answers: '["yes"]',
    			enforce_possible_answer: true
    		}
    	})
    	const clock = sinon.useFakeTimers();
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	clock.tick(1500);
    	expect(spy.called).to.be.true
    	Chat.methods.configChat.restore()
    	Vue.http.post.restore()
    	clock.restore();
    })

    it('should successfully send message and config chat (2)', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			html: 'mock',
    			file_request: ['yes'],
    			enforce_possible_answer: true
    		}
    	})
    	const clock = sinon.useFakeTimers();
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	clock.tick(1500);
    	expect(spy.called).to.be.true
    	Chat.methods.configChat.restore()
    	Vue.http.post.restore()
    	clock.restore();
    })

    it('should successfully send message and config chat (3)', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			text: 'mock',
    			file_request: ['yes'],
    			enforce_possible_answer: true,
    			possible_answers: 'null'
    		}
    	})
    	const clock = sinon.useFakeTimers();
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	clock.tick(1500);
    	expect(spy.called).to.be.true
    	Chat.methods.configChat.restore()
    	Vue.http.post.restore()
    	clock.restore();
    })

    it('should fail to send message', () => {
    	const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.sendUserMessage()
    	expect(vm.connectionError).to.be.true
    	Vue.http.post.restore()
    })

    it('should successfully get chat history', () => {
    	const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
    	promiseCall.resolves({
    		body: {
    			messages: ['mock'],
    			name: 'Bruce Wayne'
    		}
    	})
    	const spy = sinon.spy(Chat.methods, 'configChat')
    	const vm = new Vue(Chat).$mount()
    	vm.zeus.input = 'mock'
    	vm.getChatHistory()
    	expect(spy.called).to.be.true
    	expect(vm.chatHistory[0]).to.be.equal('mock')
    	expect(vm.user.name).to.be.equal('Bruce Wayne')
    	Chat.methods.configChat.restore()
    	Vue.http.get.restore()
    })

    it('should fail to get chat history', () => {
    	const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
    	promiseCall.rejects()
    	const vm = new Vue(Chat).$mount()
    	vm.getChatHistory()
    	expect(vm.connectionError).to.be.true
    	Vue.http.get.restore()
    })

    it('should reset chat', () => {
    	const Component = Vue.extend(Chat)
    	const vm = new Component({
    		router: new VueRouter({
    			routes: [
    				{
    					path: '/'
    				}
    			]
    		})
    	}).$mount()
    	Vue.localStorage.set('zeusId', 1)
    	Vue.localStorage.set('username', 'Bruce Wayne')
    	Vue.localStorage.set('usertype', 'tenant')
    	vm.resetChat()
    	expect(Vue.localStorage.get('zeusId')).to.be.equal(null)
    	expect(Vue.localStorage.get('username')).to.be.equal(null)
    	expect(Vue.localStorage.get('usertype')).to.be.equal(null)
    })

    it('should logout', () => {
    	const Component = Vue.extend(Chat)
    	const vm = new Component({
    		router: new VueRouter({
    			routes: [
    				{
    					path: '/'
    				}
    			]
    		})
    	}).$mount()
    	vm.isLoggedIn = true
    	vm.resetChat()
    })

})
<|endoftext|>


<commit_before>'use strict';

angular.module('gendex.controllers', [])
	.controller('GenDexCtrl', ['$scope', '$http', '$timeout', '$location', 'Data', 'StorageRequest', 'notify', 'cachedThrottle', 'StateUrl',
		function ($scope, $http, $timeout, $location, Data, StorageRequest, notify, cachedThrottle, StateUrl) {
	    $scope.shared = {
	        data: [],
	        selectedRow: [],
	        selectedGenes: [],
	        widgets: {
	            elements: {},
	            childElements: {},
	            turnedOn: {}
	        },
	        markedGenesSet: {} // all keys should be either true or deleted
	    };

	    var qArrSeperator = ",";

        /**
            default widget positions and sizes
        */
        function windowGridSize(newSize, oldSize) {
            $scope.gridCellSize = $('.windowWidthRef').width()/8;
            var hCell = 444/8;
            var hb = 8*hCell+30;
            var h8 = 8*hCell;
            var wb = 8*$scope.gridCellSize+30;
            var w8 = 8*$scope.gridCellSize;

            $scope.positions2222 = {
                zIndex: [ 5,  4,  3,  2,    1],
                left:   [ 0, wb,  0, wb,    0],
                top:    [ 0,  0, hb, hb, 2*hb],
                width:  [w8, w8, w8, w8,   w8],
                height: [h8, h8, h8, h8,   h8]
            };

            if(oldSize && newSize){
                var resizedWidthRatio = newSize/oldSize;
                var currentPositions = $scope.getWindowsInfo();
                angular.forEach(currentPositions.width, function (width, ix) {
                    currentPositions.width[ix] *= resizedWidthRatio;
                    currentPositions.height[ix] *= resizedWidthRatio;
                    currentPositions.top[ix] *= resizedWidthRatio;
                    currentPositions.left[ix] *= resizedWidthRatio;
                });
                //TODO: solve issue of scaling up from small screen where .window width is below min-width
                $scope.loadPos(currentPositions);
            }
        }
        windowGridSize();
        $scope.$watch(cachedThrottle($scope, function () {
            return $('.windowWidthRef').width();
        }, 600), windowGridSize);

        /**
            move and resize widgets
        */
        $scope.loadPos = function (q) {
            var neededList = ['zIndex', 'left', 'top', 'width', 'height'];

            var hasNeeded = _.all(neededList, function (prop) {
                return _.has(q, prop);
            });
            if (hasNeeded) {
                if(_.isString(q.zIndex)){
                    q = _.map(q, function (str) {
                        return str.split(qArrSeperator);
                    });
                }

                var infoLength = _.max(_.map(_.pick(q, neededList), _.size));

                var wins = $('.window');
                wins = wins.slice(0, infoLength);

                var keys = _.keys(q);
                var cols = _.values(q);
                var rows = _.zip(cols); //transpone
                var objs = _.map(rows, function (row) {
                    return _.object(keys, row);
                });
                wins.each(function (i) {
                    $(this).css(objs[i]);
                    $(this).addClass('animateMovement');
                });
                setTimeout(function () {
                    wins.each(function (i) {
                        $(this).removeClass('animateMovement');
                    });
                }, 200);
            }
        };

        $scope.startedWidgetsPositions = false;
        $timeout(function () {
            // loadedState part taken out of original function from GenExpress controller.js
            (localStorage.genexpressWindowsInfo) ?
            $scope.loadPos(JSON.parse(localStorage.genexpressWindowsInfo)) : $scope.loadPos($scope.positions2222);
            $scope.startedWidgetsPositions = true;
        }, 0);

        $scope.resetPos = function () {
            delete localStorage.genexpressWindowsInfo;
            windowGridSize();
            $scope.loadPos($scope.positions2222);
        };

        $scope.getWindowsInfo = function () {
            var objs = $(".window").map(function () {
                var e = $(this);
                return {
                    zIndex: parseInt(e.css("z-index")),
                    left:   parseInt(e.css("left")),
                    top:    parseInt(e.css("top")),
                    width:  e.width(),
                    height: e.height()
                };
            });

            var rows = _.map(objs, _.values);
            var cols = _.zip(rows); //transpone
            var keys = _.keys(objs[0]);

            return _.object(keys, cols);
        };

        $scope.$watch(cachedThrottle($scope, function () {
            return $scope.getWindowsInfo();
        }, 600), function (windowsInfo) {
            if ($scope.startedWidgetsPositions) {
                $scope.relativeWindowsInfo = angular.copy(windowsInfo);
                var relativeToWidth = $('.windowWidthRef').width();
                angular.forEach($scope.relativeWindowsInfo.width, function (width, ix) {
                    $scope.relativeWindowsInfo.width[ix] /= relativeToWidth;
                    $scope.relativeWindowsInfo.height[ix] /= relativeToWidth;
                    $scope.relativeWindowsInfo.top[ix] /= relativeToWidth;
                    $scope.relativeWindowsInfo.left[ix] /= relativeToWidth;
                });
                // why localStorage? remove all instances, if possible
                localStorage.genexpressWindowsInfo = JSON.stringify(windowsInfo);
            }
        }, true);

        $scope.$root.objectKeys = function (obj) {
            return _.keys(obj);
        };

	}])
;
<commit_msg>Mini clean<commit_after>'use strict';

angular.module('gendex.controllers', [])
	.controller('GenDexCtrl', ['$scope', '$http', '$timeout', '$location', 'Data', 'StorageRequest', 'notify', 'cachedThrottle', 'StateUrl',
		function ($scope, $http, $timeout, $location, Data, StorageRequest, notify, cachedThrottle, StateUrl) {
	    $scope.shared = {
	        data: [],
	        selectedRow: [],
	        selectedGenes: [],
	        widgets: {
	            elements: {},
	            childElements: {},
	            turnedOn: {}
	        },
	        markedGenesSet: {} // all keys should be either true or deleted
	    };

	    var qArrSeperator = ",";

        /**
            default widget positions and sizes
        */
        function windowGridSize(newSize, oldSize) {
            $scope.gridCellSize = $('.windowWidthRef').width()/8;
            var hCell = 444/8;
            var hb = 8*hCell+30;
            var h8 = 8*hCell;
            var wb = 8*$scope.gridCellSize+30;
            var w8 = 8*$scope.gridCellSize;

            $scope.positions2222 = {
                zIndex: [ 5,  4,  3,  2,    1],
                left:   [ 0, wb,  0, wb,    0],
                top:    [ 0,  0, hb, hb, 2*hb],
                width:  [w8, w8, w8, w8,   w8],
                height: [h8, h8, h8, h8,   h8]
            };

            if(oldSize && newSize){
                var resizedWidthRatio = newSize/oldSize;
                var currentPositions = $scope.getWindowsInfo();
                angular.forEach(currentPositions.width, function (width, ix) {
                    currentPositions.width[ix] *= resizedWidthRatio;
                    currentPositions.height[ix] *= resizedWidthRatio;
                    currentPositions.top[ix] *= resizedWidthRatio;
                    currentPositions.left[ix] *= resizedWidthRatio;
                });
                //TODO: solve issue of scaling up from small screen where .window width is below min-width
                $scope.loadPos(currentPositions);
            }
        }
        windowGridSize();
        $scope.$watch(cachedThrottle($scope, function () {
            return $('.windowWidthRef').width();
        }, 600), windowGridSize);

        /**
            move and resize widgets
        */
        $scope.loadPos = function (q) {
            var neededList = ['zIndex', 'left', 'top', 'width', 'height'];

            var hasNeeded = _.all(neededList, function (prop) {
                return _.has(q, prop);
            });
            if (hasNeeded) {
                if(_.isString(q.zIndex)){
                    q = _.map(q, function (str) {
                        return str.split(qArrSeperator);
                    });
                }

                var infoLength = _.max(_.map(_.pick(q, neededList), _.size));

                var wins = $('.window');
                wins = wins.slice(0, infoLength);

                var keys = _.keys(q);
                var cols = _.values(q);
                var rows = _.zip(cols); //transpone
                var objs = _.map(rows, function (row) {
                    return _.object(keys, row);
                });
                wins.each(function (i) {
                    $(this).css(objs[i]);
                    $(this).addClass('animateMovement');
                });
                setTimeout(function () {
                    wins.each(function (i) {
                        $(this).removeClass('animateMovement');
                    });
                }, 200);
            }
        };

        $scope.startedWidgetsPositions = false;
        $timeout(function () {
            // loadedState part taken out of original function from GenExpress controller.js
            (localStorage.genexpressWindowsInfo) ?
            $scope.loadPos(JSON.parse(localStorage.genexpressWindowsInfo)) : $scope.loadPos($scope.positions2222);
            $scope.startedWidgetsPositions = true;
        }, 0);

        $scope.resetPos = function () {
            delete localStorage.genexpressWindowsInfo;
            windowGridSize();
            $scope.loadPos($scope.positions2222);
        };

        $scope.getWindowsInfo = function () {
            var objs = $(".window").map(function () {
                var e = $(this);
                return {
                    zIndex: parseInt(e.css("z-index")),
                    left:   parseInt(e.css("left")),
                    top:    parseInt(e.css("top")),
                    width:  e.width(),
                    height: e.height()
                };
            });

            var rows = _.map(objs, _.values);
            var cols = _.zip(rows); //transpone
            var keys = _.keys(objs[0]);

            return _.object(keys, cols);
        };

        $scope.$watch(cachedThrottle($scope, function () {
            return $scope.getWindowsInfo();
        }, 600), function (windowsInfo) {
            if ($scope.startedWidgetsPositions) {
                $scope.relativeWindowsInfo = angular.copy(windowsInfo);
                var relativeToWidth = $('.windowWidthRef').width();
                angular.forEach($scope.relativeWindowsInfo.width, function (width, ix) {
                    $scope.relativeWindowsInfo.width[ix] /= relativeToWidth;
                    $scope.relativeWindowsInfo.height[ix] /= relativeToWidth;
                    $scope.relativeWindowsInfo.top[ix] /= relativeToWidth;
                    $scope.relativeWindowsInfo.left[ix] /= relativeToWidth;
                });
                // why localStorage? remove all instances, if possible
                localStorage.genexpressWindowsInfo = JSON.stringify(windowsInfo);
            }
        }, true);
	}])
;
<|endoftext|>


<commit_before>const mui = [
  {
    id: 'portrait',
    type: 'datepicker',
    props: {
      id: 'portrait',
      hintText: 'Portrait Dialog',
      value: '01/26/2017'
    }
  },
  {
    id: 'landscape',
    type: 'datepicker',
    props: {
      id: 'landscape',
      hintText: 'Landscape Dialog',
      mode: 'landscape'
    }
  },
  {
    id: 'disabled',
    type: 'datepicker',
    props: {
      id: 'disabled',
      hintText: 'Dialog Disabled',
      disabled: true
    }
  },
  {
    id: 'formatted',
    type: 'datepicker',
    props: {
      id: 'formatted',
      hintText: 'Moment Formatted Date',
      value: '01/26/2017'
    },
    format: 'll'
  },
  {
    id: 'daterange',
    type: 'datepicker',
    props: {
      id: 'formatted',
      hintText: 'Moment Formatted Date',
      minDate: '01/01/2017',
      maxDate: '' // empty string refers to now
    }
  }
];

export default mui;
<commit_msg>update json schema<commit_after>const mui = [
  {
    id: 'portrait',
    type: 'datepicker',
    props: {
      id: 'portrait',
      hintText: 'Portrait Dialog',
      value: '01/26/2017'
    }
  },
  {
    id: 'landscape',
    type: 'datepicker',
    props: {
      id: 'landscape',
      hintText: 'Landscape Dialog',
      mode: 'landscape'
    }
  },
  {
    id: 'disabled',
    type: 'datepicker',
    props: {
      id: 'disabled',
      hintText: 'Dialog Disabled',
      disabled: true
    }
  },
  {
    id: 'formatted',
    type: 'datepicker',
    props: {
      id: 'formatted',
      hintText: 'Moment Formatted Date',
      value: '01/26/2017'
    },
    format: 'll'
  },
  {
    id: 'daterange',
    type: 'datepicker',
    props: {
      id: 'formatted',
      hintText: 'Date Range',
      minDate: '01/01/2017',
      maxDate: '' // empty string refers to now
    }
  }
];

export default mui;
<|endoftext|>


<commit_before>(function() {
	function _droid_swipe(el) {
		var _child = el.getElementsByClassName("_ezswipe_surface")[0];
		el.ezSwipe = {
			center : {
				x : (_child.clientWidth / 2) - (el.clientWidth / 2),
				y : (_child.clientHeight / 2) - (el.clientHeight / 2)
			},
			timer : null,
			scrolling : false,
			result : {
				starttime : 0,
				stoptime : 0,
				delta : {
					x : 0,
					y : 0,
					t : 0
				}
			}
		};
		el.scrollLeft = el.ezSwipe.center.x;
		el.scrollTop = el.ezSwipe.center.y;
		el.onscroll = function(e) {
			var _self = this;

			if ((this.scrollLeft != this.ezSwipe.center.x) || (this.scrollTop != this.ezSwipe.center.y)) {
				function dispatchEvent(name) {
					var settings = {
						"detail" : {
							delta : {
								x : _self.ezSwipe.center.x - _self.scrollLeft,
								y : _self.ezSwipe.center.y - _self.scrollTop,
								t : (new Date().getTime()) - _self.ezSwipe.starttime
							},
							bubbles : false,
							cancelable : true
						}
					};
					var event = new CustomEvent(name, settings);
					_self.parentNode.dispatchEvent(event);
					delete event;
				};
				if (!this.ezSwipe.scrolling) {
					this.ezSwipe.result.starttime = new Date().getTime();
					dispatchEvent('swipeStart');
					this.ezSwipe.scrolling = true;
				} else {
					dispatchEvent('swipeMove');
				}
				if (this.ezSwipe.timer) {
					clearTimeout(this.ezSwipe.timer);
				}

				this.ezSwipe.timer = setTimeout(function() {
					_self.ezSwipe.timer = null;
					with (_self.ezSwipe.result) {
						stoptime = new Date().getTime();
						delta.t = stoptime - starttime;
						delta.x = _self.ezSwipe.center.x - _self.scrollLeft;
						delta.y = _self.ezSwipe.center.y - _self.scrollTop;
					};
					dispatchEvent('swipeEnd');
					if (Math.abs(_self.ezSwipe.result.delta.y) > Math.abs(_self.ezSwipe.result.delta.x)) {
						//vertical
						if (_self.ezSwipe.result.delta.y < 0) {
							dispatchEvent('swipeUp');
						} else {
							dispatchEvent('swipeDown');
						}
					} else {
						//horizontal
						if (_self.ezSwipe.result.delta.x < 0) {
							dispatchEvent('swipeLeft');
						} else {
							dispatchEvent('swipeRight');
						}
					}
					_self.ezSwipe.scrolling = false;
					_droid_swipe(_self);
				}, 100);
			}

		};
	}

	var _ezSwipes = document.getElementsByClassName("_ezswipe");
	//Prepend the HTML
	for (var i = 0; i < _ezSwipes.length; i++) {
		var ezswipe_container = document.createElement("div");
		ezswipe_container.classList.add("_ezswipe_container");
		with (ezswipe_container.style) {
			webkitUserSelect = 'none';
			webkitOverflowScrolling = 'touch';
			overflow = 'scroll';
			opacity = 0;
			position = 'relative';
			top = 0;
			left = 0;
			width = '100%';
			height = '100%';
		};
		var ezswipe_surface = document.createElement("div");
		ezswipe_surface.classList.add("_ezswipe_surface");
		with (ezswipe_surface.style) {
			position = 'relative';
			width = '300%';
			height = '300%';
		};
		ezswipe_container.appendChild(ezswipe_surface);
		var item = _ezSwipes[i].insertBefore(ezswipe_container, _ezSwipes[i].firstElementChild);
		_droid_swipe(item);
	}
})();
<commit_msg>refactoring<commit_after>(function() {
	function _droid_swipe(el) {
		var _child = el.getElementsByClassName("_ezswipe_surface")[0];
		el.ezSwipe = {
			center : {
				x : (_child.clientWidth / 2) - (el.clientWidth / 2),
				y : (_child.clientHeight / 2) - (el.clientHeight / 2)
			},
			timer : null,
			scrolling : false,
			result : {
				starttime : 0,
				stoptime : 0,
				delta : {
					x : 0,
					y : 0,
					t : 0
				}
			}
		};
		el.scrollLeft = el.ezSwipe.center.x;
		el.scrollTop = el.ezSwipe.center.y;
		el.onscroll = function(e) {
			var _self = this;
			if ((this.scrollLeft != this.ezSwipe.center.x) || (this.scrollTop != this.ezSwipe.center.y)) {
				function dispatchEvent(name) {
					var settings = {
						"detail" : {
							delta : {
								x : _self.ezSwipe.center.x - _self.scrollLeft,
								y : _self.ezSwipe.center.y - _self.scrollTop,
								t : (new Date().getTime()) - _self.ezSwipe.starttime
							},
							bubbles : false,
							cancelable : true
						}
					};
					var event = new CustomEvent(name, settings);
					_self.parentNode.dispatchEvent(event);
					delete event;
				};
				if (!this.ezSwipe.scrolling) {
					this.ezSwipe.result.starttime = new Date().getTime();
					dispatchEvent('swipeStart');
					this.ezSwipe.scrolling = true;
				} else {
					dispatchEvent('swipeMove');
				}
				if (this.ezSwipe.timer) {
					clearTimeout(this.ezSwipe.timer);
				}

				this.ezSwipe.timer = setTimeout(function() {
					_self.ezSwipe.timer = null;
					with (_self.ezSwipe.result) {
						stoptime = new Date().getTime();
						delta.t = stoptime - starttime;
						delta.x = _self.ezSwipe.center.x - _self.scrollLeft;
						delta.y = _self.ezSwipe.center.y - _self.scrollTop;
					};
					dispatchEvent('swipeEnd');
					if (Math.abs(_self.ezSwipe.result.delta.y) > Math.abs(_self.ezSwipe.result.delta.x)) {
						//vertical
						_self.ezSwipe.result.delta.y < 0 ? dispatchEvent('swipeUp') : dispatchEvent('swipeDown');
					} else {
						//horizontal
						_self.ezSwipe.result.delta.x < 0 ? dispatchEvent('swipeLeft') : dispatchEvent('swipeRight');
					}
					_self.ezSwipe.scrolling = false;
					_droid_swipe(_self);
				}, 100);
			}

		};
	}

	var _ezSwipes = document.getElementsByClassName("_ezswipe");
	//Prepend the HTML
	for (var i = 0; i < _ezSwipes.length; i++) {
		var ezswipe_container = document.createElement("div");
		ezswipe_container.classList.add("_ezswipe_container");
		with (ezswipe_container.style) {
			webkitUserSelect = 'none';
			webkitOverflowScrolling = 'touch';
			overflow = 'scroll';
			opacity = 0;
			position = 'relative';
			top = 0;
			left = 0;
			width = '100%';
			height = '100%';
		};
		var ezswipe_surface = document.createElement("div");
		ezswipe_surface.classList.add("_ezswipe_surface");
		with (ezswipe_surface.style) {
			position = 'relative';
			width = '300%';
			height = '300%';
		};
		ezswipe_container.appendChild(ezswipe_surface);
		_droid_swipe(_ezSwipes[i].insertBefore(ezswipe_container, _ezSwipes[i].firstElementChild));
	}
})();
<|endoftext|>


<commit_before>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.handlers");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.stringbuilder");
goog.require("goog.math.Long");

goog.scope(function() {

var writer   = com.cognitect.transit.impl.writer,
    caching  = com.cognitect.transit.caching,
    handlers = com.cognitect.transit.handlers,
    types    = com.cognitect.transit.types,
    d        = com.cognitect.transit.delimiters,
    sb       = com.cognitect.transit.stringbuilder,
    Long     = goog.math.Long;

writer.escape = function(string) {
    if(string.length > 0) {
        var c = string[0];
        if(c === d.RES && string[1] === d.ESC) {
            return string.substring(1);
        } else if(c === d.ESC || c === d.SUB || c === d.RES) {
            return d.ESC+string;
        } else {
            return string;
        }
    } else {
        return string;
    }
};

/**
 * @constructor
 */
writer.JSONMarshaller = function(opts) {
    this.opts = opts || {};
    this.buffer = this.opts.buffer || (new sb.StringBuilder());
    this.prefersStrings = this.opts["prefersStrings"] != null ? this.opts["prefersStrings"] : true;

    this.objectBuilder = this.opts["objectBuilder"] || null;

    this.handlers = new handlers.Handlers();
    if(this.opts["handlers"]) {
        for(var i = 0; i < this.opts["handlers"].length; i+=2) {
            this.handlers.set(this.opts["handlers"][i], this.opts["handlers"][i+1]);
        }
    }

    this.verbose = (this.opts && this.opts["verbose"]) || false;
};

writer.JSONMarshaller.prototype.handler = function(obj) {
        return this.handlers.get(handlers.constructor(obj));
};

writer.JSONMarshaller.prototype.registerHandler = function(ctor, handler) {
    this.handlers.set(ctor, handler);
};

writer.JSONMarshaller.prototype.emitNil = function(asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "_", "", asMapKey, cache);
    } else {
        return null;
    }
};

writer.JSONMarshaller.prototype.emitString = function(prefix, tag, s, asMapKey, cache) {
    var string = prefix+tag+s;
    if(cache) {
        return cache.write(string, asMapKey);
    } else {
        return string;
    }
};

writer.JSONMarshaller.prototype.emitBoolean = function(b, asMapKey, cache) {
    if(asMapKey) {
        var s = b.toString();
        return this.emitString(d.ESC, "?", s[0], asMapKey, cache);
    } else {
        return b;
    }
};

writer.JSONMarshaller.prototype.emitInteger = function(i, asMapKey, cache) {
    if(asMapKey || (typeof i === "string") || (i instanceof Long)) {
        return this.emitString(d.ESC, "i", i.toString(), asMapKey, cache);
    } else {
        return i;
    }
};

writer.JSONMarshaller.prototype.emitDouble = function(d, asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "d", d, asMapKey, cache);
    } else {
        return d;
    }
};

writer.JSONMarshaller.prototype.emitBinary = function(b, asMapKey, cache) {
    return this.emitString(d.ESC, "b", b, asMapKey, cache);
};

writer.JSONMarshaller.prototype.emitQuoted = function(obj, cache) {
    var ret = {},
        k   = this.emitString(d.ESC_TAG, "'", "", true, cache);
    ret[k] = writer.marshal(this, obj, false, cache);
    return ret;
};

writer.emitInts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitShorts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitShort(em, src[i], false, cache));
    }
    return ret;
};

writer.emitLongs = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitFloats = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitFloat(em, src[i], false, cache));
    }
    return ret;
};

writer.emitDouble = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitDouble(em, src[i], false, cache));
    }
    return ret;
};

writer.emitChars = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(writer.marshal(em, src[i], false, cache));
    }
    return ret;
};

writer.emitBooleans = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitBoolean(em, src[i], false, cache));
    }
    return ret;
};

writer.emitObjects = function(em, iterable, cache) {
    var ret = [];
    if(Array.isArray(iterable)) {
        for(var i = 0; i < iterable.length; i++) {
            ret.push(writer.marshal(em, iterable[i], false, cache));
        }
    } else {
        iterable.forEach(function(v, i) {
            ret.push(writer.marshal(em, v, false, cache));
        });
    }
    return ret;
};

writer.emitArray = function(em, iterable, skip, cache) {
    if(iterable instanceof Int8Array) {
        return writer.emitChars(em, iterable, cache);
    } else if(iterable instanceof Int16Array) {
        return writer.emitShorts(em, iterable, cache);
    } else if(iterable instanceof Int32Array) {
        return writer.emitInts(em, iterable, cache);
    } else if(iterable instanceof Float32Array) {
        return writer.emitFloats(em, iterable, cache);
    } else if(iterable instanceof Float64Array) {
        return writer.emitDoubles(em, iterable, cache);
    } else {
        return writer.emitObjects(em, iterable, cache);
    }
};

writer.isStringableKey = function(em, k) {
    if(typeof k !== "string") {
        var h = em.handler(k);
        return h && h.tag(k).length === 1;
    } else {
        return true;
    }
};

writer.stringableKeys = function(em, obj) {
    var stringableKeys = true,
        ks             = obj.keys();
    for(var i = 0; i < ks.length; i++) {
        stringableKeys = writer.isStringableKey(em, ks[i]);
        if(!stringableKeys) {
            break;
        }
    }
    return stringableKeys;
};

writer.emitMap = function(em, obj, skip, cache) {
    if((obj.constructor === Object) || (obj.forEach != null)) {
        if(em.verbose) {
            var ret = {};
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret[writer.marshal(em, k, true, false)] = writer.marshal(em, v, false, cache);
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret[writer.marshal(em, ks[i], true, false)] = writer.marshal(em, obj[ks[i]], false, cache);
                }
            }
            return ret;
        } else {
            var ret = ["^ "];
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret.push(writer.marshal(em, k, true, cache));
                    ret.push(writer.marshal(em, v, false, cache));
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret.push(writer.marshal(em, ks[i], true, cache));
                    ret.push(writer.marshal(em, obj[ks[i]], false, cache));
                }
            }
            return ret;
        }
    } else if(em.objectBuilder != null) {
        return em.objectBuilder(obj, function(k) { return writer.marshal(em, k, true, cache);  },
                                     function(v) { return writer.marshal(em, v, false, cache); });
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.emitTaggedMap = function(em, tag, rep, skip, cache) {
    var ret = {};
    ret[em.emitString(d.ESC_TAG, tag, "", true, cache)] = writer.marshal(em, rep, false, cache);
    return ret;
};

writer.emitEncoded = function(em, h, tag, rep, obj, asMapKey, cache) {
    if(tag.length === 1) {
        if(typeof rep === "string") {
            return em.emitString(d.ESC, tag, rep, asMapKey, cache);
        } else if(asMapKey || em.prefersStrings) {
            var vh = em.verbose && h.getVerboseHandler();
            if(vh) {
                tag = vh.tag(obj);
                rep = vh.stringRep(obj, vh);
            } else {
                rep = h.stringRep(obj, h);
            }
            if(rep !== null) {
                return em.emitString(d.ESC, tag, rep, asMapKey, cache);
            } else {
                var err = new Error("Cannot be encoded as string");
                err.data = {tag: tag, rep: rep, obj: obj};
                throw err;
            }
        } else {
            return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
        }
    } else if (asMapKey) {
        var err = new Error("Cannot be used as map key");
        err.data = {tag: tag, rep: rep, obj: obj};
        throw err;
    } else {
        return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
    }
}

writer.marshal = function(em, obj, asMapKey, cache) {
    var h   = em.handler(obj),
        tag = h ? h.tag(obj) : null,
        rep = h ? h.rep(obj) : null;

    if(h != null && tag != null) {
        switch(tag) {
        case "_":
            return em.emitNil(asMapKey, cache);
            break;
        case "s":
            return em.emitString("", "", writer.escape(rep), asMapKey, cache);
            break;
        case "?":
            return em.emitBoolean(rep, asMapKey, cache);
            break;
        case "i":
            return em.emitInteger(rep, asMapKey, cache);
            break;
        case "d":
            return em.emitDouble(rep, asMapKey, cache);
            break;
        case "b":
            return em.emitBinary(rep, asMapKey, cache);
            break;
        case "'":
            return em.emitQuoted(rep, cache);
            break;
        case "array":
            return writer.emitArray(em, rep, asMapKey, cache);
            break;
        case "map":
            return writer.emitMap(em, rep, asMapKey, cache);
            break;
        default:
            return writer.emitEncoded(em, h, tag, rep, obj, asMapKey, cache);
            break;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.maybeQuoted = function(em, obj) {
    var h = em.handler(obj);

    if(h != null) {
        if(h.tag(obj).length === 1) {
            return types.quoted(obj);
        } else {
            return obj;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.marshalTop = function(em, obj, asMapKey, cache) {
    return JSON.stringify(writer.marshal(em, writer.maybeQuoted(em, obj), asMapKey, cache));
};

/**
 * @constructor
 */
writer.Writer = function(marshaller, options) {
    this._marshaller = marshaller;
    this.options = options || {};
    if(this.options["cache"] === false) {
        this.cache = null;
    } else {
        this.cache = this.options["cache"] ? this.options["cache"] : new caching.WriteCache();
    }
};

writer.Writer.prototype.marshaller = function() {
    return this._marshaller;
};
writer.Writer.prototype["marshaller"] = writer.Writer.prototype.marshaller;

writer.Writer.prototype.write = function(obj, opts) {
    var ret      = null,
        ropts    = opts || {};
        asMapKey = ropts["asMapKey"] || false;

    if(ropts["marshalTop"] === false) {
        ret = writer.marshal(this._marshaller, obj, asMapKey, this.cache)
    } else {
        ret = writer.marshalTop(this._marshaller, obj, asMapKey, this.cache)
    }
    if(this.cache != null) {
        this.cache.clear();
    }
    return ret;
};
writer.Writer.prototype["write"] = writer.Writer.prototype.write;

writer.Writer.prototype.register = function(type, handler) {
    this._marshaller.registerHandler(type, handler);
};
writer.Writer.prototype["register"] = writer.Writer.prototype.register;

});
<commit_msg>no caching in verbose<commit_after>// Copyright (c) Cognitect, Inc.
// All rights reserved.

"use strict";

goog.provide("com.cognitect.transit.impl.writer");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.handlers");
goog.require("com.cognitect.transit.types");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.stringbuilder");
goog.require("goog.math.Long");

goog.scope(function() {

var writer   = com.cognitect.transit.impl.writer,
    caching  = com.cognitect.transit.caching,
    handlers = com.cognitect.transit.handlers,
    types    = com.cognitect.transit.types,
    d        = com.cognitect.transit.delimiters,
    sb       = com.cognitect.transit.stringbuilder,
    Long     = goog.math.Long;

writer.escape = function(string) {
    if(string.length > 0) {
        var c = string[0];
        if(c === d.RES && string[1] === d.ESC) {
            return string.substring(1);
        } else if(c === d.ESC || c === d.SUB || c === d.RES) {
            return d.ESC+string;
        } else {
            return string;
        }
    } else {
        return string;
    }
};

/**
 * @constructor
 */
writer.JSONMarshaller = function(opts) {
    this.opts = opts || {};
    this.buffer = this.opts.buffer || (new sb.StringBuilder());
    this.prefersStrings = this.opts["prefersStrings"] != null ? this.opts["prefersStrings"] : true;

    this.objectBuilder = this.opts["objectBuilder"] || null;

    this.handlers = new handlers.Handlers();
    if(this.opts["handlers"]) {
        for(var i = 0; i < this.opts["handlers"].length; i+=2) {
            this.handlers.set(this.opts["handlers"][i], this.opts["handlers"][i+1]);
        }
    }

    this.verbose = (this.opts && this.opts["verbose"]) || false;
};

writer.JSONMarshaller.prototype.handler = function(obj) {
        return this.handlers.get(handlers.constructor(obj));
};

writer.JSONMarshaller.prototype.registerHandler = function(ctor, handler) {
    this.handlers.set(ctor, handler);
};

writer.JSONMarshaller.prototype.emitNil = function(asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "_", "", asMapKey, cache);
    } else {
        return null;
    }
};

writer.JSONMarshaller.prototype.emitString = function(prefix, tag, s, asMapKey, cache) {
    var string = prefix+tag+s;
    if(cache) {
        return cache.write(string, asMapKey);
    } else {
        return string;
    }
};

writer.JSONMarshaller.prototype.emitBoolean = function(b, asMapKey, cache) {
    if(asMapKey) {
        var s = b.toString();
        return this.emitString(d.ESC, "?", s[0], asMapKey, cache);
    } else {
        return b;
    }
};

writer.JSONMarshaller.prototype.emitInteger = function(i, asMapKey, cache) {
    if(asMapKey || (typeof i === "string") || (i instanceof Long)) {
        return this.emitString(d.ESC, "i", i.toString(), asMapKey, cache);
    } else {
        return i;
    }
};

writer.JSONMarshaller.prototype.emitDouble = function(d, asMapKey, cache) {
    if(asMapKey) {
        return this.emitString(d.ESC, "d", d, asMapKey, cache);
    } else {
        return d;
    }
};

writer.JSONMarshaller.prototype.emitBinary = function(b, asMapKey, cache) {
    return this.emitString(d.ESC, "b", b, asMapKey, cache);
};

writer.JSONMarshaller.prototype.emitQuoted = function(obj, cache) {
    var ret = {},
        k   = this.emitString(d.ESC_TAG, "'", "", true, cache);
    ret[k] = writer.marshal(this, obj, false, cache);
    return ret;
};

writer.emitInts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitShorts = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitShort(em, src[i], false, cache));
    }
    return ret;
};

writer.emitLongs = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitInt(em, src[i], false, cache));
    }
    return ret;
};

writer.emitFloats = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitFloat(em, src[i], false, cache));
    }
    return ret;
};

writer.emitDouble = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitDouble(em, src[i], false, cache));
    }
    return ret;
};

writer.emitChars = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(writer.marshal(em, src[i], false, cache));
    }
    return ret;
};

writer.emitBooleans = function(em, src, cache) {
    var ret = [];
    for(var i = 0; i < src.length; i++) {
        ret.push(em.emitBoolean(em, src[i], false, cache));
    }
    return ret;
};

writer.emitObjects = function(em, iterable, cache) {
    var ret = [];
    if(Array.isArray(iterable)) {
        for(var i = 0; i < iterable.length; i++) {
            ret.push(writer.marshal(em, iterable[i], false, cache));
        }
    } else {
        iterable.forEach(function(v, i) {
            ret.push(writer.marshal(em, v, false, cache));
        });
    }
    return ret;
};

writer.emitArray = function(em, iterable, skip, cache) {
    if(iterable instanceof Int8Array) {
        return writer.emitChars(em, iterable, cache);
    } else if(iterable instanceof Int16Array) {
        return writer.emitShorts(em, iterable, cache);
    } else if(iterable instanceof Int32Array) {
        return writer.emitInts(em, iterable, cache);
    } else if(iterable instanceof Float32Array) {
        return writer.emitFloats(em, iterable, cache);
    } else if(iterable instanceof Float64Array) {
        return writer.emitDoubles(em, iterable, cache);
    } else {
        return writer.emitObjects(em, iterable, cache);
    }
};

writer.isStringableKey = function(em, k) {
    if(typeof k !== "string") {
        var h = em.handler(k);
        return h && h.tag(k).length === 1;
    } else {
        return true;
    }
};

writer.stringableKeys = function(em, obj) {
    var stringableKeys = true,
        ks             = obj.keys();
    for(var i = 0; i < ks.length; i++) {
        stringableKeys = writer.isStringableKey(em, ks[i]);
        if(!stringableKeys) {
            break;
        }
    }
    return stringableKeys;
};

writer.emitMap = function(em, obj, skip, cache) {
    if((obj.constructor === Object) || (obj.forEach != null)) {
        if(em.verbose) {
            var ret = {};
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret[writer.marshal(em, k, true, false)] = writer.marshal(em, v, false, cache);
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret[writer.marshal(em, ks[i], true, false)] = writer.marshal(em, obj[ks[i]], false, cache);
                }
            }
            return ret;
        } else {
            var ret = ["^ "];
            if(obj.forEach != null) {
                obj.forEach(function(v, k) {
                    ret.push(writer.marshal(em, k, true, cache));
                    ret.push(writer.marshal(em, v, false, cache));
                });
            } else {
                var ks  = Object.keys(obj);
                for(var i = 0; i < ks.length; i++) {
                    ret.push(writer.marshal(em, ks[i], true, cache));
                    ret.push(writer.marshal(em, obj[ks[i]], false, cache));
                }
            }
            return ret;
        }
    } else if(em.objectBuilder != null) {
        return em.objectBuilder(obj, function(k) { return writer.marshal(em, k, true, cache);  },
                                     function(v) { return writer.marshal(em, v, false, cache); });
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.emitTaggedMap = function(em, tag, rep, skip, cache) {
    var ret = {};
    ret[em.emitString(d.ESC_TAG, tag, "", true, cache)] = writer.marshal(em, rep, false, cache);
    return ret;
};

writer.emitEncoded = function(em, h, tag, rep, obj, asMapKey, cache) {
    if(tag.length === 1) {
        if(typeof rep === "string") {
            return em.emitString(d.ESC, tag, rep, asMapKey, cache);
        } else if(asMapKey || em.prefersStrings) {
            var vh = em.verbose && h.getVerboseHandler();
            if(vh) {
                tag = vh.tag(obj);
                rep = vh.stringRep(obj, vh);
            } else {
                rep = h.stringRep(obj, h);
            }
            if(rep !== null) {
                return em.emitString(d.ESC, tag, rep, asMapKey, cache);
            } else {
                var err = new Error("Cannot be encoded as string");
                err.data = {tag: tag, rep: rep, obj: obj};
                throw err;
            }
        } else {
            return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
        }
    } else if (asMapKey) {
        var err = new Error("Cannot be used as map key");
        err.data = {tag: tag, rep: rep, obj: obj};
        throw err;
    } else {
        return writer.emitTaggedMap(em, tag, rep, asMapKey, cache);
    }
}

writer.marshal = function(em, obj, asMapKey, cache) {
    var h   = em.handler(obj),
        tag = h ? h.tag(obj) : null,
        rep = h ? h.rep(obj) : null;

    if(h != null && tag != null) {
        switch(tag) {
        case "_":
            return em.emitNil(asMapKey, cache);
            break;
        case "s":
            return em.emitString("", "", writer.escape(rep), asMapKey, cache);
            break;
        case "?":
            return em.emitBoolean(rep, asMapKey, cache);
            break;
        case "i":
            return em.emitInteger(rep, asMapKey, cache);
            break;
        case "d":
            return em.emitDouble(rep, asMapKey, cache);
            break;
        case "b":
            return em.emitBinary(rep, asMapKey, cache);
            break;
        case "'":
            return em.emitQuoted(rep, cache);
            break;
        case "array":
            return writer.emitArray(em, rep, asMapKey, cache);
            break;
        case "map":
            return writer.emitMap(em, rep, asMapKey, cache);
            break;
        default:
            return writer.emitEncoded(em, h, tag, rep, obj, asMapKey, cache);
            break;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.maybeQuoted = function(em, obj) {
    var h = em.handler(obj);

    if(h != null) {
        if(h.tag(obj).length === 1) {
            return types.quoted(obj);
        } else {
            return obj;
        }
    } else {
        var err = new Error("Not supported");
        err.data = {obj: obj, type: handlers.constructor(obj).name};
        throw err;
    }
};

writer.marshalTop = function(em, obj, asMapKey, cache) {
    return JSON.stringify(writer.marshal(em, writer.maybeQuoted(em, obj), asMapKey, cache));
};

/**
 * @constructor
 */
writer.Writer = function(marshaller, options) {
    this._marshaller = marshaller;
    this.options = options || {};
    if(this.options["cache"] === false) {
        this.cache = null;
    } else {
        this.cache = this.options["cache"] ? this.options["cache"] : new caching.WriteCache();
    }
};

writer.Writer.prototype.marshaller = function() {
    return this._marshaller;
};
writer.Writer.prototype["marshaller"] = writer.Writer.prototype.marshaller;

writer.Writer.prototype.write = function(obj, opts) {
    var ret      = null,
        ropts    = opts || {};
        asMapKey = ropts["asMapKey"] || false,
        cache    = this._marshaller.verbose ? false : this.cache;

    if(ropts["marshalTop"] === false) {
        ret = writer.marshal(this._marshaller, obj, asMapKey, cache)
    } else {
        ret = writer.marshalTop(this._marshaller, obj, asMapKey, cache)
    }
    if(this.cache != null) {
        this.cache.clear();
    }
    return ret;
};
writer.Writer.prototype["write"] = writer.Writer.prototype.write;

writer.Writer.prototype.register = function(type, handler) {
    this._marshaller.registerHandler(type, handler);
};
writer.Writer.prototype["register"] = writer.Writer.prototype.register;

});
<|endoftext|>


<commit_before>var request = require('request-promise');
var API_BASE_URL = "https://api.tnyu.org/v1.0/";

module.exports = {
  showEvents: function(req, res, next, urlFor) {
    request({
      url: API_BASE_URL + "events/up-next",
      json: true,
      rejectUnauthorized: false
    }, function(err, response, body) {
      res.render('showEvents', {events: body.events});
    });
  },

  showConfiguredEvent: function(req, res, next, urlFor) {
    request({
      url: API_BASE_URL + "events/" + req.params.event_id,
      json: true,
      rejectUnauthorized: false
    }, function(err, response, body) {
      res.render('showEvents', {events: body.events, fromConfig: true});
    });
  },

  checkin: function(req, res, next, urlFor) {
    res.render('checkin');
  },

  thanks: function(req, res, next, urlFor) {
    res.render('thanks');
  },

  configure: function(req, res, next, urlFor) {
    request({
      url: "https://api.tnyu.org/v1.0/events/next-10",
      json: true,
      rejectUnauthorized: false
    }, function(err, response, body) {
      var events = body.events instanceof Array ? body.events : [body.events];

      events.forEach(function(event) {
        event.checkInUrl = urlFor("showConfiguredEvent", {absolute: true, params: {event_id: event.id}});
      })

      res.render('configure', {events: events});
    });
  }
}<commit_msg>Use proper endpoint for getting events to checkin<commit_after>var request = require('request-promise');
var API_BASE_URL = "https://api.tnyu.org/v1.0/";

module.exports = {
  showEvents: function(req, res, next, urlFor) {
    request({
      url: API_BASE_URL + "events/check-in-eligible",
      json: true,
      rejectUnauthorized: false
    }, function(err, response, body) {
      res.render('showEvents', {events: body.events});
    });
  },

  showConfiguredEvent: function(req, res, next, urlFor) {
    request({
      url: API_BASE_URL + "events/" + req.params.event_id,
      json: true,
      rejectUnauthorized: false
    }, function(err, response, body) {
      res.render('showEvents', {events: body.events, fromConfig: true});
    });
  },

  checkin: function(req, res, next, urlFor) {
    res.render('checkin');
  },

  thanks: function(req, res, next, urlFor) {
    res.render('thanks');
  },

  configure: function(req, res, next, urlFor) {
    request({
      url: "https://api.tnyu.org/v1.0/events/next-10",
      json: true,
      rejectUnauthorized: false
    }, function(err, response, body) {
      var events = body.events instanceof Array ? body.events : [body.events];

      events.forEach(function(event) {
        event.checkInUrl = urlFor("showConfiguredEvent", {absolute: true, params: {event_id: event.id}});
      })

      res.render('configure', {events: events});
    });
  }
}<|endoftext|>


<commit_before>var secrets = require('../config/secrets');
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport('SMTP', {
//  service: 'Mailgun',
//  auth: {
//    user: secrets.mailgun.login,
//    pass: secrets.mailgun.password
//  }
  service: 'SendGrid',
  auth: {
       user: secrets.sendgrid.user,
       pass: secrets.sendgrid.password
  }
});

/**
 * GET /contact
 * Contact form page.
 */

exports.getContact = function(req, res) {
  res.render('contact', {
    title: 'Contact'
  });
};

/**
 * POST /contact
 * Send a contact form via Nodemailer.
 * @param email
 * @param name
 * @param message
 */

exports.postContact = function(req, res) {
  req.assert('name', 'Name cannot be blank').notEmpty();
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('message', 'Message cannot be blank').notEmpty();

  var errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/contact');
  }

  var from = req.body.email;
  var name = req.body.name;
  var body = req.body.message;
  var to = 'your@email.com';
  var subject = 'Contact Form | Hackathon Starter';

  var mailOptions = {
    to: to,
    from: from,
    subject: subject,
    text: body
  };

  smtpTransport.sendMail(mailOptions, function(err) {
    if (err) {
      req.flash('errors', { msg: err.message });
      return res.redirect('/contact');
    }
    req.flash('success', { msg: 'Email has been sent successfully!' });
    res.redirect('/contact');
  });
};
<commit_msg>Removed commented out mailgun code.<commit_after>var secrets = require('../config/secrets');
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport('SMTP', {
  service: 'SendGrid',
  auth: {
       user: secrets.sendgrid.user,
       pass: secrets.sendgrid.password
  }
});

/**
 * GET /contact
 * Contact form page.
 */

exports.getContact = function(req, res) {
  res.render('contact', {
    title: 'Contact'
  });
};

/**
 * POST /contact
 * Send a contact form via Nodemailer.
 * @param email
 * @param name
 * @param message
 */

exports.postContact = function(req, res) {
  req.assert('name', 'Name cannot be blank').notEmpty();
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('message', 'Message cannot be blank').notEmpty();

  var errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/contact');
  }

  var from = req.body.email;
  var name = req.body.name;
  var body = req.body.message;
  var to = 'your@email.com';
  var subject = 'Contact Form | Hackathon Starter';

  var mailOptions = {
    to: to,
    from: from,
    subject: subject,
    text: body
  };

  smtpTransport.sendMail(mailOptions, function(err) {
    if (err) {
      req.flash('errors', { msg: err.message });
      return res.redirect('/contact');
    }
    req.flash('success', { msg: 'Email has been sent successfully!' });
    res.redirect('/contact');
  });
};
<|endoftext|>


<commit_before>import { h, Component } 				from 'preact/preact';
import { shallowDiff }	 				from 'shallow-compare/index';

import NavLink							from 'com/nav-link/link';
import ButtonLink						from 'com/button-link/link';
import SVGIcon							from 'com/svg-icon/icon';

import $Asset							from '../../shrub/js/asset/asset';

export default class InputTextarea extends Component {
	constructor( props ) {
		super(props);

		this.state = {
			'cursorPos': (props.value || '').length,
			'cachedScrollHeight': this.textarea.scrollHeight,
			'edge': /Edge/.test(navigator.userAgent)
		};

		this.onInput = this.onInput.bind(this);
		this.onFileChange = this.onFileChange.bind(this);
	}

	shouldComponentUpdate( nextProps ) {
		return shallowDiff(this.props, nextProps);
	}

	resizeTextarea() {
		if ( this.textarea  && this.cachedScrollHeight !== this.textarea.scrollHeight) {
			if (this.cachedScrollHeight > this.textarea.scrollHeight) {
				this.textarea.style.height = 0;	/* Shockingly, this is necessary. textarea wont shrink otherwise */
			}
			this.textarea.style.height = this.textarea.scrollHeight + 'px';
		}
	}

	// After initial render
	componentDidMount() {
		this.resizeTextarea();
	}

	// After every update
	componentDidUpdate() {
		if ( this.textarea && this.state.edge ) {
			this.textarea.setSelectionRange(this.state.cursorPos, this.state.cursorPos);
		}

		this.resizeTextarea();
	}

	insertAtCursor( Text ) {
		var ta = this.textarea;

		// http://stackoverflow.com/a/11077016/5678759
		if ( ta.selectionStart || ta.selectionStart == '0') {	// Is Number
			var startPos = ta.selectionStart;
			var endPos = ta.selectionEnd;
			ta.value = ta.value.substring(0, startPos) + Text + ta.value.substring(endPos, ta.value.length);
		}
		else {
			this.props.value += Text;
		}
	}

	// how to preview too
	// https://codepen.io/hartzis/pen/VvNGZP

	onFileChange( e ) {
		if ( !this.props.user )
			return null;
		if ( e.target.files && e.target.files.length ) {
			var file = e.target.files[0];

			return $Asset.Upload(this.props.user.id, file)
				.then( r => {
					if ( r.path ) {
						this.insertAtCursor('!['+r.name+'](///raw/'+r.path+')');
						this.textarea.dispatchEvent( new Event('input') );
					}
					else {
						alert(r.message);
					}
				})
				.catch(err => {
					this.setState({ 'error': err });
				});
		}
	}

	onInput( e ) {
		if ( this.props.onmodify ) {
			this.props.onmodify(e);
		}

		if( this.state.edge ) {
			e.preventDefault();
			this.setState({'cursorPos': e.target.selectionEnd});
		}
	}

	render( props ) {
		var ShowLimit = null;
		if ( props.maxlength )
			ShowLimit =
{props.value.length}/{props.maxlength}
;

		return (

					<textarea {...props}
						oninput={this.onInput}
						ref={(input) => { this.textarea = input; }}
					/>

					{ShowLimit}

							<input type="file" name="asset" style="display: none;" onchange={this.onFileChange} />
							<NavLink class="-upload"><SVGIcon baseline gap>upload</SVGIcon>Upload</NavLink>

						. Supports <NavLink blank href="/markdown"><SVGIcon>markdown</SVGIcon> Markdown</NavLink> and <NavLink href="//emoji.codes/">:emoji_codes:</NavLink>

		);
//						<NavLink class="-upload" onclick={e => {window.location = "#upload";}}><SVGIcon baseline gap>upload</SVGIcon>Upload</NavLink>

//		<NavLink class="-upload" href="#upload"><SVGIcon baseline gap>upload</SVGIcon>Upload</NavLink>
//		 {window.location = "#upload";}}><SVGIcon baseline gap>upload</SVGIcon>Upload
	}
}
<commit_msg>Working scroll control<commit_after>import { h, Component } 				from 'preact/preact';
import { shallowDiff }	 				from 'shallow-compare/index';

import NavLink							from 'com/nav-link/link';
import ButtonLink						from 'com/button-link/link';
import SVGIcon							from 'com/svg-icon/icon';

import $Asset							from '../../shrub/js/asset/asset';

export default class InputTextarea extends Component {
	constructor( props ) {
		super(props);

		this.state = {
			'cursorPos': (props.value || '').length,
			'edge': /Edge/.test(navigator.userAgent)
		};

		this.onInput = this.onInput.bind(this);
		this.onFileChange = this.onFileChange.bind(this);
	}

	shouldComponentUpdate( nextProps ) {
		return shallowDiff(this.props, nextProps);
	}

	resizeTextarea() {

		var doc = document;
		var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

		if ( this.textarea) {
			var before = this.textarea.style.height;
			window.onscroll = function () {};

			this.textarea.style.height = '1px';	/* Shockingly, this is necessary. textarea wont shrink otherwise */
			this.textarea.style.height = this.textarea.scrollHeight + 'px';

			var delta = parseInt(this.textarea.style.height) - parseInt(before) || 0;

			window.scrollTo(0, delta + top);
			window.onscroll = null;

		}
	}

	// After initial render
	componentDidMount() {
		this.resizeTextarea();
	}

	// After every update
	componentDidUpdate() {
		if ( this.textarea && this.state.edge ) {
			this.textarea.setSelectionRange(this.state.cursorPos, this.state.cursorPos);
		}

		this.resizeTextarea();
	}

	insertAtCursor( Text ) {
		var ta = this.textarea;

		// http://stackoverflow.com/a/11077016/5678759
		if ( ta.selectionStart || ta.selectionStart == '0') {	// Is Number
			var startPos = ta.selectionStart;
			var endPos = ta.selectionEnd;
			ta.value = ta.value.substring(0, startPos) + Text + ta.value.substring(endPos, ta.value.length);
		}
		else {
			this.props.value += Text;
		}
	}

	// how to preview too
	// https://codepen.io/hartzis/pen/VvNGZP

	onFileChange( e ) {
		if ( !this.props.user )
			return null;
		if ( e.target.files && e.target.files.length ) {
			var file = e.target.files[0];

			return $Asset.Upload(this.props.user.id, file)
				.then( r => {
					if ( r.path ) {
						this.insertAtCursor('!['+r.name+'](///raw/'+r.path+')');
						this.textarea.dispatchEvent( new Event('input') );
					}
					else {
						alert(r.message);
					}
				})
				.catch(err => {
					this.setState({ 'error': err });
				});
		}
	}

	onInput( e ) {
		if ( this.props.onmodify ) {
			this.props.onmodify(e);
		}

		if( this.state.edge ) {
			e.preventDefault();
			this.setState({'cursorPos': e.target.selectionEnd});
		}
	}

	render( props ) {
		var ShowLimit = null;
		if ( props.maxlength )
			ShowLimit =
{props.value.length}/{props.maxlength}
;

		return (

					<textarea {...props}
						oninput={this.onInput}
						ref={(input) => { this.textarea = input; }}
					/>

					{ShowLimit}

							<input type="file" name="asset" style="display: none;" onchange={this.onFileChange} />
							<NavLink class="-upload"><SVGIcon baseline gap>upload</SVGIcon>Upload</NavLink>

						. Supports <NavLink blank href="/markdown"><SVGIcon>markdown</SVGIcon> Markdown</NavLink> and <NavLink href="//emoji.codes/">:emoji_codes:</NavLink>

		);
//						<NavLink class="-upload" onclick={e => {window.location = "#upload";}}><SVGIcon baseline gap>upload</SVGIcon>Upload</NavLink>

//		<NavLink class="-upload" href="#upload"><SVGIcon baseline gap>upload</SVGIcon>Upload</NavLink>
//		 {window.location = "#upload";}}><SVGIcon baseline gap>upload</SVGIcon>Upload
	}
}
<|endoftext|>