WebRTC to stream new Audio

I’m building a web application, where music/audio is playing from an object using new Audio(). On another tab I’d like to listen to the music through WebRTC. I already have the WebRTC established, and I can confirm it works with microphones on both sides.
When I try to change the “music” tab’s microphone to a mediastream of a “new Audio()”, it no longer works and the listeners-tab is silent.

I’m trying it like this:

audio = new Audio();
audio.src = someArray['audiosrc'];
mediaStream = audio.captureStream()
audio.play();
webRTC.addTrack(mediaStreams.getAudioTracks()[0]);

I have no clue why the listeners-tab is completely silent… Is there anything wrong with the code? I don’t see any errors in the console, I don’t see any errors on the receiving side, but it still does not want to “stream” the audio.

NodeJS- How can I export the response data from the request?

My geocode.js class is below.

const request= require('postman-request')

async function geocode (address, callback){
    const url= `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(address)}.json?access_token=<myToken>&language=tr&limit=1`
    request({url, json:true},(error,{body})=>{
        if (error) {
            callback('Unable to connect to location services!',undefined)
        }else if (body.features.length===0) {
            callback('Unable to find the location!',undefined)
        } else {
           callback(undefined,{
               latitude: body.features[0].center[1],
               longitude: body.features[0].center[0],
               location: body.features[0].place_name
           })
        }

    })

}

module.exports= geocode;

My app.js is below.

"use strict";

const geocode = require('../src/geocode.js');

var addressArray= ["Address1", "Address2", "Address3"];

var encodingAddressArray = [];

function getGeoCode(e){
  geocode(e,(error,{latitude,longitude, location}={})=>{ 
    // Here the latitude, longitude and location fields come full
    return {
      latitude: latitude,
      longitude: longitude,
      location: location
    }
  })
}

addressArray.forEach(e => {
  // But, when I call the getGeoCode function here, it returns undefined.
  encodingAddressArray.push(getGeoCode(e))
});

console.log(encodingAddressArray)

The geocode.js class is called within the app.js class. My aim is to print the response data from the request that I have made with the mapbox Api in geocode.js into an array with the forEach loop in app.js.
However, when I want to print the response I called from geocode.js to the array I defined in app.js, the data comes as undefined. What should I do? Thank you.

How to check radio button is checked on form submit – JavaScript

I have a form using radio buttons for the user to select a rating between 1-10. Some of these questions are required to have a rating before the user is able to submit. So i call for the function validateForm() on submit to do so.

An example of my form:
Visual Example

I have success with the following code for “ease of placing order” question:

function validateForm() {
    var easeradios = document.getElementsByName("ease-rating");
    
    for (var i = 0; i < easeradios.length; i++) {
        if (easeradios[i].checked) {
        return true;
        }
    } return false;
}

I am grabbing the radio buttons by their name which for this is ease-rating. This works fine and the user cannot submit until a rating is selected on this question. However when i try to apply the same to the next row as this is also required it seems to go wrong.

    function validateForm() {


var easeradios = document.getElementsByName("ease-rating");

for (var i = 0; i < easeradios.length; i++) {
    if (easeradios[i].checked) {
    return true;
    }
} return false;


var convradios = document.getElementsByName("conv-rating");

for (var i = 0; i < convradios.length; i++) {
    if (convradios[i].checked) {
    return true;
    }
} return false;
    
   
}

It seems to only acknowledge a requirement for “Convenience of delivery” before submitting instead of taking the first questions requirement now.

Sorry i’m new to this but what i want is for the form to check that a rating is selected on each question before proceeding. I don’t want to use /required as i want to insert custom error message underneath the rating required which is why i haven’t used that.

Thanks for your help!

I want to separate my array into other arrays by matchday

I’m trying to separate a huge array in order of matchday. There are 38 matchdays in total, I’m trying to display the games by matchdays.

I have this

 data.matches = [{matchday: 1, team: xxx}, {matchday: 1, team: xxx}, {matchday: 2, team: xxx} etc..]

I would like something like this

  data.matches = [[{matchday: 1, team: xxx}, {matchday: 1, team: xxx} ],[{matchday: 2, team: xxx}] etc..]

So you can see I create a new array for each different matchday, those new arrays will be nested inside the main array.

My poor attempt:

let results: any = [];

    if (isSuccess) {
        data.matches.map((item: any) => {
            for (let i = 1; i < 38; i++) {
                if (item.matchday === i) {
                    results.push(item);
                } else {
                    results.splice(i, 0, item);
                }
            }
        });
        console.log(results);

    }

How can I remove import from JS result file?

I have file events.ts

export declare SOME_VALUE: string

I import and use this declaration in index.ts

import { SOME_VALUE } from './events'
renderValue(SOME_VALUE)

After I compile the code output JS file is:

import { SOME_VALUE } from './events'
renderValue(SOME_VALUE)

And, of course there is an error: There is no SOME_VALUE in events.js to be imported. So how can I automatically remove import line from JS file if I import declarations from events.ts?

The environment, where I execute this JS code automatically provides SOME_VALUE, so no need to import it.

html iframe src accepts literal but not js variable [closed]

I want to populate an iframe with an url:

url = "http://ibm.com";

<div id = "air"> 
<iframe id = "USCF_info"></iframe>` 
</div>

shaft = `<iframe id = "USCF_info" src = "http://ibm.com" ></iframe>` //works
shaft = `<iframe id = "USCF_info" src = "{$url}" ></iframe>` // DOESN'T WORK

document.getElementById('air').innerHTML = shaft;

Error:
Not Found
The requested URL was not found on this server.

Why is that ?

I want to add the name of my mailbox at the top of my page but it shows and goes off

I want to add the name of my mailbox at the top of my page but it shows for few seconds and goes off.

What I want is for e.g INBOX to show at the top of the page, then all the inbox mails will be below the title.

The INBOX shows for nanoseconds and then my inbox mails load and overshadows it.

How can I resolve this?

function load_mailbox(mailbox) {
  // Show the mailbox and hide other views
  document.querySelector('#emails-view').style.display = 'block';
  document.querySelector('#compose-view').style.display = 'none';
  document.querySelector('#content-view').style.display = 'none';

  //Show the mailbox name
  document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;

  // display details of mailbox
  let output = '';

  // using get request to retrieve details
  fetch(`/emails/${mailbox}`)
    .then(response => response.json())
    .then(emails => {
      emails.forEach(email => {
        //display subjecct, sender and timestamp of mail
        output += `<div class="mail" onclick="viewEmail(${email.id}, ${mailbox})">
                    <button class="btn pr-5" style="min-width: 120px; display: inline-block;">${email.sender}</button> 
                    <button class="btn">${email.subject}</button>
                    <button class="badge float-right">${email.timestamp}</button> 
                    <span class="list-group-item"></span> 
                  </div>`;
      })
      //add to html emails view
      let emailList = document.querySelector('#emails-view');
      emailList.innerHTML = output;
    });


}
<div id="emails-view">
</div>

Axios post request not sending data or recieving response

This is my first time trying to do basic authentication and nothing seems to be working. Axios post is not sending data/controllers not returning a response. I cant find exactly where I am going wrong, but I am wondering if the body of my http post request has to match requestbody or what I need to change to get userrepositroy to save form dat in database?

const Login = () => {

    const [registration, setRegistration] = useState("true");

    const [email, setEmail] = useState("");
    const [regPwd, setRegPwd] = useState("");
    const [regUsername, setRegUsername] = useState("");

    const [logUsername, setLogUsername] = useState("");
    const [logPwd, setLogPwd] = useState("");

    const redirect = useNavigate();

    const handleRegSubmit = async (e) => {
        e.preventDefault();
        const registerDTO = {
            email: email,
            username: regUsername,
            password: regPwd
        }
        try {
            const response = await axios.post('http://localhost:8080/registration',
                 {registerDTO} )
                if (response.status === 200) {
                    redirect("/user/${username}")
                } else {
                    setEmail("")
                    setRegUsername("")
                    setRegPwd("")
                }
        }
        catch (error) {
            console.log(error)
        }
    }

    const handleLogSubmit = async (e) => {
        e.preventDefault();
        const logUser = {
            username: logUsername,
            password: logPwd
        }
        try {
            const response = await axios.post('http://localhost:8080/login',
                { logUser })
                if (response.status === 200) {
                    redirect("/user/${username}")
                } else {
                    setLogUsername("")
                    setLogPwd("")
                }
        }
        catch (error) {
            console.log(error)
        };   
    }




Spring boot



@CrossOrigin(origins= "http://localhost:3000")
@RestController
@RequestMapping("")
public class AuthenticationController {

    @Autowired
    UserRepository userRepository;

       
    @PostMapping("/register")
    public ResponseEntity<Object> processRegistration(@RequestBody @Valid RegisterDTO registerDTO,
                                                      BindingResult bindingResult, HttpServletRequest request) {

        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body("An error occurred!");
        }

        User existingUser = userRepository.findByUsername(registerDTO.getUsername());

        if (existingUser != null) {
            return ResponseEntity.badRequest().body("Username already exists!");
        }


        User user = new User(registerDTO.getEmail(), registerDTO.getUsername(), registerDTO.getPassword());
        userRepository.save(user);

        return ResponseEntity.ok().body(user);
    }

    @PostMapping("/login")
    public ResponseEntity<Object> processLogin(@RequestBody @Valid LoginDTO loginDTO,
                                               BindingResult bindingResult,HttpServletRequest request) {

        if (bindingResult.hasErrors()) {
            return ResponseEntity.badRequest().body("An error occurred!");
        }

        User user = userRepository.findByUsername(loginDTO.getUsername());

        if (user == null) {
            return ResponseEntity.badRequest().body("Username does not exist!");
        }

        String password = loginDTO.getPassword();

        if (!user.isMatchingPassword(password)) {
            return ResponseEntity.badRequest().body("Invalid password!");
        }

        return ResponseEntity.ok(user);
    }

}

Reusable uncontrolled input with react-hook-form. Type error for `register: UseFormRegister` prop

I want to have a reusable uncontrolled Input component using react-hook-form, but I can’t seem to get the types right.

Something like this:

CodeSandbox link with the example.

Obs.: The code seems to be running just fine. I think it’s just a matter of adjusting the types.

// REUSABLE UNCONTROLLED INPUT

interface NoteInputValue extends FieldValues {
  note: string;
}

type NoteInputProps = {
  register: UseFormRegister<NoteInputValue>;
};

const NoteInput: React.FC<NoteInputProps> = (props) => {
  const { register } = props;
  return <input {...register("note")} />;
};

This is the form component:

// SOME FORM COMPONENT THAT NEEDS
// TO USE THE INPUT

interface FormValues extends FieldValues {
  note: string;
  someOtherField: boolean;
}

type MyFormProps = {};

const MyForm: React.FC<MyFormProps> = (props) => {
  const { register } = useForm<FormValues>({
    defaultValues: {
      note: "",
      someOtherField: true
    }
  });
  return (
    <>
      <NoteInput register={register} />
    </>
  );
};

This is the TypeScript error I’m getting:

enter image description here

useEffect hook does not work first load and refresh

I am trying to develop a web game for school using react, next.js, express, and socket io. Right now I get the user room id and name from frontend. I want to display the usernames of the people in a lobby. I use useffect function to fetch user list from server. The issue is user list only displays on a client just when a new user joins. I does not render show users on the lobby page at the first render and the first refresh. What am I doing wrong?

import {useEffect, useState} from "react";
import io from "socket.io-client";


function Playerz(){

  //  const socket = io("http://localhost:8000", {transports : ['websocket']})
    const [socket] = useState(() => io('http://localhost:8000'));
    

    const [playersL, setPlayersL] = useState([
        {username:"",
    roomid:""}]
    );

    useEffect(() =>{


            socket.on("receive_list", (data) => {

                //let uzers = data.replace(/[])}["{(]/g, '');


                //let ucerlist = uzers.split(",");


                /*            let key;
                            for(key in data) {
                                if (data.hasOwnProperty(key)) {
                                    console.log( data[key] + "n");
                                }
                            }*/

                setPlayersL(Object.values(data));

                if (playersL === null) {
                    return null
                }
                console.log('bp',playersL)


            })


    },[playersL]);
    return(
        <div style={{textAlign:"center",borderBottom:"2px solids black"}}>
            {
                playersL  ?
                (playersL.map((elem) =>(


                    <div key={elem.username}>{elem.username}</div>))) : (<div>No posts</div>)
            }
        </div>
    )
}
export default function Refine(){
    const Xapsul = <Playerz/>;

    return Xapsul;
}```

server.js

`const app = require('express')();
const server =  require('http').createServer(app);
const io = require('socket.io')(server, {
    cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"]
    }
});
let users = []
let numofusers = 0

io.on('connection', (socket) =>{
    console.log(" Connected! ");
    socket.on('joinroom',(data)=>{
       // console.log('fuck! '+ data.name);
        socket.join(data.room);

        users.push({username: data.author,
                    roomid:data.room});

       // console.log(`Users with ID: ${data.author} joined room: ${data.room}`);
        console.log(`Users with ID: ${(JSON.stringify(users))}`);


        io.emit("receive_list", (users));


    });

    socket.on("disconnect",()=>{
        console.log("User Disconnected",socket.id);
    })


    app.get('/api', function(req, res){
        res.json(users); //also tried to do it through .send, but there data only on window in browser
    });


})



server.listen(8000)`

How to get all coordinates along the way of a direction in mapbox from point A to b?

Good Day everyone,
As shown in the image We have a start and end point forming a route
I need to get all the points(Lat,Lng) forming this route

This is how I implemented the directions:

     var directions = L.mapbox.directions();

      var directionsLayer = L.mapbox.directions.layer(directions)
          .addTo(map);

      var directionsInputControl = L.mapbox.directions.inputControl('inputs', directions)
          .addTo(map);

      var directionsErrorsControl = L.mapbox.directions.errorsControl('errors', directions)
          .addTo(map);

      var directionsRoutesControl = L.mapbox.directions.routesControl('routes', directions)
          .addTo(map);

Overlay windows does not close using back button on mobile browsers

I found something weird. Desktop and mobile browsers do not work the same way regarding back button.

I have hamburger menu overlay, when I click it, it opens (absolute position DIV). When I click on the link inside this overlay, on desktop, it goes to the new page. Back button then brings the previous page back, WITHOUT the overlay. This is my expected behavior.

But as I’ve seen, on mobile (at least on Chrome, but I think on others also), when I have overlay open and click on a link, I get to the new page, but with back I get to the previous page with the overlay STILL OPEN. It would be kind of ok, IF clicking back again would open the overlay, but it doesn’t. It goes to the page I was before clicking hamburger menu or exit site, if that was my first thing I did…

Now I can handle this in 2 ways:

  1. I can close the overlay when clicking on a link inside the menu. When I did that, overlay closes and I get to the next page. Back gets me back to the previous page without overlay. So far so good, BUT… on desktop, when I click and get on a new page this way, I have to click back 2 times to come to previous page. So that is not good.

  2. I can somehow make the back button to close the overlay first and the next back would go back one page, but that seems even more dirty than the first option handling the push states etc.

As I see many sites have solved this. On mobile, clicking on link inside hamburger menu (or some other “popup” with menus) gets to a new page and clicking back goes back to the previous page with hamburger closed. Same behavior is on desktop, no need for double back click.

Does anybody know how I should manage this and if anybody knows why mobile browsers do not close the overlay in the first place when clicking inside it or is there some easy setting that I could trigger this behavior?

Yours

Jerry

python decode javascript btoa string

I am using this code in javascript to encode one json

a = {'address': "djdjdjdj", "provider": "google"}
{address: 'djdjdjdj', provider: 'google'}
btoa(a)
'W29iamVjdCBPYmplY3Rd'

I am using this code to decode in backend

    import json
    import base64
    encodes_Str = "W29iamVjdCBPYmplY3Rd"
    btoa = lambda x:base64.b64decode(x)
    atob = lambda x:base64.b64encode(bytes(x, 'utf-8')).decode('utf-8')
    decoded = json.loads(btoa(encodes_Str))
    print(decoded)

error:

    >>> decoded = json.loads(btoa("W29iamVjdCBPYmplY3Rd"))
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
        return _default_decoder.decode(s)
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode
        raise JSONDecodeError("Expecting value", s, err.value) from None
    json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
    >>> 

I am getting above error. How can i get back the json which i encodes in javascript
please take a look