<commit_before>var KNETMAPS = KNETMAPS || {};

KNETMAPS.Menu = function() {

	var iteminfo = KNETMAPS.ItemInfo();
	var container = KNETMAPS.Container();
	var stats = KNETMAPS.Stats();
	var conceptLegend = KNETMAPS.ConceptsLegend();
	var generator = KNETMAPS.Generator();

	var my=function() {};

 my.onHover = function(thisBtn) {
    $(thisBtn).removeClass('unhover').addClass('hover');
 }

 my.offHover = function(thisBtn) {
	    $(thisBtn).removeClass('hover').addClass('unhover');
 }

 my.popupItemInfo = function() {
	 iteminfo.openItemInfoPane();
	 iteminfo.showItemInfo(this);
 }

   // Go to Help docs.
 my.openKnetHelpPage = function() {
   var helpURL = 'https://github.com/Rothamsted/knetmaps.js/wiki/KnetMaps.js';
   window.open(helpURL, '_blank');
  }

  // Reset: Re-position the network graph.
 my.resetGraph = function() {
   $('#cy').cytoscape('get').reset().fit(); // reset the graph's zooming & panning properties.
  }

  // Export the graph as a JSON object in a new Tab and allow users to save it.
 my.exportAsJson = function() {
   var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`

   var exportJson= cy.json(); // full graphJSON

   var exportedJson= my.filterJsonToExport(cy, exportJson); // the final "graph" to export
   var thumbnail_image= my.exportThumbnail(); // fetch knetwork thumbnail as well.
   // fetch graphSummary from KnetMiner server API.
   var api_graphSummary= my.getGraphDBSummary();

   // compose knetwork metaData below (with name, date, etc.)
   var knet_name= "myKnetwork.json";
   // fetch total node & edge count for this knetwork.
   var totalNodes= cy.$(':visible').nodes().size();
   var totalEdges= cy.$(':visible').edges().size();
   var currentDate= new Date();
   var knet_date= String(currentDate.getDate()).padStart(2, '0') + '/' + String(currentDate.getMonth() + 1).padStart(2, '0') + '/' +
        currentDate.getFullYear() +' '+ currentDate.getHours() +':'+ ('0'+currentDate.getMinutes()).slice(-2); // formatted date (mm: January=0)

   // compose knet_metaData with the above fields.
   var knetwork_metaData= '"name":"'+ knet_name +'", "dateCreated":"'+ knet_date +'", "numNodes":'+ totalNodes +', "numEdges":'+ totalEdges;
   // add api_graphSummary to the above as well.
   knetwork_metaData= knetwork_metaData +', "speciesTaxid":"'+ api_graphSummary.speciesTaxid +'", "speciesName":"'+
       api_graphSummary.speciesName +'", "dbVersion":'+ api_graphSummary.dbVersion +', "dbDateCreated":"'+ api_graphSummary.dbDateCreated
	   +'", "sourceOrganization":"'+ api_graphSummary.sourceOrganization +'", "provider":"'+ api_graphSummary.provider +'"';
   knetwork_metaData= '{'+ knetwork_metaData +'}';

   /* final knetwork response JSON with metadata, thumbnail & the knetwork itself. */
   var knetSave_response= '{"metaData":'+ knetwork_metaData +', "graph":'+ exportedJson +', "image":"'+ thumbnail_image +'"}';

   // use FileSaver.js to save using file downloader (disable in production/demo).
   //var kNet_json_Blob= new Blob([knetSave_response], {type: 'application/javascript;charset=utf-8'});
   //saveAs(kNet_json_Blob, knet_name);

   console.log("knetSave_response: "+ knetSave_response); // test

   // transfer response to knetspace
   // POST to knetspace: /api/v1/networks/
  }

 // generate pure JSON to export from KnetMaps for graphJSON and metadata
 my.filterJsonToExport = function(cy, exportJson) {

   var elesToRetain= []; // to streamline content exported in exportJson (graphJSON) & metaJSON (allGraphData).
   cy.$(':visible').forEach(function (ele) { elesToRetain.push(ele.id()); });

   // remove hidden nodes/edges metadata from exportJson.
   exportJson.elements.nodes= exportJson.elements.nodes.filter( function( con ) {
	   return elesToRetain.includes(con.data.id); });
   exportJson.elements.edges= exportJson.elements.edges.filter( function( rel ) {
	   return elesToRetain.includes(rel.data.id); });

   // remove hidden nodes/edges metadata from metaJSON (allGraphData).
   var metaJSON= allGraphData;
   metaJSON.ondexmetadata.concepts= metaJSON.ondexmetadata.concepts.filter( function( con ) {
	   return elesToRetain.includes(con.id); });
   metaJSON.ondexmetadata.relations= metaJSON.ondexmetadata.relations.filter( function( rel ) {
	   return elesToRetain.includes(rel.id); });
   // remove other redundant metaJSON entries.
   var omit_redundant= ["graphName","numberOfConcepts","numberOfRelations","version"];
   omit_redundant.forEach(function (entry) { delete metaJSON.ondexmetadata[entry]; });

   var json_response= '{"graphJSON":'+ JSON.stringify(exportJson) + ', "allGraphData":' + JSON.stringify(metaJSON) +'}';
   return json_response;
  }

 // fetch graphSummary from KnetMiner server API.
 my.getGraphDBSummary = function() {
   var graphSummary= '';
   //if(api_url != null || api_url != undefined) {
   if(typeof api_url !== "undefined") {
       console.log("get apiGraphSummary from: "+ api_url + '/dataSource');
        $.post({
            url: api_url + '/dataSource',
            timeout: 1000000,
            headers: {
                "Accept": "application/json; charset=utf-8",
                "Content-Type": "application/json; charset=utf-8"
            },
            datatype: "json",
        })
            .fail(function (errorlog) { console.log("An error has ocurred " + errorlog); })
            .success(function (data) {
                graphSummary= JSON.parse(data).dataSource;
            });
     }
   else {
     var dummyText= '{"dataSource":{"speciesTaxid":"","speciesName":"","dbVersion":null,"dbDateCreated":"","sourceOrganization":"","provider":""}}';
     graphSummary= JSON.parse(dummyText).dataSource;
    }

    return graphSummary;
  }

  // Export the graph as a .png image and allow users to save it.
 my.exportAsImage = function() {
   var cy = $('#cy').cytoscape('get'); // now we have a global reference to `cy`
    var png64 = cy.png({
                    	"scale" : 6,
                    	"output" : 'base64'
    			}); // .setAttribute('crossOrigin', 'anonymous');
    var a = document.createElement("a"); //Create
    a.href = png64; //Image Base64 Goes here
    a.download = "knet_image.png"; //File name Here
    a.click(); //Downloaded file
  }

  // Export the network thumbnail.
  my.exportThumbnail = function() {
   var png64 = cy.png({
                    "scale" : 0.8,
                    "output" : 'base64'}); // .setAttribute('crossOrigin', 'anonymous');

   return png64.replace("data:image/png;base64,", "");
  }

  // Show all concepts & relations.
 my.showAll = function() {
   var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
   cy.elements().removeClass('HideEle');
   cy.elements().addClass('ShowEle');

   // Relayout the graph.
   my.rerunLayout();

   // Remove shadows around nodes, if any.
   cy.nodes().forEach(function( ele ) {
       iteminfo.removeNodeBlur(ele);
      });

   // Refresh network legend.
   stats.updateKnetStats();
   // Update the stats legend
   conceptLegend.populateConceptLegend();
  }

  // Re-run the entire graph's layout.
 my.rerunLayout = function() {
   // Get the cytoscape instance as a Javascript object from JQuery.
 //  var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
   var selected_elements= cy.$(':visible'); // get only the visible elements.

   // Re-run the graph's layout, but only on the visible elements.
   my.rerunGraphLayout(selected_elements);

   // Reset the graph/ viewport.
   my.resetGraph();
  }

  var layouts = KNETMAPS.Layouts();

  // Re-run the graph's layout, but only on the visible elements.
  my.rerunGraphLayout = function(eles) {
   var ld_selected= $('#layouts_dropdown').val();
   // Use preset layout for reloading saved knetwork.
   //layouts.setPresetLayout(eles); // test preset

   if(ld_selected === "circle_layout") {
	  layouts.setCircleLayout(eles);
     }
   else if(ld_selected === "cose_layout") {
	   layouts.setCoseLayout(eles);
      }
   else if(ld_selected === "coseBilkent_layout") {
	   layouts.setCoseBilkentLayout(eles);
	  }
   else if(ld_selected === "concentric_layout") {
	   layouts.setConcentricLayout(eles);
	  }
   else if(ld_selected === "ngraph_force_layout") {
	   layouts.setNgraphForceLayout(eles);
	  }
  }

  // Update the label font size for all the concepts and relations.
  my.changeLabelFontSize = function(new_size) {
   try {
     var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
     cy.style().selector('node').css({ 'font-size': new_size }).update();
     cy.style().selector('edge').css({ 'font-size': new_size }).update();
    }
   catch(err) {
          console.log("Error occurred while altering label font size. \n"+"Error Details: "+ err.stack);
         }
  }

  // Show/ Hide labels for concepts and relations.
  my.showHideLabels = function(val) {
   if(val === "Concepts") {
      my.displayConceptLabels();
     }
   else if(val === "Relations") {
	   my.displayRelationLabels();
     }
   else if(val === "Both") {
	   my.displayConRelLabels();
     }
   else if(val === "None") {
	   my.hideConRelLabels();
     }
  }

  // Show node labels.
  my.displayConceptLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOff").addClass("LabelOn");
   cy.edges().removeClass("LabelOn").addClass("LabelOff");
  }

  // Show edge labels.
  my.displayRelationLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOn").addClass("LabelOff");
   cy.edges().removeClass("LabelOff").addClass("LabelOn");
  }

  // Show node & edge labels.
  my.displayConRelLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOff").addClass("LabelOn");
   cy.edges().removeClass("LabelOff").addClass("LabelOn");
  }

  // Show node labels.
  my.hideConRelLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOn").addClass("LabelOff");
   cy.edges().removeClass("LabelOn").addClass("LabelOff");
  }

	// Full screen: Maximize/ Minimize overlay
  my.OnMaximizeClick = function() {
   var cy_target= $('#cy').cytoscape('get');
   var currentEles_jsons= cy_target.elements().jsons();
   var currentStylesheet_json= cy_target.style().json(); //cy_target.style().json();
   if(!$('#knet-maps').hasClass('full_screen')) {
      $('#maximizeOverlay').removeClass('max').addClass('min'); // toggle image
	// Maximize
      $('#knet-maps').addClass('full_screen');

	// reload the network
	container.load_reload_Network(currentEles_jsons, currentStylesheet_json, false);

      // Show Item Info table
	iteminfo.openItemInfoPane();
     }
     else {
      $('#maximizeOverlay').removeClass('min').addClass('max'); // toggle image
	// Minimize
      $('#knet-maps').removeClass('full_screen');

      // reload the network
	container.load_reload_Network(currentEles_jsons, currentStylesheet_json, false);

      // Hide Item Info table
	iteminfo.closeItemInfoPane();
   }
}

 // Import a saved network into KnetMaps.
 my.importJson = function() {
   // open file dialog
   $("#openNetworkFile").trigger("click");
  }

 // Open selected cyjs JSON file to reload KnetMaps with.
 my.OpenKnetFile = function(event) {
   var selectedFile= event.target.files[0];

   var reader= new FileReader();
   reader.onload= function(e) {
	   my.drawWithJson(e.target.result);
	  };

   // start reading selectd file's contents
   reader.readAsText(selectedFile);
  }

 // Re-initialise KnetMaps with imported/reloaded (pure) JSON.
 my.drawWithJson = function(fileContents) {
	//var selectedFileContents= fileContents; // read file
	var selectedFileContents= JSON.parse(fileContents); // parse as JSON.

	var eles_jsons= selectedFileContents.graph.graphJSON.elements;
	var eles_styles= selectedFileContents.graph.graphJSON.style;
	var metaJSON= selectedFileContents.graph.allGraphData;

	//graphJSON= eles_jsons; // re-add graphJSON
	allGraphData= metaJSON; // re-add metadataJSON to global allGraphData (JS var) for ItemInfo

	//var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
	//var currentStylesheet_json= cy.style().json(); // use loaded eles_styles instead

	// reload KnetMaps with the new network
	//container.load_reload_Network(graphJSON, /*currentStylesheet_json*/ JSON.parse(eles_styles), true);
	container.load_reload_Network(eles_jsons, eles_styles, true);
	eval('stats.updateKnetStats(); conceptLegend.populateConceptLegend();');
  }

  return my;
};
<commit_msg>add api_graphSummary only for valid api_url<commit_after>var KNETMAPS = KNETMAPS || {};

KNETMAPS.Menu = function() {

	var iteminfo = KNETMAPS.ItemInfo();
	var container = KNETMAPS.Container();
	var stats = KNETMAPS.Stats();
	var conceptLegend = KNETMAPS.ConceptsLegend();
	var generator = KNETMAPS.Generator();

	var my=function() {};

 my.onHover = function(thisBtn) {
    $(thisBtn).removeClass('unhover').addClass('hover');
 }

 my.offHover = function(thisBtn) {
	    $(thisBtn).removeClass('hover').addClass('unhover');
 }

 my.popupItemInfo = function() {
	 iteminfo.openItemInfoPane();
	 iteminfo.showItemInfo(this);
 }

   // Go to Help docs.
 my.openKnetHelpPage = function() {
   var helpURL = 'https://github.com/Rothamsted/knetmaps.js/wiki/KnetMaps.js';
   window.open(helpURL, '_blank');
  }

  // Reset: Re-position the network graph.
 my.resetGraph = function() {
   $('#cy').cytoscape('get').reset().fit(); // reset the graph's zooming & panning properties.
  }

  // Export the graph as a JSON object in a new Tab and allow users to save it.
 my.exportAsJson = function() {
   var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`

   var exportJson= cy.json(); // full graphJSON

   var exportedJson= my.filterJsonToExport(cy, exportJson); // the final "graph" to export
   var thumbnail_image= my.exportThumbnail(); // fetch knetwork thumbnail as well.
   // fetch graphSummary from KnetMiner server API.
   var api_graphSummary= my.getGraphDBSummary();

   // compose knetwork metaData below (with name, date, etc.)
   var knet_name= "myKnetwork.json";
   // fetch total node & edge count for this knetwork.
   var totalNodes= cy.$(':visible').nodes().size();
   var totalEdges= cy.$(':visible').edges().size();
   var currentDate= new Date();
   var knet_date= String(currentDate.getDate()).padStart(2, '0') + '/' + String(currentDate.getMonth() + 1).padStart(2, '0') + '/' +
        currentDate.getFullYear() +' '+ currentDate.getHours() +':'+ ('0'+currentDate.getMinutes()).slice(-2); // formatted date (mm: January=0)

   // compose knet_metaData with the above fields.
   var knetwork_metaData= '"name":"'+ knet_name +'", "dateCreated":"'+ knet_date +'", "numNodes":'+ totalNodes +', "numEdges":'+ totalEdges;
   // add api_graphSummary to the above as well, if exists.
   if(api_graphSummary !== null) {
     knetwork_metaData= knetwork_metaData +', "speciesTaxid":"'+ api_graphSummary.speciesTaxid +'", "speciesName":"'+
             api_graphSummary.speciesName +'", "dbVersion":'+ api_graphSummary.dbVersion +', "dbDateCreated":"'+ api_graphSummary.dbDateCreated
             +'", "sourceOrganization":"'+ api_graphSummary.sourceOrganization +'", "provider":"'+ api_graphSummary.provider +'"';
    }
   knetwork_metaData= '{'+ knetwork_metaData +'}';
   /* final knetwork response JSON with metadata, thumbnail & the knetwork itself. */
   var knetSave_response= '{"metaData":'+ knetwork_metaData +', "graph":'+ exportedJson +', "image":"'+ thumbnail_image +'"}';

   // use FileSaver.js to save using file downloader (disable in production/demo).
   //var kNet_json_Blob= new Blob([knetSave_response], {type: 'application/javascript;charset=utf-8'});
   //saveAs(kNet_json_Blob, knet_name);

   console.log("knetSave_response: "+ knetSave_response); // test
   // POST to knetspace: /api/v1/networks/
   // TODO
  }

 // generate pure JSON to export from KnetMaps for graphJSON and metadata
 my.filterJsonToExport = function(cy, exportJson) {

   var elesToRetain= []; // to streamline content exported in exportJson (graphJSON) & metaJSON (allGraphData).
   cy.$(':visible').forEach(function (ele) { elesToRetain.push(ele.id()); });

   // remove hidden nodes/edges metadata from exportJson.
   exportJson.elements.nodes= exportJson.elements.nodes.filter( function( con ) {
	   return elesToRetain.includes(con.data.id); });
   exportJson.elements.edges= exportJson.elements.edges.filter( function( rel ) {
	   return elesToRetain.includes(rel.data.id); });

   // remove hidden nodes/edges metadata from metaJSON (allGraphData).
   var metaJSON= allGraphData;
   metaJSON.ondexmetadata.concepts= metaJSON.ondexmetadata.concepts.filter( function( con ) {
	   return elesToRetain.includes(con.id); });
   metaJSON.ondexmetadata.relations= metaJSON.ondexmetadata.relations.filter( function( rel ) {
	   return elesToRetain.includes(rel.id); });
   // remove other redundant metaJSON entries.
   var omit_redundant= ["graphName","numberOfConcepts","numberOfRelations","version"];
   omit_redundant.forEach(function (entry) { delete metaJSON.ondexmetadata[entry]; });

   var json_response= '{"graphJSON":'+ JSON.stringify(exportJson) + ', "allGraphData":' + JSON.stringify(metaJSON) +'}';
   return json_response;
  }

 // fetch graphSummary from KnetMiner server API.
 my.getGraphDBSummary = function() {
   var graphSummary= null; //'';
   //if(api_url != null || api_url != undefined) {
   if(typeof api_url !== "undefined") {
        $.post({
            url: api_url + '/dataSource',
            timeout: 1000000,
            headers: {
                "Accept": "application/json; charset=utf-8",
                "Content-Type": "application/json; charset=utf-8"
            },
            datatype: "json",
        })
            .fail(function (errorlog) { console.log("An error has ocurred " + errorlog); })
            .success(function (data) {
                graphSummary= JSON.parse(data).dataSource;
            });
     }
 /*  else {
     var dummyText= '{"dataSource":{"speciesTaxid":"","speciesName":"","dbVersion":null,"dbDateCreated":"","sourceOrganization":"","provider":""}}';
     graphSummary= JSON.parse(dummyText).dataSource;
    }*/

    return graphSummary;
  }

  // Export the graph as a .png image and allow users to save it.
 my.exportAsImage = function() {
   var cy = $('#cy').cytoscape('get'); // now we have a global reference to `cy`
    var png64 = cy.png({
                    	"scale" : 6,
                    	"output" : 'base64'
    			}); // .setAttribute('crossOrigin', 'anonymous');
    var a = document.createElement("a"); //Create
    a.href = png64; //Image Base64 Goes here
    a.download = "knet_image.png"; //File name Here
    a.click(); //Downloaded file
  }

  // Export the network thumbnail.
  my.exportThumbnail = function() {
   var png64 = cy.png({
                    "scale" : 0.8,
                    "output" : 'base64'}); // .setAttribute('crossOrigin', 'anonymous');

   return png64.replace("data:image/png;base64,", "");
  }

  // Show all concepts & relations.
 my.showAll = function() {
   var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
   cy.elements().removeClass('HideEle');
   cy.elements().addClass('ShowEle');

   // Relayout the graph.
   my.rerunLayout();

   // Remove shadows around nodes, if any.
   cy.nodes().forEach(function( ele ) {
       iteminfo.removeNodeBlur(ele);
      });

   // Refresh network legend.
   stats.updateKnetStats();
   // Update the stats legend
   conceptLegend.populateConceptLegend();
  }

  // Re-run the entire graph's layout.
 my.rerunLayout = function() {
   // Get the cytoscape instance as a Javascript object from JQuery.
 //  var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
   var selected_elements= cy.$(':visible'); // get only the visible elements.

   // Re-run the graph's layout, but only on the visible elements.
   my.rerunGraphLayout(selected_elements);

   // Reset the graph/ viewport.
   my.resetGraph();
  }

  var layouts = KNETMAPS.Layouts();

  // Re-run the graph's layout, but only on the visible elements.
  my.rerunGraphLayout = function(eles) {
   var ld_selected= $('#layouts_dropdown').val();
   // Use preset layout for reloading saved knetwork.
   //layouts.setPresetLayout(eles); // test preset

   if(ld_selected === "circle_layout") {
	  layouts.setCircleLayout(eles);
     }
   else if(ld_selected === "cose_layout") {
	   layouts.setCoseLayout(eles);
      }
   else if(ld_selected === "coseBilkent_layout") {
	   layouts.setCoseBilkentLayout(eles);
	  }
   else if(ld_selected === "concentric_layout") {
	   layouts.setConcentricLayout(eles);
	  }
   else if(ld_selected === "ngraph_force_layout") {
	   layouts.setNgraphForceLayout(eles);
	  }
  }

  // Update the label font size for all the concepts and relations.
  my.changeLabelFontSize = function(new_size) {
   try {
     var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
     cy.style().selector('node').css({ 'font-size': new_size }).update();
     cy.style().selector('edge').css({ 'font-size': new_size }).update();
    }
   catch(err) {
          console.log("Error occurred while altering label font size. \n"+"Error Details: "+ err.stack);
         }
  }

  // Show/ Hide labels for concepts and relations.
  my.showHideLabels = function(val) {
   if(val === "Concepts") {
      my.displayConceptLabels();
     }
   else if(val === "Relations") {
	   my.displayRelationLabels();
     }
   else if(val === "Both") {
	   my.displayConRelLabels();
     }
   else if(val === "None") {
	   my.hideConRelLabels();
     }
  }

  // Show node labels.
  my.displayConceptLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOff").addClass("LabelOn");
   cy.edges().removeClass("LabelOn").addClass("LabelOff");
  }

  // Show edge labels.
  my.displayRelationLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOn").addClass("LabelOff");
   cy.edges().removeClass("LabelOff").addClass("LabelOn");
  }

  // Show node & edge labels.
  my.displayConRelLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOff").addClass("LabelOn");
   cy.edges().removeClass("LabelOff").addClass("LabelOn");
  }

  // Show node labels.
  my.hideConRelLabels = function() {
   var cy= $('#cy').cytoscape('get'); // reference to `cy`
   cy.nodes().removeClass("LabelOn").addClass("LabelOff");
   cy.edges().removeClass("LabelOn").addClass("LabelOff");
  }

	// Full screen: Maximize/ Minimize overlay
  my.OnMaximizeClick = function() {
   var cy_target= $('#cy').cytoscape('get');
   var currentEles_jsons= cy_target.elements().jsons();
   var currentStylesheet_json= cy_target.style().json(); //cy_target.style().json();
   if(!$('#knet-maps').hasClass('full_screen')) {
      $('#maximizeOverlay').removeClass('max').addClass('min'); // toggle image
	// Maximize
      $('#knet-maps').addClass('full_screen');

	// reload the network
	container.load_reload_Network(currentEles_jsons, currentStylesheet_json, false);

      // Show Item Info table
	iteminfo.openItemInfoPane();
     }
     else {
      $('#maximizeOverlay').removeClass('min').addClass('max'); // toggle image
	// Minimize
      $('#knet-maps').removeClass('full_screen');

      // reload the network
	container.load_reload_Network(currentEles_jsons, currentStylesheet_json, false);

      // Hide Item Info table
	iteminfo.closeItemInfoPane();
   }
}

 // Import a saved network into KnetMaps.
 my.importJson = function() {
   // open file dialog
   $("#openNetworkFile").trigger("click");
  }

 // Open selected cyjs JSON file to reload KnetMaps with.
 my.OpenKnetFile = function(event) {
   var selectedFile= event.target.files[0];

   var reader= new FileReader();
   reader.onload= function(e) {
	   my.drawWithJson(e.target.result);
	  };

   // start reading selectd file's contents
   reader.readAsText(selectedFile);
  }

 // Re-initialise KnetMaps with imported/reloaded (pure) JSON.
 my.drawWithJson = function(fileContents) {
	//var selectedFileContents= fileContents; // read file
	var selectedFileContents= JSON.parse(fileContents); // parse as JSON.

	var eles_jsons= selectedFileContents.graph.graphJSON.elements;
	var eles_styles= selectedFileContents.graph.graphJSON.style;
	var metaJSON= selectedFileContents.graph.allGraphData;

	//graphJSON= eles_jsons; // re-add graphJSON
	allGraphData= metaJSON; // re-add metadataJSON to global allGraphData (JS var) for ItemInfo

	//var cy= $('#cy').cytoscape('get'); // now we have a global reference to `cy`
	//var currentStylesheet_json= cy.style().json(); // use loaded eles_styles instead

	// reload KnetMaps with the new network
	//container.load_reload_Network(graphJSON, /*currentStylesheet_json*/ JSON.parse(eles_styles), true);
	container.load_reload_Network(eles_jsons, eles_styles, true);
	eval('stats.updateKnetStats(); conceptLegend.populateConceptLegend();');
  }

  return my;
};
<|endoftext|>


<commit_before>import MenuBuilder from "../menubuilder";
const FastaExporter = require("biojs-io-fasta").writer;
const _ = require("underscore");
const Exporter = require("../../utils/export");
const ShareSym = "\u21AA";

const ExportMenu = MenuBuilder.extend({

  initialize: function(data) {
    this.g = data.g;
    this.msa = data.msa;
    return this.el.style.display = "inline-block";
  },

  render: function() {
    this.setName("Export");

    this.addNode("Share view (URL)" + ShareSym, () => {
      return Exporter.shareLink(this.msa, function(link) {
        return window.open(link, '_blank');
      });
    });

    this.addNode("View in Jalview", () => {
      var url = this.g.config.get('url');
      if (!(typeof url !== "undefined" && url !== null)) {
        return alert("Sequence weren't imported via an URL");
      } else {
        if (url.indexOf("localhost" || url === "dragimport")) {
          return Exporter.publishWeb(this.msa, (link) => {
            return Exporter.openInJalview(link, this.g.colorscheme.get("scheme"));
          });
        } else {
          return Exporter.openInJalview(url, this.g.colorscheme.get("scheme"));
        }
      }
    });

    this.addNode("Export alignment (FASTA)", () => {
      return Exporter.saveAsFile(this.msa, "all.fasta");
    });

    this.addNode("Export alignment (URL)", () => {
      return Exporter.publishWeb(this.msa, function(link) {
        return window.open(link, '_blank');
      });
    });

    this.addNode("Export selected sequences (FASTA)", () => {
      return Exporter.saveSelection(this.msa, "selection.fasta");
    });

    this.addNode("Export features (GFF)", () => {
      return Exporter.saveAnnots(this.msa, "features.gff3");
    });

    this.addNode("Export MSA image (PNG)", () => {
      return Exporter.saveAsImg(this.msa, "biojs-msa.png");
    });

    this.el.appendChild(this.buildDOM());
    return this;
  }
});
export default ExportMenu;
<commit_msg>Fix exporting menu<commit_after>import MenuBuilder from "../menubuilder";
import Exporter from "../../utils/export";

const FastaExporter = require("biojs-io-fasta").writer;
const _ = require("underscore");

const ShareSym = "\u21AA";

const ExportMenu = MenuBuilder.extend({

  initialize: function(data) {
    this.g = data.g;
    this.msa = data.msa;
    return this.el.style.display = "inline-block";
  },

  render: function() {
    this.setName("Export");

    this.addNode("Share view (URL)" + ShareSym, () => {
      return Exporter.shareLink(this.msa, function(link) {
        return window.open(link, '_blank');
      });
    });

    this.addNode("View in Jalview", () => {
      var url = this.g.config.get('url');
      if (!(typeof url !== "undefined" && url !== null)) {
        return alert("Sequence weren't imported via an URL");
      } else {
        if (url.indexOf("localhost" || url === "dragimport")) {
          return Exporter.publishWeb(this.msa, (link) => {
            return Exporter.openInJalview(link, this.g.colorscheme.get("scheme"));
          });
        } else {
          return Exporter.openInJalview(url, this.g.colorscheme.get("scheme"));
        }
      }
    });

    this.addNode("Export alignment (FASTA)", () => {
      return Exporter.saveAsFile(this.msa, "all.fasta");
    });

    this.addNode("Export alignment (URL)", () => {
      return Exporter.publishWeb(this.msa, function(link) {
        return window.open(link, '_blank');
      });
    });

    this.addNode("Export selected sequences (FASTA)", () => {
      return Exporter.saveSelection(this.msa, "selection.fasta");
    });

    this.addNode("Export features (GFF)", () => {
      return Exporter.saveAnnots(this.msa, "features.gff3");
    });

    this.addNode("Export MSA image (PNG)", () => {
      return Exporter.saveAsImg(this.msa, "biojs-msa.png");
    });

    this.el.appendChild(this.buildDOM());
    return this;
  }
});
export default ExportMenu;
<|endoftext|>


<commit_before>(function (window) {
	'use strict';

var tasks = [
    {content: "Taste Javascript",
     finished:false,
     editing: false},
    {content:"Buy a Unicorn",
     finished:false,
     editing:false}
]

 new Vue ({
        el:'#todo-list',
        data: {
           tasks: tasks
        },
        methods: {
             edit: function(content) {
              content.editing = true;
        },
             save: function(content) {
                content.editing=false;
//                 SAVE
             }
    }
});

})(window);

<commit_msg>saving comments for local storage<commit_after>(function (window) {
	'use strict';

var tasks = [
    {content: "Taste Javascript",
     finished:false,
     editing: false
    },

    {content:"Buy a Unicorn",
     finished:false,
     editing:false
    }
]

 new Vue ({
        el:'#todo-list',
        data: {
           tasks: tasks
        },
        methods: {
             edit: function(content) {
              content.editing = true;
        },
             save: function(content) {
                content.editing=false;
                content.editing == this.content;
                //Storing(this.tasks);
            }
    }
});

//    function Storing(tasks) {
//    localStorage.setItem('tasks', JSON.stringify('tasks').content)};

})(window);

<|endoftext|>


<commit_before>require('electron-compile').init()
require('./app.js')

<commit_msg>Nevermind that, we can lint this just fine.<commit_after>require('electron-compile').init();
require('./app.js');
<|endoftext|>


<commit_before>// ==UserScript==
// @name Hide/Show Unnecessary Info in Chat
// @version 1.0
// @author michaelpri
// @description Userscript to hide/show unecessary information that takes up room on the chat sidebar
// @include *://chat.stackexchange.com/*
// @include *://chat.stackoverflow.com/*
// @include *://chat.meta.stackexchange.com/*
// ==/UserScript==

function hide_show($) {

    function hide_show_users() {
        var present_users = $("#present-users");
        $("

").insertAfter(present_users);
        var users_button_table = $("#users-button-table");
        users_button_table.append("

");
        var users_button_row = $('#users-button-row');
        users_button_row.append("Hide Users	");
        users_button_row.append("Show Users	");
        var hide_users = $("#hide-users");
        var show_users = $('#show-users');
        var users_show_hide_buttons = $(".users-show-hide-button");

        users_button_table.css({"border-bottom":"1px dotted #cecece", "width":"100%"});
        users_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-bottom":"5px"});
        present_users.css({"margin-bottom":"5px"});
        users_show_hide_buttons.on("mouseover", function() {
            users_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"});
        });
        users_show_hide_buttons.on("mouseout", function() {
            users_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"});
        });

        present_users.hide();
        hide_users.hide();

        show_users.on("click", function() {
            present_users.show();
            hide_users.show();
            show_users.hide();
        });
        hide_users.on("click", function() {
            present_users.hide();
            show_users.show();
            hide_users.hide();
        });
    }

    function hide_show_info() {
        var room_desc = $("#roomdesc");
        var room_tags = $('#room-tags');
        var sidebar_menu = $('#sidebar-menu');
        $("

").insertAfter(room_tags);
        var info_button_table = $("#info-button-table");
        info_button_table.append("

");
        var info_button_row = $('#info-button-row');
        info_button_row.append("Hide Info	");
        info_button_row.append("Show Info	");
        var hide_info = $("#hide-info");
        var show_info = $('#show-info');
        var info_show_hide_buttons = $(".info-show-hide-button");

        info_button_table.css({"border-top":"1px dotted #cecece", "width":"100%", "border-bottom":"1px dotted #cecece"});
        info_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-top":"5px", "padding-bottom":"5px"});
        sidebar_menu.css({"padding-top":"5px"})
        info_show_hide_buttons.on("mouseover", function() {
            info_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"});
        });
        info_show_hide_buttons.on("mouseout", function() {
            info_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"});
        });

        room_desc.hide();
        room_tags.hide();
        hide_info.hide();

        show_info.on("click", function() {
            room_desc.show();
            room_tags.show();
            hide_info.show();
            show_info.hide();
        });
        hide_info.on("click", function() {
            room_desc.hide();
            room_tags.hide();
            hide_info.hide();
            show_info.show();
        });
    }

    hide_show_users();
    hide_show_info();
}

window.addEventListener('load', function() {
    var scriptEl = document.createElement('script');
    scriptEl.type = 'text/javascript';
    scriptEl.text = '(' + hide_show + ')(jQuery);';
    document.head.appendChild(scriptEl);
});
<commit_msg>Update userscript info<commit_after>// ==UserScript==
// @name Hide Unnecessary Info in SE Chat
// @version 1.0
// @author michaelpri
// @description Userscript to hide unecessary or cluttering information that takes up room on the chat sidebar
// @include *://chat.stackexchange.com/*
// @include *://chat.stackoverflow.com/*
// @include *://chat.meta.stackexchange.com/*
// ==/UserScript==

function hide_show($) {

    function hide_show_users() {
        var present_users = $("#present-users");
        $("

").insertAfter(present_users);
        var users_button_table = $("#users-button-table");
        users_button_table.append("

");
        var users_button_row = $('#users-button-row');
        users_button_row.append("Hide Users	");
        users_button_row.append("Show Users	");
        var hide_users = $("#hide-users");
        var show_users = $('#show-users');
        var users_show_hide_buttons = $(".users-show-hide-button");

        users_button_table.css({"border-bottom":"1px dotted #cecece", "width":"100%"});
        users_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-bottom":"5px"});
        present_users.css({"margin-bottom":"5px"});
        users_show_hide_buttons.on("mouseover", function() {
            users_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"});
        });
        users_show_hide_buttons.on("mouseout", function() {
            users_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"});
        });

        present_users.hide();
        hide_users.hide();

        show_users.on("click", function() {
            present_users.show();
            hide_users.show();
            show_users.hide();
        });
        hide_users.on("click", function() {
            present_users.hide();
            show_users.show();
            hide_users.hide();
        });
    }

    function hide_show_info() {
        var room_desc = $("#roomdesc");
        var room_tags = $('#room-tags');
        var sidebar_menu = $('#sidebar-menu');
        $("

").insertAfter(room_tags);
        var info_button_table = $("#info-button-table");
        info_button_table.append("

");
        var info_button_row = $('#info-button-row');
        info_button_row.append("Hide Info	");
        info_button_row.append("Show Info	");
        var hide_info = $("#hide-info");
        var show_info = $('#show-info');
        var info_show_hide_buttons = $(".info-show-hide-button");

        info_button_table.css({"border-top":"1px dotted #cecece", "width":"100%", "border-bottom":"1px dotted #cecece"});
        info_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-top":"5px", "padding-bottom":"5px"});
        sidebar_menu.css({"padding-top":"5px"})
        info_show_hide_buttons.on("mouseover", function() {
            info_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"});
        });
        info_show_hide_buttons.on("mouseout", function() {
            info_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"});
        });

        room_desc.hide();
        room_tags.hide();
        hide_info.hide();

        show_info.on("click", function() {
            room_desc.show();
            room_tags.show();
            hide_info.show();
            show_info.hide();
        });
        hide_info.on("click", function() {
            room_desc.hide();
            room_tags.hide();
            hide_info.hide();
            show_info.show();
        });
    }

    hide_show_users();
    hide_show_info();
}

window.addEventListener('load', function() {
    var scriptEl = document.createElement('script');
    scriptEl.type = 'text/javascript';
    scriptEl.text = '(' + hide_show + ')(jQuery);';
    document.head.appendChild(scriptEl);
});
<|endoftext|>


<commit_before>/*********************************************************************
* #### jQuery File Browser Awesome v01 ####
* Coded by Ican Bachors 2014.
* http://ibacor.com/labs/jquery-file-browser-awesome/
* Updates will be posted to this site.
*********************************************************************/

// Base_URL scandir.php
var baseurl = 'http://localhost/fba/scandir.php';

/* Testing di localhost */
var fix = /\\/;

/* atau jika tombol back bermasalah ketika sudah di hosting gunakan script dibawah ini:
var fix = /\//;
*/

ibc_fba(baseurl,sub="",fix)

function ibc_fba(baseurl,sub,fix) {
	$.ajax( {
		url:baseurl+'?sub='+sub,
		crossDomain:true,
		dataType:"json"
	}).done(function(data) {
		var r="";
		r+="
";
		r+='

Name	Size	Last Modified

';
		if(data.back!="") {
			r+='
 '+data.root+"
"
		}
		$.each(data.items,function(i,item) {
			var size=ibc_ukurana(data.items[i].size);
			if(data.items[i].type=="folder") {
				r+='
 '+data.items[i].name+'	'+data.items[i].items.length+' item	'+data.items[i].modif+"
"
			} else {
				var s=data.items[i].path.substr(data.items[i].path.lastIndexOf(".")+1);
				switch(s) {
					// List read file. Custom/add example case"asp":case"jsp" etc
					case"html":
					case"php":
					case"js":
					case"css":
					case"txt":
					r+='
 '+data.items[i].name+'	'+size+'	'+data.items[i].modif+"
";
					break;
					// List download file
					default:
					r+='
 '+data.items[i].name+'	'+size+'	'+data.items[i].modif+"
"
				}
			}
		});
		r+='
'+unescape("%3C%61%20%68%72%65%66%3D%22%68%74%74%70%3A%2F%2F%69%62%61%63%6F%72%2E%63%6F%6D%2F%6C%61%62%73%2F%6A%71%75%65%72%79%2D%66%69%6C%65%2D%62%72%6F%77%73%65%72%2D%61%77%65%73%6F%6D%65%2F%22%20%74%61%72%67%65%74%3D%22%5F%42%4C%41%4E%4B%22%3E%46%69%6C%65%20%42%72%6F%77%73%65%72%20%41%77%65%73%6F%6D%65%3C%2F%61%3E")+"
";
		r+="

";
		$(".ibc_fba").html(r);
		$("#ibc_fba_file").html('');
		$(".sub").click(function() {
			var t=$(this).data("sub");
			ibc_fba(baseurl,t,fix);
			return false
		});
		$(".bsub").click(function() {
			var t=$(this).data("bsub");
			ibc_fba(baseurl,t,fix);
			return false
		});
		$(".rfile").click(function() {
			var file=$(this).data("rfile");
			ibc_fba_file(baseurl,file);
			return false
		});
	});
}

function ibc_fba_file(baseurl,file) {
	$.ajax( {
		url:baseurl+'?file='+file,
		crossDomain:true,
		dataType:"json"
	}).done(function(data) {
		var t='
 Ctrl-F / Cmd-F: Start searching, Ctrl-G / Cmd-G: Find next, Shift-Ctrl-G / Shift-Cmd-G: Find previous, Shift-Ctrl-F / Cmd-Option-F: Replace, Shift-Ctrl-R / Shift-Cmd-Option-F: Replace all
<textarea id="text" name="text">'+data.text+'</textarea>';
		$("#ibc_fba_file").html(t)
	});
}

function ibc_ukurana(e) {
	var t=["Bytes","KB","MB","GB","TB"];
	if(e==0)return"0 Bytes";
	var n=parseInt(Math.floor(Math.log(e)/Math.log(1024)));
	return Math.round(e/Math.pow(1024,n),2)+" "+t[n]
}
<commit_msg>add window.history.pushState<commit_after>/*********************************************************************
* #### jQuery File Browser Awesome v01 ####
* Coded by Ican Bachors 2014.
* http://ibacor.com/labs/jquery-file-browser-awesome/
* Updates will be posted to this site.
*********************************************************************/

// Base_URL scandir.php
var baseurl = 'http://localhost/fba/scandir.php';

/* Testing di localhost */
var fix = /\\/;

/* atau jika tombol back bermasalah ketika sudah di hosting gunakan script dibawah ini:
var fix = /\//;
*/

var value = getParameterByName('dir');
if(value != ''){
	ibc_fba(scan,sub=value,fix);
}else{
	ibc_fba(baseurl,sub="",fix)
}

function ibc_fba(baseurl,sub,fix) {
	$.ajax( {
		url:baseurl+'?sub='+sub,
		crossDomain:true,
		dataType:"json"
	}).done(function(data) {
		var r="";
		r+="
";
		r+='

Name	Size	Last Modified

';
		if(data.back!="") {
			r+='
 '+data.root+"
"
		}
		$.each(data.items,function(i,item) {
			var size=ibc_ukurana(data.items[i].size);
			if(data.items[i].type=="folder") {
				r+='
 '+data.items[i].name+'	'+data.items[i].items.length+' item	'+data.items[i].modif+"
"
			} else {
				var s=data.items[i].path.substr(data.items[i].path.lastIndexOf(".")+1);
				switch(s) {
					// List read file. Custom/add example case"asp":case"jsp" etc
					case"html":
					case"php":
					case"js":
					case"css":
					case"txt":
					r+='
 '+data.items[i].name+'	'+size+'	'+data.items[i].modif+"
";
					break;
					// List download file
					default:
					r+='
 '+data.items[i].name+'	'+size+'	'+data.items[i].modif+"
"
				}
			}
		});
		r+='
'+unescape("%3C%61%20%68%72%65%66%3D%22%68%74%74%70%3A%2F%2F%69%62%61%63%6F%72%2E%63%6F%6D%2F%6C%61%62%73%2F%6A%71%75%65%72%79%2D%66%69%6C%65%2D%62%72%6F%77%73%65%72%2D%61%77%65%73%6F%6D%65%2F%22%20%74%61%72%67%65%74%3D%22%5F%42%4C%41%4E%4B%22%3E%46%69%6C%65%20%42%72%6F%77%73%65%72%20%41%77%65%73%6F%6D%65%3C%2F%61%3E")+"
";
		r+="

";
		$(".ibc_fba").html(r);
		$("#ibc_fba_file").html('');
		$(".sub").click(function() {
			var t=$(this).data("sub");
			ibc_fba(baseurl,t,fix);
			window.history.pushState(null, null, "?dir="+t);
			return false
		});
		$(".bsub").click(function() {
			var t=$(this).data("bsub");
			ibc_fba(baseurl,t,fix);
			window.history.pushState(null, null, "?dir="+t);
			return false
		});
		$(".rfile").click(function() {
			var file=$(this).data("rfile");
			ibc_fba_file(baseurl,file);
			return false
		});
	});
}

function ibc_fba_file(baseurl,file) {
	$.ajax( {
		url:baseurl+'?file='+file,
		crossDomain:true,
		dataType:"json"
	}).done(function(data) {
		var t='
 Ctrl-F / Cmd-F: Start searching, Ctrl-G / Cmd-G: Find next, Shift-Ctrl-G / Shift-Cmd-G: Find previous, Shift-Ctrl-F / Cmd-Option-F: Replace, Shift-Ctrl-R / Shift-Cmd-Option-F: Replace all
<textarea id="text" name="text">'+data.text+'</textarea>';
		$("#ibc_fba_file").html(t)
	});
}

function ibc_ukurana(e) {
	var t=["Bytes","KB","MB","GB","TB"];
	if(e==0)return"0 Bytes";
	var n=parseInt(Math.floor(Math.log(e)/Math.log(1024)));
	return Math.round(e/Math.pow(1024,n),2)+" "+t[n]
}

function getParameterByName(name) {
	name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
	var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
	results = regex.exec(location.search);
	return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
<|endoftext|>


<commit_before>var map = {
    makeFeatures: {
        section: function(json) {
            if (!( "geojson" in json)) {
               return [];
            }
            return [
                L.geoJson(json.geojson, {
                    style: function() {
                        var color = '#fff';
                        if ("display_informations" in json) {
                            color = getTextColor(json.display_informations);
                        }
                        return {
                            color: color,
                            weight: 6,
                            opacity: 1
                        };
                    }
                }),
                L.geoJson(json.geojson, {
                    style: function() {
                        var color = '#008ACA';
                        if ("display_informations" in json) {
                            color = "#" + json.display_informations.color;
                        }
                        return {
                            color: color,
                            weight: 5,
                            opacity: 1
                        };
                    }
                })
            ];
        },
        journey: function(json) {
            return flatMap(json.sections, map.makeFeatures.section);
        },
        address: function(json) {
            return map._makeMarker('address', json);
        },
        administrative_region: function(json) {
            return map._makeMarker('administrative_region', json);
        },
        stop_area: function(json) {
            return map._makeMarker('stop_area', json);
        },
        stop_point: function(json) {
            return map._makeMarker('stop_point', json);
        },
        poi: function(json) {
            return map._makeMarker('poi', json);
        },
        response: function(json) {
            var key = responseCollectionName(json);
            if (key === null) {
                return [];
            }
            var type = getType(key);
            if (!(type in map.makeFeatures)) {
                return [];
            }
            return flatMap(json[key], map.makeFeatures[type]);
        }
    },

    run: function(type, json) {
        var div = $('
');
        // setting for default path of images used by leaflet
        L.Icon.Default.imagePath='lib/img/leaflet/dist/images';
        var features = [];
        if (map.makeFeatures[type] instanceof Function &&
            (features = map.makeFeatures[type](json)).length) {
            div.addClass('leaflet');
            var m = L.map(div.get(0)).setView([48.843693, 2.373303], 13);
            mapLink = 'OpenStreetMap';
            mapquestLink = 'MapQuest';
            mapquestPic = '';
            L.tileLayer(
                'http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
                    attribution: '© '+mapLink+'. Tiles courtesy of '+mapquestLink+mapquestPic,
                    maxZoom: 17,
                    subdomains: '1234',
            }).addTo(m);
            var overlay = L.featureGroup(features).addTo(m);
            setTimeout(function(){
                m.invalidateSize();
                m.fitBounds(overlay.getBounds());

            }, 100);

        } else {
            div.addClass('noMap');
            div.append('No map');
        }
        return div;
    },

    _makeMarker: function(type, json) {
        return [L.marker([json.coord.lat, json.coord.lon]).bindPopup(summary.run(new Context(json), type, json))];
    },
};
<commit_msg>remove empty lines<commit_after>var map = {
    makeFeatures: {
        section: function(json) {
            if (!( "geojson" in json)) {
               return [];
            }
            return [
                L.geoJson(json.geojson, {
                    style: function() {
                        var color = '#fff';
                        if ("display_informations" in json) {
                            color = getTextColor(json.display_informations);
                        }
                        return {
                            color: color,
                            weight: 6,
                            opacity: 1
                        };
                    }
                }),
                L.geoJson(json.geojson, {
                    style: function() {
                        var color = '#008ACA';
                        if ("display_informations" in json) {
                            color = "#" + json.display_informations.color;
                        }
                        return {
                            color: color,
                            weight: 5,
                            opacity: 1
                        };
                    }
                })
            ];
        },
        journey: function(json) {
            return flatMap(json.sections, map.makeFeatures.section);
        },
        address: function(json) {
            return map._makeMarker('address', json);
        },
        administrative_region: function(json) {
            return map._makeMarker('administrative_region', json);
        },
        stop_area: function(json) {
            return map._makeMarker('stop_area', json);
        },
        stop_point: function(json) {
            return map._makeMarker('stop_point', json);
        },
        poi: function(json) {
            return map._makeMarker('poi', json);
        },
        response: function(json) {
            var key = responseCollectionName(json);
            if (key === null) {
                return [];
            }
            var type = getType(key);
            if (!(type in map.makeFeatures)) {
                return [];
            }
            return flatMap(json[key], map.makeFeatures[type]);
        }
    },

    run: function(type, json) {
        var div = $('
');
        // setting for default path of images used by leaflet
        L.Icon.Default.imagePath='lib/img/leaflet/dist/images';
        var features = [];
        if (map.makeFeatures[type] instanceof Function &&
            (features = map.makeFeatures[type](json)).length) {
            div.addClass('leaflet');
            var m = L.map(div.get(0)).setView([48.843693, 2.373303], 13);
            mapLink = 'OpenStreetMap';
            mapquestLink = 'MapQuest';
            mapquestPic = '';
            L.tileLayer(
                'http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
                    attribution: '© '+mapLink+'. Tiles courtesy of '+mapquestLink+mapquestPic,
                    maxZoom: 17,
                    subdomains: '1234',
            }).addTo(m);
            var overlay = L.featureGroup(features).addTo(m);
            setTimeout(function() {
                m.invalidateSize();
                m.fitBounds(overlay.getBounds());
            }, 100);
        } else {
            div.addClass('noMap');
            div.append('No map');
        }
        return div;
    },

    _makeMarker: function(type, json) {
        return [L.marker([json.coord.lat, json.coord.lon]).bindPopup(summary.run(new Context(json), type, json))];
    },
};
<|endoftext|>


<commit_before>var difficulty;

function SparqlSend(area){

	var area2 = "'"+area+"'";

	var rdfmgr = new RDFmgr("prefecturePigPopulation");
	var prefecture = "select ?num where {?s lodcu:都道府県 "+area2+" ;lodcu:豚頭数 ?num.} LIMIT 100";

	console.log(prefecture);

	console.log(area2);

	rdfmgr.executeQuery({
		sparql: prefecture,
		success: maketable,
		error: getErrorMsg
	});
}

function maketable(re){
	var str = new String();
	while(re.next()){
		for(var i=0; i < re.getLength();i++){
			str += re.getValue(i);
		}
	}
	console.log(str);
	if(str < 250){
		difficulty = 1;
	}else if(str >= 250 && str <=500){
		difficulty = 2;
	}else if(str >= 500 && str <=750){
		difficulty = 3;
	}
	console.log(difficulty);
}

function getErrorMsg(eType,eMsg,eMsg2){
	alert(eMsg+"\n\n"+eMsg2);
}<commit_msg>データを都道府県から地方へ変更<commit_after>var difficulty;

function SparqlSend(area){

	var area2 = "'"+area+"'";

	var rdfmgr = new RDFmgr("pigArea");
	var prefecture = "select ?num where {?s lodcu:地方 "+area2+" ;lodcu:豚頭数 ?num.} LIMIT 100";

	console.log(prefecture);

	console.log(area2);

	rdfmgr.executeQuery({
		sparql: prefecture,
		success: maketable,
		error: getErrorMsg
	});
}

function maketable(re){
	var str = new String();
	while(re.next()){
		for(var i=0; i < re.getLength();i++){
			str += re.getValue(i);
		}
	}
	console.log(str);
	if(str < 250){
		difficulty = 1;
	}else if(str >= 250 && str <=500){
		difficulty = 2;
	}else if(str >= 500 && str <=750){
		difficulty = 3;
	}
	console.log(difficulty);
}

function getErrorMsg(eType,eMsg,eMsg2){
	alert(eMsg+"\n\n"+eMsg2);
}<|endoftext|>


<commit_before>import React from 'react';
import { Image, ActivityIndicator } from 'react-native';
import RNFS, { DocumentDirectoryPath } from 'react-native-fs';
import ResponsiveImage from 'react-native-responsive-image';

const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');

export default
class CacheableImage extends React.Component {
    constructor(props) {
        super(props)
        this.imageDownloadBegin = this.imageDownloadBegin.bind(this);
        this.imageDownloadProgress = this.imageDownloadProgress.bind(this);

        this.state = {
            isRemote: false,
            cachedImagePath: null,
            downloading: false,
            cacheable: true,
            jobId: null
        };
    };

    componentWillReceiveProps(nextProps) {
        if (nextProps.source != this.props.source) {
            this._processSource(nextProps.source);
        }
    }

    async imageDownloadBegin(info) {
        this.setState({downloading: true, jobId: info.jobId});
    }

    async imageDownloadProgress(info) {
        if ((info.contentLength / info.bytesWritten) == 1) {
            this.setState({downloading: false, jobId: null});
        }
    }

    async checkImageCache(imageUri, cachePath, cacheKey) {
        const dirPath = DocumentDirectoryPath+'/'+cachePath;
        const filePath = dirPath+'/'+cacheKey;

        RNFS
        .stat(filePath)
        .then((res) => {
            if (res.isFile()) {
                // means file exists, ie, cache-hit
                this.setState({cacheable: true, cachedImagePath: filePath});
            }
        })
        .catch((err) => {
            // means file does not exist
            // first make sure directory exists.. then begin download
            // The NSURLIsExcludedFromBackupKey property can be provided to set this attribute on iOS platforms.
            // Apple will reject apps for storing offline cache data that does not have this attribute.
            // https://github.com/johanneslumpe/react-native-fs#mkdirfilepath-string-options-mkdiroptions-promisevoid
            RNFS
            .mkdir(dirPath, {NSURLIsExcludedFromBackupKey: true})
            .then(() => {
                // before we change the cachedImagePath.. if the previous cachedImagePath was set.. remove it
                if (this.state.cacheable && this.state.cachedImagePath) {
                    let delImagePath = this.state.cachedImagePath;
                    RNFS
                    .exists(delImagePath)
                    .then((res) => {
                        if (res) {
                            RNFS
                            .unlink(delImagePath)
                            .catch((err) => {});
                        }
                    });
                }

              let downloadOptions = {
                fromUrl: imageUri,
                toFile: filePath,
                background: true,
                begin: this.imageDownloadBegin,
                progress: this.imageDownloadProgress
              };

                // directory exists.. begin download
                RNFS
                .downloadFile(downloadOptions)
                .then(() => {
                    this.setState({cacheable: true, cachedImagePath: filePath});
                })
                .catch((err) => {
                    this.setState({cacheable: false, cachedImagePath: null});
                });
            })
            .catch((err) => {
                this.setState({cacheable: false, cachedImagePath: null});
            })
        });
    }

    _processSource(source) {
        if (source !== null
            && typeof source === "object"
            && source.hasOwnProperty('uri'))
        { // remote
            const url = new URL(source.uri);
            const type = url.pathname.replace(/.*\.(.*)/, '$1');
            const cacheKey = SHA1(url.pathname)+'.'+type;

            this.checkImageCache(source.uri, url.host, cacheKey);
            this.setState({isRemote: true});
        }
        else {
            this.setState({isRemote: false});
        }
    }

    componentWillMount() {
        this._processSource(this.props.source);
    }

    componentWillUnmount() {
        if (this.state.downloading && this.state.jobId) {
            RNFS.stopDownload(this.state.jobId);
        }
    }

    render() {
        if (!this.state.isRemote || !this.state.cacheable) {
            return this.renderLocal();
        }

        if (this.state.cacheable && this.state.cachedImagePath) {
            return this.renderCache();
        }

        return (
            <ActivityIndicator  />
        );
    }

    renderCache() {
        return (
            <ResponsiveImage {...this.props} source={{uri: 'file://'+this.state.cachedImagePath}}>
            {this.props.children}
            </ResponsiveImage>
        );
    }

    renderLocal() {
        return (
            <ResponsiveImage {...this.props} >
            {this.props.children}
            </ResponsiveImage>
        );
    }
}
<commit_msg>Added support for defaultSource prop to allow displaying a placeholder image instead of an ActivityIndicator.<commit_after>import React from 'react';
import { Image, ActivityIndicator } from 'react-native';
import RNFS, { DocumentDirectoryPath } from 'react-native-fs';
import ResponsiveImage from 'react-native-responsive-image';

const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');

export default
class CacheableImage extends React.Component {
    constructor(props) {
        super(props)
        this.imageDownloadBegin = this.imageDownloadBegin.bind(this);
        this.imageDownloadProgress = this.imageDownloadProgress.bind(this);

        this.state = {
            isRemote: false,
            cachedImagePath: null,
            downloading: false,
            cacheable: true,
            jobId: null
        };
    };

    componentWillReceiveProps(nextProps) {
        if (nextProps.source != this.props.source) {
            this._processSource(nextProps.source);
        }
    }

    async imageDownloadBegin(info) {
        this.setState({downloading: true, jobId: info.jobId});
    }

    async imageDownloadProgress(info) {
        if ((info.contentLength / info.bytesWritten) == 1) {
            this.setState({downloading: false, jobId: null});
        }
    }

    async checkImageCache(imageUri, cachePath, cacheKey) {
        const dirPath = DocumentDirectoryPath+'/'+cachePath;
        const filePath = dirPath+'/'+cacheKey;

        RNFS
        .stat(filePath)
        .then((res) => {
            if (res.isFile()) {
                // means file exists, ie, cache-hit
                this.setState({cacheable: true, cachedImagePath: filePath});
            }
        })
        .catch((err) => {
            // means file does not exist
            // first make sure directory exists.. then begin download
            // The NSURLIsExcludedFromBackupKey property can be provided to set this attribute on iOS platforms.
            // Apple will reject apps for storing offline cache data that does not have this attribute.
            // https://github.com/johanneslumpe/react-native-fs#mkdirfilepath-string-options-mkdiroptions-promisevoid
            RNFS
            .mkdir(dirPath, {NSURLIsExcludedFromBackupKey: true})
            .then(() => {
                // before we change the cachedImagePath.. if the previous cachedImagePath was set.. remove it
                if (this.state.cacheable && this.state.cachedImagePath) {
                    let delImagePath = this.state.cachedImagePath;
                    RNFS
                    .exists(delImagePath)
                    .then((res) => {
                        if (res) {
                            RNFS
                            .unlink(delImagePath)
                            .catch((err) => {});
                        }
                    });
                }

              let downloadOptions = {
                fromUrl: imageUri,
                toFile: filePath,
                background: true,
                begin: this.imageDownloadBegin,
                progress: this.imageDownloadProgress
              };

                // directory exists.. begin download
                RNFS
                .downloadFile(downloadOptions)
                .then(() => {
                    this.setState({cacheable: true, cachedImagePath: filePath});
                })
                .catch((err) => {
                    this.setState({cacheable: false, cachedImagePath: null});
                });
            })
            .catch((err) => {
                this.setState({cacheable: false, cachedImagePath: null});
            })
        });
    }

    _processSource(source) {
        if (source !== null
            && typeof source === "object"
            && source.hasOwnProperty('uri'))
        { // remote
            const url = new URL(source.uri);
            const type = url.pathname.replace(/.*\.(.*)/, '$1');
            const cacheKey = SHA1(url.pathname)+'.'+type;

            this.checkImageCache(source.uri, url.host, cacheKey);
            this.setState({isRemote: true});
        }
        else {
            this.setState({isRemote: false});
        }
    }

    componentWillMount() {
        this._processSource(this.props.source);
    }

    componentWillUnmount() {
        if (this.state.downloading && this.state.jobId) {
            RNFS.stopDownload(this.state.jobId);
        }
    }

    render() {
        if (!this.state.isRemote || !this.state.cacheable) {
            return this.renderLocal();
        }

        if (this.state.cacheable && this.state.cachedImagePath) {
            return this.renderCache();
        }

		if (this.props.defaultSource) {
			return (
				<ResponsiveImage {...this.props} source={this.props.defaultSource}>
	            {this.props.children}
	            </ResponsiveImage>
			);
		} else {
	        return (
	            <ActivityIndicator  />
	        );
		}
    }

    renderCache() {
        return (
            <ResponsiveImage {...this.props} source={{uri: 'file://'+this.state.cachedImagePath}}>
            {this.props.children}
            </ResponsiveImage>
        );
    }

    renderLocal() {
        return (
            <ResponsiveImage {...this.props} >
            {this.props.children}
            </ResponsiveImage>
        );
    }
}
<|endoftext|>


<commit_before>var harvester = require('harvester');
var miner = require('miner');
var collecter = require('collector');
var builder = require('builder');
var guard = require('guard');
var attacker = require('attacker');
var rangedattacker = require('rangedattacker');
var upgrader = require('upgrader');
var upgraderhelper = require('upgraderhelper');

Spawn.prototype.createRole = function(role) {
    return this.createCreep(roles[role], null, {role: role});
};

Creep.prototype.isSafe = function(position) {
    return position.findInRange(FIND_HOSTILE_CREEPS, 5).length == 0
        && position.findInRange(FIND_HOSTILE_STRUCTURES, 5).length == 0;
}

var getTarget = function(creep) {
    var target = null;
    var creepTarget = creep.pos.findClosest(FIND_HOSTILE_CREEPS);
    var structTarget = creep.pos.findClosest(FIND_HOSTILE_STRUCTURES);
    if (!structTarget) {
        target = creepTarget;
    } else if (!creepTarget) {
        target = structTarget;
    } else {
        creepTargetDist = creep.pos.findPathTo(creepTarget);
        structTargetDist = creep.pos.findPathTo(structTarget);
        if (creepTargetDist < structTargetDist + 5) {
            target = creepTarget;
        } else{
            target = structTarget;
        }
    }
    return target;
}

var roles = {
    'miner': [MOVE, WORK, WORK, WORK, WORK],
    'collector': [MOVE, MOVE, CARRY, CARRY, CARRY],
    'harvester': [MOVE, MOVE, CARRY, WORK],
    'builder': [WORK, WORK, CARRY, CARRY, MOVE],
    'guard': [TOUGH, MOVE, ATTACK, ATTACK, ATTACK],
    'attack': [TOUGH, ATTACK, ATTACK, MOVE, MOVE],
    'rangedattack': [TOUGH, MOVE, RANGED_ATTACK, RANGED_ATTACK, RANGED_ATTACK],
    'upgrader': [MOVE, WORK, WORK, WORK, CARRY],
    'upgraderhelper': [MOVE, MOVE, CARRY, CARRY, CARRY],
}

var desiredRoles = {
    'miner': 1,
    'collector': 5,
    'guard': 2,
    'attack': 0,
    'builder': 3,
    'rangedattack': 0,
    'upgrader': 1,
    'upgraderhelper': 2,
}

var existingRoles = {}
for (var role in desiredRoles) {
    existingRoles[role] = 0;
}
for (var name in Game.creeps) {
    var creep = Game.creeps[name];
    existingRoles[creep.memory.role] += 1;
};
for (var role in desiredRoles) {
    if (existingRoles[role] < desiredRoles[role]) {
        Game.spawns.Spawn1.createRole(role);
        break;
    }
}

for(var name in Game.creeps) {
    var creep = Game.creeps[name];

    if(creep.memory.role == 'harvester') {
        harvester(creep);
    } else if (creep.memory.role == 'miner') {
        miner(creep);
    } else if (creep.memory.role == 'collector') {
        collecter(creep);
    } else if (creep.memory.role == 'builder') {
        builder(creep);
    } else if (creep.memory.role == 'guard') {
        guard(creep);
    } else if (creep.memory.role == 'attack') {
        attacker(creep);
    } else if (creep.memory.role == 'rangedattack') {
        rangedattacker(creep);
    } else if (creep.memory.role == 'upgrader') {
        upgrader(creep);
    } else if (creep.memory.role == 'upgraderhelper') {
        upgraderhelper(creep);
    }
}
<commit_msg>Tweak numbers<commit_after>var harvester = require('harvester');
var miner = require('miner');
var collecter = require('collector');
var builder = require('builder');
var guard = require('guard');
var attacker = require('attacker');
var rangedattacker = require('rangedattacker');
var upgrader = require('upgrader');
var upgraderhelper = require('upgraderhelper');

Spawn.prototype.createRole = function(role) {
    return this.createCreep(roles[role], null, {role: role});
};

Creep.prototype.isSafe = function(position) {
    return position.findInRange(FIND_HOSTILE_CREEPS, 5).length == 0
        && position.findInRange(FIND_HOSTILE_STRUCTURES, 5).length == 0;
}

var getTarget = function(creep) {
    var target = null;
    var creepTarget = creep.pos.findClosest(FIND_HOSTILE_CREEPS);
    var structTarget = creep.pos.findClosest(FIND_HOSTILE_STRUCTURES);
    if (!structTarget) {
        target = creepTarget;
    } else if (!creepTarget) {
        target = structTarget;
    } else {
        creepTargetDist = creep.pos.findPathTo(creepTarget);
        structTargetDist = creep.pos.findPathTo(structTarget);
        if (creepTargetDist < structTargetDist + 5) {
            target = creepTarget;
        } else{
            target = structTarget;
        }
    }
    return target;
}

var roles = {
    'miner': [MOVE, WORK, WORK, WORK, WORK],
    'collector': [MOVE, MOVE, CARRY, CARRY, CARRY],
    'harvester': [MOVE, MOVE, CARRY, WORK],
    'builder': [WORK, WORK, CARRY, CARRY, MOVE],
    'guard': [TOUGH, MOVE, ATTACK, ATTACK, ATTACK],
    'attack': [TOUGH, ATTACK, ATTACK, MOVE, MOVE],
    'rangedattack': [TOUGH, MOVE, RANGED_ATTACK, RANGED_ATTACK, RANGED_ATTACK],
    'upgrader': [MOVE, WORK, WORK, WORK, CARRY],
    'upgraderhelper': [MOVE, MOVE, CARRY, CARRY, CARRY],
}

var desiredRoles = {
    'miner': 1,
    'collector': 5,
    'guard': 2,
    'attack': 0,
    'builder': 4,
    'rangedattack': 0,
    'upgrader': 2,
    'upgraderhelper': 2
}

var existingRoles = {}
for (var role in desiredRoles) {
    existingRoles[role] = 0;
}
for (var name in Game.creeps) {
    var creep = Game.creeps[name];
    existingRoles[creep.memory.role] += 1;
};
for (var role in desiredRoles) {
    if (existingRoles[role] < desiredRoles[role]) {
        Game.spawns.Spawn1.createRole(role);
        break;
    }
}

for(var name in Game.creeps) {
    var creep = Game.creeps[name];

    if(creep.memory.role == 'harvester') {
        harvester(creep);
    } else if (creep.memory.role == 'miner') {
        miner(creep);
    } else if (creep.memory.role == 'collector') {
        collecter(creep);
    } else if (creep.memory.role == 'builder') {
        builder(creep);
    } else if (creep.memory.role == 'guard') {
        guard(creep);
    } else if (creep.memory.role == 'attack') {
        attacker(creep);
    } else if (creep.memory.role == 'rangedattack') {
        rangedattacker(creep);
    } else if (creep.memory.role == 'upgrader') {
        upgrader(creep);
    } else if (creep.memory.role == 'upgraderhelper') {
        upgraderhelper(creep);
    }
}
<|endoftext|>


<commit_before>"use strict";
var Map;
require('tile');

/**
 * Map container and utility. Contains raw map data and utility methods for
 * manipulating the map and extracting useful information.
 */
Map = function () {
    var map, buildings, buildingsList, createBuildingsIndex, units, unitsList,
            getBuildingPositions, createUnitsIndex;

    /**
     * Two-dimensional array of tiles on the map. The first index is vertical
     * axis (y), the second index is horizontal index (x). The name map is
     * used instead of tiles only for legacy reasons and should be changed one
     * day in the future.
     */
    map = [];
    /**
     * Two-dimensional array matching the tiles of the map. Each item is a null
     * or a reference to the building occupying the tile. If a building is
     * uccupying several tiles at once, all occupied tiles hold reference to
     * the building.
     * The structure of the index is: [verical axis (y)][horizontal axis (x)]
     */
    buildings = [];
    /**
     * List of all buildings instances present on the map.
     */
    buildingsList = [];
    /**
     * Tow-dimensional array matching the tiles of the map. Each item is a null
     * or a reference to the unit occupying the tile. The structure of the index
     * is: [vertical axis(y)][horizontal axis (x)]
     */
    units = [];
    /**
     * List of all units instances present on the map.
     */
    unitsList = [];

    /**
     * Updates the building's status on the map (e.g. adding to the map).
     *
     * @param {Building} building The building that has been updated on the map.
     */
    this.updateBuilding = function (building) {
        var positions, position, i;
        buildingsList.push(building);
        positions = getBuildingPositions(building);
        for (i = positions.length; i--;) {
            position = positions[i];
            buildings[position.y][position.x] = building;
        }
    };

    /**
     * Updates the unit's status on the map (e.g. adding to the map).
     *
     * @param {Unit} unit The unit that has been updated on the map.
     */
    this.updateUnit = function (unit) {
        unitsList.push(unit);
        units[unit.y][unit.x] = unit;
    };

    /**
     * Sets raw map data.
     *
     * @param {Array} newMap The two-dimensional array of map tiles
     *        representing the map.
     */
    this.setMap = function (newMap) {
        map = newMap;
        createBuildingsIndex();
    };

    /**
     * Returns the raw map data in a form of a two-dimensional array of map
     * tiles.
     *
     * @return {Array} Raw map data.
     */
    this.getMap = function () {
        return map;
    }

    /**
     * Returns list of all buildings the map contains.
     *
     * @return {Array} List of all buildings on the map.
     */
    this.getBuildings = function () {
        return buildingsList;
    };

    /**
     * Returns list of all units the map contains.
     *
     * @return {Array} List of all units on the map.
     */
    this.getUnits = function () {
        return unitsList;
    };

    /**
     * Returns the tile index referencing to the buildings occuyping the tiles.
     *
     * @return {Array} Two-dimensional array matching the tiles containing
     *         references to buildings occupying them.
     */
    this.getBuildingsIndex = function () {
        return buildings;
    };

    /**
     * Returns the chosen part of the raw map data. Originaly meant for the
     * DOM-based renderer of the main view. Currently has no known usage.
     *
     * @param {Number} x The X offset of the part to return
     * @param {Number} y The Y offset of the part to return
     * @param {Number} width The width of the part of the map data to return
     * @param {Number} height The height of the part of the map data to return
     * @return {Array} The two-dimensional array of map tiles extracted from
     *         the map.
     */
    this.getView = function (x, y, width, height) {
        var view, i;
        view = map.slice(y, y + height);
        width += x;
        for (i = height; i--;) {
            view[i] = view[i].slice(x, width);
        }
        return view;
    };

    /**
     * Generates a completely empty map consisting of only type 0 tiles.
     *
     * @param {Number} width The width of the required map
     * @param {Number} height The height of the required map
     */
    this.emptyMap = function (width, height) {
        var i, j, row;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                row.push(new Tile(0));
            }
            map.push(row);
        }
        createBuildingsIndex();
        createUnitsIndex();
    };

    /**
     * Generates a completely random map - completely random without any mean
     * or semantic or usefulness. Useful for simple testing.
     *
     * @param {Number} width The width of the required random map
     * @param {Number} height The height of the required random map
     */
    this.randomMap = function (width, height) {
        var i, j, row, tile;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                tile = new Tile(Math.floor(Math.random() * 3));
                tile.lightSfx = !Math.floor(Math.random() * 20) ?
                        Math.floor(Math.random() * 5) : 0;
                row.push(tile);
            }
            map.push(row);
        }
        createBuildingsIndex();
        createUnitsIndex();
    };

    /**
     * Exports the information about the map in a form of a JSON-serializable
     * object so that the map could be reconstructed from this data later.
     *
     * @return {Object} object representing the information about the map
     *         required to restore it to it's current state. This object is
     *         JSON-serializable.
     */
    this.exportData = function () {
        var i, j, data, mapRow, dataRow, buildingData, unitsData;
        data = [];
        for (i = map.length; i--;) {
            mapRow = map[i];
            dataRow = [];
            for (j = mapRow.length; j--;) {
                dataRow.unshift(mapRow[j].exportData());
            }
            data.unshift(dataRow);
        }
        buildingData = [];
        for (i = buildingsList.length; i--;) {
            buildingData.push(buildingsList[i].exportData());
        }
        unitsData = [];
        for (i = unitsList.length; i--;) {
            unitsData.push(unitsList[i].exportData());
        }
        return {
            tiles: data,
            buildings: buildingData,
            units: unitsData
        };
    };

    /**
     * Creates map from provided data. The data should be a result of the
     * exportData method.
     *
     * @param {Object} data The data from the exportData method.
     */
    this.importData = function (data) {
        var i, j, mapRow, dataRow;
        map = [];
        for (i = data.tiles.length; i--;) {
            mapRow = [];
            dataRow = data.tiles[i];
            for (j = dataRow.length; j--;) {
                mapRow.unshift(Tile.importData(dataRow[j]));
            }
            map.unshift(mapRow);
        }
        buildingsList = [];
        createBuildingsIndex();
        for (i = data.buildings.length; i--;) {
            this.updateBuilding(Building.importData(data.buildings[i]));
        }
        unitsList = [];
        createUnitsIndex();
        for (i = data.units.length; i--;) {
            this.updateUnit(Unit.importData(data.units[i]));
        }
    };

    getBuildingPositions = function (building) {
        var positions, startX, startY, i, j, x, y;
        positions = [];
        startX = building.x + Math.floor((building.height - 1) / 2);
        startY = building.y;
        for (j = 0; j < building.height; j++) {
            x = startX - Math.ceil((j - startY % 2) / 2);
            y = startY + j;
            for (i = 0; i < building.width; i++) {
                positions.push({
                    x: x,
                    y: y
                });
                if (y % 2) {
                    x++;
                    y++;
                } else {
                    y++;
                }
            }
        }
        return positions;
    };

    createBuildingsIndex = function () {
        var i, j, row;
        buildings = [];
        for (i = map.length; i--;) {
            row = [];
            for (j = map[0].length; j--;) {
                row.push(null);
            }
            buildings.push(row);
        }
    };

    createUnitsIndex = function () {
        var i, j, row;
        units = [];
        for (i = map.length; i--;) {
            row = [];
            for (j = map[0].length; j--;) {
                row.push(null);
            }
            units.push(row);
        }
    };
};
<commit_msg>small refactoring of index creation in the Map class<commit_after>"use strict";
var Map;
require('tile');

/**
 * Map container and utility. Contains raw map data and utility methods for
 * manipulating the map and extracting useful information.
 */
Map = function () {
    var map, buildings, buildingsList, units, unitsList,
            getBuildingPositions, createIndex, createIndexes;

    /**
     * Two-dimensional array of tiles on the map. The first index is vertical
     * axis (y), the second index is horizontal index (x). The name map is
     * used instead of tiles only for legacy reasons and should be changed one
     * day in the future.
     */
    map = [];
    /**
     * Two-dimensional array matching the tiles of the map. Each item is a null
     * or a reference to the building occupying the tile. If a building is
     * uccupying several tiles at once, all occupied tiles hold reference to
     * the building.
     * The structure of the index is: [verical axis (y)][horizontal axis (x)]
     */
    buildings = [];
    /**
     * List of all buildings instances present on the map.
     */
    buildingsList = [];
    /**
     * Tow-dimensional array matching the tiles of the map. Each item is a null
     * or a reference to the unit occupying the tile. The structure of the index
     * is: [vertical axis(y)][horizontal axis (x)]
     */
    units = [];
    /**
     * List of all units instances present on the map.
     */
    unitsList = [];

    /**
     * Updates the building's status on the map (e.g. adding to the map).
     *
     * @param {Building} building The building that has been updated on the map.
     */
    this.updateBuilding = function (building) {
        var positions, position, i;
        buildingsList.push(building);
        positions = getBuildingPositions(building);
        for (i = positions.length; i--;) {
            position = positions[i];
            buildings[position.y][position.x] = building;
        }
    };

    /**
     * Updates the unit's status on the map (e.g. adding to the map).
     *
     * @param {Unit} unit The unit that has been updated on the map.
     */
    this.updateUnit = function (unit) {
        unitsList.push(unit);
        units[unit.y][unit.x] = unit;
    };

    /**
     * Sets raw map data.
     *
     * @param {Array} newMap The two-dimensional array of map tiles
     *        representing the map.
     */
    this.setMap = function (newMap) {
        map = newMap;
        createIndexes();
    };

    /**
     * Returns the raw map data in a form of a two-dimensional array of map
     * tiles.
     *
     * @return {Array} Raw map data.
     */
    this.getMap = function () {
        return map;
    }

    /**
     * Returns list of all buildings the map contains.
     *
     * @return {Array} List of all buildings on the map.
     */
    this.getBuildings = function () {
        return buildingsList;
    };

    /**
     * Returns list of all units the map contains.
     *
     * @return {Array} List of all units on the map.
     */
    this.getUnits = function () {
        return unitsList;
    };

    /**
     * Returns the tile index referencing to the buildings occuyping the tiles.
     *
     * @return {Array} Two-dimensional array matching the tiles containing
     *         references to buildings occupying them.
     */
    this.getBuildingsIndex = function () {
        return buildings;
    };

    /**
     * Returns the chosen part of the raw map data. Originaly meant for the
     * DOM-based renderer of the main view. Currently has no known usage.
     *
     * @param {Number} x The X offset of the part to return
     * @param {Number} y The Y offset of the part to return
     * @param {Number} width The width of the part of the map data to return
     * @param {Number} height The height of the part of the map data to return
     * @return {Array} The two-dimensional array of map tiles extracted from
     *         the map.
     */
    this.getView = function (x, y, width, height) {
        var view, i;
        view = map.slice(y, y + height);
        width += x;
        for (i = height; i--;) {
            view[i] = view[i].slice(x, width);
        }
        return view;
    };

    /**
     * Generates a completely empty map consisting of only type 0 tiles.
     *
     * @param {Number} width The width of the required map
     * @param {Number} height The height of the required map
     */
    this.emptyMap = function (width, height) {
        var i, j, row;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                row.push(new Tile(0));
            }
            map.push(row);
        }
        createIndexes();
    };

    /**
     * Generates a completely random map - completely random without any mean
     * or semantic or usefulness. Useful for simple testing.
     *
     * @param {Number} width The width of the required random map
     * @param {Number} height The height of the required random map
     */
    this.randomMap = function (width, height) {
        var i, j, row, tile;
        map = [];
        for (i = height; i--;) {
            row = [];
            for (j = width; j--;) {
                tile = new Tile(Math.floor(Math.random() * 3));
                tile.lightSfx = !Math.floor(Math.random() * 20) ?
                        Math.floor(Math.random() * 5) : 0;
                row.push(tile);
            }
            map.push(row);
        }
        createIndexes();
    };

    /**
     * Exports the information about the map in a form of a JSON-serializable
     * object so that the map could be reconstructed from this data later.
     *
     * @return {Object} object representing the information about the map
     *         required to restore it to it's current state. This object is
     *         JSON-serializable.
     */
    this.exportData = function () {
        var i, j, data, mapRow, dataRow, buildingData, unitsData;
        data = [];
        for (i = map.length; i--;) {
            mapRow = map[i];
            dataRow = [];
            for (j = mapRow.length; j--;) {
                dataRow.unshift(mapRow[j].exportData());
            }
            data.unshift(dataRow);
        }
        buildingData = [];
        for (i = buildingsList.length; i--;) {
            buildingData.push(buildingsList[i].exportData());
        }
        unitsData = [];
        for (i = unitsList.length; i--;) {
            unitsData.push(unitsList[i].exportData());
        }
        return {
            tiles: data,
            buildings: buildingData,
            units: unitsData
        };
    };

    /**
     * Creates map from provided data. The data should be a result of the
     * exportData method.
     *
     * @param {Object} data The data from the exportData method.
     */
    this.importData = function (data) {
        var i, j, mapRow, dataRow;
        map = [];
        for (i = data.tiles.length; i--;) {
            mapRow = [];
            dataRow = data.tiles[i];
            for (j = dataRow.length; j--;) {
                mapRow.unshift(Tile.importData(dataRow[j]));
            }
            map.unshift(mapRow);
        }
        buildingsList = [];
        createIndexes();
        for (i = data.buildings.length; i--;) {
            this.updateBuilding(Building.importData(data.buildings[i]));
        }
        unitsList = [];
        for (i = data.units.length; i--;) {
            this.updateUnit(Unit.importData(data.units[i]));
        }
    };

    getBuildingPositions = function (building) {
        var positions, startX, startY, i, j, x, y;
        positions = [];
        startX = building.x + Math.floor((building.height - 1) / 2);
        startY = building.y;
        for (j = 0; j < building.height; j++) {
            x = startX - Math.ceil((j - startY % 2) / 2);
            y = startY + j;
            for (i = 0; i < building.width; i++) {
                positions.push({
                    x: x,
                    y: y
                });
                if (y % 2) {
                    x++;
                    y++;
                } else {
                    y++;
                }
            }
        }
        return positions;
    };

    createIndex = function () {
        var i, j, row, index;
        index = [];
        for (i = map.length; i--;) {
            row = [];
            for (j = map[0].length; j--;) {
                row.push(null);
            }
            index.push(row);
        }
        return index;
    };

    createIndexes = function () {
        buildings = createIndex();
        units = createIndex();
    };
};
<|endoftext|>