Implementing a voting simple voting sytem in vue JS

I want to develop a voting system in vuejs . I created the mechanism to fill the stars and count it by filling the star or not when hovering or clicking on the star, but it doesn’t work.

vue component

<template>
   <h2>Voting system</h2>
<div>
  <span class="fas fa-star" data-star="1"></span>
  <span class="fa fa-star" data-star="2"></span>
  <span class="fas fa-star" data-star="3"></span>
  <span class="fas fa-star" data-star="4"></span>
  <span class="fas fa-star" data-star="5"></span>
  &nbsp; rating: <span class="rating">-</span>
</div>
</template>
<script>
   export default {
     name: "MyVotingSystem",
     data () {
       return {
         allStar:undefined,
         mystar:undefined
       }
     },
     computed:{
     },
     methods: {
       vote() {
         this.allStar = document.querySelectorAll(".fa-star");
         this.mystar = document.querySelector(".rating");
         const rating = document.querySelector(".rating");
         this.allStar.forEach((star) => {
             star.addEventListener("click", saveRating);
             star.addEventListener("mouseover", addCSS);
             star.addEventListener("mouseleave", removeCSS);
           });
       },
       saveRating(e) {
      removeEventListenersToAllStars();
      rating.innerText = e.target.dataset.star;
      this.mystar = rating.innerText
      },
      removeEventListenersToAllStars() {
        this.allStar.forEach((star) => {
       star.removeEventListener("click", saveRating);
       star.removeEventListener("mouseover", addCSS);
       star.removeEventListener("mouseleave", removeCSS);
       });
      },
     addCSS(e, css = "checked") {
       const overedStar = e.target;
       overedStar.classList.add(css);
       const previousSiblings = getPreviousSiblings(overedStar);
       console.log("previousSiblings", previousSiblings);
       previousSiblings.forEach((elem) => elem.classList.add(css));
       },
      removeCSS(e, css = "checked") {
        const overedStar = e.target;
        overedStar.classList.remove(css);
        const previousSiblings = getPreviousSiblings(overedStar);
        previousSiblings.forEach((elem) => elem.classList.remove(css));
          },
         getPreviousSiblings(elem) {
            console.log("elem.previousSibling", elem.previousSibling);
            let sibs = [];
            const spanNodeType = 1;
           while ((elem = elem.previousSibling)) {
                if (elem.nodeType === spanNodeType) {
               sibs = [elem, ...sibs];
                  }
           }
              return sibs;
       }
     }
   }
</script>
<style>
     .checked {
        color: orange;
     }
</style>

At the level of the console of my browser, I have no error on my code.
When I click on a star or I hover nothing happens and does not count the number of votes 1 if I click the first star, two if I click the second star and so on

Do you have an idea?

is it anti-pattern to append .current after useRef in react

I’ve recently been debugging some old React code developed by my colleagues and noticed that they would declare some useRef‘s inside their functional components like this:

const refName = useRef(...).current;

This isn’t the first time I’ve seen ref‘s declared like this in React community, but it seems to be rare.

I can only assume that they’ve done this so that they only have to reference it by the variable name further down the line – as opposed to variableName.current.

So, this got me wondering: other than making the code a little bit cleaner, are there any clear downsides or benefits to declaring references this way?

Is it possible to loop through multiple ID’S to change an attribute

<script type="text/javascript">
    var packetStorageNum = 0;

    function increase_stored(){
        packetStorageNum++;
        if(packetStorageNum>6){
            packetStorageNum = 6
        }
    }
    function decrease_stored(){
        packetStorageNum--;
        if(packetStorageNum<0){
            packetStorageNum = 0
        }
    }
    function run()
    {
        for(let i = 1;i<packetStorageNum+1;i++){
            document.getElementById('i').style.display='block';
        }
        
    }
</script>
<body>
    <div class="container">
        <p>number of packets in storage:</p>
        <div class="buttons">
            <input type="button" onClick="increase_stored()" value="Increase"/>
            <input type="button" onClick="decrease_stored()" value="Decrease"/>
        </div>
        <input type="button" onClick="run()" value="Run"/>
    </div>

    <div>
        <div><img src="images/box.jfif" alt="" id="1" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="2" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="3" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="4" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="5" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="6" style="display:none ;"></div>         
    </div>
</body>

The code is to ‘turn on’ certain images as the increase button is clicked and to hide them when its not. I gave the boxes id’s of numbers and was trying to use a For loop to go through the numbers so when the value of boxes is say 5, box 1-5 will be visible.

How to create custom HTMLElement using class extends in JavaScript HTML

Is it possible to create custom HTMLElement using class?

Whenever I’m creating unknown element, the constructor is unknown element (obviously).

document.createElement("hello");
// return value: <hello></hello>
// constructor: HTMLUnknownElement

Can i create my own HTMLElement using class?

class HTMLHelloElement extends HTMLElement {
  //...
}
document.createElement("hello");
// return value: <hello></hello>
// constructor: HTMLHelloElement

HTML input range slider is affecting the wrong D3 chart

I have two D3 edge bundle charts, one on top of the other (CSS grid). For the top chart (id: edgeB) I have a div input style slider that changes the tension (amount of curve) of the node lines. It should affect the top chart only. Currently, the slider associated with the top chart is affecting the bottom most chart (id: edgeBTwo). I’ve tried including the correct div id but it seems to have no effect. I’m thinking that it is affecting the most recently created D3 chart but I’m not sure how to change this behavior.

Here is all of my code.

<!DOCTYPE html>
<html>
<head>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="icon" type="globe_icon.png">
    <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>

    <style type="text/css">

        body {
            padding: 90px;
            margin: 0px;
            height: 100%;
        }
        html,
        .grid-container {
            display: grid;
            grid-template-columns: 1fr;
            grid-template-rows: auto auto;
            background-color: #ffffff;
            padding: 10px;
            grid-row-gap: 10px;
          }
        .grid-item1 {
            background-color: rgb(255, 255, 255);
            border: 5px solid rgba(255, 0, 0, 0.8);
            padding: 15px;
            font-size: 12px;
            text-align: left;
            grid-row-gap: 10px;
            font: 8pt "Helvetica Neue", Arial, Helvetica, sans-serif;
            }
        .grid-item2 {
            background-color: rgb(255, 255, 255);
            border: 5px solid rgba(234, 0, 255, 0.8);
            padding: 15px;
            font-size: 12px;
            text-align: left;
            grid-row-gap: 10px;
            font: 8pt "Helvetica Neue", Arial, Helvetica, sans-serif;
            }
        .wrapword {
            white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
            white-space: -webkit-pre-wrap;          /* Chrome & Safari */ 
            white-space: -pre-wrap;                 /* Opera 4-6 */
            white-space: -o-pre-wrap;               /* Opera 7 */
            white-space: pre-wrap;                  /* CSS3 */
            word-wrap: break-word;                  /* Internet Explorer 5.5+ */
            word-break: break-all;
            white-space: normal;
        }
        path.arc {
            cursor: move;
            fill: #000000;
          }
          .node {
            font: 300 9 "Helvetica Neue", Helvetica, Arial, sans-serif;
            fill: rgb(0, 0, 0);
          }
          .node:hover {
            fill: rgb(132, 236, 255);
          }
          .node:hover,
          .node--source,
          .node--target {
            font-weight: 700;
          }
          .link {
            fill: none;
            stroke: #1f77b4;
            stroke-opacity: .5;
            pointer-events: none;
          }
          .link.source, .link.target {
            stroke-opacity: .8;
            stroke-width: 2px;
          }
          .node.target {
            fill: #d62728 !important;
          }
          .link.source {
            stroke: #d62728;
          }
          .node.source {
            fill: #00ff40;
          }
          .link.target {
            stroke: #00ff40;
          }
    </style>


</head>
<body>

    <div class="grid-container"></div>
        <div class="grid-item1" id="edgeB">
            <div id="edgeB" style="position:absolute;bottom: 2%;;font-size:16px;">Tension: <input style="position:relative;top:3px;" type="range" min="0" max="100" value="85"></div>
            <script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script>
            <script type="text/javascript" src="packages.js"></script>
            <script>
            (function chart1(){
                color = d3.scale.category10(); 
                var w = 700,
                    h = 700,
                    rx = w / 2.1,
                    ry = h / 2.1,
                    m0,
                    rotate = 0
                  pi = Math.PI;
            
                var splines = [];
            
                var cluster = d3.layout.cluster()
                    .size([360, ry - 180])
                    .sort(function(a, b) {
                        return d3.ascending(a.key, b.key);
                    });
            
                var bundle = d3.layout.bundle();
            
                var line = d3.svg.line.radial()
                    .interpolate("bundle")
                    .tension(.8)
                    .radius(function(d) {
                        return d.y;
                    })
                    .angle(function(d) {
                        return d.x / 180 * Math.PI;
                    });
            
                // Chrome 15 bug: <http://code.google.com/p/chromium/issues/detail?id=98951>
                var div = d3.select("#edgeB")
                
                    .style("width", w + "px")
                    .style("height", w + "px")
                    .style("position", "relative");
            
                var svg = div.append("svg:svg")
                    .attr("width", 700)
                    .attr("height", 700)
                    .append("svg:g")
                    .attr("transform", "translate(" + rx + "," + ry + ")");
            
                svg.append("svg:path")
                    .attr("class", "arc")
                    .attr("d", d3.svg.arc().outerRadius(ry - 180).innerRadius(0).startAngle(0).endAngle(2 * Math.PI))
                    .on("mousedown", mousedown);
            
                d3.json("flare_year.json", function(classes) {
            
                    var nodes = cluster.nodes(packages.root(classes)),
                        links = packages.imports(nodes),
                        splines = bundle(links);
            
                    var path = svg.selectAll("path.link")
                        .data(links)
                        .enter().append("svg:path")
                        .attr("class", function(d) {
                            return "link source-" + d.source.key + " target-" + d.target.key;
                        })
                        .attr("d", function(d, i) {
                            return line(splines[i]);
                        });
            
                    var groupData = svg.selectAll("g.group")
                        .data(nodes.filter(function(d) {
                          return (d.key == '1970-1979' || d.key == '1980-1989' || d.key == '1990-1999' || d.key == '2000-2009' || d.key == '2010-2019') && d.children;
          
                        }))
                        .enter().append("group")
                        .attr("class", "group");
            
                    var groupArc = d3.svg.arc()
                        .innerRadius(ry - 177)
                        .outerRadius(ry - 157)
                        .startAngle(function(d) {
                            return (findStartAngle(d.__data__.children) - 2.3) * pi / 180;
                        })
                        .endAngle(function(d) {
                            return (findEndAngle(d.__data__.children) + 2.3) * pi / 180;
                        });        
            
                    svg.selectAll("g.arc")
                        .data(groupData[0])
                        .enter().append("svg:path")
                        .attr("d", groupArc)
                        .attr("class", "groupArc")
                        .attr("id", function(d, i) {console.log(d.__data__.key); return d.__data__.key;})
                        .style("fill", function(d, i) {return color(i);})
                        .style("fill-opacity", 0.5)
                        .each(function(d,i) {
            
                            var firstArcSection = /(^.+?)L/;
            
                            var newArc = firstArcSection.exec( d3.select(this).attr("d") )[1];
            
                            newArc = newArc.replace(/,/g , " ");
            
                            svg.append("path")
                                .attr("class", "hiddenArcs")
                                .attr("id", "hidden"+d.__data__.key)
                                .attr("d", newArc)
                                .style("fill", "none");
                        });
    
                    svg.selectAll(".arcText")
                        .data(groupData[0])
                        .enter().append("text")
                        .attr("class", "arcText")
                        .attr("dy", 12)
                        .append("textPath")
                        .attr("startOffset","50%")
                        .style("text-anchor","middle")
                        .attr("xlink:href",function(d,i){return "#hidden" + d.__data__.key;})
                        .text(function(d){return d.__data__.key;});    
            
                    svg.selectAll("g.node")
                        .data(nodes.filter(function(n) {
                            return !n.children;
                        }))
                        .enter().append("svg:g")
                        .attr("class", "node")
                        .attr("id", function(d) {
                            return "node-" + d.key;
                        })
                        .attr("transform", function(d) {
                            return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
                        })
                        .append("svg:text")
                        .attr("dx", function(d) {
                            return d.x < 180 ? 25 : -25;
                        })
                        .attr("dy", ".31em")
                        .attr("text-anchor", function(d) {
                            return d.x < 180 ? "start" : "end";
                        })
                        .attr("transform", function(d) {
                            return d.x < 180 ? null : "rotate(180)";
                        })
                        .text(function(d) {
                            return d.key.replace(/_/g, ' ');
                        })
                        .on("mouseover", mouseover)
                        .on("mouseout", mouseout);
            
                    d3.select("input[type=range]").on("change", function() {
                        line.tension(this.value / 100);
                        path.attr("d", function(d, i) {
                            return line(splines[i]);
                        });
                    });
                });
            
                d3.select(window)
                    .on("mousemove", mousemove)
                    .on("mouseup", mouseup);
            
                    function mouse(e) {
                        return [e.pageX - rx, e.pageY - ry];
                      }
                      
                      function mousedown() {
                        m0 = mouse(d3.event);
                        d3.event.preventDefault();
                      }
                      
                      function mousemove() {
                        if (m0) {
                          var m1 = mouse(d3.event),
                              dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI;
                          div.style("-webkit-transform", "translate3d(0," + (ry - rx) + "px,0)rotate3d(0,0,0," + dm + "deg)translate3d(0," + (rx - ry) + "px,0)");
                        }
                      }
                      
                      function mouseup() {
                        if (m0) {
                          var m1 = mouse(d3.event),
                              dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI;
                      
                          rotate += dm;
                          if (rotate > 360) rotate -= 360;
                          else if (rotate < 0) rotate += 360;
                          m0 = null;
                      
                          div.style("-webkit-transform", "rotate3d(0,0,0,0deg)");
                      
                          svg.attr("transform", "translate(" + rx + "," + ry + ")rotate(" + rotate + ")")
                            .selectAll("g.node text")
                              .attr("dx", function(d) { return (d.x + rotate) % 360 < 180 ? 25 : -25; })
                              .attr("text-anchor", function(d) { return (d.x + rotate) % 360 < 180 ? "start" : "end"; })
                              .attr("transform", function(d) { return (d.x + rotate) % 360 < 180 ? null : "rotate(180)"; });
                        }
                      }
            
                function mouseover(d) {
                    svg.selectAll("path.link.target-" + d.key)
                        .classed("target", true)
                        .each(updateNodes("source", true));
            
                    svg.selectAll("path.link.source-" + d.key)
                        .classed("source", true)
                        .each(updateNodes("target", true));
                }
            
                function mouseout(d) {
                    svg.selectAll("path.link.source-" + d.key)
                        .classed("source", false)
                        .each(updateNodes("target", false));
            
                    svg.selectAll("path.link.target-" + d.key)
                        .classed("target", false)
                        .each(updateNodes("source", false));
                }
            
                function updateNodes(name, value) {
                    return function(d) {
                        if (value) this.parentNode.appendChild(this);
                        svg.select("#node-" + d[name].key).classed(name, value);
                    };
                }
            
                function cross(a, b) {
                    return a[0] * b[1] - a[1] * b[0];
                }
            
                function dot(a, b) {
                    return a[0] * b[0] + a[1] * b[1];
                }
            
                function findStartAngle(children) {
                    var min = children[0].x;
                    children.forEach(function(d) {
                        if (d.x < min)
                            min = d.x;
                    });
                    return min;
                }
            
                function findEndAngle(children) {
                    var max = children[0].x;
                    children.forEach(function(d) {
                        if (d.x > max)
                            max = d.x;
                    });
                    return max;
                }}())
            </script>     
        </div>
        <div class="grid-item2" id="edgeBTwo">
            <script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script>
            <script type="text/javascript" src="packages.js"></script>
            <script>
            (function chart2(){
                color = d3.scale.category10(); 
                var w = 700,
                    h = 700,
                    rx = w / 2.1,
                    ry = h / 2.1,
                    m0,
                    rotate = 0
                  pi = Math.PI;
            
                var splines = [];
            
                var cluster = d3.layout.cluster()
                    .size([360, ry - 180])
                    .sort(function(a, b) {
                        return d3.ascending(a.key, b.key);
                    });
            
                var bundle = d3.layout.bundle();
            
                var line = d3.svg.line.radial()
                    .interpolate("bundle")
                    .tension(.8)
                    .radius(function(d) {
                        return d.y;
                    })
                    .angle(function(d) {
                        return d.x / 180 * Math.PI;
                    });
            
                // Chrome 15 bug: <http://code.google.com/p/chromium/issues/detail?id=98951>
                var div = d3.select("#edgeBTwo")
                
                    .style("width", w + "px")
                    .style("height", w + "px")
                    .style("position", "relative");
            
                var svg = div.append("svg:svg")
                    .attr("width", 700)
                    .attr("height", 700)
                    .append("svg:g")
                    .attr("transform", "translate(" + rx + "," + ry + ")");
            
                svg.append("svg:path")
                    .attr("class", "arc")
                    .attr("d", d3.svg.arc().outerRadius(ry - 180).innerRadius(0).startAngle(0).endAngle(2 * Math.PI))
                    .on("mousedown", mousedown);
            
                d3.json("flare_test.json", function(classes) {
            
                    var nodes = cluster.nodes(packages.root(classes)),
                        links = packages.imports(nodes),
                        splines = bundle(links);
            
                    var path = svg.selectAll("path.link")
                        .data(links)
                        .enter().append("svg:path")
                        .attr("class", function(d) {
                            return "link source-" + d.source.key + " target-" + d.target.key;
                        })
                        .attr("d", function(d, i) {
                            return line(splines[i]);
                        });
            
                    var groupData = svg.selectAll("g.group")
                        .data(nodes.filter(function(d) {
                          return (d.key == '1970-1979' || d.key == 'Low' || d.key == 'Medium' || d.key == 'High') && d.children;
          
                        }))
                        .enter().append("group")
                        .attr("class", "group");
            
                    var groupArc = d3.svg.arc()
                        .innerRadius(ry - 177)
                        .outerRadius(ry - 157)
                        .startAngle(function(d) {
                            return (findStartAngle(d.__data__.children) - 2.3) * pi / 180;
                        })
                        .endAngle(function(d) {
                            return (findEndAngle(d.__data__.children) + 2.3) * pi / 180;
                        });        
            
                    svg.selectAll("g.arc")
                        .data(groupData[0])
                        .enter().append("svg:path")
                        .attr("d", groupArc)
                        .attr("class", "groupArc")
                        .attr("id", function(d, i) {console.log(d.__data__.key); return d.__data__.key;})
                        .style("fill", function(d, i) {return color(i);})
                        .style("fill-opacity", 0.5)
                        .each(function(d,i) {
            
                            var firstArcSection = /(^.+?)L/;
            
                            var newArc = firstArcSection.exec( d3.select(this).attr("d") )[1];
            
                            newArc = newArc.replace(/,/g , " ");
            
                            svg.append("path")
                                .attr("class", "hiddenArcs")
                                .attr("id", "hidden"+d.__data__.key)
                                .attr("d", newArc)
                                .style("fill", "none");
                        });
                    svg.selectAll(".arcText")
                        .data(groupData[0])
                        .enter().append("text")
                        .attr("class", "arcText")
                        .attr("dy", 12)
                        .append("textPath")
                        .attr("startOffset","50%")
                        .style("text-anchor","middle")
                        .attr("xlink:href",function(d,i){return "#hidden" + d.__data__.key;})
                        .text(function(d){return d.__data__.key;});    
            
                    svg.selectAll("g.node")
                        .data(nodes.filter(function(n) {
                            return !n.children;
                        }))
                        .enter().append("svg:g")
                        .attr("class", "node")
                        .attr("id", function(d) {
                            return "node-" + d.key;
                        })
                        .attr("transform", function(d) {
                            return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
                        })
                        .append("svg:text")
                        .attr("dx", function(d) {
                            return d.x < 180 ? 25 : -25;
                        })
                        .attr("dy", ".31em")
                        .attr("text-anchor", function(d) {
                            return d.x < 180 ? "start" : "end";
                        })
                        .attr("transform", function(d) {
                            return d.x < 180 ? null : "rotate(180)";
                        })
                        .text(function(d) {
                            return d.key.replace(/_/g, ' ');
                        })
                        .on("mouseover", mouseover)
                        .on("mouseout", mouseout);
            
                    d3.select("input[type=range]").on("change", function() {
                        line.tension(this.value / 100);
                        path.attr("d", function(d, i) {
                            return line(splines[i]);
                        });
                    });
                });
            
                d3.select(window)
                    .on("mousemove", mousemove)
                    .on("mouseup", mouseup);
            
                    function mouse(e) {
                        return [e.pageX - rx, e.pageY - ry];
                      }
                      
                      function mousedown() {
                        m0 = mouse(d3.event);
                        d3.event.preventDefault();
                      }
                      
                      function mousemove() {
                        if (m0) {
                          var m1 = mouse(d3.event),
                              dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI;
                          div.style("-webkit-transform", "translate3d(0," + (ry - rx) + "px,0)rotate3d(0,0,0," + dm + "deg)translate3d(0," + (rx - ry) + "px,0)");
                        }
                      }
                      
                      function mouseup() {
                        if (m0) {
                          var m1 = mouse(d3.event),
                              dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI;
                      
                          rotate += dm;
                          if (rotate > 360) rotate -= 360;
                          else if (rotate < 0) rotate += 360;
                          m0 = null;
                      
                          div.style("-webkit-transform", "rotate3d(0,0,0,0deg)");
                      
                          svg.attr("transform", "translate(" + rx + "," + ry + ")rotate(" + rotate + ")")
                            .selectAll("g.node text")
                              .attr("dx", function(d) { return (d.x + rotate) % 360 < 180 ? 25 : -25; })
                              .attr("text-anchor", function(d) { return (d.x + rotate) % 360 < 180 ? "start" : "end"; })
                              .attr("transform", function(d) { return (d.x + rotate) % 360 < 180 ? null : "rotate(180)"; });
                        }
                      }
                function mouseover(d) {
                    svg.selectAll("path.link.target-" + d.key)
                        .classed("target", true)
                        .each(updateNodes("source", true));
            
                    svg.selectAll("path.link.source-" + d.key)
                        .classed("source", true)
                        .each(updateNodes("target", true));
                }
            
                function mouseout(d) {
                    svg.selectAll("path.link.source-" + d.key)
                        .classed("source", false)
                        .each(updateNodes("target", false));
            
                    svg.selectAll("path.link.target-" + d.key)
                        .classed("target", false)
                        .each(updateNodes("source", false));
                }
            
                function updateNodes(name, value) {
                    return function(d) {
                        if (value) this.parentNode.appendChild(this);
                        svg.select("#node-" + d[name].key).classed(name, value);
                    };
                }
                function cross(a, b) {
                    return a[0] * b[1] - a[1] * b[0];
                }
                function dot(a, b) {
                    return a[0] * b[0] + a[1] * b[1];
                }
                function findStartAngle(children) {
                    var min = children[0].x;
                    children.forEach(function(d) {
                        if (d.x < min)
                            min = d.x;
                    });
                    return min;
                }
                function findEndAngle(children) {
                    var max = children[0].x;
                    children.forEach(function(d) {
                        if (d.x > max)
                            max = d.x;
                    });
                    return max;
                }}());
            </script>     
        </div>
</body>
</html>

Here is my packages.js file and both data files needed to run the above code:

packages.js

(function() {
  packages = {

    // Lazily construct the package hierarchy from class names.
    root: function(classes) {
      var map = {};

      function find(name, data) {
        var node = map[name], i;
        if (!node) {
          node = map[name] = data || {name: name, children: []};
          if (name.length) {
            node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
            node.parent.children.push(node);
            node.key = name.substring(i + 1);
          }
        }
        return node;
      }

      classes.forEach(function(d) {
        find(d.name, d);
      });

      return map[""];
    },

    // Return a list of imports for the given array of nodes.
    imports: function(nodes) {
      var map = {},
          imports = [];

      // Compute a map from name to node.
      nodes.forEach(function(d) {
        map[d.name] = d;
      });

      // For each import, construct a link from the source to target node.
      nodes.forEach(function(d) {
        if (d.imports) d.imports.forEach(function(i) {
          imports.push({source: map[d.name], target: map[i]});
        });
      });

      return imports;
    }

  };
})();

flare_year.json

[
    {
        "name": "root.2010-2019.A",
        "imports": [
            "root.1990-1999.B",
        ]
    },
    {
        "name": "root.1990-1999.B",
        "imports": [
            "root.2010-2019.A",
        ]
    }
]

flare_test.json

[
    {
        "name": "root.High.A",
        "imports": [
            "root.Medium.F",
        ]
    },
    {
        "name": "root.Medium.F",
        "imports": [
            "root.High.A",
        ]
    }
]

Handlebars Templates

I am a bit stuck with a project I am working on. The whole thing is built with Handlebars templates, within the main template there are multiple partials. The issue I am having is sometimes when I try to query the template to rerender the page, it will come back null. In one function it works just fine, and in the next, it looks like it doesn’t exist. Everything is in a ready event. Is there any way to create the template and then not lose it again? I am finding it difficult to explain this so any help would be great.

There’s too much code to post but the outline is as such. There is the main template, and within that template, it references around 6 partial templates. Each template is in a script tag in the body. Obviously, the point of the partial is to be able to rerender with new and updated info when things change, but when I query the main template in some functions it’s found and others say it’s null. I have to use the project as it is, and the structure can’t be changed. Thanks for any help available.

Can I refactor this JavaScript code any further?

I am doing some JavaScript practice and tried writing a simple script that asks for the following details from a user:

  1. Username
  2. Password
  3. First Name
  4. Last Name
  5. Email
  6. Job Title

I then store all the details in an object. I am using alert() to display the messages and prompt() to ask the questions. There is no database integration, I am just learning how to write the JavaScript. My question then, is the code any good? Is there anything I could have done better or optimized in the context of the learning?

//Get user username
let username = prompt("Enter your username")
while (validateUsername(username) == false) {
    username = prompt("Enter your username")
}

//Validate username
function validateUsername(username) {
    if (username === null || username.length < 5 || username.length > 10 || username === "") {
        alert("Username must be from 5 to 10 characters. Try again!")
        return false
    } else {
        return true
    }
}

//Get user password
let userPassword = prompt("Enter your password")
let userPassConfirm = prompt("Confirm your passsword")
while (validatePassword(userPassword) == false) {
    userPassword = prompt("Password is invalid. Please try again!")
    userPassConfirm = prompt("Confirm your passsword")
}
while (userPassConfirm !== userPassword && userPassConfirm !== null) {
    userPassConfirm = prompt("Confirm password does not match, Try again.")
}

//Validate password
function validatePassword(userPassword) {
    if (userPassword == null || userPassword.length < 6 || userPassword.length > 20) {
        alert("Password must be from 6 to 20 characters. Try again!")
        return false
    } else {
        return true
    }
}

//Get user profile
let firstName = prompt("What's your First name?")
while (firstName === "") {
    alert("Your First name cannot be empty! Try again!")
    firstName = prompt("What's your First name?")
}

let lastName = prompt(`Hello ${firstName}, what's your Last name?`)
while (lastName == "") {
    alert("Your Last name cannot be empty! Try again!")
    lastName = prompt(`Hello ${firstName}, what's your Last name?`)
}

let userEmail = prompt(`Enter your email address, ${firstName}.`)
while (userEmail == "") {
    alert("Your email address cannot be empty! Try again!")
    userEmail = prompt(`Enter your email address, ${firstName}.`)
}

let userJobTitle = prompt("What is your job title?")
while (userJobTitle == "") {
    alert("Your job title cannot be empty! Try again!")
    userJobTitle = prompt("What is your job title?")
}

alert(`Great to finally meet you ${firstName} ${lastName}!`)

//Store user details in object
const userDetails = {username, userPassword, firstName, lastName, userEmail, userJobTitle}

//Display user details
alert(`Username: ${userDetails.username} n First Name: ${userDetails.firstName} n Last Name: ${userDetails.lastName} n Email: ${userDetails.userEmail} n Job Title: ${userDetails.userJobTitle}`)

console.log(`User Details: n Username: ${userDetails.username} n First Name: ${userDetails.firstName} n Last Name: ${userDetails.lastName} n Email: ${userDetails.userEmail} n Job Title: ${userDetails.userJobTitle}`)

How to paste clipboard into a channel using a photoshop script?

I’m trying to create a image RGB or CMYK using separate greyscale documents for each channel.
My current code copy all from greyscale document and paste in a new document creating a new layer for eachone. I don’t want that, I want copy from each document and paste into eachone channels new document, same as manual way, selecting each channel and clicking Edit->paste->paste especial->paste in place.

// Loop to copy each separate channel into a new merged document
for (var doc_index = 0; doc_index < 3; doc_index++ ){
//Switch documents 
app.activeDocument = split_channels[0];

// copy active layer from separate channel document
app.activeDocument.selection.selectAll();
app.activeDocument.selection.copy();

// close document whithout save 
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);

//select activeDocument
app.activeDocument = mergedDoc;

// reference to whole channels
//var channelIndex = doc_index;
var myChannels = app.activeDocument.channels;

// the channel must be visible to paste greyscale layer
myChannels[doc_index].visible= true;

// turn off the rest of channels    
for (var secondaryIndex = 0; secondaryIndex < myChannels.length; secondaryIndex++) {
    
    if (doc_index != secondaryIndex) {
        
        myChannels[secondaryIndex].visible= false
    }
}

//paste layer for each new document channel (no works correctly)
app.activeDocument.paste();
    
//reset the channel count after copy and close each document
var split_channels = app.documents;
}

thanks a lot for any suggestion

Is there a JavaScript library that acts as an Outlook, Gmail, etc. API?

I’m looking for a solution to send/receive emails in my web app (Angular). I’m not trying to implement an email sender, nor a client with UI.

I just need the same “core functionality” in my web app that e.g. Thunderbird or any other email client has that makes it possible to add an account of any email provider and it can then “write/read” your remote account – and also need methods for this.

I found one package actually: https://www.npmjs.com/package/webmail-api. Is this the way to go? Do you know others that support more email providers?

How does this work actually? I mean, is there some standardized way you communicate with email providers or all have different custom APIs and you as an email client developer continuously have to keep up with the changes and update your software when the guys at Outlook or Gmail make changes?

Can’t select radio button of list of object but the first one

i need to fill a quiz of questions (objects), every question have four choices of radio buttons, the question are displayed within a list of (questions) from servlet to jsp with jstl loop as seen below. so the problem is that i can select an answer only in the first question (element of the list).
here you can see better

my list of question here

<c:forEach var ="question" items="${question}" varStatus="loop"> 
         <div class="card border-info mb-4" id="lavida">

<div class="d-flex justify-content-between align-items-center card-header bg-primary text-white" id="q1">
  <span>Question ${question.numero}</span>     
  <button type="button" data-toggle="collapse" data-target="#q1${question.id_question}" aria-expanded="false" aria-controls="q1${question.id_question}" 
  class="btn btn-outline-light">          
  </button>
</div>

  <div id="q1${question.id_question}" class="collapse show" aria-labelledby="h1">
    <div class="card-body">
       <div class="col-11"> 
  
      <p class="fw-bold">${question.question}</p> 
        <div class="form-check">
          <input class="form-check-input" type="radio" name="q1" value="r1">
          <label class="form-check-label" >
            study of bones
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="q1" value="r2">
          <label class="form-check-label" >
            study of muscles
          </label>
        </div>

        <div class="form-check">
          <input class="form-check-input" type="radio" name="q1" value="r3">
          <label class="form-check-label" >
            study of architecture
          </label>
        </div>        
        <div class="form-check">
          <input class="form-check-input" type="radio" name="q1" value="r4">
          <label class="form-check-label" >
            science of languages
          </label>
        </div>
              
    </div>
  </div>
 </div> 
</div>
  </c:forEach>

how to map and read an array of objects in an api response (React)

i’m tring to build a Quizz React app using the (open trivia) api ,i got the api and asigned it to my state and i’m able to read part of it but when i’m tring to read an array inside the object abi i get an error ,can you pleas tell me what i’m doing wrong and how to deal with this in the future.
this is my App component:

function App(){
    const [quizz,setQuizz] = React.useState([])
    const [data,setData] = React.useState({
        quizzOn: true
    })
     React.useEffect(()=>{
         fetch("https://opentdb.com/api.php?amount=5&type=multiple").
        then(res => res.json()).
        then(apiData => {
            dataSetter(apiData)
        })},[])
     function dataSetter(obj){
         setQuizz(obj)
         
     }
     function toggle(){
         setData(prev => ({quizzOn:!prev.quizzOn}))
         };
         
    return(
        <div>
        {data.quizzOn && <StartFront onClick={toggle} arr={quizz ? quizz : []}/>}
        <Quizz arr={quizz}/>
        </div>
    )
}

and this is my Quizz compunent in which i’m tring to read the data:

function Quizz(props){
   const data = props.arr.results
   
   return(
        <div>
        <p>{data ? JSON.stringify(data) : "error"}</p>
        </div>
    )
}

this is working but anything i try after “results” give an error like:
props.arr.results[0].question

or:

const data = props.arr.results.map(obj => {
 return <p>{obj.question}</p>})

finally this the api im tring to read :

    {response_code: 0
, results: [{category: "History"
, type: "multiple"
, difficulty: "medium"
, question: "The seed drill was invented by which British inventor?"
, correct_answer: "Jethro Tull"
, incorrect_answers: ["Charles Babbage"
, "Isaac Newton"
, "J.J Thomson"
]
}
, {category: "Entertainment: Music"
, type: "multiple"
, difficulty: "medium"
, question: "Who is the Pink Floyd song &quot;Shine On You Crazy Diamond&quot; written about?"
, correct_answer: "Syd Barrett"
, incorrect_answers: ["John Lennon"
, "David Gilmour"
, "Floyd"
]
}
, {category: "Entertainment: Television"
, type: "multiple"
, difficulty: "hard"
, question: "In &quot;Star Trek&quot;, what is the Klingon delicacy of &quot;gagh&quot; made from?"
, correct_answer: "Serpent worms"
, incorrect_answers: ["Earthworms"
, "Spaghetti noodles"
, "Klingworms"
]
}}

Make twitchbot check if I said X before saying Y

I’m new to js and try setting up a twitch bot. All works fine for basic commands and connexion to chat.
But I would like to have the bot check if a user already said salut|bonjour|hey|bonsoir before saying banane.
If false, the bot would tell him Hey, tu dis pas bonjour toi?!! , if true she’d say on m'a appelée?

With this pc of code I wrote, even if I already said one of salut|bonjour|hey|bonsoir, bot only says Hey, tu dis pas bonjour toi?!! and doesn’t go to on m'a appelée?

What am I missing?
Thanks

var usersayhello = {};

client.on('message', (channel, user, message, self) => {
if(self) return;
message=message.toLowerCase();
message=' '+message+' ';

if(/[ ]+anita[ ?]+/.test(message)){
    
    if(/(salut|bonjour|hey|bonsoir)([ ]+)anita/.test(message)){
        usersayhello = true; 
        if(user.username == 'blablabla123'){
            var responsebonjour = [
                `Salut @${user.username}! Planquez-vous! Ca va encore troller sec`
        `Hey @${user.username}, tu voles aujourd'hui?`
            ];
        }
        else{
            var responsebonjour = [
                `Salut @${user.username}, je suis contente de te voir, tu vas bien?`,
                `Hey @${user.username}, t'es venu pour moi j'espère`,
                `Hello @${user.username}, comment vas-tu?`,
                `Tu ne peux vraiment pas te passer de moi, toi! ^^`
            ];
        }

client.say(channel,responsebonjour[Math.floor(Math.random()*responsebonjour.length)]);
}

if(message == ` banane ` && checkifusersayhello (channel,user,usersayhello)) {
    client.say(channel, `on m'a appelée?`);
}  

function checkifusersayhello(channel,user,usersayhello) {
    if (!usersayhello[user.username]){
    client.say(channel, `Hey, tu dis pas bonjour toi?!!`);
    return false;
    }
    return true;
}

Displaying data from api

i’m trying to learn a little bit of react
so i’m building this randon quote machine who gets the data from an api :

function App() {

 const [quoteData,setQuoteData] = useState({})
 useEffect(() => {
  fetch('https://type.fit/api/quotes')
  .then(res => res.json())
  .then(data => setQuoteData(data))
 },[])

my probleme is when i’m tryin to display the quote by accessing it with quoteData[0].text
it gives me an error specifically Uncaught TypeError
can anyone please tell me where is my mistake because i reached a dead end here

? Java Script how to change the input value

I have an iframe frame on my page. I want to do the following in Java Script
How to create episodes that you write from 1 to 30, you print a number after a number, not all of them, one batch.
In the input form in the velue = “” then you press the button automatically after each number

yahya00

**

yahya3