<commit_before>var request = require('request');
var _ = require('underscore');
var Promise = require('bluebird');
var Boom = require('boom');
var spawn = require('child_process').spawn;
var couchUpdateViews = require('couch-update-views');
var path = require('path');

module.exports = function (server, conf) {

	if(!server.methods.clusterprovider){
		throw new Error("Have you installed the 'couch-provider' plugin with namespace 'couchprovider'?");
	}

	couchUpdateViews.migrateUp(server.methods.clusterprovider.getCouchDBServer(), path.join(__dirname, 'views'), true);

	var handler = {};
	/*
	*/
	handler.createJob = function(req, rep){

		var job = req.payload;
		job.timestamp = new Date();
		job.jobstatus = {
			status: 'CREATE'
		};

		server.methods.clusterprovider.uploadDocuments(job)
		.then(function(res){
			if(res.length === 1){
				return res[0];
			}else{
				return res;
			}
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.badRequest(e));
		});

	}

	/*
	*/
	handler.updateJob = function(req, rep){

		var job = req.payload;
		var credentials = req.auth.credentials;

		var prom = [
			server.methods.clusterprovider.validateJobOwnership(job, credentials),
			server.methods.clusterprovider.getDocument(job._id)
			.then(function(doc){
				return server.methods.clusterprovider.validateJobOwnership(doc, credentials);
			})
			.catch(function(e){
				throw Boom.unauthorized("You are not allowed to update the document, it belongs to someone else");
			})
		]

		Promise.all(prom)
		.then(function(){
			return server.methods.clusterprovider.uploadDocuments(job);
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	/*
	*/
	handler.addData = function(req, rep){
		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.isJobDocument(doc);
		})
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			return server.methods.clusterprovider.addDocumentAttachment(doc, req.params.name, req.payload);
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	const getDocumentURIAttachment = function(doc, name){
		if(doc._attachments && doc._attachments[name]){
			return server.methods.clusterprovider.getDocumentURIAttachment(doc._id + "/" + name);
		}else{
			var att = _.find(doc.inputs, function(input){
				return input.name === name;
			});
			if(!att){
				att = _.find(doc.outputs, function(output){
					return output.name === name;
				});
			}
			if(!att){
				throw Boom.notFound("The attachment was not found -> " + name);
			}
			if(att.type === 'tar.gz'){
				name += ".tar.gz";
			}
			if(att.remote){
				return server.methods.clusterprovider.getDocumentURIAttachment(att.remote.uri, att.remote.serverCodename);
			}else{
				return server.methods.clusterprovider.getDocumentURIAttachment(doc._id + "/" + name);
			}

		}
	}

	/*
	*/
	handler.getJob = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			if(req.params.name){

				var uri = getDocumentURIAttachment(doc, req.params.name);

				rep.proxy(uri);

			}else{
				rep(doc);
			}

		})
		.catch(function(e){
			rep(Boom.wrap(e));
		});

	}

	handler.getDownloadToken = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){

			var name = req.params.name;
			var maxAge = "1m";

			rep(server.methods.jwtauth.sign({ _id: doc._id, name: name }, maxAge));

		})
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	handler.downloadAttachment = function(req, rep){
		var token = req.params.token;

		try{

			var decodedToken = server.methods.jwt.verify(token);

			server.methods.clusterprovider.getDocument(decodedToken._id)
			.then(function(doc){
				rep.proxy(getDocumentURIAttachment(doc, decodedToken.name));
			})
			.catch(function(e){
				rep(Boom.unauthorized(e));
			});

		}catch(e){
			rep(Boom.unauthorized(e));
		}

	}

	handler.deleteJob = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.isJobDocument(doc);
		})
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			return server.methods.executionserver.jobdelete(doc)
			.then(function(){
				return server.methods.clusterprovider.deleteDocument(doc);
			});
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	/*
	*/
	handler.getUserJobs = function(req, rep){

		var credentials = req.auth.credentials;
		var email = credentials.email;

		if(req.query.userEmail && email !== req.query.userEmail && credentials.scope.indexOf('admin') === -1){
			throw Boom.unauthorized("You are not allowed to view the jobs of other users.");
		}else if(req.query.userEmail){
			email = req.query.userEmail;
		}

		var jobstatus = req.query.jobstatus;
		var executable = req.query.executable;

		if(jobstatus){
			var key = [email, jobstatus];
			view = '_design/searchJob/_view/useremailjobstatus?include_docs=true&key=' + JSON.stringify(key);
		}else if(executable){
			var key = [email, executable];
			view = '_design/searchJob/_view/useremailexecutable?include_docs=true&key=' + JSON.stringify(key);
		}else{
			view = '_design/searchJob/_view/useremail?include_docs=true&key=' + JSON.stringify(email);
		}

		server.methods.clusterprovider.getView(view)
		.then(function(rows){
			return _.pluck(rows, 'doc');
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		})
	}

	/*
	*/

	handler.getAllJobs = function(req, rep){
		var executable = req.query.executable;

		if(executable){
			var key = executable;
			view = '_design/searchJob/_view/executable?include_docs=true&key=' + JSON.stringify(key);
		}else{
			view = '_design/searchJob/_view/executable?include_docs=true';
		}

		server.methods.clusterprovider.getView(view)
		.then(function(rows){
			return _.pluck(rows, 'doc');
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	return handler;
}
<commit_msg>ENH: Print message if error occurs when deleting the job in the execution server<commit_after>var request = require('request');
var _ = require('underscore');
var Promise = require('bluebird');
var Boom = require('boom');
var spawn = require('child_process').spawn;
var couchUpdateViews = require('couch-update-views');
var path = require('path');

module.exports = function (server, conf) {

	if(!server.methods.clusterprovider){
		throw new Error("Have you installed the 'couch-provider' plugin with namespace 'couchprovider'?");
	}

	couchUpdateViews.migrateUp(server.methods.clusterprovider.getCouchDBServer(), path.join(__dirname, 'views'), true);

	var handler = {};
	/*
	*/
	handler.createJob = function(req, rep){

		var job = req.payload;
		job.timestamp = new Date();
		job.jobstatus = {
			status: 'CREATE'
		};

		server.methods.clusterprovider.uploadDocuments(job)
		.then(function(res){
			if(res.length === 1){
				return res[0];
			}else{
				return res;
			}
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.badRequest(e));
		});

	}

	/*
	*/
	handler.updateJob = function(req, rep){

		var job = req.payload;
		var credentials = req.auth.credentials;

		var prom = [
			server.methods.clusterprovider.validateJobOwnership(job, credentials),
			server.methods.clusterprovider.getDocument(job._id)
			.then(function(doc){
				return server.methods.clusterprovider.validateJobOwnership(doc, credentials);
			})
			.catch(function(e){
				throw Boom.unauthorized("You are not allowed to update the document, it belongs to someone else");
			})
		]

		Promise.all(prom)
		.then(function(){
			return server.methods.clusterprovider.uploadDocuments(job);
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	/*
	*/
	handler.addData = function(req, rep){
		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.isJobDocument(doc);
		})
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			return server.methods.clusterprovider.addDocumentAttachment(doc, req.params.name, req.payload);
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	const getDocumentURIAttachment = function(doc, name){
		if(doc._attachments && doc._attachments[name]){
			return server.methods.clusterprovider.getDocumentURIAttachment(doc._id + "/" + name);
		}else{
			var att = _.find(doc.inputs, function(input){
				return input.name === name;
			});
			if(!att){
				att = _.find(doc.outputs, function(output){
					return output.name === name;
				});
			}
			if(!att){
				throw Boom.notFound("The attachment was not found -> " + name);
			}
			if(att.type === 'tar.gz'){
				name += ".tar.gz";
			}
			if(att.remote){
				return server.methods.clusterprovider.getDocumentURIAttachment(att.remote.uri, att.remote.serverCodename);
			}else{
				return server.methods.clusterprovider.getDocumentURIAttachment(doc._id + "/" + name);
			}

		}
	}

	/*
	*/
	handler.getJob = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			if(req.params.name){

				var uri = getDocumentURIAttachment(doc, req.params.name);

				rep.proxy(uri);

			}else{
				rep(doc);
			}

		})
		.catch(function(e){
			rep(Boom.wrap(e));
		});

	}

	handler.getDownloadToken = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){

			var name = req.params.name;
			var maxAge = "1m";

			rep(server.methods.jwtauth.sign({ _id: doc._id, name: name }, maxAge));

		})
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	handler.downloadAttachment = function(req, rep){
		var token = req.params.token;

		try{

			var decodedToken = server.methods.jwt.verify(token);

			server.methods.clusterprovider.getDocument(decodedToken._id)
			.then(function(doc){
				rep.proxy(getDocumentURIAttachment(doc, decodedToken.name));
			})
			.catch(function(e){
				rep(Boom.unauthorized(e));
			});

		}catch(e){
			rep(Boom.unauthorized(e));
		}

	}

	handler.deleteJob = function(req, rep){

		server.methods.clusterprovider.getDocument(req.params.id)
		.then(function(doc){
			return server.methods.clusterprovider.isJobDocument(doc);
		})
		.then(function(doc){
			return server.methods.clusterprovider.validateJobOwnership(doc, req.auth.credentials);
		})
		.then(function(doc){
			return server.methods.executionserver.jobdelete(doc)
			.then(function(res){
				if(res.indexOf("Deleted:" + doc._id)){
					return server.methods.clusterprovider.deleteDocument(doc);
				}else{
					return {
						error: "Job data in execution server could not be deleted.",
						status: res
					};
				}
			});
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	/*
	*/
	handler.getUserJobs = function(req, rep){

		var credentials = req.auth.credentials;
		var email = credentials.email;

		if(req.query.userEmail && email !== req.query.userEmail && credentials.scope.indexOf('admin') === -1){
			throw Boom.unauthorized("You are not allowed to view the jobs of other users.");
		}else if(req.query.userEmail){
			email = req.query.userEmail;
		}

		var jobstatus = req.query.jobstatus;
		var executable = req.query.executable;

		if(jobstatus){
			var key = [email, jobstatus];
			view = '_design/searchJob/_view/useremailjobstatus?include_docs=true&key=' + JSON.stringify(key);
		}else if(executable){
			var key = [email, executable];
			view = '_design/searchJob/_view/useremailexecutable?include_docs=true&key=' + JSON.stringify(key);
		}else{
			view = '_design/searchJob/_view/useremail?include_docs=true&key=' + JSON.stringify(email);
		}

		server.methods.clusterprovider.getView(view)
		.then(function(rows){
			return _.pluck(rows, 'doc');
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		})
	}

	/*
	*/

	handler.getAllJobs = function(req, rep){
		var executable = req.query.executable;

		if(executable){
			var key = executable;
			view = '_design/searchJob/_view/executable?include_docs=true&key=' + JSON.stringify(key);
		}else{
			view = '_design/searchJob/_view/executable?include_docs=true';
		}

		server.methods.clusterprovider.getView(view)
		.then(function(rows){
			return _.pluck(rows, 'doc');
		})
		.then(rep)
		.catch(function(e){
			rep(Boom.wrap(e));
		});
	}

	return handler;
}
<|endoftext|>


<commit_before><commit_msg>修改列表类组件自适应作用域的逻辑，点击无子项的区域不再报错<commit_after><|endoftext|>


<commit_before>'use babel';

import fs from 'fs-plus';

export default class MeteorTemplateGeneratorView {
  constructor() {
    const div = document.createElement('div');
    div.classList.add('meteor-template-generator');

    const editor = document.createElement('atom-text-editor');
    editor.setAttribute('mini', true);

    div.appendChild(editor);

    this.content = div;

    this.panel = atom.workspace.addModalPanel({ item: this.content, visible: false });

    // Needs major cleanup
    atom.commands.add(div, 'core:confirm', this.confirm.bind(this));
    atom.commands.add(div, 'core:cancel', this.cancel.bind(this));

    this.editor = editor.model;
    this.attach();
    this.initialize();
  }
  //
  // static content() {
  //   return this.div({ class: 'meteor-template-generator' }, () => {
  //     this.tag('atom-text-editor', { mini: true, outlet: 'inputBox' });
  //     return this.div({ class: 'message', outlet: 'message' });
  //   },
  //   );
  // }
  // Returns an object that can be retrieved when package is activated

  initialize() {
    this.commandSubscription = atom.commands.add('atom-workspace', {
      'meteor-template-generator:generate-template': () => this.attach(),
    });

    // @inputBox.on 'blur', => @close()
    return atom.commands.add(this.content, {
      'core:confirm': () => this.confirm(),
      'core:cancel': () => this.close(),
    },
    );
  }

  // Tear down any state and detach
  destroy() {
    this.panel.destroy();
    return this.commandSubscription.dispose();
  }

  attach() {
    const editor = this.panel.item.firstChild.model;
    editor.setText('Enter template name');
    this.panel.show();

    this.panel.item.firstChild.focus();
  }

  close() {
    this.panel.hide();
  }

  cancel() {
    this.close();
  }

  confirm() {
    this.close();
    const editor = this.panel.item.firstChild.model;
    const text = editor.getText();
    if (text) { this.generatePackage(text); }
  }

  getPath() {
    return (atom.packages.getActivePackage('tree-view').mainModule.treeView.selectedPath);
  }

  getFileContentJs(name) {
    return `Template.${name}.onCreated(function on${name}Created() {\n\n});\n
Template.${name}.onRendered(function on${name}Rendered() {\n\n});\n
Template.${name}.events({\n\n});\n
Template.${name}.helpers({\n\n});\n`;
  }

  getFileContentHTML(name) {
    return `<template name=\"${name}\">\n\n</template>`;
  }

  generatePackage(name) {
    const path = this.getPath();
    if (!fs.isDirectorySync(path)) {
      console.error('Not a directory');
      return;
    }

    fs.writeFileSync(`${path}/${name}/${name}.js`, this.getFileContentJs(name));
    fs.writeFileSync(`${path}/${name}/${name}.html`, this.getFileContentHTML(name));
  }
}
<commit_msg>remove unused file<commit_after><|endoftext|>


<commit_before>;(function($, window, document) {
    'use strict';

    /**
     * Get the value of a cookie with the given name
     * @param name
     * @returns {string|undefined}
     */
    $.getCookie = function(name) {
        var value = '; ' + document.cookie,
            parts = value.split('; ' + name + '=');

        if (parts.length == 2) {
            return parts.pop().split(';').shift();
        }
        return undefined;
    };

    /**
     * Remove a cookie with the provided name
     * @param name
     */
    $.removeCookie = function(name) {
        var basePath = window.csrfConfig.basePath || '/';
        document.cookie = name + '=; path=' + basePath + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    };

    var CSRF = {

        /**
         * Key including subshop and -path
         */
        storageKey: '__csrf_token-' + window.csrfConfig.shopId,

        /**
         * Temporary request callback store
         */
        pendingRequests: {},

        /**
         * Returns the token
         * @returns {string}
         */
        getToken: function() {
            return $.getCookie(this.storageKey);
        },

        /**
         * Checks if the token needs to be requested
         * @returns {boolean}
         */
        checkToken: function() {
            return this.getToken() !== undefined;
        },

        /**
         * Creates a hidden input fields which holds the csrf information
         * @returns {HTMLElement}
         */
        createTokenField: function() {
            var me = this;

            return $('<input>', {
                'type': 'hidden',
                'name': '__csrf_token',
                'value': me.getToken()
            });
        },

        /**
         * Adds the token field to the given form
         * @param {HTMLElement} formElement
         */
        addTokenField: function(formElement) {
            formElement.append(CSRF.createTokenField());
            $.publish('plugin/swCsrfProtection/addTokenField', [ this, formElement ]);
        },

        /**
         *
         * @returns {HTMLElement[]}
         */
        getFormElements: function() {
            return $('form[method="post"]');
        },

        /**
         * Search all forms on the page and create or update their csrf input fields
         */
        updateForms: function() {
            var me = this,
                formElements = me.getFormElements();

            $.each(formElements, function(index, formElement) {
                var csrfInput;

                formElement = $(formElement);
                csrfInput = formElement.find('input[name="__csrf_token"]');

                if (csrfInput.length > 0) {
                    csrfInput.val(me.getToken());
                } else {
                    me.addTokenField(formElement);
                }
            });

            $.publish('plugin/swCsrfProtection/updateForms', [ this, formElements ]);
        },

        /**
         * Registers handlers before sending an AJAX request & after it is completed.
         */
        setupAjax: function() {
            var me = this;

            $(document).ajaxSend($.proxy(me._ajaxBeforeSend, me));
            $(document).ajaxSend($.proxy(me._jsonpBeforeSend, me));
            $(document).ajaxComplete($.proxy(me._ajaxAfterSend, me));

            $.publish('plugin/swCsrfProtection/setupAjax', [ me, me.getToken() ]);
        },

        /**
         * Update all forms in case a callback has replaced html parts and needs to be rebound
         *
         * @private
         */
        _ajaxAfterSend: function() {
            window.setTimeout(function() {
                this.updateForms();
            }.bind(this), 1);
        },

        /**
         * Append X-CSRF-Token header to every request which is not a jsonp-request
         *
         * @param event
         * @param request
         * @param settings
         * @private
         */
        _ajaxBeforeSend: function(event, request, settings) {
            if (settings.hasOwnProperty('ignoreCSRFHeader') || settings.ignoreCSRFHeader === true) {
                return;
            }

            if (!settings.dataType || settings.dataType.toLowerCase() === 'jsonp') {
                return;
            }
            request.setRequestHeader('X-CSRF-Token', this.getToken());
        },

        /**
         * Append __csrf_token parameter to the URL if it's missing
         * @param event
         * @param request
         * @param settings
         * @private
         */
        _jsonpBeforeSend: function(event, request, settings) {
            if (!settings.type || settings.type.toLowerCase() !== 'get') {
                return;
            }

            if (settings.url.indexOf('__csrf_token=') !== -1) {
                return;
            }
            settings.url = settings.url + '&__csrf_token=' + this.getToken();
        },

        /**
         * Calls the frontend to retrieve a new csrf token and executes the afterInit on success
         */
        requestToken: function() {
            var me = this;

            $.ajax({
                url: window.csrfConfig.generateUrl,
                success: function(response, status, xhr) {
                    me.saveToken(xhr.getResponseHeader('x-csrf-token'));
                    $.publish('plugin/swCsrfProtection/requestToken', [ me, me.getToken() ]);
                    me.afterInit();
                }
            });
        },

        /**
         * Save token into a cookie
         * @param token
         */
        saveToken: function(token) {
            var me = this,
                basePath = window.csrfConfig.basePath || '/';

            document.cookie = me.storageKey + '=' + token + '; path=' + basePath;
        },

        /**
         * Initialize the CSRF protection
         */
        init: function() {
            var me = this;

            if (me.checkToken()) {
                me.afterInit();
                return;
            }

            me.requestToken();
        },

        /**
         * Runs after a valid token is set
         */
        afterInit: function() {
            var me = this;

            me.updateForms();
            me.setupAjax();

            $.publish('plugin/swCsrfProtection/init', [ me ]);
        }

    };

    $(function() {
        CSRF.init();
    });

    window.CSRF = CSRF;
})(jQuery, window, document);
<commit_msg>SW-17932 fix bug with caused by urls without get parameter<commit_after>;(function($, window, document) {
    'use strict';

    /**
     * Get the value of a cookie with the given name
     * @param name
     * @returns {string|undefined}
     */
    $.getCookie = function(name) {
        var value = '; ' + document.cookie,
            parts = value.split('; ' + name + '=');

        if (parts.length == 2) {
            return parts.pop().split(';').shift();
        }
        return undefined;
    };

    /**
     * Remove a cookie with the provided name
     * @param name
     */
    $.removeCookie = function(name) {
        var basePath = window.csrfConfig.basePath || '/';
        document.cookie = name + '=; path=' + basePath + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    };

    var CSRF = {

        /**
         * Key including subshop and -path
         */
        storageKey: '__csrf_token-' + window.csrfConfig.shopId,

        /**
         * Temporary request callback store
         */
        pendingRequests: {},

        /**
         * Returns the token
         * @returns {string}
         */
        getToken: function() {
            return $.getCookie(this.storageKey);
        },

        /**
         * Checks if the token needs to be requested
         * @returns {boolean}
         */
        checkToken: function() {
            return this.getToken() !== undefined;
        },

        /**
         * Creates a hidden input fields which holds the csrf information
         * @returns {HTMLElement}
         */
        createTokenField: function() {
            var me = this;

            return $('<input>', {
                'type': 'hidden',
                'name': '__csrf_token',
                'value': me.getToken()
            });
        },

        /**
         * Adds the token field to the given form
         * @param {HTMLElement} formElement
         */
        addTokenField: function(formElement) {
            formElement.append(CSRF.createTokenField());
            $.publish('plugin/swCsrfProtection/addTokenField', [ this, formElement ]);
        },

        /**
         *
         * @returns {HTMLElement[]}
         */
        getFormElements: function() {
            return $('form[method="post"]');
        },

        /**
         * Search all forms on the page and create or update their csrf input fields
         */
        updateForms: function() {
            var me = this,
                formElements = me.getFormElements();

            $.each(formElements, function(index, formElement) {
                var csrfInput;

                formElement = $(formElement);
                csrfInput = formElement.find('input[name="__csrf_token"]');

                if (csrfInput.length > 0) {
                    csrfInput.val(me.getToken());
                } else {
                    me.addTokenField(formElement);
                }
            });

            $.publish('plugin/swCsrfProtection/updateForms', [ this, formElements ]);
        },

        /**
         * Registers handlers before sending an AJAX request & after it is completed.
         */
        setupAjax: function() {
            var me = this;

            $(document).ajaxSend($.proxy(me._ajaxBeforeSend, me));
            $(document).ajaxSend($.proxy(me._jsonpBeforeSend, me));
            $(document).ajaxComplete($.proxy(me._ajaxAfterSend, me));

            $.publish('plugin/swCsrfProtection/setupAjax', [ me, me.getToken() ]);
        },

        /**
         * Update all forms in case a callback has replaced html parts and needs to be rebound
         *
         * @private
         */
        _ajaxAfterSend: function() {
            window.setTimeout(function() {
                this.updateForms();
            }.bind(this), 1);
        },

        /**
         * Append X-CSRF-Token header to every request which is not a jsonp-request
         *
         * @param event
         * @param request
         * @param settings
         * @private
         */
        _ajaxBeforeSend: function(event, request, settings) {
            if (settings.hasOwnProperty('ignoreCSRFHeader') || settings.ignoreCSRFHeader === true) {
                return;
            }

            if (!settings.dataType || settings.dataType.toLowerCase() === 'jsonp') {
                return;
            }
            request.setRequestHeader('X-CSRF-Token', this.getToken());
        },

        /**
         * Append __csrf_token parameter to the URL if it's missing
         * @param event
         * @param request
         * @param settings
         * @private
         */
        _jsonpBeforeSend: function(event, request, settings) {
            if (!settings.type || settings.type.toLowerCase() !== 'get') {
                return;
            }

            if (settings.url.indexOf('__csrf_token=') !== -1) {
                return;
            }
            settings.url += ( settings.url.indexOf('?') >= 0 ? '&' : '?' ) + '__csrf_token=' + this.getToken();
        },

        /**
         * Calls the frontend to retrieve a new csrf token and executes the afterInit on success
         */
        requestToken: function() {
            var me = this;

            $.ajax({
                url: window.csrfConfig.generateUrl,
                success: function(response, status, xhr) {
                    me.saveToken(xhr.getResponseHeader('x-csrf-token'));
                    $.publish('plugin/swCsrfProtection/requestToken', [ me, me.getToken() ]);
                    me.afterInit();
                }
            });
        },

        /**
         * Save token into a cookie
         * @param token
         */
        saveToken: function(token) {
            var me = this,
                basePath = window.csrfConfig.basePath || '/';

            document.cookie = me.storageKey + '=' + token + '; path=' + basePath;
        },

        /**
         * Initialize the CSRF protection
         */
        init: function() {
            var me = this;

            if (me.checkToken()) {
                me.afterInit();
                return;
            }

            me.requestToken();
        },

        /**
         * Runs after a valid token is set
         */
        afterInit: function() {
            var me = this;

            me.updateForms();
            me.setupAjax();

            $.publish('plugin/swCsrfProtection/init', [ me ]);
        }

    };

    $(function() {
        CSRF.init();
    });

    window.CSRF = CSRF;
})(jQuery, window, document);
<|endoftext|>


<commit_before><commit_msg>支持在弹窗的元素中使用onback<commit_after><|endoftext|>


<commit_before>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.3.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var slice            = Array.prototype.slice,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeIndexOf      = Array.prototype.indexOf,
        nativeLastIndexOf  = Array.prototype.lastIndexOf;

    var jSQL, _jSQL, _jsql, _DB = {}, _DBIndexMap = {}, _protected = {};
    var jSQL_KEY_NAME = 'jSQL_Key';
    var utils = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    if(typeof(this.jsql) !== 'undefined') {
        _jsql = this.jsql;
    }

    jSQL = function() {
        this.init.apply(this, arguments);
    };

    jSQL.prototype = {
        version: '0.3.0-dev',

        init: function() {
            this._jSQL = _jSQL;
            this._jsql = _jsql;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
            this._DBIndexMap = _DBIndexMap;
            this._protected = _protected;
            this.utils = utils;
        },

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(utils.isArray(db)) {
                indexList = utils.listSlice(arguments, '2:');
                utils.appendKey(db, indexList);
                _DBIndexMap[dbname] = utils.arrayToObject(db);
            }

            if(utils.isPlainObject(db)) {
                _DBIndexMap[dbname] = utils.clone(db);
                db = utils.objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            this._currentDBName = dbname;
            this.rebase();
            return this;
        },

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        dbs: function() {
            return utils.keys(this._DB);
        },

        db: function() {
            return this._currentDBName;
        },

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer
            this._protected['field'] = [].slice.call(utils.isArray(key) ? key : arguments);

            if(key === '*') {
                return this;
            }

            //this.where(function(data) {
            //    return typeof(utils.deep(data, key)) !== 'undefined';
            //});

            return this;
        },

        count: function() {
            var result;
            result = this._buffer.length;
            this.rebase();
            return result;
        },

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            utils.deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = utils.deep(a, field);
                b = utils.deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;
            fn = utils.parseFn(fn);

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, utils.clone(this._buffer[i]), i);
                    }

                    if(utils.isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, utils.clone(this._buffer[i]), i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp.push(utils.clone(this._buffer[i]));
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        findAll: function() {
            var result;
            result = utils.clone(utils.arrayToObject(this._select()));
            this.rebase();
            return result;
        },

        find: function(key) {
            var result;
            var _tmp = this._DBIndexMap[this._currentDBName];

            if(!key) {
                for(var i in _tmp) {
                    if(_tmp.hasOwnProperty(i)) {
                        if(key) {
                            break;
                        }

                        if(this._buffer.hasOwnProperty(i)) {
                            key = i;
                        }
                    }
                }
            }

            result = utils.clone(_tmp[key]);
            this.rebase();
            return result;
        },

        listAll: function() {
            var result;
            result = utils.clone(this._select());
            this.rebase();
            return result;
        },

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        insert: function() {
            //TODO
        },

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = utils.listSlice(_tmp, limit);
            return this;
        },

        keys: function() {
            return utils.keys(this.findAll());
        },

        first: function(fn) {
            if(fn) {
                return this.where(fn).first();
            }

            return utils.listSlice(this._select(), ':1');
        },

        last: function(fn) {
            if(fn) {
                return this.where(fn).last();
            }

            return utils.listSlice(this._select(), '-1:');
        },

        rebase: function() {
            this._protected = {};
            this.select('*');
            return this;
        },

        noConflict: function() {
            if(window.jSQL === jSQL) {
                window.jSQL = this._jSQL;
            }

            if(window.jsql === jsql) {
                window.jsql = this._jsql;
            }

            return this;
        },

        _select: function(field) {
            var tmp, result = [];

            field = field || this._protected['field'];

            if(field === '*') {
                return this._buffer;
            }

            if(typeof(field) === 'string') {
                field = field.split(',');
            }

            utils.each(this._buffer, function(o, i, r) {
                tmp = {};
                utils.each(field, function(_o, _i, _r) {
                    tmp[_o.split('.').pop()] = utils.deep(o, _o);
                    tmp[jSQL_KEY_NAME] = utils.deep(o, jSQL_KEY_NAME);
                });
                result.push(tmp);
            });

            return result;
        }
    };

    utils = {
        deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        isObject: function(obj) {
            return obj === Object(obj);
        },

        isPlainObject: function(obj) {
            return this.isObject(obj) && obj.constructor === Object;
        },

        clone: function (obj) {
            if(obj == null || typeof(obj) != 'object') {
                return obj;
            }

            var temp = new obj.constructor();
            for(var key in obj) {
                temp[key] = arguments.callee(obj[key]);
            }

            return temp;
        },

        objectToArray: function(object) {
            var array = [], object = this.clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i][jSQL_KEY_NAME] = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || jSQL_KEY_NAME]] = this.clone(array[i]);
                delete object[array[i][key || jSQL_KEY_NAME]][key || jSQL_KEY_NAME];
            };

            return object;
        },

        each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that.isArray(indexList)) {
                baseRef = indexList;
            }

            that.each(baseRef, function(o, i, r) {
                key += utils.deep(object, o);
            });

            return key;
        },

        listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        appendKey: function(list, indexList) {
            var that = this;
            that.each(list, function(o, i, r) {
                o[jSQL_KEY_NAME] = that.keygen(o, indexList) || i;
            });
        },

        keys: nativeKeys || (function() {
            var hasDontEnumBug = true,
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            for (var key in {'toString': null}) {
                hasDontEnumBug = false;
            }

            return function keys(object) {
                if ((typeof object != 'object' && typeof object != 'function') || object === null) {
                    throw new TypeError('Object.keys called on a non-object');
                }

                var keys = [];
                for (var name in object) {
                    if (object.hasOwnProperty(name)) {
                        keys.push(name);
                    }
                }

                if (hasDontEnumBug) {
                    for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                        var dontEnum = dontEnums[i];
                        if (object.hasOwnProperty(dontEnum)) {
                            keys.push(dontEnum);
                        }
                    }
                }
                return keys;
            };
        })(),

        parseFn: function(fn) {
            if(typeof(fn) === 'string') {
                fn = new Function('data', 'with(data) { return ' + fn + '; }');
            }

            return fn;
        },

        indexOf: function(list, sought /*, fromIndex */ ) {
            if(nativeIndexOf) {
                return nativeIndexOf.apply(list, this.listSlice(arguments, '1:'));
            }

            var self = list,
                length = self.length >>> 0;

            if (!length) {
                return -1;
            }

            var i = 0;
            if (arguments.length > 2) {
                i = arguments[2];
            }

            // handle negative indices
            i = i >= 0 ? i : Math.max(0, length + i);
            for (; i < length; i++) {
                if (i in self && self[i] === sought) {
                    return i;
                }
            }
            return -1;
        }
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jsql = this.jSQL = jSQL;
})();
<commit_msg>update _select.<commit_after>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.3.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var slice            = Array.prototype.slice,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeIndexOf      = Array.prototype.indexOf,
        nativeLastIndexOf  = Array.prototype.lastIndexOf;

    var jSQL, _jSQL, _jsql, _DB = {}, _DBIndexMap = {}, _protected = {};
    var jSQL_KEY_NAME = 'jSQL_Key';
    var utils = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    if(typeof(this.jsql) !== 'undefined') {
        _jsql = this.jsql;
    }

    jSQL = function() {
        this.init.apply(this, arguments);
    };

    jSQL.prototype = {
        version: '0.3.0-dev',

        init: function() {
            this._jSQL = _jSQL;
            this._jsql = _jsql;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
            this._DBIndexMap = _DBIndexMap;
            this._protected = _protected;
            this.utils = utils;
        },

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(utils.isArray(db)) {
                indexList = utils.listSlice(arguments, '2:');
                utils.appendKey(db, indexList);
                _DBIndexMap[dbname] = utils.arrayToObject(db);
            }

            if(utils.isPlainObject(db)) {
                _DBIndexMap[dbname] = utils.clone(db);
                db = utils.objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            this._currentDBName = dbname;
            this.rebase();
            return this;
        },

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        dbs: function() {
            return utils.keys(this._DB);
        },

        db: function() {
            return this._currentDBName;
        },

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer
            this._protected['field'] = [].slice.call(utils.isArray(key) ? key : arguments);

            if(key === '*') {
                return this;
            }

            //this.where(function(data) {
            //    return typeof(utils.deep(data, key)) !== 'undefined';
            //});

            return this;
        },

        count: function() {
            var result;
            result = this._buffer.length;
            this.rebase();
            return result;
        },

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            utils.deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = utils.deep(a, field);
                b = utils.deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;
            fn = utils.parseFn(fn);

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, utils.clone(this._buffer[i]), i);
                    }

                    if(utils.isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, utils.clone(this._buffer[i]), i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp.push(utils.clone(this._buffer[i]));
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        findAll: function() {
            var result;
            result = utils.clone(utils.arrayToObject(this._select()));
            this.rebase();
            return result;
        },

        find: function(key) {
            var result;
            var _tmp = this._DBIndexMap[this._currentDBName];

            if(!key) {
                for(var i in _tmp) {
                    if(_tmp.hasOwnProperty(i)) {
                        if(key) {
                            break;
                        }

                        if(this._buffer.hasOwnProperty(i)) {
                            key = i;
                        }
                    }
                }
            }

            result = utils.clone(_tmp[key]);
            this.rebase();
            return result;
        },

        listAll: function() {
            var result;
            result = utils.clone(this._select());
            this.rebase();
            return result;
        },

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        insert: function() {
            //TODO
        },

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = utils.listSlice(_tmp, limit);
            return this;
        },

        keys: function() {
            return utils.keys(this.findAll());
        },

        first: function(fn) {
            if(fn) {
                return this.where(fn).first();
            }

            return utils.listSlice(this._select(), ':1');
        },

        last: function(fn) {
            if(fn) {
                return this.where(fn).last();
            }

            return utils.listSlice(this._select(), '-1:');
        },

        rebase: function() {
            this._protected = {};
            this.select('*');
            return this;
        },

        noConflict: function() {
            if(window.jSQL === jSQL) {
                window.jSQL = this._jSQL;
            }

            if(window.jsql === jsql) {
                window.jsql = this._jsql;
            }

            return this;
        },

        _select: function(field) {
            var tmp, result = [];

            field = field || this._protected['field'];

            if(field === '*') {
                return this._buffer;
            }

            if(typeof(field) === 'string') {
                field = field.split(',');
            }

            utils.each(this._buffer, function(o, i, r) {
                tmp = {};
                tmp[jSQL_KEY_NAME] = utils.deep(o, jSQL_KEY_NAME);

                utils.each(field, function(_o, _i, _r) {
                    if(o.hasOwnProperty(_o)) {
                        tmp[_o.split('.').pop()] = utils.deep(o, _o);
                    }
                });
                result.push(tmp);
            });

            return result;
        }
    };

    utils = {
        deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        isObject: function(obj) {
            return obj === Object(obj);
        },

        isPlainObject: function(obj) {
            return this.isObject(obj) && obj.constructor === Object;
        },

        clone: function (obj) {
            if(obj == null || typeof(obj) != 'object') {
                return obj;
            }

            var temp = new obj.constructor();
            for(var key in obj) {
                temp[key] = arguments.callee(obj[key]);
            }

            return temp;
        },

        objectToArray: function(object) {
            var array = [], object = this.clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i][jSQL_KEY_NAME] = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || jSQL_KEY_NAME]] = this.clone(array[i]);
                delete object[array[i][key || jSQL_KEY_NAME]][key || jSQL_KEY_NAME];
            };

            return object;
        },

        each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that.isArray(indexList)) {
                baseRef = indexList;
            }

            that.each(baseRef, function(o, i, r) {
                key += utils.deep(object, o);
            });

            return key;
        },

        listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        appendKey: function(list, indexList) {
            var that = this;
            that.each(list, function(o, i, r) {
                o[jSQL_KEY_NAME] = that.keygen(o, indexList) || i;
            });
        },

        keys: nativeKeys || (function() {
            var hasDontEnumBug = true,
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            for (var key in {'toString': null}) {
                hasDontEnumBug = false;
            }

            return function keys(object) {
                if ((typeof object != 'object' && typeof object != 'function') || object === null) {
                    throw new TypeError('Object.keys called on a non-object');
                }

                var keys = [];
                for (var name in object) {
                    if (object.hasOwnProperty(name)) {
                        keys.push(name);
                    }
                }

                if (hasDontEnumBug) {
                    for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                        var dontEnum = dontEnums[i];
                        if (object.hasOwnProperty(dontEnum)) {
                            keys.push(dontEnum);
                        }
                    }
                }
                return keys;
            };
        })(),

        parseFn: function(fn) {
            if(typeof(fn) === 'string') {
                fn = new Function('data', 'with(data) { return ' + fn + '; }');
            }

            return fn;
        },

        indexOf: function(list, sought /*, fromIndex */ ) {
            if(nativeIndexOf) {
                return nativeIndexOf.apply(list, this.listSlice(arguments, '1:'));
            }

            var self = list,
                length = self.length >>> 0;

            if (!length) {
                return -1;
            }

            var i = 0;
            if (arguments.length > 2) {
                i = arguments[2];
            }

            // handle negative indices
            i = i >= 0 ? i : Math.max(0, length + i);
            for (; i < length; i++) {
                if (i in self && self[i] === sought) {
                    return i;
                }
            }
            return -1;
        }
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jsql = this.jSQL = jSQL;
})();
<|endoftext|>


<commit_before>/*
 Copyright (c) 2013, Kenneth Koch

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

/**
 * The english normalizer will create a string in which all contractions are expanded to their
 * full meaning (i.e. "we'll" becomes "we will").
 *
 * It currently works off a conversion table and falls back to a set of rules.
 * Since it is applied first, the conversion table provides an "override" for the rules.
 **/
var replacer = require('../util/utils').replacer;

var conversionTable = {
	"can't":"can not",
	"won't":"will not",
	"couldn't've":"could not have",
	"i'm":"I am",
	"how'd":"how did"
};

var rules = [
	{ regex: /([azAZ]*)n\'[tT]/g, output: "$1 not" },
	{ regex: /([azAZ]*)\'[sS]/g, output: "$1 is" },
	{ regex: /([azAZ]*)\'[lL][lL]/g, output: "$1 will" },
	{ regex: /([azAZ]*)\'[rR][eE]/g, output: "$1 are" },
	{ regex: /([azAZ]*)\'[vV][eE]/g, output: "$1 have" },
	{ regex: /([azAZ]*)\'[dD]/g, output: "$1 would" }
];

// Accepts a list of tokens to expand.
var normalize_tokens = function(tokens) {
	if(typeof tokens === "string") {
		tokens = [tokens];
	}
        var results = [];
	var rule_count = rules.length;
	var num_tokens = tokens.length;
        var i, token, r, rule;

        for (var i = 0; i < num_tokens; i++) {
            token = tokens[i].toLowerCase();
            // Check the conversion table
            if (conversionTable[token.toLowerCase()]) {
                results = results.concat(conversionTable[token].split(/\W+/));
            }

            // Apply the rules
            else {
                var r, rule, matched = false;
                for ( r = 0; r < rule_count; r++) {
                    rule = rules[r];
                    if (token.match(rule.regex)) {
                        results = results.concat(token.replace(rule.regex, rule.output).split(/\W+/));
                        matched = true;
                        break;
                    }
                }
                if (!matched) {
                    results.push(token);
                }
            }
        }

	return results;
};

// export the relevant stuff.
exports.normalize_tokens = normalize_tokens;

<commit_msg>fix casesensitive bug to pass ci, think about 'cannot' or 'can not'?<commit_after>/*
 Copyright (c) 2013, Kenneth Koch

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

/**
 * The english normalizer will create a string in which all contractions are expanded to their
 * full meaning (i.e. "we'll" becomes "we will").
 *
 * It currently works off a conversion table and falls back to a set of rules.
 * Since it is applied first, the conversion table provides an "override" for the rules.
 **/
var replacer = require('../util/utils').replacer;

var conversionTable = {
	"can't":"cannot",
	"won't":"will not",
	"couldn't've":"could not have",
	"i'm":"I am",
	"how'd":"how did"
};

var rules = [
	{ regex: /([azAZ]*)n\'[tT]/g, output: "$1 not" },
	{ regex: /([azAZ]*)\'[sS]/g, output: "$1 is" },
	{ regex: /([azAZ]*)\'[lL][lL]/g, output: "$1 will" },
	{ regex: /([azAZ]*)\'[rR][eE]/g, output: "$1 are" },
	{ regex: /([azAZ]*)\'[vV][eE]/g, output: "$1 have" },
	{ regex: /([azAZ]*)\'[dD]/g, output: "$1 would" }
];

// Accepts a list of tokens to expand.
var normalize_tokens = function(tokens) {
	if(typeof tokens === "string") {
		tokens = [tokens];
	}
        var results = [];
	var rule_count = rules.length;
	var num_tokens = tokens.length;
        var i, token, r, rule;

        for (var i = 0; i < num_tokens; i++) {
            token = tokens[i];
            // Check the conversion table
            if (conversionTable[token.toLowerCase()]) {
                results = results.concat(conversionTable[token.toLowerCase()].split(/\W+/));
            }

            // Apply the rules
            else {
                var r, rule, matched = false;
                for ( r = 0; r < rule_count; r++) {
                    rule = rules[r];
                    if (token.match(rule.regex)) {
                        results = results.concat(token.replace(rule.regex, rule.output).split(/\W+/));
                        matched = true;
                        break;
                    }
                }
                if (!matched) {
                    results.push(token);
                }
            }
        }

	return results;
};

// export the relevant stuff.
exports.normalize_tokens = normalize_tokens;

<|endoftext|>


<commit_before>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.3.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var slice            = Array.prototype.slice,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys;

    var jSQL, _jSQL, _DB = {}, _DBIndexMap = {};
    var jSQL_KEY_NAME = 'jSQL_Key';
    var utils = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    jSQL = function() {
        this.init.apply(this, arguments);
    };

    jSQL.prototype = {
        version: '0.3.0-dev',

        init: function() {
            this._jSQL = _jSQL;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
            this._DBIndexMap = _DBIndexMap;
            this.utils = utils;
        },

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(utils.isArray(db)) {
                indexList = utils.listSlice(arguments, '2:');
                utils.appendKey(db, indexList);
                _DBIndexMap[dbname] = utils.arrayToObject(db);
            }

            if(utils.isPlainObject(db)) {
                _DBIndexMap[dbname] = utils.clone(db);
                db = utils.objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            this._currentDBName = dbname;
            this.rebase();
            return this;
        },

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        dbs: function() {
            return utils.keys(this._DB);
        },

        db: function() {
            return this._currentDBName;
        },

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer

            if(key === '*') {
                return this;
            }

            this.where(function(data) {
                return typeof(utils.deep(data, key)) !== 'undefined';
            });

            return this;
        },

        count: function() {
            var result;
            result = this._buffer.length;
            this.rebase();
            return result;
        },

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            utils.deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = utils.deep(a, field);
                b = utils.deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;
            fn = utils.parseFn(fn);

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, this._buffer[i], i);
                    }

                    if(utils.isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, this._buffer[i], i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp.push(utils.clone(this._buffer[i]));
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        findAll: function() {
            var result;
            result = utils.clone(utils.arrayToObject(this._buffer));
            this.rebase();
            return result;
        },

        find: function(key) {
            var result;
            var _tmp = this._DBIndexMap[this._currentDBName];

            if(!key) {
                for(var i in _tmp) {
                    if(_tmp.hasOwnProperty(i)) {
                        if(key) {
                            break;
                        }

                        if(this._buffer.hasOwnProperty(i)) {
                            key = i;
                        }
                    }
                }
            }

            result = utils.clone(_tmp[key]);
            this.rebase();
            return result;
        },

        listAll: function() {
            var result;
            result = utils.clone(this._buffer);
            this.rebase();
            return result;
        },

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = utils.listSlice(_tmp, limit);
            return this;
        },

        keys: function() {
            return utils.keys(this.findAll());
        },

        first: function(fn) {
            if(fn) {
                return this.where(fn).first();
            }

            return utils.listSlice(this._buffer, ':1');
        },

        last: function(fn) {
            if(fn) {
                return this.where(fn).last();
            }

            return utils.listSlice(this._buffer, '-1:');
        },

        rebase: function() {
            this.select('*');
            return this;
        }
    };

    utils = {
        deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        isObject: function(obj) {
            return obj === Object(obj);
        },

        isPlainObject: function(obj) {
            return this.isObject(obj) && obj.constructor === Object;
        },

        clone: function (obj) {
            if(obj == null || typeof(obj) != 'object') {
                return obj;
            }

            var temp = new obj.constructor();
            for(var key in obj) {
                temp[key] = arguments.callee(obj[key]);
            }

            return temp;
        },

        objectToArray: function(object) {
            var array = [], object = this.clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i][jSQL_KEY_NAME] = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || jSQL_KEY_NAME]] = this.clone(array[i]);
                delete object[array[i][key || jSQL_KEY_NAME]][key || jSQL_KEY_NAME];
            };

            return object;
        },

        each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that.isArray(indexList)) {
                baseRef = indexList;
            }

            that.each(baseRef, function(o, i, r) {
                key += utils.deep(object, o);
            });

            return key;
        },

        listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        appendKey: function(list, indexList) {
            var that = this;
            that.each(list, function(o, i, r) {
                o[jSQL_KEY_NAME] = that.keygen(o, indexList) || i;
            });
        },

        keys: nativeKeys || (function() {
            var hasDontEnumBug = true,
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            for (var key in {'toString': null}) {
                hasDontEnumBug = false;
            }

            return function keys(object) {
                if ((typeof object != 'object' && typeof object != 'function') || object === null) {
                    throw new TypeError('Object.keys called on a non-object');
                }

                var keys = [];
                for (var name in object) {
                    if (object.hasOwnProperty(name)) {
                        keys.push(name);
                    }
                }

                if (hasDontEnumBug) {
                    for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                        var dontEnum = dontEnums[i];
                        if (object.hasOwnProperty(dontEnum)) {
                            keys.push(dontEnum);
                        }
                    }
                }
                return keys;
            };
        })(),

        parseFn: function(fn) {
            if(typeof(fn) === 'string') {
                fn = new Function('data', 'with(data) { return ' + fn + '; }');
            }

            return fn;
        }
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jsql = this.jSQL = jSQL;
})();
<commit_msg>added insert todo.<commit_after>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.3.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var slice            = Array.prototype.slice,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys;

    var jSQL, _jSQL, _DB = {}, _DBIndexMap = {};
    var jSQL_KEY_NAME = 'jSQL_Key';
    var utils = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    jSQL = function() {
        this.init.apply(this, arguments);
    };

    jSQL.prototype = {
        version: '0.3.0-dev',

        init: function() {
            this._jSQL = _jSQL;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
            this._DBIndexMap = _DBIndexMap;
            this.utils = utils;
        },

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(utils.isArray(db)) {
                indexList = utils.listSlice(arguments, '2:');
                utils.appendKey(db, indexList);
                _DBIndexMap[dbname] = utils.arrayToObject(db);
            }

            if(utils.isPlainObject(db)) {
                _DBIndexMap[dbname] = utils.clone(db);
                db = utils.objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            this._currentDBName = dbname;
            this.rebase();
            return this;
        },

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        dbs: function() {
            return utils.keys(this._DB);
        },

        db: function() {
            return this._currentDBName;
        },

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer

            if(key === '*') {
                return this;
            }

            this.where(function(data) {
                return typeof(utils.deep(data, key)) !== 'undefined';
            });

            return this;
        },

        count: function() {
            var result;
            result = this._buffer.length;
            this.rebase();
            return result;
        },

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            utils.deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = utils.deep(a, field);
                b = utils.deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;
            fn = utils.parseFn(fn);

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, this._buffer[i], i);
                    }

                    if(utils.isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, this._buffer[i], i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp.push(utils.clone(this._buffer[i]));
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        findAll: function() {
            var result;
            result = utils.clone(utils.arrayToObject(this._buffer));
            this.rebase();
            return result;
        },

        find: function(key) {
            var result;
            var _tmp = this._DBIndexMap[this._currentDBName];

            if(!key) {
                for(var i in _tmp) {
                    if(_tmp.hasOwnProperty(i)) {
                        if(key) {
                            break;
                        }

                        if(this._buffer.hasOwnProperty(i)) {
                            key = i;
                        }
                    }
                }
            }

            result = utils.clone(_tmp[key]);
            this.rebase();
            return result;
        },

        listAll: function() {
            var result;
            result = utils.clone(this._buffer);
            this.rebase();
            return result;
        },

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        insert: function() {
            //TODO
        },

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = utils.listSlice(_tmp, limit);
            return this;
        },

        keys: function() {
            return utils.keys(this.findAll());
        },

        first: function(fn) {
            if(fn) {
                return this.where(fn).first();
            }

            return utils.listSlice(this._buffer, ':1');
        },

        last: function(fn) {
            if(fn) {
                return this.where(fn).last();
            }

            return utils.listSlice(this._buffer, '-1:');
        },

        rebase: function() {
            this.select('*');
            return this;
        }
    };

    utils = {
        deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        isObject: function(obj) {
            return obj === Object(obj);
        },

        isPlainObject: function(obj) {
            return this.isObject(obj) && obj.constructor === Object;
        },

        clone: function (obj) {
            if(obj == null || typeof(obj) != 'object') {
                return obj;
            }

            var temp = new obj.constructor();
            for(var key in obj) {
                temp[key] = arguments.callee(obj[key]);
            }

            return temp;
        },

        objectToArray: function(object) {
            var array = [], object = this.clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i][jSQL_KEY_NAME] = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || jSQL_KEY_NAME]] = this.clone(array[i]);
                delete object[array[i][key || jSQL_KEY_NAME]][key || jSQL_KEY_NAME];
            };

            return object;
        },

        each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that.isArray(indexList)) {
                baseRef = indexList;
            }

            that.each(baseRef, function(o, i, r) {
                key += utils.deep(object, o);
            });

            return key;
        },

        listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        appendKey: function(list, indexList) {
            var that = this;
            that.each(list, function(o, i, r) {
                o[jSQL_KEY_NAME] = that.keygen(o, indexList) || i;
            });
        },

        keys: nativeKeys || (function() {
            var hasDontEnumBug = true,
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            for (var key in {'toString': null}) {
                hasDontEnumBug = false;
            }

            return function keys(object) {
                if ((typeof object != 'object' && typeof object != 'function') || object === null) {
                    throw new TypeError('Object.keys called on a non-object');
                }

                var keys = [];
                for (var name in object) {
                    if (object.hasOwnProperty(name)) {
                        keys.push(name);
                    }
                }

                if (hasDontEnumBug) {
                    for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                        var dontEnum = dontEnums[i];
                        if (object.hasOwnProperty(dontEnum)) {
                            keys.push(dontEnum);
                        }
                    }
                }
                return keys;
            };
        })(),

        parseFn: function(fn) {
            if(typeof(fn) === 'string') {
                fn = new Function('data', 'with(data) { return ' + fn + '; }');
            }

            return fn;
        }
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jsql = this.jSQL = jSQL;
})();
<|endoftext|>