Problems minifying javascript file (asp.net application) - javascript
I have the following javascript code:
class UrlParameters {
constructor() {
this.initVariablesWithDefaultValues();
var serverUrlData = HelperJSViewBag.getValue("UrlData", true);
var urlVariables = serverUrlData ? serverUrlData : HLinks.getAllUrlVariables();
var sessionID = this.convertToString(urlVariables["sessionID"]);
var idSession = this.convertToString(urlVariables["idSession"]);
var sessionid = this.convertToString(urlVariables["sessionid"]);
if (idSession.length > 0)
this.sessionID = idSession;
else if (sessionid.length > 0)
this.sessionID = sessionid;
else
this.sessionID = sessionID;
var countryISO = this.convertToString(urlVariables["countryISO"]);
var country = this.convertToString(urlVariables["country"]);
this.countryISO = countryISO.length > 0 ? countryISO : country;
var productRef = this.convertToString(urlVariables["productRef"]);
var pRef = this.convertToString(urlVariables["ref"]);
var refproduct = this.convertToString(urlVariables["refproduct"]);
var productReference = this.convertToString(urlVariables["productReference"]);
if (productRef.length > 0)
this.productReference = productRef;
else if (pRef.length > 0)
this.productReference = pRef;
else if (refproduct.length > 0)
this.productReference = refproduct;
else
this.productReference = productReference;
var PartnerCode = this.convertToString(urlVariables["PartnerCode"]);
var partnerCode = this.convertToString(urlVariables["partnerCode"]);
this.partnerCode = PartnerCode.length > 0 ? PartnerCode : partnerCode;
var themeReference = this.convertToString(urlVariables["themeReference"]);
var theme = this.convertToString(urlVariables["theme"]);
this.themeReference = themeReference.length > 0 ? themeReference : theme;
this.projectName = this.convertToString(urlVariables["projectName"]);
var coverReference = this.convertToString(urlVariables["coverReference"]);
var refCover = this.convertToString(urlVariables["refCover"]);
this.coverReference = coverReference.length > 0 ? coverReference : refCover;
this.themeFill = this.convertToInt(urlVariables["themeFill"], 0); // 0 -> directly without autofill ; 1 -> not directly without autofill ; 2 -> not directly quick autofill ; 3 -> not directly smart autofill
this.smartOpt = this.convertToInt(urlVariables["smartOpt"], 2); //1->faces,colors,dimentions; 2-> colors and dimentions; 3-> dimentions
var open = this.convertToString(urlVariables["open"]);
var projectCode = this.convertToString(urlVariables["projectCode"]);
this.projectCode = open.length > 0 ? open : projectCode;
this.productCode = this.convertToString(urlVariables["productCode"]);
this.projectID = this.convertToString(urlVariables["projectID"]);
var categoryID = this.convertToInt(urlVariables["categoryID"]);
var cat = this.convertToInt(urlVariables["cat"]);
this.categoryID = categoryID > 0 ? categoryID : cat;
var subCategoryReference = this.convertToString(urlVariables["subCategoryReference"]);
var subCat = this.convertToString(urlVariables["subCat"]);
this.subCategoryReference = subCategoryReference.length > 0 ? subCategoryReference : subCat;
var typeFinishID = this.convertToInt(urlVariables["typeFinishID"]);
var refProdutFinish = this.convertToInt(urlVariables["refProdutFinish"]);
var productTypeFinishID = this.convertToInt(urlVariables["productTypeFinishID"]);
if (typeFinishID > 0)
this.productTypeFinishID = typeFinishID;
else if (refProdutFinish > 0)
this.productTypeFinishID = refProdutFinish;
else
this.productTypeFinishID = productTypeFinishID;
var coverTypeFinishID = this.convertToInt(urlVariables["coverTypeFinishID"]);
var coverFinishID = this.convertToInt(urlVariables["coverFinishID"]);
var refCoverFinish = this.convertToInt(urlVariables["refCoverFinish"]);
if (coverTypeFinishID > 0) this.coverTypeFinishID = coverTypeFinishID;
else if (coverFinishID > 0) this.coverTypeFinishID = coverFinishID;
else this.coverTypeFinishID = refCoverFinish;
var numPages = this.convertToInt(urlVariables["numPages"]);
var refPages = this.convertToInt(urlVariables["refPages"]);
var numberOfPages = this.convertToInt(urlVariables["numberOfPages"]);
if (numPages > 0)
this.numberOfPages = numPages;
else if (refPages > 0)
this.numberOfPages = refPages;
else
this.numberOfPages = numberOfPages;
this.coverType = this.convertToString(urlVariables["coverType"]);
var textureID = this.convertToString(urlVariables["textureID"]);
var textureReference = this.convertToString(urlVariables["textureReference"]);
if (textureID.length > 0) this.textureReference = textureID;
else this.textureReference = textureReference;
var textureColorID = this.convertToString(urlVariables["textureColorID"]);
var textureColorReference = this.convertToString(urlVariables["textureColorReference"]);
var refColor = this.convertToString(urlVariables["refColor"]);
if (textureColorID.length > 0) this.textureColorReference = textureColorID;
else if (refColor.length > 0) this.textureColorReference = refColor;
else this.textureColorReference = textureColorReference;
var windowID = this.convertToString(urlVariables["windowID"]);
var refWindow = this.convertToString(urlVariables["refWindow"]);
var windowReference = this.convertToString(urlVariables["windowReference"]);
if (windowID.length > 0)
this.windowReference = windowID;
else if (refWindow.length > 0)
this.windowReference = refWindow;
else
this.windowReference = windowReference;
this.savedProject = this.convertToBoolean(urlVariables["savedProject"]);
this.startMonth = this.convertToInt(urlVariables["startMonth"]);
this.startYear = this.convertToInt(urlVariables["startYear"]);
this.wantHolidays = this.convertToBoolean(urlVariables["wantHolidays"]);
var frameID = this.convertToString(urlVariables["frameID"]);
var frameReference = this.convertToString(urlVariables["frameReference"]);
var canvasRef = this.convertToString(urlVariables["canvasRef"]);
if (frameID.length > 0)
this.frameReference = frameID;
else if (canvasRef.length > 0)
this.frameReference = canvasRef;
else
this.frameReference = frameReference;
this.frameReference = frameID.length > 0 ? frameID : frameReference;
var colorFrameID = this.convertToString(urlVariables["colorFrameID"]);
var frameColorReference = this.convertToString(urlVariables["frameColorReference"]);
var canvasColor = this.convertToString(urlVariables["canvasColor"]);
if (colorFrameID.length > 0)
this.frameColorReference = colorFrameID;
else if (canvasColor.length > 0)
this.frameColorReference = canvasColor;
else
this.frameColorReference = frameColorReference;
this.albumXML = this.convertToString(urlVariables["albumXML"]);
this.pagesXML = this.convertToString(urlVariables["pagesXML"]);
var languageISO = this.convertToString(urlVariables["languageISO"]);
var lang = this.convertToString(urlVariables["lang"]);
if (languageISO.length > 0)
this.languageISO = languageISO;
else if (lang.length > 0)
this.languageISO = lang;
this.openThemeAccordion = this.convertToBoolean(urlVariables["openThemeAccordion"]);
var galleryID = this.convertToString(urlVariables["galleryID"]);
var galleryReference = this.convertToString(urlVariables["galleryReference"]);
this.galleryReference = galleryID.length > 0 ? galleryID : galleryReference;
var login_page = this.convertToString(urlVariables["login_page"]);
var Login_Page = this.convertToString(urlVariables["Login_Page"]);
this.Login_Page = this.convertToBoolean(login_page.length > 0 ? login_page : Login_Page);
this.forceMobile = this.convertToBoolean(urlVariables["forceMobile"]);
this.clientApplication = this.convertToString(urlVariables["clientApplication"]);
this.goToPreview = this.convertToInt(urlVariables["goToPreview"]);
this.orderID = this.convertToInt(urlVariables["orderID"], -1);
this.CID = this.convertToString(urlVariables["CID"]);
this.unblock = this.convertToBoolean(urlVariables["unblock"]);
var idPartner = this.convertToInt(urlVariables["idPartner"]);
var partnerID = this.convertToInt(urlVariables["partnerID"]);
var idEmp = this.convertToInt(urlVariables["idEmp"]);
this.forceException = this.convertToBoolean(urlVariables["forceException"]);
if (idPartner > 0)
this.partnerID = idPartner;
else if (partnerID > 0)
this.partnerID = partnerID;
else if (idEmp > 0)
this.partnerID = idEmp;
this.goDirectlyToEditor = this.convertToBoolean(urlVariables["goDirectlyToEditor"]);
}
static getInstance() {
if (typeof UrlParameters.urlParameters === "undefined")
UrlParameters.urlParameters = new UrlParameters();
return UrlParameters.urlParameters;
}
getData() {
return {
sessionID : this.sessionID,
countryISO: this.countryISO,
productReference: this.productReference,
partnerCode: this.partnerCode,
themeReference: this.themeReference,
projectName: this.projectName,
coverReference: this.coverReference,
themeFill: this.themeFill,
smartOpt: this.smartOpt,
projectCode: this.projectCode,
productCode: this.productCode,
projectID: this.projectID,
categoryID: this.categoryID,
subCategoryReference: this.subCategoryReference,
productTypeFinishID: this.productTypeFinishID,
coverTypeFinishID: this.coverTypeFinishID,
numberOfPages: this.numberOfPages,
coverType: this.coverType,
textureReference: this.textureReference,
textureColorReference: this.textureColorReference,
windowReference: this.windowReference,
savedProject: this.savedProject,
startMonth: this.startMonth,
startYear: this.startYear,
wantHolidays: this.wantHolidays,
frameReference: this.frameReference,
frameColorReference: this.frameColorReference,
albumXML: this.albumXML,
pagesXML: this.pagesXML,
languageISO: this.languageISO,
openThemeAccordion: this.openThemeAccordion,
galleryReference: this.galleryReference,
Login_Page: this.Login_Page,
forceMobile: this.forceMobile,
clientApplication: this.clientApplication,
goToPreview: this.goToPreview,
orderID: this.orderID,
CID: this.CID,
unblock: this.unblock,
partnerID: this.partnerID,
forceException: this.forceException,
goDirectlyToEditor: this.goDirectlyToEditor
}
}
getVariableOnce(name) {
if (!this.variableOnce) this.variableOnce = this.getData();
var value = this.variableOnce[name];
delete this.variableOnce[name];
return value;
}
initVariablesWithDefaultValues() {
this.projectName = "";
this.productReference = "";
this.coverReference = "";
this.textureReference = "";
this.colorReference = "";
this.windowReference = "";
this.numberOfPages = 0;
this.productTypeFinishID = 0;
this.coverTypeFinishID = 0;
this.canvasColor = "";
this.projectCode = "";
this.sessionID = "";
this.countryISO = "";
this.themeReference = "";
this.themeFill = 0;
this.smartOpt = 2;
this.projectID = "";
this.productCode = "";
this.categoryID = -1;
this.savedProject = false;
this.startMonth = 0;
this.startYear = 0;
this.wantHolidays = false;
this.albumXML = "";
this.pagesXML = "";
this.languageISO = "";
this.Login_Page = false;
this.frameReference = "";
this.frameColorReference = "";
this.partnerCode = "";
this.partnerID = "";
this.coverType = "";
this.textureColorReference = ""
this.subCategoryReference = "";
this.openThemeAccordion = false;
this.galleryReference = "";
this.clientApplication = "";
this.forceMobile = false;
this.idUpload = 0;
this.orderID = -1;
this.idControl = 0;
this.goToPreview = 0;
this.unblock = false;
this.CID = "";
this.forceException = false;
this.goDirectlyToEditor = false;
}
convertToString(value, defaultValue) {
if (typeof defaultValue !== "var") defaultValue = "";
if (value)
return value;
else
return defaultValue;
}
convertToInt(value, defaultValue) {
if (typeof defaultValue !== "number") defaultValue = 0;
if (value)
return parseInt(value);
else
return defaultValue;
}
convertToBoolean(value, defaultValue) {
if (typeof defaultValue !== "boolean") defaultValue = false;
if (value)
return value;
else
return defaultValue;
}
}
When I run my application with the BundleTable.EnableOptimizations = true the asp.net does not minify this files. Istead, return a new file with the following errors:
/* Minification failed. Returning unminified contents.
(1,1-6): run-time error JS1195: Expected expression: class
(3,19-20): run-time error JS1004: Expected ';': {
(201,12-23): run-time error JS1004: Expected ';': getInstance
(201,26-27): run-time error JS1004: Expected ';': {
(208,15-16): run-time error JS1004: Expected ';': {
(256,27-28): run-time error JS1004: Expected ';': {
(265,38-39): run-time error JS1004: Expected ';': {
(314,42-43): run-time error JS1004: Expected ';': {
(323,39-40): run-time error JS1004: Expected ';': {
(332,43-44): run-time error JS1004: Expected ';': {
(341,1-2): run-time error JS1002: Syntax error: }
(336,13-25): run-time error JS1018: 'return' statement outside of function: return value
(338,13-32): run-time error JS1018: 'return' statement outside of function: return defaultValue
(327,13-35): run-time error JS1018: 'return' statement outside of function: return parseInt(value)
(329,13-32): run-time error JS1018: 'return' statement outside of function: return defaultValue
(318,13-25): run-time error JS1018: 'return' statement outside of function: return value
(320,13-32): run-time error JS1018: 'return' statement outside of function: return defaultValue
(262,9-21): run-time error JS1018: 'return' statement outside of function: return value
(209,9,253,10): run-time error JS1018: 'return' statement outside of function: return {
sessionID : this.sessionID,
countryISO: this.countryISO,
productReference: this.productReference,
partnerCode: this.partnerCode,
themeReference: this.themeReference,
projectName: this.projectName,
coverReference: this.coverReference,
themeFill: this.themeFill,
smartOpt: this.smartOpt,
projectCode: this.projectCode,
productCode: this.productCode,
projectID: this.projectID,
categoryID: this.categoryID,
subCategoryReference: this.subCategoryReference,
productTypeFinishID: this.productTypeFinishID,
coverTypeFinishID: this.coverTypeFinishID,
numberOfPages: this.numberOfPages,
coverType: this.coverType,
textureReference: this.textureReference,
textureColorReference: this.textureColorReference,
windowReference: this.windowReference,
savedProject: this.savedProject,
startMonth: this.startMonth,
startYear: this.startYear,
wantHolidays: this.wantHolidays,
frameReference: this.frameReference,
frameColorReference: this.frameColorReference,
albumXML: this.albumXML,
pagesXML: this.pagesXML,
languageISO: this.languageISO,
openThemeAccordion: this.openThemeAccordion,
galleryReference: this.galleryReference,
Login_Page: this.Login_Page,
forceMobile: this.forceMobile,
clientApplication: this.clientApplication,
goToPreview: this.goToPreview,
orderID: this.orderID,
CID: this.CID,
unblock: this.unblock,
partnerID: this.partnerID,
forceException: this.forceException,
goDirectlyToEditor: this.goDirectlyToEditor
}
(205,9-43): run-time error JS1018: 'return' statement outside of function: return UrlParameters.urlParameters
*/
I search a lot on the internet but I didn't find any solution for this case. Maybe, it's because I'm using the ES6 standard?
I'm using the 1.1.0.0 version of System.Web.Optimization.
System.Web.Optimization doesn't support ES6 syntax
I suggest you to integrate gulp, grunt or webpack into your build process in order to minify your scripts
Related
Linkedin Autoconnect With User role
I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this. var userRole = [ "CEO", "CIO" ]; var inviter = {} || inviter; inviter.userList = []; inviter.className = 'button-secondary-small'; inviter.refresh = function () { window.scrollTo(0, document.body.scrollHeight); window.scrollTo(document.body.scrollHeight, 0); window.scrollTo(0, document.body.scrollHeight); }; inviter.initiate = function() { inviter.refresh(); var connectBtns = $(".button-secondary-small:visible"); // if (connectBtns == null) {var connectBtns = inviter.initiate();} return connectBtns; }; inviter.invite = function () { var connectBtns = inviter.initiate(); var buttonLength = connectBtns.length; for (var i = 0; i < buttonLength; i++) { if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);} //if there is a connect button and there is at least one that has not been pushed, repeat if (i == buttonLength - 1) { console.log("done: " + i); inviter.refresh(); } } }; inviter.handleRepeat = function(button) { var nameValue = button.children[1].textContent var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); function hasRole(role){ for(var i = 0; i < role.length; i++) { // cannot read children of undefined var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent; var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true; console.log('Has role: ' + role[i] + ' -> ' + hasRole); if (hasRole) { return hasRole; } } return false; } if(inviter.arrayContains(name)) { console.log("canceled"); var cancel = button.parentNode.parentNode.children[0]; cancel.click(); } else if (hasRole(userRole) == false) { console.log("cancel"); var cancel = button.parentNode.parentNode.children[0]; cancel.click(); } else if (button.textContent.indexOf("Connect")<0){ console.log("skipped"); inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them var cancel = button.parentNode.parentNode.children[0]; cancel.click(); } else { console.log("added"); inviter.userList.push(name); button.click(); } }; inviter.arrayContains = function(item) { return (inviter.userList.indexOf(item) > -1); }; inviter.usersJson = {}; inviter.loadResult = function() { var retrievedObject = localStorage.getItem('inviterList'); var temp = JSON.stringify(retrievedObject); inviter.userList = JSON.parse(temp); }; inviter.saveResult = function() { inviter.usersJson = JSON.stringify(inviter.userList); localStorage.setItem('inviterList', inviter.usersJson); }; setInterval(function () { inviter.invite(); }, 5000); ` When I try executing this, I get the following error: VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined at hasRole (<anonymous>:49:71) at Object.inviter.handleRepeat (<anonymous>:66:11) at Object.inviter.invite (<anonymous>:30:69) at <anonymous>:108:35 Any ideas as to how to fix it?
Javascript network with labels and weighted edges
I have been searching for quite a while now and I'm not able to find a simple JS library to make a network in which: The nodes have labels The edge thickness is proportional to the weight Able to spread the nodes so that it doesn't get messy. I found a script on bl.ocks.org which fits my needs, but when I use a lot of nodes it's getting quite messy: I use this as input: target,source,weight woooooow,notgood,70.0 woooooow,gainzz,32.004950495049506 woooooow,test,33.86138613861386 woooooow,peanutss,20.866336633663366 nicecode,woooooow,22.103960396039604 woooooow,oreo,20.742574257425744 bread,woooooow,37.945544554455445 jam,nutella,20.123762376237625 bread,nutsarelol,20.866336633663366 etc Question Any ideas which code/library I can use to create a graph like the graph above but with more spreading of the nodes? JS code /* Author: Corneliu S. (github.com/upphiminn) This is a javascript implementation of the Louvain community detection algorithm (http://arxiv.org/abs/0803.0476) Based on https://bitbucket.org/taynaud/python-louvain/overview */ (function(){ jLouvain = function(){ //Constants var __PASS_MAX = -1 var __MIN = 0.0000001 //Local vars var original_graph_nodes; var original_graph_edges; var original_graph = {}; var partition_init; //Helpers function make_set(array){ var set = {}; array.forEach(function(d,i){ set[d] = true; }); return Object.keys(set); }; function obj_values(obj){ var vals = []; for( var key in obj ) { if ( obj.hasOwnProperty(key) ) { vals.push(obj[key]); } } return vals; }; function get_degree_for_node(graph, node){ var neighbours = graph._assoc_mat[node] ? Object.keys(graph._assoc_mat[node]) : []; var weight = 0; neighbours.forEach(function(neighbour,i){ var value = graph._assoc_mat[node][neighbour] || 1; if(node == neighbour) value *= 2; weight += value; }); return weight; }; function get_neighbours_of_node(graph, node){ if(typeof graph._assoc_mat[node] == 'undefined') return []; var neighbours = Object.keys(graph._assoc_mat[node]); return neighbours; } function get_edge_weight(graph, node1, node2){ return graph._assoc_mat[node1] ? graph._assoc_mat[node1][node2] : undefined; } function get_graph_size(graph){ var size = 0; graph.edges.forEach(function(edge){ size += edge.weight; }); return size; } function add_edge_to_graph(graph, edge){ update_assoc_mat(graph, edge); var edge_index = graph.edges.map(function(d){ return d.source+'_'+d.target; }).indexOf(edge.source+'_'+edge.target); if(edge_index != -1) graph.edges[edge_index].weight = edge.weight; else graph.edges.push(edge); } function make_assoc_mat(edge_list){ var mat = {}; edge_list.forEach(function(edge, i){ mat[edge.source] = mat[edge.source] || {}; mat[edge.source][edge.target] = edge.weight; mat[edge.target] = mat[edge.target] || {}; mat[edge.target][edge.source] = edge.weight; }); return mat; } function update_assoc_mat(graph, edge){ graph._assoc_mat[edge.source] = graph._assoc_mat[edge.source] || {}; graph._assoc_mat[edge.source][edge.target] = edge.weight; graph._assoc_mat[edge.target] = graph._assoc_mat[edge.target] || {}; graph._assoc_mat[edge.target][edge.source] = edge.weight; } function clone(obj){ if(obj == null || typeof(obj) != 'object') return obj; var temp = obj.constructor(); for(var key in obj) temp[key] = clone(obj[key]); return temp; } //Core-Algorithm Related function init_status(graph, status, part){ status['nodes_to_com'] = {}; status['total_weight'] = 0; status['internals'] = {}; status['degrees'] = {}; status['gdegrees'] = {}; status['loops'] = {}; status['total_weight'] = get_graph_size(graph); if(typeof part == 'undefined'){ graph.nodes.forEach(function(node,i){ status.nodes_to_com[node] = i; var deg = get_degree_for_node(graph, node); if (deg < 0) throw 'Bad graph type, use positive weights!'; status.degrees[i] = deg; status.gdegrees[node] = deg; status.loops[node] = get_edge_weight(graph, node, node) || 0; status.internals[i] = status.loops[node]; }); }else{ graph.nodes.forEach(function(node,i){ var com = part[node]; status.nodes_to_com[node] = com; var deg = get_degree_for_node(graph, node); status.degrees[com] = (status.degrees[com] || 0) + deg; status.gdegrees[node] = deg; var inc = 0.0; var neighbours = get_neighbours_of_node(graph, node); neighbours.forEach(function(neighbour, i){ var weight = graph._assoc_mat[node][neighbour]; if (weight <= 0){ throw "Bad graph type, use positive weights"; } if(part[neighbour] == com){ if (neighbour == node){ inc += weight; }else{ inc += weight/2.0; } } }); status.internals[com] = (status.internals[com] || 0) + inc; }); } } function __modularity(status){ var links = status.total_weight; var result = 0.0; var communities = make_set(obj_values(status.nodes_to_com)); communities.forEach(function(com,i){ var in_degree = status.internals[com] || 0 ; var degree = status.degrees[com] || 0 ; if(links > 0){ result = result + in_degree / links - Math.pow((degree / (2.0*links)), 2); } }); return result; } function __neighcom(node, graph, status){ // compute the communities in the neighb. of the node, with the graph given by // node_to_com var weights = {}; var neighboorhood = get_neighbours_of_node(graph, node);//make iterable; neighboorhood.forEach(function(neighbour, i){ if(neighbour != node){ var weight = graph._assoc_mat[node][neighbour] || 1; var neighbourcom = status.nodes_to_com[neighbour]; weights[neighbourcom] = (weights[neighbourcom] || 0) + weight; } }); return weights; } function __insert(node, com, weight, status){ //insert node into com and modify status status.nodes_to_com[node] = +com; status.degrees[com] = (status.degrees[com] || 0) + (status.gdegrees[node]||0); status.internals[com] = (status.internals[com] || 0) + weight + (status.loops[node]||0); } function __remove(node, com, weight, status){ //remove node from com and modify status status.degrees[com] = ((status.degrees[com] || 0) - (status.gdegrees[node] || 0)); status.internals[com] = ((status.internals[com] || 0) - weight -(status.loops[node] ||0)); status.nodes_to_com[node] = -1; } function __renumber(dict){ var count = 0; var ret = clone(dict); //deep copy :) var new_values = {}; var dict_keys = Object.keys(dict); dict_keys.forEach(function(key){ var value = dict[key]; var new_value = typeof new_values[value] =='undefined' ? -1 : new_values[value]; if(new_value == -1){ new_values[value] = count; new_value = count; count = count + 1; } ret[key] = new_value; }); return ret; } function __one_level(graph, status){ //Compute one level of the Communities Dendogram. var modif = true, nb_pass_done = 0, cur_mod = __modularity(status), new_mod = cur_mod; while (modif && nb_pass_done != __PASS_MAX){ cur_mod = new_mod; modif = false; nb_pass_done += 1 graph.nodes.forEach(function(node,i){ var com_node = status.nodes_to_com[node]; var degc_totw = (status.gdegrees[node] || 0) / (status.total_weight * 2.0); var neigh_communities = __neighcom(node, graph, status); __remove(node, com_node, (neigh_communities[com_node] || 0.0), status); var best_com = com_node; var best_increase = 0; var neigh_communities_entries = Object.keys(neigh_communities);//make iterable; neigh_communities_entries.forEach(function(com,i){ var incr = neigh_communities[com] - (status.degrees[com] || 0.0) * degc_totw; if (incr > best_increase){ best_increase = incr; best_com = com; } }); __insert(node, best_com, neigh_communities[best_com] || 0, status); if(best_com != com_node) modif = true; }); new_mod = __modularity(status); if(new_mod - cur_mod < __MIN) break; } } function induced_graph(partition, graph){ var ret = {nodes:[], edges:[], _assoc_mat: {}}; var w_prec, weight; //add nodes from partition values var partition_values = obj_values(partition); ret.nodes = ret.nodes.concat(make_set(partition_values)); //make set graph.edges.forEach(function(edge,i){ weight = edge.weight || 1; var com1 = partition[edge.source]; var com2 = partition[edge.target]; w_prec = (get_edge_weight(ret, com1, com2) || 0); var new_weight = (w_prec + weight); add_edge_to_graph(ret, {'source': com1, 'target': com2, 'weight': new_weight}); }); return ret; } function partition_at_level(dendogram, level){ var partition = clone(dendogram[0]); for(var i = 1; i < level + 1; i++ ) Object.keys(partition).forEach(function(key,j){ var node = key; var com = partition[key]; partition[node] = dendogram[i][com]; }); return partition; } function generate_dendogram(graph, part_init){ if(graph.edges.length == 0){ var part = {}; graph.nodes.forEach(function(node,i){ part[node] = node; }); return part; } var status = {}; init_status(original_graph, status, part_init); var mod = __modularity(status); var status_list = []; __one_level(original_graph, status); var new_mod = __modularity(status); var partition = __renumber(status.nodes_to_com); status_list.push(partition); mod = new_mod; var current_graph = induced_graph(partition, original_graph); init_status(current_graph, status); while (true){ __one_level(current_graph, status); new_mod = __modularity(status); if(new_mod - mod < __MIN) break; partition = __renumber(status.nodes_to_com); status_list.push(partition); mod = new_mod; current_graph = induced_graph(partition, current_graph); init_status(current_graph, status); } return status_list; } var core = function(){ var status = {}; var dendogram = generate_dendogram(original_graph, partition_init); return partition_at_level(dendogram, dendogram.length - 1); }; core.nodes = function(nds){ if(arguments.length > 0){ original_graph_nodes = nds; } return core; }; core.edges = function(edgs){ if(typeof original_graph_nodes == 'undefined') throw 'Please provide the graph nodes first!'; if(arguments.length > 0){ original_graph_edges = edgs; var assoc_mat = make_assoc_mat(edgs); original_graph = { 'nodes': original_graph_nodes, 'edges': original_graph_edges, '_assoc_mat': assoc_mat }; } return core; }; core.partition_init = function(prttn){ if(arguments.length > 0){ partition_init = prttn; } return core; }; return core; } })();
Get the document object of an IFrame in PhantomJS?
I am trying to get the document of an Iframe after setting the iframe.src. I am calling this in phantom-node. The function returns an error when the iframe is empty: fetchGuestbookEntries: function () { var getGuestbookForPage = function (doc) { var result = []; var rows = doc.querySelectorAll('td[class="guestbook"]'); var date = ""; var entry = ""; for (var i = 0; i < rows.length; i++) { date = i % 2 == 0 ? rows[i].innerText : date; entry = i % 2 != 0 ? rows[i].innerText : entry; if (date && entry) { var info = date.split('\n').map(function (elem) { return elem.replace('\n', '').trim(); }); result.push( { info: { guestname: info[0], date: new Date(info[3]).toISOString().slice(0, 10), time: info[4].replace(/Uhr|h/gi, '').trim() }, entry: entry.trim() } ); date = ""; entry = ""; } } return result; }; var getPaginationSize = function () { return document.querySelector('td[class="guestbook_navijump"]') ? document.querySelector('td[class="guestbook_navijump"]').querySelectorAll('a').length : 0; }; var getIframeDoc = function(ifrm) { return ifrm.document || ifrm.contentDocument || ifrm.contentWindow.document; }; var pagination = getPaginationSize(); var entries = []; for (var i = 0; i <= pagination; i++) { var paginationPageUrl = window.location.href + "?jump=" + i; var iframe = document.createElement('iframe'); iframe.src = paginationPageUrl; var doc = getIframeDoc(iframe); entries.push(getGuestbookForPage(doc)); } return entries; } Is there a way to get the document? The error: Uncaught TypeError: Cannot read property 'document' of null at <anonymous>:2:21 at Object.InjectedScript._evaluateOn (<anonymous>:895:140) at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34) at Object.InjectedScript.evaluate (<anonymous>:694:21) I normally open the Page in PhantomJS.
You should be able to get it with this document.getElementById('myframe').contentWindow.document
getting html input value inside javascript class
i am new to javascript and im making a BMI calculator. im making a class in javascript to produce the calculations. currently users could input their height (in feet and inches) and weight. when i run a method within my class. it keeps saying this.feet = null instead of grabbing the value from the input. my javascript code is below. result() is in my html for the submit button. function calculator(feet,inches,weight) { this.feet = feet.value; this.inches = inches.value; this.weight = weight.value; this.validateInput = function() { var errors = []; if(isNaN(this.feet) || this.feet < 0) { errors.push("Feet"); } else { return this.feet }; if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) { errors.push("Inches") } else { return this.inches; }; if(isNaN(this.weight) || this.weight < 0) { errors.push("Weight"); } else { return this.weight } }; this.inchesConverter = function() { this.feet = parseFloat(feet); this.inches = parseFloat(inches); return parseInt(this.feet*12+this.inches); }; this.bmi = function() { var height = this.inchesConverter(); var validater = this.validateInput(); for(r = 0; r < errors.length; r++){ if(errors.length > 0) { return errors[r] + " must be a valid positive number."; } else { parseFloat((validateWeight * 703) / (Math.pow(height, 2))).toFixed(1); } } }; }; var getWeight = document.getElementById('txtWeight'); var getFeet = document.getElementById('txtHeightFeet'); var getInches = document.getElementById('txtHeightInches'); var test = new calculator(getFeet, getInches, getWeight); function result() { document.getElementById("lblBMI").innerHTML(test.bmi()); }
Instead of assigning feet.value to this.feet try assigning feet.getAttribute('value') If you console.log(feet) does it show the proper DOM element?
There is no need to declare the variables with "this." function calculator(paraFeet,paraInches,paraWeight) { var feet = paraFeet.value; var inches = paraInches.value; var weight = paraWeight.value; ... you can now remove "this." from every of these variables inside your function
Every browser has JavaScript console on which you can debug your code. I have some fun to fix it here or there but also you should try it yourself. Anyway here it is: function calculator(weight, feet, inches) { this.weight = weight; this.feet = feet; this.inches = inches; this.validateInput = function() { var errors = []; if (!this.validNumber(this.weight, 1000)) { errors.push("Invalid weight."); } if (!this.validNumber(this.feet, 10)) { errors.push("Invalid hight in feet."); } if (!this.validNumber(this.inches, 11)) { errors.push("Invalid hight in inches.") } return errors; }; this.validNumber = function(num, max) { if (num.length > 0 && !isNaN(num)) { var number = parseInt(num); return number > 0 && number < max + 1; } return false; } this.displayErrors = function(errors) { var html = ""; for (error of errors) html += error + "<br/>"; return html; }; this.inchesConverter = function() { var feet = parseInt(this.feet); var inches = parseInt(this.inches); return feet * 12 + inches; }; this.bmi = function() { var errors = this.validateInput(); if (errors.length > 0) { return this.displayErrors(errors); } var height = this.inchesConverter(); return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1); }; }; function result() { var getWeight = document.getElementById('txtWeight').value; var getFeet = document.getElementById('txtHeightFeet').value; var getInches = document.getElementById('txtHeightInches').value; var test = new calculator(getWeight, getFeet, getInches); document.getElementById("lblBMI").innerHTML = test.bmi(); return false; } <span> <label>Weight</label> <input id="txtWeight"> </span> <span> <label>HeightFeet</label> <input id="txtHeightFeet"> </span> <span> <label>HeightInches</label> <input id="txtHeightInches"> </span> <button id='run' onClick="return result();">Calculate</button> <div id="lblBMI"></div>
Figured out what my issue was. The problem arose from my for loop. Working code is posted below! function calculator(feet,inches,weight) { this.feet = feet.value; this.inches = inches.value; this.weight = weight.value; this.validateInput = function() { var errors = []; if(isNaN(this.feet) || this.feet < 0 || this.feet == "") { errors.push("feet"); }; if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) { errors.push("inches") }; if(isNaN(this.weight) || this.weight < 0 || this.weight == "") { errors.push("weight"); }; return errors; console.log(errors); }; this.inchesConverter = function() { var parseFeet = parseFloat(this.feet); var parseInches = parseFloat(this.inches); return parseInt(parseFeet*12+parseInches); }; this.bmi = function() { var height = this.inchesConverter(); var errors = this.validateInput(); if(errors.length > 0) { for(r = 0; r < errors.length; r++){ return "Please enter a correct number for " + errors[r]; }; } else { return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1); }; }; }; function result(){ var getWeight = document.getElementById('txtWeight'); var getFeet = document.getElementById('txtHeightFeet'); var getInches = document.getElementById('txtHeightInches'); var test = new calculator(getFeet, getInches, getWeight); document.getElementById("lblBMI").innerHTML = test.bmi(); };
Dynamic checkbox name to assign its value
what is wrong with this code I get an undefined error. my checkbox is not an array on front end it uses different names and I want user to select only one checkbox: function select_item(index){ var choice_options = []; choice_options['S'] = 'item_cb_S'; choice_options['T'] = 'item_cb_T'; choice_options['Z'] = 'item_cb_Z'; choice_options['D'] = 'item_cb_D'; choice_options['N'] = 'item_cb_N'; for (i in choice_options) { var vl = choice_options[i]; if(vl.substring(8) == index) { document.wizardform.choice_options[index].checked = true; //alert("true"); } else { document.wizardform.vl.checked = false; } } return true; }
It's not so pretty but you could use eval...... function select_item(index){ var choice_options = []; choice_options['S'] = 'item_cb_S'; choice_options['T'] = 'item_cb_T'; choice_options['Z'] = 'item_cb_Z'; choice_options['D'] = 'item_cb_D'; choice_options['N'] = 'item_cb_N'; for (i in choice_options) { var vl = choice_options[i]; if(vl.substring(8) == index) { eval("document.wizardform." + choice_options[index] + ".checked = true;"); //alert("true"); } else { document.wizardform.vl.checked = false; } } return true; }