Best JavaScript code snippet using wpt
gui.js
Source:gui.js
1import {computeProbabilities} from './physics.js';2import {basisClick, counterClick, counterBlockClick, eventClick, magnetClick} from './clicks';3import presetExperiments from './presetExperiments.json';4import {nodeLength, margin, width, dx, dy, diagonal, tree, svg} from './draw/guiConfig.js';5import * as d3 from 'd3';6import {sliderHorizontal} from 'd3-simple-slider';7import set from 'lodash/set';8import get from 'lodash/get';9import initial from 'lodash/initial';10import findIndex from 'lodash/findIndex';11import katex from 'katex';12import findDeep from 'deepdash/findDeep';13import eachDeep from 'deepdash/eachDeep';14// Import math modules in a way that minimizes bundle size15import {create, roundDependencies, piDependencies, randomDependencies} from '../mathjs/lib/esm/index.js';16const {round, pi, random} = create({roundDependencies, piDependencies, randomDependencies});17// Default experimental setup18const urlString = window.location.href;19const url = new URL(urlString);20const experiment = url.searchParams.get('experiment');21let histories = JSON.parse(JSON.stringify(experiment ? presetExperiments[experiment] : presetExperiments.one));22// Draw tree23let root = getRoot(histories);24draw(root);25// Configures a d3 hierarchy for a given set of histories26function getRoot(histories) {27 const root = d3.hierarchy(computeProbabilities(histories));28 root.x0 = dy / 2;29 root.y0 = 0;30 root.descendants().forEach((d, i) => {31 d.id = i;32 // Label analyzers33 if (d.data.children) {34 if (d.data.children[0]) {35 d.basis = d.data.children[0].basis;36 d.theta = d.data.children[0].theta;37 d.phi = d.data.children[0].phi;38 d.magnitude = d.data.children[0].magnitude;39 }40 }41 // Label count at leaves42 if (d.data.children.length === 0) {43 d.probability = d.data.probability;44 d.data.count = 0;45 }46 });47 // Handle conditional probabilities48 let ignoredEventProbabilitySum = 0;49 eachDeep(root, value => {50 if (value.data.ignored === true) {51 ignoredEventProbabilitySum += value.data.probability;52 value.data.probability = 0;53 }54 }, {leavesOnly: true, childrenPath: 'children'});55 if (ignoredEventProbabilitySum) {56 eachDeep(root, value => {57 value.data.probability /= ignoredEventProbabilitySum;58 }, {leavesOnly: true, childrenPath: 'children'});59 }60 tree(root);61 return root;62}63// Binds d3 hierarchy to svg nodes and links64function draw(source) {65 svg.selectAll('*').remove();66 const gLink = svg67 .append('g')68 .attr('fill', 'none')69 .attr('stroke', '#555')70 .attr('stroke-opacity', 0.4)71 .attr('stroke-width', 1.5);72 const gNode = svg73 .append('g')74 .attr('cursor', 'pointer')75 .attr('pointer-events', 'all');76 const nodes = root.descendants().reverse();77 const links = root.links();78 // Set svg size79 let left = root;80 let right = root;81 root.eachBefore(node => {82 if (node.x < left.x) {83 left = node;84 }85 if (node.x > right.x) {86 right = node;87 }88 });89 const height = right.x - left.x + margin.top + margin.bottom;90 svg91 .transition()92 .attr('viewBox', [-margin.left, left.x - margin.top, width, height])93 .tween(94 'resize',95 window.ResizeObserver ? null : () => () => svg.dispatch('toggle'),96 );97 // Draw oven98 const oven = gNode.selectAll('g').data(nodes.filter(99 node => (node.data.children[0] !== undefined)).filter(100 node => node.data.children[0].event === 'oven'));101 drawOven(oven, source);102 // Draw analyzers103 const analyzers = gNode.selectAll('g').data(nodes.filter(104 node => (node.data.children[0] !== undefined)).filter(105 node => node.data.children[0].event !== 'magnet').filter(106 node => node.data.children[0].event !== 'identity').filter(107 node => node.data.children[0].event !== 'oven'), d => d.id);108 drawAnalyzers(analyzers, source);109 const analyzersIgnorable = gNode.selectAll('g').data(nodes.filter(110 node => (node.data.children[0] !== undefined)).filter(111 node => node.data.children[0].event !== 'magnet').filter(112 node => node.data.children[0].event === 'identity'), d => d.id);113 drawAnalyzersIgnorable(analyzersIgnorable, source);114 // Draw magnets115 const magnets = gNode.selectAll('g').data(nodes.filter(116 node => (node.data.children[0] !== undefined)).filter(117 node => (node.data.children[0].event === 'magnet')), d => d.id);118 drawMagnets(magnets, source);119 // Draw counters120 const counters = gNode.selectAll('g').data(nodes.filter(node => (121 node.data.probability !== undefined && node.data.ignored !== true)), d => d.id);122 drawCounters(counters, source);123 // Draw counter blocks124 const counterBlocks = gNode.selectAll('g').data(nodes.filter(node => (125 node.data.probability !== undefined && node.data.ignored === true)), d => d.id);126 drawCounterBlocks(counterBlocks, source);127 // Update the linksâ¦128 const link = gLink.selectAll('path').data(links, d => d.target.id);129 // Enter any new links at the parent's previous position.130 const linkEnter = link131 .enter()132 .append('path')133 .attr('d', () => {134 const o = {x: source.x0, y: source.y0};135 return diagonal({source: o, target: o});136 });137 link.merge(linkEnter).attr('d', diagonal);138 link139 .exit()140 .remove()141 .attr('d', () => {142 const o = {x: source.x, y: source.y};143 return diagonal({source: o, target: o});144 });145}146function drawAnalyzers(analyzers, source) {147 const analyzerEnter = analyzers148 .enter()149 .append('g')150 .attr('transform', `translate(${source.y0},${source.x0})`)151 .attr('fill-opacity', 0)152 .attr('stroke-opacity', 0);153 // Draw outline154 analyzerEnter155 .append('rect')156 .attr('width', nodeLength)157 .attr('x', -1 * (nodeLength / 2))158 .attr('y', -1 * (nodeLength / 2))159 .attr('height', nodeLength)160 .attr('fill', 'white')161 .attr('stroke-width', 2)162 .attr('stroke', 'grey');163 // Draw spin-up port164 analyzerEnter165 .append('foreignObject')166 .attr('x', nodeLength / 5)167 .attr('y', -1 * (nodeLength / 2))168 .attr('width', nodeLength / 4)169 .attr('height', nodeLength / 2)170 .style('pointer-events', 'none')171 .append('xhtml:body')172 .html(katex.renderToString('\\Huge{\\pmb{+}}'));173 analyzerEnter174 .append('rect')175 .attr('width', nodeLength / 4)176 .attr('height', nodeLength / 2)177 .attr('x', nodeLength / 4)178 .attr('y', -1 * (nodeLength / 2))179 .attr('fill', 'transparent')180 .attr('stroke-width', 2)181 .attr('stroke', 'grey')182 .style('pointer-events', 'visible')183 .on('mousedown', click => {184 stop();185 root = getRoot(eventClick(click, 'spinUp', histories));186 draw(root);187 });188 // Draw spin-down port189 analyzerEnter190 .append('foreignObject')191 .attr('x', nodeLength / 5)192 .attr('y', 0)193 .attr('width', nodeLength / 4)194 .attr('height', nodeLength / 2)195 .style('pointer-events', 'none')196 .append('xhtml:body')197 .html(katex.renderToString('\\Huge{\\pmb{-}}'));198 analyzerEnter199 .append('rect')200 .attr('width', nodeLength / 4)201 .attr('height', nodeLength / 2)202 .attr('x', nodeLength / 4)203 .attr('y', 0)204 .attr('fill', 'transparent')205 .attr('stroke-width', 2)206 .attr('stroke', 'grey')207 .style('pointer-events', 'visible')208 .on('mousedown', click => {209 stop();210 root = getRoot(eventClick(click, 'spinDown', histories));211 draw(root);212 });213 // Label analyzers214 analyzerEnter215 .append('foreignObject')216 .attr('x', -0.25 * nodeLength)217 .attr('y', -0.4 * nodeLength)218 .attr('width', nodeLength / 4)219 .attr('height', nodeLength / 2)220 .style('pointer-events', 'none')221 .append('xhtml:body')222 .html(d => katex.renderToString(`\\Huge{\\hat{${d.basis}}}`));223 analyzerEnter224 .append('rect')225 .attr('x', -0.25 * nodeLength)226 .attr('y', -0.4 * nodeLength)227 .attr('width', nodeLength / 4)228 .attr('height', nodeLength / 3)229 .attr('opacity', 0)230 .style('pointer-events', 'visible')231 .on('mousedown', click => {232 stop();233 root = getRoot(basisClick(click, histories));234 draw(root);235 });236 analyzerEnter237 .append('foreignObject')238 .attr('x', -0.5 * nodeLength)239 .attr('y', -0.05 * nodeLength)240 .attr('width', nodeLength)241 .attr('height', nodeLength / 4)242 .style('pointer-events', 'none')243 .append('xhtml:body')244 .html(d => katex.renderToString((d.basis === 'n') ? `\\Large{\\theta = ${d.theta}}` : ''));245 analyzerEnter246 .append('rect')247 .attr('x', -1 * nodeLength / 2)248 .attr('y', -0.05 * nodeLength)249 .attr('width', 3 * nodeLength / 4)250 .attr('height', nodeLength / 4)251 .attr('opacity', 0)252 .style('pointer-events', (d => (d.basis === 'n') ? 'visible' : 'none'))253 .on('mousedown', click => {254 svg.selectAll('.slider').remove();255 svg.selectAll('.axis').remove();256 svg.append('foreignObject')257 .attr('class', 'axis')258 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)259 .attr('y', `${click.target.__data__.x + (0.75 * dx)}`)260 .attr('width', nodeLength / 4)261 .attr('height', nodeLength / 4)262 .style('ponter-events', 'none')263 .append('xhtml:body')264 .html(katex.renderToString('\\LARGE{\\theta}'));265 svg.append('g')266 .attr('pointer-events', 'all')267 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.4 * dx)})`)268 .call(slider(click, 'theta'));269 });270 analyzerEnter271 .append('foreignObject')272 .attr('x', -0.5 * nodeLength)273 .attr('y', 0.15 * nodeLength)274 .attr('width', nodeLength)275 .attr('height', nodeLength / 4)276 .style('pointer-events', 'none')277 .append('xhtml:body')278 .html(d => katex.renderToString(d.basis === 'n' ? `\\Large{\\phi = ${d.phi}}` : ''));279 analyzerEnter280 .append('rect')281 .attr('x', -1 * nodeLength / 2)282 .attr('y', 0.18 * nodeLength)283 .attr('width', 3 * nodeLength / 4)284 .attr('height', nodeLength / 4)285 .attr('opacity', 0)286 .style('pointer-events', (d => (d.basis === 'n') ? 'visible' : 'none'))287 .on('mousedown', click => {288 svg.selectAll('.slider').remove();289 svg.selectAll('.axis').remove();290 svg.append('foreignObject')291 .attr('class', 'axis')292 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)293 .attr('y', `${click.target.__data__.x + (0.75 * dx)}`)294 .attr('width', nodeLength / 4)295 .attr('height', nodeLength / 4)296 .style('ponter-events', 'none')297 .append('xhtml:body')298 .html(katex.renderToString('\\LARGE{\\phi}'));299 svg.append('g')300 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.4 * dx)})`)301 .call(slider(click, 'phi'));302 });303 analyzers304 .merge(analyzerEnter)305 .attr('transform', d => `translate(${d.y},${d.x})`)306 .attr('fill-opacity', 1)307 .attr('stroke-opacity', 1);308}309function drawOven(oven, source) {310 const ovenEnter = oven311 .enter()312 .append('g')313 .attr('transform', `translate(${source.y0},${source.x0})`)314 .attr('fill-opacity', 0)315 .attr('stroke-opacity', 0);316 // Draw outline317 ovenEnter318 .append('rect')319 .attr('width', nodeLength)320 .attr('x', -1 * (nodeLength / 2))321 .attr('y', -1 * (nodeLength / 2))322 .attr('height', nodeLength)323 .attr('fill', 'white')324 .attr('stroke-width', 2)325 .attr('stroke', 'grey');326 // Draw collimator327 ovenEnter328 .append('rect')329 .attr('width', nodeLength / 3)330 .attr('x', nodeLength / 2)331 .attr('y', -nodeLength / 6)332 .attr('height', nodeLength / 3)333 .attr('fill-opacity', 0)334 .attr('stroke-width', 2)335 .attr('stroke', 'grey');336 // Draw collimator lines337 const collimatorLinePositions = [338 [(nodeLength / 2) + (nodeLength / 12), -nodeLength / 6],339 [(nodeLength / 2) + (nodeLength / 12), nodeLength / 24],340 [(nodeLength / 2) + (nodeLength / 6), -nodeLength / 6],341 [(nodeLength / 2) + (nodeLength / 6), nodeLength / 24],342 [(nodeLength / 2) + (nodeLength / 4), -nodeLength / 6],343 [(nodeLength / 2) + (nodeLength / 4), nodeLength / 24],344 ];345 collimatorLinePositions.forEach(position => {346 ovenEnter347 .append('rect')348 .attr('width', 1)349 .attr('x', position[0])350 .attr('y', position[1])351 .attr('height', nodeLength / 8)352 .attr('fill-opacity', 0)353 .attr('stroke-width', 2)354 .attr('stroke', 'grey');355 });356 // Label oven357 ovenEnter358 .append('foreignObject')359 .attr('x', -0.35 * nodeLength)360 .attr('y', -0.35 * nodeLength)361 .attr('width', nodeLength)362 .attr('height', nodeLength / 2)363 .style('pointer-events', 'none')364 .append('xhtml:body')365 .html(katex.renderToString('\\Huge{\\textrm{oven}}'));366 oven367 .merge(ovenEnter)368 .attr('transform', d => `translate(${d.y},${d.x})`)369 .attr('fill-opacity', 1)370 .attr('stroke-opacity', 1);371}372function drawAnalyzersIgnorable(analyzers, source) {373 const analyzerEnter = analyzers374 .enter()375 .append('g')376 .attr('transform', `translate(${source.y0},${source.x0})`)377 .attr('fill-opacity', 0)378 .attr('stroke-opacity', 0);379 // Draw outline380 analyzerEnter381 .append('rect')382 .attr('width', nodeLength)383 .attr('x', -1 * (nodeLength / 2))384 .attr('y', -1 * (nodeLength / 2))385 .attr('height', nodeLength)386 .attr('fill', 'white')387 .attr('stroke-width', 2)388 .attr('stroke', 'grey');389 // Draw spin-up port390 analyzerEnter391 .append('foreignObject')392 .attr('x', nodeLength / 5)393 .attr('y', -1 * (nodeLength / 2))394 .attr('width', nodeLength / 4)395 .attr('height', nodeLength / 2)396 .style('pointer-events', 'none')397 .append('xhtml:body')398 .html(katex.renderToString('\\Huge{\\pmb{+}}'));399 analyzerEnter400 .append('rect')401 .attr('width', nodeLength / 4)402 .attr('height', nodeLength / 2)403 .attr('x', nodeLength / 4)404 .attr('y', -1 * (nodeLength / 2))405 .attr('fill', 'transparent')406 .attr('stroke-width', 2)407 .attr('stroke', 'grey')408 .style('pointer-events', 'visible')409 .on('mousedown', click => {410 stop();411 root = getRoot(eventClick(click, 'spinUp', histories));412 draw(root);413 });414 // Draw spin-down port415 analyzerEnter416 .append('foreignObject')417 .attr('x', nodeLength / 5)418 .attr('y', 0)419 .attr('width', nodeLength / 4)420 .attr('height', nodeLength / 2)421 .style('pointer-events', 'none')422 .append('xhtml:body')423 .html(katex.renderToString('\\Huge{\\pmb{-}}'));424 analyzerEnter425 .append('rect')426 .attr('width', nodeLength / 4)427 .attr('height', nodeLength / 2)428 .attr('x', nodeLength / 4)429 .attr('y', 0)430 .attr('fill', 'transparent')431 .attr('stroke-width', 2)432 .attr('stroke', 'grey')433 .style('pointer-events', 'visible')434 .on('mousedown', click => {435 stop();436 root = getRoot(eventClick(click, 'spinDown', histories));437 draw(root);438 });439 // Label analyzers440 analyzerEnter441 .append('foreignObject')442 .attr('x', -0.25 * nodeLength)443 .attr('y', -0.4 * nodeLength)444 .attr('width', nodeLength / 4)445 .attr('height', nodeLength / 2)446 .style('pointer-events', 'none')447 .append('xhtml:body')448 .html(d => katex.renderToString(`\\Huge{\\hat{${d.basis}}}`));449 analyzerEnter450 .append('rect')451 .attr('x', -0.25 * nodeLength)452 .attr('y', -0.4 * nodeLength)453 .attr('width', nodeLength / 4)454 .attr('height', nodeLength / 3)455 .attr('opacity', 0)456 .style('pointer-events', 'visible')457 .on('mousedown', click => {458 stop();459 root = getRoot(basisClick(click, histories));460 draw(root);461 });462 analyzerEnter463 .append('foreignObject')464 .attr('x', -0.5 * nodeLength)465 .attr('y', -0.05 * nodeLength)466 .attr('width', nodeLength)467 .attr('height', nodeLength / 4)468 .style('pointer-events', 'none')469 .append('xhtml:body')470 .html(d => katex.renderToString((d.basis === 'n') ? `\\Large{\\theta = ${d.theta}}` : ''));471 analyzerEnter472 .append('rect')473 .attr('x', -1 * nodeLength / 2)474 .attr('y', -0.05 * nodeLength)475 .attr('width', 3 * nodeLength / 4)476 .attr('height', nodeLength / 4)477 .attr('opacity', 0)478 .style('pointer-events', (d => (d.basis === 'n') ? 'visible' : 'none'))479 .on('mousedown', click => {480 svg.selectAll('.slider').remove();481 svg.selectAll('.axis').remove();482 svg.append('foreignObject')483 .attr('class', 'axis')484 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)485 .attr('y', `${click.target.__data__.x + (0.75 * dx)}`)486 .attr('width', nodeLength / 4)487 .attr('height', nodeLength / 4)488 .style('ponter-events', 'none')489 .append('xhtml:body')490 .html(katex.renderToString('\\LARGE{\\theta}'));491 svg.append('g')492 .attr('pointer-events', 'all')493 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.4 * dx)})`)494 .call(slider(click, 'theta'));495 });496 analyzerEnter497 .append('foreignObject')498 .attr('x', -0.5 * nodeLength)499 .attr('y', 0.15 * nodeLength)500 .attr('width', nodeLength)501 .attr('height', nodeLength / 4)502 .style('pointer-events', 'none')503 .append('xhtml:body')504 .html(d => katex.renderToString(d.basis === 'n' ? `\\Large{\\phi = ${d.phi}}` : ''));505 analyzerEnter506 .append('rect')507 .attr('x', -1 * nodeLength / 2)508 .attr('y', 0.18 * nodeLength)509 .attr('width', 3 * nodeLength / 4)510 .attr('height', nodeLength / 4)511 .attr('opacity', 0)512 .style('pointer-events', (d => (d.basis === 'n') ? 'visible' : 'none'))513 .on('mousedown', click => {514 svg.selectAll('.slider').remove();515 svg.selectAll('.axis').remove();516 svg.append('foreignObject')517 .attr('class', 'axis')518 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)519 .attr('y', `${click.target.__data__.x + (0.75 * dx)}`)520 .attr('width', nodeLength / 4)521 .attr('height', nodeLength / 4)522 .style('ponter-events', 'none')523 .append('xhtml:body')524 .html(katex.renderToString('\\LARGE{\\phi}'));525 svg.append('g')526 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.4 * dx)})`)527 .call(slider(click, 'phi'));528 });529 analyzers530 .merge(analyzerEnter)531 .attr('transform', d => `translate(${d.y},${d.x})`)532 .attr('fill-opacity', 1)533 .attr('stroke-opacity', 1);534}535function drawMagnets(magnets, source) {536 const magnetEnter = magnets537 .enter()538 .append('g')539 .attr('transform', `translate(${source.y0},${source.x0})`)540 .attr('fill-opacity', 0)541 .attr('stroke-opacity', 0);542 // Draw outline543 magnetEnter544 .append('rect')545 .attr('width', nodeLength)546 .attr('x', -1 * (nodeLength / 2))547 .attr('y', -1 * (nodeLength / 2))548 .attr('height', nodeLength)549 .attr('fill', 'gainsboro')550 .attr('stroke-width', 2)551 .attr('stroke', 'grey');552 // Draw output port553 magnetEnter554 .append('rect')555 .attr('width', nodeLength / 4)556 .attr('height', nodeLength)557 .attr('x', nodeLength / 4)558 .attr('y', -nodeLength / 2)559 .attr('fill', 'transparent')560 .attr('stroke-width', 2)561 .attr('stroke', 'grey')562 .style('pointer-events', 'visible')563 .on('mousedown', click => {564 stop();565 root = getRoot(magnetClick(click, histories));566 draw(root);567 });568 // Label magnets569 magnetEnter570 .append('foreignObject')571 .attr('x', -0.25 * nodeLength)572 .attr('y', -0.55 * nodeLength)573 .attr('width', nodeLength / 4)574 .attr('height', nodeLength / 2)575 .style('pointer-events', 'none')576 .append('xhtml:body')577 .html(d => katex.renderToString(`\\Huge{\\hat{${d.basis}}}`));578 magnetEnter579 .append('rect')580 .attr('x', -0.25 * nodeLength)581 .attr('y', -0.55 * nodeLength)582 .attr('width', nodeLength / 4)583 .attr('height', nodeLength / 3)584 .attr('opacity', 0)585 .style('pointer-events', 'visible')586 .on('mousedown', click => {587 stop();588 root = getRoot(basisClick(click, histories));589 draw(root);590 });591 magnetEnter592 .append('foreignObject')593 .attr('x', -0.5 * nodeLength)594 .attr('y', -0.24 * nodeLength)595 .attr('width', nodeLength)596 .attr('height', nodeLength / 3)597 .style('pointer-events', 'none')598 .append('xhtml:body')599 .html(d => katex.renderToString(`\\Large{\\omega t = ${d.magnitude}}`));600 magnetEnter601 .append('rect')602 .attr('x', -1 * nodeLength / 2)603 .attr('y', -0.24 * nodeLength)604 .attr('width', 3 * nodeLength / 4)605 .attr('height', nodeLength / 4)606 .attr('opacity', 0)607 .on('mousedown', click => {608 svg.selectAll('.slider').remove();609 svg.selectAll('.axis').remove();610 svg.append('foreignObject')611 .attr('class', 'axis')612 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)613 .attr('y', `${click.target.__data__.x + (0.85 * dx)}`)614 .attr('width', nodeLength)615 .attr('height', nodeLength / 3)616 .style('ponter-events', 'none')617 .append('xhtml:body')618 .html(katex.renderToString('\\LARGE{\\omega t = \\frac{e}{m_e} |\\vec{B}| t}'));619 svg.append('g')620 .attr('pointer-events', 'all')621 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.6 * dx)})`)622 .call(slider(click, 'magnitude'));623 });624 magnetEnter625 .append('foreignObject')626 .attr('x', -0.5 * nodeLength)627 .attr('y', -0.05 * nodeLength)628 .attr('width', nodeLength)629 .attr('height', nodeLength / 4)630 .style('pointer-events', 'none')631 .append('xhtml:body')632 .html(d => katex.renderToString((d.basis === 'n') ? `\\Large{\\theta = ${d.theta}}` : ''));633 magnetEnter634 .append('rect')635 .attr('x', -1 * nodeLength / 2)636 .attr('y', -0.05 * nodeLength)637 .attr('width', 3 * nodeLength / 4)638 .attr('height', nodeLength / 4)639 .attr('opacity', 0)640 .style('pointer-events', (d => (d.basis === 'n') ? 'visible' : 'none'))641 .on('mousedown', click => {642 svg.selectAll('.slider').remove();643 svg.selectAll('.axis').remove();644 svg.append('foreignObject')645 .attr('class', 'axis')646 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)647 .attr('y', `${click.target.__data__.x + (0.75 * dx)}`)648 .attr('width', nodeLength / 4)649 .attr('height', nodeLength / 4)650 .style('ponter-events', 'none')651 .append('xhtml:body')652 .html(katex.renderToString('\\LARGE{\\theta}'));653 svg.append('g')654 .attr('pointer-events', 'all')655 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.4 * dx)})`)656 .call(slider(click, 'theta'));657 });658 magnetEnter659 .append('foreignObject')660 .attr('x', -0.5 * nodeLength)661 .attr('y', 0.15 * nodeLength)662 .attr('width', nodeLength)663 .attr('height', nodeLength / 4)664 .style('pointer-events', 'none')665 .append('xhtml:body')666 .html(d => katex.renderToString(d.basis === 'n' ? `\\Large{\\phi = ${d.phi}}` : ''));667 magnetEnter668 .append('rect')669 .attr('x', -1 * nodeLength / 2)670 .attr('y', 0.18 * nodeLength)671 .attr('width', 3 * nodeLength / 4)672 .attr('height', nodeLength / 4)673 .attr('opacity', 0)674 .style('pointer-events', (d => (d.basis === 'n') ? 'visible' : 'none'))675 .on('mousedown', click => {676 svg.selectAll('.slider').remove();677 svg.selectAll('.axis').remove();678 svg.append('foreignObject')679 .attr('class', 'axis')680 .attr('x', `${click.target.__data__.y + (1.25 * dx)}`)681 .attr('y', `${click.target.__data__.x + (0.75 * dx)}`)682 .attr('width', nodeLength / 4)683 .attr('height', nodeLength / 4)684 .style('ponter-events', 'none')685 .append('xhtml:body')686 .html(katex.renderToString('\\LARGE{\\phi}'));687 svg.append('g')688 .attr('transform', `translate(${click.target.__data__.y + dx}, ${click.target.__data__.x + (1.4 * dx)})`)689 .call(slider(click, 'phi'));690 });691 magnets692 .merge(magnetEnter)693 .attr('transform', d => `translate(${d.y},${d.x})`)694 .attr('fill-opacity', 1)695 .attr('stroke-opacity', 1);696}697function drawCounterBlocks(counterBlocks, source) {698 const counterBlockEnter = counterBlocks699 .enter()700 .append('g')701 .attr('transform', `translate(${source.y0},${source.x0})`)702 .attr('fill-opacity', 0)703 .attr('stroke-opacity', 0);704 counterBlockEnter705 .append('rect')706 .attr('width', 0.02 * nodeLength)707 .attr('x', -0.35 * nodeLength)708 .attr('y', -nodeLength / 8)709 .attr('height', nodeLength / 4)710 .attr('fill', 'grey')711 .attr('stroke-width', 2)712 .attr('stroke', 'grey');713 counterBlockEnter714 .append('rect')715 .attr('width', 0.2 * nodeLength)716 .attr('x', -0.425 * nodeLength)717 .attr('y', -nodeLength / 8)718 .attr('height', nodeLength / 4)719 .attr('fill', 'transparent')720 .attr('stroke-width', 2)721 .attr('stroke', 'transparent')722 .on('mousedown', click => {723 stop();724 root = getRoot(counterBlockClick(click, histories));725 draw(root);726 });727 counterBlocks728 .merge(counterBlockEnter)729 .attr('transform', d => `translate(${d.y},${d.x})`)730 .attr('fill-opacity', 1)731 .attr('stroke-opacity', 1);732}733function drawCounters(counters, source) {734 const counterEnter = counters735 .enter()736 .append('g')737 .attr('transform', `translate(${source.y0},${source.x0})`)738 .attr('fill-opacity', 0)739 .attr('stroke-opacity', 0);740 counterEnter741 .append('foreignObject')742 .attr('width', nodeLength / 2)743 .attr('height', nodeLength / 4)744 .style('pointer-events', 'none')745 .attr('x', -0.35 * nodeLength)746 .attr('y', -0.4 * nodeLength)747 .append('xhtml:body')748 .html(d => katex.renderToString(`\\LARGE{${d.data.count}}`));749 counterEnter750 .append('rect')751 .attr('width', 0.7 * nodeLength)752 .attr('x', -0.3 * nodeLength)753 .attr('y', -nodeLength / 16)754 .attr('height', nodeLength / 8)755 .attr('fill', 'white')756 .attr('stroke-width', 2)757 .attr('stroke', 'grey')758 .on('mousedown', click => {759 stop();760 root = getRoot(counterClick(click, histories));761 draw(root);762 });763 counterEnter764 .append('rect')765 .attr('width', d => (0.7 * nodeLength) * (d.data.count / 100))766 .attr('x', -0.3 * nodeLength)767 .attr('y', -nodeLength / 16)768 .attr('height', nodeLength / 8)769 .attr('fill', 'LightSteelBlue')770 .attr('stroke-width', 2)771 .attr('stroke', 'grey')772 .on('mousedown', click => {773 stop();774 root = getRoot(counterClick(click, histories));775 draw(root);776 });777 counters778 .merge(counterEnter)779 .attr('transform', d => `translate(${d.y},${d.x})`)780 .attr('fill-opacity', 1)781 .attr('stroke-opacity', 1);782}783function slider(click, parameter) {784 stop();785 let parent = click.target.__data__;786 const path = [];787 while (parent.parent) {788 const childIndex = findIndex(parent.parent.data.children, child =>789 (child.basis === parent.data.basis & child.event === parent.data.event));790 path.unshift('children', childIndex);791 parent = parent.parent;792 }793 path.push('children');794 const parameterInit = get(histories, path)[0][parameter];795 return sliderHorizontal().min(0).max(2 * pi).step(0.01).displayFormat(d3.format('.2f')).width(dy * 2).default(parameterInit)796 .on('end', value => {797 histories = set(histories, path, get(histories, path).map(child => {798 child[parameter] = round(value, 2);799 return child;800 }));801 root = getRoot(histories);802 draw(root);803 });804}805function recordEvent() {806 // Choose a history807 const sample = random();808 let probabilitySum = 0;809 const branch = findDeep(root, (value, key) => {810 if (key === 'probability') {811 probabilitySum += value;812 return (probabilitySum >= sample) || (probabilitySum === 1);813 }814 return false;815 }, {pathFormat: 'array', leavesOnly: true});816 const path = initial(branch.context._item.path);817 const count = branch.parent.count + 1;818 if (count > 100) {819 root = getRoot(histories);820 draw(root);821 } else {822 set(root, path.concat(['count']), count);823 draw(root);824 }825}826// Start/stop827let eventRecorder = null;828function stop() {829 clearInterval(eventRecorder);830 eventRecorder = null;831 document.getElementById('enable').innerHTML = 'Start';832}833document.getElementById('enable').onclick = function () {834 if (eventRecorder) {835 stop();836 } else {837 eventRecorder = setInterval(() => {838 recordEvent();839 }, 10);840 document.getElementById('enable').innerHTML = 'Stop';841 }842};843// Reset counters844document.getElementById('reset').onclick = function () {845 root = getRoot(histories);846 draw(root);847};848// Preset experiment chooser849document.getElementById('experiment').onchange = function (selectObject) {850 stop();851 histories = JSON.parse(JSON.stringify({852 1: presetExperiments.one,853 2: presetExperiments.two,854 3: presetExperiments.three,855 '4a': presetExperiments.fourA,856 '4b': presetExperiments.fourB,857 '4c': presetExperiments.fourC,858 }[selectObject.target.value]));859 root = getRoot(histories);860 draw(root);861};862// Config file reader863document.getElementById('selectFiles').onclick = function () {864 document.getElementById('selectFiles').value = null;865};866document.getElementById('selectFiles').onchange = function () {867 const {files} = document.getElementById('selectFiles');868 if (files.length <= 0) {869 return false;870 }871 const fr = new FileReader();872 fr.onload = function (e) {873 histories = JSON.parse(e.target.result);874 root = getRoot(histories);875 draw(root);876 };877 fr.readAsText(files.item(0));878};879// Config file saver880document.getElementById('export').onclick = function () {881 const a = document.createElement('a');882 const file = new Blob([JSON.stringify(histories, null, 2)], {type: 'application/json'});883 a.href = URL.createObjectURL(file);884 a.download = 'histories.json';885 a.click();...
loopList2.js
Source:loopList2.js
1// 线æ§è¡¨çæ½è±¡æ°æ®ç±»å2class loopList2 {3 constructor() {4 this.init()5 }6 dataType(prev,value, next) {7 return Object.create(null, {8 prev: {9 value: prev,10 writable: true,11 configurable: true,12 enumerable: true13 },14 value: {15 value: value,16 writable: true,17 configurable: true,18 enumerable: true19 },20 next: {21 value: next,22 writable: true,23 configurable: true,24 enumerable: true25 }26 })27 }28 init() {29 // åå§åæä½ï¼å»ºç«ä¸ä¸ªç©ºç线æ§è¡¨30 this.list=this.dataType(null,null,null)31 this.nodeLength = 032 }33 reset() {34 //å°çº¿æ§è¡¨æ¸
空35 }36 getLength() {37 //è¿å线æ§è¡¨çå
ç´ ä¸ªæ°38 }39 isEmpty() {40 // è¥çº¿æ§è¡¨ä¸ºç©ºï¼è¿åtrueï¼å¦åè¿åfalse41 }42 insert(i, value) {43 //å¨çº¿æ§è¡¨ç第i个ä½ç½®æå
¥æ°å
ç´ 44 if (i < 1 || i > this.nodeLength + 1) {45 return 'error'46 }47 var node=this.list48 if(i<Math.ceil(this.nodeLength/2)){//ååé¨å49 console.log("å¢1")50 for(var j=1;j<i;j++){51 node=node.next52 }53 var before=node54 var after=node.next55 if(after==null||after==this.list){56 // this.dataType(this.list,value,after)57 var n= this.dataType(this.list,value,after)58 before=this.list59 }else{60 var n= this.dataType(before,value,after)61 }62 after.prev=n63 before.next=n64 }else{//ååé¨å65 console.log("å¢2")66 for(var j=this.nodeLength;j>=i;j--){67 node=node.prev68 }69 var after=node70 var before=node.prev71 if(before==null||before==this.list){72 // this.dataType(this.list,value,after)73 var n= this.dataType(this.list,value,after)74 before=this.list75 }else{76 var n= this.dataType(before,value,after)77 }78 after.prev=n79 before.next=n80 81 }82 this.nodeLength++83 }84 delete(i) {85 //å é¤çº¿æ§è¡¨ä¸ç¬¬i个ä½ç½®çå
ç´ å¹¶è¿åå
ç´ å¼86 if (i < 1 || i > this.nodeLength||this.nodeLength==0) {87 return 'error'88 }89 var node=this.list90 if(i<Math.ceil(this.nodeLength/2)){//ååé¨å91 console.log("å 11")92 for(var j=1;j<i;j++){93 node=node.next94 }95 var before=node96 node=node.next97 var after=node.next98 if(after==this.list){99 after.prev=null100 before.next=null101 }else{102 after.prev=before103 before.next=after104 }105 106 }else{//ååé¨å107 console.log("å 22")108 for(var j=this.nodeLength;j>i;j--){109 node=node.prev110 }111 var after=node112 node=node.prev113 var before=node.prev114 if(before==this.list){115 after.prev=null116 before.next=null117 }else{118 after.prev=before119 before.next=after120 }121 122 }123 this.nodeLength--124 return node.value125 }126 update(i, value) {127 //ä¿®æ¹çº¿æ§è¡¨ä¸ç¬¬i个ä½ç½®çå
ç´ å¹¶è¿ååå
ç´ å¼128 if (i < 1 || i > this.nodeLength||this.nodeLength==0) {129 return 'error'130 }131 var node=this.list132 if(i<Math.ceil(this.nodeLength/2)){//ååé¨å133 console.log("æ¹111")134 for(var j=1;j<i;j++){135 node=node.next136 }137 node=node.next138 }else{//ååé¨å139 console.log("æ¹222")140 for(var j=this.nodeLength;j>i;j--){141 node=node.prev142 }143 node=node.prev144 }145 var tmp=node.value146 node.value=value147 return tmp148 }149 selectByKey(i) {150 //å°çº¿æ§è¡¨ä¸ç¬¬i个ä½ç½®çå
ç´ å¼è¿å151 if (i < 1 || i > this.nodeLength||this.nodeLength==0) {152 return 'error'153 }154 var node=this.list155 if(i<Math.ceil(this.nodeLength/2)){//ååé¨å156 console.log("æ¥11")157 for(var j=1;j<i;j++){158 node=node.next159 }160 node=node.next161 }else{//ååé¨å162 console.log("æ¥22")163 for(var j=this.nodeLength;j>i;j--){164 node=node.prev165 }166 node=node.prev167 }168 return node.value169 }170 selectByValue() {171 //å¨çº¿æ§è¡¨ä¸æ¥æ¾ä¸ç»å®å¼eç¸ççå
ç´ 172 //æ¥æ¾æåï¼è¿å该å
ç´ å¨è¡¨ä¸çä½ç½®173 }...
orderList.js
Source:orderList.js
1// 线æ§è¡¨ç顺åºåå¨2class orderList {3 constructor() {4 this.init()5 }6 dataType(node) {7 return node8 }9 init() {10 // åå§åæä½ï¼å»ºç«ä¸ä¸ªç©ºç线æ§è¡¨11 this.list = []12 this.listLength = 10;13 this.nodeLength = this.list.length14 }15 reset() {16 //å°çº¿æ§è¡¨æ¸
空17 this.list = []18 this.listLength = 10;19 this.nodeLength = this.list.length20 }21 getLength() {22 //è¿å线æ§è¡¨çå
ç´ ä¸ªæ°23 return this.nodeLength24 }25 isEmpty() {26 // è¥çº¿æ§è¡¨ä¸ºç©ºï¼è¿åtrueï¼å¦åè¿åfalse27 if (this.nodeLength == 0) {28 return true29 } else {30 return false31 }32 }33 insert(i, value) {34 //å¨çº¿æ§è¡¨ç第i个ä½ç½®æå
¥æ°å
ç´ 35 //iå¼å¨æ£å¸¸èå´å
36 if (i < 1 || i > this.nodeLength + 1 || i > this.listLength) {37 return 'error'38 }39 if (this.nodeLength == this.listLength) {40 return 'error'41 }42 //[1,2,3,4,5]43 if (i != this.nodeLength + 1) {44 //ä¸æ¯å¨æåé¢45 for (var j = this.nodeLength; j >= i; j--) {46 this.list[j] = this.list[j - 1]47 }48 }49 this.list[i - 1] = this.dataType(value)50 this.nodeLength = this.list.length51 return 'success'52 }53 delete(i) {54 //å é¤çº¿æ§è¡¨ä¸ç¬¬i个ä½ç½®çå
ç´ å¹¶è¿åå
ç´ å¼55 //线æ§è¡¨é¿åº¦ä¸ä¸º0ï¼iå¼å¨æ£å¸¸èå´å
56 if (this.nodeLength == 0 || i < 1 || i > this.nodeLength) {57 return 'error'58 }59 //[1,2,3,4,5]60 var tmp = this.list[i - 1]61 if (i != this.nodeLength) {62 //iä¸æ¯æåä¸ä¸ª63 for (var j = i; j < this.nodeLength; j++) {64 this.list[j - 1] = this.list[j]65 }66 } 67 this.nodeLength = --this.list.length;68 return tmp69 }70 update(i, value) {71 //ä¿®æ¹çº¿æ§è¡¨ä¸ç¬¬i个ä½ç½®çå
ç´ å¹¶è¿ååå
ç´ å¼72 //线æ§è¡¨é¿åº¦ä¸ä¸º0ï¼iå¼å¨æ£å¸¸èå´å
73 if (this.nodeLength == 0 || i < 1 || i > this.nodeLength) {74 return 'error'75 }76 var tmp = this.list[i - 1]77 this.list[i - 1] = this.dataType(value)78 return tmp79 }80 selectByKey(i) {81 //å°çº¿æ§è¡¨ä¸ç¬¬i个ä½ç½®çå
ç´ å¼è¿å82 //线æ§è¡¨é¿åº¦ä¸ä¸º0ï¼iå¼å¨æ£å¸¸èå´å
83 if (this.nodeLength == 0 || i < 1 || i > this.nodeLength) {84 return 'error'85 }86 return this.list[i - 1]87 }88 selectByValue() {89 //å¨çº¿æ§è¡¨ä¸æ¥æ¾ä¸ç»å®å¼eç¸ççå
ç´ 90 //æ¥æ¾æåï¼è¿å该å
ç´ å¨è¡¨ä¸çä½ç½®91 //æ¥æ¾å¤±è´¥ï¼è¿å092 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.getLocations(function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7 if (err) return console.error(err);8 console.log(data);9});10wpt.getTestStatus('150412_3M_1e8a8f9c9f9d0c5e5c8f5a5f5c5e5b5c', function(err, data) {11 if (err) return console.error(err);12 console.log(data);13});14wpt.getTestResults('150412_3M_1e8a8f9c9f9d0c5e5c8f5a5f5c5e5b5c', function(err, data) {15 if (err) return console.error(err);16 console.log(data);17});18wpt.getTestResults('150412_3M_1e8a8f9c9f9d0c5e5c8f5a5f5c5e5b5c', function(err, data) {19 if (err) return console.error(err);20 console.log(data);21});22wpt.getHAR('150412_3M_1e8a8f9c9f9d0c5e5c8f5a5f5c5e5b5c', function(err, data) {23 if (err) return console.error(err);24 console.log(data);25});26wpt.getTesters(function(err, data) {27 if (err) return console.error(err);28 console.log(data);29});30wpt.getTesters('Dulles:Chrome', function(err, data) {31 if (err) return console.error(err);32 console.log(data);33});34wpt.getTesters('Dulles', function(err, data) {35 if (err) return console.error(err);36 console.log(data);37});38wpt.getTesters('Chrome', function(err, data) {39 if (err) return console.error(err);40 console.log(data);41});42wpt.getTesters('Dulles:Chrome', function(err, data) {
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(url, {4}, function(err, data) {5 if (err) return console.log(err);6 var testId = data.data.testId;7 wpt.getTestResults(testId, function(err, data) {8 if (err) return console.log(err);9 console.log(data.data.median.firstView.nodeLength);10 });11});
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.get(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var page = wptools.page('Barack Obama');8page.get(function(err, resp) {9 console.log(resp);10});11var wptools = require('wptools');12var page = wptools.page('Barack Obama');13page.get(function(err, resp) {14 console.log(resp);15});16var wptools = require('wptools');17var page = wptools.page('Barack Obama');18page.get(function(err, resp) {19 console.log(resp);20});21var wptools = require('wptools');22var page = wptools.page('Barack Obama');23page.get(function(err, resp) {24 console.log(resp);25});26var wptools = require('wptools');27var page = wptools.page('Barack Obama');28page.get(function(err, resp) {29 console.log(resp);30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.get(function(err, resp) {34 console.log(resp);35});
Using AI Code Generation
1var wpt = require('webpagetest');2var url = process.argv[2];3var location = process.argv[3];4var browser = process.argv[4];5var runs = process.argv[5];6var key = process.argv[6];7var wpt = new WebPageTest('www.webpagetest.org', key);8var testId;9var results;10wpt.runTest(url, {11}, function(err, data) {12 if (err) return console.error(err);13 console.log('Test ID: %s', data.data.testId);14 testId = data.data.testId;15 wpt.getTestStatus(testId, function(err, data) {16 if (err) return console.error(err);17 console.log('Test Status: %s', data.data.statusText);18 if (data.data.statusText === 'Test Complete') {19 wpt.getTestResults(testId, function(err, data) {20 if (err) return console.error(err);21 results = data.data.runs[1].firstView;22 console.log('Test Results: %s', testUrl + testId);23 console.log('Speed Index: %s', results.SpeedIndex);24 console.log('Visual Complete: %s', results.VisualComplete);25 console.log('Speed Index: %s', results.SpeedIndex);26 console.log('Time To First Byte: %s', results.TTFB);27 console.log('Start Render: %s', results.render);28 console.log('Fully Loaded: %s', results.fullyLoaded);29 console.log('Requests: %s', results.requests);30 console.log('Bytes In: %s', results.bytesIn);31 console.log('Bytes Out: %s', results.bytesOut);32 console.log('Connections: %s', results.connections);33 console.log('Dom Elements: %s', results.domElements);34 console.log('Title: %s', results.title);35 console.log('Doc Complete: %s', results.docTime);36 console.log('Load Time: %s', results.loadTime);37 console.log('Last Visual Change: %s',
Using AI Code Generation
1var wpt = require('./wpt');2var wptInstance = new wpt();3 if(err){4 console.log(err);5 }else{6 console.log(data);7 }8});9var wpt = require('./wpt');10var wptInstance = new wpt();11 if(err){12 console.log(err);13 }else{14 console.log(data);15 }16});17var wpt = require('./wpt');18var wptInstance = new wpt();19 if(err){20 console.log(err);21 }else{22 console.log(data);23 }24});25var wpt = require('./wpt');26var wptInstance = new wpt();27wptInstance.result(123456789, function(data, err){28 if(err){29 console.log(err);30 }else{31 console.log(data);32 }33});
Using AI Code Generation
1var wpt = require('webpagetest');2var api = new wpt('A.9a9b9c9d9e9f9g9h9i9j9k9l9m9n9o9p9q9r9s9t9u9v9w9x9y9z');3api.runTest(testURL, {4}, function(err, data) {5 if (err) return console.error(err);6 console.log('Test Results: ' + data.data.runs[1].firstView.SpeedIndex);7 console.log('Test Results: ' + data.data.runs[1].firstView.SpeedIndex);8 console.log('Test Results: ' + data.data.runs[1].firstView.SpeedIndex);9});
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!!