get rid of FormData in Next.JS backend

I simply would like to repeat this guide: https://medium.com/@_hanglucas/file-upload-in-next-js-app-router-13-4-6d24f2e3d00f for uploading files using Next.js, but the line const formData = await req.formData(); throws error, it says Error [TypeError]: req.formData is not a function, although autocomplete of Visual Studio Code displays, that such method exists (method) Body.formData(): Promise<FormData> and there is no error.

Since this is the TypeError, I updated next, react, typescript and @types related to it to @latest, but still have this error.

Any ideas why is it so? Maybe there is another @types I must install?

Versions:

“next”: “^13.4.4”,
“react”: “^18.2.0”,
“react-dom”: “^18.2.0”,
“typescript”: “^5.1.3”,
“@types/node”: “^20.2.5”,
“@types/react”: “^18.2.8”,
“@types/react-dom”: “^18.2.4”

Sending and receiving data from Date Picker MUI

I ran into a problem: when I use 2 DatePickers. It works as follows: Starting to fix the first cell with a datepicker (ddatebegin), the data is successfully changed using a patch request, getting new values. The second datepicker (dataend) and other fields in the patch request are simply duplicated from the props. However, the problem starts if you change the first datepicker in turn, and then the second one (or vice versa). This happens because during the second patch request, the previous modified date field is overwritten with the old value. Thus, the first modified datepicker again receives the previously received old value from the server. For some reason, after updating one of the datepickers, the hook does not save the new value, but is overwritten each time with the old one of the props. Individually changing each datepicker works well. How can I fix this? Thank you

export const MyDatePicker = (props: any) => {

    let [databe, setDatabe] = useState(props.params.ddatebegin) //HOOKS
    let [dataen, setDataen] = useState(props.params.ddateend)

    const handleChange =  async (newValue: any, flag: any, params: any) =>  {

       let ddateb3 = props.params.ddatebegin
       let ddatee3 = props.params.ddateend

        if (flag === 'dbegin') {
            let ddateb = props.params.ddatebegin //init Date
            if (ddateb !== null) {
                let ddateb2 = moment(newValue.$d).format('DD-MM-YYYY')
                    ddateb3 = ddateb2
                    setDatabe(ddateb3) //this should update the hook to use this state in another Datepicker
                    ddatee3 = params.ddateend 
            }

             let response = await axios.patch('http://10.3.6.124:3003/api/post/upd/stage', { 
                id: props.params.id, 
                id_dk: props.params.id_dk,  
                bdone: props.params.bdone, 
                ddatebegin:ddateb3, //current value from Datagrid's renderCell 
                ddateend: dataen, //HOOK state
                sotv: props.params.sotv, 
                npp: props.params.npp, 
                description: props.params.description }) 
                

    }
        
        else if (flag === 'dend') {
            let ddatee = props.params.ddateend //init Date
            if (ddatee !== null) { //если в бд имеется дата начала
                let ddatee2 = moment(newValue.$d).format('DD-MM-YYYY') //current Value dateend
                    ddatee3 = ddatee2 
                    setDataen(ddatee3) //this should update the hook to use this state in another Datepicker
                    ddateb3 = params.ddatebegin
            }


             let response = await axios.patch('http://10.3.6.124:3003/api/post/upd/stage', { 
                id: props.params.id, 
                id_dk: props.params.id_dk,  
                bdone: props.params.bdone, 
                ddatebegin: databe, //HOOK state
                ddateend: ddatee3, //current value from Datagrid's renderCell 
                sotv: props.params.sotv, 
                npp: props.params.npp, 
                description: props.params.description })
    }


    return (
        <LocalizationProvider dateAdapter={AdapterDayjs}>
                  <DatePicker onChange={(newValue) => {handleChange(newValue, props.flag, props.params)}} 
                              format='DD/MM/YYYY' 
                              value={dayjs(  
                                    (props.flag==='dbegin' && props.params.ddatebegin) || 
                                    (props.flag==='dend' && props.params.ddateend)  
                                    )}
                             
                  />        
                </LocalizationProvider>

    ) 
}

i tried to use hooks, but they are overwritten and become with old values again. I tried to take values from props.params.ddatebegin (and ddataend) from rendercell, but they also come not updated. I tried to use the global state and dispatch updates, it seems to be a working option, but each time you enter a day, month, or year into the datepicker, the field selection is reset, since the state is updated, and the table depends on the same state and it is also updated accordingly. the moment you enter each value.

Editable ReactJS MUI Datagrid component showing Uncaught TypeError

I am using React Data Table component from MUI (material UI) but i need to customize it such that i can create a marksheet.

The error is as follows: Uncaught TypeError: Cannot read properties of undefined (reading ‘type’) at GridRow.js:180:1 at HTMLUnknownElement.callCallback (react-dom.development.js:3733:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:3777:1) at invokeGuardedCallback (react-dom.development.js:3834:1) at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:3848:1) at executeDispatch (react-dom.development.js:7992:1) at processDispatchQueueItemsInOrder (react-dom.development.js:8018:1) at processDispatchQueue (react-dom.development.js:8029:1) at dispatchEventsForPlugins (react-dom.development.js:8038:1) at react-dom.development.js:8198:1 at batchedUpdates$1 (react-dom.development.js:22595:1) at batchedUpdates (react-dom.development.js:3581:1) at dispatchEventForPluginEventSystem (react-dom.development.js:8197:1) at dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay (react-dom.development.js:5703:1) at dispatchEvent (react-dom.development.js:5697:1) at dispatchDiscreteEvent (react-dom.development.js:5674:1) it shows the following error

I have tried the following updating all dependencies.
I have tried runnning it on sandbox and stackblitz with same dependecies but the error does show up there.

Following is the output
Here is the code: Please help
text

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';

const columns = [
    { field: 'id', headerName: 'ID', width: 60,},

    { field: 'subject', 
    headerName: 'Subject',
    width: 180, 
    editable: true, },

    { field: 'mark',
    headerName: 'Marks (Out of 100)',
    editable: true,},
];

const rows = [
    {
        id: 1,
        subject: "Subject 1",
        mark: 0,
    },
    {
        id: 2,
        subject: "Subject 2",
        mark: 0,
    },
    {
        id: 3,
        subject: "Subject 3",
        mark: 0,
    },
    {
        id: 4,
        subject: "Subject 4",
        mark: 0,
    },
    {
        id: 5,
        subject: "Subject 5",
        mark: 0,
    },
    {
        id: 6,
        subject: "Subject 6",
        mark: 0,
    },
    {
        id: 7,
        subject: "Subject 7",
        mark: 0,
    },
    {
        id: 8,
        subject: "Subject 8",
        mark: 0,
    }
];
export default function AddResult(props) {

    const handleCellEditCommit = React.useCallback((params) => {
    const { id, field, value } = params;
    const updatedRows = rows.map((row) => {
        if (row.id === id) {
            return { ...row, [field]: value };
        }
            return row;
        });
        console.log('Updated Rows:', updatedRows);
    }, []);
    

    return (
    <>
        <form>
            <label htmlFor='resultTitle'> Add Result Title</label>
            <input type='text' id='resultTitle' />

            <label htmlFor='remarks'> Add Remarks</label>
            <input type='text' id='remarks' />
        </form>

        <div style={{ height: 500, width: '100%' }}> 
        <DataGrid 
            rows={rows} columns={columns} 
            onCellEditCommit={handleCellEditCommit}
            hideFooter
            />
        </div>

        <div>
            <h3>Total</h3>
            <h3>100</h3>
            <h3>Percentage</h3>
            <h3>Total</h3>
        </div>
    </>
    );
    }


Websocket issue in Python Django

The console shows that the websocket is connected in the inbox, but the real-time notification is not received

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from .models import ChatRoom, Message, Notification
from django.contrib.auth import get_user_model
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        formatted_timestamp = await self.save_message(message)

        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'sender': self.scope['user'].username,
                'formatted_timestamp': formatted_timestamp,
            }
        )

    async def chat_message(self, event):
        message = event['message']
        sender = event['sender']
        formatted_timestamp = event['formatted_timestamp']

        await self.send(text_data=json.dumps({
            'message': message,
            'sender': sender,
            'formatted_timestamp': formatted_timestamp,
        }))

    @database_sync_to_async
    def save_message(self, message):
        chat_room = ChatRoom.objects.get(name=self.room_name)
        sender = self.scope['user']

        new_message = Message(chat_room=chat_room, sender=sender, content=message)
        new_message.save()

        formatted_timestamp = new_message.formatted_timestamp()

        participants = chat_room.participants.exclude(id=sender.id)
        for participant in participants:
            notification = Notification(user=participant, chat_room=chat_room, message=new_message)
            notification.save()

        return formatted_timestamp

    @database_sync_to_async
    def get_or_create_room(self, user_ids):
        users = get_user_model().objects.filter(id__in=user_ids)
        chat_room = ChatRoom.get_or_create_chat_room(users)
        return chat_room


class NotificationConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        print("NotificationConsumer Connected")
        print('connected')
        print(self.scope['user'].username)
        self.room_group_name = '%s_notifications' % self.scope['user'].username
        print(self.room_group_name)
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        print(text_data_json)
        message = text_data_json['message']
        formatted_timestamp = await self.save_message(message)
        room_name = text_data_json['room_name']

        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_notification',
                'message': message,
                'sender': self.scope['user'].username,
                'formatted_timestamp': formatted_timestamp,
                'room_name': room_name,
            }
        )

    async def chat_notification(self, event):
        message = event['message']
        sender = event['sender']
        formatted_timestamp = event['formatted_timestamp']
        room_name = event['room_name']

        await self.send(text_data=json.dumps({
            'message': message,
            'sender': sender,
            'formatted_timestamp': formatted_timestamp,
            'room_name': room_name,
        }))

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer.as_asgi()),
    re_path(r'ws/chat/inbox/$', consumers.NotificationConsumer.as_asgi()),
]

{% extends "base.html" %}
{% load static %}

{% block head %}
<link rel="stylesheet" href="{% static 'css/chat/inbox.css' %}">
{% endblock head %}

{% block content %}
<section>
  <a href="{% url 'chat:start_chat' user.id %}"><h2>나와의 채팅하기</h2></a>
  <h2>사용자 목록</h2>
  <form method="post" action="{% url 'chat:start_group_chat' %}">
    {% csrf_token %}
    {% for user in all_users %}
      <input type="checkbox" name="user_ids" value="{{ user.id }}"> {{ user.username }}
    {% empty %}
      <p>다른 사용자가 없습니다.</p>
    {% endfor %}
    <input type="submit" value="채팅방 만들기">
  </form>
</section>
<section id="chat-rooms-section">
  {% if chat_rooms %}
    {% for chat_room, last_message, unread_notifications in chat_rooms %}
      <div class="chat_room" id="{{ chat_room.name }}">
        <a href="{% url 'chat:room' chat_room.name %}" style="margin-right: 0.5rem;">{{ chat_room }}</a>
        {% if unread_notifications > 0 %}
          <p class="notification" style="color: red">!</p>
        {% endif %}
        {% if last_message %}
          <p class="last-message">{{ last_message.content }}</p>
          <p class="last-message">{{ last_message.formatted_timestamp }}</p>
        {% else %}
          <p class="last-message">메시지 없음</p>
          <p class="timestamp"></p>
        {% endif %}
        <form action="{% url 'chat:delete_chat' room_name=chat_room.name %}" method="post">
          {% csrf_token %}
          <input type="submit" value="삭제">
        </form>
      </div>
    {% endfor %}
  {% else %}
    <p>채팅방이 없습니다.</p>
  {% endif %}
</section>
{% endblock content %}

{% block script %}
<script>
  document.addEventListener('DOMContentLoaded', () => {
    let loc = window.location;
    let wsStart = 'ws://';
    if (loc.protocol == 'https:') {
      wsStart = 'wss://';
    }

    const notificationSocket = new WebSocket(
      wsStart + window.location.host + '/ws/chat/inbox/'
    );
    console.log(notificationSocket)

    notificationSocket.onopen = function (event) {
      console.log('WebSocket connection established.');
    };

    notificationSocket.onmessage = function (event) {
      console.log(event.data)
      const messageData = JSON.parse(event.data);
      console.log('Received notification:', messageData);
      updateNotificationCount(messageData.room_name);
      updateChatRooms(messageData);
    };

    notificationSocket.onclose = function (event) {
      console.log('WebSocket connection closed.');
    };

    notificationSocket.onerror = function (event) {
      console.error('WebSocket error:', event);
    };

    function updateNotificationCount(room_name) {
      const chatRoomElement = document.getElementById(room_name);
      const notificationElement = chatRoomElement.querySelector('.notification');
      
      if (notificationElement) {
        notificationElement.style.display = 'block';
      }
    }

    function updateChatRooms(messageData) {
      const chatRoomElement = document.getElementById(messageData.room_name);
  
      if (chatRoomElement) {
        const lastMessageElement = chatRoomElement.querySelector('.last-message');
        const timestampElement = chatRoomElement.querySelector('.timestamp');
  
        if (lastMessageElement && timestampElement) {
          lastMessageElement.textContent = messageData.message;
          timestampElement.textContent = messageData.formatted_timestamp;
        }
      }
    }
  });
</script>
{% endblock script %}
{% extends 'base.html' %}
{% load static %}

{% block head %}
<link rel="stylesheet" href="{% static 'css/chat/room.css' %}">
{% endblock head %}

{% block content %}

{{ room_name|json_script:"room-name" }}
  <div id="chat-room">
    {% for message in messages %}
      <div class="message">
        <p>{{ message.sender.username }}: {{ message.content }}</p>
        <p>{{ message.formatted_timestamp }}</p>
      </div>
    {% empty %}
      <p>No messages yet.</p>
    {% endfor %}
  </div>

  <form id="text_form" class="text-form">
    <input type="text" id="message_input" name="message" placeholder="Type your message">
    <button type="submit">Send</button>
  </form>
{% endblock %}

{% block script %}
<script>

  document.addEventListener('DOMContentLoaded', () => {
    const roomName = JSON.parse(document.getElementById('room-name').textContent);

    let loc = window.location;
    let wsStart = 'ws://';
    if (loc.protocol == 'https:') {
      wsStart = 'wss://';
    }

    const chatSocket = new WebSocket(
      wsStart + window.location.host + '/ws/chat/' + roomName + '/'
    );

    chatSocket.onopen = function (event) {
      console.log('WebSocket connection established.');
    };
  
    chatSocket.onmessage = function (event) {
      const message = JSON.parse(event.data);
      console.log('Received message:', message);
      displayMessage({
        sender: message.sender,
        content: message.message,
        formatted_timestamp: message.formatted_timestamp,
      });
    };


    chatSocket.onclose = function (event) {
      console.log('WebSocket connection closed.');
    };

    chatSocket.onerror = function (event) {
      console.error('WebSocket error:', event);
    };
  
    const form = document.getElementById('text_form');
    const messageInput = document.getElementById('message_input');
  
    form.addEventListener('submit', function (event) {
      event.preventDefault();
      const message = messageInput.value.trim();
      if (message !== '') {
        const messageData = {
          'message': message
        };
        chatSocket.send(JSON.stringify(messageData));
        messageInput.value = '';
      }
    });
  
    function displayMessage(message) {
      const chatRoom = document.getElementById('chat-room');
      const messageElement = document.createElement('div');
      messageElement.classList.add('message');
      
      const content = document.createElement('p');
      content.textContent = `${message.sender}: ${message.content}`;
      messageElement.appendChild(content);

      const timestamp = document.createElement('p');
      timestamp.textContent = message.formatted_timestamp;
      messageElement.appendChild(timestamp);

      chatRoom.appendChild(messageElement);
    }
  });
</script>
{% endblock script %}

Consumers have also been modified, and all related codes have been looked at, but it is impossible to figure out what the problem is. It seems that connect function is not executed in NotificationConsumer.

I have an error showing a fullcalendar inside a modal

hi im trying to set a fullcalendar inside a bootstrap modal but it shows itself comprimed at the top-left corner and i cant see anything, but when i resize the screen it changes and shows perfect, and i dont know why, i also tried doing it outside of the modal and it works perfects, do any of you have a hint about the problem?

before resize
after rsize

 <div class="modal fade" id="calendarModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Holidays</h5>
                        <button type="button" class="btn btn-secondary" id="closeCalendarModal">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div id="calendar"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
$(document).ready(function() {

            var token = $('meta[name="csrf-token"]').attr('content');
            $(".calendarmodal").click(function(e) {
                e.preventDefault();

                var calendarEl = document.getElementById('calendar');
                var calendar = new FullCalendar.Calendar(calendarEl, {
                    initialView: 'dayGridMonth'
                });
                calendar.setOption('locale', 'es');
                calendar.render();

                $("#calendarModal").modal("toggle");

            });
});
#calendarModal .modal-dialog {
            max-width: 70%;
            /* Ajusta el ancho máximo según tus necesidades */
        }

        #calendarModal .modal-content {
            width: 100%;
            height: 100%;
            max-height: 80vh;
            /* Ajusta la altura máxima según tus necesidades */
        }

i tried putting outside and inside the modal, applied css styles and initializing with javascript and jquery

I am not able to export useHistory in reactjs [duplicate]

I have imported useHistory as follows.
import { useHistory } from ‘react-router-dom’;

used it properly
const history = useHistory();

But when I am trying this on my react component. I am getting an error, can someone help me in this.
<StyledHeader onClick={()=>history.push(“/”)}>Crypto Tracker

This is the error message
export ‘useHistory’ (imported as ‘useHistory’) was not found in ‘react-router-dom’ (possible exports: AbortedDeferredError, Await, BrowserRouter, Form, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, createSearchParams, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_HistoryRouter, unstable_useBlocker, unstable_usePrompt, useActionData, useAsyncError, useAsyncValue, useBeforeUnload, useFetcher, useFetchers, useFormAction, useHref, useInRouterContext, useLinkClickHandler, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, useSearchParams, useSubmit)

Also I have latest react-router-dom in package.json
“react-router-dom”: “^6.11.2”,

Does someone have solution of this problem

How to fix this bug modals? | Discord.js v14

I have an error: TypeError: Cannot read properties of undefined (reading 'getTextInputValue') and I don’t know how to solve it… (Discord.js v14)
I have already tested many changes in code.
Please help me.

Code:

        if (interaction.customId === 'wyglad2') {
          const modal = new ModalBuilder()
          .setCustomId('myModal1')
          .setTitle('Pożegnania wygląd');
        
          const fields = {
            tytul: new TextInputBuilder()
              .setCustomId('tytul')
              .setLabel("Tytuł pożegnania")
              .setPlaceholder('Napisz tytuł pożegnania!')
              .setStyle(TextInputStyle.Short)
              .setRequired(false),
            tresc: new TextInputBuilder()
              .setCustomId('tresc')
              .setLabel("Treść pożegnania")
              .setPlaceholder('Wpisz treść pożegnania!')
              .setStyle(TextInputStyle.Paragraph)
              .setRequired(true),
            footer: new TextInputBuilder()
              .setCustomId('footer')
              .setLabel("Stopka pożegnania")
              .setPlaceholder('Wpisz treść pożegnania!')
              .setStyle(TextInputStyle.Short)
              .setRequired(false)
          }
        const tytul1 = new ActionRowBuilder().addComponents(fields.tytul);
        const tresc1 = new ActionRowBuilder().addComponents(fields.tresc);
        const footer1 = new ActionRowBuilder().addComponents(fields.footer);
        modal.addComponents(tytul1, tresc1, footer1);
        await interaction.showModal(modal)
        
        if (!interaction.isModalSubmit()) {
      const tytul = interaction.fields.getTextInputValue("tytul");
      const tresc = interaction.fields.getTextInputValue("tresc");
      const footer = interaction.fields.getTextInputValue("footer");
  
      const embed = new EmbedBuilder()
        .setThumbnail(interaction.user.displayAvatarURL({ dynamic: true }))
        .setTitle(tytul)
        .setDescription(tresc)
        .setFooter(footer)
    
      await interaction.reply({ content: `Ustawiono nowy wygląd pożegnać! Podgląd:`, embeds: , ephemeral: true })
    }

I’ve tried many ways and I still don’t know what’s wrong 🙁

Adding Select2 class from JavaScript not working

In my web application, I’m adding new rows to the table from javascript.

There is an element in the row and for the Im loading data from the ViewBag.

Also, I want to add Select2 class to the same element.

So I tried doing,

'<select onchange="sendInfo(this)" class="form-select Select2 ItemId" data-id= '+counter+' name="Item_Id[' +
  counter +']" id="ItemId[' + counter +']" required="required" ' + "</select>" 

But it doesn’t apply to the class correctly.

I want help from you to fix this issue.

Here is my full code.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</div>

Javascript

 var counter = 1;

 var dropdownOptions = @Html.Raw(Json.Encode(ViewBag.Item_ID));

 $(function () {

   $("#add").click(function () {
     var newRow = $(
       '<tr id="tablerow' +
       counter +
       '" class ="poSet"> ' +
       "<td>" +
       '<label id="CountItems"><strong>' +
       counter +
       "</strong></label>" +
       "</td>" +
       '<td width="40%">' +
       '<select onchange="sendInfo(this)" class="form-select ItemId" data-id= ' + counter + ' name="Item_Id[' +
       counter +
       ']" id="ItemId[' + counter + ']" required="required" ' +
       "</select>" +
       "</td>" +
       '<td width="10%">' +
       '<input type="text" class="form-control Qty" name="Qty[' +
       counter +
       ']" value="1" id="Qty[' + counter + ']" onchange="calQtyBase(this)" data-QtyId= ' + counter + ' required="required" />' +
       "</td>" +
       '<td width="10%">' +
       '<input type="text" class="form-control" name="MeasureBy[' +
       counter +
       ']" value="" id="MeasureBy[' + counter + ']" readonly />' +
       "</td>" +
       '<td width="20%">' +
       '<input type="text" class="form-control UnitPrice" name="Unit_Price[' +
       counter +
       ']" value="0.00" id="UnitPrice[' + counter + ']"  onchange="priceBase(this)" data-PriceId= ' + counter + '  required="required" />' +
       "</td>" +
       '<td width="20%">' +
       '<input type="text" class="form-control LineTotal" name="Line_Total[' +
       counter +
       ']" value="0.00" id="LineTotal[' + counter + ']"    required="required" />' +
       "</td>" +
       "<td>" +
       '<button type="button" class="btn btn-danger" onclick="removeTr(' +
       counter +
       ');">x</button>' +
       "</td>" +
       "</tr>"
     );

     var selectElement = newRow.find("select"); // Find the <select> element in the new row

     // Populate the <select> element with options

     dropdownOptions.forEach(function (option) {

       var optionElement = $("<option>").val(option.Value).text(option.Text);
       selectElement.append(optionElement);
       optionElement.select2();

     });
     newRow.appendTo("#submissionTable");

     counter++;
     return false;
   });

 });

Coding a calculator but having problem with the arrays in the calculate function

I’m trying to code a calculator, but I’m having a problem with the calculate function.
I want to be able to take more than two numbers and calculate the answer, but I can’t work my way around it

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <style>
        html {
            box-sizing: border-box;
            margin: 0;
        }

        body {
            margin: 0;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            overflow: hidden;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .box {
            border: 2px solid black;
            background-color: dimgrey;
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 320px;
            height: 380px;
            justify-content: space-evenly;
            border-radius: 15px;
            padding: 10px 0;
        }

        .display {
            border: 2px solid darkslategrey;
            width: 85%;
            height: 30%;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            justify-content: flex-end;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 2.5rem;
            overflow: hidden;
        }

        .up_screen,
        .down_screen {
            width: 100%;
            height: 50%;
            display: flex;
            align-items: center;
            justify-content: end;
            /* overflow: scroll; */
        }

        .up_screen {
            background-color: lightgray;
            color: darkcyan;
        }

        .down_screen {
            background-color: lightcyan;
        }

        .keypad {
            width: 90%;
            height: 60%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-evenly;
        }

        .keyrow {
            display: flex;
            width: 90%;
            justify-content: space-around;
        }

        button {
            width: 60px;
            height: 40px;
            background-color: white;
            font-size: 1.5rem;
        }

        .special_keys {
            flex: auto;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="display">
            <div class="up_screen"></div>
            <div class="down_screen"></div>
        </div>

        <div class="keypad">
            <div class="keyrow row1">
                <button class="num_key">7</button>
                <button type="button" class="calc_key num_key">8</button>
                <button type="button" class="calc_key num_key">9</button>
                <button type="button" class="calc_key math_key">+</button>
            </div>

            <div class="keyrow row2">
                <button type="button" class="calc_key num_key">4</button>
                <button type="button" class="calc_key num_key">5</button>
                <button type="button" class="calc_key num_key">6</button>
                <button type="button" class="calc_key math_key">-</button>
            </div>

            <div class="keyrow row3">
                <button type="button" class="calc_key num_key">1</button>
                <button type="button" class="calc_key num_key">2</button>
                <button type="button" class="calc_key num_key">3</button>
                <button type="button" class="calc_key math_key">÷</button>
            </div>

            <div class="keyrow row4">
                <button type="button" class="calc_key num_key">.</button>
                <button type="button" class="calc_key num_key">0</button>
                <button type="button" id="result">=</button>
                <button type="button" class="calc_key math_key">*</button>
            </div>

            <div class="keyrow row5 ">
                <button class="special_keys" id="clear">C</button>
                <button class="special_keys" id="delete">Del</button>
            </div>
        </div>
    </div> 

<script>
        class Calculator {
            constructor(currText, prevText) {
                this.currText = currText;
                this.prevText = prevText;
            }


            calcInput() {
                for (let i = 0; i < operators.length; i++) {
                    let result;

                    if (operators[i] == "*") {
                        result = parseInt(numbers[i]) * parseInt(numbers[i+1])
                        numbers.splice(numbers[0], 2, result);
                        operators.splice(operators[0], 1);
                    }

                    // if (operators[0] == "+") {
                    //     result = parseInt(numbers[i]) + parseInt(numbers[i + 1])
                    // }

                    // if (operators[0] == "-") {
                    //     result = parseInt(numbers[i]) - parseInt(numbers[i + 1])
                    // }

                    // if (operators[0] == "÷") {
                    //     result = parseInt(numbers[i]) / parseInt(numbers[i + 1])
                    // }
                    console.log(result, numbers)
                }
                // this.clearInput()
                // this.updateDisplay(result)
            }
            deleteInput() {

            }

            clearInput() {
                currText.innerHTML = ""
                prevText.innerHTML = ""
            }

            updateDisplay(digit) {
                currText.innerHTML = currText.innerHTML.toString() + digit.toString()
                numbers = currText.innerHTML.split(/+|-|*|÷/g)
                operators = currText.innerHTML.replace(/[0-9]|./g, "").split("")
            }
        }
        let numbers;
        let operators;

        let prevText = document.querySelector(".up_screen")
        let currText = document.querySelector(".down_screen")

        let clearKey = document.getElementById("clear")
        let deleteKey = document.getElementById("delete")
        let resultKey = document.getElementById("result")

        let calcKeys = document.querySelectorAll(".calc_key")
        let mathKeys = document.querySelectorAll(".math_key")
        let numKeys = document.querySelectorAll('.num_key')

        const calculator = new Calculator(currText, prevText)

        numKeys.forEach(button => {
            button.addEventListener('click', () => {
                calculator.updateDisplay(button.innerHTML)
            })
        })

        mathKeys.forEach(button => {
            button.addEventListener('click', (e) => {
                let lastChar = currText.innerHTML[currText.innerHTML.length - 1]

                if (lastChar === "+" || lastChar === "-" || lastChar === "*" || lastChar === "÷") {
                    currText.innerHTML = currText.innerHTML.substring(0, currText.innerHTML.length - 1) + e.target.innerHTML
                } else if (currText.innerHTML.length == 0) {
                    console.log("Enter number");
                } else {
                    calculator.updateDisplay(button.innerHTML)
                }
            })
        })

        resultKey.addEventListener("click", () => {
            calculator.calcInput()
            // calculator.updateDisplay()
        })

        clearKey.addEventListener("click", () => {
            calculator.clearInput()
        })

    </script>

</body>

</html>

My idea is to work with two numbers at a time and accumulate the till the final answer.
I’ve tried using for loop with splice and I’ve tried reduce method.
I just realized that the numbers array I’m working with isn’t splicing the way I want to.

And also, I’m trying to find a way to remove “currText.innerHTML” and place it in a variable. But everything I’ve used doesn’t reflect on the calculator screen. I left it to continue with the project, but I’ll appreciate help there too.
Please help.

How do I set a type for a prop in Svelte with Typescript

I’m trying to adapt this excellent Svelte virtual list to Typescript. However, I don’t quite understand how to make sure that the variables that I pass are of a specific type. Here is the relevant original code:

  <VirtualList items={books} {itemHeight} {containerHeight} {scrollTop} let:item let:dummy let:y>
    <div class="book" class:dummy style="top:{y}px;">
      {#if !dummy}
        #{item.id} - {item.title}
      {/if}
    </div>
  </VirtualList>

As you can see, there is let:item to pass the items.

What I would like is just pass the item to another component, like so:

{#if !dummy}
  <BookRowEntry {item} />  <!-- where <BookRowEntry/> has: 'export let item: BookClass;`-->
{/if}

This works in plain Javascript, but when I switch to Typescript, I get an error:

Type ‘{}’ is missing the following properties from type ‘BookClass’: pg, indexts(2739)

So how do I specify/make sure that the item that I pass is of a certain class?

Thank you in advance!

refused to execute script because it is MIME type

I ran ui5 serve, but nothing appears on the screen. When I inspected the page, I received the following error message:

`"Refused to execute script from 'http://localhost:8080/resources/sap-ui-core.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."`

Could you please provide guidance on how to resolve this issue?

Change a element of an array with setState

I initialized a new constant like that :

    const [data, setData] = useState([
     {
      id: "a1",
      score: "",
      name: "MyA1"
     },
     {
      id: "a2",
      score: "",
      name: "MyA2"
     }
    ]);

I want to change the score with setData. But I don’t know how to access to data[0].score and data[1].score with setData

I tried to do :

    const updateList = (data) => {
      setData(previousState => {
        return { ...previousState, score:'Good' }
      });
    }

but it is not working because with this code I can’t access to data[0]. I tried also :

   const updateList = (data) => {
      setData(previousState => {
        return { ...previousState, previousStat[0].score:'Good' }
      });
    }

but it is not working too.

Do you know how to do that ? Thank you !!

Uncaught TypeError: manager.push(…) is not a function

im working on a todo list manager project. it was all working fine until I tried adjusting it to work with local storage
this is my code below – it seems like every function suddenly is not recognized and i cant tell why –
https://jsfiddle.net/yrbajkhp/

manager is an set to local storage like this :

manager = new TaskManager(); manager.addTask("Portfolio project"); localStorage.setItem("userManager", JSON.stringify(manager));

*TaskManager creates an array of the type Task , all defined in a different file in the project

function addNewTask() { alert("hello"); let description = (document.getElementById("description") as HTMLInputElement).value; manager.push(new Task(description)) (document.getElementById("description") as HTMLInputElement).value = ""; showTasksInLists(); }
I was expecting the function to add a new task to the tasks array but for some reason it wont work

main.js:43 Uncaught TypeError: manager.push(...) is not a function
    at addNewTask (main.js:43:40)
    at HTMLButtonElement.onclick (index.html:32:64)
index.html:49 Uncaught ReferenceError: updateDescription is not defined
    at HTMLButtonElement.onclick (index.html:49:39)
2main.js:22 Uncaught TypeError: manager.findIndex is not a function
    at completeTask (main.js:22:33)

any help will be great 🙂

Alternatives to BFJ for big json parsing

I need to parse very large json files. Memory and speed is not a problem, but I need a solution that does not block event loop. I’ve learned about BFJ library that does exactly what I need. However, I want to consider all alternative. Can you recommend any other solution/library with functionality similar to what BFJ provides?

Some additional context:

  • I can’t use worker threads
  • Making data smaller, messaging, caching are possible options I considered and would like to avoid

Tailwind css a specific style for publication page

I am making my page using Tailwind CSS and I stuck on the publication page. I want something like this.
enter image description here

I tried to do with Tailwind CSS but did not able to get it fully.

const abstractButton = document.getElementById('abstract-button');
const closeButton = document.getElementById('close-button');
const abstractPopup = document.getElementById('abstract-popup');

abstractButton.addEventListener('click', () => {
    abstractPopup.classList.remove('hidden');
});

closeButton.addEventListener('click', () => {
    abstractPopup.classList.add('hidden');
});
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>
<div class="flex flex-col h-screen">    
    <div class="flex flex-row justify-center items-center my-4">
    <div class="mr-8 h-60 w-60">
        <img src="https://via.placeholder.com/150" alt="Journal of Algebra" class="w-36 h-auto">
    </div>
    <div>
        <p class="mb-4 text-lg">
            The image of polynomials and Waring type problems on upper triangular matrix algebras
        </p>
        <p class="mb-4">
            <span class="authors">Authors: </span><strong>Sachchidanand Prasad</strong>, Saikat Panja and Navnath Daundkar
        </p>
        <div class="flex space-x-4 items-center my-2">
            <div class="border rounded-lg border-gray-600 p-1">
            <a href="https://arxiv.org/abs/2206.08827" target="_blank" class="text-blue-500 hover:text-blue-800">arXiv</a>
            </div>
            <div class="border rounded-lg border-gray-600 p-1">
            <a href="link-to-journal" target="_blank" class="text-blue-500 hover:text-blue-800">Journal</a>
            </div>
            <div class="border rounded-lg border-gray-600 p-1">
            <a href="link-to-pdf" target="_blank" class="text-blue-500 hover:text-blue-800">PDF</a>
            </div>
        </div>
        <button class="mt-4 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700" id="abstract-button">Abstract</button>
    </div>
    </div>
    
    <!-- Abstract Popup -->
    <div id="abstract-popup" class="fixed inset-0 flex items-center justify-center hidden">
    <div class="absolute bg-white rounded-lg p-8 w-1/2">
        <h2 class="text-xl font-bold mb-4">Abstract</h2>
        <p class="text-gray-800">
        This is the abstract of your paper. It provides a concise summary of your research, highlighting the main objectives, methods, and findings. You can customize this section with your own abstract content.
        </p>
        <button class="mt-6 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700" id="close-button">Close</button>
    </div>
</div>

There are the following problems that I am facing:

  1. The image size is not constant, that is, when the title of the publication is small, the image is bigger and when it is large, then the image size is small.

  2. I am not getting the year like this.

Any help will be appreciated.