<commit_before>
(function () {

    try {

        var openWindow = function (width, height, url) {

            var remove = function () {
                var existing = document.getElementById("pimcore_admin_lightbox");
                if(existing) {
                    existing.parentNode.removeChild(existing);
                }
            }

            remove();

            if(!width) {
                width = 600;
            }
            if(!height) {
                height = 400;
            }

            var lightbox = document.createElement("div");
            lightbox.id = "pimcore_admin_lightbox";
            lightbox.style.marginTop = "-" + (height/2) + "px";
            lightbox.style.height = height + "px";

            var inner = document.createElement("div");
            inner.className = "inner";
            inner.style.width = width + "px";
            inner.style.height = height + "px";
            inner.innerHTML = '';

            inner.onclick = function () {
                remove();
            };

            lightbox.appendChild(inner);

            document.body.appendChild(lightbox);

            return lightbox;
        };

        var log = function (msg) {
            if (typeof console != "undefined" && typeof console["log"] == "function") {
                console.log(msg);
            }
        };

        window.setTimeout(function () {

            try {

                try {
                    // do no display the button in preview frame inside the admin ui
                    if(parent && parent["pimcore"] && parent["pimcore"]["helpers"]) {
                        return;
                    }
                } catch (e) {}

                var html = '

';

                var container = document.createElement("div");
                container.setAttribute("id", "pimcore_admin_console");
                container.className = "";

                var logo = document.createElement("img");
                logo.src = "/pimcore/static/img/logo-white.png";
                logo.className = "logo";
                container.appendChild(logo);

                logo.onclick = function () {
                    if(container.className.indexOf("open") >= 0) {
                        container.className = "";
                    } else {
                        container.className = "open";
                    }
                };

                var menu = document.createElement("ul");

                if(pimcore["admin"]["documentId"]) {
                    var editButton = document.createElement("li");
                    editButton.className = "button edit";
                    editButton.innerHTML = 'Edit Page';

                    editButton.onclick = function () {
                        if(window.opener && window.opener["pimcore"] && window.opener["pimcore"]["helpers"]) {
                            window.opener.pimcore.helpers.openDocument(pimcore["admin"]["documentId"],"page");
                        } else {
                            window.open("/admin/login/deeplink?document_" + pimcore["admin"]["documentId"] + "_page");
                        }
                    };

                    menu.appendChild(editButton);
                }

                if(pimcore["admin"]["contactEnabled"]) {
                    var featureButton = document.createElement("li");
                    featureButton.className = "button feature";
                    featureButton.innerHTML = 'Feature Request';
                    featureButton.onclick = function () {
                        openWindow(800,500, "/admin/admin-button/feature-request?url=" + encodeURIComponent(window.location.href));
                    };
                    menu.appendChild(featureButton);

                    var bugButton = document.createElement("li");
                    bugButton.className = "button bug";
                    bugButton.innerHTML = 'Bug Report';
                    bugButton.onclick = function () {
                        openWindow(800,500, "/admin/admin-button/bug-report?url=" + encodeURIComponent(window.location.href));
                    };
                    menu.appendChild(bugButton);

                    var promoteButton = document.createElement("li");
                    promoteButton.className = "button promote";
                    promoteButton.innerHTML = 'Promote';
                    promoteButton.onclick = function () {
                        openWindow(800,500, "/admin/admin-button/promote?url=" + encodeURIComponent(window.location.href));
                    };
                    menu.appendChild(promoteButton);
                }

                container.appendChild(menu);

                // add the console
                document.body.appendChild(container);

            } catch (e) {
                log(e);
            }
        }, 1000);
    } catch (e) {
        log(e);
    }
})();

<commit_msg>improved admin button frontend js<commit_after>
(function () {

    try {

        var openWindow = function (width, height, url) {

            var remove = function () {
                var existing = document.getElementById("pimcore_admin_lightbox");
                if(existing) {
                    existing.parentNode.removeChild(existing);
                }
            }

            remove();

            if(!width) {
                width = 600;
            }
            if(!height) {
                height = 400;
            }

            var lightbox = document.createElement("div");
            lightbox.id = "pimcore_admin_lightbox";
            lightbox.style.marginTop = "-" + (height/2) + "px";
            lightbox.style.height = height + "px";

            var inner = document.createElement("div");
            inner.className = "inner";
            inner.style.width = width + "px";
            inner.style.height = height + "px";
            inner.innerHTML = '';

            inner.onclick = function () {
                remove();
            };

            lightbox.appendChild(inner);

            document.body.appendChild(lightbox);

            return lightbox;
        };

        var log = function (msg) {
            if (typeof console != "undefined" && typeof console["log"] == "function") {
                console.log(msg);
            }
        };

        window.setTimeout(function () {

            try {

                try {
                    // do no display the button in preview frame inside the admin ui
                    if(parent && parent["pimcore"] && parent["pimcore"]["helpers"]) {
                        return;
                    }
                } catch (e) {}

                var html = '

';

                var container = document.createElement("div");
                container.setAttribute("id", "pimcore_admin_console");
                container.className = "";

                var logo = document.createElement("img");
                logo.src = "/pimcore/static/img/logo-white.png";
                logo.className = "logo";
                container.appendChild(logo);

                logo.onclick = function () {
                    if(container.className.indexOf("open") >= 0) {
                        container.className = "";
                    } else {
                        container.className = "open";
                    }
                };

                var menu = document.createElement("ul");

                if(pimcore["admin"]["documentId"]) {
                    var editButton = document.createElement("li");
                    editButton.className = "button edit";
                    editButton.innerHTML = 'Edit Page';

                    editButton.onclick = function () {
                        if(window.opener && window.opener["pimcore"] && window.opener["pimcore"]["helpers"]) {
                            window.opener.pimcore.helpers.openDocument(pimcore["admin"]["documentId"],"page");
                            alert("Please switch to the pimcore admin tab. This document is already opened for you!");
                        } else {
                            window.open("/admin/login/deeplink?document_" + pimcore["admin"]["documentId"] + "_page");
                        }
                    };

                    menu.appendChild(editButton);
                }

                if(pimcore["admin"]["contactEnabled"]) {
                    var featureButton = document.createElement("li");
                    featureButton.className = "button feature";
                    featureButton.innerHTML = 'Feature Request';
                    featureButton.onclick = function () {
                        openWindow(800,500, "/admin/admin-button/feature-request?url=" + encodeURIComponent(window.location.href));
                    };
                    menu.appendChild(featureButton);

                    var bugButton = document.createElement("li");
                    bugButton.className = "button bug";
                    bugButton.innerHTML = 'Bug Report';
                    bugButton.onclick = function () {
                        openWindow(800,500, "/admin/admin-button/bug-report?url=" + encodeURIComponent(window.location.href));
                    };
                    menu.appendChild(bugButton);

                    var promoteButton = document.createElement("li");
                    promoteButton.className = "button promote";
                    promoteButton.innerHTML = 'Promote';
                    promoteButton.onclick = function () {
                        openWindow(800,500, "/admin/admin-button/promote?url=" + encodeURIComponent(window.location.href));
                    };
                    menu.appendChild(promoteButton);
                }

                container.appendChild(menu);

                // add the console
                document.body.appendChild(container);

            } catch (e) {
                log(e);
            }
        }, 1000);
    } catch (e) {
        log(e);
    }
})();

<|endoftext|>


<commit_before>let objBrowser = chrome ? chrome : browser;

class EtherAddressLookup {

    constructor()
    {
        console.log("Init EAL");
        this.setDefaultExtensionSettings();
        this.init();
    }

    setDefaultExtensionSettings()
    {
        this.blHighlight = false;
        this.strBlockchainExplorer = "https://etherscan.io/address";

        this.intSettingsCount = 0;
        this.intSettingsTotalCount = 2;
    }

    /**
     * @name init
     * @desc Gets extension settings and applies DOM manipulation
     */
    init()
    {
        let objBrowser = chrome ? chrome : browser;
        //Get the highlight option for the user
        objBrowser.runtime.sendMessage({func: "highlight_option"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                this.blHighlight = (objResponse.resp == 1);
            }
            ++this.intSettingsCount;
        }.bind(this));

        //Get the blockchain explorer for the user
        objBrowser.runtime.sendMessage({func: "blockchain_explorer"}, function(objResponse) {
            this.strBlockchainExplorer = objResponse.resp;
            ++this.intSettingsCount;
        }.bind(this));

        //Update the DOM once all settings have been received...
        setTimeout(function() {
            // Needs to happen after user settings have been collected
            // and in the context of init();
            this.setSearchAndReplaceSettings();
            this.setWarningSettings();
            this.manipulateDOM();
        }.bind(this), 10);
    }

    /**
     * @name Set Search And Replace Settings
     * @desc
     */
    setSearchAndReplaceSettings()
    {
        // Check user is on their favourite block explorer, on fail target blank.
        this.target = (this.isBlockchainExplorerSite() ? '_self' : '_blank');

        // Register RegEx Patterns
        this.regExPatterns = [
            // Ethereum Address Regex
            /(^|\s|:|-)((?:0x)[0-9a-fA-F]{40})(\s|$)/gi,

            // ENS Address Regex
            /([a-z0-9][a-z0-9-\.]+[a-z0-9](?:\.eth))(\s|$)/gi
        ];

        // Register RegEx Matching Patterns
        this.matchPatterns = [
            // Ethereum Match Pattern
            /((?:0x)[0-9a-fA-F]{40})/gi,

            // ENS Match Pattern
            this.regExPatterns[1]
        ];

        // Register Replace Patterns
        this.replacePatterns = [
            // Ethereum Address Replace
            '$1$2$3',

            // ENS Address Replace
            '$1$2'
        ];
    }

    /**
     * @name Set Warning Settings
     * @desc
     */
    setWarningSettings()
    {
        // The block explorers that can handle ENS addresses
        this.ENSCompatiableExplorers = [
            "https://etherscan.io/address",
            "https://etherchain.org/account"
        ];

        // Does the user's favorite explorer support an ENS address
        for(var i=0; i<this.ENSCompatiableExplorers.length; i++){
            if(this.strBlockchainExplorer == this.ENSCompatiableExplorers[i]){
                this.ENSCompatiable = true;
                break;
            }
            this.ENSCompatiable = false;
        }

        // On failure give the user a warning.
        if(!this.ENSCompatiable){
            this.replacePatterns[1] = '$1$2';
        }
    }

    manipulateDOM()
    {
        if(true || this.intSettingsCount === this.intSettingsTotalCount) {
            if(this.blBlacklistDomains) {
                this.blacklistedDomainCheck();
            }
            this.convertAddressToLink();
        }
    }

    /**
     * @name Convert Address To Link
     * @desc Finds Ethereum addresses and converts to a link to a block explorer
     */
    convertAddressToLink()
    {
        var arrWhitelistedTags = ["code", "span", "p", "td", "li", "em", "i", "b", "strong", "small"];

        //Get the whitelisted nodes
        for(var i=0; i<arrWhitelistedTags.length; i++) {
            var objNodes = document.getElementsByTagName(arrWhitelistedTags[i]);
            //Loop through the whitelisted content
            for(var x=0; x<objNodes.length; x++) {
                this.convertAddresses(objNodes[x]);
            }
        }

        this.tidyUpSlots();

        if(this.blHighlight) {
            this.addHighlightStyle();
        }
    }

    /**
     * @name Convert Addresses
     * @desc Takes a Node and checks if any of its children are textNodes. On success replace textNode with slot node
     * @desc slot node contains regex replaced content; see generateReplacementContent()
     * @param {Node} objNode
     */
    convertAddresses(objNode)
    {
        // Some nodes have non-textNode children
        // we need to ensure regex is applied only to text otherwise we will mess the html up
        for(var i=0; i < objNode.childNodes.length; i++){
            // Only check textNodes to prevent applying RegEx against element attributes
            if(objNode.childNodes[i].nodeType == 3){ // nodeType 3 = a text node

                var child = objNode.childNodes[i];
                var childContent = child.textContent;

                // Only start replacing stuff if the we get a RegEx match.
                if(this.isPatternMatched(childContent)) {
                    // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot
                    var replacement = document.createElement('slot');
                    replacement.setAttribute('class', 'ext-etheraddresslookup-temporary');
                    replacement.innerHTML = this.generateReplacementContent(childContent);
                    objNode.replaceChild(replacement, child);
                }
            }
        }
    }

    /**
     * @name Generate Replacement Content
     * @desc Takes string and replaces any regex pattern matches with the associated replace patterns
     * @param {string} content
     * @returns {string}
     */
    generateReplacementContent(content)
    {
        for(var i=0; i < this.regExPatterns.length; i++){
            content = content.replace(this.regExPatterns[i], this.replacePatterns[i]);
        }
        return content;
    }

    /**
     * @name Is Pattern Matched
     * @desc Checks content matches any of the object's matchPatterns
     * @param {string} content
     * @returns {boolean}
     */
    isPatternMatched(content)
    {
        for(var i=0; i < this.matchPatterns.length; i++){
            if(this.matchPatterns[i].exec(content) !== null){
                return true;
            }
        }
        return false;
    }

    /**
     * @name Is Blockchain Explorer Site
     * @desc Check if the current website is the user's selected block explorer
     * @returns {boolean}
     */
    isBlockchainExplorerSite()
    {
        var objBlockchainExplorer = document.createElement("a");
        objBlockchainExplorer.href = this.strBlockchainExplorer;
        return (objBlockchainExplorer.hostname === window.location.hostname);
    }

    /**
     * @name Tidy Slots
     * @desc Searches document for slots adds the slot's child nodes to its parent then removes the slot
     */
    tidyUpSlots()
    {
        var slots = document.querySelectorAll("slot.ext-etheraddresslookup-temporary");
        for(var i=0; i < slots.length; i++){
            while(slots[i].childNodes.length > 0){
                slots[i].parentNode.insertBefore(slots[i].firstChild, slots[i]);
            }
            slots[i].parentNode.removeChild(slots[i]);
        }
    }

    //Removes the highlight style from Ethereum addresses
    removeHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-no_highlight");
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
        }
        return false;
    }

    //Adds the highlight style
    addHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
            objEtherAddresses[i].classList.remove("ext-etheraddresslookup-link-no_highlight");
        }
        return false;
    }
}

window.addEventListener("load", function() {
    let objEtherAddressLookup = new EtherAddressLookup();
});

//Send message from the extension to here.
objBrowser.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        let objEtherAddressLookup = new EtherAddressLookup();
        if(typeof request.func !== "undefined") {
            if(typeof objEtherAddressLookup[request.func] == "function") {
                objEtherAddressLookup[request.func]();
                sendResponse({status: "ok"});
                return true;
            }
        }
        sendResponse({status: "fail"});
    }
);
<commit_msg>Fix for bug 138<commit_after>let objBrowser = chrome ? chrome : browser;

class EtherAddressLookup {

    constructor()
    {
        console.log("Init EAL");
        this.setDefaultExtensionSettings();
        this.init();
    }

    setDefaultExtensionSettings()
    {
        this.blHighlight = false;
        this.strBlockchainExplorer = "https://etherscan.io/address";

        this.intSettingsCount = 0;
        this.intSettingsTotalCount = 2;
    }

    /**
     * @name init
     * @desc Gets extension settings and applies DOM manipulation
     */
    init()
    {
        let objBrowser = chrome ? chrome : browser;
        //Get the highlight option for the user
        objBrowser.runtime.sendMessage({func: "highlight_option"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                this.blHighlight = (objResponse.resp == 1);
            }
            ++this.intSettingsCount;
        }.bind(this));

        //Get the blockchain explorer for the user
        objBrowser.runtime.sendMessage({func: "blockchain_explorer"}, function(objResponse) {
            this.strBlockchainExplorer = objResponse.resp;
            ++this.intSettingsCount;
        }.bind(this));

        //Update the DOM once all settings have been received...
        setTimeout(function() {
            // Needs to happen after user settings have been collected
            // and in the context of init();
            this.setSearchAndReplaceSettings();
            this.setWarningSettings();
            this.manipulateDOM();
        }.bind(this), 10);
    }

    /**
     * @name Set Search And Replace Settings
     * @desc
     */
    setSearchAndReplaceSettings()
    {
        // Check user is on their favourite block explorer, on fail target blank.
        this.target = (this.isBlockchainExplorerSite() ? '_self' : '_blank');

        // Register RegEx Patterns
        this.regExPatterns = [
            // Ethereum Address Regex
            /(^|\s|:|-)((?:0x)[0-9a-fA-F]{40})(\s|$)/gi,

            // ENS Address Regex
            /([a-z0-9][a-z0-9-\.]+[a-z0-9](?:\.eth))(\s|$)/gi
        ];

        // Register RegEx Matching Patterns
        this.matchPatterns = [
            // Ethereum Match Pattern
            /((?:0x)[0-9a-fA-F]{40})/gi,

            // ENS Match Pattern
            this.regExPatterns[1]
        ];

        // Register Replace Patterns
        this.replacePatterns = [
            // Ethereum Address Replace
            '$1$2$3',

            // ENS Address Replace
            '$1$2'
        ];
    }

    /**
     * @name Set Warning Settings
     * @desc
     */
    setWarningSettings()
    {
        // The block explorers that can handle ENS addresses
        this.ENSCompatiableExplorers = [
            "https://etherscan.io/address",
            "https://etherchain.org/account"
        ];

        // Does the user's favorite explorer support an ENS address
        for(var i=0; i<this.ENSCompatiableExplorers.length; i++){
            if(this.strBlockchainExplorer == this.ENSCompatiableExplorers[i]){
                this.ENSCompatiable = true;
                break;
            }
            this.ENSCompatiable = false;
        }

        // On failure give the user a warning.
        if(!this.ENSCompatiable){
            this.replacePatterns[1] = '$1$2';
        }
    }

    manipulateDOM()
    {
        if(true || this.intSettingsCount === this.intSettingsTotalCount) {
            if(this.blBlacklistDomains) {
                this.blacklistedDomainCheck();
            }
            this.convertAddressToLink();
        }
    }

    /**
     * @name Convert Address To Link
     * @desc Finds Ethereum addresses and converts to a link to a block explorer
     */
    convertAddressToLink()
    {
        var arrWhitelistedTags = ["code", "span", "p", "td", "li", "em", "i", "b", "strong", "small"];

        //Get the whitelisted nodes
        for(var i=0; i<arrWhitelistedTags.length; i++) {
            var objNodes = document.getElementsByTagName(arrWhitelistedTags[i]);
            //Loop through the whitelisted content
            for(var x=0; x<objNodes.length; x++) {

                if(this.hasIgnoreAttributes(objNodes[x])){
                    continue;
                }

                this.convertAddresses(objNodes[x]);
            }
        }

        this.tidyUpSlots();

        if(this.blHighlight) {
            this.addHighlightStyle();
        }
    }

    /**
     * @name Convert Addresses
     * @desc Takes a Node and checks if any of its children are textNodes. On success replace textNode with slot node
     * @desc slot node contains regex replaced content; see generateReplacementContent()
     * @param {Node} objNode
     */
    convertAddresses(objNode)
    {
        // Some nodes have non-textNode children
        // we need to ensure regex is applied only to text otherwise we will mess the html up
        for(var i=0; i < objNode.childNodes.length; i++){
            // Only check textNodes to prevent applying RegEx against element attributes
            if(objNode.childNodes[i].nodeType == 3){ // nodeType 3 = a text node

                var child = objNode.childNodes[i];
                var childContent = child.textContent;

                // Only start replacing stuff if the we get a RegEx match.
                if(this.isPatternMatched(childContent)) {
                    // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot
                    var replacement = document.createElement('slot');
                    replacement.setAttribute('class', 'ext-etheraddresslookup-temporary');
                    replacement.innerHTML = this.generateReplacementContent(childContent);
                    objNode.replaceChild(replacement, child);
                }
            }
        }
    }

    /**
     * @name Generate Replacement Content
     * @desc Takes string and replaces any regex pattern matches with the associated replace patterns
     * @param {string} content
     * @returns {string}
     */
    generateReplacementContent(content)
    {
        for(var i=0; i < this.regExPatterns.length; i++){
            content = content.replace(this.regExPatterns[i], this.replacePatterns[i]);
        }
        return content;
    }

    /**
     * @name Has Ignore Attributes
     * @desc Checks if a node contains any attribute that we want to avoid manipulating
     * @param {Element} node
     * @returns {boolean}
     */
    hasIgnoreAttributes(node)
    {
        var ignoreAttributes = {
            "class": ["ng-binding"]
        };

        // Loop through all attributes we want to test for ignoring
        for(var attributeName in ignoreAttributes){
            // Filter out the object's default properties
            if (ignoreAttributes.hasOwnProperty(attributeName)) {

                // Check this node has the attribute we are currently checking for
                if(node.hasAttribute(attributeName)){

                    // This node's value for the attribute we are checking
                    var nodeAttributeValue = node.getAttribute(attributeName);
                    // The values we want to ignore for this attribute
                    var badAttributeValueList = ignoreAttributes[attributeName];

                    // Loop through the attribute values we want to ignore
                    for(var i=0; i < badAttributeValueList.length; i++){
                        // If we find an indexOf, this value is present in the attribute
                        if(nodeAttributeValue.indexOf(badAttributeValueList[i]) !== -1){
                            return true;
                        }
                    }

                }

            }
        }

        return false;
    }

    /**
     * @name Is Pattern Matched
     * @desc Checks content matches any of the object's matchPatterns
     * @param {string} content
     * @returns {boolean}
     */
    isPatternMatched(content)
    {
        for(var i=0; i < this.matchPatterns.length; i++){
            if(this.matchPatterns[i].exec(content) !== null){
                return true;
            }
        }
        return false;
    }

    /**
     * @name Is Blockchain Explorer Site
     * @desc Check if the current website is the user's selected block explorer
     * @returns {boolean}
     */
    isBlockchainExplorerSite()
    {
        var objBlockchainExplorer = document.createElement("a");
        objBlockchainExplorer.href = this.strBlockchainExplorer;
        return (objBlockchainExplorer.hostname === window.location.hostname);
    }

    /**
     * @name Tidy Slots
     * @desc Searches document for slots adds the slot's child nodes to its parent then removes the slot
     */
    tidyUpSlots()
    {
        var slots = document.querySelectorAll("slot.ext-etheraddresslookup-temporary");
        for(var i=0; i < slots.length; i++){
            while(slots[i].childNodes.length > 0){
                slots[i].parentNode.insertBefore(slots[i].firstChild, slots[i]);
            }
            slots[i].parentNode.removeChild(slots[i]);
        }
    }

    //Removes the highlight style from Ethereum addresses
    removeHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-no_highlight");
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
        }
        return false;
    }

    //Adds the highlight style
    addHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
            objEtherAddresses[i].classList.remove("ext-etheraddresslookup-link-no_highlight");
        }
        return false;
    }
}

window.addEventListener("load", function() {
    let objEtherAddressLookup = new EtherAddressLookup();
});

//Send message from the extension to here.
objBrowser.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        let objEtherAddressLookup = new EtherAddressLookup();
        if(typeof request.func !== "undefined") {
            if(typeof objEtherAddressLookup[request.func] == "function") {
                objEtherAddressLookup[request.func]();
                sendResponse({status: "ok"});
                return true;
            }
        }
        sendResponse({status: "fail"});
    }
);
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Eye dropper, with a button for dispensing whatever is in the dropper.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var Circle = require( 'SCENERY/nodes/Circle' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Property = require( 'AXON/Property' );
  var RoundMomentaryButton = require( 'SUN/buttons/RoundMomentaryButton' );
  var Shape = require( 'KITE/Shape' );

  // images
  var foregroundImage = require( 'image!SCENERY_PHET/eye_dropper_foreground.png' );
  var backgroundImage = require( 'image!SCENERY_PHET/eye_dropper_background.png' );

  // constants
  var DEBUG_ORIGIN = false; // if true, put a red dot at the dropper's origin (bottom center)

  // constants specific to the image files
  var TIP_WIDTH = 15;
  var TIP_HEIGHT = 4;
  var GLASS_WIDTH = 46;
  var GLASS_MAX_Y = -18; // relative to bottom center
  var GLASS_MIN_Y = -124; // relative to bottom center
  var BUTTON_CENTER_Y_OFFSET = 32; // y-offset of button's center in dropper image file

  /**
   * @param {Object} [options]
   * @constructor
   */
  function EyeDropperNode( options ) {

    options = _.extend( {
      cursor: 'pointer',
      onProperty: new Property( false ), // is the dropper on? (ie, dispensing)
      enabledProperty: new Property( true ), // is the button enabled?
      emptyProperty: new Property( false ), // does the dropper appear to be empty?
      buttonTouchAreaDilation: 30, // dilation of the button's radius for touchArea
      fluidColor: 'yellow' // {Color|String} color of the fluid in the glass
    }, options );

    var thisNode = this;

    // @public
    this.onProperty = options.onProperty;
    this.enabledProperty = options.enabledProperty;
    this.emptyProperty = options.emptyProperty;

    // @private fluid fills the glass portion of the dropper, shape is specific to the dropper image file
    this.fluidNode = new Path( new Shape()
      .moveTo( -TIP_WIDTH / 2, 0 )
      .lineTo( -TIP_WIDTH / 2, -TIP_HEIGHT )
      .lineTo( -GLASS_WIDTH / 2, GLASS_MAX_Y )
      .lineTo( -GLASS_WIDTH / 2, GLASS_MIN_Y )
      .lineTo( GLASS_WIDTH / 2, GLASS_MIN_Y )
      .lineTo( GLASS_WIDTH / 2, GLASS_MAX_Y )
      .lineTo( TIP_WIDTH / 2, -TIP_HEIGHT )
      .lineTo( TIP_WIDTH / 2, 0 )
      .close(), {
      fill: options.fluidColor
    } );

    // images, origin moved to bottom center
    var foreground = new Image( foregroundImage );
    var background = new Image( backgroundImage );
    foreground.x = -foreground.width / 2;
    foreground.y = -foreground.height;
    background.x = -background.width / 2;
    background.y = -background.height;

    // button, centered in the dropper's bulb
    // @public but only so it can be accessed for together instrumentation
    this.button = new RoundMomentaryButton( this.onProperty, {
      baseColor: 'red',
      radius: 18
    } );
    this.enabledProperty.link( function( enabled ) { thisNode.button.enabled = enabled; } );
    this.button.touchArea = Shape.circle( this.button.width / 2, this.button.height / 2, ( this.button.width / 2 ) + options.buttonTouchAreaDilation );
    this.button.centerX = foreground.centerX;
    this.button.centerY = foreground.top + BUTTON_CENTER_Y_OFFSET;

    // make the background visible only when the dropper is empty
    this.emptyProperty.link( function( empty ) {
      thisNode.fluidNode.visible = !empty;
      background.visible = empty;
    } );

    options.children = [ this.fluidNode, background, foreground, this.button ];

    // add a red dot at the origin
    if ( DEBUG_ORIGIN ) {
      options.children.push( new Circle( { radius: 3, fill: 'red' } ) );
    }

    Node.call( this, options );
  }

  return inherit( Node, EyeDropperNode, {

    // You'll need these if you want to create fluid coming out of the tip, or put a label on the glass.
    TIP_WIDTH: TIP_WIDTH,
    TIP_HEIGHT: TIP_HEIGHT,
    GLASS_WIDTH: GLASS_WIDTH,
    GLASS_MIN_Y: GLASS_MIN_Y,
    GLASS_MAX_Y: GLASS_MAX_Y,

    set on( value ) { this.onProperty = value; },

    get on() { return this.onProperty.value; },

    set enabled( value ) { this.enabledProperty = value; },

    get enabled() { return this.enabledProperty.value; },

    set empty( value ) { this.emptyProperty = value; },

    get empty() { return this.emptyProperty.value; },

    set fluidColor( value ) { this.fluidNode.fill = value; },

    get fluidColor() { return this.fluidNode.fill; }
  } );
} );
<commit_msg>on -> dispensing in EyeDropperNode and clients, phetsims/scenery-phet#149<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Eye dropper, with a button for dispensing whatever is in the dropper.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var Circle = require( 'SCENERY/nodes/Circle' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Property = require( 'AXON/Property' );
  var RoundMomentaryButton = require( 'SUN/buttons/RoundMomentaryButton' );
  var Shape = require( 'KITE/Shape' );

  // images
  var foregroundImage = require( 'image!SCENERY_PHET/eye_dropper_foreground.png' );
  var backgroundImage = require( 'image!SCENERY_PHET/eye_dropper_background.png' );

  // constants
  var DEBUG_ORIGIN = false; // if true, put a red dot at the dropper's origin (bottom center)

  // constants specific to the image files
  var TIP_WIDTH = 15;
  var TIP_HEIGHT = 4;
  var GLASS_WIDTH = 46;
  var GLASS_MAX_Y = -18; // relative to bottom center
  var GLASS_MIN_Y = -124; // relative to bottom center
  var BUTTON_CENTER_Y_OFFSET = 32; // y-offset of button's center in dropper image file

  /**
   * @param {Object} [options]
   * @constructor
   */
  function EyeDropperNode( options ) {

    options = _.extend( {
      cursor: 'pointer',
      dispensingProperty: new Property( false ), // is the dropper dispensing?
      enabledProperty: new Property( true ), // is the button enabled?
      emptyProperty: new Property( false ), // does the dropper appear to be empty?
      buttonTouchAreaDilation: 30, // dilation of the button's radius for touchArea
      fluidColor: 'yellow' // {Color|String} color of the fluid in the glass
    }, options );

    var thisNode = this;

    // @public
    this.dispensingProperty = options.dispensingProperty;
    this.enabledProperty = options.enabledProperty;
    this.emptyProperty = options.emptyProperty;

    // @private fluid fills the glass portion of the dropper, shape is specific to the dropper image file
    this.fluidNode = new Path( new Shape()
      .moveTo( -TIP_WIDTH / 2, 0 )
      .lineTo( -TIP_WIDTH / 2, -TIP_HEIGHT )
      .lineTo( -GLASS_WIDTH / 2, GLASS_MAX_Y )
      .lineTo( -GLASS_WIDTH / 2, GLASS_MIN_Y )
      .lineTo( GLASS_WIDTH / 2, GLASS_MIN_Y )
      .lineTo( GLASS_WIDTH / 2, GLASS_MAX_Y )
      .lineTo( TIP_WIDTH / 2, -TIP_HEIGHT )
      .lineTo( TIP_WIDTH / 2, 0 )
      .close(), {
      fill: options.fluidColor
    } );

    // images, origin moved to bottom center
    var foreground = new Image( foregroundImage );
    var background = new Image( backgroundImage );
    foreground.x = -foreground.width / 2;
    foreground.y = -foreground.height;
    background.x = -background.width / 2;
    background.y = -background.height;

    // button, centered in the dropper's bulb
    // @public but only so it can be accessed for together instrumentation
    this.button = new RoundMomentaryButton( this.dispensingProperty, {
      baseColor: 'red',
      radius: 18
    } );
    this.enabledProperty.link( function( enabled ) { thisNode.button.enabled = enabled; } );
    this.button.touchArea = Shape.circle( this.button.width / 2, this.button.height / 2, ( this.button.width / 2 ) + options.buttonTouchAreaDilation );
    this.button.centerX = foreground.centerX;
    this.button.centerY = foreground.top + BUTTON_CENTER_Y_OFFSET;

    // make the background visible only when the dropper is empty
    this.emptyProperty.link( function( empty ) {
      thisNode.fluidNode.visible = !empty;
      background.visible = empty;
    } );

    options.children = [ this.fluidNode, background, foreground, this.button ];

    // add a red dot at the origin
    if ( DEBUG_ORIGIN ) {
      options.children.push( new Circle( { radius: 3, fill: 'red' } ) );
    }

    Node.call( this, options );
  }

  return inherit( Node, EyeDropperNode, {

    // You'll need these if you want to create fluid coming out of the tip, or put a label on the glass.
    TIP_WIDTH: TIP_WIDTH,
    TIP_HEIGHT: TIP_HEIGHT,
    GLASS_WIDTH: GLASS_WIDTH,
    GLASS_MIN_Y: GLASS_MIN_Y,
    GLASS_MAX_Y: GLASS_MAX_Y,

    set dispensing( value ) { this.dispensingProperty = value; },

    get dispensing() { return this.dispensingProperty.value; },

    set enabled( value ) { this.enabledProperty = value; },

    get enabled() { return this.enabledProperty.value; },

    set empty( value ) { this.emptyProperty = value; },

    get empty() { return this.emptyProperty.value; },

    set fluidColor( value ) { this.fluidNode.fill = value; },

    get fluidColor() { return this.fluidNode.fill; }
  } );
} );
<|endoftext|>


<commit_before>/*global jQuery, $, _, AjaxSolr, EUMSSI, CONF, UTIL */
(function(callback){
	if (typeof define === 'function' && define.amd) {
		define(['core/AbstractManager'], callback);
	} else {
		callback();
	}
}(function(){

	/**
	 * @see http://wiki.apache.org/solr/SolJSON#JSON_specific_parameters
	 * @class Manager
	 * @augments AjaxSolr.AbstractManager
	 */
	AjaxSolr.Manager = AjaxSolr.AbstractManager.extend(/** @lends AjaxSolr.Manager.prototype */
		{
			//Transversal Flag
			// Pagination Request Flag, true if the request is maded from paginator
			flag_PaginationRequest: false, //// When click to filter by some Facet maintains the rest only update the number of times
			//flag_TagFacetRequest : false,
			//// When click to filter by some Country on MapChartWidget
			//flag_MapChartRequest : false,

			// The fields that solr has indexed, must be fetched on start.
			_solrFields : [],

			/**
			 * Custom REQUEST execution for jQuery
			 * @param servlet
			 * @param string
			 * @param handler
			 * @param errorHandler
			 */
			executeRequest: function(servlet, string, handler, errorHandler){
				var self = this, options = {dataType: 'json'};
				this._regenFilter();
				string = string || this.store.string();

				handler = handler || function(data){
					self.handleResponse(data);
				};

				errorHandler = errorHandler || function(jqXHR, textStatus, errorThrown){
					self.handleError(textStatus + ', ' + errorThrown);
				};

				if (this.proxyUrl) {
					options.url = this.proxyUrl;
					options.data = {query: string};
					options.type = 'POST';
				} else {
					//ORIGINAL
					// options.url = this.solrUrl + servlet + '?' + string + '&wt=json&json.wrf=?';
					//MINE - problems with json.wrf param
					options.url = this.solrUrl + servlet + '?' + string + '&wt=json';
					options.headers = {Origin: undefined};
				}

				this._showLoader();
				jQuery.ajax(options).done(handler).fail(errorHandler).always(this._hideLoader.bind(this));
			},

			/**
			 * Custom AddWidget function that initializes the widget if the manager has been already init.
			 * Adds a widget to the manager.
			 * @overrides
			 * @param {AjaxSolr.AbstractWidget} widget
			 */
			addWidget: function (widget) {
				widget.manager = this;
				this.widgets[widget.id] = widget;
				if (this.initialized) {
					this.widgets[widget.id].init();
				}
			},

			/**
			 * Refresh the Filter query
			 * @private
			 */
			_regenFilter: function(){
				var q = EUMSSI.FilterManager.getQueryString();
				var fq = EUMSSI.FilterManager.getFilterQueryString();

				this.store.addByValue("q",q);
				this._lastq = q;

				this.store.removeByValue("fq",this._lastfq);
				if(fq.length > 0){
					this.store.addByValue("fq",fq);
					this._lastfq = fq;
				} else {
					this._lastfq = "";
				}
			},

			/**
			 * Fetch the current indexed fields on Solr
			 * and save it in Manager._solrFields
			 */
			retrieveSolrFieldsNames: function(){
				$.ajax({
					url: this.solrUrl + this.servlet + '?' + "q=*%3A*&rows=0&wt=csv&indent=true",
					success: function(response){
						this._solrFields = response.split(",").sort();
					}.bind(this)
				});
			},

			/**
			 * Obtain the Segments of the given Item
			 * @param parentId
			 */
			getSegmentsByParentId: function(parentId){
				var url = this.segmentsCoreUrl + this.servlet + '?';
				var params = {
					q : this.getLastQuery(),
					fq : "parent_id:"+AjaxSolr.Parameter.escapeValue(parentId),
					sort : "beginOffset asc",
					wt : "json",
					indent : "true",
					rows : "15"
				};
				return $.ajax({
					url: url + $.param(params),
					success: function(response){
						this._solrFields = response.split(",").sort();
					}.bind(this)
				});
			},

			/**
			 * Retrieve Tweets with the current Query
			 * @param {number} [start=0] - The current page start index for the current search.
			 * @param {string} [order=desc] - Sort for the Solr.
			 * @param {number} [gapsize=10] - The paginagion gap size.
			 * @returns {*}
			 */
			getTweets: function(start, order, gapsize){
				var url = this.solrUrl + this.servlet + '?';
				var sort = "meta.extracted.text_polarity.numeric " + (order || "desc");
				var discretePolarity = order === "asc" ? "NEGATIVE" : "POSITIVE";
				var params = {
					q : this.getLastQuery(),
					//For the moment only retrieve the NEGATIVE OR POSITIVE excluding NEUTRAL
					fq : "+source:Twitter +meta.extracted.text_polarity.discrete:\"" + discretePolarity +"\"",
					sort : sort,
					wt : "json",
					indent : "true",
					rows: (gapsize || 10),		// pageSize
					start: (start || 0)			// paginationGap start
				};
				return $.ajax({ url: url + $.param(params) });
			},

			_showLoader: function(){
				$(".result-panel-content").addClass("ui-loading-modal");
			},

			_hideLoader: function(){
				$(".result-panel-content").removeClass("ui-loading-modal");
			},

			/* Filter Interface  */
			addFilter: function(filterName, query, widgetId, filterText){
				EUMSSI.FilterManager.addFilter(filterName, query, widgetId, filterText);
			},

			removeFilterByName: function(filterName, widgetId){
				EUMSSI.FilterManager.removeFilterByName(filterName, widgetId);
			},

			removeFilterByWidget: function(widgetId){
				EUMSSI.FilterManager.removeFilterByWidget(widgetId);
			},

			getLastFilterQuery: function(){
				return this._lastfq || "";
			},

			getLastQuery: function(){
				return this._lastq || "*:*";
			}

		});

}));
<commit_msg>apply date filter in tweet polarity widget<commit_after>/*global jQuery, $, _, AjaxSolr, EUMSSI, CONF, UTIL */
(function(callback){
	if (typeof define === 'function' && define.amd) {
		define(['core/AbstractManager'], callback);
	} else {
		callback();
	}
}(function(){

	/**
	 * @see http://wiki.apache.org/solr/SolJSON#JSON_specific_parameters
	 * @class Manager
	 * @augments AjaxSolr.AbstractManager
	 */
	AjaxSolr.Manager = AjaxSolr.AbstractManager.extend(/** @lends AjaxSolr.Manager.prototype */
		{
			//Transversal Flag
			// Pagination Request Flag, true if the request is maded from paginator
			flag_PaginationRequest: false, //// When click to filter by some Facet maintains the rest only update the number of times
			//flag_TagFacetRequest : false,
			//// When click to filter by some Country on MapChartWidget
			//flag_MapChartRequest : false,

			// The fields that solr has indexed, must be fetched on start.
			_solrFields : [],

			/**
			 * Custom REQUEST execution for jQuery
			 * @param servlet
			 * @param string
			 * @param handler
			 * @param errorHandler
			 */
			executeRequest: function(servlet, string, handler, errorHandler){
				var self = this, options = {dataType: 'json'};
				this._regenFilter();
				string = string || this.store.string();

				handler = handler || function(data){
					self.handleResponse(data);
				};

				errorHandler = errorHandler || function(jqXHR, textStatus, errorThrown){
					self.handleError(textStatus + ', ' + errorThrown);
				};

				if (this.proxyUrl) {
					options.url = this.proxyUrl;
					options.data = {query: string};
					options.type = 'POST';
				} else {
					//ORIGINAL
					// options.url = this.solrUrl + servlet + '?' + string + '&wt=json&json.wrf=?';
					//MINE - problems with json.wrf param
					options.url = this.solrUrl + servlet + '?' + string + '&wt=json';
					options.headers = {Origin: undefined};
				}

				this._showLoader();
				jQuery.ajax(options).done(handler).fail(errorHandler).always(this._hideLoader.bind(this));
			},

			/**
			 * Custom AddWidget function that initializes the widget if the manager has been already init.
			 * Adds a widget to the manager.
			 * @overrides
			 * @param {AjaxSolr.AbstractWidget} widget
			 */
			addWidget: function (widget) {
				widget.manager = this;
				this.widgets[widget.id] = widget;
				if (this.initialized) {
					this.widgets[widget.id].init();
				}
			},

			/**
			 * Refresh the Filter query
			 * @private
			 */
			_regenFilter: function(){
				var q = EUMSSI.FilterManager.getQueryString();
				var fq = EUMSSI.FilterManager.getFilterQueryString();

				this.store.addByValue("q",q);
				this._lastq = q;

				this.store.removeByValue("fq",this._lastfq);
				if(fq.length > 0){
					this.store.addByValue("fq",fq);
					this._lastfq = fq;
				} else {
					this._lastfq = "";
				}
			},

			/**
			 * Fetch the current indexed fields on Solr
			 * and save it in Manager._solrFields
			 */
			retrieveSolrFieldsNames: function(){
				$.ajax({
					url: this.solrUrl + this.servlet + '?' + "q=*%3A*&rows=0&wt=csv&indent=true",
					success: function(response){
						this._solrFields = response.split(",").sort();
					}.bind(this)
				});
			},

			/**
			 * Obtain the Segments of the given Item
			 * @param parentId
			 */
			getSegmentsByParentId: function(parentId){
				var url = this.segmentsCoreUrl + this.servlet + '?';
				var params = {
					q : this.getLastQuery(),
					fq : "parent_id:"+AjaxSolr.Parameter.escapeValue(parentId),
					sort : "beginOffset asc",
					wt : "json",
					indent : "true",
					rows : "15"
				};
				return $.ajax({
					url: url + $.param(params),
					success: function(response){
						this._solrFields = response.split(",").sort();
					}.bind(this)
				});
			},

			/**
			 * Retrieve Tweets with the current Query
			 * @param {number} [start=0] - The current page start index for the current search.
			 * @param {string} [order=desc] - Sort for the Solr.
			 * @param {number} [gapsize=10] - The paginagion gap size.
			 * @returns {*}
			 */
			getTweets: function(start, order, gapsize){
				var url = this.solrUrl + this.servlet + '?';
				var sort = "meta.extracted.text_polarity.numeric " + (order || "desc");
				var discretePolarity = order === "asc" ? "NEGATIVE" : "POSITIVE";
				console.log('Manager.getTweets\t' + EUMSSI.FilterManager.getFilters('meta.source.datePublished'));
				var filters = ""
				EUMSSI.FilterManager.getFilters("meta.source.datePublished").forEach(function(f) {
					filters += '+(' + f['query'] + ') ';
				})
				var params = {
					q : this.getLastQuery(),
					//For the moment only retrieve the NEGATIVE OR POSITIVE excluding NEUTRAL
					fq : filters + "+source:Twitter +meta.extracted.text_polarity.discrete:\"" + discretePolarity +"\"",
					sort : sort,
					wt : "json",
					indent : "true",
					rows: (gapsize || 10),		// pageSize
					start: (start || 0)			// paginationGap start
				};
				return $.ajax({ url: url + $.param(params) });
			},

			_showLoader: function(){
				$(".result-panel-content").addClass("ui-loading-modal");
			},

			_hideLoader: function(){
				$(".result-panel-content").removeClass("ui-loading-modal");
			},

			/* Filter Interface  */
			addFilter: function(filterName, query, widgetId, filterText){
				EUMSSI.FilterManager.addFilter(filterName, query, widgetId, filterText);
			},

			removeFilterByName: function(filterName, widgetId){
				EUMSSI.FilterManager.removeFilterByName(filterName, widgetId);
			},

			removeFilterByWidget: function(widgetId){
				EUMSSI.FilterManager.removeFilterByWidget(widgetId);
			},

			getLastFilterQuery: function(){
				return this._lastfq || "";
			},

			getLastQuery: function(){
				return this._lastq || "*:*";
			}

		});

}));
<|endoftext|>


<commit_before>// Copyright 2016-2018, University of Colorado Boulder

/**
 * Property whose value must be a number.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var axon = require( 'AXON/axon' );
  var inherit = require( 'PHET_CORE/inherit' );
  var NumberPropertyIO = require( 'AXON/NumberPropertyIO' );
  var Property = require( 'AXON/Property' );
  var Range = require( 'DOT/Range' );

  // constants
  var VALID_NUMBER_TYPES = NumberPropertyIO.VALID_NUMBER_TYPES;

  /**
   * @param {number} value - initial value
   * @param {Object} [options]
   * @constructor
   */
  function NumberProperty( value, options ) {

    options = _.extend( {
      numberType: 'FloatingPoint', // {string} see VALID_VALUE_TYPES

      // {Range|null} range
      range: null
    }, options );

    assert && assert( _.includes( VALID_NUMBER_TYPES, options.numberType ), 'invalid numberType: ' + options.numberType );
    options.range && assert && assert( options.range instanceof Range, 'options.range must be of type Range:' + options.range );

    assert && assert( !options.hasOwnProperty( 'phetioType' ), 'phetioType is set by NumberProperty' );
    options.phetioType = NumberPropertyIO;

    // @public (read-only) - used by PhET-iO in NumberPropertyIO as metadata passed to the wrapper.
    this.numberType = options.numberType;
    this.range = options.range;

    assert && assert( !options.valueType, 'valueType is set by NumberProperty' );
    options.valueType = 'number';

    // @private {function|null} value validation that is specific to NumberProperty, null if assertions are disabled
    this.assertNumberPropertyValidateValue = assert && function( value ) {
      if ( options.numberType === 'Integer' ) {
        assert( value % 1 === 0, 'numberType was Integer but value was ' + value );
      }
      options.range && assert( value >= options.range.min && value <= options.range.max,
        'value is out of range, value=' + value + ', range=[' + options.range.min + ',' + options.range.max + ']' );
    };

    // verify that validValues meet other NumberProperty-specific validation criteria
    if ( options.validValues && this.assertNumberPropertyValidateValue ) {
      options.validValues.forEach( this.assertNumberPropertyValidateValue );
    }

    // validate initial value
    this.assertNumberPropertyValidateValue && this.assertNumberPropertyValidateValue( value );

    Property.call( this, value, options );
  }

  axon.register( 'NumberProperty', NumberProperty );

  return inherit( Property, NumberProperty, {

    /**
     * Performs value validation that is specific to NumberProperty.
     * Then sets the value and notifies listeners.
     * @param {*} value
     * @public
     * @override
     */
    set: function( value ) {
      this.assertNumberPropertyValidateValue && this.assertNumberPropertyValidateValue( value );
      Property.prototype.set.call( this, value );
    }
  } );
} );<commit_msg>Check assert && first so it can be stripped out<commit_after>// Copyright 2016-2018, University of Colorado Boulder

/**
 * Property whose value must be a number.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var axon = require( 'AXON/axon' );
  var inherit = require( 'PHET_CORE/inherit' );
  var NumberPropertyIO = require( 'AXON/NumberPropertyIO' );
  var Property = require( 'AXON/Property' );
  var Range = require( 'DOT/Range' );

  // constants
  var VALID_NUMBER_TYPES = NumberPropertyIO.VALID_NUMBER_TYPES;

  /**
   * @param {number} value - initial value
   * @param {Object} [options]
   * @constructor
   */
  function NumberProperty( value, options ) {

    options = _.extend( {
      numberType: 'FloatingPoint', // {string} see VALID_VALUE_TYPES

      // {Range|null} range
      range: null
    }, options );

    assert && assert( _.includes( VALID_NUMBER_TYPES, options.numberType ), 'invalid numberType: ' + options.numberType );
    assert && options.range && assert( options.range instanceof Range, 'options.range must be of type Range:' + options.range );

    assert && assert( !options.hasOwnProperty( 'phetioType' ), 'phetioType is set by NumberProperty' );
    options.phetioType = NumberPropertyIO;

    // @public (read-only) - used by PhET-iO in NumberPropertyIO as metadata passed to the wrapper.
    this.numberType = options.numberType;
    this.range = options.range;

    assert && assert( !options.valueType, 'valueType is set by NumberProperty' );
    options.valueType = 'number';

    // @private {function|null} value validation that is specific to NumberProperty, null if assertions are disabled
    this.assertNumberPropertyValidateValue = assert && function( value ) {
      if ( options.numberType === 'Integer' ) {
        assert( value % 1 === 0, 'numberType was Integer but value was ' + value );
      }
      options.range && assert( value >= options.range.min && value <= options.range.max,
        'value is out of range, value=' + value + ', range=[' + options.range.min + ',' + options.range.max + ']' );
    };

    // verify that validValues meet other NumberProperty-specific validation criteria
    if ( options.validValues && this.assertNumberPropertyValidateValue ) {
      options.validValues.forEach( this.assertNumberPropertyValidateValue );
    }

    // validate initial value
    this.assertNumberPropertyValidateValue && this.assertNumberPropertyValidateValue( value );

    Property.call( this, value, options );
  }

  axon.register( 'NumberProperty', NumberProperty );

  return inherit( Property, NumberProperty, {

    /**
     * Performs value validation that is specific to NumberProperty.
     * Then sets the value and notifies listeners.
     * @param {*} value
     * @public
     * @override
     */
    set: function( value ) {
      this.assertNumberPropertyValidateValue && this.assertNumberPropertyValidateValue( value );
      Property.prototype.set.call( this, value );
    }
  } );
} );<|endoftext|>


<commit_before>// RkqqvYKque
"use strict";
var TweetStructure=function(options){
    var maxNumUser = 150;
    //this.Layout = options.layout; //Check
    var scene = options.scene;
    var graph = new Graph(options);
    var layoutOptions={};
    var lastTweetTime=new Date(Date.now() - 24*3600*1000); //seed date to 24 hours back
    var numNodes = 0;

    // var tweetsInContext=[];
    // tweetsInContext = tweetsInContext;

    graph.layout = new Layout.ForceDirected(graph, layoutOptions);
    //graph.layout.init(); //TODO: CALL WHEN EVERYTHING IS READY

    // options = {scene:drawing.scene};
    // var graph = new Graph(options);

    var makeConnections = function(origin,dest){
        graph.addEdge(origin,dest);
    };

    var drawGraph=function(tweet){
        //console.log("batch processing usernames");
        var user = tweet.user;
        var description = tweet.description;
        var retweet = tweet.retweet;

        var node = createUserNode(user);
        var panel = createTweetPanel(description);

        var edge = graph.addEdge(node, panel);
        edge.draw();

        graph.layout.init({iterations: 100000});
        //for(var i = 0; i < 2; i++){
        //    var node = createUserNode(usernames[i]);  //Small number of nodes for debugging animation.
        //}

    };

    var createUserNode = function(username){
        var location = lookupStartPosition(username);
        var userNode = new TwitterNode(username,null,null,location,0);
        userNode.id = numNodes; //NOT SURE
        graph.addNode(userNode);
       // userNode.mesh.position.copy(location); //CHECK
       // userNode.mesh._dirtyPosition = true;
        //userNode.mesh.geometry =  new THREE.SphereGeometry(6, 32, 32);

        //userNode.id = numNodes; //NOT SURE
        numNodes++; //NOT SURE.

        userNode.draw(location);

        return userNode;//Testing

    };

    var createTweetPanel = function(tweet){
        var location = lookupStartPosition(tweet);
        var tweetPanel = new TweetPanel(tweet,location,0);
        tweetPanel.id = numNodes;
        graph.addNode(tweetPanel);
        //tweetPanel.mesh.position.copy(location); //mesh is undefined...
        //tweetPanel.mesh._dirtyPosition = true;
        numNodes++;
        tweetPanel.draw(location);
        return tweetPanel; //Testing
    };

    var processTweets=function(tweets){
        //var numTweets = tweets.length;
        //lastTweetTime.setTime(new Date(tweets[numTweets-1].created_at).getTime());
        //doProcessTweets(tweets);
        console.log("Creating tweet panels!");
        tweets.forEach(function(tweet){
            createTweetPanel(tweet);
        })
    };

    //Modified by Colin Clayton
    var lookupStartPosition=function(twitterHandle){
        //Todo: Hook to db of tracked users and their model positions
        var position = new THREE.Vector3((Math.random()-0.5)*50,
            Math.random()*0.5 * 200,
            (Math.random()-0.5)*50);
        return position;
    };

    //var processOneTweet=function(tweet, nodeOrigin){
    //    //var node = createUserNode(tweet, nodeOrigin);  //TODO: THIS NEEDS A LOT OF WORK!
    //    var node = new TwitterNode(tweet,null,null,nodeOrigin,0);
    //    graph.addNode(node);
    //    node.draw();
    //
    //    //var date = new Date(tweet.raw.created_at);
    //    //node.data.date = date;
    //
    //    //if(isRetweet(tweet.raw)){ //it's a retweet, we don't add text here, but add to orig node
    //      //  var orgNode = createUserNode(tweet.raw.retweeted_status.user, nodeOrigin);
    //       // orgNode.data.date = new Date();
    //       // orgNode.data.date.setTime(date.getTime());
    //       // addTweetToUser(orgNode, tweet.raw.retweeted_status);
    //        //var edge = graph.addEdge(orgNode, node);
    //        //edge.draw();
    //    //}else{
    //   //     addTweetToUser(node, tweet);
    //    //}
    //   // renderTweet(tweet, node);
    //
    //    if(graph.nodes.length > maxNumUser)
    //        removeOldestNode();
    //
    //    if(graph.nodes.length > maxNumUser)
    //        removeOldestNode();
    //};

    var render=function(){

        // Generate layout if not finished
        if(!graph.layout.finished) {
            // info_text.calc = "Calculating layout...";
            //graph.layout.generate(new THREE.Vector3(40,10,-60));
            graph.layout.generate();
            //graph.layout.repulsion_multiplier = 1;
            //graph.layout.attraction_multiplier = 0
            //graph.layout.speedUpFactor = 100;

        }

        //// Update position of lines (edges)
        //for(var i=0; i<graph.geometries.length; i++) {
        //    graph.geometries[i].verticesNeedUpdate = true;
        //}

        ////TODO: Update position of nodes and panels
        //for(var i = 0; i < graph.nodes.length; i++){ //was nodeSet
            //var nodeToBe =  graph.getNode(i);
            //var nodeToBe = graph.nodes[i];

            //nodeToBe.draw();
            //console.log(nodeToBe);
            // nodeToBe.mesh.geometry.verticesNeedUpdate = true;
            // nodeToBe.mesh.geometry.elementsNeedUpdate = true;
            //console.log(nodeToBe.position);

            // nodeToBe.position = new THREE.Vector3(nodeToBe.position.x+Math.random()*10,nodeToBe.position.y+Math.random()*10,nodeToBe.position.z + Math.random() * 10);

            //nodeToBe.draw();

            // nodeToBe.mesh.position.x += Math.random() * 10;
            // nodeToBe.mesh.position.y += Math.random() * 10; //DOESN'T WORK!
            // nodeToBe.mesh.position.z += Math.random() * 10;
            // nodeToBe.setPosition(new THREE.Vector3( nodeToBe.position.x, nodeToBe.position.y , nodeToBe.position.z += Math.random() + 0.001));
            // nodeToBe.setRotation(new THREE.Vector3(0,0.2,0));

            //console.log(nodeToBe.position);

            // console.log("x = " +nodeToBe.position.x + "y = "+ nodeToBe.position.y + "z = "+ nodeToBe.position.z);

       // }
        graph.edges.forEach(function(e){
            e.line.geometry.verticesNeedUpdate=true;
            e.line.geometry.elementsNeedUpdate = true;
        })

        //
        //
        //// Show labels if set
        //// It creates the labels when this options is set during visualization
        //if(that.show_labels) {
        //    var length = graph.nodes.length;
        //    for(var i=0; i<length; i++) {
        //        var node = graph.nodes[i];
        //        if (node != undefined) {
        //            node.position.x = node.position.x;
        //            node.position.y = node.position.y - 100;
        //            node.position.z = node.position.z;
        //           // node.data.label_object.lookAt(camera.position);
        //        }
        //    }
        //        } else {
        //            if(node.data.title != undefined) {
        //                var label_object = new THREE.Label(node.data.title, node.data.draw_object);
        //            } else {
        //                var label_object = new THREE.Label(node.id, node.data.draw_object);
        //            }
        //            node.data.label_object = label_object;
        //            scene.add( node.data.label_object );
        //        }
        //    }
        //} else {
        //    var length = graph.nodes.length;
        //    for(var i=0; i<length; i++) {
        //        var node = graph.nodes[i];
        //        if(node.data.label_object != undefined) {
        //            scene.remove( node.data.label_object );
        //            node.data.label_object = undefined;
        //        }
        //    }
        //}
        //
        //// render selection
        //if(that.selection) {
        //    object_selection.render(scene, camera);
        //}
        //
        //// update stats
        //if(that.show_stats) {
        //    stats.update();
        //}

    };

    var clear=function(){
        console.log("clearing graph to start new");
        graph.removeAllNodes();
        tweetsInContext.length = 0;
    };

    return {
        // graph:function(){return graph;},
        graph:graph,
        render:render,
        resetLastTweetTime:function(){lastTweetTime=new Date(Date.now() - 24*3600*1000);},

        drawGraph: drawGraph,
        processTweets: processTweets,
        createUserNode: createUserNode,
        createTweetPanel: createTweetPanel

        // tweetsInContext: tweetsInContext
    }
};

<commit_msg>Retweets working<commit_after>// RkqqvYKque
"use strict";
var TweetStructure=function(options){
    var maxNumUser = 150;
    //this.Layout = options.layout; //Check
    var scene = options.scene;
    var graph = new Graph(options);
    var layoutOptions={};
    var lastTweetTime=new Date(Date.now() - 24*3600*1000); //seed date to 24 hours back
    var numNodes = 0;
    var storedTweets = [];

    // var tweetsInContext=[];
    // tweetsInContext = tweetsInContext;

    graph.layout = new Layout.ForceDirected(graph, layoutOptions);
    //graph.layout.init(); //TODO: CALL WHEN EVERYTHING IS READY

    // options = {scene:drawing.scene};
    // var graph = new Graph(options);

    var makeConnections = function(origin,dest){
        graph.addEdge(origin,dest);
    };

    var drawGraph=function(tweet){
        //console.log("batch processing usernames");
        var user = tweet.user;
        var description = tweet.description;
        var retweet = tweet.retweet;

        if (retweet != null) {
            console.log("ITS A RETWEET BROS");
            var retweetNode = createUserNode(user);
            var node_id = getASCIIvalue(description);
            console.log(node_id);
            var retweetText = graph.getNode(node_id);
            if (retweetText != null) {
                var retweetEdge = graph.addEdge(retweetNode, retweetText);

                retweetEdge.draw();
            } else {
                retweetText = createTweetPanel(description);
                var originalNode = createUserNode(retweet);
                var tweetEdge = graph.addEdge(originalNode, retweetText);
                var retweetEdge = graph.addEdge(retweetNode, retweetText);

                tweetEdge.draw();
                retweetEdge.draw();
            }

        } else {

            var node = createUserNode(user);
            var panel = createTweetPanel(description);

            var edge = graph.addEdge(node, panel);
            edge.draw();
            storedTweets.push(description);

            //for(var i = 0; i < 2; i++){
            //    var node = createUserNode(usernames[i]);  //Small number of nodes for debugging animation.
            //}
        }
        graph.layout.init({iterations: 100000});

    };

    var getASCIIvalue = function(tweet) {
        var value = 0;
        for (var i = 0; i < tweet.length; i++) {
            value += tweet.charCodeAt(i);
        }
        return value;
    }

    var createUserNode = function(username){
        var location = lookupStartPosition(username);
        var userNode = new TwitterNode(username,null,null,location,0);
        userNode.id = numNodes; //NOT SURE
        graph.addNode(userNode);
       // userNode.mesh.position.copy(location); //CHECK
       // userNode.mesh._dirtyPosition = true;
        //userNode.mesh.geometry =  new THREE.SphereGeometry(6, 32, 32);

        //userNode.id = numNodes; //NOT SURE
        numNodes++; //NOT SURE.

        userNode.draw(location);

        return userNode;//Testing

    };

    var createTweetPanel = function(tweet){
        var location = lookupStartPosition(tweet);
        var tweetPanel = new TweetPanel(tweet,location,0);
        tweetPanel.id = getASCIIvalue(tweet);
        console.log(tweetPanel.id);
        //tweetPanel.id = numNodes;
        graph.addNode(tweetPanel);
        //tweetPanel.mesh.position.copy(location); //mesh is undefined...
        //tweetPanel.mesh._dirtyPosition = true;
        numNodes++;
        tweetPanel.draw(location);
        return tweetPanel; //Testing
    };

    var processTweets=function(tweets){
        //var numTweets = tweets.length;
        //lastTweetTime.setTime(new Date(tweets[numTweets-1].created_at).getTime());
        //doProcessTweets(tweets);
        console.log("Creating tweet panels!");
        tweets.forEach(function(tweet){
            createTweetPanel(tweet);
        })
    };

    //Modified by Colin Clayton
    var lookupStartPosition=function(twitterHandle){
        //Todo: Hook to db of tracked users and their model positions
        var position = new THREE.Vector3((Math.random()-0.5)*50,
            Math.random()*0.5 * 200,
            (Math.random()-0.5)*50);
        return position;
    };

    //var processOneTweet=function(tweet, nodeOrigin){
    //    //var node = createUserNode(tweet, nodeOrigin);  //TODO: THIS NEEDS A LOT OF WORK!
    //    var node = new TwitterNode(tweet,null,null,nodeOrigin,0);
    //    graph.addNode(node);
    //    node.draw();
    //
    //    //var date = new Date(tweet.raw.created_at);
    //    //node.data.date = date;
    //
    //    //if(isRetweet(tweet.raw)){ //it's a retweet, we don't add text here, but add to orig node
    //      //  var orgNode = createUserNode(tweet.raw.retweeted_status.user, nodeOrigin);
    //       // orgNode.data.date = new Date();
    //       // orgNode.data.date.setTime(date.getTime());
    //       // addTweetToUser(orgNode, tweet.raw.retweeted_status);
    //        //var edge = graph.addEdge(orgNode, node);
    //        //edge.draw();
    //    //}else{
    //   //     addTweetToUser(node, tweet);
    //    //}
    //   // renderTweet(tweet, node);
    //
    //    if(graph.nodes.length > maxNumUser)
    //        removeOldestNode();
    //
    //    if(graph.nodes.length > maxNumUser)
    //        removeOldestNode();
    //};

    var render=function(){

        // Generate layout if not finished
        if(!graph.layout.finished) {
            // info_text.calc = "Calculating layout...";
            //graph.layout.generate(new THREE.Vector3(40,10,-60));
            graph.layout.generate();
            //graph.layout.repulsion_multiplier = 1;
            //graph.layout.attraction_multiplier = 0
            //graph.layout.speedUpFactor = 100;

        }

        //// Update position of lines (edges)
        //for(var i=0; i<graph.geometries.length; i++) {
        //    graph.geometries[i].verticesNeedUpdate = true;
        //}

        ////TODO: Update position of nodes and panels
        //for(var i = 0; i < graph.nodes.length; i++){ //was nodeSet
            //var nodeToBe =  graph.getNode(i);
            //var nodeToBe = graph.nodes[i];

            //nodeToBe.draw();
            //console.log(nodeToBe);
            // nodeToBe.mesh.geometry.verticesNeedUpdate = true;
            // nodeToBe.mesh.geometry.elementsNeedUpdate = true;
            //console.log(nodeToBe.position);

            // nodeToBe.position = new THREE.Vector3(nodeToBe.position.x+Math.random()*10,nodeToBe.position.y+Math.random()*10,nodeToBe.position.z + Math.random() * 10);

            //nodeToBe.draw();

            // nodeToBe.mesh.position.x += Math.random() * 10;
            // nodeToBe.mesh.position.y += Math.random() * 10; //DOESN'T WORK!
            // nodeToBe.mesh.position.z += Math.random() * 10;
            // nodeToBe.setPosition(new THREE.Vector3( nodeToBe.position.x, nodeToBe.position.y , nodeToBe.position.z += Math.random() + 0.001));
            // nodeToBe.setRotation(new THREE.Vector3(0,0.2,0));

            //console.log(nodeToBe.position);

            // console.log("x = " +nodeToBe.position.x + "y = "+ nodeToBe.position.y + "z = "+ nodeToBe.position.z);

       // }
        graph.edges.forEach(function(e){
            e.line.geometry.verticesNeedUpdate=true;
            e.line.geometry.elementsNeedUpdate = true;
        })

        //
        //
        //// Show labels if set
        //// It creates the labels when this options is set during visualization
        //if(that.show_labels) {
        //    var length = graph.nodes.length;
        //    for(var i=0; i<length; i++) {
        //        var node = graph.nodes[i];
        //        if (node != undefined) {
        //            node.position.x = node.position.x;
        //            node.position.y = node.position.y - 100;
        //            node.position.z = node.position.z;
        //           // node.data.label_object.lookAt(camera.position);
        //        }
        //    }
        //        } else {
        //            if(node.data.title != undefined) {
        //                var label_object = new THREE.Label(node.data.title, node.data.draw_object);
        //            } else {
        //                var label_object = new THREE.Label(node.id, node.data.draw_object);
        //            }
        //            node.data.label_object = label_object;
        //            scene.add( node.data.label_object );
        //        }
        //    }
        //} else {
        //    var length = graph.nodes.length;
        //    for(var i=0; i<length; i++) {
        //        var node = graph.nodes[i];
        //        if(node.data.label_object != undefined) {
        //            scene.remove( node.data.label_object );
        //            node.data.label_object = undefined;
        //        }
        //    }
        //}
        //
        //// render selection
        //if(that.selection) {
        //    object_selection.render(scene, camera);
        //}
        //
        //// update stats
        //if(that.show_stats) {
        //    stats.update();
        //}

    };

    var clear=function(){
        console.log("clearing graph to start new");
        graph.removeAllNodes();
        tweetsInContext.length = 0;
    };

    return {
        // graph:function(){return graph;},
        graph:graph,
        render:render,
        resetLastTweetTime:function(){lastTweetTime=new Date(Date.now() - 24*3600*1000);},

        drawGraph: drawGraph,
        processTweets: processTweets,
        createUserNode: createUserNode,
        createTweetPanel: createTweetPanel

        // tweetsInContext: tweetsInContext
    }
};

<|endoftext|>


<commit_before>/*jslint browser: true, white: true, plusplus: true */
/*global angular, console, alert*/

(function () {
  'use strict';

  var app = angular.module('keira2');

  app.controller("GameobjectController", function ($scope, $http, $stateParams, $modal) {

    /* All Gameobject tabs, disabled by default.
    *  Only one tab can be active at a time */
    $scope.gameobjectTabs = {
      search    : false,
      template  : false,
      spawns    : false,
      loot      : false,
      script    : false
    };

    /* Init arrays */
    $scope.current_gameobject               = [];
    $scope.new_gameobject                   = [];
    $scope.current_gameobject_loot_template = [];
    $scope.new_gameobject_loot_template     = [];

    /* Check if a gameobject is selected */
    if ($stateParams.id) {

      /* We have a gameobject selected and default active tab is template */
      $scope.isGameobjectSelected = true;
      $scope.gameobjectTabs.template = true;

      /*  Following lines retrieve all Gameobject datas
       *  current_* mantains the database state
       *  new_*     mantains the editor state
       *  we will use those two objects to generate the SQL queries
       */

      /* Retrieve all gameobject_template datas */
      $http.get( app.api + "gameobject/template/" + $stateParams.id )
        .success(function (data, status, header, config) {
        $scope.current_gameobject_template = data[0];
        $scope.new_gameobject_template = angular.copy($scope.current_gameobject_template);
        $scope.selectionText = "Gameobject " + $scope.current_gameobject_template.entry;
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] gameobject/template/" + $stateParams.id + " $http.get request failed");
      });

      /* Retrieve all gameobject_loot_template datas */
      $http.get( app.api + "loot/template/gameobject/" + $stateParams.id )
        .success(function (data, status, header, config) {
        $scope.current_gameobject_loot_template = data;
        $scope.new_gameobject_loot_template = angular.copy($scope.current_gameobject_loot_template);
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] loot/template/gameobject/" + $stateParams.id + " $http.get request failed");
      });

      /* Retrieve all gameobject datas */
      $http.get( app.api + "/gameobject/spawn/id/" + $stateParams.id )
        .success(function (data, status, header, config) {
        $scope.current_gameobject = data;
        $scope.new_gameobject = angular.copy($scope.current_gameobject);
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] /gameobject/spawn/id/" + $stateParams.id + " $http.get request failed");
      });

    } else {
      /* We have no gameobject selected and default active tab is search */
      $scope.isGameobjectSelected = false;
      $scope.gameobjectTabs.search = true;
      $scope.selectionText = "No GameObject selected. Please use Search to select one.";
    }

    /* [Function] Search */
    $scope.search = function (gameobjectEntry, gameobjectName) {

      if ( gameobjectEntry && !gameobjectName && (gameobjectEntry.length < 2) ) {
        alert("Please insert an ID of at least 2 characters");
        return;
      }
      if ( gameobjectName && !gameobjectEntry && (gameobjectName.length < 3) ) {
        alert("Please insert a Title of at least 3 characters");
        return;
      }

      $http.get( app.api + "/search/gameobject/", {
        params: {
          id: gameobjectEntry,
          name: gameobjectName
        }
      }).success(function (data, status, header, config) {
        $scope.gameobjects = data;
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] GAMEOBJECT SEARCH $http.get request failed");
      });

    };

    /* [Function] Generate SQL Script for Gameobject */
    $scope.generateGameobjectScript = function() {

      if (!$scope.isGameobjectSelected) {
        $scope.gameobjectScript = "# No Gameobject selected";
        return;
      }

      $scope.gameobjectScript = "";

      var whereCondition = "Entry = " + $scope.current_gameobject_template.Entry;

      $scope.gameobjectScript += app.getUpdateQuery("gameobject_template", whereCondition, $scope.current_gameobject_template, $scope.new_gameobject_template);
    };

    /* [Function] disactive all tabs */
    $scope.disactiveAllTabs = function() {
      angular.forEach($scope.gameobjectTabs, function(value, key) {
        value = false;
      });
    };

    /* [Function] open SQL Script tab */
    $scope.openScriptTab = function() {
      $scope.disactiveAllTabs();
      $scope.generateGameobjectScript();
      $scope.gameobjectTabs.script = true;
    };

  });

}());
<commit_msg>Fixed GameObject update query<commit_after>/*jslint browser: true, white: true, plusplus: true */
/*global angular, console, alert*/

(function () {
  'use strict';

  var app = angular.module('keira2');

  app.controller("GameobjectController", function ($scope, $http, $stateParams, $modal) {

    /* All Gameobject tabs, disabled by default.
    *  Only one tab can be active at a time */
    $scope.gameobjectTabs = {
      search    : false,
      template  : false,
      spawns    : false,
      loot      : false,
      script    : false
    };

    /* Init arrays */
    $scope.current_gameobject               = [];
    $scope.new_gameobject                   = [];
    $scope.current_gameobject_loot_template = [];
    $scope.new_gameobject_loot_template     = [];

    /* Check if a gameobject is selected */
    if ($stateParams.id) {

      /* We have a gameobject selected and default active tab is template */
      $scope.isGameobjectSelected = true;
      $scope.gameobjectTabs.template = true;

      /*  Following lines retrieve all Gameobject datas
       *  current_* mantains the database state
       *  new_*     mantains the editor state
       *  we will use those two objects to generate the SQL queries
       */

      /* Retrieve all gameobject_template datas */
      $http.get( app.api + "gameobject/template/" + $stateParams.id )
        .success(function (data, status, header, config) {
        $scope.current_gameobject_template = data[0];
        $scope.new_gameobject_template = angular.copy($scope.current_gameobject_template);
        $scope.selectionText = "Gameobject " + $scope.current_gameobject_template.entry;
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] gameobject/template/" + $stateParams.id + " $http.get request failed");
      });

      /* Retrieve all gameobject_loot_template datas */
      $http.get( app.api + "loot/template/gameobject/" + $stateParams.id )
        .success(function (data, status, header, config) {
        $scope.current_gameobject_loot_template = data;
        $scope.new_gameobject_loot_template = angular.copy($scope.current_gameobject_loot_template);
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] loot/template/gameobject/" + $stateParams.id + " $http.get request failed");
      });

      /* Retrieve all gameobject datas */
      $http.get( app.api + "/gameobject/spawn/id/" + $stateParams.id )
        .success(function (data, status, header, config) {
        $scope.current_gameobject = data;
        $scope.new_gameobject = angular.copy($scope.current_gameobject);
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] /gameobject/spawn/id/" + $stateParams.id + " $http.get request failed");
      });

    } else {
      /* We have no gameobject selected and default active tab is search */
      $scope.isGameobjectSelected = false;
      $scope.gameobjectTabs.search = true;
      $scope.selectionText = "No GameObject selected. Please use Search to select one.";
    }

    /* [Function] Search */
    $scope.search = function (gameobjectEntry, gameobjectName) {

      if ( gameobjectEntry && !gameobjectName && (gameobjectEntry.length < 2) ) {
        alert("Please insert an ID of at least 2 characters");
        return;
      }
      if ( gameobjectName && !gameobjectEntry && (gameobjectName.length < 3) ) {
        alert("Please insert a Title of at least 3 characters");
        return;
      }

      $http.get( app.api + "/search/gameobject/", {
        params: {
          id: gameobjectEntry,
          name: gameobjectName
        }
      }).success(function (data, status, header, config) {
        $scope.gameobjects = data;
      })
        .error(function (data, status, header, config) {
        console.log("[ERROR] GAMEOBJECT SEARCH $http.get request failed");
      });

    };

    /* [Function] Generate SQL Script for Gameobject */
    $scope.generateGameobjectScript = function() {

      if (!$scope.isGameobjectSelected) {
        $scope.gameobjectScript = "# No Gameobject selected";
        return;
      }

      $scope.gameobjectScript = "";

      var whereCondition = "entry = " + $scope.current_gameobject_template.entry;

      $scope.gameobjectScript += app.getUpdateQuery("gameobject_template", whereCondition, $scope.current_gameobject_template, $scope.new_gameobject_template);
    };

    /* [Function] disactive all tabs */
    $scope.disactiveAllTabs = function() {
      angular.forEach($scope.gameobjectTabs, function(value, key) {
        value = false;
      });
    };

    /* [Function] open SQL Script tab */
    $scope.openScriptTab = function() {
      $scope.disactiveAllTabs();
      $scope.generateGameobjectScript();
      $scope.gameobjectTabs.script = true;
    };

  });

}());
<|endoftext|>


<commit_before>"use strict";

/*  ------------------------------------------------------------------------ */

const { unCamelCase } = require ('./functions/string')

const unCamelCasePropertyNames = x => {
                                    for (const k in x) x[unCamelCase (k)] = x[k] // camel_case_method = camelCaseMethod
                                    return x
                                }

/*  ------------------------------------------------------------------------ */

module.exports = unCamelCasePropertyNames ({

    ...require ('./functions/platform'),
    ...require ('./functions/generic'),
    ...require ('./functions/string'),
    ...require ('./functions/safe'),
    ...require ('./functions/number'),
    ...require ('./functions/encode'),
    ...require ('./functions/crypto'),
    ...require ('./functions/time'),
    ...require ('./functions/throttle'),

/*  .............................................   */

    json:   JSON.stringify,
    unjson: JSON.parse,

/*  .............................................   */

    aggregate (bidasks) {

        let result = {}

        for (const [price, volume] of bidasks) {
            if (volume > 0)
                result[price] = (result[price] || 0) + volume
        }

        return Object.keys (result)
                     .map (price => [parseFloat (price),
                                     parseFloat (result[price])])
    }
})

/*  ------------------------------------------------------------------------ */
<commit_msg>forgot to change a require path..<commit_after>"use strict";

/*  ------------------------------------------------------------------------ */

const { unCamelCase } = require ('./functions/string')

const unCamelCasePropertyNames = x => {
                                    for (const k in x) x[unCamelCase (k)] = x[k] // camel_case_method = camelCaseMethod
                                    return x
                                }

/*  ------------------------------------------------------------------------ */

module.exports = unCamelCasePropertyNames ({

    ...require ('./functions/platform'),
    ...require ('./functions/generic'),
    ...require ('./functions/string'),
    ...require ('./functions/type'),
    ...require ('./functions/number'),
    ...require ('./functions/encode'),
    ...require ('./functions/crypto'),
    ...require ('./functions/time'),
    ...require ('./functions/throttle'),

/*  .............................................   */

    json:   JSON.stringify,
    unjson: JSON.parse,

/*  .............................................   */

    aggregate (bidasks) {

        let result = {}

        for (const [price, volume] of bidasks) {
            if (volume > 0)
                result[price] = (result[price] || 0) + volume
        }

        return Object.keys (result)
                     .map (price => [parseFloat (price),
                                     parseFloat (result[price])])
    }
})

/*  ------------------------------------------------------------------------ */
<|endoftext|>


<commit_before>
XMLDocument.prototype.insertIntoHTMLDocument = function() {

	//this.transformToInternalFormat();

	//var nsResolver = this.createNSResolver(this.documentElement);
	var nsResolver = new bxe_nsResolver(this.documentElement);

	var nodes = bxe_getAllEditableAreas();

	for (var i = 0; i < nodes.length; i++) {
		nodes[i].removeAllChildren();
		var xpath = nodes[i].getAttribute("bxe_xpath");
		var xmlresult = document.evaluate(xpath, this.documentElement, nsResolver, 0, null);
		if (document.defaultView.getComputedStyle(nodes[i], null).getPropertyValue("display") == "inline") {
			var bxe_areaHolder = document.createElement("span");
			nodes[i].display = "inline";
		} else {
			var bxe_areaHolder = document.createElement("div");
			nodes[i].display = "block";
		}
		bxe_areaHolder.setAttribute("name","bxe_areaHolder");
		nodes[i].parentNode.insertBefore(bxe_areaHolder,nodes[i]);
		bxe_areaHolder.appendChild(nodes[i]);
		while (xmlnode = xmlresult.iterateNext()) {
			if (xmlnode.nodeType == 1) {
				nodes[i].XMLNode.setNode( xmlnode);
				xmlnode.insertIntoHTMLDocument(nodes[i],true);
			} else {
				nodes[i].XMLNode._xmlnode = xmlnode.parentNode;
				xmlnode.insertIntoHTMLDocument(nodes[i]);
			}
			var menu = new Widget_AreaInfo(nodes[i]);
			bxe_alignAreaNode(menu,nodes[i]);
			nodes[i].AreaInfo = menu;
			menu.editableArea = nodes[i];
		}

	}

	bxe_draw_widgets();
}

XMLDocument.prototype.checkParserError = function()
{
	if(this.documentElement && this.documentElement.nodeName=="parsererror")
	{
		var alerttext = "Parse Error: \n \n";
		alerttext += this.documentElement.firstChild.data +"\n\n";
		alerttext += "Sourcetext:\n\n";
		alerttext += this.documentElement.childNodes[1].firstChild.data;

		return (alerttext);
	}
	return true;
}

XMLDocument.prototype.transformToXPathMode = function(xslfile) {
	var xsldoc = document.implementation.createDocument("", "", null);
	xsldoc.addEventListener("load", onload_xsl, false);
	xsldoc.xmldoc = this;
	xsldoc.load(xslfile);

	function onload_xsl(e) {
		xsldoc = e.currentTarget;
		var xsltransformdoc = document.implementation.createDocument("", "", null);
		xsltransformdoc.addEventListener("load", onload_xsltransform, false);
		xsltransformdoc.xsldoc = xsldoc;
		xsltransformdoc.load(mozile_root_dir + "xsl/transformxsl.xsl");
	}

	function onload_xsltransform (e) {
		var processor = new XSLTProcessor();
		xsltransformdoc = e.currentTarget;
		processor.importStylesheet(xsltransformdoc);
		try {
			var newDocument = processor.transformToDocument(xsltransformdoc.xsldoc);
		}
		catch (e) {
			alert ( e + "\n\n xsltransformdoc.xsldoc is : " + xsltransformdoc.xsldoc);
		}
		var processor = new XSLTProcessor();
		try {
			processor.importStylesheet(newDocument);
		} catch(e) {
			alert("Something went wrong during importing the XSLT document.\n" + bxe_catch_alert_message(e) + "\n" + newDocument.saveXML(newDocument));
		}
		var xmldoc = processor.transformToFragment(xsltransformdoc.xsldoc.xmldoc,document);
		var bxe_area = document.getElementById("bxe_area");
		bxe_area.parentNode.replaceChild(xmldoc,bxe_area);
		xsltransformdoc.xsldoc.xmldoc.insertIntoHTMLDocument();

	}

}

<commit_msg>alert if xsl was not found<commit_after>
XMLDocument.prototype.insertIntoHTMLDocument = function() {

	//this.transformToInternalFormat();

	//var nsResolver = this.createNSResolver(this.documentElement);
	var nsResolver = new bxe_nsResolver(this.documentElement);

	var nodes = bxe_getAllEditableAreas();

	for (var i = 0; i < nodes.length; i++) {
		nodes[i].removeAllChildren();
		var xpath = nodes[i].getAttribute("bxe_xpath");
		var xmlresult = document.evaluate(xpath, this.documentElement, nsResolver, 0, null);
		if (document.defaultView.getComputedStyle(nodes[i], null).getPropertyValue("display") == "inline") {
			var bxe_areaHolder = document.createElement("span");
			nodes[i].display = "inline";
		} else {
			var bxe_areaHolder = document.createElement("div");
			nodes[i].display = "block";
		}
		bxe_areaHolder.setAttribute("name","bxe_areaHolder");
		nodes[i].parentNode.insertBefore(bxe_areaHolder,nodes[i]);
		bxe_areaHolder.appendChild(nodes[i]);
		while (xmlnode = xmlresult.iterateNext()) {
			if (xmlnode.nodeType == 1) {
				nodes[i].XMLNode.setNode( xmlnode);
				xmlnode.insertIntoHTMLDocument(nodes[i],true);
			} else {
				nodes[i].XMLNode._xmlnode = xmlnode.parentNode;
				xmlnode.insertIntoHTMLDocument(nodes[i]);
			}
			var menu = new Widget_AreaInfo(nodes[i]);
			bxe_alignAreaNode(menu,nodes[i]);
			nodes[i].AreaInfo = menu;
			menu.editableArea = nodes[i];
		}

	}

	bxe_draw_widgets();
}

XMLDocument.prototype.checkParserError = function()
{
	if(this.documentElement && this.documentElement.nodeName=="parsererror")
	{
		var alerttext = "Parse Error: \n \n";
		alerttext += this.documentElement.firstChild.data +"\n\n";
		alerttext += "Sourcetext:\n\n";
		alerttext += this.documentElement.childNodes[1].firstChild.data;

		return (alerttext);
	}
	return true;
}

XMLDocument.prototype.transformToXPathMode = function(xslfile) {
	var xsldoc = document.implementation.createDocument("", "", null);
	xsldoc.addEventListener("load", onload_xsl, false);
	xsldoc.xmldoc = this;
	try {
		xsldoc.load(xslfile);
	} catch(e) {
		alert("The xslfile: '" + xslfile + "' was not found");
	}

	function onload_xsl(e) {
		xsldoc = e.currentTarget;
		var xsltransformdoc = document.implementation.createDocument("", "", null);
		xsltransformdoc.addEventListener("load", onload_xsltransform, false);
		xsltransformdoc.xsldoc = xsldoc;
		xsltransformdoc.load(mozile_root_dir + "xsl/transformxsl.xsl");
	}

	function onload_xsltransform (e) {
		var processor = new XSLTProcessor();
		xsltransformdoc = e.currentTarget;
		processor.importStylesheet(xsltransformdoc);
		try {
			var newDocument = processor.transformToDocument(xsltransformdoc.xsldoc);
		}
		catch (e) {
			alert ( e + "\n\n xsltransformdoc.xsldoc is : " + xsltransformdoc.xsldoc);
		}
		var processor = new XSLTProcessor();
		try {
			processor.importStylesheet(newDocument);
		} catch(e) {
			alert("Something went wrong during importing the XSLT document.\n" + bxe_catch_alert_message(e) + "\n" + newDocument.saveXML(newDocument));
		}
		var xmldoc = processor.transformToFragment(xsltransformdoc.xsldoc.xmldoc,document);
		var bxe_area = document.getElementById("bxe_area");
		bxe_area.parentNode.replaceChild(xmldoc,bxe_area);
		xsltransformdoc.xsldoc.xmldoc.insertIntoHTMLDocument();

	}

}

<|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import { rhythm } from 'utils/typography'
import Helmet from 'react-helmet'
import { config } from 'config'
import sortBy from 'lodash/sortBy'
import get from 'lodash/get'
import include from 'underscore.string/include'
import footer from 'components/Footer'
import EventsList from 'components/EventsList'
// Import components needed for this page
// - to learn more about what the following components do, just take a
// - look at the their own files under the components folder in the project
import JumboTron from 'components/JumboTron'
import IntroBlock from 'components/IntroBlock'

// The following line is commented out because the component it imports
// has not been created yet

// DAN: 'uncomment' the line below, so that we import the new EventsList component

// The Home page component
class Index extends React.Component {
  render() {
     // Sort pages.
      console.log(this.props)
    const sortedPages = sortBy(this.props.route.pages, 'data.date')
    // Posts are those with md extension that are not 404 pages OR have a date (meaning they're a react component post).
    const visiblePages = sortedPages.filter(page => (
      get(page, 'file.ext') === 'md' && !include(page.path, '/404') && get(page, 'data.type' === 'event' ) || get(page, 'data.date')
    ))
    return (

        { /* add our pages components */ }
        <JumboTron />
        <IntroBlock />

        { /* DAN: uncomment the line below to activate the code */ }

        <EventsList />

Featured Events

            {visiblePages.map((page) => (

                    <Link style={{boxShadow: 'none'}} to={prefixLink(page.path)}>

                </Link>

          ))}

    )

  }
}

Index.propTypes = {
  route: React.PropTypes.object,
}

export default Index<commit_msg>changed footer component placing in code<commit_after>import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import { rhythm } from 'utils/typography'
import Helmet from 'react-helmet'
import { config } from 'config'
import sortBy from 'lodash/sortBy'
import get from 'lodash/get'
import include from 'underscore.string/include'
import footer from 'components/Footer'
import EventsList from 'components/EventsList'
// Import components needed for this page
// - to learn more about what the following components do, just take a
// - look at the their own files under the components folder in the project
import JumboTron from 'components/JumboTron'
import IntroBlock from 'components/IntroBlock'

// The following line is commented out because the component it imports
// has not been created yet

// DAN: 'uncomment' the line below, so that we import the new EventsList component

// The Home page component
class Index extends React.Component {
  render() {
     // Sort pages.
      console.log(this.props)
    const sortedPages = sortBy(this.props.route.pages, 'data.date')
    // Posts are those with md extension that are not 404 pages OR have a date (meaning they're a react component post).
    const visiblePages = sortedPages.filter(page => (
      get(page, 'file.ext') === 'md' && !include(page.path, '/404') && get(page, 'data.type' === 'event' ) || get(page, 'data.date')
    ))
    return (

        { /* add our pages components */ }
        <JumboTron />
        <IntroBlock />

        { /* DAN: uncomment the line below to activate the code */ }

        <EventsList />

Featured Events

            {visiblePages.map((page) => (

                    <Link style={{boxShadow: 'none'}} to={prefixLink(page.path)}>

                </Link>

          ))}

    )

  }
}

Index.propTypes = {
  route: React.PropTypes.object,
}

export default Index<|endoftext|>