How to move mouse cursor to element on a page with Selenium & JavaScript?

I need move mouse cursor to element by xpath, but don’t click them. This code doesn’t work. Browser is opened on mainpage and that’s all.

const {Builder, By} = require('selenium-webdriver');
let driver = await new Builder().forBrowser('chrome').build(); 

class homepage{


async moveToElement() {
  
    // Navigate to Url
    await driver.get('https://test.io/'); 
    let gmailLink = driver.findElement(By.xpath('//*[@class="top-navigation__item-link"][1]'));
    const actions = driver.actions({async: true});  
    await actions.move({origin:gmailLink}).perform();
  }

}

how to JSON to Parse in react?

I have tree list components when I click on any item of the tree list it shows the result of JSON data. I don’t wanna JSON format but parse format.

i have tried let json = JSON.parse(this.props.node, null, 4); but it showing Unexpected token u in JSON at position 0

You can visit the Link

class NodeViewer extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const style = styles.viewer;
    let json = JSON.stringify(this.props.node, null, 4);
    if (!json) {
      json = HELP_MSG;
    }
    return <div style={style.base}>{json}</div>;
  }
}

NodeViewer.propTypes = {
  node: PropTypes.object
};

Append new Item to Div Container in svelte after addEventListener Message

so as you can see I have created a component. And I am reporting to my script that I am listening for a window event listener(message). I actually want to make that every time this EventListnere is called, that I add a new Notification under gold notify box. How would I archive that in svelte. ?

<script>

    import Notification from './Components/Notification.svelte';
    let type,text,time,title,icon,position,top,progress
    let slideIn = true;
    let showNoti;
    $: if(!slideIn) {
        slideIn === false;
    } 

window.addEventListener('message', (event) => {
    showNoti = true;
    if(showNoti) {

        let data = event.data;
        type = data.type
        text = data.text
        time = data.time
        title = data.title
        icon = data.icons;
        top = data.top;
        progress = data.progress;
        position = data.position;
        if(type == "success") {
            type = "success"
        }else if(type == "error") {
            type = "error"
        }else if(type == "money") {
            type = "money"
        }
        setTimeout(() => {
            slideIn = false;
        }, time);
    }
});



</script>


<main> 
{#if showNoti}
    <div class="notif-container {position}" style="top: {top}">
        <div class="gold-notify-box">
                <Notification text={text} type={type} time={time} title={title} icon={icon} position={position} top={top} progress={progress} slideIn={slideIn} />
          </div>
    </div>

{/if}

</main>

<style>
    
</style>

Creating a Etch-and-Sketch grid with JavaScript

I am creating a grid for an Etch-and-Sketch project. I have an empty div (.container) in my HTML and use a JS loop to create a 16×16 grid.
All appended elements appear in the inspect tool, but not on Live screen. You’ll see my code below, thanks!

HTML:

<!DOCTYPE html>
<html lang="en-US">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Etch and Sketch</title>
    <link rel="stylesheet" href="style.css">
</head>


<body>
    <h1 class="title">Etch and Sketch</h1>
    <div class="gridSize">Waiting</div>
    <div class="buttons">
        <button class="clear">Clear</button>
        <button class="black">Black</button>
        <button class="colors">Colors</button>
        <div class="colorPalette">Color Palette</div>
     </div>

     <div class="container">
    </div>

     <button class="End">End test</button>

     <script src="script.js"></script>
</body> 
</html>

Javascript:

const container = document.querySelector(".container");

let gridSize = 16;

function makeGrid(screenSize) {
  for (let i = 0; i < screenSize ** 2; i++) {
      let square = document.createElement("div");
      square.classList.add('square');
      square.style.backgroundColor = 'blue';
      container.appendChild(square);
  }
  container.style.gridTemplateColumns = 'repeat($(screenSize), auto)';
  container.style.gridTemplateRows = 'repeat($(screenSize), auto)';
};

makeGrid(gridSize);

CSS:

.container {
  border-color: 1px solid black;
  background-color: blue;
  display: grid;
  width:50%;
  height:50%;
}

.square {
  border-color: 1px solid black;
  background-color: blue;
}

how to make an image as a clickable link to another html page using javascript?

this is the js code I wrote :

var goToSecondPage= document.querySelector('.mobile');

goToSecondPage.addEventListener("click", function() {

document.location.href='productDetails.html';
 })

I’m trying to use an image in an existed class on an index html page (called mobile) and make it as a clickable link image to another html file called “productDetails.html”

Random color for boxShadow javascript

I have a function that randomly creates divs with circles.

It has a random color choice for the border. It works as it should.

I also added a box shadow, and I want the color to change the same way as the border.

I did everything by analogy as with the border, but I get an error:

“message”: “Uncaught SyntaxError: Invalid or unexpected token”

How can I set a random color for the box shadow?

function createDiv(id, color) {
  let div = document.createElement('div');
  div.setAttribute('id', id);
  if (color === undefined) {
    let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
    div.style.borderColor = colors[Math.floor(Math.random() * colors.length)];
    div.style.boxShadow = 0px 0px 15px 5px colors[Math.floor(Math.random() * colors.length)];
  }
  else {
   div.style.borderColor = color; 
   div.style.boxShadow = 0px 0px 15px 5px color; 
  }
  div.classList.add("circle");
  document.body.appendChild(div);
}
    
let i = 0;

const oneSeconds = 1000;

setInterval(() => {
  i += 1;
  createDiv(`div-${i}`)
}, oneSeconds);
div {
  display: inline-block;
  margin: 20px;
}

.circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  background-color: #ffffff;
  border: 3px solid #000;
  box-shadow: 0px 0px 15px 5px #0ff;
  margin: 20px;
}

JavaScript, NodeJS – automate website refresh and data gathering

I have been tasked in my work to gather data from the website of our client.
Usually, I would gather those data via SQL but we don’t have access to their server. Only by the use of browser.
I wonder if is there any possibility to automate this proccess:

  1. Refresh website with new URL (for certain product)
  2. Get HTML to gather data
  3. Save it to file.
  4. Repeat for certain amount of names of product.

I have tried with using Javascript and AJAX. It didn’t work.
I also think if it is possible to do with NodeJS.
Do you have any suggestions, I would be gratefull for anything 🙂

Discord JS: Extracting data from a collection

I have a command where I want to write the id from a user in a Voice Channel into an array. So far I managed to write the whole collection of the user with joinedTimestamp etc. Now I want to extract the ID from the user from the collection. My command looks like this:

client.on('messageCreate', (message) => {
    let waitingroom = message.guild.channels.cache.get("952324088762867722")
    let player = [];
    let isadmin = message.member.roles.cache.has(adminRole);

    if (message.content.toLowerCase() === prefix + 'startgame' && isadmin) {
        player.push(waitingroom.members);
        console.log(player);
    }    
});

And this is what I get from the array when 2 users are in the waitingroom:

[
  Collection(2) [Map] {
    '392776445375545355' => GuildMember {
      guild: [Guild],
      joinedTimestamp: 1646940658665,
      premiumSinceTimestamp: null,
      nickname: null,
      pending: false,
      communicationDisabledUntilTimestamp: null,
      _roles: [Array],
      user: [User],
      avatar: null
    },
    '849388169614196737' => GuildMember {
      guild: [Guild],
      joinedTimestamp: 1647168003344,
      premiumSinceTimestamp: null,
      nickname: 'Test-Account [Nils]',
      pending: false,
      communicationDisabledUntilTimestamp: null,
      _roles: [],
      user: [User],
      avatar: null
    }
  }
]

But I only want the ID’s from the users from the collection. I appreciate any help.

React DnD, could not find “store” in the context of Connect(Droppable)

Hello I am trying to make a drag and drop in my application but I have got a huge error. I have no idea if property is missing because in IDE it is an error free code.

Uncaught Error: Could not find "store" in the context of "Connect(Droppable)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Droppable) in connect options.

Down here are my components

3 Columns ( I want drag and drop across one column each, not between them)

const DetailColumns: React.FC<funcProps> = (props) => {
  const onDragEnd = () => {};
  return (
    <Box
      h="80vh"
      borderWidth="0.5rem"
      borderColor="orange.300"
      borderRadius="1rem"
      w="80%"
      marginTop="2rem"
    >
      <Grid w="100%" h="100%" templateColumns="60% 20% 20%">
        <Box border="0.5rem" borderColor="orange.300">
          <RecipeDescriptionBox recipe={props.recipe} />
        </Box>
        <Box borderLeftWidth="0.5rem" borderColor="orange.300">
          <RecipeStepsBox recipe={props.recipe} />
        </Box>
        <DragDropContext onDragEnd={onDragEnd}>
          <Box borderLeftWidth="0.5rem" borderColor="orange.300">
            <RecipeIngredientsBox recipe={props.recipe} />
          </Box>
        </DragDropContext>
      </Grid>
    </Box>
  );
};

List of Items

<Box>
      <ColumnHeader title="Steps" />
      <Droppable droppableId="unique">
        {(provided) => (
          <Box {...provided.droppableProps} innerRef={provided.innerRef}>
            {steps.map((step, index) => (
              <DetailListItem
                key={step}
                itemName={step}
                indexOfItem={index}
                id={Math.random().toString()}
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </Droppable>
    </Box>

Item element

<Draggable draggableId={props.id} index={props.indexOfItem}>
      {(provided) => (
        <Box
          {...provided.draggableProps}
          {...provided.dragHandleProps}
          innerRef={provided.innerRef}
        >
          <Flex margin="1rem">
            <Box
              bgGradient="linear(to-r, orange.200, orange.400)"
              height="6vh"
              width="6vh"
              boxShadow="md"
              rounded="md"
            >
              <Grid w="100%" h="100%" placeItems="center">
                <Text color="white" fontWeight="700" fontSize="140%">
                  {props.amount && props.amount + props.unit}
                  {!props.amount && props.indexOfItem}
                </Text>
              </Grid>
            </Box>
            <Grid placeItems="center">
              <Text marginLeft="1rem" fontWeight="500" fontSize="1.8rem">
                {props.itemName}
              </Text>
            </Grid>
          </Flex>
        </Box>
      )}
    </Draggable>

If you want I can put this code to some sandbox to make it easier to debug.

Why does only one of the two functions work, i.e. the one called first?

This is the table function for adding data into a table:

const table = () => {
  let table_details = document.getElementById("table_details")
  let data = localStorage.getItem("projects")
  
  if (data == null) {
    arr = []
  }
  else {
    tabledata = JSON.parse(data);
  }
  
  console.log(tabledata)
  projectTable = ""
  tabledata.map((items, index) => {
    projectTable += `<tr><td>${index}</td> <td>${items.pname}</td> <td>${items.pleader}</td> <td>${items.pstatus}</td> <td>${items.pcompany}</td><tr/>`
  })
  tabledata.length > 0 ? (table_details.innerHTML = projectTable) : (`No project found !`)
}

This is the projectDetails function for showing data as cards:

const projectDetails = () => {
  let projectDetails = document.getElementById("project_details");
  let data = localStorage.getItem("projects");

  if (data == null) {
    arr = [];
  }
  else {
    projectdata = JSON.parse(data); //converting data into an array
  }

  showDetails = "";
  console.log(projectdata)
  projectdata.forEach((items, index) => {
    showDetails += ` <div class="card-body col-6 p-3  " style ="width:30rem">
    <span class ="card-title"><p class = "text-info">projectName:  ${items.pname}</p> <a href="#"> leader:${items.pleader} </a> 
      </span><p class ="card-text p-0">description:${items.pdesc}</p><p class = "text-muted p-0 m-0">[status:${items.pstatus}] <br> <button  onclick = "deleteProject(${index})" class = "btn btn-info  p-1">delete</button>
      </div> <hr>`
  });

  if (projectdata.length > 0) {
    projectDetails.innerHTML = showDetails
  }
  else {
    (projectDetails.innerHTML = `<h4 class = "text-danger"><strong>No Projects Found !</strong></h4>`);
  }
}

This is how both functions get called:

table();
projectDetails();

When calling two functions, only one function is working: the one which is called first.

How can I split orders data based on product owner in reactjs or nodejs

I need some idea!

Is there any possible way To separate user orders based on vendor email? I am trying to develop a multi-vendor project where vendors can be able to upload products. I am trying to do when a user orders from a different shop the orders need to be split based on vendor email.

Suppose a customer trying to buy from x vendor and y vendor products. When customers order the products the data look like the below array objects. It is difficult to show vendor orders in their dashboard who ordered your product. So I am trying to split the order based on email also the amount will be divided between the vendors from paymentDetail.amount when splitting the order.

[
        {
            _id: "622d70a49bd88b1599026318",
            products: [
                {
                    _id: "6223186e2278d4e502f5264a",
                    title: "Product number 1",
                    price: 600,
                    cartQuantity: 1,
                    vendor: {email: "[email protected]"}
                },
                {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "[email protected]"
                    }
                },
                 {
                    _id: "622d4e9f9bd88b1599026317",
                    title: "asdas",
                    price: 100,
                    cartQuantity: 5,
                    vendor: {
                        email: "[email protected]"
                    }
                },
            ],
            paymentDetails: {
                createdId: 1647145079,
                date: "Sun Mar 13 2022",
                amount: 110000,
                email: "[email protected]",
                last4: "4242",
                transaction: "p"
            },
            status: "Pending",
            billing: {
                country: "BD",
                name: "Md. Fathe Karim",
                phone: "+88010000000",
                line1: "Madhabdi",
                city: "Narshingdi",
                postal_code: "1604",
                state: "Bandarban"
            }
        }]

This is my POST request from frontend:

   await fetch('https://guarded-ocean-73313.herokuapp.com/dashboard/orders', {
                method: 'POST',
                headers: {
                    'content-type': 'application/json'
                },
                body: JSON.stringify({
                    products: [...cart], paymentDetails: {
                        createdId: paymentIntent.created,
                        date,
                        amount: paymentIntent.amount,
                        email: emailRef.current?.value,
                        billing: paymentIntent.billing_details,
                        last4: paymentMethod.card.last4,
                        transaction: paymentIntent?.client_secret.slice('_secret')[0]
                    },
                    status: 'Pending',
                    billing: {
                        country: countryRef.current?.value,
                        name: nameRef.current?.value,
                        phone: phoneRef.current?.value,
                        line1: addressRef.current?.value,
                        city: cityRef.current?.value,
                        postal_code: zipRef.current?.value,
                        state: stateRef.current?.value,
                    }
                })
            })
                .then(res => res.json())

This is my order API

 app.post('/dashboard/orders', async (req, res) => {
            const productDetail = req.body
            const result = await unityMartOrdersCollection.insertOne(productDetail)
            res.json(result)
        })

I think it’s possible by the reduce method? Is there anyone who can give me some ideas? Thank you.

network graph with circular pack

hey everyone I just want to create a network graph with a circular pack,in which the connection between parents nodes should be always there but the connection between child node show only we click particular child nodes.

first image is the image while our page is opening enter image description here

second image is while we click particular child nodes here we click white color child nodes so connection between all child nodes with white nodes show here.enter image description here

actual connection for reference enter image description here

nodes data

 let root = {
        "children": [
          {
            "name": "analytics",
            "children": [
              {
                "name": "animate1",
                "size": 1500
              },
              {
                "name": "animate2",
                "size": 1500
              },
              {
                "name": "animate3",
                "size": 1500
              }
            ]
          },
          {
            "name": "analytics1",
            "children": [
              {
                "name": "animate4",
                "size": 1500
              },
              {
                "name": "animate5",
                "size": 1500
              },
              {
                "name": "animate6",
                "size": 1500
              }
            ]
          },
          {
            "name": "analytics2",
            "children": [
              {
                "name": "animate7",
                "size": 1500
              },
              {
                "name": "animate8",
                "size": 1500
              },
              {
                "name": "animate9",
                "size": 1500
              }
            ]
          }
        ]
        }

links connection

const links = [
        { source: "animate1", target: "animate4" },
        { source: "animate6", target: "animate9" },
        { source: "animate9", target: "animate6" },
        { source: "animate3", target: "animate2" },
        { source: "animate1", target: "animate8" },
         { source: "animate3", target: "animate5" },
           { source: "analytics", target: "analytics2" },
            { source: "analytics1", target: "analytics2" },
             { source: "analytics1", target: "analytics" }
           
        
        
      ] ;

what I did

const svg = d3.select("svg"),
    diameter = +svg.attr("width"),
    g = svg.append("g").attr("transform", "translate(2,2)"),
    format = d3.format(",d");


      const links = [
        { source: "animate1", target: "animate4" },
        { source: "animate6", target: "animate9" },
        { source: "animate9", target: "animate6" },
        { source: "animate3", target: "animate2" },
        { source: "animate1", target: "animate8" },
         { source: "animate3", target: "animate5" },
           { source: "analytics", target: "analytics2" },
            { source: "analytics1", target: "analytics2" },
             { source: "analytics1", target: "analytics" }
           
        
        
      ] ;
      
      let root = {
        "children": [
          {
            "name": "analytics",
            "children": [
              {
                "name": "animate1",
                "size": 1500
              },
              {
                "name": "animate2",
                "size": 1500
              },
              {
                "name": "animate3",
                "size": 1500
              }
            ]
          },
          {
            "name": "analytics1",
            "children": [
              {
                "name": "animate4",
                "size": 1500
              },
              {
                "name": "animate5",
                "size": 1500
              },
              {
                "name": "animate6",
                "size": 1500
              }
            ]
          },
          {
            "name": "analytics2",
            "children": [
              {
                "name": "animate7",
                "size": 1500
              },
              {
                "name": "animate8",
                "size": 1500
              },
              {
                "name": "animate9",
                "size": 1500
              }
            ]
          }
        ]
        }


 svg.append("svg:defs")
        .append("svg:marker")
        .attr("id", "arrow")
        .attr("viewBox", "0 0 10 10")
        .attr("refX", 10)
        .attr("refY", 5)
        .attr("markerUnits", "strokeWidth")
        .attr("markerWidth", 6)
        .attr("markerHeight", 3)
        .attr("orient", "auto")
        .append("svg:path")
        .style("stroke","none")
        .attr("d", "M 0 0 L 10 5 L 0 10 z");


const pack = d3.pack()
    .size([diameter/2, diameter/2])
    .padding(40)

  root = d3.hierarchy(root)
      .sum(function(d) { return d.size; })
      .sort(function(a, b) { return b.value - a.value; });

  const node = g.selectAll(".node")
    .data(pack(root).descendants())
    .enter()
    .filter(function(d){
            return  !!d.data.name
        })
    .append("g")
    .attr('id', function(d) {
      return d.data.name;
    })
      .attr("class", function(d) { return d.children ? "node" : "leaf node"; })
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
      .text(function(d) { return d.data.name + "n" + format(d.value); });




  
    const arrow = svg.selectAll('path.arrow').data( links, JSON.stringify );
  arrow.enter()
        .append("path")
        .attr("class","arrow")
        .attr("x1", function(d){
            let translate = getTranslate(d.source);
            return translate[0]
        })
        .attr("x2", function(d){
            let translate = getTranslate(d.target);
            return translate[0]
        })
        .attr("y1", function(d){
            let translate = getTranslate(d.source);
            return translate[1]
        })
        .attr("y2", function(d){
            let translate = getTranslate(d.target);
            return translate[1]
        })
        .attr("d", function(d) {
            let source = getTranslate(d.source),
                target = getTranslate(d.target),
                 x1= source[0],
                 x2= target[0],
                 y1= source[1],
                 y2= target[1];


            let dx = x1 - x2,
                dy = y1 - y2,
                dr = Math.sqrt(dx * dx + dy * dy);
            // return "M" + x1 + "," + y1 + "A" + dr + "," + dr + " 0 0,1 " + (x2 - 0.6) + "," + (y2 - 0.9);
            return "M" + x1 + "," + y1 + "A" + dr + "," + dr + " 0 0,1 " + x2 + "," + y2;
        })
        .style("stroke", "black")
        .style("fill", "none")
        .style("stroke-width", 3)
        .attr("marker-end", "url(#arrow)");    



  node.append("circle")
      .attr("r", function(d) { return d.r; })

  node.filter(function(d) { return !d.children; }).append("text")
      .attr("dy", "0.3em")
      .text(function(d) { return d.data.name.substring(0, d.r / 3); });


        function getTranslate(datum) {
            const circle = d3.select('#'+datum);
            const string = circle.attr("transform");
            const translate =  string.substring(string.indexOf("(")+1, string.indexOf(")")).split(",");
            return translate;
        }
circle {
  fill: rgb(31, 119, 180);
  fill-opacity: .25;
  stroke: rgb(31, 119, 180);
  stroke-width: 1px;
}

.leaf circle {
  fill: #ff7f0e;
  fill-opacity: 1;
}

text {
  font: 10px sans-serif;
  text-anchor: middle;
}
<svg width="960" height="960"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

Javascript cameraOffset and increasecameraOffset

I found a java script url file that contains the function cameraOffset and increasecameraOffset and i dont know what they are and what they are used for
are they used to turn webcam on ??
or they are not related to webcam
please tell me
Thanks
If you want the url to check it i will put it

JavaScript Webstite Logging : Logging on Kibana,eslastic,splunk or Server Side

How do we log JavaScript based website code, what are the best practices and solution.

Currently we do not have any logging in Javascript code, we started with small but now it has become humongous and very difficult to debug.

Since, it is not best to use console.log developers avoided to use but now it is next to impossible to track what is happening in the code since that code has several sdk calls and different modules within Javascript.

I have spent time to search on this but looking for more insights on what can we use, my findings are on the below lines

  1. console.log them and send to Kibana,Elastic,Splunk or a VSI and dump log file there.
  2. Elegant way to do the above approach
  3. Use some 3rd party logging framework who can handle this efficiently and elegantly

NOTE: The site is already developed and it would be tough to go to each of the function and add console.log, also want to persist the logs in server or splunk etc