Best way to create an ‘online virtual piano’ webpage?

I want to create a basic online midi piano webpage. I know Python very well but not JavaScript yet. What is the best way to do this? Is Django or Flask relevant here? Essentially I just want a super basic midi piano on a webpage and am just looking for a point in the right direction, thanks.

Context: I have made a PyQT5 Desktop App but have now decided I want it as a webpage so I need to completely remake it. I’ve never done any web development. I need Midi and not audio files.

Payload in Redux Toolkit

Can someone explain me what is payload in redux-toolkit?

Where does this value came from?

import { createSlice, PayloadAction } from ‘@reduxjs/toolkit’

export interface CounterState {
value: number
}

const initialState: CounterState = {
value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload
    },
  },
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

how to fire off multiple forms/submit buttons at the same time at the click of one button

I have some tabs, each containing their own form and their own submit button. I want to fire off all the forms and send requests for each form at the click of one button. That one button should essentially click each individual submit button for each form (in this case that button would be the button with class “submit_all”. The html:

div class="tab-content" id="tab_content_one"
 div id="#tab1" class="tab-pane fade in active"  
        = form_tag({ action: "route1" }, method: method) 
          .form-group  
            textarea.form-control  name="words" 
          input.btn.btn-primary type="submit" class="submit" 
 div id="tab2" class="tab-pane fade"  
         = form_tag({ action: "route1" }, method: method)  
          .form-group  
            textarea.form-control  name="words" 
          input.btn.btn-primary type="submit" class="submit" 
 div id="tab3" class="tab-pane fade"  
         = form_tag({ action: "route1" }, method: method) 
          .form-group  
            textarea.form-control  name="words" 
         input.btn.btn-primary type="submit" class="submit" 
input.btn.btn-primary type="submit"  class="submit_all" onclick="goBack()"

I tried using javascript to retrieve all the submit buttons for each of the forms and iterating through and clicking each submit button however that did not work. It ended up only firing off the final form.

function goBack() {
var submit2 = document.getElementsByClassName('submit')

console.log(submit2)
for (i=0; i<=(submit2.length); i++){
  submit2[i].click()
}

Am I doing something wrong? and how else can I go about this?

Why does the console tell me uncaught in promise?

I have a fetch request to delete some lists from my backend, but the console is giving me a complaint. The console says “Uncaught (in promise).”

This is my fetch() in the frontend:

  const handleClickGarbage = (key) => { // for deleting a grocery list
    const temp = loginUserr;

    try {
      console.log('inside click garbage');
      const accessToken = temp.accessToken;
      console.log(accessToken);
      const param = key;
      console.log(param);

      fetch(`http://localhost:3010/v0/grocerylists?listName=${param}`, {
        method: 'DELETE',
        headers: new Headers({
          'Authorization': 'Bearer ' + accessToken,
        }),
      })
        .then((results) => {
          if (!results.ok) {
            throw results;
          }
          console.log(results);
          getCurrentGroceryListTabInfo(); // get the current tab info again because we just updated the info
        });
    } catch (e) {
      console.log(e);
    }
  };

This is my user.js:

exports.deleteGroceryList = async (req, res) => {
  const listNamee = req.query.listName;
  const memberIdd = req.userID;
  console.log('inside delete gl');
  console.log(listNamee);
  console.log(memberIdd);

  const deleted = await db.deleteGroceryList(listNamee, memberIdd);
  console.log('user.js line 286)n');
  console.log(deleted);
  if (deleted === null) {
    res.status(400).send();
  } else {
    console.log('user.js line 292)n');
    res.sendStatus(200);
  }
};

This is my db.js:

exports.deleteGroceryList = async (listNamee, memberIdd) => {
  const listName = listNamee;
  const memberId = memberIdd;

  const select = 'DELETE FROM grocery_list WHERE list_name = $1 AND member_id = $2 RETURNING *';
  const query = {
    text: select,
    values: [listName, memberId],
  };

  const {rows} = await pool.query(query);
  console.log('db.js line 495)n');
  console.log(rows);

  if (rows.length > 0) {
    return rows.length;
  } else {
    return null;
  }
};

And this is my openapi.yaml:

  /grocerylists:
    delete:
      description: Deletes a grocery list from user's existing grocery lists'
      security:
      - bearerAuth: [] 
      parameters:
        - name: listName
          in: query
          description: name of grocery list to delete
          schema:
            type: string
      responses:
        200:
          description: Removed list from grocery lists successfully
        401:
          description: Unauthorised
        400:
          description: Bad Request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

I suspect it is something wrong with my api because console.logging results in the front end shows that user.js returned a status code of 200.:
enter image description here

But then the console also says uncaught promise:
enter image description here

Testing a solidity smart contract with Truffle: how to make it to pass all test cases?

I’m trying this smart contract which has functions to set and get a user. I’m also testing it on JavaScript with mocha and chai tools and for all of this I use Truffle. But the thing is that for the test case “should Add New User”, I’m not getting this test case to pass and I realized that when I’m calling this.storageContract.getUser function and storaging its result on user constant, if I print its content I’m not getting the data I stored when calling this.storageContract.setUser, so when I use checkUserData function, it does not pass.

I wonder how can I make this test case to pass, because I can’t find the error for which it currently fails the test. I deployed this smart contract on Remix IDE and it works well, so the problem must be on the test script.

This is Solidity Smart Contract:

contract SupplyChainStorage is SupplyChainStorageOwnable {
    address public lastAccess;

    constructor() {
        authorizedCaller[msg.sender] = 1;
        emit AuthorizedCaller(msg.sender);
    }

    event AuthorizedCaller(address caller);
    event DeAuthorizedCaller(address caller);

    event UserUpdate(address userAddress);
    event UserRoleUpdate(address userAddress);

    modifier onlyAuthCaller() {
        lastAccess = msg.sender;
        require(authorizedCaller[msg.sender] == 1);
        _;
    }

    struct User {
        string name;
        string contactNo;
        bool isActive;
        string profileHash;
    }

    mapping(address => User) userDetails;
    mapping(address => string) userRole;

    mapping(address => uint8) authorizedCaller;

    function authorizeCaller(address _caller) public onlyOwner returns (bool) {
        authorizedCaller[_caller] = 1;
        emit AuthorizedCaller(_caller);
        return true;
    }

    function deAuthorizeCaller(address _caller)
        public
        onlyOwner
        returns (bool)
    {
        authorizedCaller[_caller] = 0;
        emit DeAuthorizedCaller(_caller);
        return true;
    }

    User userData;
   
    function setUser(
        address _userAddress,
        string memory _name,
        string memory _contactNo,
        string memory _role,
        bool _isActive,
        string memory _profileHash
    ) public onlyAuthCaller returns (bool) {
        userData.name = _name;
        userData.contactNo = _contactNo;
        userData.isActive = _isActive;
        userData.profileHash = _profileHash;

        userDetails[_userAddress] = userData;
        userRole[_userAddress] = _role;

        emit UserUpdate(_userAddress);
        emit UserRoleUpdate(_userAddress);
        return true;
    }

    function getUserRole(address _userAddress)
        public
        onlyAuthCaller
        returns (string memory)
    {
        return userRole[_userAddress];
    }

    function getUser(address _userAddress)
        public
        onlyAuthCaller
        returns (
            string memory name,
            string memory contactNo,
            string memory role,
            bool isActive,
            string memory profileHash
        )
    {
        User memory tmpData = userDetails[_userAddress];
        return (
            tmpData.name,
            tmpData.contactNo,
            userRole[_userAddress],
            tmpData.isActive,
            tmpData.profileHash
        );
    }
}

This is JavaScript test:

const SupplyChainStorage = artifacts.require('SupplyChainStorage');

const _name = 'Mat';
const _contactNo = '0979081091';
const _role = 'PROCESSOR';
const _isActive = true;
const _profileHash = 'Qmadp4L61MaQPX5NFfjqaihnY8r7PmogqZL6wvX1HqvL';

contract('SupplyChainStorage', function(accounts){
    const spenderAddress = accounts[0];
    const authorizedCaller = accounts[1];
    const userAddress = accounts[2];

    beforeEach(async() => {
        this.storageContract = await SupplyChainStorage.new({from:spenderAddress, gas: 6000000});
    });

    it('should Authorize', async() => {
        const {logs} = await this.storageContract.authorizeCaller(authorizedCaller,{from: spenderAddress});

        const authorizedCallerEvent = logs.find(e => e.event === 'AuthorizedCaller');
        assert.exists(authorizedCallerEvent, "AuthorizedCaller does not exists");
    });

    it('should DeAuthorize', async() => {
        const {logs} = await this.storageContract.deAuthorizeCaller(authorizedCaller, {from: spenderAddress});

        const deAuthorizeCallerEvent = logs.find(e => e.event === 'DeAuthorizedCaller');
        assert.exists(deAuthorizeCallerEvent, "DeAuthorizedCaller does not exists");
    });

    it('should Add New User', async() => {
        const {logs} = await this.storageContract.setUser(userAddress,_name, _contactNo, _role, _isActive, _profileHash, {from: spenderAddress});

        checkUserExists(logs, function(result){
            console.log(result);
        });

        const user = await this.storageContract.getUser(userAddress, {from: spenderAddress});
        // console.log(user[0]); it returns undefined value

        checkUserData(user, function(result){
            console.log("checkUserData");
        });
    });
})

function checkUserExists(logs, callback) {
    const updateUserEvent = logs.find(e => e.event === 'UserUpdate');
    assert.exists(updateUserEvent, "UserUpdate does not exists");

    const updateUserRoleEvent = logs.find(e => e.event === 'UserRoleUpdate');
    assert.exists(updateUserRoleEvent, "UserRoleUpdate does not exists");

    callback(true);
}

function checkUserData(user, callback){
    assert.equal(user[0],_name,"Name checked:");
    assert.equal(user[1],_contactNo,"Contact No checked:");
    assert.equal(user[2],_role,"Role checked:");
    assert.equal(user[3],_isActive,"isActive checked:");
    assert.equal(user[4],_profileHash,"Profile Hash checked:");
    assert.isTrue(true);

    callback(true);
}

This is the log I get when running truffle test --network ganache command:

  2 passing (2s)
  1 failing

  1) Contract: SupplyChainStorage
       should Add New User:
     AssertionError: Name checked:: expected undefined to equal 'Mat'
      at checkUserData (test/SupplyChainStorage.js:66:12)
      at Context.<anonymous> (test/SupplyChainStorage.js:49:9)
      at processTicksAndRejections (internal/process/task_queues.js:95:5)

TypeError: Cannot read property ‘1’ of undefined (JavaScript)

I’m making some functions that loop through my 2D array and check if the value in an index is matching the parameter I passed. But I keep getting this error of “TypeError: Cannot read property ‘1’ of undefined at findBookByTitle”

Any suggestions, I have tried everything 🙁

const BooksInfo = [];

function addBook(BookID, BookTitle, Author, Price, Quantity){

    let newBook = [BookID,BookTitle,Author,Price,Quantity]
    BooksInfo.push(newBook);
}

addBook(1,"Start with Why","Simon Sinek", 80.0, 13);
addBook(2, "But how do it know", "J. Clark Scott", 59.9, 22);
addBook(3, "Clean Code", "Rober Cecil Martin", 50.0, 5);
addBook(4, "Zero to One", "Peter Thiel", 45.0, 12);
addBook(5, "You don't know JS", "Kyle Simpson", 39.9, 9);

//console.log(BooksInfo);

function findBookByID(BookID){
    for(i=0; i <= BooksInfo.length; i++){
        if(BooksInfo[i][0] == BookID){
            console.log(BooksInfo[i])
        }
    }
}

function findBookByTitle(BookTitle){
    for(i=0; i <= BooksInfo.length; i++){
        if(BooksInfo[i][1] == BookTitle){
            console.log(BooksInfo[i])
        }
    }
}

function findBookByAuthor(Author){
    for(i=0; i <= BooksInfo.length; i++){
        if(BooksInfo[i][2] == Author){
            console.log(BooksInfo[i])
        }
    }
}

findBookByAuthor("Kyle Simpson");
findBookByID(1);
findBookByTitle("But how do it know");


D3.js Getting event object instead of data after adding ‘onchange’ event to listitem

I used the code showed by this video (see from 24:34 time)

https://www.youtube.com/watch?v=aHJCt2adSWA

to make an interactive bar chart with D3.js Version 7

the video was made in 2020 and used version 5

the strange issue I am facing is that I am getting , when calling console.log(data) in the code below, the event object:

Event {isTrusted: true, type: ‘change’, target: input, currentTarget:
input, eventPhase: 2, …}isTrusted: truebubbles: truecancelBubble:
falsecancelable: falsecomposed: falsecurrentTarget:
nulldefaultPrevented: falseeventPhase: 0path: (9) [input, li, ul,
div#data, div#app, body, html, document, Window]returnValue:
truesrcElement: inputtarget: inputtimeStamp: 239761.39999997616type:
“change”[[Prototype]]: Event D3JSCHART-interactive1.html:131

instead of the data Array (as the presenter is getting in his video)

enter image description here

const listItems=d3
.select('#data')
.select('ul')
.selectAll('li')
.data(MyData)
.enter()
.append('li');
listItems.append('span').text(data => data.region);
listItems.append('input').attr('type','checkbox').attr('checked',true)
.on('change',(data) => {
console.log(data);
});

below the full code

<html lang="fr">
<head>
<style>
#app{
display:flex;
margin:2rem 1rem;
}
#data ul
{
list-style:none;
margin:0;
padding:0
}
#data li
{
margin-bottom:1rem;
padding:1rem;
box-shadow:0 2px 8px rgba(0, 0, 0, 0.6);
width:10rem;
display:flex;
justify-content:space-between;
align-items:center;
font-weight:bold;
}
.label
{
background-color:green;
fill:#ff0077;
font-size:9px;
}

.bar {
fill:#ff0077;}
</style>
<title>D3.JS CHART Interactive 06/03/2022</title>
<!-- https://www.youtube.com/watch?v=aHJCt2adSWA-->
<script src="https://d3js.org/d3.v7.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/d3-scale@4" ></script>
<script src="https://cdn.jsdelivr.net/npm/d3-axis@3"></script>
</head>

<body>
<div id="app">
<div id="chart"><svg></svg></div>
<div id="data"><ul></ul></div>
</div>
<script>
const MyData=
[ 
{id:'d1',value:15, region:'Tunisia'},
{id:'d2',value:13, region:'Algeria'},
{id:'d3',value:17, region:'Egypt'},
{id:'d4',value:28, region:'Lybia'},
{id:'d5',value:19, region:'Sudan'}];

const MARGINS={top:20, bottom:15};
const CHART_Width=600;
const CHART_HEIGHT=400 -MARGINS.top-MARGINS.bottom;

let selectedData=MyData;

const x=d3
.scaleBand().rangeRound([0, CHART_Width]).padding(0.1);
const y=d3
.scaleLinear().range([CHART_HEIGHT, 0]);

const ChartContainer=d3.
select('svg')
.attr('width',CHART_Width)
.attr('height',CHART_HEIGHT +MARGINS.top+MARGINS.bottom);

x.domain(MyData.map(d => d.region));
y.domain([0, d3.max(MyData,d => d.value)+3]);



let unselectedIds=[];

const chart=ChartContainer.append('g');

chart
.append('g')
.call(d3.axisBottom(x).tickSizeOuter(0))
.attr('transform',`translate(0,${CHART_HEIGHT})`)
.attr('color','#4f009e');

function renderChart()
{
chart
.selectAll('.bar')
.data(selectedData, data => data.id)
.enter()
.append('rect')
.classed('bar',true)
.attr('width',x.bandwidth())
.attr('height',data => CHART_HEIGHT -y(data.value))
.attr('x',(data) => x(data.region))
.attr('y',(data) => y(data.value));

chart.selectAll('.bar').data(selectedData).exit().remove();

chart
.selectAll('.label')
.data(selectedData, data => data.id)
.enter()
.append('text')
.text((data) => data.value)
.attr('x',data => x(data.region)+x.bandwidth()/2)
.attr('y',data => y(data.value)-7)
.attr('text-anchor','middle')
.classed('label',true);

chart.selectAll('.label').data(selectedData).exit().remove();
}


renderChart();



const listItems=d3
.select('#data')
.select('ul')
.selectAll('li')
.data(MyData)
.enter()
.append('li');
listItems.append('span').text(data => data.region);
listItems.append('input').attr('type','checkbox').attr('checked',true)
.on('change',(data) => {
console.log(data);

/*if(unselectedIds.indexOf(data.id) === -1)
{unselectedIds.push(data.id);}
else
{unselectedIds=unselectedIds.filter(id => id !== data.id);}

SelectedData=MyData.filter(
(d) => unselectedIds.indexOf(d.id) === -1

);
renderChart();
*/
});



</script>
</body>
</html>

Eventlistener only works after clicking twice

My addEventListener only works when I click the image twice. The console log does say that the item has been deleted from the database, I see this as well in the array. This means that the function works, but why does it take two times to actually delete the item from the DOM?

const addToDom = async (data) => {
const item = document.createElement("li");
item.innerHTML = '';

data.forEach((task) => {
    const deleteImage = document.createElement('img');
    const toDoList = document.getElementById("todo-list");
    deleteImage.id = task._id;
        
    item.classList.add("task-item");
    deleteImage.src = 'bin.png';
    item.innerHTML = task.description;
    toDoList.appendChild(item); 
    item.appendChild(deleteImage);

    deleteImage.addEventListener("click", (event) => {

            const idToDelete = event.target.id;
            toDoList.removeChild(item);
            item.innerHTML = '';
            console.log(`Delete ${task.description}`);
            deleteData(idToDelete);
            loadData(data);
    });
    
});

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code.
test.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title
</head>

<body>
    <script type="module" src="./test.js"></script>
</body>

</html>

test.js

import * as tf from "./node_modules/@tensorflow/tfjs";
import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter";

const MODEL_URL = './model.json';

const model = await loadGraphModel(MODEL_URL);
const cat = document.getElementById('cat');
model.execute(tf.browser.fromPixels(cat));

Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Can anyone help to solve this? Thank you

Create a Javascript vidiprinter

I’m using javascript on a webpage and looking for a way to create a vidiprinter effect to output text to a text area on a web page. I mean in the style of how they use to do the latest football results back in the 80’s and with an ‘*’ as the flashing cursor.

For example it would first show * flashing for a couple of seconds and then start typing out the text one letter at a time with the * flashing as it goes along.

Hope that makes sense with what I’m after. I’ve tried myself using different methods but with no success.