How to make oscillator loudness match the loudness of a sample?

I want a tone from an oscillator to play under an audio clip of a song. How do I make the tones loudness match the loudness of the sample? I want the tone to be quieter when the song is quieter, and the tone to be louder at the louder parts. I have used the createAnalyzer to detect the volume of the sample, but the code does not work.

const audioContext = new AudioContext();
const audiodiv = document.querySelector('.audiodiv')
const buffer = audioContext.createBuffer(
    1,
    audioContext.sampleRate * 1,
    audioContext.sampleRate
);

const channelData = buffer.getChannelData(0)

for (let i = 0; i < buffer.length; i++){
    channelData[i] = Math.random() * 2 - 1;
}
const primaryGainControl = audioContext.createGain()
primaryGainControl.gain.setValueAtTime(0.005, 0);
primaryGainControl.connect(audioContext.destination);


const samplebutton = document.createElement('button')
samplebutton.innerText = 'sample'
samplebutton.addEventListener('click', async () => {
    let volume = 0
    const response = await fetch('testsong.wav')
    const soundBuffer = await response.arrayBuffer()
    const sampleBuffer = await audioContext.decodeAudioData(soundBuffer)
    const analyzer = audioContext.createAnalyser()
    volume = analyzer.frequencyBinCount
    const sampleSource = audioContext.createBufferSource()
    sampleSource.buffer = sampleBuffer

    sampleSource.playbackRate.setValueAtTime(1, 0)


    sampleSource.connect(primaryGainControl)
    sampleSource.start()
})
audiodiv.appendChild(samplebutton)

const toneButton = document.createElement('button')
toneButton.innerText = "tone"
toneButton.addEventListener("click", () => {
    const toneOscillator = audioContext.createOscillator();
    toneOscillator.frequency.setValueAtTime(150, 0)
    toneOscillator.type = "sine"
    toneOscillator.connect(oscGain);
    toneOscillator.start()
    toneOscillator.stop(audioContext.currentTime + 5)

    const oscGain = audioContext.createGain()
    oscGain.gain.value = volume
    oscGain.connect(primaryGainControl)
})
audiodiv.appendChild(toneButton)

Is there an official implementation of ECMAScript Language Specification?

I’m interesting in how JS source code works and seems that I should to use ECMAScript® Language Specification. In my case I tried to write my own implemetetion of Function.prototype.call

Function.prototype._call = function (thisArg = {}, ...arg) {
  // 1. Let func be the this value.
  let func = this
  // 2. If IsCallable(func) is false, throw a TypeError exception.
  if (typeof func !== 'function') {
    throw new TypeError(this + "isn't callable")
  }
  // 3. Perform PrepareForTailCall().
  thisArg.func = func
  // 4. Return ? Call(func, thisArg, args).
  return thisArg.func(...arg)
}

It works, but I’m not sure that my implementation is correct and would like to compare it with the “official” implementation. Where may I find code references for ECMAScript examples? Thank you!

How to pass a value to a Bootstrap modal in Django

I’m trying to implement a feature where I get to change a product by passing its id to a modal and change it there, then reflect the changes in the same page, where the user can click on the product name, a modal page appears with the product name and a list of products, then he can change the product from the list of products, click save changes, the modal page closes, and the product is now updated.

The problem is that I was facing difficulty in passing the product id to the modal div that exist in the same template, but couldn’t figure it out, then I saw Martín De la Fuente‘s approach and tried it, but it didn’t work with me as well.

It shows me this error message:

django.urls.exceptions.NoReverseMatch: Reverse for 'products_modal' not found. 'products_modal' is not a valid view function or pattern name.

My code is as the following:

In product template:

Sending product id to the product_modal template:

<td>
<a href="#" class="open-modal" data-url="{% url 'products_modal' product.id %}"><span>{{product.name}}</span></a> 
</td>

Creating an empty div to insert the product_modal in it:

<div id="product-modal-div"></div>

Javascript part:

<script>
   var productModalDiv=$("#product-modal-div")
   $(".open-modal").on("click",function(){
       $.ajax({
           url:$(this).attr("data-url"),
           success:function(data){
            productModalDiv.html(data);
            $("#ProductModal").modal();
           }
       })
   })
</script>

in product modal template:

<div class="modal fade" id="ProductModal" tabindex="-1" role="dialog" aria-labelledby="ProductModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="ProductModalLabel">Change</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
                <form method="post">
                    <div class="form-group">
                        <label for="product" class="col-form-label">Product:</label>
                        <select class="custom-select" id="product">
                            {% for product in products_list %}
                            <option value="{{product.id}}" selected>{{product.name}}</option>
                            {% endfor %}
                        </select>
                    </div>
              </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Save Changes</button>
                <button type="button" class="btn btn-light border-primary text-primary" data-dismiss="modal">Cancel</button>
            </div>
          </div>
        </div>
      </div>

In urls.py:

path('products-modal/<int:product_id>', ProductsChange.as_view(), name='products_modal'),

In views.py:

class ProductsChange(ListView):
    model = Medicine
    template_name = 'pharmacy/products_modal.html'
    context_object_name = 'products_list'

    def get_queryset(self):
        queryset= super().get_queryset()
        queryset=queryset.filter(id=self.kwargs.get('product_id'))
        return queryset

I tried to follow the existed solution but it didn’t work, so if you guys know what’s the missing part in my code please let me know.
thank you.

Error: Debug Failure. False expression: Non-string value passed to `ts.resolveTypeReferenceDirective`,

I don’t know why am I getting the following error which say:

Error: Debug Failure. False expression: Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.

When i try to import the package inquirer in my nodejs application.

console.log("Hello world!");
import inquirer from "inquirer";
....

To run the application I’m using ts-node and I’m running it as follows:

ts-node index.ts

This is my package.json file:

{
....
     "dependencies": {
    "chalk": "^4.1.2",
    "cors": "^2.8.5",
    "cross-fetch": "2.6.1",
    "dotenv": "^16.0.1",
    "inquirer": "^8.2.4",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.3"
  },
  "devDependencies": {
    "@types/chalk": "^2.2.0",
    "@types/cors": "^2.8.12",
    "@types/inquirer": "^8.2.1",
    "@types/node": "^17.0.42",
    "nodemon": "^2.0.16",
    "ts-node-dev": "^2.0.0"
  }
....
}
  • I’ve tried to change the versions of inquirer and typescript but still it did not work.

What can be possibly the problem.

Got a problem with React useContext – returns undefined and have no idea what’s wrong

As title, I am learning React and I decided to use useContext function in my app for the first time. When I try to fetch useContext value, it returns undefined no matter what. I’ve tried a lot of combinations with .Provider in main file, nothing has changed.

App.js

import React, { useState } from 'react'
import './index.css'
import Data from './data.json'
import Comment from './Comment'

function App() {

  const [content, setContent] = useState((Data))
  const LoggedUser = React.createContext(Data.currentUser.username)
  const comments = content.comments

  return (
    <LoggedUser.Provider value={Data.currentUser.username}>
      {comments.map((value) => {
        <Comment key={value.id} image={value.user.image.png} username={value.user.username} created={value.createdAt} content={value.content} score={value.score} replies={value.replies} />
      })}
    </LoggedUser.Provider>
  )
}

export default App

Comment.js

import React from 'react'
import Reply from './Reply'

function Comment(props) {
  return (
    <div className='container'>
        <div className='comment'>
            <div className='header'>
                <img src={props.image} alt='image' />
                <span>{props.username}</span>
                <span>{props.created}</span>
            </div>
            <div className='content'>
                {props.content}
            </div>
            <div className='footer'>
                <div className='input'>
                    <img src='./images/icon-plus.svg' alt='plus' />
                    <img src='./images/icon-minus.svg' alt='minus' />
                    {props.score}
                </div>
                <div className='reply'>
                    <img src='./images/icon-reply.svg' alt='reply' />
                    <span>Reply</span>
                </div>
            </div>
        </div>
        {props.replies &&
            props.replies.map((value) => {
                return <Reply key={value.id} image={value.user.image.png} username={value.user.username} created={value.createdAt} content={value.content} score={value.score} replies={value.replies} replyTo={value.replyingTo}/>
            })
            
        }
    </div>
  )
}

export default Comment

Reply.js

import React from 'react'

function Reply(props) {

  const user = React.useContext(LoggedUser)
  
  return (
    <div className='reply'>
            <div className='header'>
                <img src={props.image} alt='image' />
                <span>{props.username}</span>
                <span>{props.created}</span>
            </div>
            <div className='content'>
                <span>@{props.replyTo}</span> {props.content}
            </div>
            <div className='footer'>
                <div className='input'>
                    <img src='./images/icon-plus.svg' alt='plus' />
                    <img src='./images/icon-minus.svg' alt='minus' />
                    {props.score}
                </div>
                <div className='reply'>
                    <img src='./images/icon-reply.svg' alt='reply' />
                    <span>Reply</span>
                </div>
            </div>
        </div>
  )
}

export default Reply

As it’s shown, I am trying to fetch LoggedUser value from App.js in Reply.js, but each time I’ve tried, I’ve got this error ‘Compiled with problems:X

ERROR

srcReply.js
Line 5:33: ‘LoggedUser’ is not defined no-undef

Search for the keywords to learn more about each error.’
Help me out guys please, I would really appreciate your help.
If anybody asks, Data.currentUser.username returns the username from file correctly.

Regex: Match specific words between two string

I have finished to join in this community because I can not found the solution to my problem.

I have a regular expression that only allows match all string between two words, but I need match specific words between those two words, not all string.

I have this regular expression:

(?<=START).+?(?=END)

I am programming with JavaScript y use the website regex101 to edit regular expressions.

Thanks for atention and help me.

Can I post files from one server to another?

I am making a simple website to store files using express-fileupload.And I found that the files stored in the server will be deleted when the website is updated.Therefore I’ve made another website for storing files.Here’s some of the source code.

Uploadfile.com

//...someting
var file=req.files.fle
  file.mv(path.join(__dirname+"/cloud/",file.name),(err)=>{
    if(err){
        console.log(err)
        res.send("ERROR")
      }else{
//something..

Is there any ways that I can send the file to the website that used to store file(for example,StoreFile.com) by changing the __dirname?

SparkAR pinLastValue() returning 0;

I’m started a project in SparkAR and having some trouble with getting the correct value in my script in 2 places now. Using .pinLastValue() doesn’t provided the number shown in the diagnostics.

Example 1:

const directionX = Reactive.sub(Object.worldTransform.x, Target.worldTransform.x);
const directionY = Reactive.sub(Object.worldTransform.y, Target.worldTransform.y);
const directionZ = Reactive.sub(Object.worldTransform.z, Target.worldTransform.z);

Diagnostics.watch('directionX: ', directionX);
Diagnostics.watch('directionZ: ', directionZ);

Provides the values in the diagnostics:

directionX: -0.44

directionZ: -0.02

const angleRad = Math.atan2(directionX, directionZ);
Diagnostics.watch('angleRad: ', angleRad);

returns null/underfined

const angleRad = Math.atan2(directionX.pinLastValue(), directionZ.pinLastValue());
Diagnostics.watch('angleRad: ', angleRad);

returns angleRad of 0

const angleRad = Math.atan2(-0.44, -0.02);
Diagnostics.watch('angleRad: ', angleRad);

returns the correct value

Example 2:

when I call

const closestIndex = indexes.reduce((acc, cur) => Reactive.max(acc, cur));
Diagnostics.watch('Result',closestIndex);

returns closestIndex as 2

If I try to use closetIndex to find an object by name in my array it doesn’t give me the 3rd object [2] in the list it just provides me the first [0]

I’m using:

Diagnostics.log(objArray[closestIndex.pinLastValue()].name);

returns object_0

where I want it to return object_2

In both these examples it doesn’t return the number I want (what’s in the diagnostics) but just returns 0. What am I doing wrong? Thank you for your time.

Check volume of audio in real time

I want to log the volume level of an audio file as its playing, to see if it hits a threshold. I tried using the .createAnalyzer function but can’t figure it out.
I have the function “repeat” to check every 0.1 seconds for a new volume, I just don’t know how to actually get the volume.

const audioContext = new AudioContext();
const audiodiv = document.querySelector('.audiodiv')

const buffer = audioContext.createBuffer(
    1,
    audioContext.sampleRate * 1,
    audioContext.sampleRate
);

const channelData = buffer.getChannelData(0)

for (let i = 0; i < buffer.length; i++){
    channelData[i] = Math.random() * 2 - 1;
}
//OUTPUT VOLUME
const primaryGainControl = audioContext.createGain()
primaryGainControl.gain.setValueAtTime(0.01, 0);
primaryGainControl.connect(audioContext.destination);
//SAMPLE
const songbutton = document.createElement('button')
songbutton.innerText = 'song'
songbutton.addEventListener('click', async () => {
    const response = await fetch('testsong.wav')
    const soundBuffer = await response.arrayBuffer()
    const songBuffer = await audioContext.decodeAudioData(soundBuffer)
    
    const songSource = audioContext.createBufferSource()
    songSource.buffer = songBuffer


    const songSource2 = audioContext.createBufferSource()
    songSource2.buffer = songBuffer

    songSource.playbackRate.setValueAtTime(1, 0)
    songSource2.playbackRate.setValueAtTime(1, 0)

    const songGain = audioContext.createGain()
    songGain.gain.setValueAtTime(0.01, 0)
    

    const analyserNode = audioContext.createAnalyser();
    analyserNode.connect(primaryGainControl)
    
    repeat()
    function repeat(){
        setTimeout(() => {
        console.log(analyzerNode.VOLUME)

        repeat()
        }, 100);
    }


    console.log(analyserNode.frequencyBinCount)

    songSource.connect(primaryGainControl)
    songSource2.connect(analyserNode)
    songSource2.start()
    
    console.log(songSource2.amplitude)
    
})
audiodiv.appendChild(songbutton)

How to filter JSON data to show fields by certain words?

I’m looking for a way to get a URL from JSON data that matches certain words. I’m not familiar with JSON but my JSON data looks like this:

const data = {
  "links": {
    "thumbnail": [{
        "href": "https://media.wwltv.com/assets/WWL/images/d111cadc-2ca1-4cfc-adec-422d9228e6a0/d111cadc-2ca1-4cfc-adec-422d9228e6a0_1920x1080.jpg",
        "rel": [
          "thumbnail",
          "ssl"
        ],
        "type": "image/jpg",
        "content_length": 123865,
        "media": {
          "width": 1920,
          "height": 1080
        }
      },
      {
        "href": "https://media.wwltv.com/assets/WWL/images/b9c0109f-f504-4330-9dbb-5d0461316d00/b9c0109f-f504-4330-9dbb-5d0461316d00_1140x641.jpg",
        "type": "image/jpg",
        "rel": [
          "twitter",
          "thumbnail",
          "ssl",
          "og"
        ],
        "media": {
          "width": 1140,
          "height": 641
        },
        "content_length": 94781
      }
    ]
  }
};

And my AJAX function is below. What it does is get JSON data and then store them in a value in a field:

$.ajax({
      type:"GET",
      url: "https://iframe.ly/api/iframely?url=" + link_raw.value + "&api_key=xxx",
      success: function(data) {
               $(".acf-fields div.acf-field.acf-field-text.acf-field-62a253c405887 div.acf-input div.acf-input-wrap input").val(JSON.parse(JSON.stringify(data.links.thumbnail[0].href)));
       },
       dataType: 'JSON',
});

What I’m trying to do is show the href if rel[0].twitter. Something like:

if (filter == rel[0].twitter) {
    $(".acf-fields div.acf-field.acf-field-text.acf-field-62a253c405887 div.acf-input div.acf-input-wrap input").val(JSON.parse(JSON.stringify(data.links.thumbnail)));
}

JavaScript prompt() is showing up twice? [closed]

I am coding a program in Replit using Node.js. For some reason, when running the program, the prompt() statement in line 16 repeats twice. The first time, it doesn’t react regardless of the input, and then second time, it works as expected.

This is a screenshot of my code.
This is a screenshot of the bug.

I’ve tried to do research about this, however I’m really lost as to what is going wrong. Some people seem to say that prompt() does not work in Node.js. However, in other parts of the program, prompt() statements seem to be working?

Does anyone know what might be causing this bug? Any help is greatly appreciated. Thank you so much for taking the time to read this post.

How to edit a todo list using vanilla JS and no local storage

I am doing a standard to do list. One text input and a button to submit the text. I can create the elements necessary to get a to do list item to show, with three buttons green check mark that toggles line through of to do text, an edit icon which if I could figure out would edit the to do text, and a delete red X used for deleting the to do item.

The project I am trying to follow, when editing, puts the text of the to do item into the single text box on the screen and changes the text of the button from add to edit. When editing is done, the to do list item text is updated, the text box is emptied and the button goes back to saying add.

I have added my code below with some edit code commented out in the JS. I really need some help or I will have a giant hole in all of my CRUD operations, no updating.

let inputTextEl = document.getElementById("inputText");
let inputButtonEl = document.getElementById("submitInput");
let outputDiv = document.getElementById("outputToDoDiv");
let deleteAllButton = document.getElementById("deleteAllButton");

let addToDo = function () {
   let text = inputTextEl.value;
   if (text === "") {
      alert("Must have a to do item in the to do box.");
      return;
   }
   inputTextEl.value = "";

   let todoContainer = document.createElement("div");
   todoContainer.id = "todoContainer";
   let pEl = document.createElement("p");
   pEl.id = "todo"
   pEl.style.textDecoration = "none";
   pEl.innerText = text;
   todoContainer.appendChild(pEl);

   let iconDiv = document.createElement("div");
   iconDiv.id = "iconsDiv";
   let greenCheckImg = document.createElement("img");
   greenCheckImg.id = "greenCheck";
   greenCheckImg.src = "green_check.png";
   greenCheckImg.width = "16";

   let editIconImg = document.createElement("img");
   editIconImg.id = "editIcon";
   editIconImg.src = "edit_icon.png";
   editIconImg.width = "16";

   let redXImg = document.createElement("img");
   redXImg.id = "redX";
   redXImg.src = "redX.jpg";
   redXImg.width = "16";
   
   iconDiv.appendChild(greenCheckImg);
   iconDiv.appendChild(editIconImg);
   iconDiv.appendChild(redXImg);

   todoContainer.appendChild(iconDiv);

   outputDiv.appendChild(todoContainer);
}

inputButtonEl.addEventListener("click", addToDo);


// let editToDo = function (event) {

// }


let handleIconClicks = function (event) {
   let targetEl = event.target;
   if (targetEl.id === "greenCheck" || targetEl.id === "editIcon" || targetEl.id === "redX") {
      if (targetEl.id === "greenCheck") {
         let pEl = targetEl.parentElement.parentElement.firstElementChild;
         if (pEl.style.textDecoration === "none") {
            pEl.style.textDecoration = "line-through";
         }
         else {
            pEl.style.textDecoration = "none";
         }
      }
      // else if (targetEl.id === "editIcon") {
      //    let pEl = targetEl.parentElement.parentElement.firstElementChild;
      //    inputTextEl.value = pEl.innerText;
      //    inputButtonEl.textContent = "Edit"
      //    inputButtonEl.addEventListener("click", editToDo);
      // }
      else if (targetEl.id === "redX") {
         let divToDelete = targetEl.parentElement.parentElement;
         divToDelete.parentElement.removeChild(divToDelete);
      }
   }
   else {
      return;
   }
}

document.addEventListener("click", handleIconClicks);

let deleteAllToDos = function () {
   outputDiv.innerHTML = "";
   outputDiv.innerText = "";
}

deleteAllButton.addEventListener("click", deleteAllToDos);
@charset "utf-8";

body {
   background-color: rgb(211,211,211);
   max-width: 1680px;
   height: 100vh;
}

#wrapper {
   background-color: white;
   width: 90%;
   margin: 0 auto;
   min-height: 100%;
}

header > h1 {
   font-size: 2em;
   font-weight: bold;
   padding: 0.67em 0;
   text-align: center;
}

div#inputDiv, div#deleteAllButtonDiv {
   text-align: center;
}

div#deleteAllButtonDiv {
   margin-top: 20px;
}

#outputToDoDiv {
   width: 600px;
   margin: 20px auto 0 auto;
}

#todoContainer {
   display: flex;
   flex-flow: row nowrap;
   justify-content: space-between;
   width: 100%;
   margin-top: 10px;
}
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>To Do List</title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <link rel="stylesheet" href="eric_meyer_reset_2.css" />
      <link rel="stylesheet" href="styles.css" />
   </head>
   <body>
      <div id="wrapper">
         <header>
            <h1>To Do List</h1>
         </header>
         <div id="inputDiv">
            <input type="text" id="inputText" size="65" />
            <button type="button" id="submitInput">Add</button>
         </div>
         <div id="outputToDoDiv">
         </div>
         <div id="deleteAllButtonDiv">
            <button type="button" id="deleteAllButton">Delete All</button>
         </div>
      </div>
      <script type="module" src="main.js"></script>
   </body>
</html>

How to extract form data from post

My payment gateway has send a POST to my website with the information as form data click link to check image:
Form data

I tired retrieving the data as:

this.http
  .post<any>('https://xyz.app/test', {
    title: 'Testing...',
  })
  .subscribe((data) => {      
    console.log(data);
  });

But no success.
I want to retrieve the payment transaction data and then later display it.