Getting this error when I try to use video feature in WebSocket connection to ‘wss://endpoint.twilio.com/’ failed:

I’m using “Programmable Video” product to chat video call in my site using PHP.
When i try to connect with the video, i’m getting WebSocket connection to ‘wss://endpoint.twilio.com/’ failed: error. How to solve this issue. I am using JavaScript method to connect twilio video: https://media.twiliocdn.com/sdk/js/video/releases/1.20.1/twilio-video.min.js

Why not By using the JavaScript CDN https://media.twiliocdn.com/sdk/js/video/releases/1.20.1/twilio-video.min.js
The video call feature not working.

In twilio site it says the “Programmable Video” product no longer support. However, it says it will work for existing customers till Dec 2024. Please advise why its not working in my website.
How to solve this issue.

Alpine.js with Laravel: preselect dynamic option in select after page reload

I’m kinda new to Alpine.js and I have 3 selects in my blade view: make, model, engine. Options on model and engine are dynamic and being populated once the previous select has been changed (just to be able to select a vehicle with corresponding configuration):

<div class="md:col-span-5" x-data="{
        selectedMake: '',
        selectedModel: '',
        models: [],
        engines: [],
        isLoading: false,
        makeDisabled: false,
        engineDisabled: false,
        showAlert: false,
        isFormValid: false,
        fetchModels() {
            fetchModels(this.selectedMake, this.models, this.isLoading, this.makeDisabled);
        },
        fetchEngines() {
            fetchEngines(this.selectedModel, this.engines, this.isEngineLoading, this.engineDisabled)
        },
        resetEnginesSelector() {
            this.selectedModel = '';
            this.engines = [];
            this.engineDisabled = true;
        },
        checkFormValidity() {
            this.isFormValid = this.selectedMake !== '' && this.selectedModel !== '';
        },
    }"
    x-init="$watch('selectedMake', () => { resetEnginesSelector(); checkFormValidity() }); $watch('selectedModel', () => checkFormValidity())"
>
    <x-forms.select label="Make"
        x-model="selectedMake"
        @change="fetchModels"
        x-bind:disabled="isLoading || makeDisabled"
        id="make"
        name="make"
        :options="$makes"
        required />

    <select name="model"
        id="model"
        @change="fetchEngines"
        x-model="selectedModel"
        required
        x-bind:disabled="Object.keys(models).length === 0 || isLoading"
        class="form-control"
    >
        <option value="" selected>Please select</option>
        <template x-for="model in models" :key="model.id">
            <option x-bind:value="model.id" x-text="model.name"></option>
        </template>
    </select>

    <select name="engine"
        id="engine"
        required
        x-bind:disabled="Object.keys(engines).length === 0 || isLoading"
        class="form-control"
    >
        <option value="" selected>Please select</option>
        <template x-for="engine in engines" :key="engine.id">
            <option x-bind:value="engine.id" x-text="engine.name"></option>
        </template>
    </select>
</div>

And in my <script> tag, there is the following:

function fetchEngines(
    selectedModel,
    engines,
    isLoading,
    engineDisabled
) {
    engineDisabled = true;
    isLoading = true;

    fetch(router.fetchEngines, {
        method: 'post',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': token,
        },
        body: JSON.stringify({
            model: selectedModel
        })
    })
    .then(r => {
        if (!r.ok) {
            throw new Error('Network response was not ok')
        }

        return r.json();
    })
    .then(data => {
        engines.splice(0, engines.length, ...data);
        engineDisabled = false;
    })
    .finally(() => {
        isLoading = false;
    })
}

function fetchModels(
    selectedMake,
    models,
    isLoading,
    makeDisabled
) {
    makeDisabled = true;
    isLoading = true;

    fetch(router.fetchModels, {
        method: 'post',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': token,
        },
        body: JSON.stringify({
            make: selectedMake
        })
    })
        .then(r => {
            if (!r.ok) {
                throw new Error('Network response was not ok')
            }

            return r.json();
        })
        .then(data => {
            models.splice(0, models.length, ...data);
            makeDisabled = false;
        })
        .finally(() => {
            isLoading = false;
        })
    }

So, what I am trying to achieve is: when the backend validation fails or any other backend exception is being thrown, I want to return back to the form and these 3 selects to be pre-populated and pre-checked with old values.

For this reason in my Laravel Controller, I am returning a redirect response: return back()->withInput().

I have tried to set the selectedMake and selectedEngine, by including old values in the x-data part:

selectedMake: '{{ old('make') }}',
selectedModel: '{{ old('model') }}',
selectedEngine: '{{ old('engine') }}',
....

But that didn’t work, since only the Make select has been selected, but Model and Engine selects were not pre-populated with options.

As ChatGPT suggested, I even created a separate function:

if (oldMake && oldModel) {
    fetchModels(oldMake);
    fetchEngines(oldModel);
}

and in x-init of the first DIV I added the fetchModels(selectedMake); fetchEngines(selectedModel) part. That didn’t work as well, since again – only Make select has been selected, but Model and Engine selects were not, since these are empty at that moment.

How can I achieve the desired behavior, so that all 3 selects are prefilled and preselected with old values?

P.S. As you can see, I have a Make select already pre-populated from backend, since Make list is static and for this reason, I created a blade component. For other 2 selects I used the regular HTML select with Alpine attributes.

P.P.S.: An idea came to me while writing this question: on my Backend, I could already pre-fetch the model and engines list and maybe send these 2 lists as a session variable: return back()->with(['models' => ...])->withInput(); and put the list somewhere in JS and then somehow preselect without AJAX request

Update 1

I have came up with a somehow almost working solution:

<div x-data="{
    selectedMake: '{{ old('make') }}',
    selectedModel: '{{ old('model') }}',
    selectedEngine: '{{ old('engine') }}',
    ... // other code, unchanged
}">
    <select name="model" id="model" @change="fetchEngines" 
        x-init="if (selectedModel !== '') (this.selectedMake, this.models, this.isLoading, this.makeDisabled)"
        x-model="selectedModel"
        required
        x-bind:disabled="Object.keys(models).length === 0 || isLoading"
        class="form-control"
    >
        <option value="" selected>Please select</option>
        <template x-for="model in models" :key="model.id">
            <option :value="model.id" :selected="model.id == this.selectedModel" x-text="model.name"></option>
        </template>
    </select>

In this case, the models select is being pre-populated, but not yet pre-selected. What am I missing? I have tried x-bind:selected and :selected on the option tag, but nothing seems to work here.

Update all values string in object or array in dynamic data

I need to validate, update, escape every value string in object or array in the data object, the data is always changing this the base scheme.
I have this code is working, can be done better or do less depth of recursion ?

function _has_array_to_validate_get_string(array) {
  return Array.isArray(array) && array.length === 2 && typeof array[0] === "string" && array[0].includes('valid_type');
}

function validate_escape(...args) {return args}


function funct(object) {


  for ( var key in object ) {

    if (typeof object[key] === "string") {
      object[key] = validate_escape(object[key]);
    }
    else if ( _has_array_to_validate_get_string(object[key]) ) { // ["valid_type.pathdir", "/pathdir/desdss"],

      object[key][1] = validate_escape(object[key][0], object[key][1]);

    }
    else if ( Array.isArray(object[key]) && object[key].every(item => typeof item === "string")  ) {

      object[key].forEach((value, index) => {
        object[key][index] = validate_escape(value);
      });

    }
    else if ( Array.isArray(object[key]) && object[key].every(    item => typeof item === "object" && !Array.isArray(item)     )  ) {

      object[key].forEach((value) => {
        funct(value);
      });

    }
    else if (typeof object[key] === 'object' && !Array.isArray(object[key]) ) {

      funct(object[key])

    }
    else if ( Array.isArray(object[key] ) ) {

      funct(object[key])

    }

      
  }

  return object;

}

Error in VS Code studio when using Javascript in the git bash in terminal section

prati@LAPTOP-A2ET79D1 MINGW64 ~/OneDrive/Desktop/WEB D/2.2+Native+Modules
$ node index.js
node:internal/modules/cjs/loader:1152
throw err;
^

Error: Cannot find module ‘C:UserspratiOneDriveDesktopWEB D2.2+Native+Modulesindex.js’
at Module._resolveFilename (node:internal/modules/cjs/loader:1149:15)
at Module._load (node:internal/modules/cjs/loader:990:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:142:12)
at node:internal/main/run_main_module:28:49 {
code: ‘MODULE_NOT_FOUND’,
requireStack: []
}

Node.js v21.6.1

this error
what can i doenter image description here

so i am using VS Code studio for my web dev project
i install git bash and node js to use javascript in it
at the terminal i select bash and make a directory
in the directory i create a file namely index.js in which i wrote console.log (“hello”);
now i am using the command node index.js to run javascript
after writing node index.js it should show hello but it is showing an error

I need an that contain real url mp3 track [closed]

I want a json file or an api which contain the music mp3 data along with their actual track url or link which can be used in the javascript fetch function through which i can access that url and when i run that audio url using the play() and pause() in javascript that music should be played in my browser when i fire an event on a button

If anyone know the solution please answer the solution

Update image in laravel controller using javascript

i need to use javascript to update a image file from form in controller. The server response:(Internal Server Error)
For more clarify i post my code:
the view blade..php è:

<div class="col">
<form action="{{ route('upload.uploadImage') }}" id="imageForm" >
 @csrf
<input type="file"   onchange="loadFile(event)"> <br>        
      <img  id="output" />

</form></div>

The javascript code on view:

var loadFile = function(event) {
  var reader = new FileReader();
    reader.onload = function(){
  var output = document.getElementById('output');
    output.src = reader.result;
  var file = event.target.files[0]; 

    $.ajax({
      url: $('#imageForm').attr('action'),
      method: "POST",   
      headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}', 
      },
      data:new FormData($('#imageForm')[0]),
      dataType:'JSON',
      contentType: false,
      cache:false,
      processData: false,
    success: (data)=> {
      console.log("Value added " + output.src);
    },
    error: function(data){
           console.log(data);}
           });

    };
    reader.readAsDataURL(event.target.files[0]);
  };

the route:

Route::post('/upload', [ImageController::class,'uploadImage'])->name('upload.uploadImage');

the ImageController:

 public function uploadImage(Request $request): JsonResponse
{

    dd('Controller method called');
    $image= new Image;
    $image->name=$request->input('name');
    
    if ($request->hasFile('image')) {
        $file=$request->file('image');
        $extension=$file->getClientOriginalExtension();
        $filename=time().'.'.$extension;
        $file->move('public/images/',$filename);
        $image->image=$filename;
       session()->put('filename', $filename);

       $image->save();
       return response()->json(['success' => 'Post created successfully.']);
    }
}

Of course, head of view has the following code:

<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />

Queueing in python flask for an omegle clone

I’ve trying to make a queueing system but its not working.
The queueing logic im going with is that:
Lets say have we have dictionary “queue” which contains the queues.
When the dict is empty, we are gonna create a code, add our name to to it, and add all that to the dictionary as an item, and save allat via sessions, AND MOST IMPORTANTLY: Check if the number of members become 2, if in that case, we redirect to /chat. When the dict is not empty, the code we’re gonna use is the key of the 1st item in the dict, and save it via sessions, and redirect to /chat


The problem im facing is that the creator of the item in the dictionary, i.e when u click on it when list is empty, THEY DONT REDIRECT. But if ur not the creator of the queue item, instead u click on it when there is already an item (u join, basically), u redirect.

I think the problem lies in the checking of the number of members when an item is created when there are no members, which i wrote under an if statement. Under that if statement is the checking, which i wrote in a While Loop.


CODE:

#on submitting / on post request
        if len(queue) == 0:
            code = "".join(random.choices(ascii_uppercase, k=4))
            queue[code] = {"members" : [name]}

            session["name"] = name
            session["favColor"] = favColor
            session["code"] = code

            while len(queue[code]["members"]) == 1:
                return render_template("waiting.html")
            else:
                return redirect(url_for("chat"))
        
        else: 
            code = next(iter(queue))
            queue[code]["members"].append(name)

            session["name"] = name
            session["favColor"] = favColor
            session["code"] = code

            if len(queue[code]["members"]) == 2:
                return redirect(url_for("chat"))

And I just mentioned, the coder under the else statement is working fine “i think”, its just the code under the if statement.

HELP MY LIFE DEPENDS ON WETHER I MAKE THIS

i am getting this error “await is only valid in async functions and the top level bodies of modules ” [duplicate]

this is the code i am trying to run but i am getting error as “await is only valid in async functions and the top level bodies of modules “



const url = 'https://instagram-bulk-scraper-latest.p.rapidapi.com/media_info_from_shortcode/CwqI-QTpUG2';
const options =  {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': '3896965707mshebe233289922e1dp1165bfjsn462757791834',
        'X-RapidAPI-Host': 'instagram-bulk-scraper-latest.p.rapidapi.com'
    }
};

try {
    const response = await fetch(url, options);
    const result = await response.text();
    console.log(result);
} catch (error) {
    console.error(error);
}

Challenges Setting Input Element Values in JavaScript Console on a Website

While experimenting with a website’s behavior, I encountered a challenge when attempting to set the value of an input element via the console in JavaScript. Specifically, I’m working with the following URL: https://www.goibibo.com/hotels/. My goal is to populate the city field using the console.

The element I’m targeting is:

const inputElement = document.getElementById('downshift-1-input');
inputElement.value= "Nashik, Maharashtra, India"

Although the value appears in the browser, it remains blank in the “Elements” tab of the console. Interestingly, when I check inputElement.value in the console, it does show the desired value. However, upon clicking search, “Nashik, Maharashtra, India” disappears from the browser.

I’ve experimented with different methods to set the value, including:

const inputElement = document.getElementById('downshift-1-input');
inputElement.setAttribute('value', 'Nashik, Maharashtra, India')

and

// Get the HTML input element
const inputElement = document.getElementById('downshift-1-input');


// Text to simulate typing
const textToType = "Nashik, Maharashtra, India";

// Function to simulate typing
function simulateTyping(text) {
    let index = 0;
    const intervalId = setInterval(() => {
        const char = text.charAt(index);
        const keydownEvent = new KeyboardEvent('keydown', { 'key': char });
        inputElement.dispatchEvent(keydownEvent);       
        setTimeout(() => {
            const keyupEvent = new KeyboardEvent('keyup', { 'key': char });
            inputElement.dispatchEvent(keyupEvent);
        }, 100); // Interval between keydown and keyup events      
        inputElement.value += char; // Update input value      
        index++;
        if (index >= text.length) {
            clearInterval(intervalId);
        }
    }, 200); // Interval between each keystroke (keydown + keyup)
}
// Call the function to simulate typing
simulateTyping(textToType);

However, all attempts yield the same outcome.
Is there a workaround to achieve my objective?

How to Extract Json data from objects in typescript

I want to extract converted json from coverted excel data file but not working,
I want it to be in this form :

[{assignee: "", description: "seriene", duration: "24", floor: "Deluxe", id: 2, image_one: null,…},…]
0
: 
{assignee: "", description: "seriene", duration: "24", floor: "Deluxe", id: 2, image_one: null,…}
1
: 
{assignee: null, description: "seriene", duration: "24", floor: "Deluxe", id: 3, image_one: null,…}
2
: 
{assignee: null, description: "seriene", duration: "24", floor: "Deluxe", id: 5, image_one: null,…}

But shows this:

{Sheet1: [,…]}
Sheet1
: 
[,…]
0
: 
{First Name: "Samuel", Last Name: "Gyimah", Staff No.: "San50", Phone: 0, Address: "6th avenue tanoso",…}
Account
: 
111222554
Address
: 
"6th avenue tanoso"
Appointment
: 
45364.99990740741
Bank
: 
"UBA"
Branch
: 
"AAMUSTED"
Email
: 
"[email protected]"
First Name
: 
"Samuel"
ID No.
: 
"GHA7145562"
Joined
: 
45365.99990740741
Last Name
: 
"Gyimah"
Phone
: 
0
Resident
: 
"On Campus"
Staff No.
: 
"San50"
Subject
: 
"Social Studies"

I used this for loop :

onFileChange(ev) {
  this.loading.start();
  let workBook = null;


    let jsonData = null;
    const reader = new FileReader();
    const file = ev.target.files[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = XLSX.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      const dataString = JSON.stringify(jsonData);
      for(let i:number =0;i<dataString.length; i++){
        console.log(dataString[i]);
      }
     

Where to put custom Handlebars functions in Ghost CMS?

I’m trying to break out of the limitations of Handlebars HBS templates and make a couple of helpers, something like this for example:

// Custom Handlebars helper to compare dates
// Usage: {{#isBeforeDate date1 date2}} Content {{else}} Other content {{/isBeforeDate}}
Handlebars.registerHelper('isBeforeDate', function(date1, date2, options) {
    if (new Date(date1) < new Date(date2)) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

Where exactly should I put these helpers in (a self-hosted) Ghost CMS so that it works and doesn’t break the whole site during a scheduled Ghost update?

Analysing image – canvas is undefined

I’m writing a module that is supposed to create an rgb histogram for a given image. I’m analyzing an image onload. But for some reason I got the canvas is undefined, when I define the canvas a line above. I completely cannot figure out why it doesn’t work. The error in the console point to line 22: const context = canvas.getContext('2d');. Can you help?

import { useEffect, useRef, useState } from 'react';
import { histogram, max, scaleLinear, format } from 'd3';
import kitty from './kitty.jpg';
import { LinearAxisLeft } from '../../shared/LinearAxisLeft';
import { AxisBottomIntegers } from '../../shared/AxisBottomIntegers';

const histHeight = 200;

export const ImageAnalyzer = () => {
  const canvasRef = useRef();
  const [loaded, setLoaded] = useState(false);

  let img = null;
  let data = null;

  useEffect(() => {
    img = new Image();
    img.src = kitty;

    img.onload = () => {
      // Create a canvas element to get pixel data
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      context.drawImage(img, 0, 0, img.width, img.height);

      // Get pixel data
      const imageData = context.getImageData(0, 0, img.width, img.height).data;

      // Collect RGB values
      const rgbValues = [];
      for (let i = 0; i < imageData.length; i += 4) {
        const red = imageData[i];
        const green = imageData[i + 1];
        const blue = imageData[i + 2];
        rgbValues.push({ red, green, blue });
      }

      data = rgbValues;
      setLoaded(true);
    };
  }, []); // Empty dependency array ensures useEffect runs only once

  if (!loaded && !img) {
    return <p>Loading Image...</p>;
  }

  const redBins = histogram().value((d) => d.red).domain([0, 255]).thresholds(255);
  const greenBins = histogram().value((d) => d.green).domain([0, 255]).thresholds(20);
  const blueBins = histogram().value((d) => d.blue).domain([0, 255]).thresholds(20);

  const histRed = redBins(data);
  const histGreen = greenBins(data);
  const histBlue = blueBins(data);

  // Assuming histRed, histGreen, and histBlue are arrays of bins
  const allBins = [...histRed, ...histGreen, ...histBlue];

  // Extract the counts from each bin
  const counts = allBins.map((bin) => bin.length);

  const maxCount = max(counts);

  const yScale = scaleLinear().domain([0, maxCount]).range([0, histHeight]).nice();

  const xScale = scaleLinear().domain([0, 255]).range([0, img.width]).nice();

  return (
    <>
      <svg width={img.height} height={histHeight}>
        <LinearAxisLeft innerWidth={img.width} tickFormat={format('')} yScale={yScale} />
        <AxisBottomIntegers innerHeight={img.height} tickFormat={format('')} xScale={xScale} />
      </svg>
      <canvas ref={canvasRef} style={{ border: '1px solid red' }} />
    </>
  );
};