<commit_before>// @requires Tian.js
// @requires JSON.js

//=============================================================
// Namespace: Tian.DB
// Contains convenience functions for storage manipulation.
//-------------------------------------------------------------

// THIS IS A COPY OF JSTORAGE
// BUT RENAME jStorage TO Tian.DB FOR INTEGERITY

/*
 * ----------------------------- JSTORAGE -------------------------------------
 * Simple local storage wrapper to save data on the browser side, supporting
 * all major browsers - IE6+, Firefox2+, Safari4+, Chrome4+ and Opera 10.5+
 *
 * Copyright (c) 2010 Andris Reinman, andris.reinman@gmail.com
 * Project homepage: www.jstorage.info
 *
 * Licensed under MIT-style license:
 *
 * 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 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.
 */

/**
 * $.jStorage
 *
 * USAGE:
 *
 * jStorage requires Prototype, MooTools or jQuery! If jQuery is used, then
 * jQuery-JSON (http://code.google.com/p/jquery-json/) is also needed.
 * (jQuery-JSON needs to be loaded BEFORE jStorage!)
 *
 * Methods:
 *
 * -set(key, value[, options])
 * $.jStorage.set(key, value) -> saves a value
 *
 * -get(key[, default])
 * value = $.jStorage.get(key [, default]) ->
 *    retrieves value if key exists, or default if it doesn't
 *
 * -deleteKey(key)
 * $.jStorage.deleteKey(key) -> removes a key from the storage
 *
 * -flush()
 * $.jStorage.flush() -> clears the cache
 *
 * -storageObj()
 * $.jStorage.storageObj() -> returns a read-ony copy of the actual storage
 *
 * -storageSize()
 * $.jStorage.storageSize() -> returns the size of the storage in bytes
 *
 * -index()
 * $.jStorage.index() -> returns the used keys as an array
 *
 * -storageAvailable()
 * $.jStorage.storageAvailable() -> returns true if storage is available
 *
 * -reInit()
 * $.jStorage.reInit() -> reloads the data from browser storage
 *
 * <value> can be any JSON-able value, including objects and arrays.
 *
 **/

(function($){
    var
        /* This is the object, that holds the cached values */
        _storage = {},

        /* Actual browser storage (localStorage or globalStorage['domain']) */
        _storage_service = {jStorage:"{}"},

        /* DOM element for older IE versions, holds userData behavior */
        _storage_elm = null,

        /* How much space does the storage take */
        _storage_size = 0,

        /* function to encode objects to JSON strings */
        json_encode = $.JSON.stringify || Object.toJSON || (window.JSON && (JSON.encode || JSON.stringify)),

        /* function to decode objects from JSON strings */
        json_decode = $.JSON.parse || (window.JSON && (JSON.decode || JSON.parse)) || function(str){
            return String(str).evalJSON();
        },

        /* which backend is currently used */
        _backend = false,

        /* Next check for TTL */
        _ttl_timeout,

        /**
         * XML encoding and decoding as XML nodes can't be JSON'ized
         * XML nodes are encoded and decoded if the node is the value to be saved
         * but not if it's as a property of another object
         * Eg. -
         *   $.jStorage.set("key", xmlNode);        // IS OK
         *   $.jStorage.set("key", {xml: xmlNode}); // NOT OK
         */
        _XMLService = {

            /**
             * Validates a XML node to be XML
             * based on jQuery.isXML function
             */
            isXML: function(elm){
                var documentElement = (elm ? elm.ownerDocument || elm : 0).documentElement;
                return documentElement ? documentElement.nodeName !== "HTML" : false;
            },

            /**
             * Encodes a XML node to string
             * based on http://www.mercurytide.co.uk/news/article/issues-when-working-ajax/
             */
            encode: function(xmlNode) {
                if(!this.isXML(xmlNode)){
                    return false;
                }
                try{ // Mozilla, Webkit, Opera
                    return new XMLSerializer().serializeToString(xmlNode);
                }catch(E1) {
                    try {  // IE
                        return xmlNode.xml;
                    }catch(E2){}
                }
                return false;
            },

            /**
             * Decodes a XML node from string
             * loosely based on http://outwestmedia.com/jquery-plugins/xmldom/
             */
            decode: function(xmlString){
                var dom_parser = ("DOMParser" in window && (new DOMParser()).parseFromString) ||
                        (window.ActiveXObject && function(_xmlString) {
                    var xml_doc = new ActiveXObject('Microsoft.XMLDOM');
                    xml_doc.async = 'false';
                    xml_doc.loadXML(_xmlString);
                    return xml_doc;
                }),
                resultXML;
                if(!dom_parser){
                    return false;
                }
                resultXML = dom_parser.call("DOMParser" in window && (new DOMParser()) || window, xmlString, 'text/xml');
                return this.isXML(resultXML)?resultXML:false;
            }
        };

    ////////////////////////// PRIVATE METHODS ////////////////////////

    /**
     * Initialization function. Detects if the browser supports DOM Storage
     * or userData behavior and behaves accordingly.
     * @returns undefined
     */
    function _init(){
        /* Check if browser supports localStorage */
        var localStorageReallyWorks = false;
        if("localStorage" in window){
            try {
                window.localStorage.setItem('_tmptest', 'tmpval');
                localStorageReallyWorks = true;
                window.localStorage.removeItem('_tmptest');
            } catch(BogusQuotaExceededErrorOnIos5) {
                // Thanks be to iOS5 Private Browsing mode which throws
                // QUOTA_EXCEEDED_ERRROR DOM Exception 22.
            }
        }
        if(localStorageReallyWorks){
            try {
                if(window.localStorage) {
                    _storage_service = window.localStorage;
                    _backend = "localStorage";
                }
            } catch(E3) {/* Firefox fails when touching localStorage and cookies are disabled */}
        }
        /* Check if browser supports globalStorage */
        else if("globalStorage" in window){
            try {
                if(window.globalStorage) {
                    _storage_service = window.globalStorage[window.location.hostname];
                    _backend = "globalStorage";
                }
            } catch(E4) {/* Firefox fails when touching localStorage and cookies are disabled */}
        }
        /* Check if browser supports userData behavior */
        else {
            _storage_elm = document.createElement('link');
            if(_storage_elm.addBehavior){

                /* Use a DOM element to act as userData storage */
                _storage_elm.style.behavior = 'url(#default#userData)';

                /* userData element needs to be inserted into the DOM! */
                document.getElementsByTagName('head')[0].appendChild(_storage_elm);

                _storage_elm.load("jStorage");
                var data = "{}";
                try{
                    data = _storage_elm.getAttribute("jStorage");
                }catch(E5){}
                _storage_service.jStorage = data;
                _backend = "userDataBehavior";
            }else{
                _storage_elm = null;
                return;
            }
        }

        _load_storage();

        // remove dead keys
        _handleTTL();
    }

    /**
     * Loads the data from the storage based on the supported mechanism
     * @returns undefined
     */
    function _load_storage(){
        /* if jStorage string is retrieved, then decode it */
        if(_storage_service.jStorage){
            try{
                _storage = json_decode(String(_storage_service.jStorage));
            }catch(E6){_storage_service.jStorage = "{}";}
        }else{
            _storage_service.jStorage = "{}";
        }
        _storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0;
    }

    /**
     * This functions provides the "save" mechanism to store the jStorage object
     * @returns undefined
     */
    function _save(){
        try{
            _storage_service.jStorage = json_encode(_storage);
            // If userData is used as the storage engine, additional
            if(_storage_elm) {
                _storage_elm.setAttribute("jStorage",_storage_service.jStorage);
                _storage_elm.save("jStorage");
            }
            _storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0;
        }catch(E7){/* probably cache is full, nothing is saved this way*/}
    }

    /**
     * Function checks if a key is set and is string or numberic
     */
    function _checkKey(key){
        if(!key || (typeof key != "string" && typeof key != "number")){
            throw new TypeError('Key name must be string or numeric');
        }
        if(key == "__jstorage_meta"){
            throw new TypeError('Reserved key name');
        }
        return true;
    }

    /**
     * Removes expired keys
     */
    function _handleTTL(){
        var curtime, i, TTL, nextExpire = Infinity, changed = false;

        clearTimeout(_ttl_timeout);

        if(!_storage.__jstorage_meta || typeof _storage.__jstorage_meta.TTL != "object"){
            // nothing to do here
            return;
        }

        curtime = +new Date();
        TTL = _storage.__jstorage_meta.TTL;
        for(i in TTL){
            if(TTL.hasOwnProperty(i)){
                if(TTL[i] <= curtime){
                    delete TTL[i];
                    delete _storage[i];
                    changed = true;
                }else if(TTL[i] < nextExpire){
                    nextExpire = TTL[i];
                }
            }
        }

        // set next check
        if(nextExpire != Infinity){
            _ttl_timeout = setTimeout(_handleTTL, nextExpire - curtime);
        }

        // save changes
        if(changed){
            _save();
        }
    }

    ////////////////////////// PUBLIC INTERFACE /////////////////////////

    // rename jStorage to DB for Tian integerity
    $.DB = {
        /* Version number */
        version: "0.1.7.0",

        /**
         * Sets a key's value.
         *
         * @param {String} key - Key to set. If this value is not set or not
         *              a string an exception is raised.
         * @param {Mixed} value - Value to set. This can be any value that is JSON
         *              compatible (Numbers, Strings, Objects etc.).
         * @param {Object} [options] - possible options to use
         * @param {Number} [options.TTL] - optional TTL value
         * @returns the used value
         */
        set: function(key, value, options){
            _checkKey(key);

            options = options || {};

            if(_XMLService.isXML(value)){
                value = {_is_xml:true,xml:_XMLService.encode(value)};
            }else if(typeof value == "function"){
                value = null; // functions can't be saved!
            }else if(value && typeof value == "object"){
                // clone the object before saving to _storage tree
                value = json_decode(json_encode(value));
            }
            _storage[key] = value;

            if(!isNaN(options.TTL)){
                this.setTTL(key, options.TTL);
                // also handles saving
            }else{
                _save();
            }
            return value;
        },

        /**
         * Looks up a key in cache
         *
         * @param {String} key - Key to look up.
         * @param {mixed} def - Default value to return, if key didn't exist.
         * @returns the key value, default value or <null>
         */
        get: function(key, def){
            _checkKey(key);
            if(key in _storage){
                if(_storage[key] && typeof _storage[key] == "object" &&
                        _storage[key]._is_xml &&
                            _storage[key]._is_xml){
                    return _XMLService.decode(_storage[key].xml);
                }else{
                    return _storage[key];
                }
            }
            return typeof(def) == 'undefined' ? null : def;
        },

        /**
         * Deletes a key from cache.
         *
         * @param {String} key - Key to delete.
         * @returns true if key existed or false if it didn't
         */
        deleteKey: function(key){
            _checkKey(key);
            if(key in _storage){
                delete _storage[key];
                // remove from TTL list
                if(_storage.__jstorage_meta &&
                  typeof _storage.__jstorage_meta.TTL == "object" &&
                  key in _storage.__jstorage_meta.TTL){
                    delete _storage.__jstorage_meta.TTL[key];
                }
                _save();
                return true;
            }
            return false;
        },

        /**
         * Sets a TTL for a key, or remove it if ttl value is 0 or below
         *
         * @param {String} key - key to set the TTL for
         * @param {Number} ttl - TTL timeout in milliseconds
         * @returns true if key existed or false if it didn't
         */
        setTTL: function(key, ttl){
            var curtime = +new Date();
            _checkKey(key);
            ttl = Number(ttl) || 0;
            if(key in _storage){

                if(!_storage.__jstorage_meta){
                    _storage.__jstorage_meta = {};
                }
                if(!_storage.__jstorage_meta.TTL){
                    _storage.__jstorage_meta.TTL = {};
                }

                // Set TTL value for the key
                if(ttl>0){
                    _storage.__jstorage_meta.TTL[key] = curtime + ttl;
                }else{
                    delete _storage.__jstorage_meta.TTL[key];
                }

                _save();

                _handleTTL();
                return true;
            }
            return false;
        },

        /**
         * Deletes everything in cache.
         *
         * @return true
         */
        flush: function(){
            _storage = {};
            _save();
            return true;
        },

        /**
         * Returns a read-only copy of _storage
         *
         * @returns Object
        */
        storageObj: function(){
            function F() {}
            F.prototype = _storage;
            return new F();
        },

        /**
         * Returns an index of all used keys as an array
         * ['key1', 'key2',..'keyN']
         *
         * @returns Array
        */
        index: function(){
            var index = [], i;
            for(i in _storage){
                if(_storage.hasOwnProperty(i) && i != "__jstorage_meta"){
                    index.push(i);
                }
            }
            return index;
        },

        /**
         * How much space in bytes does the storage take?
         *
         * @returns Number
         */
        storageSize: function(){
            return _storage_size;
        },

        /**
         * Which backend is currently in use?
         *
         * @returns String
         */
        currentBackend: function(){
            return _backend;
        },

        /**
         * Test if storage is available
         *
         * @returns Boolean
         */
        storageAvailable: function(){
            return !!_backend;
        },

        /**
         * Reloads the data from browser storage
         *
         * @returns undefined
         */
        reInit: function(){
            var new_storage_elm, data;
            if(_storage_elm && _storage_elm.addBehavior){
                new_storage_elm = document.createElement('link');

                _storage_elm.parentNode.replaceChild(new_storage_elm, _storage_elm);
                _storage_elm = new_storage_elm;

                /* Use a DOM element to act as userData storage */
                _storage_elm.style.behavior = 'url(#default#userData)';

                /* userData element needs to be inserted into the DOM! */
                document.getElementsByTagName('head')[0].appendChild(_storage_elm);

                _storage_elm.load("jStorage");
                data = "{}";
                try{
                    data = _storage_elm.getAttribute("jStorage");
                }catch(E5){}
                _storage_service.jStorage = data;
                _backend = "userDataBehavior";
            }

            _load_storage();
        }
    };

    // Initialize jStorage
    _init();

})(Tian);
<commit_msg>Remove XML support of Tian.DB.<commit_after>// @requires Tian.js
// @requires JSON.js

//=============================================================
// Namespace: Tian.DB
// Contains convenience functions for storage manipulation.
//-------------------------------------------------------------

// THIS IS A COPY OF JSTORAGE
// BUT RENAME jStorage TO Tian.DB FOR INTEGERITY

/*
 * ----------------------------- JSTORAGE -------------------------------------
 * Simple local storage wrapper to save data on the browser side, supporting
 * all major browsers - IE6+, Firefox2+, Safari4+, Chrome4+ and Opera 10.5+
 *
 * Copyright (c) 2010 Andris Reinman, andris.reinman@gmail.com
 * Project homepage: www.jstorage.info
 *
 * Licensed under MIT-style license:
 *
 * 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 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.
 */

/**
 * $.jStorage
 *
 * USAGE:
 *
 * jStorage requires Prototype, MooTools or jQuery! If jQuery is used, then
 * jQuery-JSON (http://code.google.com/p/jquery-json/) is also needed.
 * (jQuery-JSON needs to be loaded BEFORE jStorage!)
 *
 * Methods:
 *
 * -set(key, value[, options])
 * $.jStorage.set(key, value) -> saves a value
 *
 * -get(key[, default])
 * value = $.jStorage.get(key [, default]) ->
 *    retrieves value if key exists, or default if it doesn't
 *
 * -deleteKey(key)
 * $.jStorage.deleteKey(key) -> removes a key from the storage
 *
 * -flush()
 * $.jStorage.flush() -> clears the cache
 *
 * -storageObj()
 * $.jStorage.storageObj() -> returns a read-ony copy of the actual storage
 *
 * -storageSize()
 * $.jStorage.storageSize() -> returns the size of the storage in bytes
 *
 * -index()
 * $.jStorage.index() -> returns the used keys as an array
 *
 * -storageAvailable()
 * $.jStorage.storageAvailable() -> returns true if storage is available
 *
 * -reInit()
 * $.jStorage.reInit() -> reloads the data from browser storage
 *
 * <value> can be any JSON-able value, including objects and arrays.
 *
 **/

(function($){
    var
        /* This is the object, that holds the cached values */
        _storage = {},

        /* Actual browser storage (localStorage or globalStorage['domain']) */
        _storage_service = {jStorage:"{}"},

        /* DOM element for older IE versions, holds userData behavior */
        _storage_elm = null,

        /* How much space does the storage take */
        _storage_size = 0,

        /* which backend is currently used */
        _backend = false,

        /* Next check for TTL */
        _ttl_timeout;

    ////////////////////////// PRIVATE METHODS ////////////////////////

    /**
     * Initialization function. Detects if the browser supports DOM Storage
     * or userData behavior and behaves accordingly.
     * @returns undefined
     */
    function _init(){
        /* Check if browser supports localStorage */
        var localStorageReallyWorks = false;
        if("localStorage" in window){
            try {
                window.localStorage.setItem('_tmptest', 'tmpval');
                localStorageReallyWorks = true;
                window.localStorage.removeItem('_tmptest');
            } catch(BogusQuotaExceededErrorOnIos5) {
                // Thanks be to iOS5 Private Browsing mode which throws
                // QUOTA_EXCEEDED_ERRROR DOM Exception 22.
            }
        }
        if(localStorageReallyWorks){
            try {
                if(window.localStorage) {
                    _storage_service = window.localStorage;
                    _backend = "localStorage";
                }
            } catch(E3) {/* Firefox fails when touching localStorage and cookies are disabled */}
        }
        /* Check if browser supports globalStorage */
        else if("globalStorage" in window){
            try {
                if(window.globalStorage) {
                    _storage_service = window.globalStorage[window.location.hostname];
                    _backend = "globalStorage";
                }
            } catch(E4) {/* Firefox fails when touching localStorage and cookies are disabled */}
        }
        /* Check if browser supports userData behavior */
        else {
            _storage_elm = document.createElement('link');
            if(_storage_elm.addBehavior){

                /* Use a DOM element to act as userData storage */
                _storage_elm.style.behavior = 'url(#default#userData)';

                /* userData element needs to be inserted into the DOM! */
                document.getElementsByTagName('head')[0].appendChild(_storage_elm);

                _storage_elm.load("jStorage");
                var data = "{}";
                try{
                    data = _storage_elm.getAttribute("jStorage");
                }catch(E5){}
                _storage_service.jStorage = data;
                _backend = "userDataBehavior";
            }else{
                _storage_elm = null;
                return;
            }
        }

        _load_storage();

        // remove dead keys
        _handleTTL();
    }

    /**
     * Loads the data from the storage based on the supported mechanism
     * @returns undefined
     */
    function _load_storage(){
        /* if jStorage string is retrieved, then decode it */
        if(_storage_service.jStorage){
            try{
                _storage = $.JSON.parse(String(_storage_service.jStorage));
            }catch(E6){_storage_service.jStorage = "{}";}
        }else{
            _storage_service.jStorage = "{}";
        }
        _storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0;
    }

    /**
     * This functions provides the "save" mechanism to store the jStorage object
     * @returns undefined
     */
    function _save(){
        try{
            _storage_service.jStorage = $.JSON.stringify(_storage);
            // If userData is used as the storage engine, additional
            if(_storage_elm) {
                _storage_elm.setAttribute("jStorage",_storage_service.jStorage);
                _storage_elm.save("jStorage");
            }
            _storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0;
        }catch(E7){/* probably cache is full, nothing is saved this way*/}
    }

    /**
     * Function checks if a key is set and is string or numberic
     */
    function _checkKey(key){
        if(!key || (typeof key != "string" && typeof key != "number")){
            throw new TypeError('Key name must be string or numeric');
        }
        if(key == "__jstorage_meta"){
            throw new TypeError('Reserved key name');
        }
        return true;
    }

    /**
     * Removes expired keys
     */
    function _handleTTL(){
        var curtime, i, TTL, nextExpire = Infinity, changed = false;

        clearTimeout(_ttl_timeout);

        if(!_storage.__jstorage_meta || typeof _storage.__jstorage_meta.TTL != "object"){
            // nothing to do here
            return;
        }

        curtime = +new Date();
        TTL = _storage.__jstorage_meta.TTL;
        for(i in TTL){
            if(TTL.hasOwnProperty(i)){
                if(TTL[i] <= curtime){
                    delete TTL[i];
                    delete _storage[i];
                    changed = true;
                }else if(TTL[i] < nextExpire){
                    nextExpire = TTL[i];
                }
            }
        }

        // set next check
        if(nextExpire != Infinity){
            _ttl_timeout = setTimeout(_handleTTL, nextExpire - curtime);
        }

        // save changes
        if(changed){
            _save();
        }
    }

    ////////////////////////// PUBLIC INTERFACE /////////////////////////

    // rename jStorage to DB for Tian integerity
    $.DB = {
        /* Version number */
        VERSION: "2012-11-29",

        /**
         * Sets a key's value.
         *
         * @param {String} key - Key to set. If this value is not set or not
         *              a string an exception is raised.
         * @param {Mixed} value - Value to set. This can be any value that is JSON
         *              compatible (Numbers, Strings, Objects etc.).
         * @param {Object} [options] - possible options to use
         * @param {Number} [options.TTL] - optional TTL value
         * @returns the used value
         */
        set: function(key, value, options){
            _checkKey(key);

            options = options || {};

            if(typeof value == "function"){
                value = null; // functions can't be saved!
            }else if(value && typeof value == "object"){
                // clone the object before saving to _storage tree
                value = $.JSON.parse($.JSON.stringify(value));
            }
            _storage[key] = value;

            if(!isNaN(options.TTL)){
                this.setTTL(key, options.TTL);
                // also handles saving
            }else{
                _save();
            }
            return value;
        },

        /**
         * Looks up a key in cache
         *
         * @param {String} key - Key to look up.
         * @param {mixed} def - Default value to return, if key didn't exist.
         * @returns the key value, default value or <null>
         */
        get: function(key, def){
            _checkKey(key);
            if(key in _storage){
                return _storage[key];
            }
            return typeof(def) == 'undefined' ? null : def;
        },

        /**
         * Deletes a key from cache.
         *
         * @param {String} key - Key to delete.
         * @returns true if key existed or false if it didn't
         */
        deleteKey: function(key){
            _checkKey(key);
            if(key in _storage){
                delete _storage[key];
                // remove from TTL list
                if(_storage.__jstorage_meta &&
                  typeof _storage.__jstorage_meta.TTL == "object" &&
                  key in _storage.__jstorage_meta.TTL){
                    delete _storage.__jstorage_meta.TTL[key];
                }
                _save();
                return true;
            }
            return false;
        },

        /**
         * Sets a TTL for a key, or remove it if ttl value is 0 or below
         *
         * @param {String} key - key to set the TTL for
         * @param {Number} ttl - TTL timeout in milliseconds
         * @returns true if key existed or false if it didn't
         */
        setTTL: function(key, ttl){
            var curtime = +new Date();
            _checkKey(key);
            ttl = Number(ttl) || 0;
            if(key in _storage){

                if(!_storage.__jstorage_meta){
                    _storage.__jstorage_meta = {};
                }
                if(!_storage.__jstorage_meta.TTL){
                    _storage.__jstorage_meta.TTL = {};
                }

                // Set TTL value for the key
                if(ttl>0){
                    _storage.__jstorage_meta.TTL[key] = curtime + ttl;
                }else{
                    delete _storage.__jstorage_meta.TTL[key];
                }

                _save();

                _handleTTL();
                return true;
            }
            return false;
        },

        /**
         * Deletes everything in cache.
         *
         * @return true
         */
        flush: function(){
            _storage = {};
            _save();
            return true;
        },

        /**
         * Returns a read-only copy of _storage
         *
         * @returns Object
        */
        storageObj: function(){
            function F() {}
            F.prototype = _storage;
            return new F();
        },

        /**
         * Returns an index of all used keys as an array
         * ['key1', 'key2',..'keyN']
         *
         * @returns Array
        */
        index: function(){
            var index = [], i;
            for(i in _storage){
                if(_storage.hasOwnProperty(i) && i != "__jstorage_meta"){
                    index.push(i);
                }
            }
            return index;
        },

        /**
         * How much space in bytes does the storage take?
         *
         * @returns Number
         */
        storageSize: function(){
            return _storage_size;
        },

        /**
         * Which backend is currently in use?
         *
         * @returns String
         */
        currentBackend: function(){
            return _backend;
        },

        /**
         * Test if storage is available
         *
         * @returns Boolean
         */
        storageAvailable: function(){
            return !!_backend;
        },

        /**
         * Reloads the data from browser storage
         *
         * @returns undefined
         */
        reInit: function(){
            var new_storage_elm, data;
            if(_storage_elm && _storage_elm.addBehavior){
                new_storage_elm = document.createElement('link');

                _storage_elm.parentNode.replaceChild(new_storage_elm, _storage_elm);
                _storage_elm = new_storage_elm;

                /* Use a DOM element to act as userData storage */
                _storage_elm.style.behavior = 'url(#default#userData)';

                /* userData element needs to be inserted into the DOM! */
                document.getElementsByTagName('head')[0].appendChild(_storage_elm);

                _storage_elm.load("jStorage");
                data = "{}";
                try{
                    data = _storage_elm.getAttribute("jStorage");
                }catch(E5){}
                _storage_service.jStorage = data;
                _backend = "userDataBehavior";
            }

            _load_storage();
        }
    };

    // Initialize jStorage
    _init();

})(Tian);
<|endoftext|>


<commit_before>import styled, {css} from 'styled-components'
import {
  declareFont,
  theme,
  shadeColor,
  StyledScrollbar,
  scale
} from 'tocco-ui'
import _get from 'lodash/get'
import {lighten} from 'polished'

import {StyledResizeHandle} from './ResizingController'

export const StyledTableCell = styled.td`
  padding: ${scale.space(-1)};
  background-color: ${theme.color('paper')};
  border-bottom: 1px solid ${props => shadeColor(_get(props.theme, 'colors.paper'), 2)};
`

export const StyledTableHeaderCell = styled.th`
  padding: ${scale.space(-1)};
  position: sticky;
  top: 0;
  background-color: ${theme.color('paper')};
  text-align: left;
  border-bottom: 2px solid ${props => shadeColor(_get(props.theme, 'colors.paper'), 2)};
  ${declareFont({fontWeight: theme.fontWeight('bold')})};
  user-select: none;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  display: flex;
  ${props => props.isResizing && `
    background-color: ${lighten(0.25, props.theme.colors.secondaryLight)};

    > ${StyledResizeHandle} {
      opacity: 1;
    }
    `
  }
  ${props => !props.resizingColumn && `
    &:hover {
      background-color: ${lighten(0.25, props.theme.colors.secondaryLight)};

        > ${StyledResizeHandle} {
          opacity: 1;
        }
    }
    `
  }
`

export const PaginationContainer = styled.div`
  grid-row-start: pagination-start;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  border-top: 1px solid ${props => shadeColor(_get(props.theme, 'colors.paper'), 2)};
`

const selectionStyles = css`
  display: contents;
  cursor: pointer;

  &.selected {
    > ${StyledTableCell} {
      background-color: ${props => lighten(0.1, props.theme.colors.secondaryLight)};
    }
  }

  &.selectableRow:not(.selected):hover {
    > ${StyledTableCell} {
      background-color: ${props => lighten(0.25, props.theme.colors.secondaryLight)};
    }
  }
`

export const StyledSortingSpan = styled.span`
  height: 100%;
  position: relative;
  left: 8px;
  top: 0;
  display: flex;
  align-items: center;
`

export const StyledFullRowProgress = styled.td`
  grid-column: 1 / -1;
  padding-top: ${scale.space(-1)};
  height: 50px;
  text-align: center;
  border: 0;
`

export const StyledFullRow = styled.td`
  grid-column: 1 / -1;
  padding-top: ${scale.space(-1)};
  height: 50px;
  text-align: center;
  border: 0;
  ${declareFont()};
`

export const StyledTableHead = styled.thead`
  ${selectionStyles}
`

export const StyledTableRow = styled.tr`
  ${selectionStyles}
`

export const StyledTableBody = styled.tbody`
  ${selectionStyles}
`

const StyledTable = styled.table`
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
  display: grid;
  border-collapse: collapse;
  grid-template-columns: ${props =>
  props.columns.map(column => column.width ? column.width + 'px' : 'minmax(50px, auto)').join(' ')};
  grid-auto-rows: min-content;
  min-width: 100%;
  ${StyledScrollbar}
`

export const StretchingTableContainer = styled.div`
  grid-row-start: table-start;
  position: relative;
`

export const StyledTableWrapper = styled.div`
  display: grid;
  padding-left: ${scale.space(-0.5)};
  background-color: ${theme.color('paper')};
  grid-template-rows: [table-start] 1fr [pagination-start] auto auto;
  height: 100%;
`

export const StyledDnD = styled.div`
  width: 100%;
  display: flex;
  border-right: ${props => props.isDraggedOver ? '3px solid ' + props.theme.colors.primary : 'none'};
  opacity: ${props => props.isDragged ? 0.2 : 1};
  pointer-events: ${props => props.isDraggedOver ? 'none' : 'auto'};
`

export default StyledTable
<commit_msg>refactor(entity-list): adjust minimum table height<commit_after>import styled, {css} from 'styled-components'
import {
  declareFont,
  theme,
  shadeColor,
  StyledScrollbar,
  scale
} from 'tocco-ui'
import _get from 'lodash/get'
import {lighten} from 'polished'

import {StyledResizeHandle} from './ResizingController'

export const StyledTableCell = styled.td`
  padding: ${scale.space(-1)};
  background-color: ${theme.color('paper')};
  border-bottom: 1px solid ${props => shadeColor(_get(props.theme, 'colors.paper'), 2)};
`

export const StyledTableHeaderCell = styled.th`
  padding: ${scale.space(-1)};
  position: sticky;
  top: 0;
  background-color: ${theme.color('paper')};
  text-align: left;
  border-bottom: 2px solid ${props => shadeColor(_get(props.theme, 'colors.paper'), 2)};
  ${declareFont({fontWeight: theme.fontWeight('bold')})};
  user-select: none;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  display: flex;
  ${props => props.isResizing && `
    background-color: ${lighten(0.25, props.theme.colors.secondaryLight)};

    > ${StyledResizeHandle} {
      opacity: 1;
    }
    `
  }
  ${props => !props.resizingColumn && `
    &:hover {
      background-color: ${lighten(0.25, props.theme.colors.secondaryLight)};

        > ${StyledResizeHandle} {
          opacity: 1;
        }
    }
    `
  }
`

export const PaginationContainer = styled.div`
  grid-row-start: pagination-start;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  border-top: 1px solid ${props => shadeColor(_get(props.theme, 'colors.paper'), 2)};
`

const selectionStyles = css`
  display: contents;
  cursor: pointer;

  &.selected {
    > ${StyledTableCell} {
      background-color: ${props => lighten(0.1, props.theme.colors.secondaryLight)};
    }
  }

  &.selectableRow:not(.selected):hover {
    > ${StyledTableCell} {
      background-color: ${props => lighten(0.25, props.theme.colors.secondaryLight)};
    }
  }
`

export const StyledSortingSpan = styled.span`
  height: 100%;
  position: relative;
  left: 8px;
  top: 0;
  display: flex;
  align-items: center;
`

export const StyledFullRowProgress = styled.td`
  grid-column: 1 / -1;
  padding-top: ${scale.space(-1)};
  height: 50px;
  text-align: center;
  border: 0;
`

export const StyledFullRow = styled.td`
  grid-column: 1 / -1;
  padding-top: ${scale.space(-1)};
  height: 50px;
  text-align: center;
  border: 0;
  ${declareFont()};
`

export const StyledTableHead = styled.thead`
  ${selectionStyles}
`

export const StyledTableRow = styled.tr`
  ${selectionStyles}
`

export const StyledTableBody = styled.tbody`
  ${selectionStyles}
`

const StyledTable = styled.table`
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
  display: grid;
  border-collapse: collapse;
  grid-template-columns: ${props =>
  props.columns.map(column => column.width ? column.width + 'px' : 'minmax(50px, auto)').join(' ')};
  grid-auto-rows: min-content;
  min-width: 100%;
  ${StyledScrollbar}
`

export const StretchingTableContainer = styled.div`
  grid-row-start: table-start;
  position: relative;
`

export const StyledTableWrapper = styled.div`
  display: grid;
  padding-left: ${scale.space(-0.5)};
  background-color: ${theme.color('paper')};
  grid-template-rows: [table-start] minmax(300px, 1fr) [pagination-start] auto auto;
  height: 100%;

  @media screen and (max-height: 650px) {
    grid-template-rows: [table-start] 1fr [pagination-start] auto auto;
  }
`

export const StyledDnD = styled.div`
  width: 100%;
  display: flex;
  border-right: ${props => props.isDraggedOver ? '3px solid ' + props.theme.colors.primary : 'none'};
  opacity: ${props => props.isDragged ? 0.2 : 1};
  pointer-events: ${props => props.isDraggedOver ? 'none' : 'auto'};
`

export default StyledTable
<|endoftext|>


<commit_before>(function() {
  var UI = {
    spotErrorMessage: function() {
      alert("That is not an available spot.\nPlease choose a different spot.");
    },

    winMessage: function(winner) {
      alert("Congratulations.\n"+ winner +" win!!");
    },

    tieMessage: function() {
      alert("Game is tied.\nGame Over.");
    },

    inputErrorMessage: function() {
      alert("You have to choose 'X' or 'O'.");
    },

    askChoicePlayer: function() {
      return prompt("What player do you require? ('X' or 'O'):");
    },

    toggleDisplayedButton: function(hideClass, showClass) {
      $(hideClass).hide();
      $(showClass).show()
    },

    hideButton: function(hideClass1, hideClass2) {
      $(hideClass1).hide();
      $(hideClass2).hide();
    }
  };
  window.UI = UI;
})();
<commit_msg>firxe UI.js<commit_after>(function() {
  var UI = {
    spotErrorMessage: function() {
      alert("That is not an available spot.\nPlease choose a different spot.");
    },

    winMessage: function(winner) {
      alert("Congratulations.\n"+ winner +" win!!");
    },

    tieMessage: function() {
      alert("Game is tied.\nGame Over.");
    },

    inputErrorMessage: function() {
      alert("You have to choose 'X' or 'O'.");
    },

    askChoicePlayer: function() {
      return prompt("What player do you require? ('X' or 'O'):");
    },

    toggleDisplayedButton: function(hideClass, showClass) {
      $(hideClass).hide();
      $(hideClass).unbind();
      $(showClass).show()
    },

    hideButton: function(hideClass1, hideClass2) {
      $(hideClass1).hide();
      $(hideClass2).hide();
    }
  };
  window.UI = UI;
})();
<|endoftext|>


<commit_before>const decks = new Map();
const games = new Map();

const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const suits = ['♣', '♦', '❤', '♠'];
const DECK_TEMPLATE = suits
	.map(suit => ranks.concat(ranks)
	.concat(ranks)
	.concat(ranks)
	.map(rank => rank + suit))
	.reduce((array, arr) => array.concat(arr));

class Blackjack {
	constructor(msg) {
		this.guildID = msg.guild.id;
		this.playerID = msg.author.id;

		games.set(this.playerID, this);
	}

	getHand() {
		return this.hit(this.hit([]));
	}

	hit(hand) {
		if (!this.deck || this.deck.length === 0) {
			if (decks.has(this.guildID) && decks.get(this.guildID).length !== 0) {
				this.deck = decks.get(this.guildID);
			} else {
				this.deck = Blackjack._shuffle(DECK_TEMPLATE);
				decks.set(this.guildID, this.deck);
			}
		}
		hand.push(this.deck.pop());

		return hand;
	}

	endGame() {
		return games.delete(this.playerID);
	}

	cardsRemaining() {
		return decks.has(this.guildID) ? decks.get(this.guildID).length : this.decks.length;
	}

	static gameExists(playerID) {
		return games.has(playerID);
	}

	static isSoft(hand) {
		let value = 0;
		let aces = 0;

		hand.forEach(card => {
			value += Blackjack._cardValue(card);
			if (Blackjack._cardValue(card) === 11) aces++;
		});

		while (value > 21 && aces > 0) {
			value -= 10;
			aces--;
		}

		if (value === 21 && hand.length === 2) return false;

		return aces !== 0;
	}

	static handValue(hand) {
		let value = 0;
		let aces = 0;

		hand.forEach(card => {
			value += Blackjack._cardValue(card);
			if (Blackjack._cardValue(card) === 11) aces++;
		});

		while (value > 21 && aces > 0) {
			value -= 10;
			aces--;
		}

		if (value === 21 && hand.length === 2) return 'Blackjack';

		return value;
	}

	static _cardValue(card) {
		const index = ranks.indexOf(card.slice(0, -1));
		if (index === 0) return 11;

		return index >= 10 ? 10 : index + 1;
	}

	static _shuffle(array) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			const temp = array[i];
			array[i] = array[j];
			array[j] = temp;
		}

		return array;
	}
}

module.exports = Blackjack;
<commit_msg>Make sure to create a new array<commit_after>const decks = new Map();
const games = new Map();

const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const suits = ['♣', '♦', '❤', '♠'];
const DECK_TEMPLATE = suits
	.map(suit => ranks.concat(ranks)
	.concat(ranks)
	.concat(ranks)
	.map(rank => rank + suit))
	.reduce((array, arr) => array.concat(arr));

class Blackjack {
	constructor(msg) {
		this.guildID = msg.guild.id;
		this.playerID = msg.author.id;

		games.set(this.playerID, this);
	}

	getHand() {
		return this.hit(this.hit([]));
	}

	hit(hand) {
		if (!this.deck || this.deck.length === 0) {
			if (decks.has(this.guildID) && decks.get(this.guildID).length !== 0) {
				this.deck = decks.get(this.guildID);
			} else {
				this.deck = Blackjack._shuffle(DECK_TEMPLATE);
				decks.set(this.guildID, this.deck);
			}
		}
		hand.push(this.deck.pop());

		return hand;
	}

	endGame() {
		return games.delete(this.playerID);
	}

	cardsRemaining() {
		return decks.has(this.guildID) ? decks.get(this.guildID).length : this.decks.length;
	}

	static gameExists(playerID) {
		return games.has(playerID);
	}

	static isSoft(hand) {
		let value = 0;
		let aces = 0;

		hand.forEach(card => {
			value += Blackjack._cardValue(card);
			if (Blackjack._cardValue(card) === 11) aces++;
		});

		while (value > 21 && aces > 0) {
			value -= 10;
			aces--;
		}

		if (value === 21 && hand.length === 2) return false;

		return aces !== 0;
	}

	static handValue(hand) {
		let value = 0;
		let aces = 0;

		hand.forEach(card => {
			value += Blackjack._cardValue(card);
			if (Blackjack._cardValue(card) === 11) aces++;
		});

		while (value > 21 && aces > 0) {
			value -= 10;
			aces--;
		}

		if (value === 21 && hand.length === 2) return 'Blackjack';

		return value;
	}

	static _cardValue(card) {
		const index = ranks.indexOf(card.slice(0, -1));
		if (index === 0) return 11;

		return index >= 10 ? 10 : index + 1;
	}

	static _shuffle(array) {
		const newArray = array.slice();
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			const temp = newArray[i];
			newArray[i] = newArray[j];
			newArray[j] = temp;
		}

		return newArray;
	}
}

module.exports = Blackjack;
<|endoftext|>


<commit_before><commit_msg>Rename of ANIMCMD_MISC_CAMERACTRL3 to ANIMCMD_MISC_RESETHAIR<commit_after><|endoftext|>


<commit_before>/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Relevance UI Team,
 * Aug 2015
 */

(function(angular) {
	"use strict";
	angular.module('workzone.blueprint', ['ui.bootstrap', 'apis.workzone', 'ngMessages'])
		.factory('formatData', [function() {
			return {
				getFormattedCollection: function(obj) {
					var list = {
						"software_stack": [],
						"docker": [],
						"os_image": [],
						"cloudFormation": [],
						"azureARM": []
					},
					temp;
					for (var i = 0; i < obj.length; i++) {
						temp = obj[i];
						temp.iconpath = this.getIconPath(temp);
						temp.cardVersions = this.getVersionList(temp);
						temp.selectedVersionBpId = temp.cardVersions[0].id;
						//temp.selectedVersionBpName = temp.cardVersions[0].name;
						switch (temp.templateType) {
							case "chef":
								list.software_stack.push(temp);
								break;
							case "ami":
								list.os_image.push(temp);
								break;
							case "cft":
								list.cloudFormation.push(temp);
								break;
							case "docker":
								list.docker.push(temp);
								break;
							case "arm":
								list.azureARM.push(temp);
								break;
						}
					}
					return list;
				},
				getVersionList : function(bpItem) {
					var allVersionsList = [];
					var currentVersion = {
						id : bpItem._id,
						name : bpItem.name,
						version : 1
					};
					allVersionsList[0] = currentVersion;
					var olderVersions = [];
					if(bpItem.versions && bpItem.versions.length) {
						olderVersions = bpItem.versions;
						allVersionsList = allVersionsList.concat(olderVersions);
					}
					return allVersionsList.reverse();
				},
				getIconPath : function(bpItem) {
					return bpItem.iconpath || "images/templateicons/imgo.jpg";
				}
			};
		}])
		.controller('blueprintCtrl', ['$scope', '$modal', 'formatData', 'workzoneServices', '$rootScope', 'workzoneUIUtils', function($scope, $modal, formatData, workzoneServices, $rootScope, workzoneUIUtils) {
			/*Open only One Accordian-Group at a time*/
			$scope.oneAtATime = true;
			/*Initialising First Accordian-group open on load*/
			$scope.isFirstOpen = true;

			var envParams ;
			$rootScope.$on('WZ_ENV_CHANGE_START', function(event, requestParams, data) {
				$scope.isBlueprintPageLoading = true;
				$scope.envParams=requestParams;
				$scope.blueprintListCards();
			});

			angular.extend($scope, {
				blueprintListCards: function() {
					$scope.isBlueprintPageLoading = true;
					$scope.blueprints = [];
					// service to get the list of blueprints
					workzoneServices.getBlueprints($scope.envParams).then(function(result) {
						var blueprint = result.data;
						$scope.blueprints = formatData.getFormattedCollection(blueprint);
						$scope.isBlueprintPageLoading = false;
		                workzoneUIUtils.makeTabScrollable('blueprintPage');
					},function(error) {
						$scope.isBlueprintPageLoading = false;
						console.log(error);
						$scope.errorMessage = "No Records found";
					});
				},
				//method used to change the bp Name when the version is changed.
				changeCardVersion: function(blueprintObj,bpType){
					var idx = $scope.blueprints[bpType].indexOf(blueprintObj);
					var cardVersions = $scope.blueprints[bpType][idx].cardVersions;
					angular.forEach(cardVersions,function(val){
						if(val.id === $scope.blueprints[bpType][idx].selectedVersionBpId){
							if(bpType === 'software_stack'){
								cardVersions.name = val.name;
							}
							if(bpType === 'os_image'){
								cardVersions.name = val.name;
							}
							if(bpType === 'docker'){
								cardVersions.name = val.name;
							}
							if(bpType === 'azureARM'){
								cardVersions.name = val.name;
							}
							if(bpType === 'cloudFormation'){
								cardVersions.name = val.name;
							}
						}
					})
				},
				launchInstance: function(blueprintObj) {
				    $modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/blueprintLaunchParams.html",
						controller: "blueprintLaunchParamsCtrl",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return blueprintObj;
							}
						}
					})
					.result.then(function(bpObj) {
						if (bpObj.bp.blueprintType === "docker") {
							$modal.open({
								animate: true,
								templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/dockerLaunchParams.html",
								controller: "dockerLaunchParamsCtrl",
								backdrop: 'static',
								keyboard: false,
								size: 'lg',
								resolve: {
									items: function() {
										return bpObj.bp;
									}
								}
							}).result.then(function() {
								console.log('The modal close is not getting invoked currently. Goes to cancel handler');
							}, function() {
								console.log('Cancel Handler getting invoked');
							});
						}else{
						$modal.open({
								animate: true,
								templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/blueprintLaunch.html",
								controller: "blueprintLaunchCtrl",
								backdrop: 'static',
								keyboard: false,
								resolve: {
									bpItem: function() {
										return bpObj;
									}
								}
							})
							.result.then(function(selectedItem) {
								$scope.selected = selectedItem;
							}, function() {

							});
						}
					}, function() {

					});
				},
				moreInfo: function(blueprintObj) {
					var modalInstance = $modal.open({
						animation: true,
						templateUrl: 'src/partials/sections/dashboard/workzone/blueprint/popups/blueprintInfo.html',
						controller: 'blueprintInfoCtrl',
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return blueprintObj;
							}
						}
					});
					modalInstance.result.then(function(selectedItem) {
						$scope.selected = selectedItem;
					}, function() {

					});
				},
				removeBlueprint: function(blueprintObj, bpType) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/removeBlueprint.html",
						controller: "removeBlueprintCtrl",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return blueprintObj;
							}
						}
					}).
					result.then(function() {
						var idx = $scope.blueprints[bpType].indexOf(blueprintObj);
						$scope.blueprints[bpType].splice(idx, 1);
					}, function() {

					});
				}
			});
		}
	]);
})(angular);<commit_msg>removed one commented line of code<commit_after>/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Relevance UI Team,
 * Aug 2015
 */

(function(angular) {
	"use strict";
	angular.module('workzone.blueprint', ['ui.bootstrap', 'apis.workzone', 'ngMessages'])
		.factory('formatData', [function() {
			return {
				getFormattedCollection: function(obj) {
					var list = {
						"software_stack": [],
						"docker": [],
						"os_image": [],
						"cloudFormation": [],
						"azureARM": []
					},
					temp;
					for (var i = 0; i < obj.length; i++) {
						temp = obj[i];
						temp.iconpath = this.getIconPath(temp);
						temp.cardVersions = this.getVersionList(temp);
						temp.selectedVersionBpId = temp.cardVersions[0].id;
						switch (temp.templateType) {
							case "chef":
								list.software_stack.push(temp);
								break;
							case "ami":
								list.os_image.push(temp);
								break;
							case "cft":
								list.cloudFormation.push(temp);
								break;
							case "docker":
								list.docker.push(temp);
								break;
							case "arm":
								list.azureARM.push(temp);
								break;
						}
					}
					return list;
				},
				getVersionList : function(bpItem) {
					var allVersionsList = [];
					var currentVersion = {
						id : bpItem._id,
						name : bpItem.name,
						version : 1
					};
					allVersionsList[0] = currentVersion;
					var olderVersions = [];
					if(bpItem.versions && bpItem.versions.length) {
						olderVersions = bpItem.versions;
						allVersionsList = allVersionsList.concat(olderVersions);
					}
					return allVersionsList.reverse();
				},
				getIconPath : function(bpItem) {
					return bpItem.iconpath || "images/templateicons/imgo.jpg";
				}
			};
		}])
		.controller('blueprintCtrl', ['$scope', '$modal', 'formatData', 'workzoneServices', '$rootScope', 'workzoneUIUtils', function($scope, $modal, formatData, workzoneServices, $rootScope, workzoneUIUtils) {
			/*Open only One Accordian-Group at a time*/
			$scope.oneAtATime = true;
			/*Initialising First Accordian-group open on load*/
			$scope.isFirstOpen = true;

			var envParams ;
			$rootScope.$on('WZ_ENV_CHANGE_START', function(event, requestParams, data) {
				$scope.isBlueprintPageLoading = true;
				$scope.envParams=requestParams;
				$scope.blueprintListCards();
			});

			angular.extend($scope, {
				blueprintListCards: function() {
					$scope.isBlueprintPageLoading = true;
					$scope.blueprints = [];
					// service to get the list of blueprints
					workzoneServices.getBlueprints($scope.envParams).then(function(result) {
						var blueprint = result.data;
						$scope.blueprints = formatData.getFormattedCollection(blueprint);
						$scope.isBlueprintPageLoading = false;
		                workzoneUIUtils.makeTabScrollable('blueprintPage');
					},function(error) {
						$scope.isBlueprintPageLoading = false;
						console.log(error);
						$scope.errorMessage = "No Records found";
					});
				},
				//method used to change the bp Name when the version is changed.
				changeCardVersion: function(blueprintObj,bpType){
					var idx = $scope.blueprints[bpType].indexOf(blueprintObj);
					var cardVersions = $scope.blueprints[bpType][idx].cardVersions;
					angular.forEach(cardVersions,function(val){
						if(val.id === $scope.blueprints[bpType][idx].selectedVersionBpId){
							if(bpType === 'software_stack'){
								cardVersions.name = val.name;
							}
							if(bpType === 'os_image'){
								cardVersions.name = val.name;
							}
							if(bpType === 'docker'){
								cardVersions.name = val.name;
							}
							if(bpType === 'azureARM'){
								cardVersions.name = val.name;
							}
							if(bpType === 'cloudFormation'){
								cardVersions.name = val.name;
							}
						}
					})
				},
				launchInstance: function(blueprintObj) {
				    $modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/blueprintLaunchParams.html",
						controller: "blueprintLaunchParamsCtrl",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return blueprintObj;
							}
						}
					})
					.result.then(function(bpObj) {
						if (bpObj.bp.blueprintType === "docker") {
							$modal.open({
								animate: true,
								templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/dockerLaunchParams.html",
								controller: "dockerLaunchParamsCtrl",
								backdrop: 'static',
								keyboard: false,
								size: 'lg',
								resolve: {
									items: function() {
										return bpObj.bp;
									}
								}
							}).result.then(function() {
								console.log('The modal close is not getting invoked currently. Goes to cancel handler');
							}, function() {
								console.log('Cancel Handler getting invoked');
							});
						}else{
						$modal.open({
								animate: true,
								templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/blueprintLaunch.html",
								controller: "blueprintLaunchCtrl",
								backdrop: 'static',
								keyboard: false,
								resolve: {
									bpItem: function() {
										return bpObj;
									}
								}
							})
							.result.then(function(selectedItem) {
								$scope.selected = selectedItem;
							}, function() {

							});
						}
					}, function() {

					});
				},
				moreInfo: function(blueprintObj) {
					var modalInstance = $modal.open({
						animation: true,
						templateUrl: 'src/partials/sections/dashboard/workzone/blueprint/popups/blueprintInfo.html',
						controller: 'blueprintInfoCtrl',
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return blueprintObj;
							}
						}
					});
					modalInstance.result.then(function(selectedItem) {
						$scope.selected = selectedItem;
					}, function() {

					});
				},
				removeBlueprint: function(blueprintObj, bpType) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/blueprint/popups/removeBlueprint.html",
						controller: "removeBlueprintCtrl",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return blueprintObj;
							}
						}
					}).
					result.then(function() {
						var idx = $scope.blueprints[bpType].indexOf(blueprintObj);
						$scope.blueprints[bpType].splice(idx, 1);
					}, function() {

					});
				}
			});
		}
	]);
})(angular);<|endoftext|>


<commit_before>const Discord = require('discord.js');

module.exports = (client, message, args) => {

  message.channel.send({embed:{
      color: 3447003,
      author: {  name: message.guild.name, icon_url: message.guild.iconURL },
      title: `Informações do servidor`,  /*url: "http://google.com",*/ description: `${message.guild.name}`,
      fields:
      [
        { name: `Nome: `, value: `${message.guild.name}` /*value: "[link](http://google.com)."*/ , "inline": true },
        { name: `Número do ID: `, value: `${message.guild.id}`, "inline": true },
        { name: `Localização: `, value: `${message.guild.region}`, "inline": true },
        { name: `Data de criação: `, value: `${message.guild.createdAt}` },
        { name: `Dono: `, value: `${message.guild.owner.user.tag}`, "inline": true },
        { name: `Número do ID do dono: `, value: `${message.guild.owner.user.id}`, "inline": true },
        { name: `Total de canais: `, value: `${message.guild.channels.filter(chan => chan.type === 'voice').size} voz / ${message.guild.channels.filter(chan => chan.type === 'text').size} texto`, "inline": true },
        { name: `Total de BoTs: `, value: `${message.guild.members.filter(member => member.user.bot).size}`, "inline": true },
        { name: `Usuários cadastrados: `, value: `${message.guild.memberCount}`, "inline": true },
        { name: `Cargos existentes: `, value: message.guild.roles.map(role => role.name).join(', ') }
        //não use as roles fora das embeds(normal text) (vai chamar a atenção de todo mundo online)
      ],
      timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
    }
  }).then(msg => {
    msg.delete(60000)
  });
  message.delete(60000);
};<commit_msg><commit_after>const Discord = require('discord.js');

module.exports = (client, message, args) => {

  message.channel.send({embed:{
      color: 3447003,
      author: {  name: message.guild.name, icon_url: message.guild.iconURL },
      title: `Informações do servidor`,  /*url: "http://google.com",*/ description: `${message.guild.name}`,
      fields:
      [
        { name: `Nome: `, value: `${message.guild.name}` /*value: "[link](http://google.com)."*/ , "inline": true },
        { name: `Número do ID: `, value: `${message.guild.id}`, "inline": true },
        { name: `Localização: `, value: `${message.guild.region}`, "inline": true },
        { name: `Data de criação: `, value: `${message.guild.createdAt}` },
        { name: `Dono: `, value: `${message.guild.owner.user.tag}`, "inline": true },
        { name: `Número do ID do dono: `, value: `${message.guild.owner.user.id}`, "inline": true },
        { name: `Cargos existentes: `, value: message.guild.roles.map(role => role.name).join(', ') },
        { name: `Total de canais: `, value: `${message.guild.channels.filter(chan => chan.type === 'voice').size} voz / ${message.guild.channels.filter(chan => chan.type === 'text').size} texto`, "inline": true },
        { name: `Total de BoTs: `, value: `${message.guild.members.filter(member => member.user.bot).size}`, "inline": true },
        { name: `Usuários cadastrados: `, value: `${message.guild.memberCount}`, "inline": true }

        //não use as roles fora das embeds(normal text) (vai chamar a atenção de todo mundo online)
      ],
      timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
    }
  }).then(msg => {
    msg.delete(60000)
  });
  message.delete(60000);
};<|endoftext|>


<commit_before>var
	kind = require('enyo/kind');

var
	Button = require('moonstone/Button'),
	ContextualPopup = require('moonstone/ContextualPopup'),
	ContextualPopupDecorator = require('moonstone/ContextualPopupDecorator'),
	Divider = require('moonstone/Divider'),
	Input = require('moonstone/Input'),
	InputDecorator = require('moonstone/InputDecorator'),
	Item = require('moonstone/Item'),
	RadioItem = require('moonstone/RadioItem'),
	RadioItemGroup = require('moonstone/RadioItemGroup'),
	Scroller = require('moonstone/Scroller'),
	ToggleButton = require('moonstone/ToggleButton');

module.exports = kind({
	name: 'moon.sample.ontextualPopupSample',
	classes: 'moon enyo-unselectable enyo-fit',
	components: [
		{
			kind: ContextualPopupDecorator,
			style: 'position: absolute; left: 0px; top: 0px;',
			components:
			[
				{content: 'Average'},
				{
					kind: ContextualPopup,
					classes: 'moon-2h moon-8v',
					components: [
						{content: 'Item 1'},
						{content: 'Item 2'},
						{content: 'Item 3'}
					]
				}
			]
		},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 0px;', components: [
			{content: 'Small', small:true},
			{kind: ContextualPopup}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 13%;', components: [
			{content: 'Nested Radio', small:true},
				{name: 'nestedRadioPopup', kind: ContextualPopup, components:[
					{name: 'nestedRadioGroup', kind: RadioItemGroup, components: [
						{content: 'Creek', selected: true},
						{content: 'River'},
						{content: 'Ocean'}
					]},
					{components:[
						{content: 'Radio Group Value'},
						{name: 'nestedRadioValue'}
					]},
					{name: 'nestedRadioDismissButton',
					 kind: ToggleButton,
					 style: 'margin-top:5px',
					 small: true,
					 toggleOnLabel: 'select dismiss on',
					 toggleOffLabel: 'select dismiss off'
					}
				]}
			]
		},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; top: 25%;', components: [
			{content: 'Left'},
			{
				kind: ContextualPopup,
				classes: 'moon-3h moon-4v',
				components: [
					{content: 'Item 1'},
					{content: 'Item 2'},
					{content: 'Item 3'}
				]
			}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 25%;', components: [
			{content: 'Right', small:true},
			{kind: ContextualPopup, components: [
				{content: 'Outside scroller', kind: Item},
				{classes: 'moon-8h moon-6v', components: [
					{kind: Scroller, classes: 'enyo-fill', components: [
						{content: 'testing 1', kind: Item},
						{content: 'testing 2', kind: Item},
						{content: 'testing 3', kind: Item},
						{content: 'testing 4', kind: Item},
						{content: 'testing 5', kind: Item},
						{content: 'testing 6', kind: Item},
						{content: 'testing 7', kind: Item},
						{content: 'testing 8', kind: Item},
						{content: 'testing 9', kind: Item},
						{content: 'testing 10', kind: Item},
						{content: 'testing 12', kind: Item},
						{content: 'testing 13', kind: Item},
						{content: 'testing 14', kind: Item},
						{content: 'testing 15', kind: Item},
						{content: 'testing 16', kind: Item},
						{content: 'testing 17', kind: Item},
						{content: 'testing 18', kind: Item},
						{content: 'testing 19', kind: Item}
					]}

				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; top: 45%;', components: [
			{content: 'Wide'},
			{kind: ContextualPopup, classes: 'moon-6h moon-4v', components: [
				{kind: Scroller, classes: 'enyo-fill', components:[
					{content: 'testing 1'},
					{content: 'testing 2'}
				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 45%;', components: [
			{content: 'Long but Small Button with truncation', small:true},
			{kind: ContextualPopup, components: [
				{content: 'Outside scroller', kind: Item},
				{classes: 'moon-16v', components: [
					{kind: Scroller, classes: 'enyo-fill', components: [
						{content: 'testing 1', kind: Item},
						{content: 'testing 2', kind: Item},
						{content: 'testing 3', kind: Item},
						{content: 'testing 4', kind: Item},
						{content: 'testing 5', kind: Item},
						{content: 'testing 6', kind: Item},
						{content: 'testing 7', kind: Item},
						{content: 'testing 8', kind: Item},
						{content: 'testing 9', kind: Item},
						{content: 'testing 10', kind: Item},
						{content: 'testing 12', kind: Item},
						{content: 'testing 13', kind: Item},
						{content: 'testing 14', kind: Item},
						{content: 'testing 15', kind: Item},
						{content: 'testing 16', kind: Item},
						{content: 'testing 17', kind: Item},
						{content: 'testing 18', kind: Item},
						{content: 'testing 19', kind: Item}
					]}

				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; top: 65%;', components: [
			{content: 'Deactivated', disabled:true},
			{kind: ContextualPopup, classes: 'moon-6h moon-4v', components: [
				{kind: Scroller, classes: 'enyo-fill', components:[
					{content: 'testing 1'},
					{content: 'testing 2'}
				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 65%;', components: [
			{content: 'Small Deactivated', small:true, disabled:true},
			{kind: ContextualPopup, classes: 'moon-6h moon-4v', components: [
				{kind: Scroller, classes: 'enyo-fill', components:[
					{content: 'testing 1'},
					{content: 'testing 2'}
				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; bottom: 0px;', components: [
			{content: 'Spotlight Modal'},
			{
				kind: ContextualPopup,
				name: 'buttonPopup',
				classes: 'moon-8h moon-8v',
				modal: true,
				autoDismiss: false,
				spotlightModal: true,
				components: [
					{kind: Scroller, horizontal: 'auto', classes: 'enyo-fill', components: [
						{kind: Button, content: 'Button'},
						{kind: ToggleButton, content: 'SpotlightModal', value: true, ontap: 'buttonToggled'},
						{tag: 'br'},
						{tag: 'br'},
						{kind: InputDecorator, spotlight: true, components: [
							{kind: Input, placeholder: 'USERNAME'}
						]}
					]}
				]
			}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; bottom: 0px;', components: [
			{content: 'Spottable', small:true},
			{
				kind: ContextualPopup,
				classes: 'moon-9h moon-4v',
				components: [
					{kind: Scroller, horizontal: 'auto', classes: 'enyo-fill', components: [
						{kind: Button, content: 'Button 1'},
						{kind: Button, content: 'Button 2'},
						{kind: Button, content: 'Button 3'}
					]}
				]
			}
		]},
		{style: 'position: absolute; left: 30%; top: 25%;', components: [
			{kind: Divider, content: 'Button Position', classes: 'radioItemFont'},
			{kind: InputDecorator, components: [
				{kind: Input, style: 'width: 120px', name: 'leftInput', placeholder: 'left (px or %)', classes: 'radioItemFont'}
			]},
			{kind: InputDecorator, components: [
				{kind: Input, style: 'width: 120px', name: 'topInput', placeholder: 'top (px or %)', classes: 'radioItemFont'}
			]},
			{kind: Button, small: true, content: 'Set Position', ontap: 'setPosition'}
		]},
		{style: 'position: absolute; left: 30%; top: 50%; ', components: [
			{kind: Divider, content: 'Popup Direction', classes: 'radioItemFont'},
			{kind: RadioItemGroup, onActivate: 'groupChanged', components: [
				{content: 'none', classes: 'radioItemFont'},
				{content: 'left', classes: 'radioItemFont'},
				{content: 'right', classes: 'radioItemFont'},
				{content: 'top', classes: 'radioItemFont'},
				{content: 'bottom', classes: 'radioItemFont'}
			]}
		]},
		{kind: ContextualPopupDecorator, name: 'directionButton', style: 'position: absolute; left: 40%; top: 70%;', components: [
			{content: 'Direction'},
			{
				kind: ContextualPopup,
				name: 'directionContext',
				classes: 'moon-4v',
				components: [
					{kind: Scroller, horizontal: 'auto', classes: 'enyo-fill', components: [
						{kind: Button, content: 'Button 1'},
						{kind: Button, content: 'Button 2'}
					]}
				]
			}
		]}
	],
	bindings: [
		{from: '.$.nestedRadioGroup.active.content', to: '.$.nestedRadioValue.content', transform: function(val){
			this.dismissRadioSelection();
			return val;
		}}
	],
	buttonToggled: function(inSender, inEvent) {
		this.$.buttonPopup.setSpotlightModal(inSender.getActive());
		this.$.buttonPopup.setAutoDismiss(!inSender.getActive());
	},
	dismissRadioSelection: function(){
		if(this.$.nestedRadioDismissButton.value) this.$.nestedRadioPopup.hide();
	},
	setPosition: function(){
		this.$.directionButton.applyStyle('left', this.$.leftInput.getValue() === '' ? '40%' : this.$.leftInput.getValue());
		this.$.directionButton.applyStyle('top', this.$.topInput.getValue() === '' ? '70%' : this.$.topInput.getValue());
	},
	groupChanged: function(inSender, inEvent) {
		if(inEvent.originator.getActive() && inEvent.originator.kind === RadioItem) {
			var selected = inEvent.originator.getContent();
			this.$.directionContext.set('direction', selected);
		}
	}
});<commit_msg>PLAT-2454: Button is getting overlapped with Spotlight modal button.<commit_after>var
	kind = require('enyo/kind');

var
	Button = require('moonstone/Button'),
	ContextualPopup = require('moonstone/ContextualPopup'),
	ContextualPopupDecorator = require('moonstone/ContextualPopupDecorator'),
	Divider = require('moonstone/Divider'),
	Input = require('moonstone/Input'),
	InputDecorator = require('moonstone/InputDecorator'),
	Item = require('moonstone/Item'),
	RadioItem = require('moonstone/RadioItem'),
	RadioItemGroup = require('moonstone/RadioItemGroup'),
	Scroller = require('moonstone/Scroller'),
	ToggleButton = require('moonstone/ToggleButton');

module.exports = kind({
	name: 'moon.sample.ontextualPopupSample',
	classes: 'moon enyo-unselectable enyo-fit',
	components: [
		{
			kind: ContextualPopupDecorator,
			style: 'position: absolute; left: 0px; top: 0px;',
			components:
			[
				{content: 'Average'},
				{
					kind: ContextualPopup,
					classes: 'moon-2h moon-8v',
					components: [
						{content: 'Item 1'},
						{content: 'Item 2'},
						{content: 'Item 3'}
					]
				}
			]
		},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 0px;', components: [
			{content: 'Small', small:true},
			{kind: ContextualPopup}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 13%;', components: [
			{content: 'Nested Radio', small:true},
				{name: 'nestedRadioPopup', kind: ContextualPopup, components:[
					{name: 'nestedRadioGroup', kind: RadioItemGroup, components: [
						{content: 'Creek', selected: true},
						{content: 'River'},
						{content: 'Ocean'}
					]},
					{components:[
						{content: 'Radio Group Value'},
						{name: 'nestedRadioValue'}
					]},
					{name: 'nestedRadioDismissButton',
					 kind: ToggleButton,
					 style: 'margin-top:5px',
					 small: true,
					 toggleOnLabel: 'select dismiss on',
					 toggleOffLabel: 'select dismiss off'
					}
				]}
			]
		},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; top: 25%;', components: [
			{content: 'Left'},
			{
				kind: ContextualPopup,
				classes: 'moon-3h moon-4v',
				components: [
					{content: 'Item 1'},
					{content: 'Item 2'},
					{content: 'Item 3'}
				]
			}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 25%;', components: [
			{content: 'Right', small:true},
			{kind: ContextualPopup, components: [
				{content: 'Outside scroller', kind: Item},
				{classes: 'moon-8h moon-6v', components: [
					{kind: Scroller, classes: 'enyo-fill', components: [
						{content: 'testing 1', kind: Item},
						{content: 'testing 2', kind: Item},
						{content: 'testing 3', kind: Item},
						{content: 'testing 4', kind: Item},
						{content: 'testing 5', kind: Item},
						{content: 'testing 6', kind: Item},
						{content: 'testing 7', kind: Item},
						{content: 'testing 8', kind: Item},
						{content: 'testing 9', kind: Item},
						{content: 'testing 10', kind: Item},
						{content: 'testing 12', kind: Item},
						{content: 'testing 13', kind: Item},
						{content: 'testing 14', kind: Item},
						{content: 'testing 15', kind: Item},
						{content: 'testing 16', kind: Item},
						{content: 'testing 17', kind: Item},
						{content: 'testing 18', kind: Item},
						{content: 'testing 19', kind: Item}
					]}

				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; top: 45%;', components: [
			{content: 'Wide'},
			{kind: ContextualPopup, classes: 'moon-6h moon-4v', components: [
				{kind: Scroller, classes: 'enyo-fill', components:[
					{content: 'testing 1'},
					{content: 'testing 2'}
				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 45%;', components: [
			{content: 'Long but Small Button with truncation', small:true},
			{kind: ContextualPopup, components: [
				{content: 'Outside scroller', kind: Item},
				{classes: 'moon-16v', components: [
					{kind: Scroller, classes: 'enyo-fill', components: [
						{content: 'testing 1', kind: Item},
						{content: 'testing 2', kind: Item},
						{content: 'testing 3', kind: Item},
						{content: 'testing 4', kind: Item},
						{content: 'testing 5', kind: Item},
						{content: 'testing 6', kind: Item},
						{content: 'testing 7', kind: Item},
						{content: 'testing 8', kind: Item},
						{content: 'testing 9', kind: Item},
						{content: 'testing 10', kind: Item},
						{content: 'testing 12', kind: Item},
						{content: 'testing 13', kind: Item},
						{content: 'testing 14', kind: Item},
						{content: 'testing 15', kind: Item},
						{content: 'testing 16', kind: Item},
						{content: 'testing 17', kind: Item},
						{content: 'testing 18', kind: Item},
						{content: 'testing 19', kind: Item}
					]}

				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; top: 65%;', components: [
			{content: 'Deactivated', disabled:true},
			{kind: ContextualPopup, classes: 'moon-6h moon-4v', components: [
				{kind: Scroller, classes: 'enyo-fill', components:[
					{content: 'testing 1'},
					{content: 'testing 2'}
				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; top: 65%;', components: [
			{content: 'Small Deactivated', small:true, disabled:true},
			{kind: ContextualPopup, classes: 'moon-6h moon-4v', components: [
				{kind: Scroller, classes: 'enyo-fill', components:[
					{content: 'testing 1'},
					{content: 'testing 2'}
				]}
			]}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; left: 0px; bottom: 0px;', components: [
			{content: 'Spotlight Modal'},
			{
				kind: ContextualPopup,
				name: 'buttonPopup',
				classes: 'moon-10h moon-8v',
				modal: true,
				autoDismiss: false,
				spotlightModal: true,
				components: [
					{kind: Scroller, horizontal: 'auto', classes: 'enyo-fill', components: [
						{kind: Button, content: 'Button'},
						{kind: ToggleButton, content: 'SpotlightModal', value: true, ontap: 'buttonToggled'},
						{tag: 'br'},
						{tag: 'br'},
						{kind: InputDecorator, spotlight: true, components: [
							{kind: Input, placeholder: 'USERNAME'}
						]}
					]}
				]
			}
		]},
		{kind: ContextualPopupDecorator, style: 'position: absolute; right: 0px; bottom: 0px;', components: [
			{content: 'Spottable', small:true},
			{
				kind: ContextualPopup,
				classes: 'moon-10h moon-4v',
				components: [
					{kind: Scroller, horizontal: 'auto', classes: 'enyo-fill', components: [
						{kind: Button, content: 'Button 1'},
						{kind: Button, content: 'Button 2'},
						{kind: Button, content: 'Button 3'}
					]}
				]
			}
		]},
		{style: 'position: absolute; left: 30%; top: 25%;', components: [
			{kind: Divider, content: 'Button Position', classes: 'radioItemFont'},
			{kind: InputDecorator, components: [
				{kind: Input, style: 'width: 120px', name: 'leftInput', placeholder: 'left (px or %)', classes: 'radioItemFont'}
			]},
			{kind: InputDecorator, components: [
				{kind: Input, style: 'width: 120px', name: 'topInput', placeholder: 'top (px or %)', classes: 'radioItemFont'}
			]},
			{kind: Button, small: true, content: 'Set Position', ontap: 'setPosition'}
		]},
		{style: 'position: absolute; left: 30%; top: 50%; ', components: [
			{kind: Divider, content: 'Popup Direction', classes: 'radioItemFont'},
			{kind: RadioItemGroup, onActivate: 'groupChanged', components: [
				{content: 'none', classes: 'radioItemFont'},
				{content: 'left', classes: 'radioItemFont'},
				{content: 'right', classes: 'radioItemFont'},
				{content: 'top', classes: 'radioItemFont'},
				{content: 'bottom', classes: 'radioItemFont'}
			]}
		]},
		{kind: ContextualPopupDecorator, name: 'directionButton', style: 'position: absolute; left: 40%; top: 70%;', components: [
			{content: 'Direction'},
			{
				kind: ContextualPopup,
				name: 'directionContext',
				classes: 'moon-4v',
				components: [
					{kind: Scroller, horizontal: 'auto', classes: 'enyo-fill', components: [
						{kind: Button, content: 'Button 1'},
						{kind: Button, content: 'Button 2'}
					]}
				]
			}
		]}
	],
	bindings: [
		{from: '.$.nestedRadioGroup.active.content', to: '.$.nestedRadioValue.content', transform: function(val){
			this.dismissRadioSelection();
			return val;
		}}
	],
	buttonToggled: function(inSender, inEvent) {
		this.$.buttonPopup.setSpotlightModal(inSender.getActive());
		this.$.buttonPopup.setAutoDismiss(!inSender.getActive());
	},
	dismissRadioSelection: function(){
		if(this.$.nestedRadioDismissButton.value) this.$.nestedRadioPopup.hide();
	},
	setPosition: function(){
		this.$.directionButton.applyStyle('left', this.$.leftInput.getValue() === '' ? '40%' : this.$.leftInput.getValue());
		this.$.directionButton.applyStyle('top', this.$.topInput.getValue() === '' ? '70%' : this.$.topInput.getValue());
	},
	groupChanged: function(inSender, inEvent) {
		if(inEvent.originator.getActive() && inEvent.originator.kind === RadioItem) {
			var selected = inEvent.originator.getContent();
			this.$.directionContext.set('direction', selected);
		}
	}
});<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname  = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function() {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function() {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function() { return firstname; };
      this.getLastName  = function() { return lastname; };
      this.getFullName  = function() { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname  = "Andrews";
    aPerson.fullName  = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function() {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Passes "It should expect object properties to be public and mutable."<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname  = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function() {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function() {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function() { return firstname; };
      this.getLastName  = function() { return lastname; };
      this.getFullName  = function() { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname  = "Andrews";
    aPerson.fullName  = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function() {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe("Andrews , Penny");
  });

});
<commit_msg>AboutMutability.js completed<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe("Andrews, Penny");
  });

});
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var ApplicationModel = mongoose.model('Application', new Schema({
	Name: {
		type: String,
		required: true,
		lowercase: true
	}
}));

var UserModel = mongoose.model('User', new Schema({
	Name: {
		type: String,
		required: true,
		lowercase: true
	},
	Email: {
		type: String,
		required: true,
		lowercase: true
	},
	PasswordHash: {
		type: String,
		select: false,
		required: true,
		lowercase: true
	}
}));

var TrackingDataModel = mongoose.model('TrackingData', new Schema({
	Name: {
		type: String,
		required: true,
		lowercase: true
	}
}));

mongoose.connect('mongodb://localhost/atlas');

exports.User = UserModel;
exports.Application = ApplicationModel;
exports.TrackingData = TrackingDataModel;<commit_msg>No need for temp variables, really.<commit_after>var mongoose = require('mongoose');

var Schema = mongoose.Schema;

exports.Application = mongoose.model('Application', new Schema({
	Name: {
		type: String,
		required: true,
		lowercase: true,
		index: {
			unique: true
		}
	}
}));

exports.User = mongoose.model('User', new Schema({
	Name: {
		type: String,
		required: true,
		lowercase: true,
		index: {
			unique: true
		}
	},
	Email: {
		type: String,
		required: true,
		lowercase: true
	},
	PasswordHash: {
		type: String,
		select: false,
		required: true,
		lowercase: true
	}
}));

exports.TrackingData = mongoose.model('TrackingData', new Schema({
	Name: {
		type: String,
		required: true,
		lowercase: true,
		index: {
			unique: true
		}
	}
}));

mongoose.connect('mongodb://localhost/atlas');<|endoftext|>