How to hold a function from finishing until the user clicks a button or until a variable is set

Let me explain since that probably doesn’t make much sense.

I got this snake game where the user can select the difficulty of the game. All of the difficulties are done as buttons but I also added this extra button as a custom difficulty.

Now when the normal difficulties are clicked, it’s supposed to go to another module and then based on the button clicked, get the speed for that chosen difficulty and return it and then after that the game with the snake speed starts.

But when the custom button is clicked, another section is supposed to show up. This section has an input to ask for the speed and also a button to click when you chose the speed.

Well I added an event listener that when that button is clicked, it returns the speed of the snake from the input but the problem is that by the time the button get clicked, the function is already done and it pretty much returns undefined. So the speed is undefined and the game kinda ‘crashes’.

let custom_page = document.querySelector('#custom_inputs');
let speed_input_holder = document.querySelector('#custom_speed');
let is_clicked = false;
let temp_number = 0;

custom_btn.addEventListener('click', () => {
    is_clicked = true;
    temp_number = speed_input_holder.value;
})


for(let btn of button_parent.children){
    btn.addEventListener('click', (event) => {
        snake_speed = startGame(event.target);
        setTimeout(() => {
                 window.requestAnimationFrame(main); // starts game
        }, 1100);
    })
}

function startGame(btn){
   if(btn.className != '5'){ //btns have classes. 5 is custom, rest are basic
        speed = setUpSpeed(btn); // returns speed as a number
        return speed;
    } else {
        function isDone(){
            while(!is_clicked){
                 isDone();
            }
            is_clicked= false;
            return temp_number; // this is the speed 
        }
        isDone();
    }
}


I tried to simplify the code from how it actually is.
I tried to add something to check whether the button has been clicked. If it has, get the speed that I saved inside a variable and if it hasn’t, then simply run the function again. Basically a loop, but this kinda returns an error because of making so many calls.

let val = false;
function isDone(){
      while(!val){
           isDone();
      }
      showGame(custom_page);
      speed = valueHolder.value;
}
isDone();

I tried to fix this with an async function, but doing something like
snake_speed = await getSpeed(class) doesn’t really do much because await doesn’t seem to work on these “normal” functions and snake_speed just becomes undefined again. I’m not really familiar with promises and async/await so I just tried to wing it here, but it didn’t work.

async function info(){
     let spd = await startGame(event.target);
     spd.then(function(snake_speed){
          setTimeout(() => {
              window.requestAnimationFrame(main); // starts game
          }, 1100);
     })
  }
  info();

Can you give me any ideas?

Unable to upload image using Api in Nodejs

I am working with Nodejs and i am using express js,Right now i am trying to upload image using API,But right now i am getting following error

Route.post() requires a callback function but got a [object Undefined]


Here is my “api.router.js” file

const multer  = require('multer')

router.post('/uploadimage', apiController.upload);

And here is my controller file(apicontroller) code

const storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, 'uploads/')

  },

  filename: function (req, file, cb) {

    cb(null, file.fieldname + '-' + Date.now())

  }

})

const upload = multer({ storage: storage })


I need to made 9 divs in each div should be random number(1-9 but not repeatable)

Hello here I need to check the past z variable with a new one(z),please help

Hello here is what i got

<html>
    <head>
        <link rel = "stylesheet" href = "style.css">
    </head>
    <body onload = "myFunction()" id = "body">
        <div id = 'play_ground'>
        </div>
        <b2>PLAY<b2>
        <script src = "Game-9.js"></script>
    </body>
</html>
var play_box = document.getElementById('play_ground');
function myFunction(){
    for (i = 1; i <= 9; i++){
        var z = Math.floor(Math.random() * 10)
             play_box.innerHTML += '<div class = "box">'+ z +'</div>' };
        }
}

I just cant imagine how can i check the past z variable with a new one(z),please help

What does createConnection() and connect() method do in NodeJS MySql module?

This is how we connect our NodeJS app with Mysql database using MySQL module:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {
  if (err) {
    console.error('Error connecting to database:', err);
    return;
  }
  console.log('Connected to database!');
});

I understand we need to call both createConnection() and connect() to make a connection to the database.

However, I want to understand the individual role of the createConnection() and connect() methods.

  • What does createConnection() do?
  • What does connect() do?

Calling client side URL across domains in JavaScript [closed]

It wasn’t until yesterday that I discovered the concept of bookmarklets to access a web page’s DOM. I want to use it to capture the currently playing song on a radio station website and send it to my own database. It works fine, but the fetch statement throws CORS errors. They don’t break the script, but it looks kind of ugly. Here’s my bookmarklet:

javascript: (function() {
    // some code to get the current playing song (myArtist, myTitle and myStartTime)
    let url="https://www.mywebsite.com/insert_song.aspx?artist="+myArtist+"&title="+mySong+"&tstart="+myStartTime;
    fetch(url);
})();

I have no administrative rights on my website to configure CORS, so what other options are there to avoid these CORS errors?

Javascript: Combine array of objects based on the matching value [closed]

I would like to merge array objects, Below is the array if roundNo matches, should combine dates separated by comma and combing into a single object like mentioned as an expected output below. Date order needs to be preserved while combining.

Input:

const dataArray =
[{"date":"Dec 15—28","round":"Round 1","roundNo":"1"},
{"date":"Jul 1—7","round":"Round 1","roundNo":"1"},
{"date":"Jan 8—14","round":"Round 2","roundNo":"2"},
{"date":"Jan 7—10","round":"Round 2","roundNo":"2"}
{"date":"Jan 15—21","round":"Round 3","roundNo":"3"}]

Expected output

const dataArray =
[{"date":"Dec 15—28,Jul 1—7","round":"Round 1","roundNo":"1"},
{"date":"Jan 8—14,Jan 7—10","round":"Round 2","roundNo":"2"},
{"date":"Jan 15—21","round":"Round 3","roundNo":"3"}]

I don’t see MongoDB data on Heroku deploy

I have problem with getting data in my MERN app deployed on Heroku. Deployed app works fine locally – both app and MongoDB – but only locally. When I try to open web on other comp I got data error:

Failed to load resource: net:: ERR_Connection_Refused
localhost:8000/api/ads:1

I’ve read many threads about that problem. I think I’ve missed something. If you have any idea what I should do I’d be very glad for info.

Here is what I did:

  • I’ve set general network access on 0.0.0.0/0 (MONGODB Atlas)
  • I’ve set config vars on heroku

Here is my code:

server.js

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const session = require('express-session');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo');
const bcrypt = require('bcryptjs');

// set dotenv
dotenv.config();

// import routes
const noticesRoutes = require('./routes/notices.routes');
const authRoutes = require('./routes/auth.routes');

const app = express();

/* MIDDLEWARE */

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({ 
  secret: bcrypt.hashSync('pass', 8), 
  store: MongoStore.create({ mongoUrl: process.env.DB_URL, collection: 'sessions' }), 
  resave: false, 
  saveUninitialized: false,
  cookie: {
    secure: process.env.NODE_ENV == 'production',
  }, 
}))

// access to storage folder
app.use(express.static(path.join(__dirname, '/client/build')));
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, '/uploads/')));

// use routes
app.use('/api', noticesRoutes);
app.use('/auth', authRoutes);

// error status
app.use((req, res) => {
  res.status(404).send('404 not found...');
})

// React website
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname + '/client/build/index.html'));
});

/* MONGOOSE */
const NODE_ENV = process.env.NODE_ENV;
let dbUri = '';
const password = process.env.PASSDB;

if(NODE_ENV === 'production') dbUri = 'mongodb+srv://MarcinEden:' + password + '@cluster1.sg1w6lh.mongodb.net/RealEstateBoard?retryWrites=true&w=majority';
else dbUri = 'mongodb+srv://MarcinEden:' + password + '@cluster1.sg1w6lh.mongodb.net/RealEstateBoard?retryWrites=true&w=majority';

mongoose.connect(dbUri, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;

db.once('open', () => {
  console.log('Successfully connected to the database');
});
db.on('error', err => console.log('Error: ' + err));

/* START SERVER */
const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log('Server is running on port: '+ port);
});

Env vars

env.file
NODE_ENV = production
DB_URL = mongodb+srv://MarcinEden:[email protected]/RealEstateBoard?retryWrites=true&w=majority

If you need any more data, please let me know.

ChartJS : represent data over timeslots

I’ve been looking everywhere but I cannot find the solution to my problem.
I have a dataset like so : {“2023-03-31T00:00:00”: [“B”, “C”], “2023-03-31T00:20:00”: [], “2023-03-31T00:40:00”: [], …}
Each timestamp is 20 minutes after the previous one and associated with a array of elements. I need to bar graph the size of the array over time.

My problem is : each datapoint is actually representing a number of element over a timeslot starting from the timestamp and ending 20 minutes later, so for example, the first bar would amount to 2 (two elements in the array) but has to fill the space between the 00:00 and 00:20 ticks on my X Axis.

The midnight bar is centered over 00:00

I didn’t find any solution that works for me. Everything I tried centers the bar on the timestamp but in my case I would like to have the left of the bar clip to the timestamp.

I’ve tried changing the alignment of the labels, setting the grid offset to true or false, “cheating” with a 10 minutes time offset on the labels (half of my timestep). Everytime it turned out to be too complicated or not conclusive.

Is there a simple way to achieve what I want, which is moving all the bars half of their size to the right, i.e. cliping the left edge to the label of the datapoint.

I’m lost right now so any help would be much appreciated.

Here is the current config of my graph :

const config = {
  type: 'bar',
  data: data,
  options: {
    responsive: true,
    scales: {
        x: {
            type: 'time',
            time: {
                unit: 'hour',
                displayFormats: {
                    'hour': 'HH:mm'
                },
            },
            min: new Date("2023-03-31T00:00:00Z"),
            max: new Date("2023-04-01T00:00:00Z"),
            grid:
            {
                offset: false,
            },
        },
        y: {
            min: 0,
            ticks:
            {
                stepSize: 1,
            }
        }
    },
    plugins: {
        legend: {
            // Removes the colored rectangle next to the dataset label
            labels: {
                boxWidth: 0,
            },
            // Removes the ability to hide the dataset on click on the label (makes no sense since we only have one
            // dataset)
            onClick: null,
        },

        tooltip: {
            // Removes the colored squared on the tooltip label
            displayColors: false,
            callbacks: {
                // Using our custom tooltip labels
                label: tooltipLabel,
                title: tooltipTitle,
            },
        },
    },
  }
};

Cheers,
Prims

Template rendering in odoo

I want to render the template (.xml file) having id ‘dashboard_example’ from javascript code in odoo15. I am quite new to odoo and just got to know about Qweb2. Can you please help in finding out how should I render the template and what all dependencies and other things I need to add in order to get it working?

I tried with Qweb but it says Qweb is not defined

Blockchain data is not written to the MongoDB database

I started delving into blockchain development and implemented one in Node.JS. I managed to write the data into a file and read it from there, but the hosting environment does not allow this, and so I would like to implement this using MongoDB. I did it to some extent, but the problem is that the data is somehow not written to the database after running the script and navigating to the hosted page. No error messages or success messages come back, everything looks normal on the console. If anyone could help, I would greatly appreciate it. I am attaching my code and console output.
My code:

class Block {
    constructor(index, transactions, timestamp, previousHash, nonce = 0) {
        this.index = index;
        this.transactions = transactions;
        this.timestamp = timestamp;
        this.previousHash = previousHash;
        this.nonce = nonce;
    }

    computeHash() {
        const blockString = JSON.stringify(this, Object.keys(this).sort());
        return crypto.createHash('sha256').update(blockString).digest('hex');
    }
}

class Blockchain {
    constructor() {

        /*const chainData = await readChain();
        if (chainData === '') {
            this.chain = [this.createGenesisBlock()];
            fs.writeFileSync('blockchain.json', JSON.stringify(this.chain));
            await writeChain(JSON.stringify(this.chain));
        } else {
            this.chain = JSON.parse(chainData);
        }
        
        this.chain = [this.createGenesisBlock()];
        this.difficulty = 2;*/
    }
    
    async initialize() {
        const chainData = await this.readChain();
        console.log("Chain data: ",chainData);
        if (!chainData) {
            this.chain = [this.createGenesisBlock()];
            //fs.writeFileSync('blockchain.json', JSON.stringify(this.chain));
            console.log(JSON.stringify(this.chain));
            await this.writeChain(JSON.stringify(this.chain));
        } else {
            this.chain = JSON.parse(chainData);
        }
        
        this.chain = [this.createGenesisBlock()];
        this.difficulty = 2;
    }

    static async create() {
        const o = new Blockchain();
        await o.initialize();
        return o;
    }

    async readChain(){
        client.connect(err => {
            const collection = client.db(DB).collection(COLL);
            collection.find({}).toArray((err, docs) => {
                if (err) {
                    console.log(err);
                    client.close();
                } else {
                    console.log('Found documents:', docs);
                    client.close();
                    return docs;
                }
            });
        });
    }
    
    async writeChain(data){
        const newValues = { $set:{ chain: data} };
        client.connect(err => {
            const collection = client.db(DB).collection(COLL);
            collection.updateOne({ }, newValues, (err, result) => {
                if (err) {
                    console.log(err);
                    client.close();
                } else {
                    console.log('Document modified:', result.result);
                    client.close();
                }
            });
        });
    }
    
    

    createGenesisBlock() {
        return new Block(0, [{ fromAddress: 'root', toAddress: 'petertill', amount: 100}], Date.now(), '0');
    }

    getLatestBlock() {
        return this.chain[this.chain.length - 1];
    }

    async addBlock(newBlock, proof) {
        const previousHash = this.getLatestBlock().computeHash();
        if (previousHash !== newBlock.previousHash) {
            return false;
        }
        if (!this.isValidProof(newBlock, proof)) {
            return false;
        }
        this.chain.push(newBlock);

        //fs.writeFileSync('blockchain.json', JSON.stringify(this.chain));
        await this.writeChain(JSON.stringify(this.chain));

        
        return true;
    }

    isValidProof(block, blockHash) {
        return blockHash.startsWith('0'.repeat(this.difficulty)) && blockHash === block.computeHash();
    }

    proofOfWork(block) {
        block.nonce = 0;
        let computedHash = block.computeHash();
        while (!computedHash.startsWith('0'.repeat(this.difficulty))) {
            block.nonce++;
            computedHash = block.computeHash();
        }
        return computedHash;
    }

    async addTransaction(transaction) {
        const { fromAddress, toAddress, amount } = transaction;
        if (this.getBalance(fromAddress) < amount) {
            return { status: false, message: 'Insufficient balance' };
        }

        /*ToDo: if the latest block's transactions are 
        less than something, add transactions to it. Otherwise,
        create new block. I may not need very high number of
        transactions each block*/

        //Adding only two transactions may not be optimal in real blockchain
        const newBlock = new Block(this.chain.length+1, [transaction], Date.now(), this.getLatestBlock().computeHash());
        //console.log(newBlock);
        this.addBlock(newBlock, this.proofOfWork(newBlock));
        
        //this.getLatestBlock().transactions.push(transaction);
        return { status: true, message: 'Transaction added successfully' };
    }

    async getBalance(address) {
        let balance = 0;
        for (const block of this.chain) {
            for (const transaction of block.transactions) {
                if (transaction.fromAddress === address) {
                    balance -= transaction.amount;
                } else if (transaction.toAddress === address) {
                    balance += transaction.amount;
                }
            }
        }
        return balance;
    }

    async getBlockchain() {
        //ToDo: Remove JSON.stringify() if I don't want to see transactions
        return JSON.stringify(this.chain.map(block => ({ ...block, transactions: [...block.transactions] })) );
        
    }
}

/*const myCoin = new Blockchain();

myCoin.addTransaction({ fromAddress: 'petertill', toAddress: 'John', amount: 10 });
const { status, message } = myCoin.addTransaction({ fromAddress: 'John', toAddress: 'Bob', amount: 10 });
if (status) {
    console.log(message);
} else {
    console.log(`Transaction failed. Message: ${message}`);
}
myCoin.addTransaction({ fromAddress: 'Bob', toAddress: 'petertill', amount: 5});
/* Bányászat*//*
const latestBlock = myCoin.getLatestBlock();
console.log(latestBlock.computeHash())
const newBlock = new Block(latestBlock.index + 1, latestBlock.transactions, Date.now(), latestBlock.computeHash());
const proof = myCoin.proofOfWork(newBlock);
myCoin.addBlock(newBlock, proof);*/
/*
console.log(`Peter's balance: ${myCoin.getBalance('Peter')}`);
console.log(`John's balance: ${myCoin.getBalance('John')}`);
console.log(`Bob's balance: ${myCoin.getBalance('Bob')}`);

console.log(myCoin.getBlockchain());
*/

app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', {
    successRedirect: '/success',
    failureRedirect: '/error'
}));

app.get('/success', async (req, res) => {
    // Check if the user is authenticated
    /*if (!req.user) {
        return res.redirect('/error');
    }*/
    //const Coin = new Blockchain();
    const Coin = await Blockchain.create();
    const { status, message } = await Coin.addTransaction({ fromAddress: 'petertill', toAddress: 'John', amount: 10 });
    if (status) {
        console.log(message);
    } else {
        console.log(`Transaction failed. Message: ${message}`);
    }
    console.log(`Peter's balance: ${await Coin.getBalance('petertill')}`);
    console.log(`John's balance: ${await Coin.getBalance('John')}`);
    console.log(`Bob's balance: ${await Coin.getBalance('Bob')}`);
    //res.render(__dirname + "/home.html", {name:req.user.username, balance:await Coin.getBalance(req.user.username), pfp:req.user.photos[0].value});
    //res.sendFile(__dirname + "/index.html");
    res.send(`balance: ${await Coin.getBalance('petertill')}`);
    // Render the success page with the user's credentials
    //res.send(`Welcome ${req.user.displayName}! Your Github username is ${req.user.username}.`);
});

Console output:

Hint: hit control+c anytime to enter REPL.
Example app listening on port 3000
Chain data:  undefined
[{"index":0,"transactions":[{"fromAddress":"root","toAddress":"petertill","amount":100}],"timestamp":1681403116454,"previousHash":"0","nonce":0}]
Transaction added successfully
Peter's balance: 90
John's balance: 10

Bob's balance: 0

I’ve tried abbreviating the async functions and writing out the variables, but I can’t figure out what the problem might be.

A very basic question about building a chrome extension with html css and js

I’m a beginner in building codes, and I’m building a chrome extension. I have done all the things the book told me, but it doesn’t work. This is part of my HTML and Js code. If I check the “clear-history-checkbox”check box, I want the JS to delete all the history.

로그삭제 <input type="checkbox" id="clear-history-checkbox" onclick="clearHistory()">

JS: function clearHistory() {
  chrome.history.deleteAll(function() {
    alert("History cleared!");
  });
}

I’ve placed in body and head, but it didn’t work.

How to do error handling using react-dropzone

Working on ReactJS working on drag and drop multiple files upload functionality Using react-dropzone libraries. I’m not able to display errors message for file limit, same as I need error message for file types I’m Using below code for onrejected function.to display errors but I’m not able to do how to display error for rejected files based on error type.


function DragandDrop(props) {

  const {

    acceptedFiles,

    fileRejections,

    getRootProps,

    getInputProps

  } = useDropzone({    

    maxFiles:2

  });

  const acceptedFileItems = acceptedFiles.map(file => (

    <li key={file.path}>

      {file.path} - {file.size} bytes

    </li>

  ));

  const fileRejectionItems = fileRejections.map(({ file, errors  }) => { 

   Console.log(file)

  });

  return (

    <section className="container">

      <div {...getRootProps({ className: 'dropzone' })}>

        <input {...getInputProps()} />

        <p>Drag 'n' drop some files here, or click to select files</p>

        <em>(2 files are the maximum number of files you can drop here)</em>

      </div>

        {acceptedFileItems}

        {fileRejectionItems}

    </section>

  )

<DragandDrop />```

React setState default value type

I am new to React, but I struggle to find the error in what I am writing.

The objective is to show a list of users, asking it to a server via socket.io. My original code is as follows:

// the list of users
const [users, setUsers] = useState()

useEffect(() => {
    if (socket == null) return

    // listen once to the get user event
    socket.once('load-users', userList => {
        console.log('received type', typeof(userList), ':', userList)
        setUsers(userList)
    })

    console.log('emitting get users')
    // ask the server for the users
    socket.emit('get-users', {all: true})
}, [socket, users])

When rendering the component I wanted to return a simple list:

return (
    <ul>
        {users.map((user) => <li key={user.name}>{user.name} | {user.password}</li>)}
    </ul>
)

This gives me an ominous error in the browser:

Compiled with problems:
×
ERROR
undefined is not a function (near '...users.map...')
Dashboard@http://localhost:3000/static/js/bundle.js:184:24
...

After some hours struggling I tried to initialize the state to an array

const [users, setUsers] = useState([])

And lo and behold, it works! The real problem is that I don’t know why.

Why is the initial type of the state so important? Why setState can’t change it?

How to get around waiting for a new page to load and selecting an id that wasn’t visible on the previous page

I’m trying to create a script for a browser game I’m playing using the scripty extension for chrome with javascript.

When I simulate a button click, I’m pretty sure it’s bringing up a new page to submit the command.

`//selecting location
document.getElementsByClassName(“target-input-field target-input-autocomplete ui-autocomplete-input”)[0].value = “433|539”;

//sword count
document.getElementById(“unit_input_sword”).value = “2”;

//spear count
document.getElementById(“unit_input_spear”).value = “2”;
`

this works ^

the problem is after I simulate the target_attack click, it brings up a new page and I cant find the id. I was thinking I could use window.onload() for this but I just haven’t managed to get it to work, or an async await function, which again I can’t get to work.

The below code is the last of what I was trying to get work before I’ve now give up and ask for help.

`const submit = async function () {
return document.getElementById(“target_attack”).click();
};

submit().then(function() {

    document.getElementById("troop_confirm_submit").click();    

});
`

Apologies for the the bit of a mess, it’s my first time posting.

Expecting after the target_attack click is triggered, the troop_confirm_submit get’s triggered right after.

Uncaught Type Error Within my Array Statement

As the title says, I am getting the following error in my code

Uncaught TypeError: Cannot read properties of undefined (reading ‘length’)

This is the location of the error

//Initial Array for ovens
var ovens_init = new Array();
ovens_init[1] = [];
ovens_init[2] = [];
ovens_init[3] = [];
ovens_init[4] = [];
ovens_init[5] = [];


//Figures out the max length of the inital arrays
var oven_max_length = 0;
for (i = 1; i < 6; i++){
  if(ovens_init[i][0].length > oven_max_length){
    oven_max_length = ovens_init[i][0].length;
  }
}

The code runs fine when they array has data but when its empty I get the following code above. What can I add to my code to allow the program to run, even when it is empty?