Toast Notification Appears on Every Page After Login Failure in CodeIgniter

I’m facing an issue with toast notifications in my CodeIgniter app. After a failed login attempt, the error message is displayed correctly using Toastr. However, this message keeps appearing on every page after the login attempt, even after navigating or refreshing the page.

I’ve tried using flashdata to show the error message, but the toast notification keeps appearing on all pages until the session expires or I manually clear the session.

Here’s my login function:

$login_status = $this->validate_login($email, $password);`
if ($login_status == 'success') {`
    redirect(site_url('dashboard'), 'refresh');`
} else {
    $this->session->set_flashdata('error_message', get_phrase('login_failed'));`
    redirect(site_url('login'), 'refresh');
}

Logout Function:

    $this->session->sess_destroy();
    $this->session->set_flashdata('logout_notification', 'logged_out');
    redirect(site_url('login'), 'refresh');
}

In includes-bottom.php:

    <script>
        toastr.error('<?php echo $this->session->flashdata('error_message');?>');
    </script>
<?php } ?>

Session Config:

$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

I’ve ensured the flash message is unset after use, and session regeneration is done. However, the issue persists where the toast notification keeps appearing across all pages after a failed login.

Has anyone faced this issue before? What am I missing here?

I tried using flashdata to display the error message for login failure and unset the session after showing the message. I also ensured the session is regenerated and cleared on logout. I expected the toast message to only appear once when the login fails and not persist across multiple pages or after a page refresh. However, the issue persists, and the toast message keeps showing on every page even after navigating or refreshing the page.

Can I get any google user’s profile picture? [closed]

I have a big software with thousands of clients. I just thought it would be a nice touch if I could add their google profile picture, just to identify them easier.

I mean, I’m not attempting to hack or intrude anything, I’m just trying to access a low resolution image of their PUBLIC profiles from some URL or API, only using their emails, either to store the pictures or just to request them to display realtime. This has nothing to do with logins or with asking permissions.

What I want is either:

a) an URL I can access via javascript or PHP’s file_get_contents or similar

b) an API I can call via PHP
…so I can loop the entire DB and do this with those who have gmail.

How to fix file upload in livewire [duplicate]

I try to upload a file in livewire but I faced some problems
this is my code

my component code is

<?php

namespace AppLivewire;

use AppModelsbrand;
use Exception;
use LivewireComponent;
use LivewireWithFileUploads;
use LivewireWithPagination;

class LiveBrand extends Component
{
    use WithPagination;
    use WithFileUploads;
    public $search;
    public $t_name;
    public $sort = '';
    public string $name = '';
    public $logo;
    public $namb = 5;
    public bool $stat = false;
    public function stat()
    {
        $this->stat = !$this->stat;
    }

    public function show()
    {
        $this->namb++;
    }

    public function stor()
    {
        try {
            $validated = $this->validate([
                'name' => 'required|string|max:255|min:2',
                'logo' => 'required|image|max:1024', // 1MB Max
                'stat' => 'nullable|boolean'
            ]);

            // Check if logo exists
            if ($this->logo) {
                $imagePath = $this->logo->store(path: 'public');

                Brand::create([
                    'name' => $validated['name'],
                    'logo' => $imagePath,
                    'stat' => $validated['stat'] ?? false
                ]);

                $this->reset(['name', 'logo', 'stat']);
                $this->create_alert('Brand');
                $this->dispatch('brand-created');
            } else {
                session()->flash('error', 'Please select a logo file');
            }
        } catch (Exception $e) {
            session()->flash('upload_error', 'File upload failed: ' . $e->getMessage());
            $this->exception_alert($e);
        }
    }


    public function sorter($name)
    {
        $this->sort = $this->sort === 'desc' ? 'asc' : 'desc';
        $this->t_name = $name;
    }

    public function render()
    {
        $all = brand::where('name', 'like', "%{$this->search}%")
            ->orWhere('created_at', 'like', "%{$this->search}%")
            ->orderBy(empty($this->t_name) ? 'id' : '' . $this->t_name . '', '' . empty($this->sort) ? 'desc' : '' . $this->sort . '' . '')
            ->latest()
            ->paginate(5);
        $tabelnames = [
            "Brand" => 'name',
            "Logo" => 'logo',
            "Créé Le" => 'created_at',
            "Statut" => 'stat'
        ];
        return view('livewire.live-brand', [
            "thname" => $tabelnames,
            "all" => $all,
            "uploadError" => session('upload_error')
        ]);
    }
}

me view is

<div class="page-wrapper row">
   <form wire:submit="stor">
       @error('logo')
        <div classs="alert alert-danger text-danger">{{$message}}</div>
       @enderror
      <div class="col-12">
        <label for="" class="form-label">Name</label>
        <input class="form-control" type="text" wire:model="name">
      </div>
      <div class="col-12">
       <label for="" class="form-label">Logo</label>
       <input class="form-control" type="file" wire:model="logo">
     </div>
    <button class="btn btn-primary" type="submit">Upload</button>
  </form>
</div>

enter image description here

it show me this error The logo failed to upload. and when I click on the upload button it show me the The logo field is required please help me .
enter image description here

How to fix av_interleaved_write_frame() broken pipe error in php

I have an issue using ffmpeg to stream audio and parse to google cloud speech to text in PHP.

It returns this output.
I have tried delaying some part of the script, that did not solve it.
I have also checked for similar questions. however, they are mostly in python and none of the solutions actually work for this.

  built with gcc 8 (GCC)
  cpudetect
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
Input #0, mp3, from 'https://npr-ice.streamguys1.com/live.mp3':
  Metadata:
    icy-br          : 96
    icy-description : NPR Program Stream
    icy-genre       : News and Talk
    icy-name        : NPR Program Stream
    icy-pub         : 0
    StreamTitle     :
  Duration: N/A, start: 0.000000, bitrate: 96 kb/s
    Stream #0:0: Audio: mp3, 32000 Hz, stereo, fltp, 96 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (mp3 (mp3float) -> pcm_s16le (native))
Press [q] to stop, [?] for help
Output #0, s16le, to 'pipe:':
  Metadata:
    icy-br          : 96
    icy-description : NPR Program Stream
    icy-genre       : News and Talk
    icy-name        : NPR Program Stream
    icy-pub         : 0
    StreamTitle     :
    encoder         : Lavf58.29.100
    Stream #0:0: Audio: pcm_s16le, 16000 Hz, mono, s16, 256 kb/s
    Metadata:
      encoder         : Lavc58.54.100 pcm_s16le
**av_interleaved_write_frame(): Broken pipe** 256.0kbits/s speed=1.02x
**Error writing trailer of pipe:: Broken pipe**
size=      54kB time=00:00:01.76 bitrate= 250.8kbits/s speed=0.465x
video:0kB audio:55kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
Conversion failed!

this is my PHP code

require_once 'vendor/autoload.php';
    
    $projectId = "xxx-45512";
    putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/xxx-45512-be3eb805f1d7.json');
    
    // Database connection
    $pdo = new PDO('mysql:host=localhost;dbname=', '', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $url = "https://npr-ice.streamguys1.com/live.mp3";
    
    $ffmpegCmd = "ffmpeg -re -i $url -acodec pcm_s16le -ac 1 -ar 16000 -f s16le -";
    
    $fp = popen($ffmpegCmd, "r");
    if (!$fp) {
        die("Failed to open FFmpeg stream.");
    }
    sleep(5);

    try {
        $client = new SpeechClient(['transport' => 'grpc', 'credentials' => json_decode(file_get_contents(getenv('GOOGLE_APPLICATION_CREDENTIALS')), true)]);
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage(); 
        exit;
    }
    
    $recognitionConfig = new RecognitionConfig([
        'auto_decoding_config' => new AutoDetectDecodingConfig(),
        'language_codes' => ['en-US'],
        'model' => 'long',
    ]);
    
    $streamingConfig = new StreamingRecognitionConfig([
        'config' => $recognitionConfig,
    ]);
    
    $configRequest = new StreamingRecognizeRequest([
        'recognizer' => "projects/$projectId/locations/global/recognizers/_",
        'streaming_config' => $streamingConfig,
    ]);
    
    
    function streamAudio($fp)
    {
        while (!feof($fp)) {
            yield fread($fp, 4096);
        }
    }
    
    $responses = $client->streamingRecognize([
    'requests' => (function () use ($configRequest, $fp) {
            yield $configRequest; // Send initial config
            foreach (streamAudio($fp) as $audioChunk) {
                yield new StreamingRecognizeRequest(['audio' => $audioChunk]);
            }
        })()]
    );
    
    // $responses = $speechClient->streamingRecognize();
    // $responses->writeAll([$request,]);
    
    foreach ($responses as $response) {
        foreach ($response->getResults() as $result) {
            $transcript = $result->getAlternatives()[0]->getTranscript();
            // echo "Transcript: $transcriptn";
    
            // Insert into the database
            $stmt = $pdo->prepare("INSERT INTO transcriptions (transcript) VALUES (:transcript)");
            $stmt->execute(['transcript' => $transcript]);
        }
    }
    
    
    pclose($fp);
    $client->close();

I’m not sure what the issue is at this time.

UPDATE

I’ve done some more debugging and i have gotten the error to clear and to stream actually starts.
However, I expect the audio to transcribe and update my database but instead I get this error when i close the stream

error after closing stream

this is my updated code

    $handle = popen($ffmpegCommand, "r");

    try {
        $client = new SpeechClient(['transport' => 'grpc', 'credentials' => json_decode(file_get_contents(getenv('GOOGLE_APPLICATION_CREDENTIALS')), true)]);
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage(); 
        exit;
    }
    
    try {
    $recognitionConfig = (new RecognitionConfig())
        ->setAutoDecodingConfig(new AutoDetectDecodingConfig())
        ->setLanguageCodes(['en-US'], ['en-UK'])
        ->setModel('long');
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage(); 
        exit;
    }
    
    try {
        $streamConfig = (new StreamingRecognitionConfig())
        ->setConfig($recognitionConfig);
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
        exit;
    }
    try {
        $configRequest = (new StreamingRecognizeRequest())
        ->setRecognizer("projects/$projectId/locations/global/recognizers/_")
        ->setStreamingConfig($streamConfig);
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage(); 
        exit;
    }
    
    $stream = $client->streamingRecognize();
    $stream->write($configRequest);
    
    mysqli_query($conn, "INSERT INTO transcriptions (transcript) VALUES ('bef')");
    
    while (!feof($handle)) {
        $chunk = fread($handle, 25600);
        // printf('chunk: ' . $chunk);
        if ($chunk !== false) {
            try {
                $request = (new StreamingRecognizeRequest())
                        ->setAudio($chunk);
                    $stream->write($request);
            } catch (Exception $e) {
                printf('Errorc: ' . $e->getMessage());
            }
        }
    }
    
    
    $insr = json_encode($stream);
    mysqli_query($conn, "INSERT INTO transcriptions (transcript) VALUES ('$insr')");
    
    foreach ($stream->read() as $response) {
        mysqli_query($conn, "INSERT INTO transcriptions (transcript) VALUES ('loop1')");
        foreach ($response->getResults() as $result) {
            mysqli_query($conn, "INSERT INTO transcriptions (transcript) VALUES ('loop2')");
            foreach ($result->getAlternatives() as $alternative) {
                $trans = $alternative->getTranscript();
                mysqli_query($conn, "INSERT INTO transcriptions (transcript) VALUES ('$trans')");
            }
        }
    }
    
    pclose($handle);
    $stream->close();
    $client->close();```

How to get custom checkout field values with Woocommerce Checkout Blocks

I added some data with the function :

woocommerce_register_additional_checkout_field(
            array(
                'id'       => 'namespace/newsletter-opt-in',
                'label'    => 'Subscribe to newsletter ?',
                'location' => 'order',
                'type'     => 'checkbox',
            )
        );

I try to check this checkbox but I can’t get the value
However, the data is well returned in my order data column

I tried :

$order = wc_get_order($order_id);
$subscribe = $order->get_meta('namespace/newsletter-opt-in');

But $subscribe is empty

Scraping a Gamma site and hosting it on Hostinger [closed]

I’m trying to scrape this page: https://digital-dynamo-1txmi5g.gamma.site/ (built with Gamma) and upload it to public_html on Hostinger. However, I encountered issues with images, animations, and responsiveness.

How can I scrape and host the page while preserving images, animations, and responsiveness? Any suggestions?

Here’s what I tried:

  • Save as “Web Page, Complete” – The page breaks (missing images, animations, incorrect layout).

  • DevTools > Save as “HTML only” (mobile version) – The mobile version works, but the desktop one doesn’t.

  • Puppeteer (Node.js) – Same results as “HTML only”.

server page showing cannot find ejs module

i have already installed ejs in my mac terminal but when i m running the project the server page showing cannot find ejs module
anyone knows how to resolve it and i have also done reinstalling ejs , restarting the server , checking node module (dont suggest these methods)
pls suggest some

Server error in different browsers when i use my local server – cors [duplicate]

I am writing and testing a full-stack application. My frontend is uploaded to hosting and has the address for example – planner. And my server is on a local computer with a database. For the test, I run the server through the ngrok tunnel, I registered, and received a free static domain for example – grateful.
In requests, I use axios, I have public requests – $public, and authorized with a token – $auth. Public requests work without problems, but for requests with authorization I get a CORS error. This error is in both desktop Google Chrome and mobile Google Chrome, in Microsoft Edge, and also in Safari on the iPhone.
My CORS ERROR is: cross-origin resource sharing error wildcard origin not allowed


I am sending next code

  1. axios request settings
  2. CORS settings on the server
  3. as well as responses in the Google Chrome browser to an authorized request, as well as the response from the Microsoft Edge browser.

  1. const $auth = axios.create({
    baseURL: “grateful”,
    withCredentials: true,
    });
    const $public = axios.create({
    baseURL: “grateful”,
    withCredentials: true,
    });

    $auth.interceptors.request.use((config) => {
    config.headers.Authorization = Bearer ${localStorage.getItem( "accessTokenPlanner" )};
    return config;
    });

  2. const allowedOrigins = [
    “planner”,
    “grateful”,
    ];

    app.use(
    cors({
    origin: function (origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
    callback(null, true);
    } else {
    callback(new Error(“CORS not allowed”));
    }
    },
    credentials: true,
    methods: [“GET”, “POST”, “PUT”, “DELETE”, “OPTIONS”],
    allowedHeaders: [“Content-Type”, “Authorization”],
    })
    );

    app.options(“*”, cors());

3)

Google chrome
access-control-allow-origin: *
content-length: 2906
content-security-policy: default-src 'self' https://cdn.ngrok.com 'unsafe-eval' 'unsafe-inline'; img-src data: w3.org/svg/2000
content-type: text/html
date: Thu, 27 Mar 2025 14:43:11 GMT
referrer-policy:no-referrer
x-content-type-options:nosniff
----
MS Edge
access-control-allow-origin:*
content-length:2906
content-security-policy:default-src 'self' https://cdn.ngrok.com 'unsafe-eval' 'unsafe-inline'; img-src data: w3.org/svg/2000
content-type:text/html
date:Thu, 27 Mar 2025 15:31:51 GMT
referrer-policy:no-referrer
x-content-type-options:nosniff

I checked all the link addresses and rewrote the settings several times.
The most interesting thing is that with these settings that I wrote above, everything works periodically in the desktop version of Google Chrome. But now it doesn’t work anymore, although I didn’t change anything.

How to structure nestjs project [closed]

How to structure an event organization web application?

I’m new to programming projects from scratch, and I’ve started creating an event organization web application. I’m confused about how to divide the functionality.

Application Requirements:

  1. User:

    • Can see upcoming events
    • Can choose an existing group to enroll in
  2. Admin:

    • Can create and manage groups for an event
    • Each group represents an activity for the event (presentation, song, dance, etc.)

My Questions:

  1. What is the right way to define modules for this nestjs project

  2. How to define whick entities shoould i create

I would appreciate any guidance on the architecture and role division for this type of application.

I haven’t started creating modules yet, was a bit scared to mess things up from the start

btFixedConstraint freeze objects

I am trying to ‘freeze objects together’ using Bullet (via JavaScript + Three.JS)

Here is my scene
https://codepen.io/PartyPants2/pen/emYLRPX?editors=0010

Here we see a Merry-go-round simulation, in which 8 horses are generated above a turntable/disc.

a 3d simulation of horses on a Merry-go-round

This GIF illustrates the system working as expected – the 8 horses (instances of bodyA) are frozen-in-place to the turntable/disc (bodyB)

However a problem becomes apparent when the disc (bodyB) has different rotation applied: the horses are being rotated by a factor of bodyB‘s rotation, knocking them off of their target axis.

a 3d simulation of horses on a Merry-go-round has tilted turntable and the horses are being tilted a disproportionally when constraints are activated2

When we turn on the physics, the FixedConstraints activate. Because the constraints are being misconfigured (in some way I am trying to determine) the horses are rotating disproportionately to the turntable.

I have tried every combination of absolute and relative rotations that I can think of (to the point of making an interface to trial different combinations), but the horses never adhere correctly to the turntable.

Here’s a simplified version of my btFixedConstraint implementation

// bodyA = the rigidBody being attached
// bodyB = what bodyA is being attached to
const applyFixedConstraint = (bodyA, bodyB) => {
    const relRotationAB = getRelativeRotation(bodyA, bodyB);
    const relPosBA = getRelativePosition(bodyB, bodyA);
    // FRAME IN A
    const frameInA = new Ammo.btTransform();
    frameInA.setIdentity();
    frameInA.getOrigin().setValue(0, 0, 0);
    frameInB.setRotation(new Ammo.btQuaternion(0,0,0,1)); // i.e. 'none'
    // FRAME IN B
    const frameInB = new Ammo.btTransform();
    frameInB.setIdentity();
    frameInB.getOrigin().setValue(relPosBA.x, relPosBA.y, relPosBA.z); 
    frameInB.setRotation(new Ammo.btQuaternion(relRotationAB.x, relRotationAB.y, relRotationAB.z, relRotationAB.w));
    // RESULT
    const fixedConstraint = new Ammo.btFixedConstraint(bodyA,bodyB,frameInA,frameInB); // this line doesn't "freeze items in the air" like it should
    physicsWorld.addConstraint(fixedConstraint, true);
    return fixedConstraint;
}

btFixedConstraint only has one constructor: new Ammo.btFixedConstraint(bodyA,bodyB,frameInA,frameInB); and since bodyA and bodyB are certain to be correct, only frameInA or frameInB could have the problem…

How can I calculate the correct frameInA and frameInB for freezing objects together using btFixedConstraint ?

Resolving Javascript Modules with importmap not working on android chrome

I have a symfony project with the assetmapper package active. There is an app.js which imports:

import './styles/app.css';
import Wood from "./wood.js";

The gernerated importmap looks like this:

<script type="importmap">
{
    "imports": {
        "app": "/assets/app-g2dctYT.js",
        "/assets/styles/app.css": "data:application/javascript,",
        "/assets/wood.js": "/assets/wood-PRFWpuV.js"
    }
}
</script>

On my Desktop Chrome. Everything works as expected. But on the mobile chrome on my android device (134.0.6998.135) it will try to load the file from /assets/wood.js instead of /assets/wood-PRFWpuV.js. If a manually edit the importmap making it “foo”: “/assets/wood-PRFWpuV.js” and making it import Wood from “foo” accordingly it works. Is there a known issue on chrome Android with this or am I doing something wrong?

Video element shows blank while the media stream is set through srcObject

I know this is a little long code, however, I gave complete code because I really couldn’t find exact cause.
The local view works perfectly, but other’s users shows blank div in chrome.
Please help with this, I’m stuck with this since a week.

And, as I tested, the MediaStream (event.stream) wasn’t null, and is valid.

Full code: https://drive.google.com/file/d/1f2YV5tyXgIiRQV378zIhsDJ03j3EYFnK/view?usp=sharing

import SendIcon from '@mui/icons-material/Send';
import GridLayout from "react-grid-layout";


import "./Video.css"

import ReactPlayer from 'react-player';

const server_url = 'http://localhost:3002/';
const beforeUnloadListener = (event) => {
    //Send something to back end
    // event.preventDefault(); // This is necessary for the confirmation dialog to show in some browsers
    // event.returnValue = 'Are you sure you want to leave?'; // This will show a confirmation dialog
    this.handleDeleteCurrUserFromDB();
    this.handleEndCall();

}



const viewTypes = [
    {
        value: 'Default',
        label: <LabelWithIcon icon={InterpreterModeIcon} text="Default View" />,
    },
    {
        value: 'GridView',
        label: <LabelWithIcon icon={GridViewIcon} text="Grid View" />,
    },

];


class Video extends Component {




    constructor(props) {
        super(props)

        this.myVidRef = React.createRef();
        this.remoteStreamsRef = React.createRef();

        this.videoContainerRef = React.createRef();


        this.localVideoref = React.createRef()

        this.videoAvailable = false
        this.audioAvailable = false

        this.state = {
            video: false,
            audio: false,
            screen: false,
            showModal: false,
            screenAvailable: false,
            messages: [],
            localStream: [],
            streams: [],
            message: "",
            newmessages: 0,
            askForUsername: true,
            username: name,
            gridRows: 1,
            meetLinkPSM: meetLinkPSMt,
            videoType: "Default", // Add this line
            remoteStreams: [],
            forceRenderKey: 0, // Force re-render when needed
            gridLayoutData: [],
            renderReloader: 0,

        }
        connections = {}

        this.getPermissions()




    }

    handleVideoTypeChange = (event) => {
        const selectedType = event.target.value;
        this.setState({ videoType: selectedType }, () => {
            console.log("Selected video type:", this.state.videoType); // Debug log
        });
        this.getUserMedia(); // Call getUserMedia after updating the video type
        console.log("Local video stream:", this.localVideoref.current?.srcObject);
        

    };
    getPermissions = async () => {
        try {
            await navigator.mediaDevices.getUserMedia({ video: true })
                .then(() => this.videoAvailable = true)
                .catch(() => this.videoAvailable = false)

            await navigator.mediaDevices.getUserMedia({ audio: true })
                .then(() => this.audioAvailable = true)
                .catch(() => this.audioAvailable = false)

            if (navigator.mediaDevices.getDisplayMedia) {
                this.setState({ screenAvailable: true })
            } else {
                this.setState({ screenAvailable: false })
            }

            if (this.videoAvailable || this.audioAvailable) {
                navigator.mediaDevices.getUserMedia({ video: this.videoAvailable, audio: this.audioAvailable })
                    .then((stream) => {
                        window.localStream = stream
                        this.localVideoref.current.srcObject = stream
                    })
                    .then((stream) => { })
                    .catch((e) => console.log(e))
            }
        } catch (e) { console.log(e) }
    }
    putfullScreen = (event) => {
        let elem = event.target
        if (elem.requestFullscreen) {
            elem.requestFullscreen()
        } else if (elem.mozRequestFullScreen) { /* Firefox */
            elem.mozRequestFullScreen()
        } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari and Opera */
            elem.webkitRequestFullscreen()
        } else if (elem.msRequestFullscreen) { /* IE/Edge */
            elem.msRequestFullscreen()
        }

    }
    getMedia = () => {
        this.setState({
            video: this.videoAvailable,
            audio: this.audioAvailable
        }, () => {
            this.getUserMedia()
            this.connectToSocketServer()
        })
    }

    getUserMedia = () => {
        if ((this.state.video && this.videoAvailable) || (this.state.audio && this.audioAvailable)) {
            navigator.mediaDevices.getUserMedia({ video: this.state.video, audio: this.state.audio })
                .then(this.getUserMediaSuccess)
                .then((stream) => { })
                .catch((e) => console.log(e))
        } else {
            try {
                let tracks = this.localVideoref.current.srcObject.getTracks()
                tracks.forEach(track => track.stop())
            } catch (e) { }
        }
    }

    getUserMediaSuccess = (stream) => {
        try {
            window.localStream.getTracks().forEach(track => track.stop())
        } catch (e) { console.log(e) }

        setTimeout(() => {
            const videoElem = document.getElementById('my-video');
            if (videoElem) {
                videoElem.srcObject = stream;
                console.log("Video element found, setting srcObject");
            } else {
                console.error("Video element not found in the DOM");
            }
        }, 1000);




        this.setState({ localStream: stream });

        for (let id in connections) {
            if (id === socketId) continue

            connections[id].addStream(window.localStream)

            connections[id].createOffer().then((description) => {
                connections[id].setLocalDescription(description)
                    .then(() => {
                        socket.emit('signal', id, JSON.stringify({ 'sdp': connections[id].localDescription }))
                    })
                    .catch(e => console.log(e))
            })
        }

        stream.getTracks().forEach(track => track.onended = () => {
            this.setState({
                video: false,
                audio: false,
            }, () => {
                try {
                    let tracks = this.localVideoref.current.srcObject.getTracks()
                    tracks.forEach(track => track.stop())
                } catch (e) { console.log(e) }

                let blackSilence = (...args) => new MediaStream([this.black(...args), this.silence()])
                window.localStream = blackSilence()
                this.localVideoref.current.srcObject = window.localStream

                for (let id in connections) {
                    connections[id].addStream(window.localStream)

                    connections[id].createOffer().then((description) => {
                        connections[id].setLocalDescription(description)
                            .then(() => {
                                socket.emit('signal', id, JSON.stringify({ 'sdp': connections[id].localDescription }))
                            })
                            .catch(e => console.log(e))
                    })
                }
            })
        })
    }

    getDislayMedia = () => {
        if (this.state.screen) {
            if (navigator.mediaDevices.getDisplayMedia) {
                navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
                    .then(this.getDislayMediaSuccess)
                    .then((stream) => { })
                    .catch((e) => console.log(e))
            }
        }
    }

    getDislayMediaSuccess = (stream) => {
        try {
            window.localStream.getTracks().forEach(track => track.stop())
        } catch (e) { console.log(e) }

        window.localStream = stream
        this.localVideoref.current.srcObject = stream

        for (let id in connections) {
            if (id === socketId) continue

            connections[id].addStream(window.localStream)

            connections[id].createOffer().then((description) => {
                connections[id].setLocalDescription(description)
                    .then(() => {
                        socket.emit('signal', id, JSON.stringify({ 'sdp': connections[id].localDescription }))
                    })
                    .catch(e => console.log(e))
            })
        }

        stream.getTracks().forEach(track => track.onended = () => {
            this.setState({
                screen: false,
            }, () => {
                try {
                    let tracks = this.localVideoref.current.srcObject.getTracks()
                    tracks.forEach(track => track.stop())
                } catch (e) { console.log(e) }

                let blackSilence = (...args) => new MediaStream([this.black(...args), this.silence()])
                window.localStream = blackSilence()
                this.localVideoref.current.srcObject = window.localStream

                this.getUserMedia()
            })
        })
    }




    gotMessageFromServer = (fromId, message) => {
        var signal = JSON.parse(message)

        if (fromId !== socketId) {
            if (signal.sdp) {
                connections[fromId].setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(() => {
                    if (signal.sdp.type === 'offer') {
                        connections[fromId].createAnswer().then((description) => {
                            connections[fromId].setLocalDescription(description).then(() => {
                                socket.emit('signal', fromId, JSON.stringify({ 'sdp': connections[fromId].localDescription }))
                            }).catch(e => console.log(e))
                        }).catch(e => console.log(e))
                    }
                }).catch(e => console.log(e))
            }

            if (signal.ice) {
                connections[fromId].addIceCandidate(new RTCIceCandidate(signal.ice)).catch(e => console.log(e))
            }
        }
    }



    connectToSocketServer = () => {
        socket = io.connect(server_url, { secure: false })

        socket.on('signal', this.gotMessageFromServer)

        socket.on('connect', () => {
            socket.emit('join-call', { path: window.location.href, username: this.state.username })
            socketId = socket.id



            // socket.on('chat-message', this.addMessage)
            socket.on('chat-message', (data, sender, socketIdSender) => {
                console.log("Received chat message:", data, "from:", sender, "socketId:", socketIdSender); // Debug log
                this.addMessage(data, sender, socketIdSender);
            });

            socket.on('user-left', (id) => {

                this.state.gridLayoutData = this.state.gridLayoutData.filter(item => item.i !== id); // Remove the user from the grid layout data



                // Force a re-render
                this.forceUpdate();
                let video = document.querySelector(`[data-socket="${id}"]`)
                if (video !== null) {
                    elms--
                    video.parentNode.removeChild(video)

                    // let main = document.getElementById('main')
                    // this.changeCssVideos(main)
                }
            })

            socket.on('user-joined', (id, clients) => {
                clients.forEach((client) => {

                    const socketListId = client.id;
                    socketdmd = socketListId;
                    const username = client.username; // Add this line to get the username


                    this.triggerEventMessage(username + " Joined"); // Call the function with the socketListId and username

                    connections[socketListId] = new RTCPeerConnection(peerConnectionConfig)
                    // Wait for their ice candidate       
                    connections[socketListId].onicecandidate = function (event) {
                        if (event.candidate != null) {
                            socket.emit('signal', socketListId, JSON.stringify({ 'ice': event.candidate }))
                        }
                    }


                    const userExists = this.state.gridLayoutData.some(item => item.i == socketListId);
                    if (!userExists && socketListId !== socketId) {

                        var gridData = {
                            i: socketListId,
                            x: this.state.gridRows,
                            y: 0,
                            w: 2,
                            h: 6,
                            static: true,
                            username: username, // Add the username to the grid data
                        };
                        


                        this.setState((prevState) => {
                            // Check if the user already exists in gridLayoutData

                            const updatedGridLayoutData = prevState.gridLayoutData.map((item) => {
                                if (item.i === socketListId) {
                                    return { ...item, stream }; // Update the stream property
                                }
                                return item;

                            });

                            return { gridLayoutData: updatedGridLayoutData };
                        });
                        console.log("Stream added:", stream); // Debug log






                    };




                    // Add the local video stream
                    if (window.localStream !== undefined && window.localStream !== null) {
                        // alert("Local Stream is not null");
                        connections[socketListId].addStream(window.localStream)
                    } else {
                        // alert("Local Stream is null");
                        let blackSilence = (...args) => new MediaStream([this.black(...args), this.silence()])
                        window.localStream = blackSilence()
                        connections[socketListId].addStream(window.localStream)
                    }
                })

                if (id === socketId) {
                    for (let id2 in connections) {
                        if (id2 === socketId) continue

                        try {
                            connections[id2].addStream(window.localStream)
                        } catch (e) { }

                        connections[id2].createOffer().then((description) => {
                            connections[id2].setLocalDescription(description)
                                .then(() => {
                                    socket.emit('signal', id2, JSON.stringify({ 'sdp': connections[id2].localDescription }))
                                })
                                .catch(e => console.log(e))
                        })
                    }
                }
            })
        })
    };

    silence = () => {
        let ctx = new AudioContext()
        let oscillator = ctx.createOscillator()
        let dst = oscillator.connect(ctx.createMediaStreamDestination())
        oscillator.start()
        ctx.resume()
        return Object.assign(dst.stream.getAudioTracks()[0], { enabled: false })
    }
    black = ({ width = 640, height = 480 } = {}) => {
        let canvas = Object.assign(document.createElement("canvas"), { width, height })
        canvas.getContext('2d').fillRect(0, 0, width, height)
        let stream = canvas.captureStream()
        return Object.assign(stream.getVideoTracks()[0], { enabled: false })
    }

    handleVideo = () => this.setState({ video: !this.state.video }, () => this.getUserMedia())
    handleAudio = () => this.setState({ audio: !this.state.audio }, () => this.getUserMedia())
    handleScreen = () => this.setState({ screen: !this.state.screen }, () => this.getDislayMedia())





    openChat = () => this.setState({ showModal: true, newmessages: 0 })
    closeChat = () => this.setState({ showModal: false })
    handleMessage = (e) => this.setState({ message: e.target.value })

    // addMessage = (data, sender, socketIdSender) => {
    //  this.setState(prevState => ({
    //      messages: [...prevState.messages, { "sender": sender, "data": data }],
    //  }))
    //  if (socketIdSender !== socketId) {
    //      this.setState({ newmessages: this.state.newmessages + 1 })
    //  }
    // }

    addMessage = (data, sender, socketIdSender) => {
        console.log("Adding message to state:", data, sender, socketIdSender); // Debug log
        this.setState(prevState => ({
            messages: [...prevState.messages, { sender, data }],
        }), () => {
            console.log("Updated messages state:", this.state.messages); // Debug log after state update
        });
        if (socketIdSender !== socketId) {
            this.setState({ newmessages: this.state.newmessages + 1 });
        }
    };


    handleUsername = (e) => this.setState({ username: e.target.value })

    sendMessage = () => {
        socket.emit('chat-message', this.state.message, this.state.username)
        console.log("Message sent:", this.state.message, this.state.username)
        this.setState({ message: "", sender: this.state.username })
    }


    connect = () => {
        this.setState({ askForUsername: false }, () => this.getMedia());
        this.updateDataBaseMain();
    }
    handleShowDiagForEnd = () => {
        this.setState({ openDialog: true });
    }



    render() {

        const isMobile = this.isMobileDevice(); // Check if the device is mobile



        return (
            <div>
                {this.state.askForUsername === true ?
                    <div>
                        <div style={{
                            background: "white", width: "30%", height: "auto", padding: "20px", minWidth: "400px",
                            textAlign: "center", margin: "auto", marginTop: "50px", justifyContent: "center"
                        }}>
                            <p style={{ margin: 0, fontWeight: "bold", paddingRight: "50px" }}>Please Type You Name Here!</p>
                            <Input placeholder="Your Name" value={this.state.username} onChange={e => this.handleUsername(e)} />
                            <Button variant="contained" color="primary" onClick={this.connect} style={{ margin: "20px" }}>Connect</Button>
                        </div>

                        <div style={{ justifyContent: "center", textAlign: "center", paddingTop: "40px" }}>
                            <video id="my-video" ref={this.localVideoref} autoPlay muted style={{
                                borderStyle: "solid", borderColor: "#bdbdbd", objectFit: "fill", width: "60%", height: "30%"
                            }}></video>
                        </div>
                    </div>
                    :
                    <div>

                        <LatestEvent eventMessage={this.state.eventMessage} />
                        <div className="btn-down" style={{ position: "fixed", backgroundColor: "gray", color: "whitesmoke", textAlign: "center" }}>
                            <IconButton style={{ color: "#424242" }} onClick={this.handleVideo}>
                                {(this.state.video === true) ? <VideocamIcon /> : <VideocamOffIcon />}
                            </IconButton>

                            <IconButton style={{ color: "#f44336" }} id="btnEC" onClick={this.handleShowDiagForEnd}>
                                <CallEndIcon />
                            </IconButton>

                            <IconButton style={{ color: "#424242" }} onClick={this.handleAudio}>
                                {this.state.audio === true ? <MicIcon /> : <MicOffIcon />}
                            </IconButton>

                            {this.state.screenAvailable === true ?
                                <IconButton style={{ color: "#424242" }} onClick={this.handleScreen}>
                                    {this.state.screen === true ? <ScreenShareIcon /> : <StopScreenShareIcon />}
                                </IconButton>
                                : null}

                            <Badge badgeContent={this.state.newmessages} max={999} color="secondary" onClick={this.openChat}>
                                <IconButton style={{ color: "#424242" }} onClick={this.openChat}>
                                    <ChatIcon />
                                </IconButton>
                            </Badge>
                        </div>

                        <Modal show={this.state.showModal} onHide={this.closeChat} style={{ zIndex: "999999" }}>
                            <Modal.Header closeButton={false}>
                                <Modal.Title>Chat Room</Modal.Title>
                                <CloseIcon style={{ color: "#f44336", cursor: "pointer" }} id="btnEC" onClick={this.closeChat}>
                                </CloseIcon>
                            </Modal.Header>
                            <Modal.Body style={{ overflow: "auto", overflowY: "auto", height: "400px", textAlign: "left" }} >
                                {this.state.messages.length > 0 ? this.state.messages.map((item, index) => (
                                    <div key={index} style={{ textAlign: "left" }}>
                                        <p style={{ wordBreak: "break-all" }}><b>{item.sender}</b>: {item.data}</p>
                                    </div>
                                )) : <p>No message yet</p>}
                            </Modal.Body>
                            <Modal.Footer className="div-send-msg">
                                <TextField id="filled-full-width" variant='filled' fullWidth multiline placeholder="Message" value={this.state.message} onChange={e => this.handleMessage(e)} />
                                <br />
                                <br />
                                <Button onClick={this.sendMessage} variant="contained" endIcon={<SendIcon />}>
                                    Send
                                </Button>
                                {/* <Button variant="contained" color="primary" onClick={this.sendMessage}>Send</Button> */}
                            </Modal.Footer>
                        </Modal>

                        <div className="container">
                            <div className='header'>

                                <div className='left'>


                                    <div style={{ paddingTop: "20px" }}>

                                        <InfoIcon />
                                        <Input value={this.state.meetLinkPSM} disable="true"></Input>
                                        <Button style={{
                                            backgroundColor: "#3f51b5", color: "whitesmoke", marginLeft: "20px",
                                            marginTop: "10px", width: "120px", fontSize: "10px"
                                        }} onClick={this.copyUrl}>Copy invite link</Button>

                                    </div>
                                    <div className='right'>

                                        {!isMobile && (

                                            <TextField
                                                id="outlined-select-currency"
                                                select
                                                className='selectView'
                                                style={{ right: 0 }}
                                                value={this.state.videoType}
                                                onChange={this.handleVideoTypeChange}
                                                variant="outlined"
                                            >
                                                {viewTypes.map((option) => (
                                                    <MenuItem key={option.value} value={option.value}>
                                                        {option.label}
                                                    </MenuItem>
                                                ))}
                                            </TextField>

                                        )}
                                    </div>

                                </div>

                            </div>

                            {/* <Row id="main" className="flex-container" style={{ margin: 0, padding: 0 }}>

                                <br />

                            </Row> */}

                            {this.state.videoType === "GridView" ?

                                <div>



                                    <div style={{ paddingBottom: "80px" }}>
                                        <GridLayout
                                            id="main"
                                            className="layout"
                                            layout={this.state.gridLayoutData}
                                            cols={6}
                                            rowHeight={30}
                                            width={1200}
                                            isResizable={false}
                                            isDraggable={true}
                                        >


                                            <div
                                                key="local"
                                                data-grid={{ i: "local", x: 0, y: 0, w: 2, h: 6 }}
                                                className="video-tile main-video"
                                            >

                                                <video
                                                    id="my-video"
                                                    autoPlay
                                                    ref={this.localVideoref}
                                                    muted
                                                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                                />
                                                <div className="video-label">
                                                    {this.state.username} (You)
                                                </div>
                                            </div>

                                            {this.state.gridLayoutData.map((item) => (
                                                <div
                                                    id={item.i}
                                                    data-grid={{ i: item.i, x: item.x, y: item.y, w: item.w, h: item.h }}
                                                    key={item.i} className="video-container"
                                                >

                                                    <>
                                                        <video
                                                            id={item.i}
                                                            autoPlay
                                                            playsInline
                                                            muted
                                                            style={{ borderColor: "#000", borderStyle: "solid", borderWidth: "1", width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                                                            ref={(videoElement) => {
                                                                if (videoElement && item.stream) {
                                                                    console.log(" Video element found:", videoElement);
                                                                    console.log(" Stream for item:", item.stream);
                                                                    
                                                                    // Set attributes
                                                                    videoElement.setAttribute("data-socket", item.i);
                                                                    videoElement.setAttribute("title", item.username);
                                                                    videoElement.muted = true;
                                                                    videoElement.autoplay = true;
                                                            
                                                                    // If a different stream is set, remove the old one
                                                                    if (videoElement.srcObject !== item.stream) {
                                                                        console.log("Updating srcObject...");
                                                                        videoElement.srcObject = item.stream;
                                                                    }
                                                            
                                                                    // Debugging: Check if the stream actually has video tracks
                                                                    const videoTracks = item.stream.getVideoTracks();
                                                                    if (videoTracks.length === 0) {
                                                                        console.error(" No video tracks found in the stream!");
                                                                    } else {
                                                                        console.log(" Video track found:", videoTracks[0]);
                                                                    }
                                                            
                                                                    // Ensure the video plays when the metadata is loaded
                                                                    videoElement.onloadedmetadata = () => {
                                                                        console.log("Video metadata loaded, attempting to play...");
                                                                        videoElement.play()
                                                                            .then(() => console.log("✅ Video is playing!"))
                                                                            .catch((error) => console.error("⚠️ Video play error:", error));
                                                                    };
                                                            
                                                                    // Extra debugging: Check when a track is added or removed
                                                                    item.stream.onaddtrack = (event) => {
                                                                        console.log(" New track added:", event.track);
                                                                    };
                                                            
                                                                    item.stream.onremovetrack = (event) => {
                                                                        console.log("Track removed:", event.track);
                                                                    };
                                                                }
                                                            }}
                                                            
                                                        ></video>

                                                    </>

                                                </div>
                                            ))}




                                        </GridLayout>
                                    </div>


                                </div>


How to execute code after a call to a function that uses fetch is done? [duplicate]

I have a function that I call that uses fetch:

function fetchData() {
fetch(`${url}`)
    .then(response => response.json())
    .then(json => {
         // use the json to update some UI
        });

    })
    .catch(function (err) {

    })
    .finally(function () {
        
    });
}

Now whenever I fetch this data, I always want to update a certain part of the UI the same way, that’s why I have the json part inside the function:

    .then(response => response.json())
    .then(json => {
         // use the json to update some UI
        });

    })

But I also want to call this function to do other different UI updates depending on where it was called from, for example opening different modals:

function someFunction() {
    fetchData();
    openModal();
}

function someOtherFunction() {
    fetchData();
    openOtherModal();
}

How can I call the second function only after fetchData() is done? Is there a way to “chain” the then() outside?

For example something like:

fetchData().then(openModal());

Or, it’s not possible in the way it’s currently written?

Is there any to select child elements by the relative position of the same class?

This example provides the desired outcome of selecting the first, second, and third child elements that are of class “subhead”. However, my question is, Is there any selection method that will select the first, second, and third occurrences of class “subhead” irregardless of its exact child position in the parent, such that this would work when it is not known in advance what those positions will be; and we could use postions 1,2,3 instead of 1,3,5 since it won’t known how many sibling elements will be between each subhead?

Thank you.

div.scrl_can * {
  height:25px;
  border: 1px solid black;
}
.subhead:nth-of-type(1) {
  background-color: blue;
}
.subhead:nth-of-type(3) {
  background-color: green;
}
.subhead:nth-of-type(5) {
  background-color: yellow;
}
<div id="main">
  <div>
    <div>
      <div class="scrl_can">
        <div class="subhead"></div>
        <div></div>
        <div class="subhead"></div>
        <div></div>
        <div class="subhead"></div>
        <div></div>
      </div>
    </div>
  </div>
</div>

Issue related to skywise – Slate dashboard

I am working on modifying an existing dashboard in Airbus Skywise. My task involves:

Fetching Data:

When the user clicks the “Fetch” button, the system should fetch data from the columns specified by the user and store it for later use.

Manual Description Input:

In the “Manual Description” cell, the user will manually paste description texts from the Airbus database, corresponding to specific FUID IDs.

Generating a TDD Assessment:

When the user clicks “Generate Assessment”, the system should:

  1. Use the previously fetched data and the manual descriptions as
    references.
  2. Leverage ML/AI models to auto-generate a TDD Assessment based on
    predefined reference scripts for different error types.
  3. Since I am new to Skywise, I am looking for guidance on how to
    implement this functionality. Specifically, I need help with:
  4. Fetching and storing user-specified column data.
  5. Handling manual descriptions and linking them to FUID IDs.
  6. Implementing ML/AI-based auto-generation of the TDD Assessment using
    reference scripts.

Any insights or best practices on Skywise development would be greatly appreciated!