Close SQL connection Nodejs

I tried to close the connection for the below query by using connection.close(). but it is not working, so how to close connection inside route file

var express = require('express');
var router = express.Router();
var connection  = require('../database.js');
var db  = require('../database.js');


 
/* GET home page. */
 router.get('/', function(req, res, next) {
  connection.query("Select users..... ",function(err,supervisorrows)     {

             if(err){
          req.flash('error', err); 
          res.render('View',{page_title:"Users - Node.js",supervisor:''});   
         }else{
            
             res.render('View',{page_title:"Users - Node.js",supervisor:supervisorrows.recordset});

         }                     
        });




 
module.exports = router;

I can’t get the data of the user by his id

I can’t get the data from the API to display it on the screen when I try to retrieve it I get a 400 error I don’t know how to retrieve the data I put the right routes and so far nothing works.

import Card from "../../components/Card";
import styled from "styled-components";
import { Loader } from "../../utils/styles/Atoms";
import { useFetch, useTheme } from "../../utils/hooks";
import freelancers from "../Freelances";

const CardsContainer = styled.div`
  display: grid;
  gap: 24px;
  grid-template-rows: 350px 350px;
  grid-template-columns: repeat(2, 1fr);
  align-items: center;
  justify-items: center;
`;

const LoaderWrapper = styled.div`
  display: flex;
  justify-content: center;
`;

export function getFreelance(id) {
  const freelance = [];
  console.log(freelance);
  return freelance.find((freelancer) => freelancer.id === id);
}

function Freelance() {
  const { theme } = useTheme();
  const freelanceData = getFreelance();
  const { data, isLoading, error } = useFetch(
    `http://localhost:8000/profile/?id=${freelanceData}`
  );
  console.log(data);
  const freelanceProfil = data?.freelanceProfil;

  if (error) {
    return <span>Oups il y a eu un problème</span>;
  }
  return (
    <div>
      {isLoading ? (
        <LoaderWrapper>
          <Loader theme={theme} data-testid="loader" />
        </LoaderWrapper>
      ) : (
        <CardsContainer>
          {getFreelance((profile, index) => (
            <Card
              key={`${profile.name}-${index}`}
              label={profile.job}
              title={profile.name}
              picture={profile.picture}
            />
          ))}
        </CardsContainer>
      )}
    </div>
  );
}

export default Freelance;

/*The different routes to make API calls*/

/*
     Node Js API

          ul 
          li /freelances
          li /profile/?id={id}
          li /survey
          li /results/?a1={answer1}&a2={answer2}&a3={answer3}...
  */
/*The model to get the unique user using his Id*/

const freelancesData = require("../models/freelances");

function getFreelance(id) {
  return freelancesData.find((freelancer) => freelancer.id === id);
}

module.exports = getFreelance;

How to convert Excel Table to specific JSON format using Office Scripts

I’m trying to get a specific JSON output from Office Scripts in order to make an API call with Power Automate. The output I’m receiving from Power Automate does not have the format required in the API docs (link to API docs below). Tried modifying the script to get the required output but unfortunately, I’m just starting out with js, so I can’t figure out what I need.

Right now, the input must come from an Excel table. I can format the excel table differently for this flow if it’s needed, but nevertheless, the input must come from an Excel table. Right now, the Excel table looks like this:

This is the Office Script I am using, comes from this blog post: https://docs.microsoft.com/en-us/office/dev/scripts/resources/samples/get-table-data:

function main(workbook: ExcelScript.Workbook): TableData[] {
 // Get the first table in the "WithHyperLink" worksheet.
 // If you know the table name, use `workbook.getTable('TableName')` instead.
 const table = workbook.getWorksheet('WithHyperLink').getTables()[0];

 // Get all the values from the table as text.
 const range = table.getRange();

 // Create an array of JSON objects that match the row structure.
 let returnObjects: TableData[] = [];
 if (table.getRowCount() > 0) {
 returnObjects = returnObjectFromValues(range);
}

// Log the information and return it for a Power Automate flow.
console.log(JSON.stringify(returnObjects));
return returnObjects
}

function returnObjectFromValues(range: ExcelScript.Range): TableData[] {
 let values = range.getTexts();
 let objectArray : TableData[] = [];
 let objectKeys: string[] = [];
 for (let i = 0; i < values.length; i++) {
 if (i === 0) {
  objectKeys = values[i]
  continue;
}

let object = {}
for (let j = 0; j < values[i].length; j++) {
  // For the 4th column (0 index), extract the hyperlink and use that instead of text. 
  if (j === 4) {
    object[objectKeys[j]] = range.getCell(i, j).getHyperlink().address;
  } else {
    object[objectKeys[j]] = values[i][j];
  }
}

objectArray.push(object as TableData);
 }
 return objectArray;
}

interface TableData {
  "Event ID": string
  Date: string
  Location: string
  Capacity: string
  "Search link": string
  Speakers: string
 }

And this is the output I am getting in Power Automate when I run the Office Script:

[
 {
  "Line": "",
   "Id": "0",
   "Description": "nov portion of rider insurance",
   "Amount": "100",
   "DetailType": "JournalEntryLineDetail",
   "JournalEntryLineDetail": "",
   "PostingType": "Debit",
   "AccountRef": "",
   "value": "39",
   "name": "Opening Bal Equity"
 },
{
   "Line": "",
   "Id": "",
   "Description": "nov portion of rider insurance",
   "Amount": "100",
   "DetailType": "JournalEntryLineDetail",
   "JournalEntryLineDetail": "",
   "PostingType": "Credit",
   "AccountRef": "",
   "value": "44",
   "name": "Notes Payable"
 }
]

BUT, the schema I need looks like this (it is based on this API doc https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/journalentry):

{
 "Line": [
   {
     "Id": "0",
     "Description": "nov portion of rider insurance",
     "Amount": 100.0,
     "DetailType": "JournalEntryLineDetail",
     "JournalEntryLineDetail": {
     "PostingType": "Debit",
     "AccountRef": {
            "value": "39",
            "name": "Opening Bal Equity"
          }
    }
  },
  {
    "Description": "nov portion of rider insurance",
    "Amount": 100.0,
    "DetailType": "JournalEntryLineDetail",
    "JournalEntryLineDetail": {
    "PostingType": "Credit",
          "AccountRef": {
            "value": "44",
            "name": "Notes Payable"
          }

   }
  }
 ]
}

There are a lot of differences and obviously, when I try to make the API call, I get a 400 ‘Bad request’ error. Does anyone know how I must modify either the Script or the Excel table or do something different in Power Automate in order to get the specific schema I need?

Any help will be appreciated. Thanks!!

How to remove addEventListener using class list?

I want to remove an infinite scroll event listener from the favourite nav page using class list.

Is this possible?

function showContent(page) {
  if (page === 'results') {
    resultsNav.classList.remove('hidden');
    favouritesNav.classList.add('hidden');
  } else {
    resultsNav.classList.add('hidden');
    favouritesNav.classList.remove('hidden');
  }
  loader.classList.add('hidden');
}

window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 1000) {
    getPictures();
  }
});

stompjs how to get status after sending message

i’m creating a chat application with spring boot websocket, STOMP and stompjs, here is my js code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script>
    //some code

    //send message
    stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage));
</script>

Backend code:

@MessageMapping("/chat.sendMessage")
public MessageDTO sendMessage(@Payload MessageDTO chatMessage) {
    //HERE
    if(!validatorService.validate(chatMessage)) {
        throw new RuntimeException("invalid");
    }
    messagingTemplate.convertAndSend("/topic/public", chatMessage);
    return chatMessage;
}

You can see if the message is not valid, the exception is thrown, and the message is not sent to /topic/public. In js side is there any way to know that the message is processed successfully like

stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage), successCallback, errorCallback);

window.addEventListner, functions, IconContext not working in my functional component React

window.addEventListner, functions, IconContext not working in my functional component React.
I have it change to red when scrolling but it isn’t, also, the color I set doesn’t change, and toggleHome doesn’t scroll to the top, nothing happens when I click the logo.
I want it to acknowledge scrolling and scroll to the top when the logo is pressed.

import React, { useState, useEffect } from "react";
import { FaBars } from 'react-icons/fa'
import { IconContext } from 'react-icons/lib';
import { animateScroll as scroll } from 'react-scroll'
import {
  Nav,
  NavbarContainer,
  NavLogo,
  MobileIcon,
  NavMenu,
  NavItem,
  NavLinks,
  NavBtn,
  NavBtnLink
} from "./NavbarElements";

const Navbar = ({ toggle }) => {
  const [scrollNav, setScrollNav] = useState(false);

  const changeNav = () => {
    if(window.scrollY >= 80) {
      setScrollNav(true);
    } else {
      setScrollNav(false);
    }
  };

  useEffect(() => {
   this. window.addEventListener('scroll', changeNav)
  }, [changeNav]);

  const toggleHome = () => {
    scroll.scrollToTop();
  }

  return (
    <>
    <IconContext.Provider value={{ color: '#fff' }}>
      <Nav scrollNav={scrollNav}>
        <NavbarContainer>
          <NavLogo to="/" onClick={toggleHome}>dolla</NavLogo>
          <MobileIcon onClick={toggle} >
            <FaBars />
          </MobileIcon>
          <NavMenu>
            <NavItem>
              <NavLinks to="about">About</NavLinks>
            </NavItem>
            <NavItem>
              <NavLinks to="discover">Discover</NavLinks>
            </NavItem>
            <NavItem>
              <NavLinks to="services">Services</NavLinks>
            </NavItem>
            <NavItem>
              <NavLinks to="signup">Sign Up</NavLinks>
            </NavItem>
          </NavMenu>
          <NavBtn>
            <NavBtnLink to='/signin'>Sign In</NavBtnLink>
          </NavBtn>
        </NavbarContainer>
      </Nav>
      </IconContext.Provider>
    </>
  );
};

export default Navbar;
import styled from 'styled-components'
import { Link as LinkR } from 'react-router-dom'
import { Link as LinkS } from 'react-scroll'

export const Nav = styled.nav`
    background: ${({scrollNav}) => (scrollNav ? 'red' : 'transparent')};
    height: 80px;
    margin-top: -80px; 
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1rem;
    position: sticky;
    top: 0;
    z-index: 10;

    @media screen and (max-width: 960px) {
        transition: 0.8s all ease;
    }
`;

export const NavbarContainer = styled.div`
    display: flex;
    justify-content: space-between;
    height: 80px;
    z-index: 1;
    width: 100%;
    padding: 0 24px;
    max-width: 1100px;
`;

export const NavLogo = styled(LinkR)`
    color: #fff;
    justify-self: flex-start;
    cursor: pointer;
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    margin-left: 24px;
    font-weight: bold;
    text-decoration: none;
`;

export const MobileIcon = styled.div`
    display: none;

    @media screen and (max-width: 768px){
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(-100%, 60%);
        font-size: 1.8rem;
        cursor: pointer;
        color: #fff
    }
`;

export const NavMenu = styled.ul`
    display: flex;
    align-items: center;
    list-style: none;
    text-align: center;
    margin-right: -22px;

    @media screen and (max-width: 768px) {
        display: none;
    }
`;

export const NavItem = styled.li`
    height: 80px;
`;

export const NavLinks = styled(LinkS)`
    color: #fff;
    display: flex;
    align-items: center;
    text-decoration: none;
    padding: 0 1rem;
    height: 100%;
    cursor: pointer;

    &.active {
        border-bottom: 3px solid #01bf71;
    }
`;

export const NavBtn = styled.nav`
    display: flex; 
    align-items: center;
    

    @media screen and (max-width: 768px) {
        display: none;
    }
`;

export const NavBtnLink = styled(LinkR)`
    border-radius: 50px;
    background: #01bf71;
    white-space: nowrap;
    padding: 10px 22px;
    color: #010606;
    font-size: 16px;
    outline: none;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
    text-decoration: none;

    &:hover {
        transition: all 0.2s ease-in-out;
        background: #fff;
        color: #010606;
    }
` ;
   

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.