How to fetch SQLite database values from HTML/CSS/Javascript and display on HTML page in the form of chart/graph?

So basically, i’ve a SQLite database full of data and i want to create an app which can fetch the data and display the data in the form of charts or graphs. So, i chose HTML/CSS/Javascript to do the job. Can somebody please explain the whole procedure with a small example or share me some accurate links???

I don’t know anything about it. Saw some tutorials and found html+css+javascript aesthetically nice. Right now ive written a node.js code to fetch the data from the database but how do i send it to the HTML page and display it in the form of chart/graph?

How to mock react custom hook return value as a module with Jest

I need to mock my custom hook when unit testing React component. I’ve read some stackoverflow answers but haven’t succeeded in implementing it correctly.

I can’t use useAuth without mocking it as it depends on server request and I’m only writing unit tests at the moment.

//useAuth.js - custom hook

const authContext = createContext();

function useProvideAuth() {
    const [accessToken, setAccessToken] = useState('');
    const [isAuthenticated, setAuthenticated] = useState(
        accessToken ? true : false
    );

    useEffect(() => {
        refreshToken();
    }, []);

    const login = async (loginCredentials) => {
        const accessToken = await sendLoginRequest(loginCredentials);
        if (accessToken) {
            setAccessToken(accessToken);
            setAuthenticated(true);
        }
    };

    const logout = async () => {
        setAccessToken(null);
        setAuthenticated(false);
        await sendLogoutRequest();
    };

    const refreshToken = async () => {
        const accessToken = await sendRefreshRequest();
        if (accessToken) {
            setAccessToken(accessToken);
            setAuthenticated(true);
        } else setAuthenticated(false);
        setTimeout(async () => {
            refreshToken();
        }, 15 * 60000 - 1000);
    };

    return {
        isAuthenticated,
        accessToken,
        login,
        logout
    };
}

export function AuthProvider({ children }) {
    const auth = useProvideAuth();

    return <authContext.Provider value={auth}>{children}</authContext.Provider>;
}

AuthProvider.propTypes = {
    children: PropTypes.any
};

const useAuth = () => {
    return useContext(authContext);
};

export default useAuth;

The test I’ve written

//mainPage.test.js

import React from 'react';
import { render, screen } from '@testing-library/react';
import Main from '../main/mainPage';

describe('Main when !isAuthenticated', () => {
    beforeEach(() => {
        jest.mock('../auth/useAuth', () => {
            const originalModule = jest.requireActual('../auth/useAuth');
            return {
                __esModule: true,
                ...originalModule,
                default: () => ({
                    isAuthenticated: false,
                    login: jest.fn,
                    logout: jest.fn
                })
            };
        });
    });

    afterEach(() => {
        jest.resetModules();
    });

    it('displays image and login form', () => {
        render(<Main />);

        const image = screen.getByRole('img');
        const form = document.querySelector('[data-testid=loginForm]');
        expect(image).toBeInTheDocument();
        expect(form).toBeInTheDocument();
    });
});

However, I get this error.

 TypeError: Cannot read properties of undefined (reading 'isAuthenticated')

       7 |
       8 | function Main() {
    >  9 |      const isAuthenticated = useAuth().isAuthenticated;
         |                              ^
      10 |      const location = useLocation();
      11 |
      12 |      if (isAuthenticated)

      at Main (src/main/mainPage.js:9:26)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)...

I’ve been also trying to use spyOn but nothing helped. What exactly do I need to change to make the mock work?

How do I export an async/await function in node js [duplicate]

I want an export quick function. How can I do that?

Here’s my main code,

const axios = require('axios')
const quick = async (slug) => {
    const res = await axios.post('https://localhost:3000/api/read', {
        slug: slug
    })
    return res.data.data
}

module.exports = quick

Here is what I encounter when importing the function into another file,

const quick = require('./main.js')

console.log(quick('slug'))

Output

Promise { <pending> }

I want to get the proper output while exporting and importing other functions.

TOP Etch-a-sketch grid resizing

I’m trying to complete The Odin Project’s Etch-a-Sketch challenge and am currently stuck with trying to resize the divs that make up the sketchpad. The app creates a 16×16 grid by default, and when pressing the erase button it asks for a number. It should then recreate the grid based on that number. However, the size of the pad goes all wonky. Link to codepen for clarification: https://codepen.io/eerolli/pen/abELQbp

Any help is much appreciated.

Edit: It should probably be noted, that the app works fine when I enter a number equal to or lower than 16.

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Etch-a-Sketch</title>
</head>
<body>
    <div class="content">
        <h1>Etch-a-Sketch</h1>
        <div class="container">

        </div>
        <button>Erase</button>
    </div>
</body>
<script src="script.js"></script>
</html>

javascript:

let clear = document.querySelector("button");

//function to create a 16x16 grid
function createGrid(size){
    function resetSize(){
        clear.addEventListener('click', ()=>{
            let number = prompt("What size would you like the grid to be? (1-100)");
            container.style.gridTemplateRows = `repeat(${number}, 1fr)`;
            container.style.gridTemplateColumns = `repeat(${number}, 1fr)`;
        })
        
        
    }
    resetSize();

    let container = document.querySelector(".container");
    container.style.gridTemplateRows = `repeat(${size}, 1fr)`;
    container.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
    
    for (let i = 0; i < size*size; i++) {
        
        let square = document.createElement("div");
        square.style.backgroundColor = "black";
        container.appendChild(square);

        //change background color of a square on hover
        square.addEventListener('mouseover', e=>{
            square.style.backgroundColor = "white";
        })


        //function to reset the grid
        function clearGrid(){
            clear.addEventListener('click', e=>{
                square.style.backgroundColor = "black"
           })
        }
        

        clearGrid();    
    }
}

createGrid(16);

Filtering nested objects via Attribute with Javascript-

I have an array of nested objects, I want to filter this to return only the object tjat contains an author who’s age === 21.

I’ve attempted to implement this SO answer, but I keep having ‘x is not a function’ returned.

let arrayOfElements = 
[
  {
  author: { name: 'Kim', age: 21 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
  {
  author: { name: 'John', age: 62 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
  {
  author: { name: 'Mary', age: 31 },
  employment: { employer: 'Logiothech', role: 'Human Resources' }
  }
  
];

What I have tried: (I believe I’m incorrectly using subElements, but unsure what to correctly sub in it’s place)

 let filteredMap =  array_of_elements.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.author.age === 21)}
})

How to load data for autosuggest

I am building a note-taking app where you can add tags to notes. When a user starts adding a new tag, I want to autosuggest the tag from all of its previous saved tags.
How do I implement that?
Do I request for the user’s every previously saved notes, get tags and compare them with what the user is typing or do I maintain a collection of tags when the user is adding a note?
What is the correct approach and how do we decide?

How to use Javascript variable in an if condition in Django template?

I am currently working on a django template wherein I want to use a javascript variable in the if condition. My code is as follows

{% extends 'base.html' %}
{% block content %}

    <br>
    <div class="buttonRow">
        {% for t in tickerList %}
            <button class="btn btn-dark" onclick="changeChart(this.value)" value="{{ t }}">{{ t }}</button>
        {% endfor %}

    </div>
    <br><br>
    {% if {{ currentTicker }} %}
        {{ currentTicker |safe }}
    {% else %}
        <p>NO Graph</p>
    {% endif %}
{% endblock %}

<style>
    .buttonRow {
        width: 100%;
        float: left;
        border: solid 1px blue;
        text-align: center;
    }

    button {
        background: black;
        color: white;
    }
</style>

<script>


    var currentTicker = {{ tickerList.0 }}
        function changeChart(ticker) {
            currentTicker = ticker;
        }
</script>

Here the dictionary I send from the server-side may look like this

{
  "tickerList" : ["GOOGL","TSLA"],
  "GOOGL" : (plotly object),
  "TSLA" : (plotly Object)

}

Depending on the button clicked by the user I want to change the graph (plotly object) on the screen. As you can I have made the necessary buttons and I change “`currentTicker“ variable but I am not sure how I can change the graph in real-time on the screen when the user clicks the button. Could anyone help with this?

Can i control Windows Volume Mixer with Javascript + Arduino

Hi i would like to create my own mixer that can control the output volume of individual apps in the windows volume mixer using an Arduino and specifically JavaScript.

I am learning JS for my job and i think this would be a good little project that i could actual utilize.

What i have learned so far are interactions between JS and HTML web pages so i am wondering is this even possible or would i need to use another language like python.

I’m hoping there is some API that allows me to do this with JS as I am a industrial hardware engineer and python is not something I work with, at least at the minute…

I would appreciate any help, thank you.

ReactJS: Detect which button is clicked

I have this simple requirement that detects which button is clicked. The code is as below:

import React, { useState } from 'react'

const App = () => {
  const data = [
    ['Hotel 1A', ['A']],
    ['Hotel 1B', ['B']],
  ]

  const [sameText, setSameText] = useState(false)

  const changeText = (e: any, index: number, item: any) => {
    console.log(e.target.value)
    console.log(index)
    console.log(item)

    if ((item[e.target.value] = item[index])) {
      setSameText(true)
    }
  }
  return (
    <div className='mx-auto'>
      <div className='flex p-16'>
        {data.map((item, index) => (
          <div className='mx-16' key={index}>
            <div className='p-12'>
              <button onClick={(e) => changeText(e, index, item)} value={index}>
                {item[0]}
              </button>
              <div>{sameText ? 'C' : item[1][0]}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default App

The code above will display text as below:

Hotel 1A      Hotel 1B
A             B

If I click on Hotel 1A, I have like A to be changed to C and if I click on Hotel 1B, only B will change to C. I thought I need to get the value of the button but I could not get it to work.

Any help would be greatly appreciated.

Bootstrap 5 Nested Accordion How to open Top level accordion when opening nested ones through link

so i am trying to create a page with bootstrap 5 nested accordions.
The idea is to have a button that opens a nested accordion within another accordion but i cant get that to work.

The button works and it opens the nested accordion but only if the top level one is already opened previously.

You can check that on this fiddle i made real quick.

JSFiddle

My HTML Code Bellow :

<button data-bs-toggle="collapse" href="#sub-collapseOne"> This should open both Accordion #1 and accordion #1 sub item #1</button>
<button data-bs-toggle="collapse" href="#collapseTwo"> This opens accordion #2</button>

<div class="container">

<div class="accordion" id="accordionExample">
<div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
            Accordion #1
        </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
        <div class="accordion-body">

            <div class="accordion" id="sub-accordionExample">
                <div class="accordion-item">
                    <h2 class="accordion-header" id="sub-headingOne">
                        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#sub-collapseOne" aria-expanded="true" aria-controls="collapseOne">
                            Accordion #1 Sub Item #1
                        </button>
                    </h2>
                    <div id="sub-collapseOne" class="accordion-collapse collapse" aria-labelledby="sub-headingOne" data-bs-parent="#collapseOne">
                        <div class="accordion-body">
                            <strong>This is the first item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
                        </div>
                    </div>
                </div>
                <div class="accordion-item">
                    <h2 class="accordion-header" id="sub-headingTwo">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sub-collapseTwo" aria-expanded="false" aria-controls="sub-collapseTwo">
                            Accordion #1 Sub Item #2
                        </button>
                    </h2>
                    <div id="sub-collapseTwo" class="accordion-collapse collapse" aria-labelledby="sub-headingTwo" data-bs-parent="#collapseOne">
                        <div class="accordion-body">
                            <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
                        </div>
                    </div>
                </div>
                <div class="accordion-item">
                    <h2 class="accordion-header" id="sub-headingThree">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sub-collapseThree" aria-expanded="false" aria-controls="sub-collapseTwo">
                            Accordion #1 Sub Item #3
                        </button>
                    </h2>
                    <div id="sub-collapseThree" class="accordion-collapse collapse" aria-labelledby="sub-headingThree" data-bs-parent="#collapseOne">
                        <div class="accordion-body">
                            <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
            Accordion #2
        </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
        <div class="accordion-body">

            <div class="accordion" id="sub2-accordionExample">
                <div class="accordion-item">
                    <h2 class="accordion-header" id="sub2-headingOne">
                        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#sub2-collapseOne" aria-expanded="true" aria-controls="collapseTwo">
                            Accordion #2 Sub Item #1
                        </button>
                    </h2>
                    <div id="sub2-collapseOne" class="accordion-collapse collapse" aria-labelledby="sub2-headingOne" data-bs-parent="#sub2-accordionExample">
                        <div class="accordion-body">
                            <strong>This is the first item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
                        </div>
                    </div>
                </div>
                <div class="accordion-item">
                    <h2 class="accordion-header" id="sub2-headingTwo">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sub2-collapseTwo" aria-expanded="false" aria-controls="sub2-collapseTwo">
                            Accordion #2 Sub Item #2
                        </button>
                    </h2>
                    <div id="sub2-collapseTwo" class="accordion-collapse collapse" aria-labelledby="sub2-headingTwo" data-bs-parent="#sub2-accordionExample">
                        <div class="accordion-body">
                            <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
                        </div>
                    </div>
                </div>
                <div class="accordion-item">
                    <h2 class="accordion-header" id="sub2-headingThree">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sub2-collapseThree" aria-expanded="false" aria-controls="sub2-collapseTwo">
                            Accordion #2 Sub Item #3
                        </button>
                    </h2>
                    <div id="sub2-collapseThree" class="accordion-collapse collapse" aria-labelledby="sub2-headingThree" data-bs-parent="#sub2-accordionExample">
                        <div class="accordion-body">
                            <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

</div>
</div>

Have tried messing around with data-bs-target and data-bs-parent to no avail.

state href pass scope parameters to new tab

I’m unable to pass $scope value to a new tab via $state.href, it is because the $scope values get destroyed when the $statechanges. my question is how do I persist my values so I can access them on my new tab ?

let stateParams = {
  element: element.id,
  entity: {
        id: $scope.el.id,
        label: $scope.el.reference,
        topic: $scope.el.title
    };
  };

let url = $state.href('element.create', stateParams);
$window.open(url, '_blank');

Better way to inject data between props & axios

What is the better way to inject data in vue files between :

Inject data via props in twig for example or with axios requests when DOM is mounted ?

Both comes from a controller obviously.

{% set data = [] %}

    {% for d in datafromcontroller %}
        {% set data = data|merge([{ name: d.name}]) %}
    {% endfor %}

<component prop="{{ data }}"></component>

or

 mounted() {
    axios
      .get("getData")
      .then((response) => {
        this.data= response.data;
      });
  }

Javascript power and root [duplicate]

simple question
is there an operator for the root as for the power there’s the “* *”.

I tried to search but I couldn’t find it, so I don’t think there is, but if for any reason I didn’t saw but it exist can someone please tell? thx