websocket error: can’t connect socket.io to react-native project

I am using socket.io Version: ^4.5.1 in a chat application, but I am facing this error:

websocket error

my code:

import {io} from 'socket.io-client';
import {server} from 'store/config';

export const connectSocket = (token: string, eventId: string) => {
  const socket = io(server.stageSocketUrl, {
    transports: ['websocket', 'polling'],
  });

  socket.on('connect', () => {
    console.log('connected');
    socket.emit('join', {
      authorization: `Bearer ${token}`,
      eventId,
    });
  });

  socket.on('connect_error', err => {
    console.log(err, 'connect error');
  });
  return {socket};
};

when I use "socket.io-client": "^2.2.0" it connects to server successfully, so any clue how can I use version ^4.5.1 and make websocket connect to the server?

Issues with Chrome when trying to create a draggable list in HTML/Javscript

First off, this is being designed in Vue, but the problem seems to be purely HTML.

Basically the list is laid out in the following format

[separator]
[element]
[separator]
[element]
[separator]
[element]
[separator]

The separator elements start out at 0px, and on an element’s dragstart() event they get set to a height that causes them to overlap the elements and are used to detect where the element should be placed in the list. This works perfectly in Firefox, however Chrome seems to have an issue with elements overlapping other elements when dragging, and it immediately causes the dragging to stop, triggering the dragend() event.

I tried keeping the height consistent and disabling/enabling pointer events on drag, however it’s the same result.

Here’s a pure HTML reproduction of the bug in a codepen https://codepen.io/zHixson/pen/ZExzyyM. Works in Firefox, not in chrome, just like the original

Anyone have experience dealing with this issue before and know the solution?

ESlint doesn’t see yarn workspace package

I have a yarn workspace project(monorepo) that has a shared library.

Eslint fails to detect the common library even though it is listed in the package.json in dependencies.

If I disable the eslint completely the project works.

I am using vitejs on a react project with the vite-plugin-eslint eslint plugin.

error  '@****/common' should be listed in the project's dependencies. Run 'npm i -S @****/common' to add it 

ESlint packs

    "eslint": "^7.2.0",
    "eslint-config-airbnb": "18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jest": "^24.3.7",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",

npm script not executed error occurred “The filename, directory name, or volume label syntax is incorrect.”

my package.json file content is

{
  "name": "confusion",
  "version": "1.0.0",
  "description": "This is a website for Ristorante Con Fusion",
  "main": "index.html",
  "scripts": {
    "start": "npm run watch:all",
    "test": "echo "Error: no test specified" && exit 1",
    "lite": "lite-server",
    "scss": "node-sass -o css/ css/", 
    "watch:scss": "onchange "css/*.scss" -- npm run scss",
    "watch:all": "parallelshell "npm run watch:scss" "npm run lite""
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "lite-server": "^2.3.0",
    "node-sass": "^7.0.1",
    "onchange": "^7.1.0",
    "parallelshell": "^3.0.2"
  },
  "dependencies": {
    "bootstrap": "^5.0.0",
    "bootstrap-social": "^5.1.1",
    "chokidar": "^3.5.3",
    "font-awesome": "^4.7.0",
    "jquery": "^3.6.0",
    "popper.js": "^1.16.1",
    "wrap-ansi": "^7.0.0"
  }
}

now “npm start” start not working giving error “The filename, directory name, or volume label syntax is incorrect.” How it can be fixed?

How do I fix this JS function so it doesn’t return false positives when checking if two line segments intersect?

I’m working on a mapping project (with the Google Maps SDK). Before drawing a line segment on the map I check to see if it intersects with any existing lines.

I’m experiencing a situation where the code below is reporting the line segments are intersecting, but they’re not. Although, they do share an endpoint.

Perhaps this intersect() function isn’t meant to be used with Geo coordinates and I need a different function. I found this intersects() function here: Test if two lines intersect – JavaScript function

In this project I have about 150 lines and about 10-15 of them are detected as intersecting, and they’re not (although they share a common endpoint with the line that is reported as intersecting).

Below is a screenshot of how the lines are drawn on Google Maps for a better visual. The red line is the second one passed to the intersects() function and is detected as intersecting the first line. Interestingly, if I reverse the lines passed to intersects() it does not find them to be intersecting.

let crosses = intersects(
        39.018223, -76.75899, 39.018387, -76.758773,
        39.018387, -76.758773, 39.019813, -76.757388,
);
      
console.log('Intersects:', crosses);

// returns true if the line from (a,b)->(c,d) intersects with (p,q)->(r,s)
function intersects(a,b,c,d,p,q,r,s) {
        var det, gamma, lambda;
        det = (c - a) * (s - q) - (r - p) * (d - b);
        if (det === 0) {
                console.log('det is zero');
                return false;
        } else {
                lambda = ((s - q) * (r - a) + (p - r) * (s - b)) / det;
                gamma = ((b - d) * (r - a) + (c - a) * (s - b)) / det;
                return (0 < lambda && lambda < 1) && (0 < gamma && gamma < 1);
        }
};

Two lines

Problem with Node.JS and jsconfig.json with absolute imports

IDE: Replit

Good afternoon, thanks for checking out.

I wanted to implement absolute imports to my node project, but something odd is happening whenever I try to run the code.

Here are the things I set for my jsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": "src"
  }
}

Now, this is how i’m calling the file I need inside another one:

const {title} = require('util.js')

Oddly, replit’s intellisense shows up the right path:
Thumbs Up From Replit

But then, when I finally execute the code, I get this error message:

Error: Cannot find module ‘/home/runner/Moniqueta-Discordjs/node_modules/util.js/index.js’. Please verify that the package.json has a valid “main” entry
at tryPackage (node:internal/modules/cjs/loader:353:19)
at Function.Module._findPath (node:internal/modules/cjs/loader:566:18)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object. (/home/runner/Moniqueta-Discordjs/src/commands/rps.js:2:17)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
code: ‘MODULE_NOT_FOUND’,
path: ‘/home/runner/Moniqueta-Discordjs/node_modules/util.js/package.json’,
requestPath: ‘util.js’
}

I tried following the error by adding a “valid main entry to my package.json” file, like this:

{
  "name": "moniqueta-discordjs",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "keywords": [],
  "author": "sum117",
  "license": "ISC",
  "dependencies": {
    "@replit/database": "^2.0.2",
    "discord.js": "^13.8.0",
    "src": "^1.1.2",
    "util.js": "^0.0.0"
  }
}

And when I checked it, it had “util.js” as a declared dependency, I really don’t understand what’s going on.

Thanks for reading. What am I missing? I really would love this to work…

If my explanation is not enough, you can access my open source code via the link.

function executed by setInterval() multiple doesn’t show results | Javascript

I am making a timer in javascript. But there is one thing I am not getting.

Here’s the code…

var time = 0;
var timeInterval;
var testTime;


//Main code which increases the value of variable time by 1 every second until interval is stopped

timeInterval = setInterval(function (){
    time++;
    testTime = time;
}, 1000);



//Code to stop the interval after 10 seconds.
setTimeOut(function() {
    clearInterval(timeInterval);
},10000);



//Expected value -> 10
//I get -> 0

console.log(testTime)

If I am running a function which increases the value of time by 1 10times by setInterval() method… Why the value of time is not updating?

read messages from realtime databse in firebase with javascript

i want to read messagea from realtime database in firebase with vue or javascript in quasar framework

my collection name in db is messages that have this strtucture:
******************************************* my db structure*******

messages
         -N4zbIt0Ey6Bix54f5SE
             content: "Hi"
             fromId: "nTTcnND2y6OHUBVO2GxHoBFwQf32"
             timestamp: 1655703420767
             toId: "0FXpksPdL4OAf9KAXx9B0R6nzmh2"
             type: 1
        -N4zbIt0Ey6Bix54f5SE
             content: "Hi,HOW ARE YOU"
             fromId: "0FXpksPdL4OAf9KAXx9B0R6nzmh2"             
             timestamp: 1655703448111
             toId: "nTTcnND2y6OHUBVO2GxHoBFwQf32"
             type: 1

do you know how i query firebase to getmessages?? ithis is for save in state with Vuex

firebaseGetMessages({ commit, state }, otherUserId) {
    let userId = state.userDetails.userId
    messagesRef = firebaseDb.ref('messages/' + fromId + '/' + toId)
    messagesRef.on('child_added', snapshot => {
        let messageDetails = snapshot.val()
        let messageId = snapshot.key
        commit('addMessage', {
            messageId,
            messageDetails
        })
    })

i think this code is wrong
please help me if you have any experince with firebase

Finding the shortest path of a BFS solution

I am having difficulties to rewrite the path from the start to the end point after finding a BFS solution.

I have found other questions similars to mine, but still couldnt understand what to do. I am saving the visited notes on nodeTable, but it only returns all visited nodes, not the optimal path.

The idea is to find the shortest path on a binary matrix, where the only paths possible are through cells marked with 1.

const C = Map.width;
const R = Map.height;
const startPoint = [308,863];
const endPoint = [473,894];

const rowQ = [];
const colQ = [];

let reachedEnd = false;

let nodeTable = [];

let dr = [1,-1,0,0,1,-1,1,-1];
let dc = [0,0,-1,1,1,-1,-1,1];

function solve() {
    rowQ.push(startPoint[0]);
    colQ.push(startPoint[1]);
    visitedMap[startPoint[0],startPoint[1]] = true;

    while ( rowQ.length > 0 ) {
        const r = rowQ[0];
        const c = colQ[0];
        rowQ.splice(0,1);
        colQ.splice(0,1);

        if (endPoint[0] == r && endPoint[1] == c) {
            reachedEnd = true;
            break;
        }
        explore_neighbors(r,c);
    }

        if (reachedEnd) {
            console.log("Solucao encontrada: ", endPoint);
            return;
        } else {
            console.log("Solucao nao encontrada");
            return;
        }
}

function explore_neighbors(r,c)  {
    for (let i = 0; i < 8 ; i++) {
        let rr = r + dr[i];
        let cc = c + dc[i];
        
        if (rr < 0 || cc < 0) {  continue }
        if (rr > R || cc > C) {  continue }

        if (visitedMap[rr][cc] == true ) { continue }  

        if (roadMap[rr][cc] == 0) { continue }

        addPointToTable([rr,cc],"yellow");
        rowQ.push(rr);
        colQ.push(cc);
        visitedMap[rr][cc] = true;
        nodeTable.push([rr,cc]);
    }
}

Linking audio to p5js sound within same component in React

I’m trying to build an audio visualiser using p5js and Reactjs. The user will input a YouTube link, from which a separate component will extract the .mp3 file. Then, the Visualiser component will process this into a p5 graphic.
In the Visualiser component, I have:

  • mp3_to_hist(filename), which provides the audio by setting the song state. At the moment it takes a sample mp3 file (default.mp3, located in the public folder), and creates the Audio element, audio context, etc.
  • a p5js sketch, Sketch (demo of what it should look like when working);
  • a button to play and pause the audio.

I am a bit clueless on how to access the song that mp3_to_hist(filename) provides into Sketch.

The aim is for the p5 sketch animation to begin and stop as the play/pause button is pressed.

This is my code:

export default function Visualiser() {
  const [songPlaying, setSongPlaying] = useState(false);
  const [song, setSong] = useState(undefined);
  const [audioCtx, setAudioCtx] = useState(undefined); //needed to play in Chrome
  const canvasRef = React.createRef()
  let p5ref;
  const dataArray = new Uint8Array(32);
  const [analyser, setAnalyser] = useState(undefined);

  //for button to play/pause song
  useEffect(() => {
    if (song !== undefined) {
      song.pause();
    }
    mp3_to_hist('default.mp3');
  }, [])

  //render canvas and update it
  useEffect(() => {
    if (p5ref === undefined) {
      p5ref = new p5(Sketch, canvasRef.current);
    }
    // draw(canvasRef.current);
  }, [p5ref]);

  //p5 sketch
  const Sketch = (p) => {
    let fft, amp;

    p.setup = () => {
      console.log(song, 'song in drawing') //currently returns undefined, regardless of whether the song is playing or not
      amp = new p5.Amplitude();
      fft = new p5.FFT();
      p.createCanvas(600, 600)
    }

    p.draw = () => {
      p.background(0);
      const vol = amp.getLevel();
      const freqs = fft.analyze()
      const h = Math.random() * 200;
      p.fill('red');
      p.stroke('white');

      for (let i = 5; i < 1024; i += 5) {
        for (let j = 0; j < 20; j++) {
          p.noStroke()
          p.fill(255, 255, 255, 10);
          p.circle(10 * i, p.height / 2 - freqs[i], j * 2);
          p.circle(10 * i, p.height / 2 + freqs[i], j * 2);
        }
      }
    }
  }

  function mp3_to_hist(filename) {
    const tune = new Audio(filename);
    setSong(tune);
    const audioContext = new AudioContext();
    setAudioCtx(audioContext);
    const audioSource = audioContext.createMediaElementSource(tune);
    const myAnalyser = audioContext.createAnalyser();
    audioSource.connect(myAnalyser);
    myAnalyser.connect(audioContext.destination);
    myAnalyser.fftSize = 64;
    setAnalyser(myAnalyser);

    return 'hi';
  }
//button play
  const playSong = () => {
    console.log('playing', songPlaying)
    if (song === undefined) {
      return;
    }
    audioCtx.resume()
    setSongPlaying(true);
    song.play();
  }
//button pause
  const pauseSong = () => {
    console.log('pause', songPlaying)
    if (song === undefined) {
      return;
    }
    song.pause();
    setSongPlaying(false);
  }

  return ( <
    div className = {
      style.visualiser
    } >
    <
    section ref = {
      canvasRef
    }
    /> <
    Button onClick = {
      songPlaying ? pauseSong : playSong
    }
    variant = "outlined" > {
      songPlaying ? 'Pause' : 'Play'
    } < /Button> { /*<button onClick={play}>Play </button>*/ } <
    /div>
  )

How to send multiple data to server using for loop

const submit = e => {
    e.preventDefault();
    fetch('', {
      method: 'POST',
      body: JSON.stringify({
        product_option_id: 1,
        quantity: 2,
      }),
    })
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          goToCart();
        } else {
          alert('error');
        }
      });
  };

I have a question regaring sending data to backend using fetch.
I have product_option_id in array format as result = [4, 3] for example.
And I have quantity in array format as count = [1, 2] for example accordingly. So here I have product_option_id: 4 and its quantity is 1 and I also have product_option_id: 3 and its quantity is 2. If I have to send these data separately one after another one as above instead of sending array, can I write an if statement like this in body?

fetch('', {
      method: 'POST',
      body: JSON.stringify({
        for (let i =0; i < result.length; i++) {
        product_option_id: result[i],
        quantity: count[i],
        }
      }),
    })

Thank you in advance.

How to work with FormData in React and Next?

New to React and I’m building a dashboard page, and thought it will be having so many forms so I created a component for Input with label and I use that component to populate element with my required format of input. On submit, I used FormData() to attempt to create or extract data from form without any tedious state management(which I don’t feel to have in this situation).
But FormData() doesn’t seem to work as expected, let me know where am I doing wrong.

Form component:

import Input from "../micro components/Input"

export default function Form() {
    const handleSubmit = async (e) => {
        e.preventDefault();
        const fd = new FormData(e.target)
        console.log(fd)
        const res = await fetch('/api/admin/add', {
            method: 'POST',
            body: fd
        }).then(res => res.json())
        console.log(res)
    }

    return <>
        <div className="text-xl font-semibold select-none">Add a Hospital/Clinic</div>
        <form className="flex flex-col gap-3 mt-5" onSubmit={handleSubmit}>
            <label>Fields with <strong>*</strong> are mandatory</label>
            <Input name="Name" placeholder="hospital/clinic name" required />
            <Input name="Branch" placeholder="Locality Eg: Uppal; Madhapur etc" />
            {/* Regex pattern / ^[6-9]d{9}$ /gi will match phone numbers of 10 digits starting with 6 7 8 9 */}
            <Input name="Phone - 10 digits" type="tel" placeholder="9876543210" pattern="^[6-9]d{9}$" required />
            <Input name="Mail" type="email" placeholder="[email protected]" required />
            <Input name="Full Address" placeholder="Recommended to paste from google maps" />
            <button type="submit" className="btn btn-primary">Submit</button>
        </form>
    </>
}

Input component:

export default function Input({ name, type, placeholder, pattern, input, required }) {
    return (
        <label className="input-group input-group-vertical">
            <span className="select-none">{required ? '*' + name : name}</span>
            <input type={type} className="input input-bordered" pattern={pattern}
                placeholder={placeholder} value={input} required={required} />
        </label>
    )
}

server-side:

export default async function AddHosp(req, res){
    console.log(req.body)
    return res.status(200).json({
        msg: 'testin'
    })
}

When I console.log request body on server-side, I get the following as output :
------WebKitFormBoundaryPvEYMB5QuQqszbrx--

I also tried accessing FormData elements at client-side but no success

PS: FormData isn’t properly documented with examples afaik, if I’m wrong correct me

How to Fetch each records from MySQL with jQuery AJAX in Dynamically Add or Remove Input Fields in Laravel?

I’m trying to Fetch each records from MySQL with jQuery AJAX in Dynamically Add or Remove Input Fields in Laravel, but when I add the second dynamic element, it doesn’t add Fetch each records from database.

Can someone guide me how to Fetch each records from database when adding each item.

This is my function in jquery:

$("#addsalequote").click(function(){
    $(".product-text").hide();
    var data = [
        {   code: '<td id="addSaleQuoteProductReference" class="text-center addSaleQuoteProductReference"></td>', 
            product: '<select id="addSaleQuoteProduct" class="js-basic-single form-select" name="addsalequote['+i+'][product_id]" id="product"><option selected>Articulos/Productos</option>@foreach($products as $key => $value)<option value="{{$key}}">{{$value}}</option>@endforeach</select>', 
            quantity: '<input type="number" name="addsalequote['+i+'][quantity]" min="1" class="form-control" />', 
            price: '{!! Form::number('addsalequote[0][price]', null, array('id' => 'saleQuoteProductPrice', 'class' => 'form-control addSaleQuoteProductPrice')) !!}',
            total: '<td class="text-end row-saleQuoteTotal"></td>',
            button: '<button type="button" class="btn btn-danger btn-icon btn-xs remove-tr" data-bs-toggle="tooltip" data-bs-placement="top" title="Quitar producto"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg></button>'
        }
    ];

    var $saleQuoteTable = $('#saleQuoteProductTable');

    var rowElements = data.map(function ( row ) {

        var $row = $('<tr></tr>');

        var $code = $('<td style="width: 5%; vertical-align:middle"></td>').html(row.code);
        var $product = $('<td style="width: 20%"></td>').html(row.product);
        var $quantity = $('<td style="width: 5%"></td>').html(row.quantity);
        var $price = $('<td style="width: 5%"></td>').html(row.price);
        var $total = $('<td style="width: 10%; vertical-align:middle"></td>').html(row.total);
        var $button = $('<td style="width: 5%; vertical-align:middle"></td>').html(row.button);

        $row.append($code, $product, $quantity, $price, $total, $button);
        
        return $row;
    });

    $saleQuoteTable.append(rowElements); 
    
    $('#addSaleQuoteProduct').change(function(){ 
       
        var id=$(this).val();

        $.ajax({
            url:"/get/product/"+id,
            method:'get',
            dataType: 'json',
            data:{id:id,'_token':"{{csrf_token()}}"},
            success:function(response)
            {
                createRows(response);
            }
        });

        function createRows(response){
            $('.addSaleQuoteProductPrice').val(response.sale_price); 
            $('.addSaleQuoteProductReference').text(response.reference); 
        }

    });

    $(document).on('click', '.remove-tr', function(){          
        $(this).parents('tr').remove();        
    });
});