<commit_before>var shapetime = {};

function stateUpdated() {
  // 'state' is an object of key-value pairs that map ids to JSON serialization of SVG elements
  // 'keys' is an array of all the keys in the state
  var state = wave.getState();
  var keys = state.getKeys();
  svgCanvas.each(function(e) {
    // 'this' is the SVG DOM element node (ellipse, rect, etc)
    // 'e' is an integer describing the position within the document
    var k = this.id;
    var v = state.get(k);
    if (v) {
      var ob = JSON.parse(v);
      if (ob) {
        // do nothing
      } else {
        //var node = document.getElementById(k);
        //if (node) node.parentNode.removeChild(node);
      }
      //keys.remove(k);

    } else if(this.id != "selectorParentGroup"){
      //console.log(this)
      this.parentNode.removeChild(this);
    }
  });

  // New nodes
  for (var k in keys) {
    var v = state.get(keys[k]);
    var ob = JSON.parse(v);
    if (ob){
      if(!shapetime[k] || ob.time > shapetime[k]){
        var a;
        if(a = document.getElementById(k)){
          var attrs = {};
          for(var i = a.length; i--;){
            attrs[a.item(i).nodeName] = a.item(i).nodeValue;
          }
          if(JSON.stringify(attrs) != JSON.stringify(ob.attr)){
            shapetime[k] = ob.time
            svgCanvas.updateElementFromJson(ob)
          }
        }else{
          shapetime[k] = ob.time
          svgCanvas.updateElementFromJson(ob)
        }

      }
    }
  }
}

function getId(canvas, objnum) {
  return "svg_"+wave.getViewer().getId()+"_"+objnum;
}

function main() {
  $(document).ready(function(){
    if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(stateUpdated);
    }

    var oldchanged = svgCanvas.bind("changed", function(canvas, elem){
      if(oldchanged)oldchanged.apply(this, [canvas,elem]);

      var delta = {}
      $.each(elem, function(){

        var attrs = {};
        var a = this.attributes;
        if(a){
          for(var i = a.length; i--;){
            attrs[a.item(i).nodeName] = a.item(i).nodeValue;
          }
          var ob = {element: this.nodeName, attr: attrs};

          ob.time = shapetime[this.id] = (new Date).getTime()
          delta[this.id] = JSON.stringify(ob);
        }
      })
      wave.getState().submitDelta(delta)
      //sendDelta(canvas, elem)
    });
    var oldselected = svgCanvas.bind("selected", function(canvas, elem){

      if(oldselected)oldselected.apply(this, [canvas,elem]);

      var delta = {}
      var deletions = 0;
      $.each(elem, function(){
        console.log(elem)
        if(!this.parentNode){
          delta[this.id] = null;

          deletions ++
        }
      });
      if(deletions > 0){
        wave.getState().submitDelta(delta)
      }
    });
    svgCanvas.bind("cleared", function(){
      //alert("cleared")
        var state = {}, keys = wave.getState().getKeys()
        for(var i = 0; i < keys.length; i++){
          state[keys[i]] = null;
        }
        wave.getState().submitDelta(state)
    });
    svgCanvas.bind("getid", getId);
  })
}

gadgets.util.registerOnLoadHandler(main);
<commit_msg>remvoed logging<commit_after>var shapetime = {};

function stateUpdated() {
  // 'state' is an object of key-value pairs that map ids to JSON serialization of SVG elements
  // 'keys' is an array of all the keys in the state
  var state = wave.getState();
  var keys = state.getKeys();
  svgCanvas.each(function(e) {
    // 'this' is the SVG DOM element node (ellipse, rect, etc)
    // 'e' is an integer describing the position within the document
    var k = this.id;
    var v = state.get(k);
    if (v) {
      var ob = JSON.parse(v);
      if (ob) {
        // do nothing
      } else {
        //var node = document.getElementById(k);
        //if (node) node.parentNode.removeChild(node);
      }
      //keys.remove(k);

    } else if(this.id != "selectorParentGroup"){
      //console.log(this)
      this.parentNode.removeChild(this);
    }
  });

  // New nodes
  for (var k in keys) {
    var v = state.get(keys[k]);
    var ob = JSON.parse(v);
    if (ob){
      if(!shapetime[k] || ob.time > shapetime[k]){
        var a;
        if(a = document.getElementById(k)){
          var attrs = {};
          for(var i = a.length; i--;){
            attrs[a.item(i).nodeName] = a.item(i).nodeValue;
          }
          if(JSON.stringify(attrs) != JSON.stringify(ob.attr)){
            shapetime[k] = ob.time
            svgCanvas.updateElementFromJson(ob)
          }
        }else{
          shapetime[k] = ob.time
          svgCanvas.updateElementFromJson(ob)
        }

      }
    }
  }
}

function getId(canvas, objnum) {
  return "svg_"+wave.getViewer().getId()+"_"+objnum;
}

function main() {
  $(document).ready(function(){
    if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(stateUpdated);
    }

    var oldchanged = svgCanvas.bind("changed", function(canvas, elem){
      if(oldchanged)oldchanged.apply(this, [canvas,elem]);

      var delta = {}
      $.each(elem, function(){

        var attrs = {};
        var a = this.attributes;
        if(a){
          for(var i = a.length; i--;){
            attrs[a.item(i).nodeName] = a.item(i).nodeValue;
          }
          var ob = {element: this.nodeName, attr: attrs};

          ob.time = shapetime[this.id] = (new Date).getTime()
          delta[this.id] = JSON.stringify(ob);
        }
      })
      wave.getState().submitDelta(delta)
      //sendDelta(canvas, elem)
    });
    var oldselected = svgCanvas.bind("selected", function(canvas, elem){

      if(oldselected)oldselected.apply(this, [canvas,elem]);

      var delta = {}
      var deletions = 0;
      $.each(elem, function(){
        if(!this.parentNode){
          delta[this.id] = null;

          deletions ++
        }
      });
      if(deletions > 0){
        wave.getState().submitDelta(delta)
      }
    });
    svgCanvas.bind("cleared", function(){
      //alert("cleared")
        var state = {}, keys = wave.getState().getKeys()
        for(var i = 0; i < keys.length; i++){
          state[keys[i]] = null;
        }
        wave.getState().submitDelta(state)
    });
    svgCanvas.bind("getid", getId);
  })
}

gadgets.util.registerOnLoadHandler(main);
<|endoftext|>


<commit_before>/**
 * Created by swaathi on 28/03/17.
 */

class VariantUtils {

    static jsonToTabConvert(json, studiesPopFrequencies) {
        let dataString = [];
        let variantString = [];
        let populationMap = {};

        for (var key in json[0]) {
            console.log(key);
        }

        variantString.push("Variant");
        variantString.push("SNP ID");
        variantString.push("Genes");
        variantString.push("Type");
        variantString.push("Consequence Type");
        variantString.push("SIFT");
        variantString.push("Polyphen");
        variantString.push("CADD");
        variantString.push("PhyloP");
        variantString.push("PhastCons");
        variantString.push("GERP");
        // variantString.push("Population frequencies");
        studiesPopFrequencies.forEach((study) => {
            study.populations.forEach(pop => variantString.push(study.id + "_" + pop.id));
        });
        variantString.push("Clinvar");
        variantString.push("Cosmic");
        dataString.push(variantString.join('\t'));
        variantString = [];
        for (let i = 0; i < json.length; i++) {
            variantString.push(json[i].chromosome + ':' + json[i].start + " " + json[i].reference + '/' + json[i].alternate);
            variantString.push(json[i].id);
            let genes = [];
            let ct = [];
            let pfArray  = [];
            let sift, polyphen, cadd = "-", phylop = "-", phastCons = "-", gerp = "-";
            let clinvar = [];
            let cosmic = [];

            if (typeof json[i].annotation !== "undefined") {
                if (typeof json[i].annotation.consequenceTypes !== "undefined" && json[i].annotation.consequenceTypes.length > 0) {
                    let visitedGenes = {};
                    let visitedCT = new Set();
                    for (let j = 0; j < json[i].annotation.consequenceTypes.length; j++) {
                        // gene
                        if (typeof json[i].annotation.consequenceTypes[j].geneName !== "undefined" && json[i].annotation.consequenceTypes[j].geneName != ""
                            && typeof visitedGenes[json[i].annotation.consequenceTypes[j].geneName] === "undefined") {
                            genes.push(json[i].annotation.consequenceTypes[j].geneName);
                            visitedGenes[json[i].annotation.consequenceTypes[j].geneName] = true;
                        }

                        // Consequence Type
                        for (let z = 0; z < json[i].annotation.consequenceTypes[j].sequenceOntologyTerms.length; z++) {
                            let consequenceTypeName = json[i].annotation.consequenceTypes[j].sequenceOntologyTerms[z].name;
                            if (typeof consequenceTypeName !== "undefined" && consequenceTypeName != "" && !visitedCT.has(consequenceTypeName)) {
                                ct.push(consequenceTypeName);
                                visitedCT.add(consequenceTypeName);
                            }
                        }

                        // Sift, Polyphen
                        let min = 10;
                        let max = 0;
                        let description = {};
                        if (typeof json[i].annotation.consequenceTypes[j].proteinVariantAnnotation !== "undefined"
                            && typeof json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores !== "undefined") {
                            for (let ss = 0; ss < json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores.length; ss++) {
                                let source = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].source;
                                switch (source) {
                                    case "sift":
                                        if (json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score < min) {
                                            min = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score;
                                            description.sift = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].description;
                                        }
                                        break;
                                    case "polyphen":
                                        if (json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score > max) {
                                            max = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score;
                                            description.polyphen = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].description;
                                        }
                                        break;
                                }
                            }
                        }
                        sift = typeof description.sift !== "undefined" ? description.sift : "-";
                        polyphen = typeof description.polyphen !== "undefined" ? description.polyphen : "-";
                    }
                }
                // CADD
                if (typeof json[i].annotation.functionalScore !== "undefined") {
                    for (let fs = 0; fs < json[i].annotation.functionalScore.length; fs++) {
                        if (typeof json[i].annotation.functionalScore[fs] !== "undefined" && json[i].annotation.functionalScore[fs].source == "cadd_scaled") {
                            cadd = Number(json[i].annotation.functionalScore[fs].score).toFixed(2);
                        }
                    }
                }

                // Conservation
                if (typeof json[i].annotation.conservation !== "undefined") {
                    for (let cons = 0; cons < json[i].annotation.conservation.length; cons++) {
                        switch (json[i].annotation.conservation[cons].source) {
                            case "phylop":
                                phylop = Number(json[i].annotation.conservation[cons].score).toFixed(3);
                                break;
                            case "phastCons":
                                phastCons = Number(json[i].annotation.conservation[cons].score).toFixed(3);
                                break;
                            case "gerp":
                                gerp = Number(json[i].annotation.conservation[cons].score).toFixed(3);
                                break;
                        }
                    }
                }

                // Population frequency
                let populations = [];
                let populationStudyBidimensional = [];
                let populationMapExists = [];
                studiesPopFrequencies.forEach((study) => {
                    populations[study.id] = study.populations.map(pop => pop.id);
                    study.populations.forEach((pop) => {
                        populationMapExists[pop.id] = true;
                    });
                    populationStudyBidimensional[study.id] = populationMapExists;
                });
                if (typeof studiesPopFrequencies !== "undefined" && studiesPopFrequencies.length > 0) {
                    for (let j = 0; j < studiesPopFrequencies.length; j++) {
                        let study = studiesPopFrequencies[j];
                        for (let popFreqIdx in json[i].annotation.populationFrequencies) {
                            let popFreq = json[i].annotation.populationFrequencies[popFreqIdx];
                            if (UtilsNew.isNotUndefinedOrNull(popFreq)) {
                                let population = popFreq.population;
                                if (study.id === popFreq.study && populationStudyBidimensional[study.id][population] === true) {
                                    populationMap[study.id + "_" + population] = 'NA';
                                }
                            }
                        }
                    }
                }

                if (typeof json[i].annotation.populationFrequencies !== "undefined") {
                    for (let pf = 0; pf < json[i].annotation.populationFrequencies.length; pf++) {
                        let pop = json[i].annotation.populationFrequencies[pf].study + '_' + json[i].annotation.populationFrequencies[pf].population;
                        if (typeof populationMap[pop] !== "undefined" && populationMap[pop] == "NA") {
                            populationMap[pop] = Number(json[i].annotation.populationFrequencies[pf].altAlleleFreq).toFixed(4);
                        }
                    }
                }
                // pfArray = Object.keys(populationMap).map(key => populationMap[key]);

                // Clinvar, cosmic
                if (typeof json[i].annotation.variantTraitAssociation !== "undefined" && json[i].annotation.variantTraitAssociation != null) {
                    for (let key in json[i].annotation.variantTraitAssociation) {
                        let clinicalData = json[i].annotation.variantTraitAssociation[key];
                        if (typeof clinicalData !== "undefined") {
                            for (let cd = 0; cd < clinicalData.length; cd++) {
                                switch (key) {
                                    case "clinvar":
                                        clinvar.push(clinicalData[cd].traits[0]);
                                        break;
                                    case "cosmic":
                                        cosmic.push(clinicalData[cd].primaryHistology);
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            if (genes.length > 0) {
                variantString.push(genes.join(','));
            } else {
                variantString.push("-");
            }
            variantString.push(json[i].type);
            if (ct.length > 0) {
                variantString.push(ct.join(','));
            } else {
                variantString.push("-");
            }
            variantString.push(sift);
            variantString.push(polyphen);
            variantString.push(cadd);
            variantString.push(phylop);
            variantString.push(phastCons);
            variantString.push(gerp);
            studiesPopFrequencies.forEach((study) => {
                study.populations.forEach(pop => variantString.push(populationMap[study.id + "_" + pop.id]));
            });
            // variantString.push(pfArray.join(','));
            if (clinvar.length > 0) {
                variantString.push(clinvar.join(','));
            } else {
                variantString.push("-");
            }
            if (cosmic.length > 0) {
                variantString.push(cosmic.join(','));
            } else {
                variantString.push("-");
            }

            dataString.push(variantString.join('\t'));
            variantString = [];
        }
        return dataString;
    }
}<commit_msg>core: Fixed error on download tab with population frequencies nil values<commit_after>/**
 * Created by swaathi on 28/03/17.
 */

class VariantUtils {

    static jsonToTabConvert(json, studiesPopFrequencies) {
        let dataString = [];
        let populationMap = {};

        let variantString = [];
        for (var key in json[0]) {
            console.log(key);

        }
        variantString.push("Variant");
        variantString.push("SNP ID");
        variantString.push("Genes");
        variantString.push("Type");
        variantString.push("Consequence Type");
        variantString.push("SIFT");
        variantString.push("Polyphen");
        variantString.push("CADD");
        variantString.push("PhyloP");
        variantString.push("PhastCons");
        variantString.push("GERP");
        // variantString.push("Population frequencies");
        studiesPopFrequencies.forEach((study) => {
            study.populations.forEach(pop => variantString.push(study.id + "_" + pop.id));
        });
        variantString.push("Clinvar");
        variantString.push("Cosmic");
        dataString.push(variantString.join('\t'));
        variantString = [];
        for (let i = 0; i < json.length; i++) {
            variantString.push(json[i].chromosome + ':' + json[i].start + " " + json[i].reference + '/' + json[i].alternate);
            variantString.push(json[i].id);
            let genes = [];
            let ct = [];
            let pfArray  = [];
            let sift, polyphen, cadd = "-", phylop = "-", phastCons = "-", gerp = "-";
            let clinvar = [];
            let cosmic = [];
            populationMap = {};

            if (typeof json[i].annotation !== "undefined") {
                if (typeof json[i].annotation.consequenceTypes !== "undefined" && json[i].annotation.consequenceTypes.length > 0) {
                    let visitedGenes = {};
                    let visitedCT = new Set();
                    for (let j = 0; j < json[i].annotation.consequenceTypes.length; j++) {
                        // gene
                        if (typeof json[i].annotation.consequenceTypes[j].geneName !== "undefined" && json[i].annotation.consequenceTypes[j].geneName != ""
                            && typeof visitedGenes[json[i].annotation.consequenceTypes[j].geneName] === "undefined") {
                            genes.push(json[i].annotation.consequenceTypes[j].geneName);
                            visitedGenes[json[i].annotation.consequenceTypes[j].geneName] = true;
                        }

                        // Consequence Type
                        for (let z = 0; z < json[i].annotation.consequenceTypes[j].sequenceOntologyTerms.length; z++) {
                            let consequenceTypeName = json[i].annotation.consequenceTypes[j].sequenceOntologyTerms[z].name;
                            if (typeof consequenceTypeName !== "undefined" && consequenceTypeName != "" && !visitedCT.has(consequenceTypeName)) {
                                ct.push(consequenceTypeName);
                                visitedCT.add(consequenceTypeName);
                            }
                        }

                        // Sift, Polyphen
                        let min = 10;
                        let max = 0;
                        let description = {};
                        if (typeof json[i].annotation.consequenceTypes[j].proteinVariantAnnotation !== "undefined"
                            && typeof json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores !== "undefined") {
                            for (let ss = 0; ss < json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores.length; ss++) {
                                let source = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].source;
                                switch (source) {
                                    case "sift":
                                        if (json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score < min) {
                                            min = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score;
                                            description.sift = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].description;
                                        }
                                        break;
                                    case "polyphen":
                                        if (json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score > max) {
                                            max = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].score;
                                            description.polyphen = json[i].annotation.consequenceTypes[j].proteinVariantAnnotation.substitutionScores[ss].description;
                                        }
                                        break;
                                }
                            }
                        }
                        sift = typeof description.sift !== "undefined" ? description.sift : "-";
                        polyphen = typeof description.polyphen !== "undefined" ? description.polyphen : "-";
                    }
                }
                // CADD
                if (typeof json[i].annotation.functionalScore !== "undefined") {
                    for (let fs = 0; fs < json[i].annotation.functionalScore.length; fs++) {
                        if (typeof json[i].annotation.functionalScore[fs] !== "undefined" && json[i].annotation.functionalScore[fs].source == "cadd_scaled") {
                            cadd = Number(json[i].annotation.functionalScore[fs].score).toFixed(2);
                        }
                    }
                }

                // Conservation
                if (typeof json[i].annotation.conservation !== "undefined") {
                    for (let cons = 0; cons < json[i].annotation.conservation.length; cons++) {
                        switch (json[i].annotation.conservation[cons].source) {
                            case "phylop":
                                phylop = Number(json[i].annotation.conservation[cons].score).toFixed(3);
                                break;
                            case "phastCons":
                                phastCons = Number(json[i].annotation.conservation[cons].score).toFixed(3);
                                break;
                            case "gerp":
                                gerp = Number(json[i].annotation.conservation[cons].score).toFixed(3);
                                break;
                        }
                    }
                }

                // Population frequency
                let populations = [];
                let populationStudyBidimensional = [];
                let populationMapExists = [];
                studiesPopFrequencies.forEach((study) => {
                    populations[study.id] = study.populations.map(pop => pop.id);
                    study.populations.forEach((pop) => {
                        populationMapExists[pop.id] = true;
                    });
                    populationStudyBidimensional[study.id] = populationMapExists;
                });
                if (typeof studiesPopFrequencies !== "undefined" && studiesPopFrequencies.length > 0) {
                    for (let j = 0; j < studiesPopFrequencies.length; j++) {
                        let study = studiesPopFrequencies[j];
                        for (let popFreqIdx in json[i].annotation.populationFrequencies) {
                            let popFreq = json[i].annotation.populationFrequencies[popFreqIdx];
                            if (UtilsNew.isNotUndefinedOrNull(popFreq)) {
                                let population = popFreq.population;
                                if (study.id === popFreq.study && populationStudyBidimensional[study.id][population] === true) {
                                    populationMap[study.id + "_" + population] = 'NA';
                                }
                            }
                        }
                    }
                }

                if (typeof json[i].annotation.populationFrequencies !== "undefined") {
                    for (let pf = 0; pf < json[i].annotation.populationFrequencies.length; pf++) {
                        let pop = json[i].annotation.populationFrequencies[pf].study + '_' + json[i].annotation.populationFrequencies[pf].population;
                        if (typeof populationMap[pop] !== "undefined" && populationMap[pop] == "NA") {
                            populationMap[pop] = Number(json[i].annotation.populationFrequencies[pf].altAlleleFreq).toFixed(4);
                        }
                    }
                }
                // pfArray = Object.keys(populationMap).map(key => populationMap[key]);

                // Clinvar, cosmic
                if (typeof json[i].annotation.variantTraitAssociation !== "undefined" && json[i].annotation.variantTraitAssociation != null) {
                    for (let key in json[i].annotation.variantTraitAssociation) {
                        let clinicalData = json[i].annotation.variantTraitAssociation[key];
                        if (typeof clinicalData !== "undefined") {
                            for (let cd = 0; cd < clinicalData.length; cd++) {
                                switch (key) {
                                    case "clinvar":
                                        clinvar.push(clinicalData[cd].traits[0]);
                                        break;
                                    case "cosmic":
                                        cosmic.push(clinicalData[cd].primaryHistology);
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            if (genes.length > 0) {
                variantString.push(genes.join(','));
            } else {
                variantString.push("-");
            }
            variantString.push(json[i].type);
            if (ct.length > 0) {
                variantString.push(ct.join(','));
            } else {
                variantString.push("-");
            }
            variantString.push(sift);
            variantString.push(polyphen);
            variantString.push(cadd);
            variantString.push(phylop);
            variantString.push(phastCons);
            variantString.push(gerp);
            studiesPopFrequencies.forEach((study) => {
                study.populations.forEach(pop => variantString.push(populationMap[study.id + "_" + pop.id]));
            });
            // variantString.push(pfArray.join(','));
            if (clinvar.length > 0) {
                variantString.push(clinvar.join(','));
            } else {
                variantString.push("-");
            }
            if (cosmic.length > 0) {
                variantString.push(cosmic.join(','));
            } else {
                variantString.push("-");
            }

            dataString.push(variantString.join('\t'));
            variantString = [];
        }
        return dataString;
    }
}<|endoftext|>


<commit_before>// see https://github.com/gajus/eslint-plugin-jsdoc

module.exports = {
	// Require JSDoc comments
	'require-jsdoc': [ 'error', {
		require: {
			MethodDefinition: true,
		},
	} ],
	// Ensure JSDoc comments are valid
	'valid-jsdoc': [ 'error', {
		prefer: {
			returns: 'return',
		},
	} ],
	// Ensures that parameter names in JSDoc match those in the function declaration.
	'jsdoc/check-param-names': 'warn',
	// Reports invalid block tag names.
	'jsdoc/check-tag-names': 'warn',
	// Reports invalid types.
	'jsdoc/check-types': 'warn',
	// Enforces a consistent padding of the block description.
	'jsdoc/newline-after-description': 'warn',
	// Requires that block description and tag description are written in complete sentences.
	'jsdoc/require-description-complete-sentence': 'warn',
	// Requires that all functions have examples.
	'jsdoc/require-example': 'off',
	// Requires a hyphen before the @param description.
	'jsdoc/require-hyphen-before-param-description': 'off',
	// Requires that all function parameters are documented.
	'jsdoc/require-param': 'warn',
	// Requires that @param tag has description value.
	'jsdoc/require-param-description': 'warn',
	// Requires that @param tag has type value.
	'jsdoc/require-param-type': 'warn',
	// Requires that @returns tag has description value.
	'jsdoc/require-returns-description': 'warn',
	// Requires that @returns tag has type value.
	'jsdoc/require-returns-type': 'warn',
};
<commit_msg>fix: assign preferred JSDoc tags and types for ESLint `valid-jsdoc` rule<commit_after>// see https://github.com/gajus/eslint-plugin-jsdoc

module.exports = {
	// Require JSDoc comments
	'require-jsdoc': [ 'error', {
		require: {
			MethodDefinition: true,
		},
	} ],
	// Ensure JSDoc comments are valid
	'valid-jsdoc': [ 'error', {
		prefer: {
			arg: 'param',
			argument: 'param',
			extends: 'augments',
			returns: 'return',
		},
		preferType: {
			array: 'Array',
			bool: 'boolean',
			Boolean: 'boolean',
			float: 'number',
			Float: 'number',
			int: 'number',
			integer: 'number',
			Integer: 'number',
			Number: 'number',
			object: 'Object',
			String: 'string',
			Void: 'void',
		},
		requireParamDescription: false,
		requireReturn: false,
	} ],
	// Ensures that parameter names in JSDoc match those in the function declaration.
	'jsdoc/check-param-names': 'warn',
	// Reports invalid block tag names.
	'jsdoc/check-tag-names': 'warn',
	// Reports invalid types.
	'jsdoc/check-types': 'warn',
	// Enforces a consistent padding of the block description.
	'jsdoc/newline-after-description': 'warn',
	// Requires that block description and tag description are written in complete sentences.
	'jsdoc/require-description-complete-sentence': 'warn',
	// Requires that all functions have examples.
	'jsdoc/require-example': 'off',
	// Requires a hyphen before the @param description.
	'jsdoc/require-hyphen-before-param-description': 'off',
	// Requires that all function parameters are documented.
	'jsdoc/require-param': 'warn',
	// Requires that @param tag has description value.
	'jsdoc/require-param-description': 'warn',
	// Requires that @param tag has type value.
	'jsdoc/require-param-type': 'warn',
	// Requires that @returns tag has description value.
	'jsdoc/require-returns-description': 'warn',
	// Requires that @returns tag has type value.
	'jsdoc/require-returns-type': 'warn',
};
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.0.0');
		this.setClientTag('node:22-03-11');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.0.0');
		this.setClientTag('node:22-03-12');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>//= require libs/GlobalBarHelper.js

'use strict'
window.GOVUK = window.GOVUK || {}

// Bump this if you are releasing a major change to the banner
// This will reset the view count so all users will see the banner, even if previously seen
var BANNER_VERSION = 3;

var globalBarInit = {
  getBannerVersion: function() {
    return BANNER_VERSION
  },

  getLatestCookie: function() {
    var currentCookie = document.cookie.match("(?:^|[ ;])(?:global_bar_seen=)(.+?)(?:(?=;|$))")

    if (currentCookie == null) {
      return currentCookie
    } else {
      return currentCookie[1]
    }
  },

  blacklistedUrl: function() {
    var paths = [
      "/register-to-vote",
      "/done",
      "/transition",
      "/transition-check"
    ]

    return new RegExp(paths.join("|")).test(window.location.pathname)
  },

  setBannerCookie: function() {
    var eighty_four_days = 84*24*60*60*1000
    var expiryDate = new Date(Date.now() + eighty_four_days).toUTCString()
    var value = JSON.stringify({count: 0, version: globalBarInit.getBannerVersion()})
    var cookieString = "global_bar_seen=" + value + "; expires=" + expiryDate + ";"

    document.cookie=cookieString
  },

  makeBannerVisible: function() {
    document.documentElement.className = document.documentElement.className.concat(" show-global-bar")
  },

  init: function() {
    if (!globalBarInit.blacklistedUrl()) {
      if (globalBarInit.getLatestCookie() === null) {
        globalBarInit.setBannerCookie()
        globalBarInit.makeBannerVisible()
      } else {
        var currentCookieVersion = parseCookie(globalBarInit.getLatestCookie()).version

        if (currentCookieVersion !== globalBarInit.getBannerVersion()) {
          globalBarInit.setBannerCookie()
        }

        var newCookieCount = parseCookie(globalBarInit.getLatestCookie()).count

        if (newCookieCount < 3) {
          globalBarInit.makeBannerVisible()
        }
      }
    }
  }
}

window.GOVUK.globalBarInit = globalBarInit;
<commit_msg>Set initial global bar cookie with helper function<commit_after>//= require libs/GlobalBarHelper.js
//= require govuk_publishing_components/lib/cookie-functions

'use strict'
window.GOVUK = window.GOVUK || {}

// Bump this if you are releasing a major change to the banner
// This will reset the view count so all users will see the banner, even if previously seen
var BANNER_VERSION = 3;

var globalBarInit = {
  getBannerVersion: function() {
    return BANNER_VERSION
  },

  getLatestCookie: function() {
    var currentCookie = document.cookie.match("(?:^|[ ;])(?:global_bar_seen=)(.+?)(?:(?=;|$))")

    if (currentCookie == null) {
      return currentCookie
    } else {
      return currentCookie[1]
    }
  },

  blacklistedUrl: function() {
    var paths = [
      "/register-to-vote",
      "/done",
      "/transition",
      "/transition-check"
    ]

    return new RegExp(paths.join("|")).test(window.location.pathname)
  },

  setBannerCookie: function() {
      var value = JSON.stringify({count: 0, version: globalBarInit.getBannerVersion()})

      window.GOVUK.setCookie("global_bar_seen", value, {days: 84});
  },

  makeBannerVisible: function() {
    document.documentElement.className = document.documentElement.className.concat(" show-global-bar")
  },

  init: function() {
    if (!globalBarInit.blacklistedUrl()) {
      if (globalBarInit.getLatestCookie() === null) {
        globalBarInit.setBannerCookie()
        globalBarInit.makeBannerVisible()
      } else {
        var currentCookieVersion = parseCookie(globalBarInit.getLatestCookie()).version

        if (currentCookieVersion !== globalBarInit.getBannerVersion()) {
          globalBarInit.setBannerCookie()
        }

        var newCookieCount = parseCookie(globalBarInit.getLatestCookie()).count

        if (newCookieCount < 3) {
          globalBarInit.makeBannerVisible()
        }
      }
    }
  }
}

window.GOVUK.globalBarInit = globalBarInit;
<|endoftext|>


<commit_before>var Simulation = require('./Simulation');
var request = require('request');

var simulationInterval;
var simulationArgs;
var simDuration = 0;
var simulationResults = [];

var simState = [
  'Not Started',
  'Initialized',
  'Running',
  'Completed',
  'Aborted'
];
var simStatus = simState[0];

const initSim = (Simulation) => {
  simulationArgs = Simulation;

  console.log(`Simulation Initialized with args: ${JSON.stringify(simulationArgs)}`);

  simStatus = simState[1];
};

const runSim = () => {
  simulationInterval = setInterval( () => {
    if (simDuration < simulationArgs.maxDuration) {
      console.log(`Running: ${simDuration / 1000} seconds`);

      simulationArgs.api.payload.temperature = 100;
      simulationArgs.api.payload.date_created = new Date();

      request.post({
        uri: simulationArgs.api.uri,
        body:  JSON.stringify(simulationArgs.api.payload),
        headers: simulationArgs.api.headers
      }, (err, res, body) => {
        if (err) {
          console.log(`Error posting sim run to api: ${err}`);
        } else {
          simulationResults.push(res.body);
          console.log(`Run posted: ${JSON.stringify(res.body)}`);
        }
      });

      simDuration += simulationArgs.interval;
      simStatus = simState[2];
    } else {
      console.log(`Simulation complete. Total time: ${simDuration / 1000} seconds`);
      reportOnSim();

      clearInterval(simulationInterval);
      simStatus = simState[3];
      simDuration = 0;
    }
  }, simulationArgs.interval);
}

const reportOnSim = () => {
  console.log(`Total runs: ${simulationResults.length}`);
}

const getStatus = () => {
  return simStatus;
}

module.exports = {
  init: initSim,
  run: runSim,
  status: getStatus
};<commit_msg>cleaned up status changes<commit_after>var Simulation = require('./Simulation');
var request = require('request');

var simulationInterval;
var simulationArgs;
var simDuration = 0;
var simulationResults = [];

var simState = [
  'Not Started',
  'Initialized',
  'Running',
  'Completed',
  'Aborted'
];
var simStatus = simState[0];

const initSim = (Simulation) => {
  simulationArgs = Simulation;

  console.log(`Simulation Initialized with args: ${JSON.stringify(simulationArgs)}`);

  simStatus = simState[1];
};

const runSim = () => {
  simStatus = simState[2];

  simulationInterval = setInterval( () => {
    if (simDuration < simulationArgs.maxDuration) {
      console.log(`Running: ${simDuration / 1000} seconds`);

      simulationArgs.api.payload.temperature = 100;
      simulationArgs.api.payload.date_created = new Date();

      request.post({
        uri: simulationArgs.api.uri,
        body:  JSON.stringify(simulationArgs.api.payload),
        headers: simulationArgs.api.headers
      }, (err, res, body) => {
        if (err) {
          console.log(`Error posting sim run to api: ${err}`);
        } else {
          simulationResults.push(res.body);
          console.log(`Run posted: ${JSON.stringify(res.body)}`);
        }
      });

      simDuration += simulationArgs.interval;
    } else {
      console.log(`Simulation complete. Total time: ${simDuration / 1000} seconds`);
      reportOnSim();

      clearInterval(simulationInterval);
      simStatus = simState[3];
      simDuration = 0;
    }
  }, simulationArgs.interval);
}

const reportOnSim = () => {
  console.log(`Total runs: ${simulationResults.length}`);
}

const getStatus = () => {
  return simStatus;
}

module.exports = {
  init: initSim,
  run: runSim,
  status: getStatus
};<|endoftext|>


<commit_before>import React from "react"
import Link from "gatsby-link"
import { Container } from "react-responsive-grid"
import Back from 'react-icons/lib/fa/arrow-left'
import { slide as Menu } from 'react-burger-menu'
import { rhythm, scale } from "../utils/typography"

class Template extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      mobile: false
    }
  }

  componentDidMount () {
    let check = false
    let a = (function (a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
    this.setState({mobile: check})
  }

  showSettings (event) {
    event.preventDefault();
  }

  render () {
    const { location, children } = this.props
    const height = this.state.mobile ? 56 : 64
    const marginBottom = location.pathname === "/" ? null : null
    styles.bmBurgerButton.left = this.state.mobile ? 16 : 24
    styles.bmBurgerButton.top = this.state.mobile ? 16 : 20
    let header, title
    if (location.pathname === "/" || location.pathname === '/about') {
      title = 'Fuck Up Some Comics'
      header = (
        <Menu styles={styles} >
          Home
          About
        </Menu>
          // Settings
      )
    } else {
      title = 'Comics'
      header = (
        <Link
          style={{
            boxShadow: "none",
            textDecoration: "none",
            color: "inherit",
          }}
          to={"/"}
        >
          <Back size={24} color={'white'} style={styles.bmBurgerButton} />
        </Link>
      )
    }
    return (

{title}

        {header}
        <Container
          style={{
            maxWidth: rhythm(24),
            padding: `${rhythm(1.5)} ${rhythm(3 / 4)}`,
          }}
        >
          {children()}
        </Container>

    )
  }
}

Template.propTypes = {
  children: React.PropTypes.function,
  location: React.PropTypes.object,
  route: React.PropTypes.object,
}

var styles = {
  bmBurgerButton: {
    position: 'absolute',
    width: 24,
    color: 'white',
    height: 24,
    left: 16,
    top: 16
  },
  bmBurgerBars: {
    background: 'white'
  },
  bmCrossButton: {
    height: '24px',
    width: '24px'
  },
  bmCross: {
    background: '#bdc3c7'
  },
  bmMenu: {
    background: 'white',
    padding: '2.5em 1.5em 0',
    fontSize: '1.15em',
  },
  bmMorphShape: {
    fill: '#373a47'
  },
  bmItemList: {
    color: '#b8b7ad',
  },
  bmItem: {
    paddingTop: 16,
    textDecoration: 'none'
  },
  bmOverlay: {
    background: 'rgba(0, 0, 0, 0.3)',
    height: '100%'
  }
}

export default Template
<commit_msg>fix header<commit_after>import React from "react"
import Link from "gatsby-link"
import { Container } from "react-responsive-grid"
import Back from 'react-icons/lib/fa/arrow-left'
import { slide as Menu } from 'react-burger-menu'
import { rhythm, scale } from "../utils/typography"

class Template extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      mobile: false
    }
  }

  componentDidMount () {
    let check = false
    let a = (function (a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
    this.setState({mobile: check})
  }

  showSettings (event) {
    event.preventDefault();
  }

  render () {
    const { location, children } = this.props
    const height = this.state.mobile ? 56 : 64
    const marginBottom = location.pathname === "/" ? null : null
    styles.bmBurgerButton.left = this.state.mobile ? 16 : 24
    styles.bmBurgerButton.top = this.state.mobile ? 16 : 20
    let header, title
    if (location.pathname === "/" || location.pathname === '/about') {
      title = 'Fuck Up Some Comics'
      header = (
        <Menu styles={styles} >
          Home
          About
        </Menu>
          // Settings
      )
    } else {
      title = 'Comics'
      header = (
        <Link
          style={{
            boxShadow: "none",
            textDecoration: "none",
            color: "inherit",
          }}
          to={"/"}
        >
          <Back size={24} color={'white'} style={styles.bmBurgerButton} />
        </Link>
      )
    }
    return (

{title}

        {header}
        <Container
          style={{
            maxWidth: rhythm(24),
            padding: `${rhythm(1.5)} ${rhythm(3 / 4)}`,
          }}
        >
          {children()}
        </Container>

    )
  }
}

Template.propTypes = {
  children: React.PropTypes.function,
  location: React.PropTypes.object,
  route: React.PropTypes.object,
}

var styles = {
  bmBurgerButton: {
    position: 'absolute',
    width: 24,
    color: 'white',
    height: 24,
    left: 16,
    top: 16
  },
  bmBurgerBars: {
    background: 'white'
  },
  bmCrossButton: {
    height: '24px',
    width: '24px'
  },
  bmCross: {
    background: '#bdc3c7'
  },
  bmMenu: {
    background: 'white',
    padding: '2.5em 1.5em 0',
    fontSize: '1.15em',
  },
  bmMorphShape: {
    fill: '#373a47'
  },
  bmItemList: {
    color: '#b8b7ad',
  },
  bmItem: {
    paddingTop: 16,
    textDecoration: 'none'
  },
  bmOverlay: {
    background: 'rgba(0, 0, 0, 0.3)',
    height: '100%'
  }
}

export default Template
<|endoftext|>


<commit_before>
wicky.ui = {};

(function (ui, jQuery) {

	ui.editable = function(editor) {
		var binder = ui.binder(editor.data('binder'));
		var blocking = false;
		if (!editor.is('input, textarea')) {
			return;
		}

		function editorOnAction (ev) {
			var markdown_text = editor.val();
			if (blocking || !markdown_text) {
				return;
			}
			blocking = true;
			binder.update({
				method: 'get',
				data: {
					md: markdown_text
				}
			}).done(function () {
				setTimeout(function () {
					blocking = false;
				}, 4000);
			});
		}

		['change', 'keypress', 'paste', 'click', 'focus'].forEach(function (eventName) {
			editor.on(eventName, editorOnAction);
		});
	}

	ui.binder = (function (binders) {
		return function (id) {
			var bindingContainer, bindUpdateAPI;
			if (!binders.hasOwnProperty(id)) {
				bindingContainer = jQuery('[data-bind-id=' + id + ']');
				bindUpdateAPI = bindingContainer.data('bind-update-api');
				binders[id] = {
					update: function (config) {
						return jQuery.ajax(bindUpdateAPI, config).done(function (html) {
							bindingContainer.html(html);
						});
					}
				};
			}
			return binders[id];
		};
	}({}));

}(wicky.ui, jQuery));

<commit_msg>shortens updating preview intervals<commit_after>
wicky.ui = {};

(function (ui, jQuery) {

	ui.editorUpdateInterval = 2000;

	ui.editable = function(editor) {
		var binder = ui.binder(editor.data('binder'));
		var blocking = false;
		if (!editor.is('input, textarea')) {
			return;
		}

		function editorOnAction (ev) {
			var markdown_text = editor.val();
			if (blocking || !markdown_text) {
				return;
			}
			blocking = true;
			binder.update({
				method: 'get',
				data: {
					md: markdown_text
				}
			}).done(function () {
				setTimeout(function () {
					blocking = false;
				}, ui.editorUpdateInterval);
			});
		}

		['change', 'keypress', 'paste', 'click', 'focus'].forEach(function (eventName) {
			editor.on(eventName, editorOnAction);
		});
	};

	ui.binder = (function (binders) {
		return function (id) {
			var bindingContainer, bindUpdateAPI;
			if (!binders.hasOwnProperty(id)) {
				bindingContainer = jQuery('[data-bind-id=' + id + ']');
				bindUpdateAPI = bindingContainer.data('bind-update-api');
				binders[id] = {
					update: function (config) {
						return jQuery.ajax(bindUpdateAPI, config).done(function (html) {
							bindingContainer.html(html);
						});
					}
				};
			}
			return binders[id];
		};
	}({}));

}(wicky.ui, jQuery));

<|endoftext|>


<commit_before>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });
<commit_msg>Update dynamic_carousel.js<commit_after>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

          doc = new jsPDF('p', 'pt', 'a4', false);

          if(duration_longue){
            var logo = new Image();
            logo.src = "../donnes/1.png";
            doc.addImage(logo, 'JPEG', 2, 2, 590,850);
            doc.addPage();
            var logo = new Image();
            logo.src = "2.png";
            doc.addImage(logo, 'JPEG', 2, 2, 590,850);

          }else if(duration_courte) {
            logo.src = "../donnes/2.png";
            doc.addImage(logo, 'JPEG', 2, 2, 590,850);
            doc.addPage();
            logo.src = "3.png";
            doc.addImage(logo, 'JPEG', 2, 2, 590,850);

          }

           var uno= 1;

          var paso;
         for (paso = 4; paso < 6; paso++) {
            doc.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            doc.addImage(logo, 'JPEG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };

          doc.output("dataurlnewwindow");

        }
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.3.0');
		this.setClientTag('node:20-06-01');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.3.0');
		this.setClientTag('node:20-06-02');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>/**
 * Constructs a Pancore object that handles all JavaScript on the Unique
 * Peptide Finder page.
 *
 * @param <Array> args.data The data array used to construct the selection tree
 *          has around 2500 objects with this format:
 *          {"bioproject_id":57587,"class_id":29547,"genus_id":194,
 *          "name":"Campylobacter jejuni","order_id":213849,"species_id":197}
 * @param <Hash> args.taxa is a list of key-value pairs mapping
 *          taxon id's to taxon names used for the selection tree.
 * @return <Pancore> that The constructed Pancore object
 */
var constructPancore = function constructPancore(args) {
    /*************** Private variables ***************/

    var that = {},
        genomes = {},
        isLoading = false,
        toLoad = 0,
        rank = 0,
        lca = "",
        tree,
        graph,
        matrix,
        table,
        worker;

    /*************** Private methods ***************/

    /**
     * Initializes pancore
     */
    function init() {
        // Construct the selection tree
        tree = constructSelectionTree({data : args.data, taxa : args.taxa});
        tree.drawTree({
            tree : "#treeView",
            tableDiv : "#genomes-table-div",
            treeSearch : "#treeSearchDiv"
        });

        // Constructs the table
        table = constructGenomeTable({
            genomes : genomes,
            pancore : that
        });

        // Constructs the graph
        graph = constructPancoreGraph({
            pancore : that,
            table : table,
            transitionDuration : 500,
            width : 930,
            height : 600,
            genomes : genomes
        });
        graph.redraw();

        // Create the Javascript Worker for background data processing
        worker = new Worker("/assets/workers/pancore_worker.js");
        worker.addEventListener('message', handleWorkerMessage, false);
        worker.addEventListener('error', error, false);

        // Constructs the matrix
        matrix = constructSimMatrix(worker);

        // Initialize the rest of the page
        initSpeciesForm();
        initFullScreen();
        initSaveImage();

        // IE10 message
        if (navigator.appVersion.indexOf("MSIE 10") !== -1) {
            info("You're using Internet Explorer 10. Everything should work as expected, but for an optimal experience, please use a recent version of Mozilla Firefox or Google Chrome.");
        }

        // Ready for take off
        $("#species_id").val(470);
        $("#add_species_peptidome").click();
    }

    /**
     * Initializes the add species button
     */
    function initSpeciesForm() {
        // Add handler to the "add species"-form
        $("#add_species_peptidome").click(function () {
            var url;
            // Get all bioproject id's for the selected species id
            url = "/pancore/genomes/species/" + $("#species_id").val() + ".json";
            $.getJSON(url, function (genomes) {
                that.addGenomes(genomes);
            })
            .fail(function () {
                error("request error for " + url, "It seems like something went wrong while we loaded the data");
            });
            return false;
        });
    }

    /**
     * Initializes the full screen stuff
     */
    function initFullScreen() {
        if (fullScreenApi.supportsFullScreen) {
            $("#buttons-pancore").prepend("<button id='zoom-btn' class='btn btn-default btn-xs'> Enter full screen</button>");
            $("#zoom-btn").click(function () {
                if ($(".tab-content .active").attr('id') === "pancore_graph_wrapper") {
                    // GA event tracking
                    _gaq.push(['_trackEvent', 'Pancore', 'Full Screen', 'graph']);
                    window.fullScreenApi.requestFullScreen($("#pancore_graph_wrapper").get(0));
                } else {
                    // GA event tracking
                    _gaq.push(['_trackEvent', 'Pancore', 'Full Screen', 'simmatrix']);
                    window.fullScreenApi.requestFullScreen($("#sim_matrix_wrapper").get(0));
                }
            });
            $(document).bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', resizeFullScreen);
        }
    }

    /**
     * Initializes the save image stuff
     */
    function initSaveImage() {
        $("#buttons-pancore").prepend("<button id='save-img' class='btn btn-default btn-xs'> Save image</button>");
        $("#save-img").click(function clickSaveImage() {
            if ($(".tab-content .active").attr('id') === "pancore_graph_wrapper") {
                _gaq.push(['_trackEvent', 'Pancore', 'Save Image', 'graph']);
                triggerDownloadModal("#pancore_graph svg", null, "unique_peptides_graph");
            } else {
                _gaq.push(['_trackEvent', 'Pancore', 'Save Image', 'sim matrix']);
                triggerDownloadModal("#sim_matrix svg", null, "unique_peptides_matrix");
            }
        });
        $("#buttons-pancore").prepend("<button id='save-data' class='btn btn-default btn-xs'> Save data</button>");
        $("#save-data").click(function clickSaveData() {
            _gaq.push(['_trackEvent', 'Pancore', 'Save Data']);
            that.exportCsvData();
        });
    }

    /**
     * Gets called to handle the change from and to full screen mode.
     * Mostly just scales the SVG
     */
    function resizeFullScreen() {
        if ($(".tab-content .active").attr('id') === "pancore_graph_wrapper") {
            setTimeout(function () {
                var w = fullWidth,
                    h = fullHeight;
                if (window.fullScreenApi.isFullScreen()) {
                    w = $(window).width();
                    h = $(window).height();
                }
                $("#pancore_graph svg").attr("width", w);
                $("#pancore_graph svg").attr("height", h);
            }, 100);
        } else {
            // TODO: add handling code for sim matrix
        }
    }

    /**
     * Handles message events for the worker
     *
     * @param <Event> e The event we want to handle
     */
    function handleWorkerMessage(e) {
        var data = e.data;
        switch (data.type) {
        case 'log':
            console.log(data.msg);
            break;
        case 'error':
            error(data.msg.error, data.msg.msg);
            break;
        case 'processLoadedGenome':
            processLoadedGenome(data.msg.data, data.msg.rank);
            break;
        case 'processPancoreData':
            processPancoreData(data.msg.data, data.msg.lca, data.msg.rank);
            break;
        case 'processDownloadedSequences':
            processDownloadedSequences(data.msg.sequences, data.msg.type);
            break;
        case 'sim_graph':
            drawTree(data.msg.data, data.msg.order);
            break;
        default:
            console.log(data.msg);
        }
    }

    /**
     * Sends a command and message to the worker
     */
    function sendToWorker(command, message) {
        worker.postMessage({'cmd': command, 'msg': message});
    }

    /**
     * Asks the worker to load a genome
     *
     * @param <Number> bioproject_id The id of the genome we want to load
     * @param <String> name The name of the genome we want to load
     */
    function loadData(bioproject_id, name) {
        matrix.addGenome(bioproject_id, name);
        sendToWorker("loadData", {"bioproject_id" : bioproject_id, "name" : name});
    }

    /**
     * Gets called when the worker is done loading a new genome the calculated
     * data gets added the update queue if the request_rank matches
     *
     * @param <Genome> genome The data that's loaded
     * @param <Number> requestRank The rank of the original request
     */
    function processLoadedGenome(genome, requestRank) {
        // If the rank doesn't match, this is old data
        if (rank !== requestRank) return;
        toLoad--;
        table.setGenomeStatus(genome.bioproject_id, "Done", false);

        graph.addToDataQueue(genome);

        setLoading(toLoad !== 0);
    }

    /**
     * Replaces all the data in the pancore graph
     *
     * @param <Array> data Array of pancoreGraph data
     * @param <String> l The lowest common ancestor of the loaded genomes
     * @param <Number> requestRank The rank at the time of the request
     */
    function processPancoreData(data, l, requestRank) {
        if (rank !== requestRank) return;

        graph.setData(data);
        lca = l;
    }

    /**
     * Takes the downloaded sequences from the worker and pushes them to the
     * user via a file download.
     *
     * @param <String> sequences The list of sequences
     * @param <String> type The type of the sequences
     */
    function processDownloadedSequences(sequences, type) {
        downloadDataByForm(sequences, type + '-sequences.txt', function enableButton() {
            $("#download-peptides-toggle").button('reset');
        });
    }

    /**
     * Gets called when the data is (done) loading
     * Enables/disables some buttons and actions (e.g. reordering)
     *
     * @param <Boolean> loading The new(?) loading status
     */
    function setLoading(loading) {
        // don't do anything if the state hasn't changed
        if (isLoading === loading) return;
        isLoading = loading;
        if (loading) {
            $("#add_species_peptidome").button('loading');
            table.setEnabled(false);
        } else {
            $("#add_species_peptidome").button('reset');
            table.setEnabled(true);

            // REMOVE THIS LINE
            // dirty hack
            setTimeout(function () { sendToWorker("getUniqueSequences", {order : table.getOrder() });}, 1000);
        }
    }

    /*************** Public methods ***************/

    /**
     * Gives the order to add genomes to the visualisation.
     *
     * @param <Array> g Array of bioproject_id's of the genomes we want to add
     */
    that.addGenomes = function addGenomes(g) {
        var i;
        for (i = 0; i < g.length; i++) {
            // only add new genomes
            if (genomes[g[i].bioproject_id] === undefined) {
                toLoad++;
                table.addGenome({
                    "bioproject_id" : g[i].bioproject_id,
                    "name" : g[i].name,
                    "status" : "Loading...",
                    "position" : 100 + i
                });
                loadData(g[i].bioproject_id, g[i].name);
            }
        }
        setLoading(toLoad !== 0);
    };

    /**
     * Removes a genomes from the visualization:
     * - Removes it from the table
     * - Instructs the worker to recalculate the graph
     *
     * @param <Genome> genome The genome we want to remove
     */
    that.removeGenome = function removeGenome(genome) {
        var removeData = table.removeGenome(genome.bioproject_id);
        sendToWorker("removeData", removeData);
    };

    /**
     * Resets everything:
     * - instructs the worker to flush all data
     * - clear all data vars
     * - update graph and table
     */
    that.clearAllData = function clearAllData() {
        rank++;
        sendToWorker("clearAllData", "");
        lca = "";
        setLoading(false);
        table.clearAllData();
        graph.clearAllData();
    };

    /**
     * Requests the worker to recalculate all data based on a new order
     *
     * @param <Array> orderData.order The new order
     * @param <Number> orderData.start The position from where there's a change
     * @param <Number> orderData.stop The position till where there's a change
     */
    that.updateOrder = function updateOrder(orderData) {
        sendToWorker("recalculatePanCore", orderData);
        table.setOrder(orderData.order);
    };

    /**
     * Invokes a file download containing all data currently shown
     * in the graph (i.e. each datapoint) in csv format.
     */
    that.exportCsvData = function exportCsvData() {
        downloadDataByForm(graph.getDataAsCsv(), "unique_peptides.csv");
    };

    /**
     * Requests a set of sequences to the worker
     *
     * @param <Number> bioprojectId The id of the genome we want data from
     * @param <String> type The type of sequences we want
     */
    that.requestSequences = function requestSequences(bioprojectId, type) {
        sendToWorker("getSequences", {
            "bioproject_id" : bioprojectId,
            "type" : type
        });
    };

    /**
     * Send the autoSort command to the worker
     *
     * @param <String> type The type of sort we want to run
     */
    that.autoSort = function autoSort(type){
        sendToWorker("autoSort", {type : type});
    }

    // initialize the object
    init();

    return that;
};

function removeMe() {

    // TODO move to phylotree object
    function drawTree(newick, order) {
        var parsed = Newick.parse(newick);
        console.log(parsed);
        $("#sim_graph").html("");
        d3.phylogram.build('#sim_graph', parsed, {width: 100, height: 500}, order);
    }

    // TODO move to matrix object
    // Only cluster when the initial data has loaded
    function clusterIfReady() {
        if( toLoad === 0 ) {
            sendToWorker('clusterMatrix', '');
        } else {
            setTimeout(clusterIfReady, 200);
        }
    }
    // On click of tab, cluster matrix
    $("a[href='#sim_matrix_wrapper']").click(clusterIfReady);
    function showMatrix(g, data, order) {
        $('#sim_matrix').empty();
        redrawMatrix(g, data, order);
    }
}
<commit_msg>remove removeMe<commit_after>/**
 * Constructs a Pancore object that handles all JavaScript on the Unique
 * Peptide Finder page.
 *
 * @param <Array> args.data The data array used to construct the selection tree
 *          has around 2500 objects with this format:
 *          {"bioproject_id":57587,"class_id":29547,"genus_id":194,
 *          "name":"Campylobacter jejuni","order_id":213849,"species_id":197}
 * @param <Hash> args.taxa is a list of key-value pairs mapping
 *          taxon id's to taxon names used for the selection tree.
 * @return <Pancore> that The constructed Pancore object
 */
var constructPancore = function constructPancore(args) {
    /*************** Private variables ***************/

    var that = {},
        genomes = {},
        isLoading = false,
        toLoad = 0,
        rank = 0,
        lca = "",
        tree,
        graph,
        matrix,
        table,
        worker;

    /*************** Private methods ***************/

    /**
     * Initializes pancore
     */
    function init() {
        // Construct the selection tree
        tree = constructSelectionTree({data : args.data, taxa : args.taxa});
        tree.drawTree({
            tree : "#treeView",
            tableDiv : "#genomes-table-div",
            treeSearch : "#treeSearchDiv"
        });

        // Constructs the table
        table = constructGenomeTable({
            genomes : genomes,
            pancore : that
        });

        // Constructs the graph
        graph = constructPancoreGraph({
            pancore : that,
            table : table,
            transitionDuration : 500,
            width : 930,
            height : 600,
            genomes : genomes
        });
        graph.redraw();

        // Create the Javascript Worker for background data processing
        worker = new Worker("/assets/workers/pancore_worker.js");
        worker.addEventListener('message', handleWorkerMessage, false);
        worker.addEventListener('error', error, false);

        // Constructs the matrix
        matrix = constructSimMatrix(worker);

        // Initialize the rest of the page
        initSpeciesForm();
        initFullScreen();
        initSaveImage();

        // IE10 message
        if (navigator.appVersion.indexOf("MSIE 10") !== -1) {
            info("You're using Internet Explorer 10. Everything should work as expected, but for an optimal experience, please use a recent version of Mozilla Firefox or Google Chrome.");
        }

        // Ready for take off
        $("#species_id").val(470);
        $("#add_species_peptidome").click();
    }

    /**
     * Initializes the add species button
     */
    function initSpeciesForm() {
        // Add handler to the "add species"-form
        $("#add_species_peptidome").click(function () {
            var url;
            // Get all bioproject id's for the selected species id
            url = "/pancore/genomes/species/" + $("#species_id").val() + ".json";
            $.getJSON(url, function (genomes) {
                that.addGenomes(genomes);
            })
            .fail(function () {
                error("request error for " + url, "It seems like something went wrong while we loaded the data");
            });
            return false;
        });
    }

    /**
     * Initializes the full screen stuff
     */
    function initFullScreen() {
        if (fullScreenApi.supportsFullScreen) {
            $("#buttons-pancore").prepend("<button id='zoom-btn' class='btn btn-default btn-xs'> Enter full screen</button>");
            $("#zoom-btn").click(function () {
                if ($(".tab-content .active").attr('id') === "pancore_graph_wrapper") {
                    // GA event tracking
                    _gaq.push(['_trackEvent', 'Pancore', 'Full Screen', 'graph']);
                    window.fullScreenApi.requestFullScreen($("#pancore_graph_wrapper").get(0));
                } else {
                    // GA event tracking
                    _gaq.push(['_trackEvent', 'Pancore', 'Full Screen', 'simmatrix']);
                    window.fullScreenApi.requestFullScreen($("#sim_matrix_wrapper").get(0));
                }
            });
            $(document).bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', resizeFullScreen);
        }
    }

    /**
     * Initializes the save image stuff
     */
    function initSaveImage() {
        $("#buttons-pancore").prepend("<button id='save-img' class='btn btn-default btn-xs'> Save image</button>");
        $("#save-img").click(function clickSaveImage() {
            if ($(".tab-content .active").attr('id') === "pancore_graph_wrapper") {
                _gaq.push(['_trackEvent', 'Pancore', 'Save Image', 'graph']);
                triggerDownloadModal("#pancore_graph svg", null, "unique_peptides_graph");
            } else {
                _gaq.push(['_trackEvent', 'Pancore', 'Save Image', 'sim matrix']);
                triggerDownloadModal("#sim_matrix svg", null, "unique_peptides_matrix");
            }
        });
        $("#buttons-pancore").prepend("<button id='save-data' class='btn btn-default btn-xs'> Save data</button>");
        $("#save-data").click(function clickSaveData() {
            _gaq.push(['_trackEvent', 'Pancore', 'Save Data']);
            that.exportCsvData();
        });
    }

    /**
     * Gets called to handle the change from and to full screen mode.
     * Mostly just scales the SVG
     */
    function resizeFullScreen() {
        if ($(".tab-content .active").attr('id') === "pancore_graph_wrapper") {
            setTimeout(function () {
                var w = fullWidth,
                    h = fullHeight;
                if (window.fullScreenApi.isFullScreen()) {
                    w = $(window).width();
                    h = $(window).height();
                }
                $("#pancore_graph svg").attr("width", w);
                $("#pancore_graph svg").attr("height", h);
            }, 100);
        } else {
            // TODO: add handling code for sim matrix
        }
    }

    /**
     * Handles message events for the worker
     *
     * @param <Event> e The event we want to handle
     */
    function handleWorkerMessage(e) {
        var data = e.data;
        switch (data.type) {
        case 'log':
            console.log(data.msg);
            break;
        case 'error':
            error(data.msg.error, data.msg.msg);
            break;
        case 'processLoadedGenome':
            processLoadedGenome(data.msg.data, data.msg.rank);
            break;
        case 'processPancoreData':
            processPancoreData(data.msg.data, data.msg.lca, data.msg.rank);
            break;
        case 'processDownloadedSequences':
            processDownloadedSequences(data.msg.sequences, data.msg.type);
            break;
        case 'sim_graph':
            drawTree(data.msg.data, data.msg.order);
            break;
        default:
            console.log(data.msg);
        }
    }

    /**
     * Sends a command and message to the worker
     */
    function sendToWorker(command, message) {
        worker.postMessage({'cmd': command, 'msg': message});
    }

    /**
     * Asks the worker to load a genome
     *
     * @param <Number> bioproject_id The id of the genome we want to load
     * @param <String> name The name of the genome we want to load
     */
    function loadData(bioproject_id, name) {
        matrix.addGenome(bioproject_id, name);
        sendToWorker("loadData", {"bioproject_id" : bioproject_id, "name" : name});
    }

    /**
     * Gets called when the worker is done loading a new genome the calculated
     * data gets added the update queue if the request_rank matches
     *
     * @param <Genome> genome The data that's loaded
     * @param <Number> requestRank The rank of the original request
     */
    function processLoadedGenome(genome, requestRank) {
        // If the rank doesn't match, this is old data
        if (rank !== requestRank) return;
        toLoad--;
        table.setGenomeStatus(genome.bioproject_id, "Done", false);

        graph.addToDataQueue(genome);

        setLoading(toLoad !== 0);
    }

    /**
     * Replaces all the data in the pancore graph
     *
     * @param <Array> data Array of pancoreGraph data
     * @param <String> l The lowest common ancestor of the loaded genomes
     * @param <Number> requestRank The rank at the time of the request
     */
    function processPancoreData(data, l, requestRank) {
        if (rank !== requestRank) return;

        graph.setData(data);
        lca = l;
    }

    /**
     * Takes the downloaded sequences from the worker and pushes them to the
     * user via a file download.
     *
     * @param <String> sequences The list of sequences
     * @param <String> type The type of the sequences
     */
    function processDownloadedSequences(sequences, type) {
        downloadDataByForm(sequences, type + '-sequences.txt', function enableButton() {
            $("#download-peptides-toggle").button('reset');
        });
    }

    /**
     * Gets called when the data is (done) loading
     * Enables/disables some buttons and actions (e.g. reordering)
     *
     * @param <Boolean> loading The new(?) loading status
     */
    function setLoading(loading) {
        // don't do anything if the state hasn't changed
        if (isLoading === loading) return;
        isLoading = loading;
        if (loading) {
            $("#add_species_peptidome").button('loading');
            table.setEnabled(false);
        } else {
            $("#add_species_peptidome").button('reset');
            table.setEnabled(true);

            // REMOVE THIS LINE
            // dirty hack
            setTimeout(function () { sendToWorker("getUniqueSequences", {order : table.getOrder() });}, 1000);
        }
    }

    /*************** Public methods ***************/

    /**
     * Gives the order to add genomes to the visualisation.
     *
     * @param <Array> g Array of bioproject_id's of the genomes we want to add
     */
    that.addGenomes = function addGenomes(g) {
        var i;
        for (i = 0; i < g.length; i++) {
            // only add new genomes
            if (genomes[g[i].bioproject_id] === undefined) {
                toLoad++;
                table.addGenome({
                    "bioproject_id" : g[i].bioproject_id,
                    "name" : g[i].name,
                    "status" : "Loading...",
                    "position" : 100 + i
                });
                loadData(g[i].bioproject_id, g[i].name);
            }
        }
        setLoading(toLoad !== 0);
    };

    /**
     * Removes a genomes from the visualization:
     * - Removes it from the table
     * - Instructs the worker to recalculate the graph
     *
     * @param <Genome> genome The genome we want to remove
     */
    that.removeGenome = function removeGenome(genome) {
        var removeData = table.removeGenome(genome.bioproject_id);
        sendToWorker("removeData", removeData);
    };

    /**
     * Resets everything:
     * - instructs the worker to flush all data
     * - clear all data vars
     * - update graph and table
     */
    that.clearAllData = function clearAllData() {
        rank++;
        sendToWorker("clearAllData", "");
        lca = "";
        setLoading(false);
        table.clearAllData();
        graph.clearAllData();
    };

    /**
     * Requests the worker to recalculate all data based on a new order
     *
     * @param <Array> orderData.order The new order
     * @param <Number> orderData.start The position from where there's a change
     * @param <Number> orderData.stop The position till where there's a change
     */
    that.updateOrder = function updateOrder(orderData) {
        sendToWorker("recalculatePanCore", orderData);
        table.setOrder(orderData.order);
    };

    /**
     * Invokes a file download containing all data currently shown
     * in the graph (i.e. each datapoint) in csv format.
     */
    that.exportCsvData = function exportCsvData() {
        downloadDataByForm(graph.getDataAsCsv(), "unique_peptides.csv");
    };

    /**
     * Requests a set of sequences to the worker
     *
     * @param <Number> bioprojectId The id of the genome we want data from
     * @param <String> type The type of sequences we want
     */
    that.requestSequences = function requestSequences(bioprojectId, type) {
        sendToWorker("getSequences", {
            "bioproject_id" : bioprojectId,
            "type" : type
        });
    };

    /**
     * Send the autoSort command to the worker
     *
     * @param <String> type The type of sort we want to run
     */
    that.autoSort = function autoSort(type){
        sendToWorker("autoSort", {type : type});
    }

    // initialize the object
    init();

    return that;
};
<|endoftext|>


<commit_before>import * as fontoxpath from '../src/index';

const xmlSource = document.getElementById('xmlSource');
const xmlFile = document.getElementById('xmlFile');
const log = document.getElementById('log');
const resultText = document.getElementById('resultText');
const xpathField = document.getElementById('xpathField');
const allowXQuery = document.getElementById('allowXQuery');

xmlSource.innerText = `<xml>
<herp>Herp</herp>
<derp id="durp">derp</derp>
<hurr durr="durrdurrdurr">durrrrrr</hurr>
</xml>
	`;

const domParser = new DOMParser();

let xmlDoc = domParser.parseFromString(xmlSource.innerText, 'text/xml');
xmlFile.innerHTML = xmlSource.innerText;

function tryEvaluateToNodes () {
	let resultNodes;
	try {
		resultNodes = fontoxpath.evaluateXPathToNodes(
			xpathField.value,
			xmlDoc,
			null,
			null,
			{
				language: allowXQuery.checked ? fontoxpath.evaluateXPath.XQUERY_3_1_LANGUAGE : fontoxpath.evaluateXPath.XPATH_3_1_LANGUAGE
			}
		);
	}
	catch (err) {
		xmlFile.innerText = err.message;
		return false;
	}

	log.innerText = '';
	const text = resultNodes.map(node => node.nodeType === node.TEXT_NODE ? node.textContent : node.outerHTML).join('\n\n');
	resultText.innerText = text;

	const paths = resultNodes.map(
		node => {
			if (!node.ownerDocument ||
				!node.ownerDocument.contains(node)) {
				return 'false()';
			}
			return fontoxpath.evaluateXPathToString(
				'if (not(self::element())) then "false()" else ancestor-or-self::*!("child::*[" || count(preceding-sibling::*) + 1 || "]") => reverse() => string-join("/")',
				node);
		});
	const htmlNodes = paths
		.map(path => fontoxpath.evaluateXPathToFirstNode(path, xmlFile, fontoxpath.domFacade))
		.filter(n => !!n);

	htmlNodes.forEach(node => node.setAttribute('style', 'border: 1px solid red'));
	return true;
}

function rerunXPath () {
	if (tryEvaluateToNodes()) {
		return;
	}
	try {
		const result = fontoxpath.evaluateXPath(xpathField.value, xmlDoc, fontoxpath.domFacade) + '';
		resultText.innerText = result;
	}
	catch (err) {
		log.innerText = 'Error: ' + err.message;
		resultText.innerText = '';
		return;
	}
	log.innerText = '';
}

xmlSource.oninput = xpathField.oninput = _evt => {
	try {
		xmlDoc = domParser.parseFromString(xmlSource.innerText, 'text/xml');
		xmlFile.innerHTML = xmlDoc.documentElement.outerHTML;

		if (fontoxpath.evaluateXPathToBoolean('//parseerror', xmlDoc, fontoxpath.domFacade)) {
			log.innerText = 'Error: invalid XML';
			return;
		}
		rerunXPath();
	}
	catch (_) {
		// Catch all exceptions
	}
};

rerunXPath();
<commit_msg>[skip ci] Allow demo page to parse evaluate the same XQueries as the playground<commit_after>import * as fontoxpath from '../src/index';

const xmlSource = document.getElementById('xmlSource');
const xmlFile = document.getElementById('xmlFile');
const log = document.getElementById('log');
const resultText = document.getElementById('resultText');
const xpathField = document.getElementById('xpathField');
const allowXQuery = document.getElementById('allowXQuery');

xmlSource.innerText = `<xml>
	<herp>Herp</herp>
	<derp id="durp">derp</derp>
	<hurr durr="durrdurrdurr">durrrrrr</hurr>
</xml>
	`;

const domParser = new DOMParser();

let xmlDoc = domParser.parseFromString(xmlSource.innerText, 'text/xml');
xmlFile.innerHTML = xmlSource.innerText;

function tryEvaluateToNodes () {
	let resultNodes;
	try {
		resultNodes = fontoxpath.evaluateXPathToNodes(
			xpathField.value,
			xmlDoc,
			null,
			null,
			{
				language: allowXQuery.checked ? fontoxpath.evaluateXPath.XQUERY_3_1_LANGUAGE : fontoxpath.evaluateXPath.XPATH_3_1_LANGUAGE
			}
		);
	}
	catch (err) {
		xmlFile.innerText = err.message;
		return false;
	}

	log.innerText = '';

	const paths = resultNodes.map(
		node => {
			if (!node.ownerDocument ||
				!node.ownerDocument.contains(node)) {
				return 'false()';
			}
			return fontoxpath.evaluateXPathToString(
				'if (not(self::element())) then "false()" else ancestor-or-self::*!("child::*[" || count(preceding-sibling::*) + 1 || "]") => reverse() => string-join("/")',
				node);
		});
	const htmlNodes = paths
		.map(path => fontoxpath.evaluateXPathToFirstNode(path, xmlFile, fontoxpath.domFacade))
		.filter(n => !!n);

	htmlNodes.forEach(node => node.setAttribute('style', 'border: 1px solid red'));
	return true;
}

async function rerunXPath () {
	// Clear results from previous run
	log.innerText = '';
	resultText.innerText = '';

	let it;
	try {
		it = await fontoxpath.evaluateXPathToAsyncIterator(
			xpathField.value,
			xmlDoc,
			null,
			null,
			{
				language: allowXQuery.checked ? fontoxpath.evaluateXPath.XQUERY_3_1_LANGUAGE : fontoxpath.evaluateXPath.XPATH_3_1_LANGUAGE
			}
		);
	}
	catch (err) {
		log.innerText = err.message;
		return;
	}

	const raw = [];
	for (let item = await it.next(); !item.done; item = await it.next()) {
		if (item.value instanceof Node) {
			raw.push(item.value.outerHTML);
		}
		else {
			raw.push(item.value);
		}
	}

	resultText.innerText = '[' + raw.map(item => `"${item}"`).join(', ') + ']';

	tryEvaluateToNodes();
}

xmlSource.oninput = xpathField.oninput = _evt => {
	try {
		xmlDoc = domParser.parseFromString(xmlSource.innerText, 'text/xml');
		xmlFile.innerHTML = xmlDoc.documentElement.outerHTML;

		if (fontoxpath.evaluateXPathToBoolean('//parseerror', xmlDoc, fontoxpath.domFacade)) {
			log.innerText = 'Error: invalid XML';
			return;
		}
		rerunXPath();
	}
	catch (_) {
		// Catch all exceptions
	}
};

rerunXPath();
<|endoftext|>