Validations using if else and hasClass statements in Cypress

I am trying to validate the set of titles for a component. Below is my Cypress code snippet:

it('Validate the titles of all the tiles', () => {
    cy.get('.bms-scoreboard__game-tile')
      .each(($el) => {
        if($el.hasClass('bms-scoreboard__game-tile--cancelled')) {
            $el.get('.bms-scoreboard__game-tile-status--cancelled')
               .invoke('text')
               .then((text) => {
                  expect(text).equals('Cancelled')
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--pre-game')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                    const gameTime = text.split(" ").pop()
                    expect(['AM', 'PM']).to.include(gameTime)
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--final')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const finalTitle = text.trim()
                   expect(finalTitle).to.be.oneOf(['Final','Final (OT)'])
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--ongoing')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const ongoingTitle = text.trim()
                   expect(ongoingTitle).equals('Ongoing')
               })
        }
    })
})

But I get an error message: ‘Cannot read properties of undefined (reading ‘invoke’)’.

It works fine if I try it with only if block.

How can you efficiently update the fill of GeoJson polygons in MapboxGL?

I’m building an application that will render a map with a large GeoJSON set (around 3MB). The map is a choropleth, and the different GeoJSON polygons are meant to be colored differently depending on the data that they “contain.”

The problem I’m running into is that I’m unsure how to separate the GeoJSON (e.g. polygon data) from the actual data. Let’s say we set the data like this (or as Mapbox recommends, just via the URL to a data source):

const { data } = await axios.post(sourceUrl, settings);
map.current.addSource("states", {
  type: "geojson",
  data,
}

The underlying data in this map will need to update frequently with user interaction. However, right now the GeoJSON contains both the data for the polygons (coordinates) and the properties (the data itself).

For instance, the user might click a checkbox, or type in a search parameter. This currently makes a GET to our DB, which runs a query and returns the new data. We could return a new GeoJSON object with this data added inside of it and call a .getSource("source").setData(newData) will all of the new GeoJSON, but that would be terribly inefficient. The polygons aren’t changing, only the data they contain is.

I’ve looked into data-driven styling, but that doesn’t appear to be what I need either. Our underlying data set for the map is far too large to be crammed into a single GeoJSON layer, we can’t transfer hundreds of MBs over the network in order to apply data-driven styles on the client.

How can we render GeoJSON polygons to the map just once, and then update their fill colors depending on how a different data set is changed?

Hamburger menu not working when I change class name using UseState in React

I am creating a navigation bar for a website, and everything is working fine, and the hamburger menu when you change screen size. However, I also made my navbar fixed as the user scrolls.

The hamburger menu works fine when you are scrolled to the top, but once you start scrolling, the hamburger doesn’t click.

If I change the initial state of ‘false’ to ‘true,’ it will work in reverse order .. so it will not work when at the top, but it will work when scrolling.

I have been trying to figure this out all day, and I have been attempting to find a solution, but I could not. If anyone could help me, It would be greatly appreciated.

Hamburger menu at the top working

Hamburger menu at the top working

enter image description here

When I scroll down the hamburger menu doesn’t click anymore

enter image description here

Navbar code:

function Navbar2() {
  const [scrolled, setScrolled] = useState(false);

  const canvasRef = useRef();
  const navLinksRef = useRef();
  const liRefAbout = useRef();
  const liRefServices = useRef();
  const liRefGallery = useRef();
  const liRefTestimonials = useRef();
  const liRefContact = useRef();

  // toggle mobile menu on icon click
  useEffect(() => {
    const burger = canvasRef.current;
    const nav = navLinksRef.current;
    const aboutLink = liRefAbout.current;
    const servicesLink = liRefServices.current;
    const galleryLink = liRefGallery.current;
    const testimonialsLink = liRefTestimonials.current;
    const contactLink = liRefContact.current;

    burger.addEventListener('click', () => {
      nav.classList.toggle('nav-active');
      aboutLink.classList.toggle('list-about-active');
      servicesLink.classList.toggle('list-services-active');
      galleryLink.classList.toggle('list-gallery-active');
      testimonialsLink.classList.toggle('list-testimonials-active');
      contactLink.classList.toggle('list-contact-active');
      burger.classList.toggle('toggle');
    });
  }, [scrolled]);

  // make navbar fixed on scroll
  const handleScroll = () => {
    const offset = window.scrollY;
    if (offset > 80) {
      setScrolled(true);
    } else if (offset < 80) {
      setScrolled(false);
    }
  };
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
  });

  let x = ['navbar'];
  if (scrolled) {
    x.push('scrolled');
  }

  return (
    <nav className={`navbar ${scrolled ? 'scrolled' : ''}`}>
........

Navbar CSS

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 8vh;
  background: transparent;
  transition: all 0.4s linear;

  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 900;
}

.scrolled {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(6px);
  width: 100%;
}

please help me to solve hash table and explain it [closed]

In the hash table below we use open addressing with linear probing to resolve collisions.
The hash function is h(x)=x(mod11). In the table x denotes the places of deleted elements.

     0     1      2     3    4    5    6    7    8    9    10
     11   34     24     x         x    6         x         x

When inserting number 12 what is distance between its hash value and its final position?

Select one or more:

A- 10

B- 1

C- 4

D- 3

E- 9

The JavaScript ‘clearInterval’ function does not appear to be working. Can anyone help me?

I have the following code which adjusts the size of two panels, one above the other. Move the mouse up and the top panel will get smaller while the bottom panel will get larger. It all seems to work well enough, however, on mouseup although the ‘clearInterval’ line appears to be executed, ‘interval’ is not reset and movement of the mouse still alters the panel sizes.

Can anyone point out where I have gone wrong or indeed indicate a better way to do this?

Thanks in advance.

document.addEventListener('DOMContentLoaded',function(event){
  document.querySelector('#partition').onmousedown = function(event){
    //Set a timer to check every millisecond the position of the mouse and asign that position to the panels
    var interval=setInterval(function(){
      onmousemove = function(e){
        document.getElementById('topPanel').style.height = e.clientY;
        document.getElementById('btmPanel').style.height = viewport_height - e.clientY - 10;
      }
      //check for mouse up and cancel timer.
      onmouseup = function(){
        clearInterval(interval); 
      }
    }, 100); // the above code is executed every 100 ms  
  }
});

why innerHTML is not able to set the value of id = ‘result’ field to show the interest ..?

[i am not able to get the desired output of getting the simple interest….here innerhtml is not responding to set the value of id = ‘result’ field……here i have posted my code part..

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Document</title>
<script type="text/javascript">
    function fun1()
    {
      var a = document.getElementById('p').value ;
      var b = document.getElementById('n').value ;
      var c = document.getElementById('r').value ;
      var result = document.getElementById('result');

      result.innerHTML = "The interest is" + (p*n*r/100) ;
    }
</script>
</head>
<body>

<form name="form1">
    <label> Enter Principal amount :
        <input type="text" id="p"><br>
    </label>

    <label> Enter no. of years :
        <input type="text" id="n"><br>
    </label>

    <label> Enter rate  :
        <input type="text" id="r"><br>
    </label>
   
    <button type="submit" onclick="fun1()"> calculate </button>

    <p id="result">
   </p>
  </form>

  <script type="text/javascript">
 
  </script>

  </body>
  </html>

][1]

JS Array Reduce with Merging Duplicate Nested Array

I have an array like this:

var myArray = [
    {
        "name": "walkway_lights",
        "title": "Brilliance Sequoia Pathlight",
        "subCat": "Area & Pathway Lights",
        "cat": "Fixture-Speaker-Sub",
        "msrp": 599,
        "accTotal": 50,
        "purchasePrice": 222.35,
        "totalPrice": 1222,
        "totalPurchasePrice": 468.7,
        "lightShadowColor": "warmWhite",
        "wattage": {
            "key": "-Mm46mr5KHJwLXsucsJK",
            "upPrice": 12,
            "value": "3.5w G4"
        },
        "selectedAccessory": [
            {
                "key": "-Mxa9Jt-9si0Bw7Zhj1S",
                "name": "Demo 1",
                "price": 5
            },
            {
                "key": "-Mxa9NUjMExUd8b5UgfU",
                "name": "Demo 2",
                "price": 10
            },
            {
                "key": "-Mxa9Vh4yBK9j-GNpA0v",
                "name": "Demo 4",
                "price": 20
            }
        ],
        "beam": {
            "key": "-Mm4B0FO34Ineht5O0sw",
            "value": "360"
        }
    },
    {
        "name": "walkway_lights",
        "title": "Brilliance Sequoia Pathlight",
        "type": "group",
        "subCat": "Area & Pathway Lights",
        "cat": "Fixture-Speaker-Sub",
        "msrp": 599,
        "accTotal": 15,
        "purchasePrice": 222.35,
        "totalPrice": 626,
        "totalPurchasePrice": 249.35,
        "lightShadowColor": "warmWhite",
        "wattage": {
            "key": "-Mm46mr5KHJwLXsucsJK",
            "upPrice": 12,
            "value": "3.5w G4"
        },
        "selectedAccessory": [
            {
                "key": "-Mxa9Jt-9si0Bw7Zhj1S",
                "name": "Demo 1",
                "price": 5
            },
            {
                "key": "-Mxa9NUjMExUd8b5UgfU",
                "name": "Demo 2",
                "price": 10
            },
            ,
            {
                "key": "-Mxa9ZUjMExUd3g5Ugfs",
                "name": "Demo 3",
                "price": 15
            }
        ],
        "beam": {
            "key": "-Mm4B0FO34Ineht5O0sw",
            "value": "360"
        }
    }
]

I need to reformat “myArray” in such a way that it nest all objects based “subCat” and then “subCat” inside “cat”. In those nested children, I am converting duplicate objects based on “name + lightShadowColor + wattage.value + beam.value” and I am adding a variable “count” to remove duplicate objects. I am able to come up with a solution like below:

let result = [], counter = {};
for (let item of myArray) {
    let countId;
    if(item.lightShadowColor && item.wattage) {
    countId = item.name + item.lightShadowColor + item.wattage.value + item.beam.value
    } else {
    countId = item.name
    }
    let a = [];
    if (counter[countId]) {
    counter[countId].count++;
    counter[countId].totalPrice = counter[countId].count * (counter[countId].msrp + counter[countId].wattage.upPrice)
    counter[countId].totalPurchasePrice = counter[countId].count * (counter[countId].purchasePrice + counter[countId].wattage.upPrice);
    continue
    }

    let cat = result.find(o => o.cat == item.cat);
    if (!cat) result.push(cat = { cat: item.cat, children: [] });
    let subCat = cat.children.find(o => o.subCat == item.subCat);
    if (!subCat) cat.children.push(subCat = { subCat: item.subCat, children: [] });
    item.count = 1;
    subCat.children.push(counter[countId] = item);
}
console.log(result)

The above code gives me output which I desire as below:

result = [
    {
        "cat": "Fixture-Speaker-Sub",
        "children": [
            {
                "subCat": "Area & Pathway Lights",
                "children": [
                    {
                        "count": 2
                        "name": "walkway_lights",
                        "title": "Brilliance Sequoia Pathlight",
                        "subCat": "Area & Pathway Lights",
                        "cat": "Fixture-Speaker-Sub",
                        "msrp": 599,
                        "accTotal": 50,
                        "purchasePrice": 222.35,
                        "totalPrice": 1222,
                        "totalPurchasePrice": 468.7,
                        "lightShadowColor": "warmWhite",
                        "wattage": {
                            "key": "-Mm46mr5KHJwLXsucsJK",
                            "upPrice": 12,
                            "value": "3.5w G4"
                        },
                        "selectedAccessory": [
                            {
                                "key": "-Mxa9Jt-9si0Bw7Zhj1S",
                                "name": "Demo 1",
                                "price": 5
                            },
                            {
                                "key": "-Mxa9NUjMExUd8b5UgfU",
                                "name": "Demo 2",
                                "price": 10
                            },
                            {
                                "key": "-Mxa9Vh4yBK9j-GNpA0v",
                                "name": "Demo 4",
                                "price": 20
                            }
                        ],
                        "beam": {
                            "key": "-Mm4B0FO34Ineht5O0sw",
                            "value": "360"
                        }
                    }
                ]
            }
        ]
    }
]

Now, I am trying to figure out how should I merge “selectedAccessory” array for duplicate objects. Any idea how should I merge those keys? Inside the result, I need “selectedAccessory” array like this:

"selectedAccessory": [
    //The below come from myArray first duplicate object
    {
        "key": "-Mxa9Jt-9si0Bw7Zhj1S",
        "name": "Demo 1",
        "price": 5
    },
    {
        "key": "-Mxa9NUjMExUd8b5UgfU",
        "name": "Demo 2",
        "price": 10
    },
    {
        "key": "-Mxa9Vh4yBK9j-GNpA0v",
        "name": "Demo 4",
        "price": 20
    },
    //The below come from myArray second duplicate object
    {     
        "key": "-Mxa9Jt-9si0Bw7Zhj1S",
        "name": "Demo 1",
        "price": 5
    },
    {
        "key": "-Mxa9NUjMExUd8b5UgfU",
        "name": "Demo 2",
        "price": 10
    },
    ,
    {
        "key": "-Mxa9ZUjMExUd3g5Ugfs",
        "name": "Demo 3",
        "price": 15
    }
],

img.src gives different URL than the one shown in inspector

When I was inspecting an webpage (namely, any web page from Wayback Machine), I found that any <img> element’s .src when you used in JS snippet (or console) would be the original URL, while in inspector it shows the one with archive.org prefix:

enter image description here

(Same goes for Firefox.)

How does this happen? I don’t even know this is possible.

Furthermore, how can you get the one that is shown in inspector?

TypeScript – using recursive generics properly

I am trying to use recursive generics in a way I can get a lot of help from editor.

Here is an example:

interface ServiceEndpointNode {
  self: string;
  context?: Record<string, ServiceEndpointNode>
}

const ServiceEndpoints: ServiceEndpointNode = {
  self: 'BASE_URL',
  context: {
    songs: {
      self: 'GET_SONGS',
      context: {
        getSong: {
          self: 'GET_SONG',
        },
        getContributors: {
          self: 'GET_CONTRIBUTORS',
        }
      }
    }
  }
}

This works properly and the structure is strict, but I don’t got help from the editor. For example I want help like:

ServiceEndpoints.context.songs.context.getsong.self

But because I only told the typing that the context should be a string I don’t really receiving help about the traversable object. I guess I need to be include some generics or something, but don’t know how to achieve that. 🙁

So I want to have to maintain this strict structure, yet get help from the editor for all the possible routes, keys, etc.

Question in the dom about deleting a specific element [closed]

im making a small comment section and want to add a delete comment feature which pops up a modal to confirm delete or cancel and when i click cancel it just saves the previous parent element like in this picture [1]: https://i.stack.imgur.com/DA4d3.jpg. whenever i click cancel it just keeps adding so i really have hard times figuring this out and i need a bit of direction here. here’s my code [2]: https://i.stack.imgur.com/F7432.jpg

Using a let in a for loop with setTimeout function

If the arguments to functions are passed by value in javascript how come the console.log() below seems to get its input by reference? Shouldn’t each time it is invoked inside setTimeout just the value of i be passed and not its reference?

let i;

for (i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

remove unwanted json value if not present inside the another json object in node js /javascript

let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };
  return acc;
}, {});

document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);



function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
        
      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },
    
    
    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/jsonpath.min.js"></script>

I am trying to put two object data in one output but by reading the link which is Asset

but in the multiple Array list the output is displaying as I want but the problem is while comparing the output from the anotherObj if the Id with that Obj is present it showing me the expected value which is data Asset replaced by the anotherObj

But I want to remove the value which is not matched with the object which are present inside the anotherObj

for eg:-

"mediaGalary": [
        {
          "sys": {
            "type": "Link",
            "link": "Asset",
            "id": "gHcw3Z1Ko"
          }
        },
        {
          /**id:c**/
          "status": true,
          "tag": [],
          "filename": "wallpapers-6.jpg",
          "is_dir": false,
          "parent_uid": null
        }
      ]

and

"mediaFile": [
    {
     "sys": {
      "type": "Link",
      "link": "Asset",
      "id": "7kRzyt4PFo"
     }
    },
    {
     "status": true,
     "tag": [],
     "filename": "mediaFile1.jpg",
     "is_dir": false,
     "parent_uid": null
    }
   ]

look like this here “id”: “gHcw3Z1Ko” is not present inside the anotherObj so I want to remove it but don’t know how to remove it

as my expected output is like this

"mediaGalary": [
        {
          /**id:c**/
          "status": true,
          "tag": [],
          "filename": "wallpapers-6.jpg",
          "is_dir": false,
          "parent_uid": null
        }
      ]
and


"mediaFile": [
    {
     "status": true,
     "tag": [],
     "filename": "mediaFile1.jpg",
     "is_dir": false,
     "parent_uid": null
    }
   ]

if the given id is not present inside the anotherObj or any other id which are not present inside the anotherObj

Accessing specific values in a nested object

I have a nested object which looks like the below

{
    "Place One": {
        primary: "#000000",
        secondary: "#97233f",
        coordinates: {
            lat: 49.5013,
            lon: 87.0622
        }
    },
    "Place Two": {
        primary: "#000000",
        secondary: "#a71930",
        coordinates: {
            lat: 40.6013,
            lon: 81.0622
        }
    },
    "Place Three": {
        primary: "#9e7c0c",
        secondary: "#241773",
        coordinates: {
            lat: 40.5033,
            lon: 84.0622
        }
    }
}

I am trying to get access to each of the lat /lon variables to pass to a Leaflet React component

 <Marker
          key={park.properties.PARK_ID}
          position={[
            ***the lat***,
            ***the lon***
          ]}
        
        />

I’ve tried the below:

Object.fromEntries(
                Object.entries(teams).map(([key, { coordinates }]) => <Marker
                    position={[
                        coordinates.lat,
                        coordinates.lon
                    ]} />
                )

but cannot access the values.

can anyone please advise the best way to do this?