Sending an array from the javascript to the laravel controller

Im trying to send an array from my javascript to my laravel controller but when I dd() I get null.
Javascript :

$('#submmit').click(function() {
            $.ajax({
                method: 'POST',
                url: '/Calendar/store',
                contentType: 'json',
                data: JSON.stringify(partconValues),
                success: function(response) {
                    console.log(response);
                },
                error: function(error) {
                    console.error('Error sending partconValues to the controller:', error);
                }
            });
        })

Controller :

public function store(Request $request)
{
    Log::info('Request data:', $request->all());
    $partconValues = json_decode($request->getContent());
    $process = AppModelsProcess::find($request->input('partcon_id'));
    $part = AppModelsProductPart::find($request->input('part_id'));
    $product = AppModelsProduct::find($request->input('product_id'));

    $userStartTime = Carbon::createFromFormat('m/d/Y H:i', $request->input("start") . ' ' . $request->input("starttime"));
    $workStart = Carbon::createFromTime(8, 0);
    $workEnd = Carbon::createFromTime(18, 0);

    $task = new AppModelsTask;
    $task->name = $request->input('TaskName');
    $task->process_id = $partconValues;
    dd($task);
    $task->save();

    $totalDuration = $process->construction_time * $request->input('construction_time');

    if ($totalDuration <= $workStart->diffInMinutes($workEnd)) {
        $data = new AppModelsCalendar;
        $data->name = $process->name;
        $data->code = $product->code . $part->code . $process->code;
        $data->duration = $totalDuration;
        $data->start = $userStartTime;
        $data->finish = $userStartTime->copy()->addMinutes($totalDuration)->toDateTimeString();
        $data->station_id = $request->input('station_id');
        $data->priority = "1";
        $data->save();

        return redirect('/admin');
    } else {
        $remainingDuration = $totalDuration;

        while ($remainingDuration > 0) {
            $currentDayEndTime = $userStartTime->copy()->setTime(18, 0);
            $currentDayActualEndTime = min($currentDayEndTime, $userStartTime->copy()->addMinutes($remainingDuration));

            $data = new AppModelsCalendar;
            $data->name = $process->name;
            $data->code = $product->code . $part->code . $process->code;
            $data->duration = $currentDayActualEndTime->diffInMinutes($userStartTime);
            $data->start = $userStartTime;
            $data->finish = $currentDayActualEndTime->toDateTimeString();
            $data->station_id = $request->input('station_id');
            $data->priority = "1";
            $data->save();

            $userStartTime = $data->start->setTime(8, 0)->addDay();
            $workEnd = Carbon::createFromTime(18, 0);

            $remainingDuration -= $data->duration;
        }

        return redirect('/admin');
    }
}

My Laravel log :

[2023-11-25 22:27:35] local.INFO: Request data: {"TaskName":"HI","product_id":"1","construction_time":"12","station_id":"1","starttime":"08:00","start":"11/25/2023","_token":"GhbA5tVuVHKGZPb0YM8w0fL9BrsCdvHnaWRWAUGy"}

partconValues is the array Im trying to send.
I console loged the array too and it is showing up currectly.
I think my problem is in reciving the array in the controller I tested few ways but I didnt have any luck. please help me thank you.

Execution failed for task ‘:app:compileDebugJavaWithJavac’ Task failed with an exception. – What went wrong: java.lang.StackOverflowError

moeen@moeen-HP-ProBook-640-G4:~/Downloads/TS-app-routes_issue$ npx react-native run-android
info JS server already running.
info Installing the app…

Task :app:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use ‘–warning-mode all’ to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings
35 actionable tasks: 1 executed, 34 up-to-date
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/MainApplication.java:5: error: cannot find symbol
import com.facebook.react.PackageList;
^
symbol: class PackageList
location: package com.facebook.react
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/newarchitecture/MainApplicationReactNativeHost.java:5: error: cannot find symbol
import com.facebook.react.PackageList;
^
symbol: class PackageList
location: package com.facebook.react
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/MainApplication.java:28: error: cannot find symbol
List packages = new PackageList(this).getPackages();
^
symbol: class PackageList
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/newarchitecture/MainApplicationReactNativeHost.java:47: error: cannot find symbol
List packages = new PackageList(this).getPackages();
^
symbol: class PackageList
location: class MainApplicationReactNativeHost
Note: /home/moeen/Downloads/TS-app-routes_issue/android/app/src/debug/java/com/techstuffapp/ReactNativeFlipper.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
4 errors

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.

  • What went wrong:
    Execution failed for task ‘:app:compileDebugJavaWithJavac’.

Compilation failed; see the compiler error output for details.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.
==============================================================================

2: Task failed with an exception.

  • What went wrong:
    java.lang.StackOverflowError (no error message)

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.
==============================================================================

BUILD FAILED in 2s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/MainApplication.java:5: error: cannot find symbol
import com.facebook.react.PackageList;
^
symbol: class PackageList
location: package com.facebook.react
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/newarchitecture/MainApplicationReactNativeHost.java:5: error: cannot find symbol
import com.facebook.react.PackageList;
^
symbol: class PackageList
location: package com.facebook.react
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/MainApplication.java:28: error: cannot find symbol
List packages = new PackageList(this).getPackages();
^
symbol: class PackageList
/home/moeen/Downloads/TS-app-routes_issue/android/app/src/main/java/com/techstuffapp/newarchitecture/MainApplicationReactNativeHost.java:47: error: cannot find symbol
List packages = new PackageList(this).getPackages();
^
symbol: class PackageList
location: class MainApplicationReactNativeHost
Note: /home/moeen/Downloads/TS-app-routes_issue/android/app/src/debug/java/com/techstuffapp/ReactNativeFlipper.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
4 errors

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.

  • What went wrong:
    Execution failed for task ‘:app:compileDebugJavaWithJavac’.

Compilation failed; see the compiler error output for details.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.
==============================================================================

2: Task failed with an exception.

  • What went wrong:
    java.lang.StackOverflowError (no error message)

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.
==============================================================================

BUILD FAILED in 2s

at makeError (/home/moeen/Downloads/TS-app-routes_issue/node_modules/execa/index.js:174:9)
at /home/moeen/Downloads/TS-app-routes_issue/node_modules/execa/index.js:278:16
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async runOnAllDevices (/home/moeen/Downloads/TS-app-routes_issue/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:109:5)
at async Command.handleAction (/home/moeen/Downloads/TS-app-routes_issue/node_modules/react-native/node_modules/@react-native-community/cli/build/index.js:142:9)

react native build failed

Create and Save a File With JavaScript and No Server

I’m attempting to use the code from here https://stackoverflow.com/a/34156339
to make a json object, then save it as a file. No server, running a local file in my browser.

I might suspect this https://stackoverflow.com/a/28378004
to be the issue, but I can’t print anything.

I expected a file saving dialog box. The results vary between browsers.

In Firefox, Uncaught TypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads.

In Chrome, Uncaught TypeError: Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed.

I am giving it a Blob so there should be no problem.

having issue with axios.post() to fetch the data with node.js

I am currently trying to fetch the data once the user access to the website and use this data to draw a chart.

But as the chart is not being displayed I debugged and I found that either the function to fetch the data or overall structure to call this function is not working.

And, I used separate python file to fetch the data with same url , route with requests.post() and printed them –> worked fine

So, it is clear that it got problem at the js or html file.

But front-end is not my primary area so I cannot debug it for any furthermore.

Please at least give me advice how to further investigate this issue

cument.addEventListener('DOMContentLoaded',(event)=>{
var overallChartData = null;
var dailyChartData = null;
var lastDailyFetchTime = null;
async function fetchData(url) {
      try {
            const response = await axios.post(url);
            return response.data;
        } catch (error) {
            console.error('Error fetching data:', error);
            return null;
        }
    }


async function updateOverallChart() {
        if (!overallChartData) { // Fetch only if data is not already fetched
            overallChartData = await fetchData('http://localhost:3001/returnOverallData');
            processAndCreateOverallChart();
        }
        processAndCreateOverallChart();
    }

updateOverallChart()


}


//if the user access to the website -- > document.addEventListener('DOMContentLoaded',(event) will be activated

//then create variable to store the fetched data such as overallChartData 

//then updateOverallChart() will be called which will check if overallChartData is null, if it is null it call fetchData to fetch data

//the serverside app.route is already tested with independent python file using requests.post() method with same url

//currently the biggest problem is that at the server-side the following message is not printed meaning that the fetchData or the logic to call it have issue 
@app.route('/returnOverallData',methods=['POST'])
def returnOverallData():
    print("returnOverallData") --> this is not being printed --> but it gets printed well with another separate python file with requests.post()
  1. I tried to solve this issue with chatgpt and google bard, and they all give me unclear answers and I changed

    overallChartData, dailyChartData, lastDailyFetchTime into let and not var and it also not worked

  2. I removed async from the functoin fetchData and it also not worked

  3. I called fetchData directly with url, and it also not worked

async function fetchData(url) {
        try {
            const response = await axios.post(url);
            return response.data;
        } catch (error) {
            console.error('Error fetching data:', error);
            return null;
        }
    }
    fetchData('http://localhost:3001/returnOverallData')  --> still at serverside "returnOverallData" is not printed

so I guess that I have core issue with function fetchData as even if I call it directly it does not work. but I am new in node.js and overall front-end, please help me to fix this function

Google Analytics 4 Not Updating User Count in Real-Time for Chrome Extension Events

I have a chrome extension and I’ve applied Google analytics to that, like if a button is clicked, I perform this –

async function ga4(category, label, event) {
  chrome.storage.local.get("userId", function (data) {
      user_id = data.userId;
  });
  const params = {
      v: '2',
      tid: ga_tid,
      cid: user_id,
      en: event,
      'ep.event_category': category,
      'ep.event_label': label
  };
  const queryString = new URLSearchParams(params).toString();
  const url = `https://www.google-analytics.com/g/collect?${queryString}`;
  const options = { method: 'POST' };
  if(ga_tid){
    fetch(url, options);
  }
}

When i see users from audience in GA4 property, i see there are 38 users, but I do not get any demographic details from that, or even if a new user clicks on an event, I get that the event was clicked in realtime data but the number of users remain 0 there.

When I add a new user or even from an old user when I click on a button that event is shown here – GA4 showing event was added in last 30 minutes .
But the Users in last 30 minutes remain 0 like this –
GA4 showing 0 users

How to trigger V8 “tiering up” with Liftoff [Arm64]

Working with V8 right now and I am trying to trying to trigger the Tiering Up of the Liftoff Assembler found in v8/v8/src/wasm/baseline/arm64/liftoff-assembler-arm64.h

Does anyone know how to do this? Or if it’s possible to construct a WASM Module complex enough for the Tiering up to occur — I guess my basic goal is to exhaust the tiering budget.

Even a preexisting module that is known to be big/complex enough to trigger it would be much appreciated.

I’m currently debugging in lldb and am unfortunately unable to see any tiering up from Liftoff.

Any help would be very much appreciated.

‘TINYMCE_SCRIPT_SRC’ was not found in ‘@tinymce/tinymce-angular’ package

I have an Angular 8 project. I am trying to implement tinymce in my project.

So I went through these 2 documentation links which I found useful: Link1 Link2

Mentioned in the above Link2 document, as I am on Angular 8 so I am using tinymce 3.x
enter image description here

So I started to follow the installation & configuration steps given in Link1.

But now facing an issue in which TINYMCE_SCRIPT_SRC is not found in ‘@tinymce/tinymce-angular’.

enter image description here

I followed all the instructions as mentioned in the document:
enter image description here

enter image description here

enter image description here

But I am still facing the issue. What can be the problem?

Kindly help. Thanks.

how can I get data from a child component to a parent component if there are several input fields in the child component?

The parent component has data that I want to pass to the child component. For example, I created such a component with data.
Parent component

<template>
         
   <NameUser :data="userData"></NameUser>
   <div>first name: {{ userData.firstName }}</div>
   <div>last name: {{ userData.lastName }}</div>
 
</template>

<script setup>
    
    import {ref} from 'vue'
    import NameUser from '../components/NameUser.vue';
    const userData = ref({
        firstName: 'testName',
        lastName: 'testLastName'
    })

</script>

In the child component, I receive this data and will have to pass it back to the parent component after changing it.
Child component

<template>

    <label>First name</label>
    <input :value="data.firstName" @input="changeData">

    <label>Last name</label>
    <input :value="data.lastName" @input="changeData">

</template>

<script setup>

    const props = defineProps({
        data:Object
    })

    function changeData(){}

</script>

Help to implement the changeData function. Please tell me if it is necessary to use the computed property to avoid re-rendering.

svelte: Issue with API call staying pending when accessing application via IP address or hostname, server response as stream data, chat-UI

Title: Issue with API call staying pending when accessing application via IP address

Description:

I have forked the chat-ui project and made several changes, including Azure AD integration, OpenAI API compatible serving layer support, and making it more container-friendly. The application works fine on localhost, but when I try to access it via an IP address, I encounter an issue.

Problem:

The backend code provides data as a stream to the frontend using the POST method. On localhost, everything works as expected, but when accessing the application via an IP address, the API call from the network stays pending until it reaches component.close() in the frontend. The issue seems to be related to the stream not being processed properly.

Backend Code (excerpt):

export async function POST({ request, locals, params, getClientAddress }) {
    const id = z.string().parse(params.id);
    const convId = new ObjectId(id);
    const promptedAt = new Date();

    const userId = locals.user?._id ?? locals.sessionId;

    // check user
    if (!userId) {
        throw error(401, "Unauthorized");
    }
    console.log("post", {userId, params, ip: getClientAddress()})

    // check if the user has access to the conversation
    const conv = await collections.conversations.findOne({
        _id: convId,
        ...authCondition(locals),
    });

    if (!conv) {
        throw error(404, "Conversation not found");
    }

    // register the event for ratelimiting
    await collections.messageEvents.insertOne({
        userId: userId,
        createdAt: new Date(),
        ip: getClientAddress(),
    });

    // guest mode check
    if (
        !locals.user?._id &&
        requiresUser &&
        (MESSAGES_BEFORE_LOGIN ? parseInt(MESSAGES_BEFORE_LOGIN) : 0) > 0
    ) {
        const totalMessages =
            (
                await collections.conversations
                    .aggregate([
                        { $match: authCondition(locals) },
                        { $project: { messages: 1 } },
                        { $unwind: "$messages" },
                        { $match: { "messages.from": "assistant" } },
                        { $count: "messages" },
                    ])
                    .toArray()
            )[0]?.messages ?? 0;

        if (totalMessages > parseInt(MESSAGES_BEFORE_LOGIN)) {
            throw error(429, "Exceeded number of messages before login");
        }
    }

    // check if the user is rate limited
    const nEvents = Math.max(
        await collections.messageEvents.countDocuments({ userId }),
        await collections.messageEvents.countDocuments({ ip: getClientAddress() })
    );

    if (RATE_LIMIT != "" && nEvents > parseInt(RATE_LIMIT)) {
        throw error(429, ERROR_MESSAGES.rateLimited);
    }

    // fetch the model
    const model = models.find((m) => m.id === conv.model);

    if (!model) {
        throw error(410, "Model not available anymore");
    }

    // finally parse the content of the request
    const json = await request.json();

    const {
        inputs: newPrompt,
        response_id: responseId,
        id: messageId,
        is_retry,
        web_search: webSearch,
    } = z
        .object({
            inputs: z.string().trim().min(1),
            id: z.optional(z.string().uuid()),
            response_id: z.optional(z.string().uuid()),
            is_retry: z.optional(z.boolean()),
            web_search: z.optional(z.boolean()),
        })
        .parse(json);

    // get the list of messages
    // while checking for retries
    let messages = (() => {
        if (is_retry && messageId) {
            // if the message is a retry, replace the message and remove the messages after it
            let retryMessageIdx = conv.messages.findIndex((message) => message.id === messageId);
            if (retryMessageIdx === -1) {
                retryMessageIdx = conv.messages.length;
            }
            return [
                ...conv.messages.slice(0, retryMessageIdx),
                { content: newPrompt, from: "user", id: messageId as Message["id"], updatedAt: new Date() },
            ];
        } // else append the message at the bottom

        return [
            ...conv.messages,
            {
                content: newPrompt,
                from: "user",
                id: (messageId as Message["id"]) || crypto.randomUUID(),
                createdAt: new Date(),
                updatedAt: new Date(),
            },
        ];
    })() satisfies Message[];

    await collections.conversations.updateOne(
        {
            _id: convId,
        },
        {
            $set: {
                messages,
                title: conv.title,
                updatedAt: new Date(),
            },
        }
    );

    // we now build the stream
    const stream = new ReadableStream({
        async start(controller) {
            const updates: MessageUpdate[] = [];

            function update(newUpdate: MessageUpdate) {
                if (newUpdate.type !== "stream") {
                    updates.push(newUpdate);
                }
                controller.enqueue(JSON.stringify(newUpdate) + "n");
            }

            update({ type: "status", status: "started" });

            if (conv.title === "New Chat" && messages.length === 1) {
                try {
                    conv.title = (await summarize(newPrompt)) ?? conv.title;
                    update({ type: "status", status: "title", message: conv.title });
                } catch (e) {
                    console.error(e);
                }
            }

            await collections.conversations.updateOne(
                {
                    _id: convId,
                },
                {
                    $set: {
                        messages,
                        title: conv.title,
                        updatedAt: new Date(),
                    },
                }
            );

            let webSearchResults: WebSearch | undefined;

            if (webSearch) {
                webSearchResults = await runWebSearch(conv, newPrompt, update);
            }

            messages[messages.length - 1].webSearch = webSearchResults;

            conv.messages = messages;

            const endpoint = await model.getEndpoint();

            for await (const output of await endpoint({ conversation: conv })) {
                // if not generated_text is here it means the generation is not done
                if (!output.generated_text) {
                    // else we get the next token
                    if (!output.token.special) {
                        update({
                            type: "stream",
                            token: output.token.text,
                        });

                        // if the last message is not from assistant, it means this is the first token
                        const lastMessage = messages[messages.length - 1];

                        if (lastMessage?.from !== "assistant") {
                            // so we create a new message
                            messages = [
                                ...messages,
                                // id doesn't match the backend id but it's not important for assistant messages
                                // First token has a space at the beginning, trim it
                                {
                                    from: "assistant",
                                    content: output.token.text.trimStart(),
                                    webSearch: webSearchResults,
                                    updates: updates,
                                    id: (responseId as Message["id"]) || crypto.randomUUID(),
                                    createdAt: new Date(),
                                    updatedAt: new Date(),
                                },
                            ];
                        } else {
                            // abort check
                            const date = abortedGenerations.get(convId.toString());
                            if (date && date > promptedAt) {
                                break;
                            }

                            if (!output) {
                                break;
                            }

                            // otherwise we just concatenate tokens
                            lastMessage.content += output.token.text;
                        }
                    }
                } else {
                    // add output.generated text to the last message
                    messages = [
                        ...messages.slice(0, -1),
                        {
                            ...messages[messages.length - 1],
                            content: output.generated_text,
                            updates: updates,
                            updatedAt: new Date(),
                        },
                    ];
                }
            }

            await collections.conversations.updateOne(
                {
                    _id: convId,
                },
                {
                    $set: {
                        messages,
                        title: conv?.title,
                        updatedAt: new Date(),
                    },
                }
            );

            update({
                type: "finalAnswer",
                text: messages[messages.length - 1].content,
            });
            controller.close();
        },
        async cancel() {
            await collections.conversations.updateOne(
                {
                    _id: convId,
                },
                {
                    $set: {
                        messages,
                        title: conv.title,
                        updatedAt: new Date(),
                    },
                }
            );
        },
    });

    // Todo: maybe we should wait for the message to be saved before ending the response - in case of errors
    return new Response(stream, {
        headers: {
            "Content-Type": "application/x-ndjson",
        },
    });
}

Frontend Code (excerpt):

async function writeMessage(message: string, messageId = randomUUID()) {
        if (!message.trim()) return;

        try {
            isAborted = false;
            loading = true;
            pending = true;

            // first we check if the messageId already exists, indicating a retry

            let retryMessageIndex = messages.findIndex((msg) => msg.id === messageId);
            const isRetry = retryMessageIndex !== -1;
            // if it's not a retry we just use the whole array
            if (!isRetry) {
                retryMessageIndex = messages.length;
            }

            // slice up to the point of the retry
            messages = [
                ...messages.slice(0, retryMessageIndex),
                { from: "user", content: message, id: messageId },
            ];

            const responseId = randomUUID();

            const response = await fetch(`${base}/conversation/${$page.params.id}`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    inputs: message,
                    id: messageId,
                    response_id: responseId,
                    is_retry: isRetry,
                    web_search: $webSearchParameters.useSearch,
                }),
            });

            if (!response.body) {
                throw new Error("Body not defined");
            }

            if (!response.ok) {
                error.set((await response.json())?.message);
                return;
            }
            // eslint-disable-next-line no-undef
            const encoder = new TextDecoderStream();
            const reader = response?.body?.pipeThrough(encoder).getReader();
            let finalAnswer = "";

            // this is a bit ugly
            // we read the stream until we get the final answer
            while (finalAnswer === "") {
                await new Promise((r) => setTimeout(r, 25));

                // check for abort
                if (isAborted) {
                    reader?.cancel();
                    break;
                }

                // if there is something to read
                await reader?.read().then(async ({ done, value }) => {
                    // we read, if it's done we cancel
                    if (done) {
                        reader.cancel();
                        return;
                    }

                    if (!value) {
                        return;
                    }

                    // if it's not done we parse the value, which contains all messages
                    const inputs = value.split("n");
                    inputs.forEach(async (el: string) => {
                        try {
                            const update = JSON.parse(el) as MessageUpdate;
                            if (update.type === "finalAnswer") {
                                finalAnswer = update.text;
                                reader.cancel();
                                invalidate(UrlDependency.Conversation);
                            } else if (update.type === "stream") {
                                pending = false;

                                let lastMessage = messages[messages.length - 1];

                                if (lastMessage.from !== "assistant") {
                                    messages = [
                                        ...messages,
                                        { from: "assistant", id: randomUUID(), content: update.token },
                                    ];
                                } else {
                                    lastMessage.content += update.token;
                                    messages = [...messages];
                                }
                            } else if (update.type === "webSearch") {
                                webSearchMessages = [...webSearchMessages, update];
                            } else if (update.type === "status") {
                                if (update.status === "title" && update.message) {
                                    const conv = data.conversations.find(({ id }) => id === $page.params.id);
                                    if (conv) {
                                        conv.title = update.message;

                                        $titleUpdate = {
                                            title: update.message,
                                            convId: $page. params.id,
                                        };
                                    }
                                }
                            }
                        } catch (parseError) {
                            // in case of parsing error we wait for the next message
                            return;
                        }
                    });
                });
            }

            // reset the websearchmessages
            webSearchMessages = [];

            await invalidate(UrlDependency.ConversationList);
        } catch (err) {
            if (err instanceof Error && err.message.includes("overloaded")) {
                $error = "Too much traffic, please try again.";
            } else if (err instanceof Error && err.message.includes("429")) {
                $error = ERROR_MESSAGES.rateLimited;
            } else if (err instanceof Error) {
                $error = err.message;
            } else {
                $error = ERROR_MESSAGES.default;
            }
            console.error(err);
        } finally {
            loading = false;
            pending = false;
        }
    }

Steps to Reproduce:

  1. Fork the chat-ui project.
  2. Make the specified changes related to Azure AD integration, OpenAI API, and container support.
  3. Run the application on localhost and access it via an IP address.
  4. Observe the behavior where the API call stays pending until component.close() is reached.

Expected Behavior:

The application should behave consistently whether accessed via localhost or an IP address or hostname. The API call should not stay pending, and the stream should be processed correctly.

Additional Information:

  • before Adding component.close() in the stream code the windows machine was not at all returning the response and at the end it was saying promise uncaught

  • Network requests and responses from the browser’s developer tools.
    Local host starts immediately and waterfall of api start getting response and stream is wring at FE correctly :
    enter image description here
    With IP it stays in pending state and when final message arrives at that time it writes everything at once
    enter image description here
    server LOGs:
    enter image description here
    you can see the difference when ip ::1 it starts writing at FE and processing stream data,
    when IP ‘::ffff:10.10.100.106’ it stays in pending until the stream generation is completed i assume

  • Any specific configurations or dependencies related to hosting the application via an IP address.

Environment:

  • Operating System: it is working fine on mac but facing issues in windows
  • Browser: chrome
  • Node.js version: >18
  • Any other relevant environment details.

Note:
Please let me know if additional code snippets or information are needed. Thanks for your help!


Feel free to customize the template based on your specific situation and provide any additional details that might be relevant to the issue.

multiple promise in async await

I’m facing a confusion and would appreciate some clarification or a reference article explaining the behavior observed in the following code snippets.

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise Resolved Value!!");
  }, 20000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise Resolved Value!!");
  }, 10000);
});


async function handlePromise() {
  try {
    console.log("Hello World!!");
    const val = await p1;
    console.log("Namaste JavaScript");
    console.log(val);

    const val2 = await p2;
    console.log("Namaste JavaScript 2");
    console.log(val2);
  } catch (error) {
    console.error("Error:", error);
  }
}
handlePromise();

In this case, the program prints “Hello World!!” and then waits for 20 seconds. After the waiting period, both p1 and p2 parts are printed simultaneously. I’m trying to understand why there is a simultaneous execution of both promises.

but

for this peice of code

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise Resolved Value!!");
  }, 10000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise Resolved Value!!");
  }, 20000);
});


async function handlePromise() {
  try {
    console.log("Hello World!!");
    const val = await p1;
    console.log("Namaste JavaScript");
    console.log(val);

    const val2 = await p2;
    console.log("Namaste JavaScript 2");
    console.log(val2);
  } catch (error) {
    console.error("Error:", error);
  }


}

handlePromise();

In this scenario, after printing “Hello World!!”, the program prints the p1 part after a 20-second delay, followed by the p2 part after a 10-second delay. I’m seeking an explanation for this specific timing behavior.

Any insights or references to articles explaining the underlying asynchronous nature of JavaScript promises would be greatly helpful. Thank you!

tried to seek explanation of a behavior of multiple promise, async await

JS class constructor and update function share the same implementation, using private properties. Crashes on subclasses

I’d like to be able to instantiate an object with some props, and then later update that object with the same props, and run them through the same logic.

class A {
  #a = ''
  constructor(props = {}) {
    this.update(props)
  }
  update(props) {
    this.#a = props.a ?? ''
  }
}
a = new A({a: '123'})

I’m using private properties here, which I didn’t think was a big deal, until I made a subclass:

class B extends A {
  #b = ''
  update(props) {
    super.update(props)
    this.#b = props.b ?? ''
  }
}
b = new B({a: 'a', b: 'b'})
# TypeError: Cannot write private member #b to an object whose class did not declare it

Avoiding private properties solves it, but that’s just avoiding the problem, not fixing it.

Any ideas?

Display word file by docx-preview.js

i was looking for a solution to display the Word file on the HTML page, and I found the following code, and it is exactly what I want.

The only problem I have is: You have to upload the Word file here and click on the button to display the file.

That is, I don’t want any button to be clicked!

For example, you enter the following link: mysite.com/articles?id=5

I have a table in the database where I saved the address of the Word file, for example ID 5, the following address is saved:

files/articles/new-method-in-raising-children.docx

I want to display this in the div tag in the page load.

<html>
<head>
    <title>display word file</title>
</head>
<body>
    <input id="files" type="file" accept=".docx"/>
    <input type="button" id="btnPreview" value="Preview Word Document" onclick="PreviewWordDoc()"/>
    <div id="word-container" class=""></div>
    
    <script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
    <script src="Scripts/docx-preview.js"></script>
    <script type="text/javascript">
        function PreviewWordDoc() {
            //Read the Word Document data from the File Upload.
            var doc = document.getElementById("files").files[0];
     
            //If Document not NULL, render it.
            if (doc != null) {
                //Set the Document options.
                var docxOptions = Object.assign(docx.defaultOptions, {
                    useMathMLPolyfill: true
                });
                //Reference the Container DIV.
                var container = document.querySelector("#word-container");
     
                //Render the Word Document.
                docx.renderAsync(doc, container, null, docxOptions);
            }
        }
    </script>
</body>
</html>

Event delegation not working as expected when trying to remove elements in JavaScript

Sure, here’s a suggestion on how you could frame your question for Stack Overflow:


Title: Event delegation not working as expected when trying to remove elements in JavaScript

Body:

I’m trying to use event delegation in JavaScript to handle click events on elements that are dynamically added to the DOM. I have a container element with the class “experience-cont”, and inside this container, there are elements with the class “garbage-btn”. I’m trying to set up an event listener so that when a “garbage-btn” is clicked, its grandparent element is removed from the DOM.

Here’s the JavaScript code I’m using:

let experienceCont = document.getElementsByClassName("experience-cont")[0];
let resultCont = document.getElementById("experienceResult");
experienceCont.addEventListener("click", (e) => {
    if(e.target && e.target.classList.contains("garbage-btn")){
        let removeEle = e.target.parentNode.parentNode;
        console.log("remove");
        resultCont.removeChild(removeEle);
    }
    else if(e.target && e.target.value === "Add"){
        let ele = document.getElementsByClassName("hidden")[0];
        console.log("add");
        resultCont.appendChild(ele.cloneNode(true));
    }
});

And here’s the relevant part of my HTML:

<div class="form-cont experience-cont accordion-cont">
    <div class="static-form-cont">
        <div class="title-cont"><span class="text">Experience</span></div>
        <div class="accordion-btn"><img src="../arrow-down-sign-to-navigate.png" alt="arrown btn"></div>
    </div>
    <label><input type="submit" value="Add" id="experienceBtn"></label>
    <div class="experience-result" id="experienceResult">
        <div class="hidden">
            <div class="static-form-cont">
                <div class="garbage-btn"><img src="../trash.png" alt="delete btn"></div>
                <div class="title-cont"><span class="text"></span></div>
                <div class="accordion-btn"><img src="../arrow-down-sign-to-navigate.png" alt="arrown btn"></div>
            </div>
            <!-- More HTML here... -->
        </div>
    </div>
</div>

The problem is that the “garbage-btn” click event is not working as expected. When I click a “garbage-btn”, I expect its grandparent element to be removed from the DOM, but this is not happening. There are no error messages in the console, and I’ve confirmed that the event listener is being triggered when a “garbage-btn” is clicked.

I’ve tried using both removeChild() and remove() to remove the element, but neither is working. I’ve also tried attaching the event listener to different elements and using different methods to select the element to be removed, but nothing has solved the issue.

Does anyone know what could be causing this issue and how I can fix it?

Issue with export xls file from api to js

I get set of characters instead of real data in the response. But when I click Download file in swagger, everything works fine. Help me to find the problem

function downloadDocFile(data: Blob, ext = 'xlsx', name = 'Export'): void {
  const downloadUrl = window.URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.href = downloadUrl
  link.setAttribute('download', `${name}-${DateTime.now().toLocaleString()}.${ext}`)
  document.body.appendChild(link)
  link.click()
  link.remove()
}

const loading = useLoading()
function handleExport() {
  loading.show()
  const url = `/bill-of-material/${bomItems.value[0]?.billOfMaterialId}/available-kits/export-xls`
    
  getApiInstance('kitting')
    .post(url, { responseType: 'blob' })
    .then((data: any) => {
      if (data) {
        downloadDocFile(data)
      }
      loading.hide()
    })
}

Please see screenshots:
Responce Image
Swagger Image

I tried changing the downloadDocFile and handleExport functions, but nothing worked.