Best JavaScript code snippet using wpt
functioninfo.js
Source:functioninfo.js
1//show info about a function2 var showinfofunction = function (event, pos, item) {3 4 if (item && item.series["label"] == "functions") { 5 getInfo(item.dataIndex);6 } 7 };8 9 //load doxygen tag file if available10 var xmlDoc;11 function loadDoxyIndex(){12 try{13 if (window.XMLHttpRequest)14 {// code for IE7+, Firefox, Chrome, Opera, Safari15 xmlhttp=new XMLHttpRequest();16 }17 else18 {// code for IE6, IE519 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");20 }21 xmlhttp.open("GET","doxygen/doxygen.tag",false);22 xmlhttp.send();23 var parser = new DOMParser();24 xmlDoc = parser.parseFromString(xmlhttp.responseText, "application/xml");25 }26 //when doxygen.tag is not found27 catch(e){28 xmlDoc=null;29 }30 }31 loadDoxyIndex();32 //load doxygen information if available33 function getDoxygenFile(functionname){ 34 link=[];35 if(xmlDoc !== null){36 x=xmlDoc.getElementsByTagName("name");37 for (i=0;i<x.length;i++){38 if(x[i].firstChild.nodeValue == functionname){39 anchorfile = x[i].parentNode.getElementsByTagName("anchorfile")[0].firstChild.nodeValue;40 anchor = x[i].parentNode.getElementsByTagName("anchor")[0].firstChild.nodeValue;41 link.push("doxygen/html/"+anchorfile+"#"+anchor);42 }43 }44 }45 return link;46 }47 48 //return number with comma separators49 function numberWithCommas(x) {50 return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");51 }52 //write info in the function info div53 function getInfo(functionindex){54 plot1.unhighlight(0,currentfunctionid);55 overviewplot1.unhighlight(0,currentfunctionid);56 plot2.unhighlight(0,currentfunctionid);57 overviewplot2.unhighlight(0,currentfunctionid);58 //now highlight new point59 plot1.highlight(0, functionindex); 60 overviewplot1.highlight(0, functionindex);61 plot2.highlight(0, functionindex); 62 overviewplot2.highlight(0, functionindex);63 createOptimizationTable(functionindex);64 callspercentage = functionpercentages[functionindex]["calls"]*100;65 icountpercentage = functionpercentages[functionindex]["icount"]*100;66 coretimepercentage = functionpercentages[functionindex]["core_elapsed_time"]*100;67 nonidletimepercentage = functionpercentages[functionindex]["nonidle_elapsed_time"]*100;68 fp_addsubpercentage = functionpercentages[functionindex]["fp_addsub"]*100;69 fp_muldivpercentage = functionpercentages[functionindex]["fp_muldiv"]*100;70 l3misspercentage = functionpercentages[functionindex]["l3miss"]*100;71 72 73 //$("#clickdata").hide();74 $("#functionname").text(functions[functionindex]["name_clean"]);75 $("#eip").text("0x"+functions[functionindex]["eip"]);76 $("#source").text(shortenSourcecode(functions[functionindex]["source"]));77 $("#calls").text(numberWithCommas(functions[functionindex]["calls"]));78 $("#callspercentage").text(numberWithCommas(Math.round(callspercentage))+"%");79 $("#icount").text(numberWithCommas(functions[functionindex]["instruction_count"]));80 $("#icountpercentage").text(numberWithCommas(Math.round(icountpercentage))+"%");81 $("#coretime").text(numberWithCommas(Math.round(functions[functionindex]["core_elapsed_time"]))+" ns");82 $("#coretimepercentage").text(numberWithCommas(Math.round(coretimepercentage))+"%");83 $("#nonidletime").text(numberWithCommas(Math.round(functions[functionindex]["nonidle_elapsed_time"]))+" ns");84 $("#nonidletimepercentage").text(numberWithCommas(Math.round(nonidletimepercentage))+"%");85 $("#fp_addsub").text(numberWithCommas(functions[functionindex]["fp_addsub"]));86 $("#fp_addsubpercentage").text(numberWithCommas(Math.round(fp_addsubpercentage))+"%");87 $("#fp_muldiv").text(numberWithCommas(functions[functionindex]["fp_muldiv"]));88 $("#fp_muldivpercentage").text(numberWithCommas(Math.round(fp_muldivpercentage))+"%");89 $("#l3miss").text(numberWithCommas(functions[functionindex]["l3miss"]));90 $("#l3misspercentage").text(numberWithCommas(Math.round(l3misspercentage))+"%");91 $("#cpivalue").text(functions[functionindex]["cpi"].toFixed(3));92 93 $( "#callprogress" ).progressbar({value: callspercentage});94 $( "#icountprogress" ).progressbar({value: icountpercentage});95 $( "#coretimeprogress" ).progressbar({value: coretimepercentage});96 $( "#nonidletimeprogress" ).progressbar({value: nonidletimepercentage});97 $( "#fp_addsubprogress" ).progressbar({value: fp_addsubpercentage});98 $( "#fp_muldivprogress" ).progressbar({value: fp_muldivpercentage});99 $( "#l3missprogress" ).progressbar({value: l3misspercentage});100 101 if ($('#container3').is(':hidden')) {102 $("#container3").slideToggle('slow', function() {});103 }104 if ($("#nextcore_elapsed_time").is(':hidden')){105 for(i=0; i < props.length; i++){106 for (j=0; j<2; j++){107 $("#"+minmax[j]+props[i]).slideToggle('slow', function() {});108 $("#"+nextprev[j]+props[i]).slideToggle('slow', function() {}); 109 }110 }111 }112 currentfunctionid=functionindex;113 //currentfunctionname = functions[functionindex]["name"];114 checkMinMax(functionindex); 115 if(getDoxygenFile(functions[functionindex]["name"]).length > 0){116 $("#doxygen").show();117 }118 else {119 $("#doxygen").hide();120 }121 fillCPIBar(functionindex);122 123 }124 125 function fillCPIBar(functionindex){126 plotoptions = { 127 series: {128 stack: true,129 lines: { show:false },130 bars: { show: true, barWidth: 0.6, horizontal:true }131 }, 132 xaxis: { show: false},133 yaxis: {show: false},134 grid: {show: false,135 hoverable: true, 136 clickable: true, 137 },138 legend: {show: false} 139 };140 totaltime = functions[functionindex]["core_elapsed_time"]*1e6;141 basevalue = 100*(functions[functionindex]["cpiBase"])/totaltime;142 branchvalue = 100*(functions[functionindex]["cpiBranchPredictor"])/totaltime;143 memvalue = 100*(functions[functionindex]["cpiMem"])/totaltime;144 othervalue = 100-basevalue-branchvalue-memvalue;145 var base = {146 color: "red",147 label: "Base",148 data : [[basevalue,0]]149 };150 var branch = {151 color: "yellow",152 label: "Branch",153 data : [[branchvalue,0]]154 };155 var mem = {156 color: "green",157 label: "Memory",158 data : [[memvalue,0]]159 };160 var other = {161 color: "gray",162 label: "Other",163 data : [[othervalue,0]]164 };165 $.plot($("#cpibar"), [base,branch,mem,other ], plotoptions);166 previousSeries=null;167 $("#cpibar").bind("plothover", function (event, pos, item) {168 if (item) {169 if (previousSeries != item.seriesIndex) {170 previousSeries = item.seriesIndex;171 $("#tooltip").remove();172 var x = item.datapoint[0].toFixed(2),173 y = item.datapoint[1].toFixed(2);174 showTooltip(item.pageX, item.pageY,item.series["label"]+" "+item.series.data[item.dataIndex][0].toFixed(2)+"%");175 }176 } 177 else {178 $("#tooltip").remove();179 previousSeries = null; 180 }181 182 });183 }184 //shorten de source code filename185 function shortenSourcecode(sourcecode){186 newname = sourcecode.split('/').pop().replace(":0","");187 if (newname == ":0"){188 newname = "";189 }190 return newname;191 }192 //check if we reach the minimum or maximum of a property, to gray out arrows193 function checkMinMax(functionindex){194 for(i=0; i < props.length; i++){195 for (j=0; j<2; j++){196 if(functionindex == functionboundaries[props[i]][minmax[j]]){197 $("#"+minmax[j]+props[i]).animate({"opacity":0.3},"fast", "swing", null);198 $("#"+nextprev[j]+props[i]).animate({"opacity":0.3},"fast", "swing", null);199 }200 else if ($("#"+minmax[j]+props[i]).css('opacity') < 1){201 $("#"+minmax[j]+props[i]).animate({"opacity":1},"fast", "swing", null);202 $("#"+nextprev[j]+props[i]).animate({"opacity":1},"fast", "swing", null);203 } 204 }205 }206 }207 //prettyfy a number (in fs). Output in ns and with comma separators208 function prettyNumber(number){209 number /= 1e6; //to nanoseconds210 pretty = number.toFixed(0); //round211 pretty = numberWithCommas(pretty);212 return pretty;213 }214 215 //create optimizationtable in per function statistics216 function createOptimizationTable(functionid)217 {218 var num_rows = optimizationsperfunction[functionid].length;219 var theader = '<table border="0">\n';220 var tbody = '';221 tbody += '<td width="150">Optimization</td>';222 tbody += '<td class="funoptimizationbar"></td>';223 tbody += '<td width="100" align="right" title="Application speedup">Speedup</td>'224 for( var i=0; i<num_rows;i++)225 {226 tbody += '<tr>';227 tbody += '<td title="'+optimization_summary[optimizationsperfunction[functionid][i]["optimization"][0]["optimization"]]["full_name"]+'">';228 tbody += optimizationsperfunction[functionid][i]["optimization"][0]["optimization"]+'</td>';229 tbody += '<td class="funoptimizationbar"><div id="finfoopt'+functionid+'a'+i+'" style="width:100px;height:15px;top:5px"></div></td>';230 tbody += '<td align="right">x'+optimizationsperfunction[functionid][i]["app_speedup"].toFixed(3);231 tbody += '</td>';232 tbody += '</tr>\n';233 234 235 }236 var tfooter = '</table>';237 document.getElementById('optimizationtable').innerHTML = theader + tbody + tfooter;238 createOptBar(functionid);239 }240 function createOptBar(functionid){241 var num_rows = optimizationsperfunction[functionid].length;242 var barsize = 380;243 var normalized = optimizationsperfunction[functionid][0]["app_speedup"]-1+0.0000000001;244 for(var index=0; index <num_rows; index++){245 var opt = optimizationsperfunction[functionid][index]["optimization"][0]["optimization"];246 var value = optimizationsperfunction[functionid][index]["app_speedup"]-1;247 var barlength = barsize*(value/normalized);248 document.getElementById("finfoopt"+functionid+"a"+index).style.width=barlength+"px";249 plotoptions = { 250 series: {251 stack: false,252 lines: { show:false },253 bars: { show: true, barWidth: 0.6, horizontal:true }254 }, 255 xaxis: { show: false},256 yaxis: {show: false},257 grid: {show: false,258 hoverable: true, 259 clickable: true, 260 },261 legend: {show: false} 262 };263 var Optbar = {264 color: colors[opt],265 label: functionid+":"+index,266 data : [[10,0]]267 };268 if(barlength > 1){269 $.plot($("#finfoopt"+functionid+"a"+index), [Optbar], plotoptions);270 $("#finfoopt"+functionid+"a"+index).bind("plothover", function (event, pos, item) {271 if (item) {272 if (previousSeries != item.seriesIndex) {273 previousSeries = item.seriesIndex;274 $("#tooltip").remove();275 var x = item.datapoint[0].toFixed(2),276 y = item.datapoint[1].toFixed(2);277 var funindex = item.series["label"].split(":")[0];278 var optindexj = item.series["label"].split(":")[1];279 var optimization = optimizationsperfunction[funindex][optindexj]["optimization"][0]["optimization"];280 var timewonback = (optimizationsperfunction[funindex][optindexj]["time_won_back_pct"]).toFixed(2)+"%";281 var timegain = prettyNumber(optimizationsperfunction[funindex][optindexj]["time_won_back"].toFixed(0))+" ns";282 var speedup = "x"+optimizationsperfunction[funindex][optindexj]["app_speedup"].toFixed(3);283 showTooltip(item.pageX,item.pageY,"<table>"+284 "<tr><td>Optimization</td><td align='right'>"+optimization+"</td></tr>"+285 "<tr><td>Time gain (function %) </td><td align='right'>"+timewonback+"</td></tr>"+286 "<tr><td>Time won back</td><td align='right'>"+timegain+"</td></tr>"+287 "<tr><td>Speedup</td><td align='right'>"+speedup+"</td></tr></table>"288 289 );290 }291 } 292 else {293 $("#tooltip").remove();294 previousSeries = null; 295 }296 297 298 });299 }300 }301 }302 //to have a nicer line up of the percentages, add a space to percentages < 10303 function addSpace(percentage){304 if (percentage.length < 5){305 return "<span style='visibility: hidden'>0</span>"+percentage;306 }307 return percentage;308 }309 //hover over function310 var hoverfunction = function (event, pos, item) {311 if (item) {312 if (previousPoint != item.dataIndex) {313 previousPoint = item.dataIndex;314 $("#tooltip").remove();315 var x = item.datapoint[0].toFixed(2),316 y = item.datapoint[1].toFixed(2);317 if(item.series["label"] == "functions"){318 showTooltip(item.pageX, item.pageY,319 functions[item.dataIndex]["name_clean"]);320 }321 else {322 showTooltip(item.pageX, item.pageY,323 item.series["label"]);324 }325 }326 } 327 else {328 $("#tooltip").remove();329 previousPoint = null; 330 }331 332 };333 //get next function334 function getNext(sortby, next){335 sortedfunctions = functions.slice();336 sortedfunctions.sort(function(x,y) 337 { 338 return (parseInt(1000*y[sortby]) - parseInt(1000*x[sortby])); 339 });340 i=sortedfunctions.length-1;341 if(next=="prev"){ 342 while(i>=0 && (parseInt(1000*sortedfunctions[i][sortby]) < parseInt(1000*functions[currentfunctionid][sortby]))){343 i--;344 }345 if(i!=-1 && i!=sortedfunctions.length-1){346 return sortedfunctions[i+1]["id"];347 } 348 }349 else{350 while(i>0 && (parseInt(1000*sortedfunctions[i][sortby]) <= parseInt(1000*functions[currentfunctionid][sortby]))){351 i--;352 }353 if(i>=0 && i!=sortedfunctions.length-1){354 return sortedfunctions[i]["id"];355 } 356 }357 return currentfunctionid;358 }359 function goToFunctionInfo(functionid){ 360 if(functionid > 0){361 getInfo(functionid);362 }363 else{364 getInfo(currentfunctionid);365 }366 window.location.hash="function_info";...
UI.js
Source:UI.js
1function UI(options) {2 let callbacks = options.callbacks;3 const showGraphInputBtn = document.querySelector('.show-graph-input-btn');4 const graphInput = document.querySelector('.graph-input');5 const graphFunctionInput = document.querySelector('#graph-input__function');6 const graphLineWidthInput = document.querySelector('#graph-input__line-width');7 const graphColorInput = document.querySelector('#graph-input__color');8 const graphAddBtn = document.querySelector('.graph-input__add-graph-btn');9 const graphsContainer = document.querySelector('.graphs-container');10 this.getAB = function () {11 const a = document.querySelector('#a').value - 0;12 const b = document.querySelector('#b').value - 0;13 return { a, b };14 };15 graphFunctionInput.addEventListener('keyup', () => {16 drawCurrentFunction();17 });18 graphLineWidthInput.addEventListener('keyup', () => {19 drawCurrentFunction();20 });21 graphColorInput.addEventListener('input', () => {22 drawCurrentFunction();23 });24 showGraphInputBtn.addEventListener('click', function () {25 graphInput.classList.toggle('graph-input--hidden');26 });27 graphAddBtn.addEventListener('click', addFunction);28 let functionIndex = 0;29 function drawCurrentFunction() {30 let graphData = parseGraphData();31 drawFunction(graphData);32 }33 function drawFunction(graphData) {34 if (graphData) callbacks.setFunction(graphData, functionIndex);35 }36 function addFunction() {37 let graphData = parseGraphData();38 drawFunction(graphData);39 drawGraphBlock(graphData);40 functionIndex++;41 graphInput.classList.remove('graph-input--hidden');42 }43 function drawGraphBlock(graphData) {44 const graphBlock = document.createElement('div');45 graphBlock.classList.add('graph');46 const blockInner = `47 <div class="graph__row">48 <label class="graph__label graph__row-item">Function #${functionIndex + 1}:</label>49 <div class="graph__function graph__row-item">${graphFunctionInput.value}</div>50 </div>51 <div class="graph__row">52 <label class="graph__label graph__row-item" for="derivative${functionIndex}">Derivative:</label>53 <input class="graph__derivative graph__row-item" id="integral${functionIndex}" type="checkbox"></input>54 </div>55 <div class="graph__row">56 <label class="graph__label graph__row-item" for="integral${functionIndex}">Integral:</label>57 <input class="graph__integral graph__row-item" id="integral${functionIndex}" type="checkbox"></input>58 </div>59 <div class="graph__row">60 <button class="graph__remove-btn btn-base">Remove function</div>61 </div>62 `;63 graphBlock.innerHTML = blockInner;64 const derivative = graphBlock.querySelector('.graph__derivative');65 const integral = graphBlock.querySelector('.graph__integral');66 const removeBtn = graphBlock.querySelector('.graph__remove-btn');67 derivative.setAttribute('id', `derivative${functionIndex}`);68 derivative.dataset.functionIndex = functionIndex;69 derivative.addEventListener('change', function () {70 callbacks.setDerivative(this.checked, derivative.dataset.functionIndex);71 });72 integral.setAttribute('id', `integral${functionIndex}`);73 integral.dataset.functionIndex = functionIndex;74 integral.addEventListener('change', function () {75 callbacks.setIntegral(this.checked, integral.dataset.functionIndex);76 });77 removeBtn.addEventListener('click', () => {78 callbacks.removeFunction(graphData);79 graphBlock.remove();80 });81 graphsContainer.append(graphBlock);82 }83 function parseGraphData() {84 try {85 let graphData = {86 lineWidth: parseFloat(graphLineWidthInput.value),87 color: graphColorInput.value,88 };89 eval(`graphData.f = function(x) { return ${graphFunctionInput.value} }`);90 return graphData;91 } catch (e) {92 //console.log(e, "Can't parse function");93 }94 }...
Using AI Code Generation
1var wptools = require('wptools');2var options = {3}4var page = wptools.page('Albert Einstein', options);5page.get(function(err, info) {6 if (err) {7 console.log(err);8 } else {9 console.log(info);10 }11});
Using AI Code Generation
1var wptools = require('wptools');2wptools.page('Barack Obama').then(function(page) {3 return page.functionIndex();4}).then(function(result) {5 console.log(result);6});
Using AI Code Generation
1var wpt = require('wpt');2var wptClient = new wpt('API_KEY');3var options = {4};5wptClient.runTest(options, function(err, data) {6 if (err) {7 console.log('Error: ' + err);8 } else {9 console.log('Test submitted. Polling results...');10 wptClient.getTestResults(data.data.testId, function(err, data) {11 if (err) {12 console.log('Error: ' + err);13 } else {14 console.log('First View');15 console.log('------------');16 console.log('Speed Index: ' + data.data.average.firstView.SpeedIndex);17 console.log('Load Time: ' + data.data.average.firstView.loadTime);18 console.log('Fully Loaded Time: ' + data.data.average.firstView.fullyLoaded);19 console.log('TTFB: ' + data.data.average.firstView.TTFB);20 console.log('Bytes In: ' + data.data.average.firstView.bytesIn);21 console.log('Bytes In Doc: ' + data.data.average.firstView.bytesInDoc);22 console.log('Requests Doc: ' + data.data.average.firstView.requestsDoc);23 console.log('Requests Full: ' + data.data.average.firstView.requestsFull);24 console.log('Response Code: ' + data.data.average.firstView.responseCode);25 console.log('Render: ' + data.data.average.firstView.render);26 console.log('DOM Elements: ' + data.data.average.firstView.domElements);27 console.log('Title Time: ' + data.data.average.firstView.titleTime);28 console.log('Load Event Start: ' + data.data.average.firstView.loadEventStart);29 console.log('Load Event End: ' + data.data.average.firstView.loadEventEnd);30 console.log('DOM Interactive: ' + data.data.average.firstView.domInteractive);31 console.log('Last Visual Change: ' + data.data.average.firstView.lastVisualChange);32 console.log('Speed Index (Doc Complete): ' + data.data.average.firstView.SpeedIndexDoc);33 console.log('Visual Complete 85%: ' + data.data.average.firstView.visual
Using AI Code Generation
1const wptools = require("wptools");2const fs = require("fs");3const test = async () => {4 const page = await wptools.page("India");5 const data = await page.get();6 console.log(data);7 fs.writeFileSync("data.json", JSON.stringify(data));8};9test();
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var path = require('path');4var _ = require('underscore');5var data = [];6var data2 = [];7var data3 = [];8var data4 = [];9var data5 = [];10var data6 = [];11var data7 = [];12var data8 = [];13var data9 = [];14var data10 = [];15var data11 = [];16var data12 = [];17var data13 = [];18var data14 = [];19var data15 = [];20var data16 = [];21var data17 = [];22var data18 = [];23var data19 = [];24var data20 = [];25var data21 = [];26var data22 = [];27var data23 = [];28var data24 = [];29var data25 = [];30var data26 = [];31var data27 = [];32var data28 = [];33var data29 = [];34var data30 = [];35var data31 = [];36var data32 = [];37var data33 = [];38var data34 = [];39var data35 = [];40var data36 = [];41var data37 = [];42var data38 = [];43var data39 = [];44var data40 = [];45var data41 = [];46var data42 = [];47var data43 = [];48var data44 = [];49var data45 = [];50var data46 = [];51var data47 = [];52var data48 = [];53var data49 = [];54var data50 = [];55var data51 = [];56var data52 = [];57var data53 = [];58var data54 = [];59var data55 = [];60var data56 = [];61var data57 = [];62var data58 = [];63var data59 = [];64var data60 = [];65var data61 = [];66var data62 = [];67var data63 = [];68var data64 = [];69var data65 = [];70var data66 = [];71var data67 = [];72var data68 = [];73var data69 = [];74var data70 = [];75var data71 = [];76var data72 = [];77var data73 = [];78var data74 = [];79var data75 = [];80var data76 = [];81var data77 = [];82var data78 = [];83var data79 = [];84var data80 = [];85var data81 = [];86var data82 = [];87var data83 = [];88var data84 = [];89var data85 = [];90var data86 = [];91var data87 = [];92var data88 = [];93var data89 = [];94var data90 = [];95var data91 = [];96var data92 = [];97var data93 = [];
Using AI Code Generation
1var wpt = require('webpage');2var page = wpt.create();3var arr = [3,4,5,6,7,8,9];4console.log(page.evaluate(function(arr){5 return arr.indexOf(5);6},arr));
Using AI Code Generation
1function f1() {2 return 1;3}4function f2() {5 return 2;6}7function f3() {8 return 3;9}10function f4() {11 return 4;12}13function f5() {14 return 5;15}16function f6() {17 return 6;18}19function f7() {20 return 7;21}22function f8() {23 return 8;24}25function f9() {26 return 9;27}28function f10() {29 return 10;30}31function f11() {32 return 11;33}34function f12() {35 return 12;36}37function f13() {38 return 13;39}40function f14() {41 return 14;42}43function f15() {44 return 15;45}46function f16() {47 return 16;48}49function f17() {50 return 17;51}52function f18() {53 return 18;54}55function f19() {56 return 19;57}58function f20() {59 return 20;60}61function f21() {62 return 21;63}64function f22() {65 return 22;66}67function f23() {68 return 23;69}70function f24() {71 return 24;72}73function f25() {74 return 25;75}76function f26() {77 return 26;78}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!