<commit_before>//This page handles all resources page content

//jquery for phone fields
$(".required").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.required');
      if ($next.length)
          $(this).next('.required').focus();
      else
          $(this).blur();
    }
});

const auth = firebase.auth();
const btnLogout = document.getElementById('btnLogout');

//Add logout event
btnLogout.addEventListener('click', function(e) {
	auth.signOut();
  console.log(e.message);
});

//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
		btnLogout.classList.remove('hide');
    console.log(firebaseUser.email);
    closeModal();
	} else {
		console.log('not logged in');
    showModal();
		btnLogout.classList.add('hide');
	}
});

function closeModal() {
  $('#myModal').modal('close');
};

function showModal(){
  $('#myModal').modal('show');
};

//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();

function updateStatistics(statisticID) {
	var id = statisticID;
	var statValue = id + "Value";

	var valueUpdate = document.getElementById(statValue);
	statRef.ref("data_dashboard").child(statisticID).update(valueUpdate);
};

//Filters all statistics
function allStatistics() {

	//Clears table of statistics
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull statistics from Firebase database
	rootref.child("data_dashboard").on("child_added", function(snap) {

		//store data from firebase to be used in table
		var id = snap.key;
		var stringID = id.toString();
		var statValue = snap.val();

		//Creates table with statistics pulled from firebase
		$("#table_body").append("
<input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input>	<input id='"+id+"Value' type='text'  value=\""+statValue+"\" ></input>		<input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input>
"
		);
		});
};
<commit_msg>Update firebase-edit-data-dashboard.js<commit_after>//This page handles all resources page content

//jquery for phone fields
$(".required").keyup(function () {
    if (this.value.length == this.maxLength) {
      var $next = $(this).next('.required');
      if ($next.length)
          $(this).next('.required').focus();
      else
          $(this).blur();
    }
});

const auth = firebase.auth();
const btnLogout = document.getElementById('btnLogout');

//Add logout event
btnLogout.addEventListener('click', function(e) {
	auth.signOut();
  console.log(e.message);
});

//Add a realtime listener
auth.onAuthStateChanged(function(firebaseUser) {
	if(firebaseUser) {
		console.log(firebaseUser);
		btnLogout.classList.remove('hide');
    console.log(firebaseUser.email);
    closeModal();
	} else {
		console.log('not logged in');
    showModal();
		btnLogout.classList.add('hide');
	}
});

function closeModal() {
  $('#myModal').modal('close');
};

function showModal(){
  $('#myModal').modal('show');
};

//Loads all statistics on page load
window.onload = allStatistics();
var statRef = firebase.database();

function updateStatistic(statisticID) {
	var id = statisticID;
	var statValue = id + "Value";

	var valueUpdate = document.getElementById(statValue);
	statRef.ref("data_dashboard").child(statisticID).update(valueUpdate);
};

//Filters all statistics
function allStatistics() {

	//Clears table of statistics
	var tableRef = document.getElementById('table_body');
	while ( tableRef.rows.length > 0 )
	{
	 tableRef.deleteRow(0);
	}

	//Pull statistics from Firebase database
	rootref.child("data_dashboard").on("child_added", function(snap) {

		//store data from firebase to be used in table
		var id = snap.key;
		var stringID = id.toString();
		var statValue = snap.val();

		//Creates table with statistics pulled from firebase
		$("#table_body").append("
<input id='"+id+"Statistic' type='text' value=\""+stringID+"\" ></input>	<input id='"+id+"Value' type='text'  value=\""+statValue+"\" ></input>		<input type='submit' class='btn btn-success btn-send' value='Update' onclick='updateStatistic(\""+ stringID + "\")''></input>
"
		);
		});
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name                OLog
// @namespace           http://www.olog.com/
// @description         OLog Userscript
// @include             http://s*-*.ogame.gameforge.com/game/*
// @grant               GM_xmlhttpRequest
// @grant               GM_getValue
// @grant               GM_setValue
// ==/UserScript==

"use strict";

var oLogInstanceUrl = getSetting("settings.ologinstanceurl", "http://localhost:8080/");

var menuTable = document.getElementById("menuTable");

var oLogLi = document.createElement("li");
oLogLi.onfocus = function(c) {
    if (b(c.target).closest(".dropdown").length == 0) {
        b(".currentlySelected a").removeClass("hover");
        b(".currentlySelected").removeClass("focus");
    }
}

var oLogAnchor = document.createElement("a");
oLogAnchor.className = "menubutton";
oLogAnchor.href = "#ologsettings";
oLogAnchor.onclick = function() {
    showOLogSettings();
};

var oLogSpan = document.createElement("span");
oLogSpan.className = "textlabel"

var oLogText = document.createTextNode("OLog Settings");

oLogSpan.appendChild(oLogText);
oLogAnchor.appendChild(oLogSpan);
oLogLi.appendChild(oLogAnchor);
menuTable.appendChild(oLogLi);

if (window.location.hash === "#ologsettings") {
    showOLogSettings();
}

function showOLogSettings() {
    var menuTableLiList = menuTable.querySelectorAll("li");
    for (var i = 0; i < menuTableLiList.length; i++) {
        menuTableLiList[i].querySelector(".menubutton").classList.remove("selected");
    }

    oLogAnchor.classList.add("selected");

    var contentWrapperDiv = document.getElementById("contentWrapper");
    while (contentWrapperDiv.firstChild) {
        contentWrapperDiv.removeChild(contentWrapperDiv.firstChild);
    }

    var buttonzDiv = document.createElement("div");
    buttonzDiv.id = "buttonz";

    var headerDiv = document.createElement("div");
    headerDiv.className = "header";

    var headerH2 = document.createElement("h2");

    var headerText = document.createTextNode("OLog Settings");

    var contentDiv = document.createElement("div");
    contentDiv.className = "content";

    var fieldwrapperDiv = document.createElement("div");
    fieldwrapperDiv.className = "fieldwrapper";

    var oLogInstanceUrlLabel = document.createElement("label");
    oLogInstanceUrlLabel.className = "styled textBeefy";

    var oLogInstanceUrlText = document.createTextNode("OLog Instance URL:");

    var oLogInstanceUrlTheFieldDiv = document.createElement("div");
    oLogInstanceUrlTheFieldDiv.className = "thefield";

    var oLogInstanceUrlInput = document.createElement("input");
    oLogInstanceUrlInput.className = "textinput w200";
    oLogInstanceUrlInput.type = "text";
    oLogInstanceUrlInput.size = "30";
    oLogInstanceUrlInput.value = oLogInstanceUrl;
    oLogInstanceUrlInput.maxlength = "20";

    var settingsSaveDiv = document.createElement("div");
    settingsSaveDiv.className = "textCenter";

    var settingsSaveInput = document.createElement("input");
    settingsSaveInput.className = "btn_blue";
    settingsSaveInput.type = "submit";
    settingsSaveInput.value = "Save settings";
    settingsSaveInput.onclick = function() {
        saveSetting("settings.ologinstanceurl", oLogInstanceUrlInput.value);
        showSuccessMessage("Settings have been saved.");
    };

    oLogInstanceUrlLabel.appendChild(oLogInstanceUrlText);
    oLogInstanceUrlTheFieldDiv.appendChild(oLogInstanceUrlInput);
    fieldwrapperDiv.appendChild(oLogInstanceUrlLabel);
    fieldwrapperDiv.appendChild(oLogInstanceUrlTheFieldDiv);

    settingsSaveDiv.appendChild(settingsSaveInput);

    contentDiv.appendChild(fieldwrapperDiv);
    contentDiv.appendChild(settingsSaveDiv);

    headerH2.appendChild(headerText);
    headerDiv.appendChild(headerH2);
    buttonzDiv.appendChild(headerDiv);
    buttonzDiv.appendChild(contentDiv);
    contentWrapperDiv.appendChild(buttonzDiv);
}

var page = getWindowVariable("currentPage");

if (page === "messages") {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.localName === "ul" && node.classList.contains("tab_inner")) {
                    //send all messages at once such that all SR keys can be sent at once to the server
                    processMessageNodes(node.querySelectorAll(".msg"));
                }
            }
        });
    });

    observer.observe(document, { childList: true, subtree: true });
}

function processMessageNodes(nodes) {
    var reportKeys = {
        sr: [],     //spy report
        cr: [],     //combat report
        rr: [],     //recycle report
        mr: []      //missile report
    };

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var apiElement = node.querySelector(".icon_apikey");
        if (apiElement !== null) {
            var key = apiElement.parentNode.href.replace(/.*?:\/\//g, "");
            var type = key.substring(0, 2);
            if (reportKeys.hasOwnProperty(type)) {
                reportKeys[type].push(key);
            }
        }
    }

    console.log(reportKeys);

    postData({
        endpoint: "keys",
        data: {
            reportKeys: reportKeys
        }
    });
}

function postData(object) {
    addPlayerData(object.data);
    console.log(JSON.stringify(object.data));
    GM_xmlhttpRequest({
        method: "POST",
        url: oLogInstanceUrl + "api/userscript/" + object.endpoint,
        data: JSON.stringify(object.data),
        headers: {
            "Content-Type": "application/json"
        },
        onload: function(response) {
            console.log("load");
        },
        onerror: function(response) {
            console.log("error");
        }
    });
}

function addPlayerData(data) {
    data.serverGroup = getWindowVariable("constants.language");
    data.universe = getWindowVariable("constants.name");
    data.playerId = getWindowVariable("playerId");
    data.playerName = getWindowVariable("playerName");
}

/**
 * Returns a global variable.
 *
 * Needed because a @grant other than none puts the script
 * in a separate scope.
 *
 * @param {string} name The name of the global variable.
 */
function getWindowVariable(name) {
    return window.eval(name);
}

function showSuccessMessage(message) {
    getWindowVariable("fadeBox")(message, false);
}

function showErrorMessage(message) {
    getWindowVariable("fadeBox")(message, true);
}

function saveSetting(key, value) {
    var fullKey = getWindowVariable("constants.language") + ":" + getWindowVariable("constants.name") + ":" + getWindowVariable("playerId") + ":" + key;
    GM_setValue(fullKey, value);
}

function getSetting(key, defaultValue) {
    var fullKey = getWindowVariable("constants.language") + ":" + getWindowVariable("constants.name") + ":" + getWindowVariable("playerId") + ":" + key;
    return GM_getValue(fullKey, defaultValue);
}<commit_msg>Added version to userscript, initialized to 0.1pre.<commit_after>// ==UserScript==
// @name                OLog
// @namespace           http://www.olog.com/
// @description         OLog Userscript
// @downloadURL         https://github.com/skiwi2/OLog-Userscript/raw/master/olog.user.js
// @updateURL           https://github.com/skiwi2/OLog-Userscript/raw/master/olog.user.js
// @version             0.1pre
// @include             http://s*-*.ogame.gameforge.com/game/*
// @grant               GM_xmlhttpRequest
// @grant               GM_getValue
// @grant               GM_setValue
// ==/UserScript==

"use strict";

var oLogInstanceUrl = getSetting("settings.ologinstanceurl", "http://localhost:8080/");

var menuTable = document.getElementById("menuTable");

var oLogLi = document.createElement("li");
oLogLi.onfocus = function(c) {
    if (b(c.target).closest(".dropdown").length == 0) {
        b(".currentlySelected a").removeClass("hover");
        b(".currentlySelected").removeClass("focus");
    }
}

var oLogAnchor = document.createElement("a");
oLogAnchor.className = "menubutton";
oLogAnchor.href = "#ologsettings";
oLogAnchor.onclick = function() {
    showOLogSettings();
};

var oLogSpan = document.createElement("span");
oLogSpan.className = "textlabel"

var oLogText = document.createTextNode("OLog Settings");

oLogSpan.appendChild(oLogText);
oLogAnchor.appendChild(oLogSpan);
oLogLi.appendChild(oLogAnchor);
menuTable.appendChild(oLogLi);

if (window.location.hash === "#ologsettings") {
    showOLogSettings();
}

function showOLogSettings() {
    var menuTableLiList = menuTable.querySelectorAll("li");
    for (var i = 0; i < menuTableLiList.length; i++) {
        menuTableLiList[i].querySelector(".menubutton").classList.remove("selected");
    }

    oLogAnchor.classList.add("selected");

    var contentWrapperDiv = document.getElementById("contentWrapper");
    while (contentWrapperDiv.firstChild) {
        contentWrapperDiv.removeChild(contentWrapperDiv.firstChild);
    }

    var buttonzDiv = document.createElement("div");
    buttonzDiv.id = "buttonz";

    var headerDiv = document.createElement("div");
    headerDiv.className = "header";

    var headerH2 = document.createElement("h2");

    var headerText = document.createTextNode("OLog Settings");

    var contentDiv = document.createElement("div");
    contentDiv.className = "content";

    var fieldwrapperDiv = document.createElement("div");
    fieldwrapperDiv.className = "fieldwrapper";

    var oLogInstanceUrlLabel = document.createElement("label");
    oLogInstanceUrlLabel.className = "styled textBeefy";

    var oLogInstanceUrlText = document.createTextNode("OLog Instance URL:");

    var oLogInstanceUrlTheFieldDiv = document.createElement("div");
    oLogInstanceUrlTheFieldDiv.className = "thefield";

    var oLogInstanceUrlInput = document.createElement("input");
    oLogInstanceUrlInput.className = "textinput w200";
    oLogInstanceUrlInput.type = "text";
    oLogInstanceUrlInput.size = "30";
    oLogInstanceUrlInput.value = oLogInstanceUrl;
    oLogInstanceUrlInput.maxlength = "20";

    var settingsSaveDiv = document.createElement("div");
    settingsSaveDiv.className = "textCenter";

    var settingsSaveInput = document.createElement("input");
    settingsSaveInput.className = "btn_blue";
    settingsSaveInput.type = "submit";
    settingsSaveInput.value = "Save settings";
    settingsSaveInput.onclick = function() {
        saveSetting("settings.ologinstanceurl", oLogInstanceUrlInput.value);
        showSuccessMessage("Settings have been saved.");
    };

    oLogInstanceUrlLabel.appendChild(oLogInstanceUrlText);
    oLogInstanceUrlTheFieldDiv.appendChild(oLogInstanceUrlInput);
    fieldwrapperDiv.appendChild(oLogInstanceUrlLabel);
    fieldwrapperDiv.appendChild(oLogInstanceUrlTheFieldDiv);

    settingsSaveDiv.appendChild(settingsSaveInput);

    contentDiv.appendChild(fieldwrapperDiv);
    contentDiv.appendChild(settingsSaveDiv);

    headerH2.appendChild(headerText);
    headerDiv.appendChild(headerH2);
    buttonzDiv.appendChild(headerDiv);
    buttonzDiv.appendChild(contentDiv);
    contentWrapperDiv.appendChild(buttonzDiv);
}

var page = getWindowVariable("currentPage");

if (page === "messages") {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.localName === "ul" && node.classList.contains("tab_inner")) {
                    //send all messages at once such that all SR keys can be sent at once to the server
                    processMessageNodes(node.querySelectorAll(".msg"));
                }
            }
        });
    });

    observer.observe(document, { childList: true, subtree: true });
}

function processMessageNodes(nodes) {
    var reportKeys = {
        sr: [],     //spy report
        cr: [],     //combat report
        rr: [],     //recycle report
        mr: []      //missile report
    };

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var apiElement = node.querySelector(".icon_apikey");
        if (apiElement !== null) {
            var key = apiElement.parentNode.href.replace(/.*?:\/\//g, "");
            var type = key.substring(0, 2);
            if (reportKeys.hasOwnProperty(type)) {
                reportKeys[type].push(key);
            }
        }
    }

    console.log(reportKeys);

    postData({
        endpoint: "keys",
        data: {
            reportKeys: reportKeys
        }
    });
}

function postData(object) {
    addPlayerData(object.data);
    console.log(JSON.stringify(object.data));
    GM_xmlhttpRequest({
        method: "POST",
        url: oLogInstanceUrl + "api/userscript/" + object.endpoint,
        data: JSON.stringify(object.data),
        headers: {
            "Content-Type": "application/json"
        },
        onload: function(response) {
            console.log("load");
        },
        onerror: function(response) {
            console.log("error");
        }
    });
}

function addPlayerData(data) {
    data.serverGroup = getWindowVariable("constants.language");
    data.universe = getWindowVariable("constants.name");
    data.playerId = getWindowVariable("playerId");
    data.playerName = getWindowVariable("playerName");
}

/**
 * Returns a global variable.
 *
 * Needed because a @grant other than none puts the script
 * in a separate scope.
 *
 * @param {string} name The name of the global variable.
 */
function getWindowVariable(name) {
    return window.eval(name);
}

function showSuccessMessage(message) {
    getWindowVariable("fadeBox")(message, false);
}

function showErrorMessage(message) {
    getWindowVariable("fadeBox")(message, true);
}

function saveSetting(key, value) {
    var fullKey = getWindowVariable("constants.language") + ":" + getWindowVariable("constants.name") + ":" + getWindowVariable("playerId") + ":" + key;
    GM_setValue(fullKey, value);
}

function getSetting(key, defaultValue) {
    var fullKey = getWindowVariable("constants.language") + ":" + getWindowVariable("constants.name") + ":" + getWindowVariable("playerId") + ":" + key;
    return GM_getValue(fullKey, defaultValue);
}<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: For creating grouped collapsible content areas.
//>>label: Collapsible Sets (Accordions)
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "./jquery.mobile.widget", "./jquery.mobile.collapsible" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.collapsibleset", $.mobile.widget, {
	options: {
		initSelector: ":jqmData(role='collapsible-set')"
	},
	_create: function() {
		var $el = this.element.addClass( "ui-collapsible-set" ),
			o = this.options;

		// Inherit the theme from collapsible-set
		if ( !o.theme ) {
			o.theme = $.mobile.getInheritedTheme( $el, "c" );
		}
		// Inherit the content-theme from collapsible-set
		if ( !o.contentTheme ) {
			o.contentTheme = $el.jqmData( "content-theme" );
		}

		if ( !o.corners ) {
			o.corners = $el.jqmData( "corners" ) === undefined ? true : false;
		}

		// Initialize the collapsible set if it's not already initialized
		if ( !$el.jqmData( "collapsiblebound" ) ) {
			$el
				.jqmData( "collapsiblebound", true )
				.bind( "expand collapse", function( event ) {
					var isCollapse = ( event.type === "collapse" ),
						collapsible = $( event.target ).closest( ".ui-collapsible" ),
						widget = collapsible.data( "collapsible" ),
					    contentTheme = widget.options.contentTheme;
					if ( contentTheme && collapsible.jqmData( "collapsible-last" ) ) {
						collapsible.find( widget.options.heading ).first()
							.find( "a" ).first()
							.toggleClass( "ui-corner-bottom", isCollapse )
							.find( ".ui-btn-inner" )
							.toggleClass( "ui-corner-bottom", isCollapse );
						collapsible.find( ".ui-collapsible-content" ).toggleClass( "ui-corner-bottom", !isCollapse );
					}
				})
				.bind( "expand", function( event ) {
					var closestCollapsible = $( event.target )
						.closest( ".ui-collapsible" );
					if( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) {
						closestCollapsible
							.siblings( ".ui-collapsible" )
							.trigger( "collapse" );
					}
				});
		}
	},

	_init: function() {
		var $el = this.element,
			collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ),
			expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
		this.refresh();

		// Because the corners are handled by the collapsible itself and the default state is collapsed
		// That was causing https://github.com/jquery/jquery-mobile/issues/4116
		expanded.trigger( "expand" );
	},

	refresh: function() {
		var $el = this.element,
			o = this.options,
			collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" );

		$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );

		// clean up borders
		collapsiblesInSet.each( function() {
			$( this ).find( $.mobile.collapsible.prototype.options.heading )
				.find( "a" ).first()
				.removeClass( "ui-corner-top ui-corner-bottom" )
				.find( ".ui-btn-inner" )
				.removeClass( "ui-corner-top ui-corner-bottom" );
		});

		collapsiblesInSet.first()
			.find( "a" )
				.first()
				.addClass( o.corners ? "ui-corner-top" : "" )
				.find( ".ui-btn-inner" )
					.addClass( "ui-corner-top" );

		collapsiblesInSet.last()
			.jqmData( "collapsible-last", true )
			.find( "a" )
				.first()
				.addClass( o.corners ? "ui-corner-bottom" : "" )
				.find( ".ui-btn-inner" )
					.addClass( "ui-corner-bottom" );
	}
});

//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
	$.mobile.collapsibleset.prototype.enhanceWithin( e.target );
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>Fixes #4499 - Bottom accordion keeps rounded corners when expanded<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: For creating grouped collapsible content areas.
//>>label: Collapsible Sets (Accordions)
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "./jquery.mobile.widget", "./jquery.mobile.collapsible" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.collapsibleset", $.mobile.widget, {
	options: {
		initSelector: ":jqmData(role='collapsible-set')"
	},
	_create: function() {
		var $el = this.element.addClass( "ui-collapsible-set" ),
			o = this.options;

		// Inherit the theme from collapsible-set
		if ( !o.theme ) {
			o.theme = $.mobile.getInheritedTheme( $el, "c" );
		}
		// Inherit the content-theme from collapsible-set
		if ( !o.contentTheme ) {
			o.contentTheme = $el.jqmData( "content-theme" );
		}

		if ( !o.corners ) {
			o.corners = $el.jqmData( "corners" ) === undefined ? true : false;
		}

		// Initialize the collapsible set if it's not already initialized
		if ( !$el.jqmData( "collapsiblebound" ) ) {
			$el
				.jqmData( "collapsiblebound", true )
				.bind( "expand collapse", function( event ) {
					var isCollapse = ( event.type === "collapse" ),
						collapsible = $( event.target ).closest( ".ui-collapsible" ),
						widget = collapsible.data( "collapsible" );
					if ( collapsible.jqmData( "collapsible-last" ) ) {
						collapsible.find( widget.options.heading ).first()
							.find( "a" ).first()
							.toggleClass( "ui-corner-bottom", isCollapse )
							.find( ".ui-btn-inner" )
							.toggleClass( "ui-corner-bottom", isCollapse );
						collapsible.find( ".ui-collapsible-content" ).toggleClass( "ui-corner-bottom", !isCollapse );
					}
				})
				.bind( "expand", function( event ) {
					var closestCollapsible = $( event.target )
						.closest( ".ui-collapsible" );
					if( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) {
						closestCollapsible
							.siblings( ".ui-collapsible" )
							.trigger( "collapse" );
					}
				});
		}
	},

	_init: function() {
		var $el = this.element,
			collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ),
			expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
		this.refresh();

		// Because the corners are handled by the collapsible itself and the default state is collapsed
		// That was causing https://github.com/jquery/jquery-mobile/issues/4116
		expanded.trigger( "expand" );
	},

	refresh: function() {
		var $el = this.element,
			o = this.options,
			collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" );

		$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );

		// clean up borders
		collapsiblesInSet.each( function() {
			$( this ).find( $.mobile.collapsible.prototype.options.heading )
				.find( "a" ).first()
				.removeClass( "ui-corner-top ui-corner-bottom" )
				.find( ".ui-btn-inner" )
				.removeClass( "ui-corner-top ui-corner-bottom" );
		});

		collapsiblesInSet.first()
			.find( "a" )
				.first()
				.addClass( o.corners ? "ui-corner-top" : "" )
				.find( ".ui-btn-inner" )
					.addClass( "ui-corner-top" );

		collapsiblesInSet.last()
			.jqmData( "collapsible-last", true )
			.find( "a" )
				.first()
				.addClass( o.corners ? "ui-corner-bottom" : "" )
				.find( ".ui-btn-inner" )
					.addClass( "ui-corner-bottom" );
	}
});

//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
	$.mobile.collapsibleset.prototype.enhanceWithin( e.target );
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>'use strict'

var engine = require('../lib/engine')
var ComposrError = require('../lib/ComposrError')

module.exports = function (server) {

  server.get('/doc/:domain/', serveDocumentation)
  server.get('/doc/:domain/:version/', serveDocumentation)

  function serveDocumentation(req, res, next) {
    var domain = req.params.domain || ''
    // TODO move to core
    var rawPhrases = engine.composr.data.phrases
    var phrases = rawPhrases.filter(function (item) {
      return item.id.split('!')[0] === domain
    })

    var version = req.params.version
    if (version) {
      phrases = phrases.filter(function (item) {
        return item.id.split('!')[1] === version
      })
    }

    engine.composr.documentation(phrases, domain, version || '')
      .then(function (result) {
        res.writeHead(200, {
          'Content-Length': Buffer.byteLength(result),
          'Content-Type': 'text/html'
        })
        res.write(result)
        res.end()
      })
      .catch(function (err) {
        next(new ComposrError('error:phrase:doc', 'Error generating doc: ' + err, 422))
      })
  }

}
<commit_msg>linter fixed<commit_after>'use strict'

var engine = require('../lib/engine')
var ComposrError = require('../lib/ComposrError')

module.exports = function (server) {
  server.get('/doc/:domain/', serveDocumentation)
  server.get('/doc/:domain/:version/', serveDocumentation)

  function serveDocumentation (req, res, next) {
    var domain = req.params.domain || ''
    // TODO move to core
    var rawPhrases = engine.composr.data.phrases
    var phrases = rawPhrases.filter(function (item) {
      return item.id.split('!')[0] === domain
    })

    var version = req.params.version
    if (version) {
      phrases = phrases.filter(function (item) {
        return item.id.split('!')[1] === version
      })
    }

    engine.composr.documentation(phrases, domain, version || '')
      .then(function (result) {
        res.writeHead(200, {
          'Content-Length': Buffer.byteLength(result),
          'Content-Type': 'text/html'
        })
        res.write(result)
        res.end()
      })
      .catch(function (err) {
        next(new ComposrError('error:phrase:doc', 'Error generating doc: ' + err, 422))
      })
  }
}
<|endoftext|>


<commit_before>
// 引入 QCloud 小程序增强 SDK
var event = require('../../utils/event.js')
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');

// 引入配置
var config = require('../../config');
var util = require('../../utils/util.js')
/**
 * 生成一条聊天室的消息的唯一 ID
 */
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
});

function msgUuid() {
    if (!msgUuid.next) {
        msgUuid.next = 0;
    }
    return 'msg-' + (++msgUuid.next);
}
function createSystemMessage(content) {
    return { id: msgUuid(), type: 'system', content };
}

/**
 * 生成聊天室的聊天消息
 */
function createUserMessage(content, user, isMe) {
    return { id: msgUuid(), type: 'speak', content, user, isMe };
}

var hasDelete = false
var appInstance = getApp();
Page({
    data:{
         messages: [],
         friendInfo:null,
         lastMessageId:'none',
         inputContent: '大家好啊',
         type:null
    },

    onLoad(options){
        console.log(options)
        var that = this
        var openId = options.openId
        appInstance.globalData.enterOpenId = openId
        var friends = appInstance.globalData.friends
        console.log("friendsfriendsfriendsfriendsfriends",friends)
        var friendInfo
        if (options.type == "friend") {
            for (var i = 0; i < friends.length; i++) {
                if (friends[i].openId == openId) {
                    friendInfo = friends[i]
                    that.setData({
                        friendInfo
                    })
                }
            }
            that.setData({
                type:"friend"
            })
        }

        if (options.type == "stranger") {
            var groupMember = appInstance.globalData.groupMember
            console.log('appInstance.globalData.groupMember',appInstance.globalData.groupMember)
            for (var i = 0; i < groupMember.length; i++) {
                for (var j = 0; j < groupMember[i].list.length; j++) {
                    if (groupMember[i].list[j].openId == openId) {
                        friendInfo = groupMember[i].list[j]
                        event.emit('chatStranger',friendInfo)
                        that.setData({
                            friendInfo
                        })
                    }

                }
            }
            that.setData({
                type:"stranger"
            })
        }
        if (openId == appInstance.globalData.myId) {
            var friendInfo = appInstance.globalData.userData
            that.setData({
                friendInfo
            })
            console.log("friendInfofriendInfofriendInfo",friendInfo)
        }

        //this.showVerifyInfo()
        this.tunnel = appInstance.globalData.tunnel
        this.me = appInstance.globalData.userData

        event.on('openTunel',this,function(tunnel){
           this.tunnel = tunnel
        })

        event.on('addFriend',this,function(add){
           //添加好友可能需要 当聊天对方向你添加时
           var friendInfo = this.data.friendInfo
           console.log('add',add)
           if (add.openId == friendInfo.openId) {
                this.showVerifyInfo()
            }
        })

        event.on('deleteFriend',this,function(delete1){
           //当对方删除你时
           if (delete1.sourceId == friendInfo.openId) {
                hasDelete = true
           }

        })

        event.on('friendMessage',this,function(speak){
           //双方说话时
            console.log('speak.data.sourceId',speak.data.sourceId)
            console.log('friendInfo.openId',friendInfo.openId)
            if (speak.data.sourceId == friendInfo.openId) {
                var isMe = false
                var who = {
                    "nickName":speak.data.sourceName,
                    "avatarUrl":speak.data.sourceAvatar,
                }

                that.pushMessage(createUserMessage(speak.data.content,who,isMe))
           }
        })

        event.on('myMessage',this,function(speak){
            if (speak.data.sourceId == appInstance.globalData.myId && speak.targetId == friendInfo.openId) {
                var isMe = true
                var who = {
                    "nickName":speak.data.sourceName,
                    "avatarUrl":speak.data.sourceAvatar,
                }
                that.pushMessage(createUserMessage(speak.data.content,who,isMe))
            }
        })
        event.on('add2Friend',this,function(add2Friend){
            var friendInfo = this.data.friendInfo
            if (add2Friend.sourceId == friendInfo.openId) {
                friendInfo.type = "friend"
                this.setData({
                    friendInfo
                })
                that.pushMessage(createSystemMessage("你们已经是好友了"))
            }
        })
    },

    onUnload(){
        event.remove('openTunel',this);
        event.remove('addFriend',this);
        event.remove('deleteFriend',this);
        event.remove('friendMessage',this);
        event.remove('myMessage',this);
        event.remove('add2Friend',this);
    },

    onReady() {
        wx.setNavigationBarTitle({ title: this.data.friendInfo.nickName});
        if (this.data.type == 'friend') {
            var friendMessage = this.data.friendInfo.newMessages
            var isMe = false
            for (var i = 0; i < friendMessage.length; i++) {
                isMe = false
                if (friendMessage[i].sourceId == appInstance.globalData.myId) {
                    isMe = true
                }
                var who = {
                    "nickName":friendMessage[i].sourceName,
                    "avatarUrl":friendMessage[i].avatarUrl,
                }
                this.pushMessage(createUserMessage(friendMessage[i].content,who,isMe))
            }
        }

    },

    addfriend(){
        this.tunnel.emit('add',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{}
                })
        showSuccess('消息已发送')
        event.emit('add',this.data.friendInfo.openId)
        //添加对方为好友
    },

    deletefriend(){
        this.tunnel.emit('delete',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{}
                })
        event.emit('deleteStranger',this.data.friendInfo.openId)
        wx.switchTab({
            url:'../index/index'
        })
        //删除对方好友
    },
    showVerifyInfo(){
        var that = this
        wx.showModal({
            title:"对方请求添加好友",
            content: "  添加好友以后还可以继续愉快的聊天哦",
            showCancel: true,
            cancelText:"拒绝",
            cancelColor: '#6E6E6E',
            confirmText:"添加",
            confirmColor:"#6C5BB7",
            success: function(res){
                if (res.confirm) {
                    //确认添加
                    that.verifyFriend()
                    that.setData({
                        type:'friend'
                    })
                    //event.emit("addFriendToList",) 具体要传什么数据呢
                }
                else{
                    //拒绝添加
                }
            }
        });
    },

    verifyFriend(){
        var sourceId = appInstance.globalData.userData.openId
        console.log("sfsfdas  sourceId",sourceId)
        var sourceName = appInstance.globalData.userData.nickName
        var avatar = appInstance.globalData.userData.avatarUrl
        this.tunnel.emit('add2',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{
                        "sourceId":sourceId,
                        "sourceName":sourceName,
                        "avatar":avatar,
                        "result":true
                    }
                })
        this.pushMessage(createSystemMessage('对方已经是你好友'))
    },

    updateMessages(updater) {
        var messages = this.data.messages;
        updater(messages);

        this.setData({ messages });

        // 需要先更新 messagess 数据后再设置滚动位置，否则不能生效
        var lastMessageId = messages.length ? messages[messages.length - 1].id : 'none';
        this.setData({ lastMessageId });
    },

    /**
     * 追加一条消息
     */
    pushMessage(message) {
        this.updateMessages(messages => messages.push(message));
    },

    /**
     * 替换上一条消息
     */
    amendMessage(message) {
        this.updateMessages(messages => messages.splice(-1, 1, message));
    },

    /**
     * 删除上一条消息
     */
    popMessage() {
        this.updateMessages(messages => messages.pop());
    },

    /**
     * 用户输入的内容改变之后
     */
    changeInputContent(e) {
        this.setData({ inputContent: e.detail.value });
    },

    /**
     * 点击「发送」按钮，通过信道推送消息到服务器
     **/
    sendMessage(e) {
        // 信道当前不可用
        if (!this.tunnel || !this.tunnel.isActive()) {
            this.pushMessage(createSystemMessage('对不起你还未连接'));
            return;
        }
         if (hasDelete) {
            this.pushMessage(createSystemMessage('对不起对方已经将你删除，你不能向对方发消息'));
            return;
        }

        setTimeout(() => {
            if (this.data.inputContent && this.tunnel) {
                //this.tunnel.emit('speak', { word: this.data.inputContent });

                var date = Date.now()
                console.log(this.tunnel)
                this.tunnel.emit('speak',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{
                        "sourceId":appInstance.globalData.myId,
                        "sourceName":appInstance.globalData.userInfo.nickName,
                        "sourceAvatar":appInstance.globalData.userInfo.avatarUrl,
                        "date":date,
                        "content":this.data.inputContent
                    }
                })
                this.setData({ inputContent: '' });
            }
        });
    },

})<commit_msg>test add friend complete<commit_after>
// 引入 QCloud 小程序增强 SDK
var event = require('../../utils/event.js')
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');

// 引入配置
var config = require('../../config');
var util = require('../../utils/util.js')
/**
 * 生成一条聊天室的消息的唯一 ID
 */
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
});

function msgUuid() {
    if (!msgUuid.next) {
        msgUuid.next = 0;
    }
    return 'msg-' + (++msgUuid.next);
}
function createSystemMessage(content) {
    return { id: msgUuid(), type: 'system', content };
}

/**
 * 生成聊天室的聊天消息
 */
function createUserMessage(content, user, isMe) {
    return { id: msgUuid(), type: 'speak', content, user, isMe };
}

var hasDelete = false
var appInstance = getApp();
Page({
    data:{
         messages: [],
         friendInfo:null,
         lastMessageId:'none',
         inputContent: '大家好啊',
         type:null
    },

    onLoad(options){
        console.log(options)
        var that = this
        var openId = options.openId
        appInstance.globalData.enterOpenId = openId
        var friends = appInstance.globalData.friends
        console.log("friendsfriendsfriendsfriendsfriends",friends)
        var friendInfo
        if (options.type == "friend") {
            for (var i = 0; i < friends.length; i++) {
                if (friends[i].openId == openId) {
                    friendInfo = friends[i]
                    friendInfo.type = "friend"
                    that.setData({
                        friendInfo
                    })
                }
            }
            that.setData({
                type:"friend"
            })
            //终究要修改
        }

        if (options.type == "stranger") {
            var groupMember = appInstance.globalData.groupMember
            console.log('appInstance.globalData.groupMember',appInstance.globalData.groupMember)
            for (var i = 0; i < groupMember.length; i++) {
                for (var j = 0; j < groupMember[i].list.length; j++) {
                    if (groupMember[i].list[j].openId == openId) {
                        friendInfo = groupMember[i].list[j]
                        friendInfo.type = "stranger"
                        event.emit('chatStranger',friendInfo)
                        that.setData({
                            friendInfo
                        })
                    }

                }
            }
            that.setData({
                type:"stranger"
            })

        }
        if (openId == appInstance.globalData.myId) {
            var friendInfo = appInstance.globalData.userData
            that.setData({
                friendInfo
            })
            console.log("friendInfofriendInfofriendInfo",friendInfo)
        }

        //this.showVerifyInfo()
        this.tunnel = appInstance.globalData.tunnel
        this.me = appInstance.globalData.userData

        event.on('openTunel',this,function(tunnel){
           this.tunnel = tunnel
        })

        event.on('addFriend',this,function(add){
           //添加好友可能需要 当聊天对方向你添加时
           var friendInfo = this.data.friendInfo
           console.log('add',add)
           if (add.openId == friendInfo.openId) {
                this.showVerifyInfo()
            }
        })

        event.on('deleteFriend',this,function(delete1){
           //当对方删除你时
           if (delete1.sourceId == friendInfo.openId) {
                hasDelete = true
           }

        })

        event.on('friendMessage',this,function(speak){
           //双方说话时
            console.log('speak.data.sourceId',speak.data.sourceId)
            console.log('friendInfo.openId',friendInfo.openId)
            if (speak.data.sourceId == friendInfo.openId) {
                var isMe = false
                var who = {
                    "nickName":speak.data.sourceName,
                    "avatarUrl":speak.data.sourceAvatar,
                }

                that.pushMessage(createUserMessage(speak.data.content,who,isMe))
           }
        })

        event.on('myMessage',this,function(speak){
            if (speak.data.sourceId == appInstance.globalData.myId && speak.targetId == friendInfo.openId) {
                var isMe = true
                var who = {
                    "nickName":speak.data.sourceName,
                    "avatarUrl":speak.data.sourceAvatar,
                }
                that.pushMessage(createUserMessage(speak.data.content,who,isMe))
            }
        })
        event.on('add2Friend',this,function(add2Friend){
            var friendInfo = this.data.friendInfo
            if (add2Friend.sourceId == friendInfo.openId) {
                friendInfo.type = "friend"
                console.log("friendInfo",friendInfo)
                this.setData({
                    friendInfo
                })
                that.setData({
                    type:'friend'
                })
                that.pushMessage(createSystemMessage("你们已经是好友了"))
            }
        })
    },

    onUnload(){
        event.remove('openTunel',this);
        event.remove('addFriend',this);
        event.remove('deleteFriend',this);
        event.remove('friendMessage',this);
        event.remove('myMessage',this);
        event.remove('add2Friend',this);
    },

    onReady() {
        wx.setNavigationBarTitle({ title: this.data.friendInfo.nickName});
        if (this.data.type == 'friend') {
            var friendMessage = this.data.friendInfo.newMessages
            var isMe = false
            for (var i = 0; i < friendMessage.length; i++) {
                isMe = false
                if (friendMessage[i].sourceId == appInstance.globalData.myId) {
                    isMe = true
                }
                var who = {
                    "nickName":friendMessage[i].sourceName,
                    "avatarUrl":friendMessage[i].avatarUrl,
                }
                this.pushMessage(createUserMessage(friendMessage[i].content,who,isMe))
            }
        }

    },

    addfriend(){
        this.tunnel.emit('add',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{}
                })
        showSuccess('消息已发送')
        event.emit('add',this.data.friendInfo.openId)
        //添加对方为好友
    },

    deletefriend(){
        this.tunnel.emit('delete',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{}
                })
        event.emit('deleteStranger',this.data.friendInfo.openId)
        wx.switchTab({
            url:'../index/index'
        })
        //删除对方好友
    },
    showVerifyInfo(){
        var that = this
        wx.showModal({
            title:"对方请求添加好友",
            content: "  添加好友以后还可以继续愉快的聊天哦",
            showCancel: true,
            cancelText:"拒绝",
            cancelColor: '#6E6E6E',
            confirmText:"添加",
            confirmColor:"#6C5BB7",
            success: function(res){
                if (res.confirm) {
                    //确认添加
                    that.verifyFriend()
                    that.setData({
                        type:'friend'
                    })
                    //event.emit("addFriendToList",) 具体要传什么数据呢
                }
                else{
                    //拒绝添加
                }
            }
        });
    },

    verifyFriend(){
        var sourceId = appInstance.globalData.userData.openId
        console.log("sfsfdas  sourceId",sourceId)
        var sourceName = appInstance.globalData.userData.nickName
        var avatar = appInstance.globalData.userData.avatarUrl
        this.tunnel.emit('add2',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{
                        "sourceId":sourceId,
                        "sourceName":sourceName,
                        "avatar":avatar,
                        "result":true
                    }
                })
        this.pushMessage(createSystemMessage('对方已经是你好友'))
    },

    updateMessages(updater) {
        var messages = this.data.messages;
        updater(messages);

        this.setData({ messages });

        // 需要先更新 messagess 数据后再设置滚动位置，否则不能生效
        var lastMessageId = messages.length ? messages[messages.length - 1].id : 'none';
        this.setData({ lastMessageId });
    },

    /**
     * 追加一条消息
     */
    pushMessage(message) {
        this.updateMessages(messages => messages.push(message));
    },

    /**
     * 替换上一条消息
     */
    amendMessage(message) {
        this.updateMessages(messages => messages.splice(-1, 1, message));
    },

    /**
     * 删除上一条消息
     */
    popMessage() {
        this.updateMessages(messages => messages.pop());
    },

    /**
     * 用户输入的内容改变之后
     */
    changeInputContent(e) {
        this.setData({ inputContent: e.detail.value });
    },

    /**
     * 点击「发送」按钮，通过信道推送消息到服务器
     **/
    sendMessage(e) {
        // 信道当前不可用
        if (!this.tunnel || !this.tunnel.isActive()) {
            this.pushMessage(createSystemMessage('对不起你还未连接'));
            return;
        }
         if (hasDelete) {
            this.pushMessage(createSystemMessage('对不起对方已经将你删除，你不能向对方发消息'));
            return;
        }

        setTimeout(() => {
            if (this.data.inputContent && this.tunnel) {
                //this.tunnel.emit('speak', { word: this.data.inputContent });

                var date = Date.now()
                console.log(this.tunnel)
                this.tunnel.emit('speak',{
                    "targetType":"friend",
                    "targetId":this.data.friendInfo.openId,
                    "data":{
                        "sourceId":appInstance.globalData.myId,
                        "sourceName":appInstance.globalData.userInfo.nickName,
                        "sourceAvatar":appInstance.globalData.userInfo.avatarUrl,
                        "date":date,
                        "content":this.data.inputContent
                    }
                })
                this.setData({ inputContent: '' });
            }
        });
    },

})<|endoftext|>


<commit_before>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport")}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual")}, gvm);

}

function initPage() {

}
<commit_msg>Work sheet pagina debug<commit_after>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);

}

function initPage() {

}
<|endoftext|>


<commit_before>/*
 * WorkspaceToolbar.js
 *
 * Copyright (c) 2011, OSBI Ltd. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */
/**
 * The workspace toolbar, and associated actions
 */
var WorkspaceToolbar = Backbone.View.extend({
    enabled: false,
    events: {
        'click a': 'call'
    },

    initialize: function(args) {
        // Keep track of parent workspace
        this.workspace = args.workspace;

        // Maintain `this` in callbacks
        _.bindAll(this, "call", "reflect_properties", "run_query",
            "swap_axes_on_dropzones", "display_drillthrough","clicked_cell_drillthrough_export",
            "clicked_cell_drillthrough","activate_buttons", "switch_to_mdx","post_mdx_transform");

        // Redraw the toolbar to reflect properties
        this.workspace.bind('properties:loaded', this.reflect_properties);

        // Fire off workspace event
        this.workspace.trigger('workspace:toolbar:render', {
            workspace: this.workspace
        });

        // Activate buttons when a new query is created or run
        this.workspace.bind('query:new', this.activate_buttons);
        this.workspace.bind('query:result', this.activate_buttons);

    },

    activate_buttons: function(args) {
        if (args != null && args.data && args.data.cellset && args.data.cellset.length > 0 ) {
            $(args.workspace.toolbar.el).find('.button')
                .removeClass('disabled_toolbar');

            $(args.workspace.el).find("td.data").removeClass('cellhighlight').unbind('click');
            $(args.workspace.el).find(".table_mode").removeClass('on');

        } else {
            $(args.workspace.toolbar.el).find('.button')
                .addClass('disabled_toolbar').removeClass('on');
            $(args.workspace.toolbar.el)
                .find('.run,.auto,.non_empty,.toggle_fields,.toggle_sidebar,.switch_to_mdx')
                .removeClass('disabled_toolbar');
        }

        this.reflect_properties();

    },

    template: function() {
        var template = $("#template-workspace-toolbar").html() || "";
        return _.template(template)();
    },

    render: function() {
        $(this.el).html(this.template());

        return this;
    },

    call: function(event) {
        // Determine callback
        var callback = event.target.hash.replace('#', '');

        // Attempt to call callback
        if (! $(event.target).hasClass('disabled_toolbar') && this[callback]) {
            this[callback](event);
        }

        return false;
    },

    reflect_properties: function() {
        var properties = this.workspace.query.properties ?
            this.workspace.query.properties.properties : Settings.QUERY_PROPERTIES;

        // Set properties appropriately
        if (properties['saiku.olap.query.nonempty'] === 'true') {
            $(this.el).find('.non_empty').addClass('on');
        }
        if (properties['saiku.olap.query.automatic_execution'] === 'true') {
            $(this.el).find('.auto').addClass('on');
        }

        if (properties['saiku.olap.query.drillthrough'] !== 'true') {
            $(this.el).find('.drillthrough, .drillthrough_export').addClass('disabled_toolbar');
        } else {
            $(this.el).find('.non_empty').removeClass('disabled_toolbar');
        }

        if (properties['org.saiku.connection.scenario'] !== 'true') {
            $(this.el).find('.query_scenario').addClass('disabled_toolbar');
        } else {
            $(this.el).find('.query_scenario').removeClass('disabled_toolbar');
            $(this.el).find('.drillthrough, .drillthrough_export').addClass('disabled_toolbar');
        }

        if (this.workspace.query.get('formatter') !== "undefined" && this.workspace.query.get('formatter') == "flattened") {
            if (! $(this.el).find('.group_parents').hasClass('on')) {
                $(this.el).find('.group_parents').addClass('on');
            }
        }

    },

    save_query: function(event) {
        if (this.workspace.query) {
            (new SaveQuery({ query: this.workspace.query })).render().open();
        }
    },

    run_query: function(event) {
        this.workspace.query.run(true);
    },

    automatic_execution: function(event) {
        // Change property
        this.workspace.query.properties
            .toggle('saiku.olap.query.automatic_execution').update();

        // Toggle state of button
        $(event.target).toggleClass('on');
    },

    toggle_fields: function(event) {
        $(this.workspace.el).find('.workspace_fields').toggle();
    },

    toggle_sidebar: function() {
        this.workspace.toggle_sidebar();
    },

    group_parents: function(event) {
        $(event.target).toggleClass('on');
        if ($(event.target).hasClass('on')) {
            this.workspace.query.set({formatter: "flattened"})
        } else {
            this.workspace.query.set({formatter: "flat"})
        }
        this.workspace.query.run();
    },

    non_empty: function(event) {
        // Change property
        this.workspace.query.properties
            .toggle('saiku.olap.query.nonempty')
            .toggle('saiku.olap.query.nonempty.rows')
            .toggle('saiku.olap.query.nonempty.columns')
            .update();

        // Toggle state of button
        $(event.target).toggleClass('on');

        // Run query
        this.workspace.query.run();
    },

    swap_axis: function(event) {
        // Swap axes
        $(this.workspace.el).find('.workspace_results table')
            .html('
Swapping axes...
');
        Saiku.ui.block('Swapping axes...');
        this.workspace.query.action.put("/swapaxes", {
            success: this.swap_axes_on_dropzones
        });
    },

    check_modes: function(source) {
        if (typeof source === "undefined" || source == null)
            return;
        if (!$(source).hasClass('on')) {
            $(this.workspace.el).find("td.data").removeClass('cellhighlight').unbind('click');
            $(this.workspace.el).find(".table_mode").removeClass('on');
            this.workspace.query.run();
        } else {
            if ($(source).hasClass('drillthrough_export')) {
                $(this.workspace.el).find("td.data").addClass('cellhighlight').unbind('click').click(this.clicked_cell_drillthrough_export);
                $(this.workspace.el).find(".query_scenario, .drillthrough").removeClass('on');

            } else if ($(source).hasClass('drillthrough')) {
                $(this.workspace.el).find("td.data").addClass('cellhighlight').unbind('click').click(this.clicked_cell_drillthrough);
                $(this.workspace.el).find(".query_scenario, .drillthrough_export").removeClass('on');

            } else if ($(source).hasClass('query_scenario')) {
                this.workspace.query.scenario.activate();
                $(this.workspace.el).find(".drillthrough, .drillthrough_export").removeClass('on');
            }
        }

    },
    query_scenario: function(event) {
       $(event.target).toggleClass('on');
        this.check_modes($(event.target));

    },

    drillthrough: function(event) {
       $(event.target).toggleClass('on');
        this.check_modes($(event.target));
    },

    display_drillthrough: function(model, response) {
        this.workspace.table.render({ data: response });
        Saiku.ui.unblock();
    },

    export_drillthrough: function(event) {
        $(event.target).toggleClass('on');
        this.check_modes($(event.target));
    },

    clicked_cell_drillthrough_export: function(event) {
        $target = $(event.target).hasClass('data') ?
            $(event.target).find('div') : $(event.target);
        var pos = $target.attr('rel');
        (new DrillthroughModal({
            workspace: this.workspace,
            maxrows: 10000,
            title: "Drill-Through to CSV",
            action: "export",
            position: pos,
            query: this.workspace.query
        })).open();

    },

    clicked_cell_drillthrough: function(event) {
        $target = $(event.target).hasClass('data') ?
            $(event.target).find('div') : $(event.target);
        var pos = $target.attr('rel');
        (new DrillthroughModal({
            workspace: this.workspace,
            maxrows: 200,
            title: "Drill-Through",
            action: "table",
            success: this.display_drillthrough,
            position: pos,
            query: this.workspace.query
        })).open();

    },

    swap_axes_on_dropzones: function() {
        $columns = $(this.workspace.drop_zones.el).find('.columns')
            .children()
            .detach();
        $rows = $(this.workspace.drop_zones.el).find('.rows')
            .children()
            .detach();

        $(this.workspace.drop_zones.el).find('.columns').append($rows);
        $(this.workspace.drop_zones.el).find('.rows').append($columns);

        this.workspace.query.run();
        Saiku.ui.unblock();
    },

    show_mdx: function(event) {
        this.workspace.query.action.get("/mdx", {
            success: function(model, response) {
                (new MDXModal({ mdx: response.mdx })).render().open();
            }
        });
    },

    export_xls: function(event) {
        window.location = Settings.REST_URL +
            Saiku.session.username + "/query/" +
            this.workspace.query.id + "/export/xls";
    },

    export_csv: function(event) {
        window.location = Settings.REST_URL +
            Saiku.session.username + "/query/" +
            this.workspace.query.id + "/export/csv";
    },

    switch_to_mdx: function(event) {
        $(this.workspace.el).find('.workspace_fields').hide();
        $(this.el).find('.auto, ,.toggle_fields, .query_scenario, .buckets, .non_empty, .swap_axis, .mdx, .switch_to_mdx').parent().hide();

        $(this.el).find('.run').attr('href','#run_mdx');
        $(this.el).find('.run, .save').removeClass('disabled_toolbar');

        if (Settings.MODE != "view" && Settings.MODE != "table") {
            $(this.workspace.el).find('.workspace_editor .mdx_input').removeClass('hide');
            $(this.workspace.el).find('.mdx_input').width($(this.el).width()-20);
        }

        if (this.workspace.dimension_list && this.workspace.measure_list) {
            $(this.workspace.dimension_list.el).find('ul li a').css({fontWeight: "normal"});
            $(this.workspace.measure_list.el).find('ul li a').css({fontWeight: "normal"});
            $(this.workspace.dimension_list.el).find('.measure,.dimension').parent('li').draggable('enable');
            $(this.workspace.measure_list.el).find('.measure,.dimension').parent('li').draggable('enable');
        }
        this.activate_buttons({ workspace: this.workspace });
        $(this.workspace.toolbar.el)
                .find('.run')
                .removeClass('disabled_toolbar');

        $(this.workspace.table.el).empty();
        this.workspace.adjust();
        this.post_mdx_transform();

    },

    post_mdx_transform: function() {
        var self = this;

        var transformed = function() {
            self.workspace.query.set({type:'MDX', formatter: "flat" });
            $(self.el).find('.group_parents').removeClass('on');
        };

        this.workspace.query.action.get("/mdx", {
            success: function(model, response) {
                $(self.workspace.el).find(".mdx_input").val(response.mdx);
                self.workspace.query.action.post("/qm2mdx", { success: transformed } );

            }
        });

    },

    run_mdx: function(event) {
        var mdx = $(this.workspace.el).find(".mdx_input").val();
        this.workspace.query.run(true, mdx);
    },

    explain_query: function(event) {
        var self = this;
        var explained = function(model, args) {

            var explainPlan = "<textarea style='width: " + ($("body").width() - 165) + "px;height:" + ($("body").height() - 175) + "px;'>";
            if (args != null && args.error != null) {
                explainPlan += args.error;
            } else if (args.cellset && args.cellset.length === 0) {
                explainPlan += "Empty explain plan!";
            } else {
                explainPlan += args.cellset[1][0].value;
            }
            explainPlan += "</textarea>";

            Saiku.ui.unblock();
            var html =  explainPlan;
            var html = '

'
                    + "
Explain Plan
"
                    + "
" + explainPlan + "
"
                    + '

';

            $.fancybox(html
                ,
                {
                'autoDimensions'    : false,
                'autoScale'         : false,
                'height'            :  ($("body").height() - 100),
                'width'             :  ($("body").width() - 100),
                'transitionIn'      : 'none',
                'transitionOut'     : 'none'
                }
            );
        };

        self.workspace.query.action.get("/explain", { success: explained } );

        return false;

    }
});
<commit_msg>fix #232 - show explain plan for query<commit_after>/*
 * WorkspaceToolbar.js
 *
 * Copyright (c) 2011, OSBI Ltd. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */
/**
 * The workspace toolbar, and associated actions
 */
var WorkspaceToolbar = Backbone.View.extend({
    enabled: false,
    events: {
        'click a': 'call'
    },

    initialize: function(args) {
        // Keep track of parent workspace
        this.workspace = args.workspace;

        // Maintain `this` in callbacks
        _.bindAll(this, "call", "reflect_properties", "run_query",
            "swap_axes_on_dropzones", "display_drillthrough","clicked_cell_drillthrough_export",
            "clicked_cell_drillthrough","activate_buttons", "switch_to_mdx","post_mdx_transform");

        // Redraw the toolbar to reflect properties
        this.workspace.bind('properties:loaded', this.reflect_properties);

        // Fire off workspace event
        this.workspace.trigger('workspace:toolbar:render', {
            workspace: this.workspace
        });

        // Activate buttons when a new query is created or run
        this.workspace.bind('query:new', this.activate_buttons);
        this.workspace.bind('query:result', this.activate_buttons);

    },

    activate_buttons: function(args) {
        if (args != null && args.data && args.data.cellset && args.data.cellset.length > 0 ) {
            $(args.workspace.toolbar.el).find('.button')
                .removeClass('disabled_toolbar');

            $(args.workspace.el).find("td.data").removeClass('cellhighlight').unbind('click');
            $(args.workspace.el).find(".table_mode").removeClass('on');

        } else {
            $(args.workspace.toolbar.el).find('.button')
                .addClass('disabled_toolbar').removeClass('on');
            $(args.workspace.toolbar.el)
                .find('.run,.auto,.non_empty,.toggle_fields,.toggle_sidebar,.switch_to_mdx')
                .removeClass('disabled_toolbar');
        }

        this.reflect_properties();

    },

    template: function() {
        var template = $("#template-workspace-toolbar").html() || "";
        return _.template(template)();
    },

    render: function() {
        $(this.el).html(this.template());

        return this;
    },

    call: function(event) {
        // Determine callback
        var callback = event.target.hash.replace('#', '');

        // Attempt to call callback
        if (! $(event.target).hasClass('disabled_toolbar') && this[callback]) {
            this[callback](event);
        }

        return false;
    },

    reflect_properties: function() {
        var properties = this.workspace.query.properties ?
            this.workspace.query.properties.properties : Settings.QUERY_PROPERTIES;

        // Set properties appropriately
        if (properties['saiku.olap.query.nonempty'] === 'true') {
            $(this.el).find('.non_empty').addClass('on');
        }
        if (properties['saiku.olap.query.automatic_execution'] === 'true') {
            $(this.el).find('.auto').addClass('on');
        }

        if (properties['saiku.olap.query.drillthrough'] !== 'true') {
            $(this.el).find('.drillthrough, .drillthrough_export').addClass('disabled_toolbar');
        } else {
            $(this.el).find('.non_empty').removeClass('disabled_toolbar');
        }

        if (properties['org.saiku.query.explain'] !== 'true') {
            $(this.el).find('.explain_query').addClass('disabled_toolbar');
        }

        if (properties['org.saiku.connection.scenario'] !== 'true') {
            $(this.el).find('.query_scenario').addClass('disabled_toolbar');
        } else {
            $(this.el).find('.query_scenario').removeClass('disabled_toolbar');
            $(this.el).find('.drillthrough, .drillthrough_export').addClass('disabled_toolbar');
        }

        if (this.workspace.query.get('formatter') !== "undefined" && this.workspace.query.get('formatter') == "flattened") {
            if (! $(this.el).find('.group_parents').hasClass('on')) {
                $(this.el).find('.group_parents').addClass('on');
            }
        }

    },

    save_query: function(event) {
        if (this.workspace.query) {
            (new SaveQuery({ query: this.workspace.query })).render().open();
        }
    },

    run_query: function(event) {
        this.workspace.query.run(true);
    },

    automatic_execution: function(event) {
        // Change property
        this.workspace.query.properties
            .toggle('saiku.olap.query.automatic_execution').update();

        // Toggle state of button
        $(event.target).toggleClass('on');
    },

    toggle_fields: function(event) {
        $(this.workspace.el).find('.workspace_fields').toggle();
    },

    toggle_sidebar: function() {
        this.workspace.toggle_sidebar();
    },

    group_parents: function(event) {
        $(event.target).toggleClass('on');
        if ($(event.target).hasClass('on')) {
            this.workspace.query.set({formatter: "flattened"})
        } else {
            this.workspace.query.set({formatter: "flat"})
        }
        this.workspace.query.run();
    },

    non_empty: function(event) {
        // Change property
        this.workspace.query.properties
            .toggle('saiku.olap.query.nonempty')
            .toggle('saiku.olap.query.nonempty.rows')
            .toggle('saiku.olap.query.nonempty.columns')
            .update();

        // Toggle state of button
        $(event.target).toggleClass('on');

        // Run query
        this.workspace.query.run();
    },

    swap_axis: function(event) {
        // Swap axes
        $(this.workspace.el).find('.workspace_results table')
            .html('
Swapping axes...
');
        Saiku.ui.block('Swapping axes...');
        this.workspace.query.action.put("/swapaxes", {
            success: this.swap_axes_on_dropzones
        });
    },

    check_modes: function(source) {
        if (typeof source === "undefined" || source == null)
            return;
        if (!$(source).hasClass('on')) {
            $(this.workspace.el).find("td.data").removeClass('cellhighlight').unbind('click');
            $(this.workspace.el).find(".table_mode").removeClass('on');
            this.workspace.query.run();
        } else {
            if ($(source).hasClass('drillthrough_export')) {
                $(this.workspace.el).find("td.data").addClass('cellhighlight').unbind('click').click(this.clicked_cell_drillthrough_export);
                $(this.workspace.el).find(".query_scenario, .drillthrough").removeClass('on');

            } else if ($(source).hasClass('drillthrough')) {
                $(this.workspace.el).find("td.data").addClass('cellhighlight').unbind('click').click(this.clicked_cell_drillthrough);
                $(this.workspace.el).find(".query_scenario, .drillthrough_export").removeClass('on');

            } else if ($(source).hasClass('query_scenario')) {
                this.workspace.query.scenario.activate();
                $(this.workspace.el).find(".drillthrough, .drillthrough_export").removeClass('on');
            }
        }

    },
    query_scenario: function(event) {
       $(event.target).toggleClass('on');
        this.check_modes($(event.target));

    },

    drillthrough: function(event) {
       $(event.target).toggleClass('on');
        this.check_modes($(event.target));
    },

    display_drillthrough: function(model, response) {
        this.workspace.table.render({ data: response });
        Saiku.ui.unblock();
    },

    export_drillthrough: function(event) {
        $(event.target).toggleClass('on');
        this.check_modes($(event.target));
    },

    clicked_cell_drillthrough_export: function(event) {
        $target = $(event.target).hasClass('data') ?
            $(event.target).find('div') : $(event.target);
        var pos = $target.attr('rel');
        (new DrillthroughModal({
            workspace: this.workspace,
            maxrows: 10000,
            title: "Drill-Through to CSV",
            action: "export",
            position: pos,
            query: this.workspace.query
        })).open();

    },

    clicked_cell_drillthrough: function(event) {
        $target = $(event.target).hasClass('data') ?
            $(event.target).find('div') : $(event.target);
        var pos = $target.attr('rel');
        (new DrillthroughModal({
            workspace: this.workspace,
            maxrows: 200,
            title: "Drill-Through",
            action: "table",
            success: this.display_drillthrough,
            position: pos,
            query: this.workspace.query
        })).open();

    },

    swap_axes_on_dropzones: function() {
        $columns = $(this.workspace.drop_zones.el).find('.columns')
            .children()
            .detach();
        $rows = $(this.workspace.drop_zones.el).find('.rows')
            .children()
            .detach();

        $(this.workspace.drop_zones.el).find('.columns').append($rows);
        $(this.workspace.drop_zones.el).find('.rows').append($columns);

        this.workspace.query.run();
        Saiku.ui.unblock();
    },

    show_mdx: function(event) {
        this.workspace.query.action.get("/mdx", {
            success: function(model, response) {
                (new MDXModal({ mdx: response.mdx })).render().open();
            }
        });
    },

    export_xls: function(event) {
        window.location = Settings.REST_URL +
            Saiku.session.username + "/query/" +
            this.workspace.query.id + "/export/xls";
    },

    export_csv: function(event) {
        window.location = Settings.REST_URL +
            Saiku.session.username + "/query/" +
            this.workspace.query.id + "/export/csv";
    },

    switch_to_mdx: function(event) {
        $(this.workspace.el).find('.workspace_fields').hide();
        $(this.el).find('.auto, ,.toggle_fields, .query_scenario, .buckets, .non_empty, .swap_axis, .mdx, .switch_to_mdx').parent().hide();

        $(this.el).find('.run').attr('href','#run_mdx');
        $(this.el).find('.run, .save').removeClass('disabled_toolbar');

        if (Settings.MODE != "view" && Settings.MODE != "table") {
            $(this.workspace.el).find('.workspace_editor .mdx_input').removeClass('hide');
            $(this.workspace.el).find('.mdx_input').width($(this.el).width()-20);
        }

        if (this.workspace.dimension_list && this.workspace.measure_list) {
            $(this.workspace.dimension_list.el).find('ul li a').css({fontWeight: "normal"});
            $(this.workspace.measure_list.el).find('ul li a').css({fontWeight: "normal"});
            $(this.workspace.dimension_list.el).find('.measure,.dimension').parent('li').draggable('enable');
            $(this.workspace.measure_list.el).find('.measure,.dimension').parent('li').draggable('enable');
        }
        this.activate_buttons({ workspace: this.workspace });
        $(this.workspace.toolbar.el)
                .find('.run')
                .removeClass('disabled_toolbar');

        $(this.workspace.table.el).empty();
        this.workspace.adjust();
        this.post_mdx_transform();

    },

    post_mdx_transform: function() {
        var self = this;

        var transformed = function() {
            self.workspace.query.set({type:'MDX', formatter: "flat" });
            $(self.el).find('.group_parents').removeClass('on');
        };

        this.workspace.query.action.get("/mdx", {
            success: function(model, response) {
                $(self.workspace.el).find(".mdx_input").val(response.mdx);
                self.workspace.query.action.post("/qm2mdx", { success: transformed } );

            }
        });

    },

    run_mdx: function(event) {
        var mdx = $(this.workspace.el).find(".mdx_input").val();
        this.workspace.query.run(true, mdx);
    },

    explain_query: function(event) {
        var self = this;
        var explained = function(model, args) {

            var explainPlan = "<textarea style='width: " + ($("body").width() - 165) + "px;height:" + ($("body").height() - 175) + "px;'>";
            if (args != null && args.error != null) {
                explainPlan += args.error;
            } else if (args.cellset && args.cellset.length === 0) {
                explainPlan += "Empty explain plan!";
            } else {
                explainPlan += args.cellset[1][0].value;
            }
            explainPlan += "</textarea>";

            Saiku.ui.unblock();
            var html =  explainPlan;
            var html = '

'
                    + "
Explain Plan
"
                    + "
" + explainPlan + "
"
                    + '

';

            $.fancybox(html
                ,
                {
                'autoDimensions'    : false,
                'autoScale'         : false,
                'height'            :  ($("body").height() - 100),
                'width'             :  ($("body").width() - 100),
                'transitionIn'      : 'none',
                'transitionOut'     : 'none'
                }
            );
        };

        self.workspace.query.action.get("/explain", { success: explained } );

        return false;

    }
});
<|endoftext|>


<commit_before>

/**
selection population upload from lists
and files. Run prediction model on uploaded selection population
and display output.

Isaak Y Tecle
iyt2@cornell.edu
*/

JSAN.use("jquery.cookie");
JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");

jQuery(document).ready( function() {
        var list = new CXGN.List();
        var listMenu = list.listSelect("prediction_genotypes");

        jQuery("#prediction_genotypes_list").append(listMenu);

    });

jQuery(document).ready( function() {
        var listId;
        jQuery("#prediction_genotypes_list_select").change(function() {

                listId = jQuery(this).find("option:selected").val();

                if(listId) {
                    jQuery("#prediction_genotypes_list_upload").click(function() {
                            //alert('get list: ' + listId);
                            loadGenotypesList(listId);
                        });
                }
            });
    });

function getGenotypesList(listId) {

    var list = new CXGN.List();
    var genotypesList;

    if (! listId == "") {
        genotypesList = list.getList(listId);
    }

    var listName = list.listNameById(listId);

    return {'name'   : listName,
            'list'   : genotypesList
            };
}

function loadGenotypesList(listId) {

    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( list.length === 0) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {

        jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
        jQuery.blockUI({message: 'Please wait..'});

        list = JSON.stringify(list);

        jQuery.ajax({
                type: 'POST',
                    dataType: 'json',
                    data: {id: listId, 'name': listName, 'list': list},
                    url: '/solgs/upload/prediction/genotypes/list',

                    success: function(response) {

                    if (response.status == 'success') {

                        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

                        if (uploadedSelPops == false) {

                            uploadedSelPops = getUserUploadedSelPop(listId);
                            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();

                        }
                        else {

                            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
                            var listIdArg = '\'' + listId +'\'';
                            var listSource = '\'from_db\'';

                            var addRow = '
'
                                +''
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '
';

                            var tdId = '#list_prediction_output_' + listId;
                            var addedRow = jQuery(tdId).doesExist();

                            if (addedRow == false) {
                                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);

                            }
                        }
                        jQuery.unblockUI();

                    } else {

                    alert("Error occured while uploading the list of selection genotypes.");
                    jQuery.unblockUI();
                    }

                }
            });
    }
}

jQuery.fn.doesExist = function(){
        return jQuery(this).length > 0;
 };

function getModelId () {

    var modelId;
    var modelIdExists = jQuery("#model_id").doesExist();
    var comboPopsIdExists = jQuery("#combo_pops_id").doesExist();

    if ( modelIdExists == true ) {
        modelId = jQuery("#model_id").val();
    }
    else if ( comboPopsIdExists == true ) {
        modelId = jQuery("#combo_pops_id").val();
    }

    return modelId;

}

function getTraitId () {

    var traitId;
    var traitIdExists = jQuery("#trait_id").doesExist();

    if ( traitIdExists == true ) {
        traitId = jQuery("#trait_id").val();
    }

    return traitId;

}

function getUserUploadedSelPop (listId) {
    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url        =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg  = '\'' + listId +'\'';
    var listSource = '\'from_db\'';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + ''
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}

function loadPredictionOutput (url, listId, listSource) {

    var traitId        = getTraitId();
    var modelId        = getModelId();

    //  alert('loadPredictionOutput listId, listSource, url: ' + listId +" " + listSource + " " + url);
    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
    jQuery.blockUI({message: 'Please wait..'});

    jQuery.ajax({
            type: 'POST',
                url: url,
                dataType: 'json',
                data: {
                       'uploaded_prediction': 1,
                       'trait_id': traitId,
                       'model_id': modelId,
                       'prediction_id': listId,
                       'list_source': listSource,
                      },

                success: function (response) {

                if (response.status == 'success') {
                    var tdId = '#list_prediction_output_' + listId;
                    jQuery(tdId).html(response.output);
                    jQuery.unblockUI();
                }
                else {
                    alert('Error occured calculating GEBVs for the list of selection genotypes.');
                    jQuery.unblockUI();
                }
            },
                error: function(response) {
                alert('error: ' + res.responseText);

            }
        });

}

jQuery(function () {
        var url = '/solgs/upload/prediction/genotypes/file';

        jQuery('#fileupload').fileupload({
                url: url,
                    dataType: 'json',
                    submit: function(e, data) {
                    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
                    jQuery.blockUI({message: 'Please wait..'});
                },
                    done: function (e, data) {
                    jQuery.each(data.result.files, function (index, file) {

                            getCheckValue(file.name);

                        });

                    jQuery.unblockUI();

                }
            });
    });

function getCheckValue(fileName) {

    jQuery.ajax({
            type: 'POST',
                url: '/solgs/generate/checkvalue',
                dataType: 'json',
                data: {'file_name': fileName},

                success: function (response) {

                if (response.status == 'success') {

                    var checkValue = response.check_value;
                    jQuery("#check_value").empty();
                    jQuery("#check_value").val(checkValue);

                    loadListFromFile(fileName, checkValue);

                }

            }
        });

}

function loadListFromFile(fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( ! fileName ) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {
        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

        if (uploadedSelPops == false) {

            uploadedSelPops = getUserUploadedFile(fileName, listId);
            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();
        }
        else {

            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
            var listIdArg = '\'' + listId +'\'';
            var listSource = '\'from_file \'';

            var addRow = '
'
                +''
                + listName + ''
                + '	'
                + ''
                + ''
                + '[ Predict GEBVs ]'+ ''
                + '
';

            var tdId = '#list_prediction_output_' + listId;
            var addedRow = jQuery(tdId).doesExist();

            if (addedRow == false) {
                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);
            }
        }
    }

}

function getUserUploadedFile (fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg = '\'' + listId +'\'';
    var listSource = '\'from_file \'';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + ''
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}
<commit_msg>add user predicted selection list to selection index list of populations<commit_after>

/**
selection population upload from lists
and files. Run prediction model on uploaded selection population
and display output.

Isaak Y Tecle
iyt2@cornell.edu
*/

JSAN.use("jquery.cookie");
JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");

jQuery(document).ready( function() {
        var list = new CXGN.List();
        var listMenu = list.listSelect("prediction_genotypes");

        jQuery("#prediction_genotypes_list").append(listMenu);

    });

jQuery(document).ready( function() {
        var listId;
        jQuery("#prediction_genotypes_list_select").change(function() {

                listId = jQuery(this).find("option:selected").val();

                if(listId) {
                    jQuery("#prediction_genotypes_list_upload").click(function() {
                            //alert('get list: ' + listId);
                            loadGenotypesList(listId);
                        });
                }
            });
    });

function getGenotypesList(listId) {

    var list = new CXGN.List();
    var genotypesList;

    if (! listId == "") {
        genotypesList = list.getList(listId);
    }

    var listName = list.listNameById(listId);

    return {'name'   : listName,
            'list'   : genotypesList
            };
}

function loadGenotypesList(listId) {

    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( list.length === 0) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {

        jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
        jQuery.blockUI({message: 'Please wait..'});

        list = JSON.stringify(list);

        jQuery.ajax({
                type: 'POST',
                    dataType: 'json',
                    data: {id: listId, 'name': listName, 'list': list},
                    url: '/solgs/upload/prediction/genotypes/list',

                    success: function(response) {

                    if (response.status == 'success') {

                        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

                        if (uploadedSelPops == false) {

                            uploadedSelPops = getUserUploadedSelPop(listId);
                            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();

                        }
                        else {

                            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
                            var listIdArg = '\'' + listId +'\'';
                            var listSource = '\'from_db\'';

                            var addRow = '
'
                                +''
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '
';

                            var tdId = '#list_prediction_output_' + listId;
                            var addedRow = jQuery(tdId).doesExist();

                            if (addedRow == false) {
                                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);

                            }
                        }
                        jQuery.unblockUI();

                    } else {

                    alert("Error occured while uploading the list of selection genotypes.");
                    jQuery.unblockUI();
                    }

                }
            });
    }
}

jQuery.fn.doesExist = function(){
        return jQuery(this).length > 0;
 };

function getModelId () {

    var modelId;
    var modelIdExists = jQuery("#model_id").doesExist();
    var comboPopsIdExists = jQuery("#combo_pops_id").doesExist();

    if ( modelIdExists == true ) {
        modelId = jQuery("#model_id").val();
    }
    else if ( comboPopsIdExists == true ) {
        modelId = jQuery("#combo_pops_id").val();
    }

    return modelId;

}

function getTraitId () {

    var traitId;
    var traitIdExists = jQuery("#trait_id").doesExist();

    if ( traitIdExists == true ) {
        traitId = jQuery("#trait_id").val();
    }

    return traitId;

}

function getUserUploadedSelPop (listId) {
    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url         =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg   = '\'' + listId +'\'';
    var listSource  = '\'from_db\'';
    var popIdName   = {id : 'uploaded_' + listId, name: listName,};
    popIdName       = JSON.stringify(popIdName);
    var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + '' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}

function loadPredictionOutput (url, listId, listSource) {

    var traitId        = getTraitId();
    var modelId        = getModelId();

    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
    jQuery.blockUI({message: 'Please wait..'});

    jQuery.ajax({
            type: 'POST',
                url: url,
                dataType: 'json',
                data: {
                       'uploaded_prediction': 1,
                       'trait_id': traitId,
                       'model_id': modelId,
                       'prediction_id': listId,
                       'list_source': listSource,
                      },

                success: function (response) {

                if (response.status == 'success') {
                    var tdId = '#list_prediction_output_' + listId;
                    jQuery(tdId).html(response.output);

                    var popsList = listSelPopulationsUploaded();

                    jQuery("#select_a_population_div").html('');

                    selectAPopulation(modelId,  popsList);

                    jQuery.unblockUI();

                }
                else {
                    alert('Error occured calculating GEBVs for the list of selection genotypes.');
                    jQuery.unblockUI();
                }
            },
                error: function(response) {
                alert('error: ' + res.responseText);

            }
        });

}

jQuery(function () {
        var url = '/solgs/upload/prediction/genotypes/file';

        jQuery('#fileupload').fileupload({
                url: url,
                    dataType: 'json',
                    submit: function(e, data) {
                    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
                    jQuery.blockUI({message: 'Please wait..'});
                },
                    done: function (e, data) {
                    jQuery.each(data.result.files, function (index, file) {

                            getCheckValue(file.name);

                        });

                    jQuery.unblockUI();

                }
            });
    });

function getCheckValue(fileName) {

    jQuery.ajax({
            type: 'POST',
                url: '/solgs/generate/checkvalue',
                dataType: 'json',
                data: {'file_name': fileName},

                success: function (response) {

                if (response.status == 'success') {

                    var checkValue = response.check_value;
                    jQuery("#check_value").empty();
                    jQuery("#check_value").val(checkValue);

                    loadListFromFile(fileName, checkValue);

                }

            }
        });

}

function loadListFromFile(fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( ! fileName ) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {
        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

        if (uploadedSelPops == false) {

            uploadedSelPops = getUserUploadedFile(fileName, listId);
            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();
        }
        else {

            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
            var listIdArg = '\'' + listId +'\'';
            var listSource = '\'from_file \'';
            var popIdName   = {'id' : 'uploaded_' + listId, 'name': listName};
            var hiddenInput =  '<input type="hidden" value=\"' + popIdName + '\">';

            var addRow = '
'
                +'' + '<data>'+ hiddenInput + '</data>' +
                + listName + ''
                + '	'
                + ''
                + ''
                + '[ Predict GEBVs ]'+ ''
                + '
';

            var tdId = '#list_prediction_output_' + listId;
            var addedRow = jQuery(tdId).doesExist();

            if (addedRow == false) {
                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);
            }
        }
    }

}

function getUserUploadedFile (fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg = '\'' + listId +'\'';
    var listSource = '\'from_file \'';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + ''
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}
<|endoftext|>