<commit_before>load("build/underscore.js");
var _ = this._;

load("steal/rhino/rhino.js");
steal('can/test/configuration.js',
	'steal/build/pluginify',
	'steal/build/amdify',
	'steal/generate/ejs.js',
	'can/build/settings.js',
function (testConfig, pluginify, amdify, EJS, libs) {
	// Use with ./js can/build/dist.js <outputfolder> <version> <library1> <library2>
	var version = _args[1] || 'edge';
	var libraries = _args[2] ? _args.slice(2) : _.keys(libs);
	var outFolder = (_args[0] || 'can/dist/') + version + '/';

	/**
	 * Build CanJS and test files for a given library
	 *
	 * @param lib
	 */
	var buildLibrary = function (lib) {
		var options = libs[lib],
			outFile = outFolder + '/can.' + lib,
			// testFile = testFolder + lib + '.html',
			buildFile = "can/build/make/" + lib + ".js",
			defaults = {
				out : outFile + '.js',
				onefunc : true,
				compress : false,
				skipAll : true
			};

		console.log('Building ' + lib + ' ' + version + ' to ' + outFile);
		steal.build.pluginify(buildFile, _.extend(defaults, options));
		steal.build.pluginify(buildFile, _.extend(defaults, options, {
			compress : true,
			out : outFile + '.min.js'
		}));

		// console.log('Creating distributable test HTML file ' + testFile);
		// render('can/build/templates/test.html.ejs', testFile, {
		//	name : testConfig[lib].name,
		//	dist : testConfig[lib].dist,
		//	version : version,
		//	type : lib
		// });
		// new steal.File('can/build/templates/qunit.js').copyTo(testFolder + '/qunit.js');
		// new steal.File('can/build/templates/qunit.css').copyTo(testFolder + '/qunit.css');
	};
	/**
	 * Build can.jquery-all.js with all plugins.
	 */
	var buildjQueryAll = function() {
		var options = libs.jquery,
			outFile = outFolder + '/can.jquery-all',
			buildFile = "can/build/make/all.js",
			defaults = {
				out : outFile + '.js',
				onefunc : true,
				compress : false,
				skipAll : true
			};

		console.log('Building ' + outFile + ' ' + version + ' to ' + outFile);
		steal.build.pluginify(buildFile, _.extend(defaults, options));
		steal.build.pluginify(buildFile, _.extend(defaults, options, {
			compress : true,
			out : outFile + '.min.js'
		}));
	};
	/**
	 * Build the AMD module distributable
	 */
	var buildAmd = function() {
		var excludes = [ "can/build/make/amd.js", "can/util/util.js" ];
		_.each(_.values(libs), function(val) {
			excludes = excludes.concat(val.exclude);
		});
		steal.build.amdify('can/build/make/amd.js', {
			out: outFolder + '/amd',
			exclude: excludes,
			map : {
				'can/util' : 'can/util/library'
			}
		});
	};

	steal.File(outFolder).mkdirs();

	_.each(libraries, buildLibrary);
	buildjQueryAll();
	buildAmd();
});
<commit_msg>Build can.jquery-all without onefunc. Closes #182<commit_after>load("build/underscore.js");
var _ = this._;

load("steal/rhino/rhino.js");
steal('can/test/configuration.js',
	'steal/build/pluginify',
	'steal/build/amdify',
	'steal/generate/ejs.js',
	'can/build/settings.js',
function (testConfig, pluginify, amdify, EJS, libs) {
	// Use with ./js can/build/dist.js <outputfolder> <version> <library1> <library2>
	var version = _args[1] || 'edge';
	var libraries = _args[2] ? _args.slice(2) : _.keys(libs);
	var outFolder = (_args[0] || 'can/dist/') + version + '/';

	/**
	 * Build CanJS and test files for a given library
	 *
	 * @param lib
	 */
	var buildLibrary = function (lib) {
		var options = libs[lib],
			outFile = outFolder + '/can.' + lib,
			// testFile = testFolder + lib + '.html',
			buildFile = "can/build/make/" + lib + ".js",
			defaults = {
				out : outFile + '.js',
				onefunc : true,
				compress : false,
				skipAll : true
			};

		console.log('Building ' + lib + ' ' + version + ' to ' + outFile);
		steal.build.pluginify(buildFile, _.extend(defaults, options));
		steal.build.pluginify(buildFile, _.extend(defaults, options, {
			compress : true,
			out : outFile + '.min.js'
		}));
	};
	/*
	var generateTestFiles = function() {
		_.each(libs, function(lib) {

		});
		console.log('Creating distributable test HTML file ' + testFile);
		render('can/build/templates/test.html.ejs', testFile, {
			name : testConfig[lib].name,
			dist : testConfig[lib].dist,
			version : version,
			type : lib
		});
		new steal.File('can/build/templates/qunit.js').copyTo(testFolder + '/qunit.js');
		new steal.File('can/build/templates/qunit.css').copyTo(testFolder + '/qunit.css');
	}
	*/
	/**
	 * Build can.jquery-all.js with all plugins.
	 */
	var buildjQueryAll = function() {
		var options = libs.jquery,
			outFile = outFolder + '/can.jquery-all',
			buildFile = "can/build/make/all.js",
			defaults = {
				out : outFile + '.js',
				// onefunc : true,
				shim : {
					jquery : 'jQuery',
					'jquery/jquery.js' : 'jQuery'
				},
				compress : false,
				skipAll : true
			};

		console.log('Building ' + outFile + ' ' + version + ' to ' + outFile);
		steal.build.pluginify(buildFile, _.extend(defaults, options));
		steal.build.pluginify(buildFile, _.extend(defaults, options, {
			compress : true,
			out : outFile + '.min.js'
		}));
	};
	/**
	 * Build the AMD module distributable
	 */
	var buildAmd = function() {
		var excludes = [ "can/build/make/amd.js", "can/util/util.js" ];
		_.each(_.values(libs), function(val) {
			excludes = excludes.concat(val.exclude);
		});
		steal.build.amdify('can/build/make/amd.js', {
			out: outFolder + '/amd',
			exclude: excludes,
			map : {
				'can/util' : 'can/util/library'
			}
		});
	};

	steal.File(outFolder).mkdirs();

	_.each(libraries, buildLibrary);
	buildjQueryAll();
	buildAmd();
});
<|endoftext|>


<commit_before>import {CREATE_NETWORK_CLASS, CREATE_NETWORK_MODAL} from "./constants";
import { queryNetworkDatabase } from "./api/grnsight-api";
import { grnState } from "./grnstate";
import { updateApp } from "./update-app";

export const createNetwork = function () {
    const createCustomWorkbook = () => {
        let genes = []
        let genesByIndex = {}
        let links = []
        let positiveWeights = []
        let i = 0
        for (let gene in grnState.customWorkbook.genes){
            genes.push({name : grnState.customWorkbook.genes[gene]});
            genesByIndex[gene] = i;
            i++;
        }
        console.log(genesByIndex)
        console.log(genes)
        console.log(grnState.customWorkbook.genes)
        for (let regulator in grnState.customWorkbook.links) {
            console.log("regulator: ",regulator, ", ",  genesByIndex[regulator])
            console.log("target", grnState.customWorkbook.links[regulator], ", ",
            genesByIndex[grnState.customWorkbook.links[regulator]]
            )

            links.push({
                source: genesByIndex[regulator],
                target: genesByIndex[grnState.customWorkbook.links[regulator]],
                value:1,
                type:"arrowhead",
                stroke: "black"
            });
            positiveWeights.push(1);
        }
        return  {
            genes,
            links,
            errors: [],
            warnings: [],
            positiveWeights,
            negativeWeights: [],
            sheetType: "unweighted",
            network: {
                genes,
                links,
                errors: [],
                warnings: [],
                positiveWeights,
            },
            meta: {
                data: {
                    species: "Saccharomyces cerevisiae",
                    taxon_id: 559292
                }
            },
            test: {
            },
            expression: {
            }
        };

    }
    const createHTMLforForm = (sources) => {
        let result =  `

Create Network

            Network Source
            <select class=\'network-dropdown\' id=\'network-source\'>
            `;
        if (sources.length !== 1) {
            result += `<option value=\'none\' selected=\'true\' disabled>Select Network Source</option> `
            for (let source in sources) {
                result += `
                            <option value=\'${sources[source]}\'>${sources[source]}</option>
                `;
            }
        } else {
            result += `
                        <option value=\'${sources[0]}\' selected=\'true\' disabled hidden>${sources[0]}</option>
            `;
        }
        result += `</select>

Warning: changing network source will remove all current genes in network

            <form id=\'getNetworkGenesForm\'>
                Select genes
                <input type=\'text\' id=\'network-search-bar\' name=\'network-search-bar\'></input>
                <button id=\'enter-search\' type=\'submit\' class=\'search-button\'>

                </button>
            </form>

Added genes go here! Click on a gene to remove it

        <button id=\'submit-network\'>Create Network</input>

        `;
        return result;
    };
    const createGeneButtons = function () {
        let result =  `

Added genes go below! Click on a gene to remove it.

        `
        for (let gene in grnState.customWorkbook.genes) {
            result += `

                        ${grnState.customWorkbook.genes[gene]}

                        (${gene})

            `
        }

        result += "

"
        return result
    };
    const displayCurrentGenes = function () {
        $("#selected-genes").remove();
        $("#selected-genes-container").append(createGeneButtons());
        for (let gene in grnState.customWorkbook.genes) {
            console.log(gene);
            $(`#${gene}`).on("click", (ev) => {
                ev.stopPropagation();
                $(`#${gene}`).remove();
                delete grnState.customWorkbook.genes[gene];
            });
        }
    };

    const addGene = function() {
        console.log("Adding Gene")
        let gene = `${$("#network-search-bar").val()}`.toUpperCase();
        $("#network-search-bar").val("");
        let source = grnState.customWorkbook.source
        let headers = {
            type:"NetworkGeneFromSource",
            info: {
                gene: gene,
                source:grnState.customWorkbook.sources[source].source,
                timestamp:grnState.customWorkbook.sources[source].timestamp.substring(0,19).replace("T", " ")
            }
        }
        console.log("Adding Gene headers:")
        console.log(headers)
        queryNetworkDatabase(headers).then(function (response) {
            console.log("recieved response")
            if (response.geneId !== null && response.displayGeneId !==null) {
            grnState.customWorkbook.genes[response.geneId] = response.displayGeneId;
            displayCurrentGenes();
            }
            else {
                alert (`Gene: ${gene} was not found in this database. Please check for any typos and try again.`);
            }
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
    };

    const displayCreateNetworkModal = function () {
        $("#createNetworkFormContainer").remove();
        grnState.customWorkbook = {
            genes : {},
            source : null
        };
    // get sources from database
        queryNetworkDatabase({type:"NetworkSource", info:null}).then(function (response) {
            $("#creatNetworkQuestions-container").append(createHTMLforForm(Object.keys(response.sources)));
            grnState.customWorkbook.sources = response.sources;
            grnState.customWorkbook.source = Object.keys(response.sources).length === 1? Object.keys(response.sources)[0] : null;
            console.log(grnState.customWorkbook)
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        $(CREATE_NETWORK_MODAL).modal("show");
    };

    const performNetworkCreation = function () {
        return function () {
            displayCreateNetworkModal();
        };
    };

    $("body").on("click", CREATE_NETWORK_CLASS, performNetworkCreation());
    $("body").on("change", "#network-source", function(event) {
        grnState.customWorkbook.source = $("#network-source").val();
        grnState.customWorkbook.genes = {};
        console.log("User changed source!")
        console.log(grnState.customWorkbook)
        event.stopPropagation();
        displayCurrentGenes();
    });
    $("body").on("click", "#submit-network", function() {
        console.log("Creating network")
        let source = grnState.customWorkbook.source
        let headers = {
            type:"CreateNetwork",
            info: {
                genes: grnState.customWorkbook.genes,
                source:grnState.customWorkbook.sources[source].source,
                timestamp:grnState.customWorkbook.sources[source].timestamp.substring(0,19).replace("T", " ")
            }
        }
        queryNetworkDatabase(headers).then(function (response) {
            console.log("HERE IS THE DATA FOR NETWORK CREATION");
            grnState.customWorkbook.links = response.regulatoryConnections;
            console.dir(grnState)
            let workbook = createCustomWorkbook();
            let genesAmount = Object.keys(grnState.customWorkbook.genes).length;
            let edgesAmount = Object.keys(grnState.customWorkbook.links).length;
            grnState.workbook = workbook;
            grnState.newWorkbook = true;
            grnState.name = `Custom Workbook: UnweightedGRN(${genesAmount} genes, ${edgesAmount} edges)`;
            updateApp(grnState);
            $(CREATE_NETWORK_MODAL).modal("hide");
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        console.dir(grnState)
    });

    $("body").on("click", "#enter-search", function(event) {
        try {
            console.log("search button has been clicked")
            event.preventDefault();
            event.stopPropagation();
            addGene();
        } catch (error) {
            console.log(error);
        }
    });
};
<commit_msg>fixed bug<commit_after>import {CREATE_NETWORK_CLASS, CREATE_NETWORK_MODAL} from "./constants";
import { queryNetworkDatabase } from "./api/grnsight-api";
import { grnState } from "./grnstate";
import { updateApp } from "./update-app";

export const createNetwork = function () {
    const createCustomWorkbook = () => {
        let genes = []
        let genesByIndex = {}
        let links = []
        let positiveWeights = []
        let i = 0
        for (let gene in grnState.customWorkbook.genes){
            genes.push({name : grnState.customWorkbook.genes[gene]});
            genesByIndex[gene] = i;
            i++;
        }
        console.log(genesByIndex)
        console.log(genes)
        console.log(grnState.customWorkbook.genes)
        for (let regulator in grnState.customWorkbook.links) {
            for (let target of grnState.customWorkbook.links[regulator]){
                console.log("regulator: ",regulator, ", ",  genesByIndex[regulator])
                console.log("target", target, ", ",
                genesByIndex[target]
            )
                links.push({
                    source: genesByIndex[regulator],
                    target: genesByIndex[target],
                    value:1,
                    type:"arrowhead",
                    stroke: "black"
                });
                positiveWeights.push(1);
            }
        }
        return  {
            genes,
            links,
            errors: [],
            warnings: [],
            positiveWeights,
            negativeWeights: [],
            sheetType: "unweighted",
            network: {
                genes,
                links,
                errors: [],
                warnings: [],
                positiveWeights,
            },
            meta: {
                data: {
                    species: "Saccharomyces cerevisiae",
                    taxon_id: 559292
                }
            },
            test: {
            },
            expression: {
            }
        };

    }
    const createHTMLforForm = (sources) => {
        let result =  `

Create Network

            Network Source
            <select class=\'network-dropdown\' id=\'network-source\'>
            `;
        if (sources.length !== 1) {
            result += `<option value=\'none\' selected=\'true\' disabled>Select Network Source</option> `
            for (let source in sources) {
                result += `
                            <option value=\'${sources[source]}\'>${sources[source]}</option>
                `;
            }
        } else {
            result += `
                        <option value=\'${sources[0]}\' selected=\'true\' disabled hidden>${sources[0]}</option>
            `;
        }
        result += `</select>

Warning: changing network source will remove all current genes in network

            <form id=\'getNetworkGenesForm\'>
                Select genes
                <input type=\'text\' id=\'network-search-bar\' name=\'network-search-bar\'></input>
                <button id=\'enter-search\' type=\'submit\' class=\'search-button\'>

                </button>
            </form>

Added genes go here! Click on a gene to remove it

        <button id=\'submit-network\'>Create Network</input>

        `;
        return result;
    };
    const createGeneButtons = function () {
        let result =  `

Added genes go below! Click on a gene to remove it.

        `
        for (let gene in grnState.customWorkbook.genes) {
            result += `

                        ${grnState.customWorkbook.genes[gene]}

                        (${gene})

            `
        }

        result += "

"
        return result
    };
    const displayCurrentGenes = function () {
        $("#selected-genes").remove();
        $("#selected-genes-container").append(createGeneButtons());
        for (let gene in grnState.customWorkbook.genes) {
            console.log(gene);
            $(`#${gene}`).on("click", (ev) => {
                ev.stopPropagation();
                $(`#${gene}`).remove();
                delete grnState.customWorkbook.genes[gene];
            });
        }
    };

    const addGene = function() {
        console.log("Adding Gene")
        let gene = `${$("#network-search-bar").val()}`.toUpperCase();
        $("#network-search-bar").val("");
        let source = grnState.customWorkbook.source
        let headers = {
            type:"NetworkGeneFromSource",
            info: {
                gene: gene,
                source:grnState.customWorkbook.sources[source].source,
                timestamp:grnState.customWorkbook.sources[source].timestamp.substring(0,19).replace("T", " ")
            }
        }
        console.log("Adding Gene headers:")
        console.log(headers)
        queryNetworkDatabase(headers).then(function (response) {
            console.log("recieved response")
            if (response.geneId !== null && response.displayGeneId !==null) {
            grnState.customWorkbook.genes[response.geneId] = response.displayGeneId;
            displayCurrentGenes();
            }
            else {
                alert (`Gene: ${gene} was not found in this database. Please check for any typos and try again.`);
            }
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
    };

    const displayCreateNetworkModal = function () {
        $("#createNetworkFormContainer").remove();
        grnState.customWorkbook = {
            genes : {},
            source : null
        };
    // get sources from database
        queryNetworkDatabase({type:"NetworkSource", info:null}).then(function (response) {
            $("#creatNetworkQuestions-container").append(createHTMLforForm(Object.keys(response.sources)));
            grnState.customWorkbook.sources = response.sources;
            grnState.customWorkbook.source = Object.keys(response.sources).length === 1? Object.keys(response.sources)[0] : null;
            console.log(grnState.customWorkbook)
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        $(CREATE_NETWORK_MODAL).modal("show");
    };

    const performNetworkCreation = function () {
        return function () {
            displayCreateNetworkModal();
        };
    };

    $("body").on("click", CREATE_NETWORK_CLASS, performNetworkCreation());
    $("body").on("change", "#network-source", function(event) {
        grnState.customWorkbook.source = $("#network-source").val();
        grnState.customWorkbook.genes = {};
        console.log("User changed source!")
        console.log(grnState.customWorkbook)
        event.stopPropagation();
        displayCurrentGenes();
    });
    $("body").on("click", "#submit-network", function() {
        console.log("Creating network")
        let source = grnState.customWorkbook.source
        let headers = {
            type:"CreateNetwork",
            info: {
                genes: grnState.customWorkbook.genes,
                source:grnState.customWorkbook.sources[source].source,
                timestamp:grnState.customWorkbook.sources[source].timestamp.substring(0,19).replace("T", " ")
            }
        }
        queryNetworkDatabase(headers).then(function (response) {
            console.log("HERE IS THE DATA FOR NETWORK CREATION");
            grnState.customWorkbook.links = response.regulatoryConnections;
            console.dir(grnState)
            let workbook = createCustomWorkbook();
            let genesAmount = Object.keys(grnState.customWorkbook.genes).length;
            let edgesAmount = Object.keys(grnState.customWorkbook.links).length;
            grnState.workbook = workbook;
            grnState.newWorkbook = true;
            grnState.name = `Custom Workbook: UnweightedGRN(${genesAmount} genes, ${edgesAmount} edges)`;
            updateApp(grnState);
            $(CREATE_NETWORK_MODAL).modal("hide");
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        console.dir(grnState)
    });

    $("body").on("click", "#enter-search", function(event) {
        try {
            console.log("search button has been clicked")
            event.preventDefault();
            event.stopPropagation();
            addGene();
        } catch (error) {
            console.log(error);
        }
    });
};
<|endoftext|>


<commit_before>import {CREATE_NETWORK_CLASS, CREATE_NETWORK_MODAL} from "./constants";
import { queryNetworkDatabase } from "./api/grnsight-api";
import { grnState } from "./grnstate";

export const createNetwork = function () {
    const createHTMLforForm = (sources) => {
        let result =  `

Create Network

            Network Source
            <select class=\'network-dropdown\' id=\'network-source\'>
                <option value=\'none\' selected=\'true\' disabled hidden>Select Network Source</option>
                    `;
        for (let source in sources) {
            result += `
                        <option value=\'${source}\'>${sources[source]}</option>
            `;
        }
        result += `</select>

Warning: changing network source will remove all current genes in network

            <form id=\'getNetworkGenesForm\' method=\'post\'>
                Select genes
                <input type=\'text\' id=\'network-search-bar\' name=\'network-search-bar\'></input>
                <button id=\'enter-search\' type=\'submit\' class=\'search-button\'>

                </button>
            </form>

Added genes go here! Click on a gene to remove it

        <input type=\'submit\' id=\'submit-network\' value=\'Create Network\'></input>

        `;
        return result;
    };
    const createGeneButtons = function () {
        let result =  `

Added genes go below! Click on a gene to remove it.

        `
        for (let gene in grnState.customWorkbook.genes) {
            result += `

                        ${grnState.customWorkbook.genes[gene]}

                        (${gene})

            `
        }

        result += "

"
        return result
    };
    const displayCurrentGenes = function () {
        $("#selected-genes").remove();
        $("#selected-genes-container").append(createGeneButtons());
        for (let gene in grnState.customWorkbook.genes) {
            console.log(gene);
            $(`#${gene}`).on("click", (ev) => {
                ev.stopPropagation();
                $(`#${gene}`).remove();
                delete grnState.customWorkbook.genes[gene];
            });
        }
    };

    const addGene = function() {
        console.log("Begin Add Gene")
        let gene = `${$("#network-search-bar").val()}`;
        console.log(gene)
        // console.log("Gets here")
        // let source = grnState.customWorkbook.source
        // console.log("Gets here 2")
        $("#network-search-bar").val("")
        // console.log("Gets here")
        // console.log(`Gene: ${gene}`);
        // console.log(`Source: ${grnState.customWorkbook.sources[source].source}`);
        // console.log(`TimeStamp: ${grnState.customWorkbook.sources[source].timestamp}`);
        grnState.customWorkbook.genes[gene.toUpperCase()] = gene.toLowerCase()
        // get genes from database
            // queryNetworkDatabase({
            //     type:"NetworkGeneFromSource",
            //     info: {
            //         gene,
            //         source:grnState.customWorkbook.sources[source].source,
            //         timestamp:grnState.customWorkbook.sources[source].timestamp
            //     }
            // }).then(function (response) {
            //     let x = response
            //     console.log(x)
            // }).catch(function (error) {
            //     console.log(error.stack);
            //     console.log(error.name);
            //     console.log(error.message);
            // });
    };

    const updateGenes = function () {
        addGene();
        displayCurrentGenes();
    };

    const displayCreateNetworkModal = function () {
        $("#createNetworkFormContainer").remove();
        // $("#creatNetworkQuestions-container").append(createHTMLforForm(["1", "2", "3"]));
        grnState.customWorkbook = {
            genes : {},
            source : null
        };
    // get sources from database
        queryNetworkDatabase({type:"NetworkSource", info:null}).then(function (response) {
            $("#creatNetworkQuestions-container").append(createHTMLforForm(Object.keys(response.sources)));
            grnState.customWorkbook.sources = response.sources;
            console.log(grnState.customWorkbook)
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        // $('#getNetworkGenesForm').on("submit", ev => {
        //     let gene = `${$("#network-search-bar").val()}`;
        //     let source = grnState.customWorkbook.source
        //     console.log("Gets here");
        //     ev.stopPropagation();
        //     queryNetworkDatabase({
        //         type:"NetworkGeneFromSource",
        //         info: {
        //             gene,
        //             source:grnState.customWorkbook.sources[source].source,
        //             timestamp:grnState.customWorkbook.sources[source].timestamp
        //         }
        //     }).then(function (response) {
        //         let x = response
        //         console.log(x)
        //     }).catch(function (error) {
        //         console.log(error.stack);
        //         console.log(error.name);
        //         console.log(error.message);
        //     });
        //     return false;
        // });
        $(CREATE_NETWORK_MODAL).modal("show");
    };

    const performNetworkCreation = function () {
        return function () {
            displayCreateNetworkModal();
        };
    };

    // $(CREATE_NETWORK_CLASS).one("click", performNetworkCreation());
    $("body").on("click", CREATE_NETWORK_CLASS, performNetworkCreation());
    // $("#network-source").on("change", ((ev) => {
    //     if (grnState.customWorkbook === undefined) grnState.customWorkbook = {source:null, genes: {}}
    //     grnState.customWorkbook.source = $("#network-source").val();
    //     grnState.customWorkbook.genes = {};
    //     console.log("User changed source!")
    //     console.log(grnState.customWorkbook)

    //     ev.stopPropagation();
    //     displayCurrentGenes();
    // })(ev));
    $("#getNetworkGenesForm").on("submit", (ev) => {
        console.log("gets here form>>?")
        ev.preventDefault();
    })
    $("#enter-search").on("click", (ev) => {
        console.log("search button has been clicked")
        console.log($('#getNetworkGenesForm').serializeArray())
        ev.stopPropagation();
        updateGenes();
    });
    $("#network-search-bar").on("keydown", (ev) => {
        if(ev.key === 'Enter') {
            console.log("search bar has been entered")
            console.log($('#getNetworkGenesForm').serializeArray())
            ev.preventDefault();
            ev.stopPropagation();
            updateGenes();
        }
    });
};
<commit_msg>maybe this will work<commit_after>import {CREATE_NETWORK_CLASS, CREATE_NETWORK_MODAL} from "./constants";
import { queryNetworkDatabase } from "./api/grnsight-api";
import { grnState } from "./grnstate";

export const createNetwork = function () {
    const createHTMLforForm = (sources) => {
        let result =  `

Create Network

            Network Source
            <select class=\'network-dropdown\' id=\'network-source\'>
                <option value=\'none\' selected=\'true\' disabled hidden>Select Network Source</option>
                    `;
        for (let source in sources) {
            result += `
                        <option value=\'${source}\'>${sources[source]}</option>
            `;
        }
        result += `</select>

Warning: changing network source will remove all current genes in network

            <form id=\'getNetworkGenesForm\'>
                Select genes
                <input type=\'text\' id=\'network-search-bar\' name=\'network-search-bar\'></input>
                <button id=\'enter-search\' type=\'submit\' class=\'search-button\'>

                </button>
            </form>

Added genes go here! Click on a gene to remove it

        <input type=\'submit\' id=\'submit-network\' value=\'Create Network\'></input>

        `;
        return result;
    };
    const createGeneButtons = function () {
        let result =  `

Added genes go below! Click on a gene to remove it.

        `
        for (let gene in grnState.customWorkbook.genes) {
            result += `

                        ${grnState.customWorkbook.genes[gene]}

                        (${gene})

            `
        }

        result += "

"
        return result
    };
    const displayCurrentGenes = function () {
        $("#selected-genes").remove();
        $("#selected-genes-container").append(createGeneButtons());
        for (let gene in grnState.customWorkbook.genes) {
            console.log(gene);
            $(`#${gene}`).on("click", (ev) => {
                ev.stopPropagation();
                $(`#${gene}`).remove();
                delete grnState.customWorkbook.genes[gene];
            });
        }
    };

    const addGene = function() {
        console.log("Begin Add Gene")
        let gene = `${$("#network-search-bar").val()}`;
        console.log(gene)
        // console.log("Gets here")
        // let source = grnState.customWorkbook.source
        // console.log("Gets here 2")
        $("#network-search-bar").val("")
        // console.log("Gets here")
        // console.log(`Gene: ${gene}`);
        // console.log(`Source: ${grnState.customWorkbook.sources[source].source}`);
        // console.log(`TimeStamp: ${grnState.customWorkbook.sources[source].timestamp}`);
        grnState.customWorkbook.genes[gene.toUpperCase()] = gene.toLowerCase()
        // get genes from database
            // queryNetworkDatabase({
            //     type:"NetworkGeneFromSource",
            //     info: {
            //         gene,
            //         source:grnState.customWorkbook.sources[source].source,
            //         timestamp:grnState.customWorkbook.sources[source].timestamp
            //     }
            // }).then(function (response) {
            //     let x = response
            //     console.log(x)
            // }).catch(function (error) {
            //     console.log(error.stack);
            //     console.log(error.name);
            //     console.log(error.message);
            // });
    };

    const updateGenes = function () {
        addGene();
        displayCurrentGenes();
    };

    const displayCreateNetworkModal = function () {
        $("#createNetworkFormContainer").remove();
        // $("#creatNetworkQuestions-container").append(createHTMLforForm(["1", "2", "3"]));
        grnState.customWorkbook = {
            genes : {},
            source : null
        };
    // get sources from database
        queryNetworkDatabase({type:"NetworkSource", info:null}).then(function (response) {
            $("#creatNetworkQuestions-container").append(createHTMLforForm(Object.keys(response.sources)));
            grnState.customWorkbook.sources = response.sources;
            console.log(grnState.customWorkbook)
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        // $('#getNetworkGenesForm').on("submit", ev => {
        //     let gene = `${$("#network-search-bar").val()}`;
        //     let source = grnState.customWorkbook.source
        //     console.log("Gets here");
        //     ev.stopPropagation();
        //     queryNetworkDatabase({
        //         type:"NetworkGeneFromSource",
        //         info: {
        //             gene,
        //             source:grnState.customWorkbook.sources[source].source,
        //             timestamp:grnState.customWorkbook.sources[source].timestamp
        //         }
        //     }).then(function (response) {
        //         let x = response
        //         console.log(x)
        //     }).catch(function (error) {
        //         console.log(error.stack);
        //         console.log(error.name);
        //         console.log(error.message);
        //     });
        //     return false;
        // });
        $(CREATE_NETWORK_MODAL).modal("show");
    };

    const performNetworkCreation = function () {
        return function () {
            displayCreateNetworkModal();
        };
    };

    // $(CREATE_NETWORK_CLASS).one("click", performNetworkCreation());
    $("body").on("click", CREATE_NETWORK_CLASS, performNetworkCreation());
    // $("#network-source").on("change", ((ev) => {
    //     if (grnState.customWorkbook === undefined) grnState.customWorkbook = {source:null, genes: {}}
    //     grnState.customWorkbook.source = $("#network-source").val();
    //     grnState.customWorkbook.genes = {};
    //     console.log("User changed source!")
    //     console.log(grnState.customWorkbook)

    //     ev.stopPropagation();
    //     displayCurrentGenes();
    // })(ev));
    $("form").on("submit", (ev) => {
        console.log("gets here form>>?")
        ev.preventDefault();
    })
    $("#enter-search").on("click", (ev) => {
        console.log("search button has been clicked")
        console.log($('#getNetworkGenesForm').serializeArray())
        ev.stopPropagation();
        updateGenes();
    });
    $("#network-search-bar").on("keydown", (ev) => {
        if(ev.key === 'Enter') {
            console.log("search bar has been entered")
            console.log($('#getNetworkGenesForm').serializeArray())
            ev.preventDefault();
            ev.stopPropagation();
            updateGenes();
        }
    });
};
<|endoftext|>


<commit_before>FLOW.MonitoringDataTableView = FLOW.View.extend({
  showingDetailsDialog: false,
  since: null,

  showDetailsDialog: function (evt) {
	FLOW.surveyInstanceControl.set('content', FLOW.store.findQuery(FLOW.SurveyInstance, {
		surveyedLocaleId: evt.context.get('keyId')
	}));
    this.toggleProperty('showingDetailsDialog');
  },

  closeDetailsDialog: function () {
    this.toggleProperty('showingDetailsDialog');
  },

  showSurveyInstanceDetails: function (evt) {
    FLOW.questionAnswerControl.doQuestionAnswerQuery(evt.context.get('keyId'));
    $('.si_details').hide();
    $('tr[data-flow-id="si_details_' + evt.context.get('keyId') + '"]').show();
  },

  showSurveyedLocaleDeleteButton: function() {
    return FLOW.surveyedLocaleControl.get('userCanDelete');
  }.property(),

  findSurveyedLocale: function (evt) {
	  var ident = this.get('identifier'),
	      displayName = this.get('displayName'),
	      sgId = FLOW.selectedControl.get('selectedSurveyGroup'),
	      cursorType = FLOW.metaControl.get('cursorType');
        criteria = {};

	  if (ident) {
		  criteria.identifier = ident;
	  }

	  if (displayName) {
		  criteria.displayName = displayName;
	  }

	  if (sgId) {
		  criteria.surveyGroupId = sgId.get('keyId');
	  }

	  FLOW.surveyedLocaleControl.set('content', FLOW.store.findQuery(FLOW.SurveyedLocale, criteria));
  },

  doNextPage: function () {
    FLOW.surveyedLocaleControl.get('sinceArray').pushObject(FLOW.metaControl.get('since'));
    this.findSurveyedLocale();
    FLOW.surveyedLocaleControl.set('pageNumber', FLOW.surveyedLocaleControl.get('pageNumber') + 1);
  },

  doPrevPage: function () {
    FLOW.surveyedLocaleControl.get('sinceArray').popObject();
    FLOW.metaControl.set('since', FLOW.surveyedLocaleControl.get('sinceArray')[FLOW.surveyedLocaleControl.get('sinceArray').length - 1]);
    this.findSurveyedLocale();
    FLOW.surveyedLocaleControl.set('pageNumber', FLOW.surveyedLocaleControl.get('pageNumber') - 1);
  },

  hasNextPage: function () {
    return FLOW.metaControl.get('numSLLoaded') == 20;
  }.property('FLOW.metaControl.numSLLoaded'),

  hasPrevPage: function () {
    return FLOW.surveyedLocaleControl.get('sinceArray').length != 0;
  }.property('FLOW.surveyedLocaleControl.sinceArray.length'),
});
<commit_msg>[#1299] Setup start cursor for next page request<commit_after>FLOW.MonitoringDataTableView = FLOW.View.extend({
  showingDetailsDialog: false,
  cursorStart: null,

  showDetailsDialog: function (evt) {
	FLOW.surveyInstanceControl.set('content', FLOW.store.findQuery(FLOW.SurveyInstance, {
		surveyedLocaleId: evt.context.get('keyId')
	}));
    this.toggleProperty('showingDetailsDialog');
  },

  closeDetailsDialog: function () {
    this.toggleProperty('showingDetailsDialog');
  },

  showSurveyInstanceDetails: function (evt) {
    FLOW.questionAnswerControl.doQuestionAnswerQuery(evt.context.get('keyId'));
    $('.si_details').hide();
    $('tr[data-flow-id="si_details_' + evt.context.get('keyId') + '"]').show();
  },

  showSurveyedLocaleDeleteButton: function() {
    return FLOW.surveyedLocaleControl.get('userCanDelete');
  }.property(),

  findSurveyedLocale: function (evt) {
	  var ident = this.get('identifier'),
	      displayName = this.get('displayName'),
	      sgId = FLOW.selectedControl.get('selectedSurveyGroup'),
	      cursorType = FLOW.metaControl.get('cursorType');
        criteria = {};

	  if (ident) {
		  criteria.identifier = ident;
	  }

	  if (displayName) {
		  criteria.displayName = displayName;
	  }

	  if (sgId) {
		  criteria.surveyGroupId = sgId.get('keyId');
	  }

	  if (this.get('cursorStart')) {
		criteria.since = this.get('cursorStart');
	  }

	  FLOW.surveyedLocaleControl.set('content', FLOW.store.findQuery(FLOW.SurveyedLocale, criteria));
  },

  doNextPage: function () {
    FLOW.surveyedLocaleControl.get('sinceArray').pushObject(FLOW.metaControl.get('since'));
	this.set('cursorStart', FLOW.metaControl.get('since'));
    this.findSurveyedLocale();
    FLOW.surveyedLocaleControl.set('pageNumber', FLOW.surveyedLocaleControl.get('pageNumber') + 1);
  },

  doPrevPage: function () {
    FLOW.surveyedLocaleControl.get('sinceArray').popObject();
    FLOW.metaControl.set('since', FLOW.surveyedLocaleControl.get('sinceArray')[FLOW.surveyedLocaleControl.get('sinceArray').length - 1]);
    this.findSurveyedLocale();
    FLOW.surveyedLocaleControl.set('pageNumber', FLOW.surveyedLocaleControl.get('pageNumber') - 1);
  },

  hasNextPage: function () {
    return FLOW.metaControl.get('numSLLoaded') == 20;
  }.property('FLOW.metaControl.numSLLoaded'),

  hasPrevPage: function () {
    return FLOW.surveyedLocaleControl.get('sinceArray').length != 0;
  }.property('FLOW.surveyedLocaleControl.sinceArray.length'),
});
<|endoftext|>


<commit_before>function NameController($window, ShareBandNameService) {
  var ctrl = this;

  ctrl.bandName = ShareBandNameService;

  ctrl.resetBandName = function() {
    ctrl.bandName.name = '';
    ctrl.bandName.genre_id = '';
  }

  console.log($window.location.href);

}

angular
  .module('app')
  .controller('NameController', NameController);<commit_msg>add FormDataService to NameController<commit_after>function NameController($window, ShareBandNameService, FormDataService) {
  var ctrl = this;

  ctrl.bandName = ShareBandNameService;

  ctrl.resetBandName = function() {
    ctrl.bandName.name = '';
    ctrl.bandName.genre_id = '';
    FormDataService.formData = {};
  }

}

angular
  .module('app')
  .controller('NameController', NameController);<|endoftext|>


<commit_before>$(document).ready(function(){
    var maxFields = 5;
    var count = ( $('.multi-pick').length - 1 ) ? ( $('.multi-pick').length - 1 ) : 1;

    if($("#post_field_field_type").val() == "select_single" || $("#post_field_field_type").val() == "select_multiple"){
      $('#image_sizer').css('display', 'none');
      $("#valueSet").css('display', 'block');
      $("#addNewValue").css('visibility', 'visible');
    } else if($("#post_field_field_type").val() == "image") {
      $('#image_sizer').css('display', 'block');
      $("#valueSet").css('display', 'none');
      $("#addNewValue").css('visibility', 'hidden');
    } else {
      $('#image_sizer').css('display', 'none');
      $("#valueSet").css('display', 'none');
      $("#addNewValue").css('visibility', 'hidden');
    }

    $("#post_field_field_type").change(function(){
        if($("#post_field_field_type").val() == "select_single" || $("#post_field_field_type").val() == "select_multiple"){
          $('#image_sizer').css('display', 'none');
          $('input.image-sizer[type="text"]').val('');
          $('input.multi-pick[type="text"]').val('');
          $("#valueSet").css('display', 'block');
          $("#addNewValue").css('visibility', 'visible');
        } else if($("#post_field_field_type").val() == "image") {
          $('#image_sizer').css('display', 'block');
          $("#valueSet").css('display', 'none');
          $("#addNewValue").css('visibility', 'hidden');
        } else {
          $('#image_sizer').css('display', 'none');
          $('input.multi-pick[type="text"]').val('');
          $('input.image-sizer[type="text"]').val('');
          $("#valueSet").css('display', 'none');
          $("#addNewValue").css('visibility', 'hidden');
        }
    });

    $("#addNewValue").click(function(){
      if(count < maxFields) {
        $("#valueSet").append($("#selector_").html());
        $('input', $('#valueSet')).each(function () {
          $(this).attr('required', true);
        });

        count++;
      }
    });
});

function deleteChoice(el) {
   $(el).parent().parent().fadeOut(300, function() {
     $(this).remove();
   });
}
<commit_msg>- quick fix<commit_after>$(document).ready(function(){
    var maxFields = 5;
    var count = ( $('.multi-pick').length - 1 ) ? ( $('.multi-pick').length - 1 ) : 1;

    if($("#post_field_field_type").val() == "select_single" || $("#post_field_field_type").val() == "select_multiple"){
      $('#image_sizer').css('display', 'none');
      $("#valueSet").css('display', 'block');
      $("#addNewValue").css('visibility', 'visible');
    } else if($("#post_field_field_type").val() == "image") {
      $('#image_sizer').css('display', 'block');
      $("#valueSet").css('display', 'none');
      $("#addNewValue").css('visibility', 'hidden');
    } else {
      $('#image_sizer').css('display', 'none');
      $("#valueSet").css('display', 'none');
      $("#addNewValue").css('visibility', 'hidden');
    }

    $("#post_field_field_type").change(function(){
        if($("#post_field_field_type").val() == "select_single" || $("#post_field_field_type").val() == "select_multiple"){
          $('#image_sizer').css('display', 'none');
          $('input.image-sizer[type="text"]').val('');
          $('input.multi-pick[type="text"]').val('');
          $("#valueSet").css('display', 'block');
          $("#addNewValue").css('visibility', 'visible');
        } else if($("#post_field_field_type").val() == "image") {
          $('#image_sizer').css('display', 'block');
          $("#valueSet").css('display', 'none');
          $("#addNewValue").css('visibility', 'hidden');
        } else {
          $('#image_sizer').css('display', 'none');
          $('input.multi-pick[type="text"]').val('');
          $('input.image-sizer[type="text"]').val('');
          $("#valueSet").css('display', 'none');
          $("#addNewValue").css('visibility', 'hidden');
        }
    });

    $("#addNewValue").click(function(){
      if(count < maxFields) {
        $("#valueSet").append($("#selector_").html());
        $('input', $('#valueSet')).each(function () {
          $(this).attr('required', true);
        });

        count++;
      }
    });

    deleteChoice = function(el) {
       $(el).parent().parent().fadeOut(300, function() {
         $(this).remove();
         count--;
       });
    }
});
<|endoftext|>


<commit_before>/**
 * Courses view. Displays courses and their sections
 * @param {HTMLElement} target- The element in which this view should be rendered
 * @param {Object} params - API params for this view
 * @return {undefined}
 * @memberOf Yacs.views
 */
Yacs.views.courses = function (target, params) {
  params.show_sections = params.show_periods = true;

  /**
   * When a section is clicked, toggle whether it is selected.
   * Uses Yacs.user for POT of selections
   * When a course is clicked, toggle its sections as selected.
   * Uses CSS for POT of selections
   */
  var bindListeners = function () {
    Yacs.on('click', target.querySelectorAll('section'), function (section) {
      Yacs.user.removeSelection(section.dataset.id) ||
        Yacs.user.addSelection(section.dataset.id,true);
    });

    Yacs.on('click', target.querySelectorAll('course-info'), function (courseInfo) {
      var courseSelected = courseInfo.parentElement.classList.contains('selected');
      if (courseSelected) {
        var sections = courseInfo.parentElement.querySelectorAll('section');
        Yacs.user.removeSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      } else {
        var sections = courseInfo.parentElement.querySelectorAll('section:not(.closed)');
        Yacs.user.addSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      }
    });
  };

  /**
   * Given the data returned from the API, populate the conflicts cache with
   * the data for conflicts.
   */
  var populateConflictsCache = function(data) {
    var courselen = data.courses.length;
    for(var i=0; i<courselen; ++i) {
      var sectlen = data.courses[i].sections.length;
      for(var j=0; j<sectlen; ++j) {
        var id = data.courses[i].sections[j].id;
        // TODO some method of cache expiration
        if(! (id in Yacs.cache.conflicts)) {
          Yacs.cache.conflicts[id] = data.courses[i].sections[j].conflicts;
        }
      }
    }
  }

  /** Given a section ID, the current selections, (and data in the conflicts cache),
   * return a boolean of whether this section has any conflicts with current selections.
   */
  var doesConflict = function(selections, sectid) {

  };

  /**
   * Update selected status (class) of sections and courses. If all open
   * sections of a course are selected, the course is considered selected.
   */
  var updateSelected = function () {
    var selected = Yacs.user.getSelections();
    each(target.querySelectorAll('course'), function (course) {
      var courseSelected = false;
      var sections = course.querySelectorAll('section');
      if (sections.length > 0) {
        courseSelected = true;
        each(sections, function (section) {
          var sectionSelected = selected.indexOf(section.dataset.id) !== -1;
          var hasConflict = doesConflict(section.dataset.id, selected);
          section.classList.toggle('selected', sectionSelected);
          if (!sectionSelected && !section.classList.contains('closed'))
            courseSelected = false;
        });
      }
      course.classList.toggle('selected', courseSelected);
    });
  };

  Yacs.models.courses.query(params, function (data, success) {
    if (success) {
      Yacs.render(target, 'courses', data);
      populateConflictsCache(data);
      // rendering will use tmp cache 'selections' field, clear this
      delete Yacs.cache.tmp.selections;
      Yacs.observe('selection', document.querySelector('courses'), updateSelected);
      bindListeners();
      updateSelected();
    }
  });
};
<commit_msg>Made bindListeners work with new user code, temporarily removed updateSelected functionality<commit_after>/**
 * Courses view. Displays courses and their sections
 * @param {HTMLElement} target- The element in which this view should be rendered
 * @param {Object} params - API params for this view
 * @return {undefined}
 * @memberOf Yacs.views
 */
Yacs.views.courses = function (target, params) {
  params.show_sections = params.show_periods = true;

  /**
   * When a section is clicked, toggle whether it is selected.
   * When a course is clicked, toggle its sections as selected.
   * Uses Yacs.user for POT of selections
   */
  var bindListeners = function () {
    Yacs.on('click', target.querySelectorAll('section'), function (section) {
      var sid = section.dataset.id;
      var cid = section.dataset.courseId;
      if(! Yacs.user.removeSelection(section.dataset.id)) {
        // remove failed so add instead
        Yacs.user.addSelection(section.dataset.id,true);
      }
    });

    Yacs.on('click', target.querySelectorAll('course-info'), function (courseInfo) {
      var cid = courseInfo.parentElement.dataset.id;
      var courseSelected = Yacs.user.courseIsSelected(cid);
      if (courseSelected) {
        Yacs.user.removeCourse(cid);
      } else {
        var sections = courseInfo.parentElement.querySelectorAll('section:not(.closed)');
        Yacs.user.addSelections(map(sections, function (section) {
          return section.dataset.id;
        }));
      }
    });
  };

  /**
   * Given the data returned from the API, populate the conflicts cache with
   * the data for conflicts.
   */
  var populateConflictsCache = function(data) {
    var courselen = data.courses.length;
    for(var i=0; i<courselen; ++i) {
      var sectlen = data.courses[i].sections.length;
      for(var j=0; j<sectlen; ++j) {
        var id = data.courses[i].sections[j].id;
        // TODO some method of cache expiration
        if(! (id in Yacs.cache.conflicts)) {
          Yacs.cache.conflicts[id] = data.courses[i].sections[j].conflicts;
        }
      }
    }
  }

  /** Given a section ID, the current selections, (and data in the conflicts cache),
   * return a boolean of whether this section has any conflicts with current selections.
   */
  var doesConflict = function(selections, sectid) {

  };

  /**
   * Update selected status (class) of sections and courses. If all open
   * sections of a course are selected, the course is considered selected.
   */
  var updateSelected = function () {
    // It would be a good idea for conflicts to optimize by checking only the course that
    // actually updated. Actually, why doesn't this already do that?
    /*
    var selected = Yacs.user.getSelections();
    each(target.querySelectorAll('course'), function (course) {
      var courseSelected = false;
      var sections = course.querySelectorAll('section');
      if (sections.length > 0) {
        courseSelected = true;
        each(sections, function (section) {
          var sectionSelected = selected.indexOf(section.dataset.id) !== -1;
          var hasConflict = doesConflict(section.dataset.id, selected);
          section.classList.toggle('selected', sectionSelected);
          if (!sectionSelected && !section.classList.contains('closed'))
            courseSelected = false;
        });
      }
      course.classList.toggle('selected', courseSelected);
    });
    */
  };

  Yacs.models.courses.query(params, function (data, success) {
    if (success) {
      Yacs.render(target, 'courses', data);
      populateConflictsCache(data);
      Yacs.observe('selection', document.querySelector('courses'), updateSelected);
      bindListeners();
      updateSelected();
    }
  });
};
<|endoftext|>


<commit_before>/**
 * Javascript behaviors for Filterrific.
 * http://filterrific.clearcove.ca
 *
 * Requires jQuery 1.7.0 or later.
 *
 * Released under the MIT license
 *
 */

// Create global Filterrific namespace
if (typeof Filterrific === 'undefined') {
  var Filterrific = {};
}

// Define function to submit Filterrific filter form
Filterrific.submitFilterForm = function(){
  var form = $(this).parents("form"),
      url = form.attr("action");
  // turn on spinner
  $('.filterrific_spinner').show();
  // Submit ajax request
  $.ajax({
    url: url,
    data: form.serialize(),
    type: 'GET',
    dataType: 'script'
  }).done(function( msg ) {
    $('.filterrific_spinner').hide();
  });
};

//
// Embed jquery.observe_field.js to observe Filterrific filter inputs
//
// Copied from https://github.com/splendeo/jquery.observe_field
// Wrap in immediately invoked function for compatibility with other js libraries
//
(function($) {

  $.fn.filterrific_observe_field = function(frequency, callback) {
    frequency = frequency * 1000; // translate to milliseconds
    return this.each(function(){
      var $this = $(this);
      var prev = $this.val();
      var check = function() {
        if(removed()){ // if removed clear the interval and don't fire the callback
          if(ti) clearInterval(ti);
          return;
        }
        var val = $this.val();
        if(prev != val){
          prev = val;
          $this.map(callback); // invokes the callback on $this
        }
      };
      var removed = function() {
        return $this.closest('html').length == 0
      };
      var reset = function() {
        if(ti){
          clearInterval(ti);
          ti = setInterval(check, frequency);
        }
      };
      check();
      var ti = setInterval(check, frequency); // invoke check periodically
      // reset counter after user interaction
      $this.bind('keyup click mousemove', reset); //mousemove is for selects
    });
  };
})(jQuery);

// Initialize event observers on document ready and turbolinks page:load
jQuery(document).on('ready page:load turbolinks:load', function() {

  // Prevent double initilisation. With turbolinks 5 this function
  // will be called twice: on read and turbolinks:load
  if(Filterrific.initialized) {
    return;
  }

  // Add change event handler to all Filterrific filter inputs.
  $('#filterrific_filter').on(
    "change",
    ":input",
    Filterrific.submitFilterForm
  );

  // Add periodic observer to selected inputs.
  // Use this for text fields you want to observe for change, e.g., a search input.
  $(".filterrific-periodically-observed").filterrific_observe_field(
    0.5,
    Filterrific.submitFilterForm
  );

  Filterrific.initialized = true
});
<commit_msg>spelling<commit_after>/**
 * Javascript behaviors for Filterrific.
 * http://filterrific.clearcove.ca
 *
 * Requires jQuery 1.7.0 or later.
 *
 * Released under the MIT license
 *
 */

// Create global Filterrific namespace
if (typeof Filterrific === 'undefined') {
  var Filterrific = {};
}

// Define function to submit Filterrific filter form
Filterrific.submitFilterForm = function(){
  var form = $(this).parents("form"),
      url = form.attr("action");
  // turn on spinner
  $('.filterrific_spinner').show();
  // Submit ajax request
  $.ajax({
    url: url,
    data: form.serialize(),
    type: 'GET',
    dataType: 'script'
  }).done(function( msg ) {
    $('.filterrific_spinner').hide();
  });
};

//
// Embed jquery.observe_field.js to observe Filterrific filter inputs
//
// Copied from https://github.com/splendeo/jquery.observe_field
// Wrap in immediately invoked function for compatibility with other js libraries
//
(function($) {

  $.fn.filterrific_observe_field = function(frequency, callback) {
    frequency = frequency * 1000; // translate to milliseconds
    return this.each(function(){
      var $this = $(this);
      var prev = $this.val();
      var check = function() {
        if(removed()){ // if removed clear the interval and don't fire the callback
          if(ti) clearInterval(ti);
          return;
        }
        var val = $this.val();
        if(prev != val){
          prev = val;
          $this.map(callback); // invokes the callback on $this
        }
      };
      var removed = function() {
        return $this.closest('html').length == 0
      };
      var reset = function() {
        if(ti){
          clearInterval(ti);
          ti = setInterval(check, frequency);
        }
      };
      check();
      var ti = setInterval(check, frequency); // invoke check periodically
      // reset counter after user interaction
      $this.bind('keyup click mousemove', reset); //mousemove is for selects
    });
  };
})(jQuery);

// Initialize event observers on document ready and turbolinks page:load
jQuery(document).on('ready page:load turbolinks:load', function() {

  // Prevent double initilisation. With turbolinks 5 this function
  // will be called twice: on 'ready' and 'turbolinks:load'
  if(Filterrific.initialized) {
    return;
  }

  // Add change event handler to all Filterrific filter inputs.
  $('#filterrific_filter').on(
    "change",
    ":input",
    Filterrific.submitFilterForm
  );

  // Add periodic observer to selected inputs.
  // Use this for text fields you want to observe for change, e.g., a search input.
  $(".filterrific-periodically-observed").filterrific_observe_field(
    0.5,
    Filterrific.submitFilterForm
  );

  Filterrific.initialized = true
});
<|endoftext|>


<commit_before>/**
 * @file trivia command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const request = require('request');
let activeChannels = [];

exports.exec = (Bastion, message) => {
  if (activeChannels.includes(message.channel.id))  {
    /**
     * Error condition is encountered.
     * @fires error
     */
    return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'busy'), Bastion.strings.error(message.guild.language, 'isGameInUse', true, 'trivia'), message.channel);
  }

  let options = {
    method: 'GET',
    url: 'https://opentdb.com/api.php?amount=1&type=boolean&encode=url3986'
  };

  request(options, async (error, response, body) => {
    try {
      if (error) {
        /**
        * Error condition is encountered.
        * @fires error
        */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'connection'), Bastion.strings.error(message.guild.language, 'connection', true), message.channel);
      }

      if (response) {
        if (response.statusCode === 200) {
          body = JSON.parse(body);
          body = body.results[0];

          let question = await message.channel.send({
            embed: {
              color: Bastion.colors.BLUE,
              title: 'Trivia - True/False',
              description: decodeURIComponent(body.question),
              fields: [
                {
                  name: 'Category',
                  value: decodeURIComponent(body.category),
                  inline: true
                },
                {
                  name: 'Difficulty',
                  value: body.difficulty.toTitleCase(),
                  inline: true
                }
              ],
              footer: {
                text: 'Reply with either True/False within 60 seconds.'
              }
            }
          });

          activeChannels.push(message.channel.id);

          let validAnswers = [
            'true',
            'false'
          ];

          const trivia = message.channel.createMessageCollector(
            msg => !msg.author.bot && validAnswers.includes(msg.content.toLowerCase()),
            { maxMatches: 1, time: 60 * 1000 }
          );

          trivia.on('collect', ans => {
            let color, description;
            if (ans.content.toLowerCase() === body.correct_answer.toLowerCase()) {
              color = Bastion.colors.BLUE;
              description = `${ans.author.tag} you're absolutely right.`;
            }
            else {
              color = Bastion.colors.RED;
              description = `Unfortunately, you're wrong ${ans.author.tag}`;
            }

            message.channel.send({
              embed: {
                color: color,
                description: description
              }
            }).catch(e => {
              Bastion.log.error(e);
            });
          });

          trivia.on('end', (answers, reason) => {
            activeChannels.splice(activeChannels.indexOf(message.channel.id), 1);

            if (reason === 'time') {
              message.channel.send({
                embed: {
                  color: Bastion.colors.RED,
                  title: 'Trivia Ended',
                  description: 'Trivia was ended as no one was able to answer within 60 seconds.'
                }
              }).then(() => {
                question.delete().catch(e => {
                  Bastion.log.error(e);
                });
              }).catch(e => {
                Bastion.log.error(e);
              });
            }
          });
        }
        else {
          /**
          * Error condition is encountered.
          * @fires error
          */
          return Bastion.emit('error', response.statusCode, response.statusMessage, message.channel);
        }
      }
    }
    catch (e) {
      Bastion.log.error(e);
    }
  });
};

exports.config = {
  aliases: [],
  enabled: true
};

exports.help = {
  name: 'trivia',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'trivia',
  example: []
};
<commit_msg>Upgraded to request-promise-native in games module<commit_after>/**
 * @file trivia command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const request = require('request-promise-native');
let activeChannels = [];

exports.exec = async (Bastion, message) => {
  try {
    if (activeChannels.includes(message.channel.id))  {
      /**
      * Error condition is encountered.
      * @fires error
      */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'busy'), Bastion.strings.error(message.guild.language, 'isGameInUse', true, 'trivia'), message.channel);
    }

    let options = {
      method: 'GET',
      url: 'https://opentdb.com/api.php?amount=1&type=boolean&encode=url3986',
      json: true
    };
    let response = await request(options);

    response = response.results[0];

    let question = await message.channel.send({
      embed: {
        color: Bastion.colors.BLUE,
        title: 'Trivia - True/False',
        description: decodeURIComponent(response.question),
        fields: [
          {
            name: 'Category',
            value: decodeURIComponent(response.category),
            inline: true
          },
          {
            name: 'Difficulty',
            value: response.difficulty.toTitleCase(),
            inline: true
          }
        ],
        footer: {
          text: 'Reply with either True/False within 60 seconds.'
        }
      }
    });

    activeChannels.push(message.channel.id);

    let validAnswers = [
      'true',
      'false'
    ];

    const trivia = message.channel.createMessageCollector(
      msg => !msg.author.bot && validAnswers.includes(msg.content.toLowerCase()),
      { maxMatches: 1, time: 60 * 1000 }
    );

    trivia.on('collect', ans => {
      let color, description;
      if (ans.content.toLowerCase() === response.correct_answer.toLowerCase()) {
        color = Bastion.colors.BLUE;
        description = `${ans.author.tag} you're absolutely right.`;
      }
      else {
        color = Bastion.colors.RED;
        description = `Unfortunately, you're wrong ${ans.author.tag}`;
      }

      message.channel.send({
        embed: {
          color: color,
          description: description
        }
      }).catch(e => {
        Bastion.log.error(e);
      });
    });

    trivia.on('end', (answers, reason) => {
      activeChannels.splice(activeChannels.indexOf(message.channel.id), 1);

      if (reason === 'time') {
        message.channel.send({
          embed: {
            color: Bastion.colors.RED,
            title: 'Trivia Ended',
            description: 'Trivia was ended as no one was able to answer within 60 seconds.'
          }
        }).then(() => {
          question.delete().catch(e => {
            Bastion.log.error(e);
          });
        }).catch(e => {
          Bastion.log.error(e);
        });
      }
    });
  }
  catch (e) {
    if (e.response) {
      return Bastion.emit('error', e.response.statusCode, e.response.statusMessage, message.channel);
    }
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [],
  enabled: true
};

exports.help = {
  name: 'trivia',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'trivia',
  example: []
};
<|endoftext|>


<commit_before>/* This file lists the files to be fetched from the node repo
 * in the /lib/ directory which will be placed in the ../lib/
 * directory after having each of the "replacements" in the
 * array for that file applied to it. The replacements are
 * simply the arguments to String#replace, so they can be
 * strings, regexes, functions.
 */

const headRegexp = /(^module.exports = \w+;?)/m

    , requireReplacement = [
          /(require\(['"])(_stream_)/g
        , '$1./$2'
      ]

    , instanceofReplacement = [
          /instanceof Stream\.(\w+)/g
        , function (match, streamType) {
            return 'instanceof ' + streamType
          }
      ]

      // use the string_decoder in node_modules rather than core
    , stringDecoderReplacement = [
          /(require\(['"])(string_decoder)(['"]\))/g
        , '$1$2/$3'
      ]

    , bufferReplacement = [
          headRegexp
        , '$1\n\n/*<replacement>*/\nvar Buffer = require(\'buffer\').Buffer;\n/*</replacement>*/\n'
      ]

    , addDuplexRequire = [
          /^(function (?:Writable|Readable)(?:State)?.*{)/gm
        , '$1\n  var Duplex = require(\'./_stream_duplex\');\n'
      ]

    , altForEachImplReplacement = require('./common-replacements').altForEachImplReplacement
    , altForEachUseReplacement  = require('./common-replacements').altForEachUseReplacement
    , altIndexOfImplReplacement = require('./common-replacements').altIndexOfImplReplacement
    , altIndexOfUseReplacement  = require('./common-replacements').altIndexOfUseReplacement

    , utilReplacement = [
          /^var util = require\('util'\);/m
        ,   '\n/*<replacement>*/\nvar util = require(\'core-util-is\');\n'
          + 'util.inherits = require(\'inherits\');\n/*</replacement>*/\n'
      ]

    , debugLogReplacement = [
          /var debug = util.debuglog\('stream'\);/
      ,   '\n\n/*<replacement>*/\nvar debug = require(\'util\');\n'
        + 'if (debug && debug.debuglog) {\n'
        + '  debug = debug.debuglog(\'stream\');\n'
        + '} else {\n'
        + '  debug = function () {};\n'
        + '}\n/*</replacement>*/\n'
      ]

    , deprecateReplacement = [
          /util.deprecate/
      ,   'require(\'util-deprecate\')'
      ]

    , objectDefinePropertyReplacement = [
          /(Object\.defineProperties)/
      ,   'if (Object.defineProperties) $1'
      ]
    , objectDefinePropertySingReplacement = [
          /Object\.defineProperty\(([\w\W]+?)\}\);/
      ,   '(function (){try {\n'
        + 'Object.defineProperty\($1});\n'
        + '}catch(_){}}());\n'
      ]

    , isArrayDefine = [
          headRegexp
        , '$1\n\n/*<replacement>*/\nvar isArray = require(\'isarray\');\n/*</replacement>*/\n'
      ]

    , isArrayReplacement = [
          /Array\.isArray/g
        , 'isArray'
      ]

    , objectKeysDefine = require('./common-replacements').objectKeysDefine

    , objectKeysReplacement = require('./common-replacements').objectKeysReplacement

    , eventEmittterReplacement = [
        /(require\('events'\)\.EventEmitter;)/
      ,   '$1\n\n/*<replacement>*/\n'
        + 'var EElistenerCount = function(emitter, type) {\n'
        + '  return emitter.listeners(type).length;\n'
        + '};\n/*</replacement>*/\n'
      ]

      , eventEmittterListenerCountReplacement = [
          /(EE\.listenerCount)/g
        ,   'EElistenerCount'
        ]

    , constReplacement = [
        /const/g
      , 'var'
      ]

    , bufferIsEncodingReplacement = [
      /Buffer.isEncoding\((\w+)\)/
    ,   '([\'hex\', \'utf8\', \'utf-8\', \'ascii\', \'binary\', \'base64\',\n'
      + '\'ucs2\', \'ucs-2\',\'utf16le\', \'utf-16le\', \'raw\']\n'
      + '.indexOf(($1 + \'\').toLowerCase()) > -1)'
    ]

    , requireStreamReplacement = [
      /var Stream = require\('stream'\);/
    ,  '\n\n/*<replacement>*/\n'
      + 'var Stream;\n(function (){try{\n'
      + '  Stream = require(\'st\' + \'ream\');\n'
      + '}catch(_){}finally{\n'
      + '  if (!Stream)\n'
      + '    Stream = require(\'events\').EventEmitter;\n'
      + '}}())'
      + '\n/*</replacement>*/\n'
    ]

    , isBufferReplacement = [
      /(\w+) instanceof Buffer/g
    , 'Buffer.isBuffer($1)'
    ]

    , processNextTickImport = [
      headRegexp
    , '$1\n\n/*<replacement>*/\nvar processNextTick = require(\'process-nextick-args\');\n/*</replacement>*/\n'
    ]

    , processNextTickReplacement = [
      /process.nextTick\(/g
    , 'processNextTick('
    ]

    , internalUtilReplacement = [
          /^var internalUtil = require\('internal\/util'\);/m
        ,   '\n/*<replacement>*/\nvar internalUtil = {\n  deprecate: require(\'util-deprecate\')\n};\n'
          + '/*</replacement>*/\n'
      ]

module.exports['_stream_duplex.js'] = [
    constReplacement
  , requireReplacement
  , instanceofReplacement
  , utilReplacement
  , stringDecoderReplacement
  , altForEachImplReplacement
  , altForEachUseReplacement
  , objectKeysReplacement
  , objectKeysDefine
  , processNextTickImport
  , processNextTickReplacement
]

module.exports['_stream_passthrough.js'] = [
    constReplacement
  , requireReplacement
  , instanceofReplacement
  , utilReplacement
  , stringDecoderReplacement
]

module.exports['_stream_readable.js'] = [
    constReplacement
  , addDuplexRequire
  , requireReplacement
  , instanceofReplacement
  , bufferReplacement
  , altForEachImplReplacement
  , altForEachUseReplacement
  , altIndexOfImplReplacement
  , altIndexOfUseReplacement
  , instanceofReplacement
  , stringDecoderReplacement
  , isArrayDefine
  , isArrayReplacement
  , debugLogReplacement
  , utilReplacement
  , stringDecoderReplacement
  , eventEmittterReplacement
  , requireStreamReplacement
  , isBufferReplacement
  , processNextTickImport
  , processNextTickReplacement
  , eventEmittterListenerCountReplacement
]

module.exports['_stream_transform.js'] = [
    constReplacement
  , requireReplacement
  , instanceofReplacement
  , utilReplacement
  , stringDecoderReplacement
]

module.exports['_stream_writable.js'] = [
    constReplacement
  , addDuplexRequire
  , requireReplacement
  , instanceofReplacement
  , bufferReplacement
  , utilReplacement
  , stringDecoderReplacement
  , debugLogReplacement
  , deprecateReplacement
  , objectDefinePropertyReplacement
  , objectDefinePropertySingReplacement
  , bufferIsEncodingReplacement
  , [ /^var assert = require\('assert'\);$/m, '' ]
  , requireStreamReplacement
  , isBufferReplacement
  , processNextTickImport
  , processNextTickReplacement
  , internalUtilReplacement
]
<commit_msg>Do not overwrite module var<commit_after>/* This file lists the files to be fetched from the node repo
 * in the /lib/ directory which will be placed in the ../lib/
 * directory after having each of the "replacements" in the
 * array for that file applied to it. The replacements are
 * simply the arguments to String#replace, so they can be
 * strings, regexes, functions.
 */

const headRegexp = /(^module.exports = \w+;?)/m

    , requireReplacement = [
          /(require\(['"])(_stream_)/g
        , '$1./$2'
      ]

    , instanceofReplacement = [
          /instanceof Stream\.(\w+)/g
        , function (match, streamType) {
            return 'instanceof ' + streamType
          }
      ]

      // use the string_decoder in node_modules rather than core
    , stringDecoderReplacement = [
          /(require\(['"])(string_decoder)(['"]\))/g
        , '$1$2/$3'
      ]

    , bufferReplacement = [
          headRegexp
        , '$1\n\n/*<replacement>*/\nvar Buffer = require(\'buffer\').Buffer;\n/*</replacement>*/\n'
      ]

    , addDuplexRequire = [
          /^(function (?:Writable|Readable)(?:State)?.*{)/gm
        , '$1\n  var Duplex = require(\'./_stream_duplex\');\n'
      ]

    , altForEachImplReplacement = require('./common-replacements').altForEachImplReplacement
    , altForEachUseReplacement  = require('./common-replacements').altForEachUseReplacement
    , altIndexOfImplReplacement = require('./common-replacements').altIndexOfImplReplacement
    , altIndexOfUseReplacement  = require('./common-replacements').altIndexOfUseReplacement

    , utilReplacement = [
          /^var util = require\('util'\);/m
        ,   '\n/*<replacement>*/\nvar util = require(\'core-util-is\');\n'
          + 'util.inherits = require(\'inherits\');\n/*</replacement>*/\n'
      ]

    , debugLogReplacement = [
          /var debug = util.debuglog\('stream'\);/
      ,   '\n\n/*<replacement>*/\nvar debugUtil = require(\'util\');\n'
        + 'var debug;\n'
        + 'if (debugUtil && debugUtil.debuglog) {\n'
        + '  debug = debugUtil.debuglog(\'stream\');\n'
        + '} else {\n'
        + '  debug = function () {};\n'
        + '}\n/*</replacement>*/\n'
      ]

    , deprecateReplacement = [
          /util.deprecate/
      ,   'require(\'util-deprecate\')'
      ]

    , objectDefinePropertyReplacement = [
          /(Object\.defineProperties)/
      ,   'if (Object.defineProperties) $1'
      ]
    , objectDefinePropertySingReplacement = [
          /Object\.defineProperty\(([\w\W]+?)\}\);/
      ,   '(function (){try {\n'
        + 'Object.defineProperty\($1});\n'
        + '}catch(_){}}());\n'
      ]

    , isArrayDefine = [
          headRegexp
        , '$1\n\n/*<replacement>*/\nvar isArray = require(\'isarray\');\n/*</replacement>*/\n'
      ]

    , isArrayReplacement = [
          /Array\.isArray/g
        , 'isArray'
      ]

    , objectKeysDefine = require('./common-replacements').objectKeysDefine

    , objectKeysReplacement = require('./common-replacements').objectKeysReplacement

    , eventEmittterReplacement = [
        /(require\('events'\)\.EventEmitter;)/
      ,   '$1\n\n/*<replacement>*/\n'
        + 'var EElistenerCount = function(emitter, type) {\n'
        + '  return emitter.listeners(type).length;\n'
        + '};\n/*</replacement>*/\n'
      ]

      , eventEmittterListenerCountReplacement = [
          /(EE\.listenerCount)/g
        ,   'EElistenerCount'
        ]

    , constReplacement = [
        /const/g
      , 'var'
      ]

    , bufferIsEncodingReplacement = [
      /Buffer.isEncoding\((\w+)\)/
    ,   '([\'hex\', \'utf8\', \'utf-8\', \'ascii\', \'binary\', \'base64\',\n'
      + '\'ucs2\', \'ucs-2\',\'utf16le\', \'utf-16le\', \'raw\']\n'
      + '.indexOf(($1 + \'\').toLowerCase()) > -1)'
    ]

    , requireStreamReplacement = [
      /var Stream = require\('stream'\);/
    ,  '\n\n/*<replacement>*/\n'
      + 'var Stream;\n(function (){try{\n'
      + '  Stream = require(\'st\' + \'ream\');\n'
      + '}catch(_){}finally{\n'
      + '  if (!Stream)\n'
      + '    Stream = require(\'events\').EventEmitter;\n'
      + '}}())'
      + '\n/*</replacement>*/\n'
    ]

    , isBufferReplacement = [
      /(\w+) instanceof Buffer/g
    , 'Buffer.isBuffer($1)'
    ]

    , processNextTickImport = [
      headRegexp
    , '$1\n\n/*<replacement>*/\nvar processNextTick = require(\'process-nextick-args\');\n/*</replacement>*/\n'
    ]

    , processNextTickReplacement = [
      /process.nextTick\(/g
    , 'processNextTick('
    ]

    , internalUtilReplacement = [
          /^var internalUtil = require\('internal\/util'\);/m
        ,   '\n/*<replacement>*/\nvar internalUtil = {\n  deprecate: require(\'util-deprecate\')\n};\n'
          + '/*</replacement>*/\n'
      ]

module.exports['_stream_duplex.js'] = [
    constReplacement
  , requireReplacement
  , instanceofReplacement
  , utilReplacement
  , stringDecoderReplacement
  , altForEachImplReplacement
  , altForEachUseReplacement
  , objectKeysReplacement
  , objectKeysDefine
  , processNextTickImport
  , processNextTickReplacement
]

module.exports['_stream_passthrough.js'] = [
    constReplacement
  , requireReplacement
  , instanceofReplacement
  , utilReplacement
  , stringDecoderReplacement
]

module.exports['_stream_readable.js'] = [
    constReplacement
  , addDuplexRequire
  , requireReplacement
  , instanceofReplacement
  , bufferReplacement
  , altForEachImplReplacement
  , altForEachUseReplacement
  , altIndexOfImplReplacement
  , altIndexOfUseReplacement
  , instanceofReplacement
  , stringDecoderReplacement
  , isArrayDefine
  , isArrayReplacement
  , debugLogReplacement
  , utilReplacement
  , stringDecoderReplacement
  , eventEmittterReplacement
  , requireStreamReplacement
  , isBufferReplacement
  , processNextTickImport
  , processNextTickReplacement
  , eventEmittterListenerCountReplacement
]

module.exports['_stream_transform.js'] = [
    constReplacement
  , requireReplacement
  , instanceofReplacement
  , utilReplacement
  , stringDecoderReplacement
]

module.exports['_stream_writable.js'] = [
    constReplacement
  , addDuplexRequire
  , requireReplacement
  , instanceofReplacement
  , bufferReplacement
  , utilReplacement
  , stringDecoderReplacement
  , debugLogReplacement
  , deprecateReplacement
  , objectDefinePropertyReplacement
  , objectDefinePropertySingReplacement
  , bufferIsEncodingReplacement
  , [ /^var assert = require\('assert'\);$/m, '' ]
  , requireStreamReplacement
  , isBufferReplacement
  , processNextTickImport
  , processNextTickReplacement
  , internalUtilReplacement
]
<|endoftext|>


<commit_before>// When close the filter panel, clear the grid filters filtered by user (don't clear the default filter like the master filter in detail grid)

WulinMaster.behaviors.clearFilters = $.extend({}, WulinMaster.behaviors.BaseBehavior, {
  event: "onFilterPanelClosed",

  subscribe: function(target) {
    this.grid = target;
    var self = this;
    if(target.filterPanel) {
      target.filterPanel[this.event].subscribe(function(){ self.handler() });
    }
  },

  unsubscribe: function() {

  },

  handler: function() {
    var master = this.grid.master;
    // if the grid has no master grid, simply clear all filters, otherwise keep the master grid related filters
    if(!master) {
      this.grid.loader.setFilter([]);
    } else {
      this.grid.loader.setFilterWithoutRefresh([]);
      this.grid.loader.addFilter(master.filter_column, master.filter_value, master.filter_operator);
    }
  }

});

WulinMaster.BehaviorManager.register("clear_filters", WulinMaster.behaviors.clearFilters);<commit_msg>MISC - after close filter panel, clear the grid active cell<commit_after>// When close the filter panel, clear the grid filters filtered by user (don't clear the default filter like the master filter in detail grid)

WulinMaster.behaviors.clearFilters = $.extend({}, WulinMaster.behaviors.BaseBehavior, {
  event: "onFilterPanelClosed",

  subscribe: function(target) {
    this.grid = target;
    var self = this;
    if(target.filterPanel) {
      target.filterPanel[this.event].subscribe(function(){ self.handler() });
    }
  },

  unsubscribe: function() {

  },

  handler: function() {
    var master = this.grid.master;
    // if the grid has no master grid, simply clear all filters, otherwise keep the master grid related filters
    if(!master) {
      this.grid.loader.setFilter([]);
    } else {
      this.grid.loader.setFilterWithoutRefresh([]);
      this.grid.loader.addFilter(master.filter_column, master.filter_value, master.filter_operator);
    }
    this.grid.resetActiveCell();
  }

});

WulinMaster.BehaviorManager.register("clear_filters", WulinMaster.behaviors.clearFilters);<|endoftext|>


<commit_before>/*
 * The webapp module provides support for building web applications in Helma NG.
 */

// import modules
require('core/string');

include('helma/webapp/request');
include('helma/webapp/response');

import('helma/engine', 'engine');
import('helma/httpserver', 'server');
import('helma/logging', 'logging');

export('start', 'stop', 'getConfig', 'handleRequest');

var log = logging.getLogger(module.id);

module.shared = true;

/**
 * Handler function called by the JSGI servlet.
 *
 * @param env the JSGI environment argument
 */
function handleRequest(env) {
    // get config and apply it to req, res
    var config = getConfig();
    if (log.debugEnabled){
        log.debug('got config: ' + config.toSource());
    }

    var webenv = require('helma/webapp/env');
    webenv.env = env;
    var req = webenv.req = new Request(env);
    var res = null;

    req.charset = config.charset || 'utf8';

    // URI-decode path-info
    req.pathInfo = decodeURI(req.pathInfo);
    // remember current scriptname as application root as scriptName will be
    // set to actual script by resolveInConfig().
    req.rootPath = req.scriptName;

    try {
        res = resolveInConfig(req, config);
    } catch (e if e.redirect) {
        return new RedirectResponse(e.redirect);
    }
    return res;
}

function resolveInConfig(req, config) {
    if (log.debugEnabled) {
        log.debug('resolving path ' + req.pathInfo);
    }
    // set config property in webapp env module
    var webenv = require('helma/webapp/env');
    webenv.addConfig(config);

    if (!Array.isArray(config.urls)) {
        throw {notfound: true};
    }

    var path = req.pathInfo.replace(/^\/+|\/+$/g, "");

    for each (var urlEntry in config.urls) {
        if (log.debugEnabled) {
            log.debug("checking url line: " + urlEntry);
        }
        var match = getPattern(urlEntry).exec(path);
        if (log.debugEnabled) {
            log.debug("got match: " + match);
        }

        if (match) {
            var module = getModule(urlEntry);
            if (log.debugEnabled) {
                log.debug("module: " + module);
            }
            // move matching path fragment from PATH_INFO to SCRIPT_NAME
            req.appendToScriptName(match[0]);
            // prepare action arguments, adding regexp capture groups if any
            var args = [req].concat(match.slice(1));
            // lookup action in module
            var action = getAction(req, module, args);
            // log.debug("got action: " + action);
            if (typeof action == "function") {
                var res = action.apply(module, args);
                if (res && typeof res.close === 'function') {
                    return res.close();
                }
                return res;
            } else if (Array.isArray(module.urls)) {
                // make sure request path has trailing slash
                if (!req.pathInfo && match.slice(1).join('').length == 0) {
                    req.checkTrailingSlash();
                }
                return resolveInConfig(req, module);
            } else {
                throw {notfound: true};
            }
        }
    }
}

function getPattern(spec) {
    var pattern = spec[0];
    if (typeof pattern == "string") {
        if (pattern.startsWith("/"))
            pattern = pattern.replace("/", "^");
        pattern = spec[0] = new RegExp(pattern);
    } else if (!(pattern instanceof RegExp)) {
        throw Error("Pattern must be a regular expression or string");
    }
    return pattern;
}

function getModule(spec) {
    var module = spec[1];
    if (typeof module == "string") {
        module = require(module);
    } else if (!(module instanceof Object)) {
        throw Error("Module must be a string or object");
    }
    return module;
}

function getAction(req, module, args) {
    var path = splitPath(req.pathInfo);
    var action, name = path[0];
    if (name) {
        action = module[name.replace(/\./g, "_")];
        if (typeof action == "function") {
            // If the request path contains additional elements check whether the
            // candidate function has formal arguments to take them
            if (path.length <= 1 || args.length + path.length - 1 <= action.length) {
                req.appendToScriptName(name);
                Array.prototype.push.apply(args, path.slice(1));
                return action;
            }
        }
    }
    action = module["index"];
    if (typeof action == "function") {
        if (path.length == 0 || args.length + path.length <= action.length) {
            if (args.slice(1).join('').length == 0) {
                req.checkTrailingSlash();
            }
            Array.prototype.push.apply(args, path);
            return action;
        }
    }
    return null;
}

function splitPath(path) {
    //remove leading and trailing slashes and split
    var array = path.replace(/^\/+|\/+$/g, "").split(/\/+/);
    return array.length == 1 && array[0] == "" ? [] : array;
}

/**
 * Try to load the configuration module.
 * @param configModuleName optional module name, default is 'config'
 */
function getConfig(configModuleName) {
    configModuleName = configModuleName || 'config';
    return require(configModuleName);
}

/**
 * Start the jetty server.
 */
function start(config) {
    // start jetty http server
    config = config || getConfig();
    var httpConfig = config.httpConfig;
    server.start(httpConfig);
}

/**
 * Stop the jetty server.
 */
function stop() {
    // stop jetty HTTP server
    server.stop();
}

if (require.main == module.id) {
    for (var i = 1; i < system.args.length; i++) {
        var arg = system.args[i];
        if (arg.indexOf('-') == 0) {
            break;
        }
        engine.addRepository(arg);
    }
    log.info('Setup module search: ' + engine.getRepositories());
    start();
}
<commit_msg>Remove code that isn't needed anymore.<commit_after>/*
 * The webapp module provides support for building web applications in Helma NG.
 */

// import modules
require('core/string');

include('helma/webapp/request');
include('helma/webapp/response');

import('helma/engine', 'engine');
import('helma/httpserver', 'server');
import('helma/logging', 'logging');

export('start', 'stop', 'getConfig', 'handleRequest');

var log = logging.getLogger(module.id);

module.shared = true;

/**
 * Handler function called by the JSGI servlet.
 *
 * @param env the JSGI environment argument
 */
function handleRequest(env) {
    // get config and apply it to req, res
    var config = getConfig();
    if (log.debugEnabled){
        log.debug('got config: ' + config.toSource());
    }

    var webenv = require('helma/webapp/env');
    webenv.env = env;
    var req = webenv.req = new Request(env);
    var res = null;

    req.charset = config.charset || 'utf8';

    // URI-decode path-info
    req.pathInfo = decodeURI(req.pathInfo);
    // remember current scriptname as application root as scriptName will be
    // set to actual script by resolveInConfig().
    req.rootPath = req.scriptName;

    try {
        res = resolveInConfig(req, config);
    } catch (e if e.redirect) {
        return new RedirectResponse(e.redirect);
    }
    return res;
}

function resolveInConfig(req, config) {
    if (log.debugEnabled) {
        log.debug('resolving path ' + req.pathInfo);
    }
    // set config property in webapp env module
    var webenv = require('helma/webapp/env');
    webenv.addConfig(config);

    if (!Array.isArray(config.urls)) {
        throw {notfound: true};
    }

    var path = req.pathInfo.replace(/^\/+|\/+$/g, "");

    for each (var urlEntry in config.urls) {
        if (log.debugEnabled) {
            log.debug("checking url line: " + urlEntry);
        }
        var match = getPattern(urlEntry).exec(path);
        if (log.debugEnabled) {
            log.debug("got match: " + match);
        }

        if (match) {
            var module = getModule(urlEntry);
            if (log.debugEnabled) {
                log.debug("module: " + module);
            }
            // move matching path fragment from PATH_INFO to SCRIPT_NAME
            req.appendToScriptName(match[0]);
            // prepare action arguments, adding regexp capture groups if any
            var args = [req].concat(match.slice(1));
            // lookup action in module
            var action = getAction(req, module, args);
            // log.debug("got action: " + action);
            if (typeof action == "function") {
                var res = action.apply(module, args);
                if (res && typeof res.close === 'function') {
                    return res.close();
                }
                return res;
            } else if (Array.isArray(module.urls)) {
                return resolveInConfig(req, module);
            } else {
                throw {notfound: true};
            }
        }
    }
}

function getPattern(spec) {
    var pattern = spec[0];
    if (typeof pattern == "string") {
        if (pattern.startsWith("/"))
            pattern = pattern.replace("/", "^");
        pattern = spec[0] = new RegExp(pattern);
    } else if (!(pattern instanceof RegExp)) {
        throw Error("Pattern must be a regular expression or string");
    }
    return pattern;
}

function getModule(spec) {
    var module = spec[1];
    if (typeof module == "string") {
        module = require(module);
    } else if (!(module instanceof Object)) {
        throw Error("Module must be a string or object");
    }
    return module;
}

function getAction(req, module, args) {
    var path = splitPath(req.pathInfo);
    var action, name = path[0];
    if (name) {
        action = module[name.replace(/\./g, "_")];
        if (typeof action == "function") {
            // If the request path contains additional elements check whether the
            // candidate function has formal arguments to take them
            if (path.length <= 1 || args.length + path.length - 1 <= action.length) {
                req.appendToScriptName(name);
                Array.prototype.push.apply(args, path.slice(1));
                return action;
            }
        }
    }
    action = module["index"];
    if (typeof action == "function") {
        if (path.length == 0 || args.length + path.length <= action.length) {
            if (args.slice(1).join('').length == 0) {
                req.checkTrailingSlash();
            }
            Array.prototype.push.apply(args, path);
            return action;
        }
    }
    return null;
}

function splitPath(path) {
    //remove leading and trailing slashes and split
    var array = path.replace(/^\/+|\/+$/g, "").split(/\/+/);
    return array.length == 1 && array[0] == "" ? [] : array;
}

/**
 * Try to load the configuration module.
 * @param configModuleName optional module name, default is 'config'
 */
function getConfig(configModuleName) {
    configModuleName = configModuleName || 'config';
    return require(configModuleName);
}

/**
 * Start the jetty server.
 */
function start(config) {
    // start jetty http server
    config = config || getConfig();
    var httpConfig = config.httpConfig;
    server.start(httpConfig);
}

/**
 * Stop the jetty server.
 */
function stop() {
    // stop jetty HTTP server
    server.stop();
}

if (require.main == module.id) {
    for (var i = 1; i < system.args.length; i++) {
        var arg = system.args[i];
        if (arg.indexOf('-') == 0) {
            break;
        }
        engine.addRepository(arg);
    }
    log.info('Setup module search: ' + engine.getRepositories());
    start();
}
<|endoftext|>