Awaiting dynamic import makes JS application exit without any error

I’m writing some code that should load all modules inside a folder.

for (let path of controllerPaths) {
    path = path.replaceAll("\", "/"); // Replace windows path backslashes

    const controller: ApiController = (await import(`file:///${path}`))?.default; // Application exits without any error

    // ...
}

Wrapping the code in a try/catch block doesn’t change the result as the application still exits.

I’m sure the path is correct and exists. The path is absolute.

Error calling Office.context.mailbox.item.body.getTypeAsync when reading an Outlook message

I’m creating my first Outlook Web Add-in app. When I’m calling Office.context.mailbox.item.body.getTypeAsync when viewing an email in Outlook, I get the error message “Uncaught
TypeError: Office.context.mailbox.item.body.getTypeAsync is not a function”:

(function () {
    Office.onReady(function () {
        Office.context.mailbox.item.body.getTypeAsync((typeResult) => {
            if (typeResult.status === Office.AsyncResultStatus.Succeeded) {
                const coercionType = typeResult.value;

                Office.context.mailbox.item.body.getAsync(coercionType, (getResult) => {
                    if (getResult.status === Office.AsyncResultStatus.Succeeded) {
                        // Do something with getResult.value - message body content.
                    }
                    else {
                        console.log(getResult.error.message);
                    }
                });
            }
            else {
                console.log(typeResult.error.message);
            }
        });
    });
})();

If I separate out the code and call Office.context.mailbox.item.body.getAsync with a hard coded coercion type (Office.CoercionType.Html or Office.CoercionType.Text), getAsync works as expected. But getTypeAsync is not available on Office.context.mailbox.item.body as a function, with getAsync being the sole function on Office.context.mailbox.item.body when reading the message in Outlook web and inspecting using dev tools. This seems unusual, as other functions should be available on Office.context.mailbox.item.body as indicated by the Office.js documentation.

What could be causing the problem, and how do I fix it so that I can call getTypeAsync correctly? I am using the live Office.js framework from Microsoft, so that should include all of the latest functionality. Is it likely to be an issue with the manifest file, or an issue of getting the Office.js framework from Microsoft?

Here is part of the header in my MessageRead.html base file with reference to my JavaScript files, including the Office.js framework:

<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="MessageRead.js" type="module"></script>

Can someone explain why this piece of code only return status 400? [closed]

Help me please

 async updateCategory(req) {
  const {id} = req.params;
  try {
    let category = await Category.findByPk(id);


    if (!req.body || !req.body.name || !req.body.slug || (req.body.use_in_menu != undefined && req.body.use_in_menu != null)) {
      return {
        status: 400,
        message: "Dados invalidos."
      }
    }

    if (!category) {
      return {
        status: 404,
        message: "Categoria não encontrada."
      }
    }

    await category.update(req.body)
    return {
      status: 204,
      message: ""
    }
  } catch (error) {
    return {
      status: 500,
      message: "Erro do servidor"
    }
  }
}

Is expected to return message 204 when i send a new payload, but it only return “400 invalid data”.

i am using createBrowserRouter i got Cannot destructure property ‘basename’ of ‘react__WEBPACK_IMPORTED_MODULE_0__.useContext(…)’ as it is null

i got this error in react = index.tsx:963 Uncaught TypeError: Cannot destructure property ‘basename’ of ‘react__WEBPACK_IMPORTED_MODULE_0__.useContext(…)’ as it is null.

In the code below, I am trying to pass the query entered by the user in the search bar from the header component to another component using props, as shown below.

in head.js i have this code

<Link to="/results">
          < SearchVideo results={searchResult} loading={loading} />
        </Link>

this is my app.js

const appRouter = createBrowserRouter([{
  path: "/",
  element: <Body />,
  children: [
    {
      path: "/",
      element: <MainContainer />,
    },
    {
      path: "watch",
      element: <WatchPage />,
    },
    {
      path: "results",
      element: <SearchVideo />,
    },
  ],
}]);

function App() {
  return (  
    <Provider store={store}>
      <div className="bg-black ">
        <Head />
        <RouterProvider router={appRouter}/>
      </div>
    </Provider>
  );
}

export default App;

this is my index.js

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
);

i have one reactapp which have bug so want solution

Fabric.js – How do I scale canvas to screen size and save full size image from the canvas

I’m using Fabric.js 5.3.1 in a website where users can upload a photo and mark them up. Everything seems to be working however when I set the uploaded image to the background of the canvas and scale it to fit the screen, then save that image, the image is the same size as its scaled dimensions. Meaning if I upload a 1920×1080 image, set it to the canvas’ background image, then scale the canvas down to screen size (say 600×337.5) then save the image using canvas.toDataUrl() my saved image is 600×337.5.

This is how I set the canvas’ background image:

setCanvasBackground: function (imgUrl) {
    let bgImg = new Image();
    bgImg.onload = function () {
        origBgWidth = bgImg.width; // global variable
        origBgHeight = bgImg.height; // global variable

        canvas.setDimensions({
            width: bgImg.width,
            height: bgImg.height
        });

        canvas.setBackgroundImage(imgUrl, function () {
            canvas.requestRenderAll();
            canvas.clearContext(canvas.contextTop);
            canvas.setZoom(1);

            undo_history.push(JSON.stringify(canvas)); // global variable
        });
    }

    bgImg.src = imgUrl;
}

Then I scale the canvas to screen dimensions like so:

resizeCanvas: function (areaWidth, areaHeight) {

    let canvasWidth = canvas.getWidth();
    let canvasHeight = canvas.getHeight();

    const wRatio = areaWidth / canvasWidth;
    const hRatio = areaHeight / canvasHeight;
    const scale = Math.min(wRatio, hRatio);

    const newWidth = canvasWidth * scale;
    const newHeight = canvasHeight * scale;
    const zoom = canvas.getZoom() * scale;

    canvas.setDimensions({ width: newWidth, height: newHeight });
    canvas.setZoom(zoom);
    canvas.requestRenderAll();
}

Finally, I save the image by converting it to a blob and uploading:

getImageBlobFromCanvas: function () {
    // I have to set the original dimensions and zoom level for it to save full size
    canvas.setDimensions({
        width: origBgWidth,
        height: origBgHeight
    });
    canvas.setZoom(1);

    let imageData = canvas.toDataURL({ format: "png" });
    return convertBase64ToBlob(imageData);
}

Is there a way to more efficiently scale and save the canvas image without having to store the original dimensions and reset them back before calling canvas.toDataUrl()? I want to scale the canvas for a responsive design but when uploading the image, it needs to be its original size. Using canvas.setDimensions() and canvas.setZoom() just before saving seems hacky.

How to use Web Sockets in my Book Store proj [closed]

This is my CSharp prog, this project is about a Book Store but I attached screenshot of the serverside only.
screenshot of my classes
I want to add web sockets to my project, I dont even know how to start.
https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket?view=net-8.0
I tried to look at this but cant understand how to begin.

In addition,I created a chat that I want to add to it socket funcion to pull from the server detailes and display it inside the chat.
I hope someone can guide me throgh it and help!
Thank you!
Dan

Issue with FormSubmission [duplicate]

I have the following code which does the form submission and everything works well, until i have a textarea with tinymce attached to it, it does not send any data to the server, not sure what is wrong

ig i use normal textarea the data is sent and saved in the database, but only seems to be a trouble with the editor based textarea

var formSubmission = document.getElementById('formSubmission'); 

if(formSubmission) {
  $("#formSubmission").validate({
    errorPlacement: function(error, element) {
      error.appendTo(element.parent());
    },
    highlight: function(element) {
      $(element).addClass("error");
    },
    unhighlight: function(element) {
      $(element).removeClass("error");
    },
    submitHandler: function(form) { 
      var $form    = $(form),
          formData = new FormData(),
          params   = $form.serializeArray();

        var filesInput = $form.find('[name="uploadfile"]');
        if (filesInput.length > 0 && filesInput[0].files.length > 0) {
            var files = filesInput[0].files;
            $.each(files, function(i, file) {
                formData.append('uploadedFiles', file);
            });
        }

        $.each(params, function(i, val) {
            formData.append(val.name, val.value);
        });

        // Block UI and show processing message
        $.blockUI({ 
            message: '<h3>Please wait, we are running some background processes to make it work...</h3>',
            css: { 
                border: 'none', 
                padding: '15px', 
                backgroundColor: '#000', 
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px', 
                opacity: .5, 
                color: '#fff' 
            } 
        });
        $.ajax({
          url:'process.cfm?action=' + $('#formSubmission').attr('data-post'),
          data: formData,
          mimeType: "multipart/form-data",
          contentType: false,
          processData: false,
          type:'POST',
          dataType: 'json',
          success: function(data) {
            // Unblock UI
            $.unblockUI();
            var json = data;
            if((json.SUCCESS === true) || (json.valid === true) || (json.sucess === true)) {
              showAlert(json.message, 'success', 1);
            } else {
              showAlert(json.message, 'error');
            }
          },
          error: function(textStatus, errorThrown) {
            // Unblock UI
            $.unblockUI();

            showAlert('An error occurred during the operation: ' + textStatus, 'error');
          }
        });
        return false;
    }
  });
}

How to decode Google CloudEvent data?

I have a Google Cloud Function that is triggered when a document is written in my Firestore.

functions.cloudEvent('onItemCreate', async (cloudEvent: functions.CloudEvent<any>) => {
    console.log("cloudEvent.data", typeof cloudEvent.data, cloudEvent.data)
    const decodedData = cloudEvent.data.toString('utf8');
    console.log("Decoded Data:", decodedData);
}

// > cloudEvent.data object <Buffer 0a 9e 03 0a 7f 70 72 6f 6a 65 63 74 73 2f 65 69 6e 73 6b 35 67 2d 69 6d 2d 64 65 76 2f 64 61 74 61 62 61 73 65 73 2f 66 69 72 65 73 74 6f 72 65 2d 69 ... 367 more bytes>
// > Decoded Data: 
// �
// oprojects/my-project-id/databases/firestore/my-firestore/documents/items/Rfhg7PU9Rb1i55VNPzxH   
// a�a��������"��������

How do I correctly decode the data as there are some weird characters with my current approach?

Getting ‘token’ undefined in api.js when registering a user through the front end

Undefined token, or token is null at api.js, none of the console.logs are triggered. so unsure how to troubleshoot at this point. chatGPT no help.

api.js

import { fetchBaseQuery, createApi } from "@reduxjs/toolkit/query/react";

export const api = createApi({
  reducerPath: "api",
  baseQuery: fetchBaseQuery({
    // baseUrl: "https://capstonebackend-0wah.onrender.com/",
    baseUrl: "http://localhost:3000",
    tagTypes: ["User"],

    prepareHeaders: (headers, { getState }) => {
      const token = getState().register.token || getState().login.token;
      const sessionToken = window.sessionStorage.getItem("Token", token);
      if (token || sessionToken) {
        headers.set("authorization", `Bearer ${token || sessionToken}`);
      }
    },
  }),
  endpoints: () => ({}),
});

registerSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { api } from "../../app/api";

const registerApi = api.injectEndpoints({
  endpoints: (builder) => ({
    register: builder.mutation({
      query: (credentials) => ({
        url: "/register",
        method: "POST",
        body: credentials,
        responseHandler: (response) => response.text(),
      }),
      invalidateTags: ["User"],
    }),
  }),
});

const registerSlice = createSlice({
  name: "register",
  initialState: {
    user: {},
    token: null,
  },
  reducers: {
    setUser: (state, action) => {
      console.log("Setting user in login:", action.payload);
      state.user = action.payload;
    },
  },

  extraReducers: (builder) => {
    builder.addMatcher(
      registerApi.endpoints.register.matchFulfilled,
      (state, { payload }) => {
        console.log(payload);
        const temp = JSON.parse(payload);
        console.log(temp);
        state.token = temp.token;
        // state.user = temp;
        // state.id = temp.id;
        // window.sessionStorage.setItem("Token", temp.token);
        // window.sessionStorage.setItem("User", temp.id);
      }
    );
  },
});

export default registerSlice.reducer;

export const { useRegisterMutation } = registerApi;

export const {  setUser } = registerSlice.actions;


Whenever I submit a registerUser request through the frontend it is getting token undefined. I put breakpoints in and found it is undefined in the api.js. It doesn’t seem like it is even triggering the registerSlice. Tested the backend in Postman and it can register a user and get a token just fine. How can I fix this to get the token to be passed correctly?

How do I get my inline editing Vue component to update the value after editing?

I’m working on a simple inline editing component for a project, and have it mostly working, except that once the edit happens, the bound variable doesn’t update the way I’d like it.

The basic approach is that I have a table cell that just has the variable text, and then on double-click I swap in an input field populated with the text value.

Why is the computedCellValue not getting the updated value of the input when it gets edited?

<script setup>
    import { defineProps, ref, computed, nextTick } from 'vue';

    const props = defineProps([
        "cellValue",
        "prefix",
        "postfix"
    ]);

    const isEditing = ref(false);
    const inputField = ref(null);
    const computedCellValue = computed(() => props.cellValue);

    function toggleEditOn() {
        isEditing.value = true;

        nextTick(function () {
            inputField.value.focus();
            inputField.value.select();
        });
    }

    function toggleEditOff() {
        isEditing.value = false;
    }
</script>

<template>
    <td class="w-64 mx-1" @dblclick="toggleEditOn()" v-show="isEditing == false">
        {{ props.prefix }}{{ computedCellValue }}{{ props.postfix }}
    </td>
    <td class="w-64 mx-1" v-show="isEditing == true">
        {{ props.prefix }}<input class="w-64 bg-slate-400 p-1 text-white" ref="inputField" type="text" :value="computedCellValue"  @blur="toggleEditOff()" @focus="focused" @keyup.enter="toggleEditOff()">{{ props.postfix }}
    </td>
</template>

How to Query Multiple Media Items by MyAnimeList IDs Using Anilist’s GraphQL API?

I’m working with a Anilist’s GraphQL API where the Media query supports fetching media by a single ID. The schema for the Media query looks like this:

query Media($idMal: Int!) {
  Media(idMal: $idMal) {
    ...media
  }
}

// idMal = [21, 166531]

However, I need to fetch multiple media items at once using an array of MyAnimeList (MAL) IDs. The API does not provide a query that allows fetching multiple items by an array of IDs in a single request.

I expected to efficiently fetch multiple media items using a single request or a more streamlined approach than making multiple separate requests.

Any help or suggestions would be greatly appreciated!

Registering Javascript file Blazor

I have a scenario where I want to register a javascript file insidemy blazor appplication.

Any suggestion how we can fix this issue. Any help is appreciated.

Thank you in advance.

I have placed the file as shown in the below image
enter image description here

I have used the script tag inside one of the razor component as shown below.
enter image description here

But I am getting the below error when I am using script tag to register Javascript.
enter image description here

While using JSRuntime am not getting any error by the javascript is not executing and is also not present while checking the page source.

I have also tried to place the script tag in the App.Razor a file where _blazor.web.js file is present. Again not getting the error but the JS file is not executing but it is present while viewing the page source.

If I remove the _blazor.web.js then the javascript file runs fine but blazor application is not working as it blazor.web.js is required other components.

Issue: JSObjectGetPrototype Returns the Same JSValueRef for Different Classes

In JavaScriptCore, when creating and manipulating classes and prototypes, the JSObjectGetPrototype function is used to retrieve the prototype of an object.

Problem:
I’ve encountered a situation where JSObjectGetPrototype always returns the same JSValueRef for different classes, even though I am creating distinct prototypes for each class.

  • I create multiple classes, each with its own unique prototype.
  • When I use JSObjectGetPrototype to retrieve the prototype of different instances, I receive the same JSValueRef for all of them, suggesting that the prototype is not unique as expected.

What I Tried:

  1. Creating Unique Prototypes:

    • I used JSObjectMake to create new objects as prototypes for different classes.
    • I then called JSObjectSetPrototype to set these prototypes for the respective constructors.
  2. Retrieving and Logging Prototypes:

    • I used JSObjectGetPrototype to retrieve the prototype for each class instance.
    • I logged the addresses of the prototypes to verify their uniqueness.
  3. Logging and Comparison:

    • I compared the addresses of the prototypes retrieved for different classes to check if they were unique.

What I Expected:

  1. Unique Prototypes:

    • I expected that each class would have its own unique prototype.
    • The addresses retrieved by JSObjectGetPrototype for different classes should be distinct.
  2. Access to Methods:

    • I anticipated that methods added to the prototypes would be accessible when interacting with instances of these classes.

Outcome:

  • Despite setting different prototypes for each class, JSObjectGetPrototype returned the same JSValueRef for all classes.
  • This suggests that the prototypes are not being set or managed correctly, resulting in all classes sharing the same prototype.

Questions:

  1. Is there a known issue or limitation with JSObjectGetPrototype returning the same value for all classes?
  2. How can I ensure that prototypes are correctly assigned and are unique for each class?
  3. Are there any additional steps or considerations to manage prototypes effectively in JavaScriptCore?

Fullcalendar show modal from url

I’m using Fullcalendar and everything is working fine, I have a weekly calendar with events and when I click on an event than a modal shows with more information about this event.

Let say I show this calendar from the url https://test.com/fullcalendar.php

I want to add some extra functions to this so that the modal of the event with ID 123 is showing when I go the to url https://test.com/fullcalendar.php?id=123, thus without clicking on the event in the calendar.

Is this possible?

One user cannot create subscription inside topic in Azure Service Bus (JavaScript)

One user of my aplication that should create subscription in a specific topic is unable to do so (all of the others can). User is getting error with the following content:

<Error>
<Code>400</Code>
<Detail>The specified resource description is invalid.
 TrackingId:1e75e58c-e002-4092-b9e5-2d00c702d785_G12, 
 SystemTracker:*name of my service bus*:Topic:*name of my topic*, 
 Timestamp:2024-08-16T08:05:54
</Detail>
</Error>

The code that is working successfully for everybody else but for this user is the following:

this._sbAdminClient.createSubscription(
                        `myApp-${user}`,
                        azureSubscriptionId,
                        {
                            autoDeleteOnIdle: 'PT1H',
                        }
                    )

Just to be clear, if I check Azure portal, the topic exists and if I manually create subscription, then receiver works fine.