Java script to play a piano tune is not generating any sound? - javascript

I had chatgpt generate a piano tune and I asked it to wrap in javascript to be played in a browser. However, I can't seem to get the code to play anything? can someone help with this?
<html>
<head>
<title>My Piano Tune</title>
</head>
<body>
<script>
// Create a new audio context
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Define the notes and timing of the tune
const notes = [
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 }
];
// Function to play the tune
async function playTune() {
for (const { note, time } of notes) {
const oscillator = audioContext.createOscillator();
oscillator.frequency.value = note;
oscillator.connect(audioContext.destination);
oscillator.start();
await new Promise(resolve => setTimeout(resolve, time * 1000));
oscillator.stop();
}
}
// Call the function to play the tune
playTune();
</script>
song does not play
</body>
</html>

You need to convert the note to a frequency, and start the song when they actually do something like click (or the browser will block it usually):
function getFrequency(note) {
var notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'],
octave,
keyNumber;
if (note.length === 3) {
octave = note.charAt(2);
} else {
octave = note.charAt(1);
}
keyNumber = notes.indexOf(note.slice(0, -1));
if (keyNumber < 3) {
keyNumber = keyNumber + 12 + ((octave - 1) * 12) + 1;
} else {
keyNumber = keyNumber + ((octave - 1) * 12) + 1;
}
// Return frequency of note
return 440 * Math.pow(2, (keyNumber- 49) / 12);
};
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Define the notes and timing of the tune
const notes = [
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 },
{ note: 'A4', time: 0.5 },
{ note: 'F4', time: 0.5 },
{ note: 'C4', time: 0.5 },
{ note: 'G4', time: 0.5 }
];
// Function to play the tune
async function playTune() {
for (const { note, time } of notes) {
const oscillator = audioContext.createOscillator();
oscillator.frequency.value = getFrequency(note);
oscillator.connect(audioContext.destination);
oscillator.start();
await new Promise(resolve => setTimeout(resolve, time * 1000));
oscillator.stop();
}
}
// Call the function to play the tune
document.getElementById('start').addEventListener('click', function() {
playTune();
});
<html>
<head>
<title>My Piano Tune</title>
</head>
<body>
<button id="start">Start</button>
song does not play
</body>
</html>

Related

How to get refund amount from a given array of objects ? (Kind of complicated..)

Let's say you were given an array of object data from database and you want to get REFUND result.
So you can give the amount of money when a user requests refund. Before we dive into the problem
- 'DEPOSIT' is the money that user deposit
- 'POINT' is like an additional extra money/deposit that the business provide when the amount of deposit is over $30($30 deposit => 3 POINT is given, $50 deposit => 10 POINT is given )
- 'POINT' is not refundable.
- 'DEDUCTION' is the amount of money that user spent.
- THE RULE IS YOU NEED TO SUBTRACT DEDUCTION FROM DEPOSIT FIRST. AND WHEN DEPOSIT BECOMES 0 or NEGATIVE, WE SUBTRACT DEDUCTION FROM POINT (if exists..) - you can realize what it means in the example 2
Let's say I got user 1's deposit history data by typing query.
const queryResult = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -5,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : -5,
type: 'DEDUCTION',
},
];
In this case, the result must become
const result = {
remained_deposit: 40,
remained_point: 10,
balance: 50 (remained_deposit + remained_point),
refundable: 40(remained_deposit)
}
** explain: we have 50 deposit and subtract two deduction from deposit.
(50 -5 -5 = 40)
So, when the user requests refund, the user must get refund $40 (not $50..)
Let's see another case.
const data2 = [
{
date: '2022-10-10 ',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -30,
type: 'DEDUCTION',
},
{
date: '2022-10-11',
amount : -25,
type: 'DEDUCTION',
},
{
date: '2022-10-11',
amount : 10,
type: 'DEPOSIT',
},
];
In this case, the result must become
const result2 = {
remained_deposit: 10,
remained_point: 5,
balance: 15,
refundable: 10
}
As we did above, we subtract deduction from deposit first.
50(deposit) - 30(deduction) = 20 (deposit)
20(deposit) - 25(deduction) = -5(deposit.. becomes negative)
In this case, we calculate with the POINT.
-5(deposit) + 10 (POINT) = 5(POINT)
if the user requests refund at this point, he/she can get nothing.
Because remained balance which is POINT(5) is not refundable.
However since the user deposit 10 after the last deduction,
and if he/she requests refund at this point, remained_deposit 10 will be given to the user.
Let's see one more confusing-looking case
const data3 = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -40,
type: 'DEDUCTION',
},
{
date: '2022-10-11',
amount : 30,
type: 'DEPOSIT',
},
{
date: '2022-10-11',
amount : 3,
type: 'POINT',
},
{
date: '2022-10-11',
amount : -25,
type: 'DEDUCTION',
},
];
In this case, the result must become
const result3 = {
remained_deposit: 25,
remained_point: 3,
balance: 28,
refundable: 25
}
**explanation
50(deposit) - 40(deduction) = 10(deposit)
10(deposit) - 25(deduction) = -15(deposit)
**even though deposit(30) comes first than deduction(-25), we subtract deduction from the very first deposit first.
-15(deposit) + 10(point ) = -5(deposit)
-5(deposit) + 30(deposit) = 25(deposit)
What matters is that the first deposit needs to be whole subtracted first and then POINT is next.
When the user request refund in this case, he/she can get $25.
I hope the examples gave you some clues how you guys must calculate to get the refund.
If you are still confused, please let me know.
And if you guys can understand the problem, I would appreciate if you guys can advise me or give me a better clues, algorithms or solutions.
Thank you.
My JS Code Solution
let totalBalance = 0;
let totalRefund = 0;
// Get total balance
for(let result of results){
totalBalance += result.amount
}
console.log(totalBalance);
// Get total refund --it gets correct answer when it's case4(below), but it's wrong in case5
for(let result of results){
totalRefund += result.amount
// console.log(totalRefund);
if(result.type === 'POINT'){
totalRefund -= result.amount
}
if(totalRefund < 0){
totalRefund = 0;
}
}
// in case 5, the totalRefund supposed to be 15. But its result is 10...
case4
const results = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -45,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : -10,
type: 'DEDUCTION',
},
{
date: '2022-10-11',
amount : 30,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 3,
type: 'POINT',
},
]
// totalRefund = 30 (correct)
50(deposit) - 45(deduction) = 5(deposit)
5(deposit) - 10(deduction) = -5(deposit)
-5(deposit) + 10(point) = 5(point)
the remain_deposit is 30 and remained point is = 8(5+3)
case5
const results = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -45,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : -10,
type: 'DEDUCTION',
},
{
date: '2022-10-11',
amount : 30,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 3,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -10,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : -10,
type: 'DEDUCTION',
},
]
// totalRefund = 10 (wrong)
50(deposit) - 45(deduction) = 5(deposit)
5(deposit) - 10(deduction) = -5(deposit)
-5(deposit) + 10(point) = 5(point)
5(point) - 10(deduction) = -5(deduction)
-5(deduction) + 30(deposit) = 25(deposit)
25(deposit) - 10(deduction) = **15(remained_deposit == refund)**
Googling and code by myself. But still get unwanted/unexpected result.
Some case, the code can get the refund correctly, but in some cases it doesn't.
Not perfect, it does everything if executed in the order in which the operations are made in your array. Even if this does not answer your question completely I hope it helps with some of your doubts
const data1 = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -5,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : -5,
type: 'DEDUCTION',
},
];
const data2 = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -30,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : -25,
type: 'DEDUCTION',
},
{
date: '2022-10-10',
amount : 10,
type: 'DEPOSIT',
},
];
const data3 = [
{
date: '2022-10-10',
amount : 50,
type: 'DEPOSIT',
},
{
date: '2022-10-10',
amount : 10,
type: 'POINT',
},
{
date: '2022-10-10',
amount : -40,
type: 'DEDUCTION',
},
{
date: '2022-10-11',
amount : 30,
type: 'DEPOSIT',
},
{
date: '2022-10-11',
amount : 3,
type: 'POINT',
},
{
date: '2022-10-11',
amount : -25,
type: 'DEDUCTION',
},
];
console.log(calculateRefund(data1))
console.log(calculateRefund(data2))
console.log(calculateRefund(data3))
function calculateRefund(arr){
let remained_deposit = 0;//remaining deposit without the points
let remained_point = 0;//remaining points
let balance = 0;//total remaining
let refundable = 0;//total refundable remaining
let over = 0;//var to help calculate point substraction
arr.forEach(function(element) {
//when money is deposited
if(element.type=='DEPOSIT'){
refundable += element.amount;//refund
balance += element.amount;//total
remained_deposit += element.amount;//deposit
}
//when points are earned
if(element.type=='POINT'){
balance += element.amount;//total
remained_point += element.amount;//points
}
//when deduction is made
if(element.type=='DEDUCTION'){
balance += element.amount;//total
//condition if deduction is higher than remaining deposit
if(remained_deposit < Math.abs(element.amount)){
over = remained_deposit + remained_point + element.amount;//set over
remained_point = over;//points after deduction
remained_deposit = 0;//no remaining deposit left
refundable = 0;//no refund left
} else {
//normal deduction
remained_deposit += element.amount;//deposit
refundable += element.amount;//refund
}
}
});
//create the return object
let result = {
remained_deposit: remained_deposit,
remained_point: remained_point,
balance: balance,
refundable: refundable
}
//return result
return result;
}

Meteor Collection Hooks - How to run the 'after insert' hook only once the previous 'after insert' has finished

Inserts are happening quicker than the after.insert function can process them and what I want to happen after the current document is inserted is dependent on what happened after the previous document was inserted.
I think the short question might be how do I make it synchronous?
FirstCollection.after.insert(function (userId, doc) {
lastDoc = SecondCollection.findOne({}, { sort: { $natural: -1 } });
if (!lastDoc) {
SecondCollection.insert({
startNumber: doc.txNumber,
count: 1,
duration: 264,
lastTx: doc.txNumber,
time: Date.now(),
finishedAt: 0,
});
return;
}
if (lastDoc.finishedAt !== 0) {
if (Date.now() - lastDoc.finishedAt < 60000) {
return;
}
SecondCollection.insert({
startNumber: doc.txNumber,
count: 1,
duration: 264,
last: doc.txNumber,
time: Date.now(),
finishedAt: 0,
});
return;
}
SecondCollection.update(
{ _id: lastDoc._id },
{ $set: { lastTx: doc.txNumber }, $inc: { count: 1 } }
);
if (lastDoc.count === lastDoc.duration) {
SecondCollection.update(
{ _id: lastDoc._id },
{ $set: { finishedAt: Date.now() } }
);
}
});

Discord JS - ssh.exec (i think)

i've got an JS script and i really don't understand why it's not working. Here is the script:
if(params[1] == "info")
{
cmdexist = true;
let totalSeconds = (bot.uptime / 1000);
let days = Math.floor(totalSeconds / 86400);
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let uptime = `${days} days, ${hours} hours, ${minutes} minutes`;
var countservers = 0; bot.guilds.cache.forEach(g => { countservers++ });
message.channel.send(`Please wait... getting informations!`).then((message) => {
var ssh = new SSH({
host: ssh_host,
user: ssh_user,
pass: ssh_pass,
agent: process.env.SSH_AUTH_SOCK
});
ssh.exec('echo $PATH', {}).start();
ssh.exec('hostname', { out: function(serverhostname) {
ssh.exec('uptime -p', { out: function(serveruptime) {
ssh.exec('uptime -s', { out: function(serveruptimesince) {
ssh.exec('cat /etc/redhat-release', { out: function(serverversion) {
ssh.end();
serveruptime = serveruptime.slice(2);
const embed = new Discord.MessageEmbed()
.setTitle("Informations:")
.setThumbnail(bot.user.displayAvatarURL({dynamic : true, size : 2048}))
.setColor('#277ecd')
.addFields
(
{ name: "Developer:", value: `${developername}`, inline: false },
{ name: "Version:", value: `${version}`, inline: false },
{ name: "Invite link:", value: "", inline: false },
{ name: "Last update:", value: `${lastupdate}`, inline: false },
{ name: "BOT uptime:", value: `${uptime}`, inline: false },
{ name: "Last restart:", value: `${restartdate}`, inline: false },
{ name: "Currently in:", value: `${countservers} servers`, inline: false },
{ name: "Server hostname:", value: `${serverhostname}`, inline: false },
{ name: "Server uptime:", value: `${serveruptime}`, inline: false },
{ name: "Server uptime since:", value: `${serveruptimesince}`, inline: false },
{ name: "OS platform:", value: `${serverversion}`, inline: false },
)
.setFooter(copyright);
message.delete();
message.channel.send(embed);
}}); }}); }}); }});
});
}
When i write the command it says me Please wait... getting informations! but never pass.
I really don't understand why it's not working. It's hosted on "gaming VPS" and host , user , pass it's from MySQL VPS. Sorry for my bad english. :) Thanks in advance for help.

Unable to remove Repeatable Job From Bull Queue Node Js

When i tried using this method - removeRepeatableByKey I am getting removeRepeatableByKey is not a function error.
queue_1.taskQueue.removeRepeatableByKey is not a function
I am not able to remove my repeatable job bytaskQueue.removeRepeatable('task', { cron: '0 47 6 * * 4' }); this too
let jobOptions = {
priority: queue_options.priority,
repeat: { cron: '0 47 6 * * 4'},
attempts: 3,
removeOnComplete: true,
jobId: queue_options.job_id,
backoff: 3,
timeout: 60000,
};
taskQueue.add('task', queue_options.data, jobOptions);
JSON of the JOB:
{ id: "repeat:09854c8042eced1337a7d8eec9357528:1552526220000", name: "task", data: { eventName: "test", parameters: [ { my_JSON }, { my_JSON } ] }, opts: { repeat: { count: 1, cron: "0 47 6 * * 4", jobId: "myJobId" }, jobId: "repeat:09854c8042eced1337a7d8eec9357528:1552526220000", delay: 603096068, timestamp: 1551923123932, prevMillis: 1552526220000, priority: 1, attempts: 3, removeOnComplete: true, backoff: { type: "fixed", delay: 3 }, timeout: 60000 }, progress: 0, delay: 603096068, timestamp: 1551923123932, attemptsMade: 0, stacktrace: [ ], returnvalue: null, finishedOn: null, processedOn: null }
I am able to remove the repeatable job now. The problem was i am adding the job to the queue with:
let jobOptions = {
priority: queue_options.priority,
repeat: { cron: '0 47 6 * * 4' },
attempts: 3,
removeOnComplete: true,
jobId: queue_options.job_id,
backoff: 3,
timeout: 60000,
};
taskQueue.add('task', queue_options.data, jobOptions);
And trying to remove the job like:
let job = await taskQueue.removeRepeatable('task', {cron : '0 47 6 * * 4'});
I fixed it by passing the jobOptions and i was able to successfully remove the job from the queue.
let job = await taskQueue.removeRepeatable('task', jobOptions);

Variable into mongodb query

ok this is driving me crazy..
function(amount){
matchingOrder = Order.findOne({
Price: {
$lte: amount
}
}, {
sort: {
Price: 1,
Order_ID: 1
}
});
}
-----does not work
this works:
function(){
amount = 2
matchingOrder = Order.findOne({
Price: {
$lte: amount
}
}, {
sort: {
Price: 1,
Order_ID: 1
}
});
}
in both cases console.log(amount) is 2 so variable gets passed
...sorry for maybe obvious scope or something..im relativly new at this
The only thing coming to my mind could be different types for amount. Try this instead:
function(amount){
matchingOrder = Order.findOne({
Price: {
$lte: parseInt(amount)
}
}, {
sort: {
Price: 1,
Order_ID: 1
}
});
}
function query_am(input){
var amount = input; //pay attention, as pre-condition your input must be a number.
matchingOrder = Order.findOne({
Price: {
$lte: amount
}
}, {
sort: {
Price: 1,
Order_ID: 1
}
});
}
To invoke this function, for example: query_am(2) or query_am(6) . don't do query_am('6')

Categories