Asynchronous user input not being stored

I am working on a project in CodeHS using Javascript. I am trying to collect user input a number of times through a loop. However, I want this input to be asynchronous because readInt is a blocking function and will prevent the following code from being executed until the input popup is finished.

Because of this, I have tried to use the readIntAsync function, which allegedly allows the user to input values without the appearance of the popup box and without the blocking of the following code. However, when I do this, the computer does not appear to store the user input.

For example, in the following code (not from my program), the circle never moves.

var x = 50;
var y = 50;
var circle = new Circle(50);
circle.setPosition(x, y);
add(circle);

async function start() {
  for (var i = 0; i < 4; i++) {
    var begin = await readIntAsync("Pick a number. ");
    println(begin);
    x += begin * 50;
    y += begin * 50;
    circle.setPosition(x, y);
    add(circle);
  }
}
start();
<script src="https://cdn.codehs.com/chs-js-lib/0.2.21/dist/chs.iife.js"></script>

Is there a way to store the input from an asynchronous input function (readLineAsync, readIntAsync, readBooleanAsync, readFloatAsync). Alternatively, is there another way to get non-blocking input that will be stored?

Reloading MVC5 Partial View that contains a Document Viewer

I have a partial view in MVC5 that displays a document viewer and a button that lets users upload a document.
I want to be able to reload the contents of the partial view or just reload the entire partial view itself when a document is uploaded so the document that the user uploaded would be visible as soon as they finish uploading it.

Here is the Document Viewer:

@{
    ViewBag.Title = ViewBag.PageTitle;
    Layout = null;
}

@using GleamTech.AspNet.Mvc;
@using GleamTech.DocumentUltimate;
@using GleamTech.DocumentUltimate.AspNet;
@using GleamTech.DocumentUltimate.AspNet.UI;

<!DOCTYPE html>
@{
    var documentViewer = new DocumentViewer
    {
        Width = 800,
        Height = 600,
        Document = @ViewBag.documentFile
    };
}
<html>
<head>
    @this.RenderHead(documentViewer)
</head>
<body>
    @this.RenderBody(documentViewer)
</body>
</html>

Here is what calls the document viewer:

        public ActionResult ViewSanctionDocument(long id)
        {
            var lstData = EmployeeMemoServices.GetEmployeeMemo(_usrInfo, id);
            string filePath = "";
            if (lstData.EmployeeDocImg != null)
            {
                filePath = Server.MapPath(lstData.EmployeeDocImg.Substring(3, lstData.EmployeeDocImg.Length - 3).ToString());
            }
            ViewBag.documentFile = filePath;
            return View();
        }

This is the display:

@if (Model.EmployeeDocImg != null)
                                {
                                    @Html.Action("ViewSanctionDocument", "TransactionSanction", new { id = @Model.Id })
                                }
                                else
                                {
                                    <div class="dt-center justify-content-center col-md-12">
                                        <img class="rounded-lg figure-img img-fluid col-md-8" id="empimgPreview" src="../../Images/no-image.jpg" />
                                    </div>
                                }
                            </div>

This is what triggers the upload and is also where i plan to trigger the reloading of the partial view:

    $('#btnEmpSancSave').change(function () {
                    var empNo = $(this).attr('bId')
                    var data = new FormData();
                    var files = $(this).get(0).files;

            if (files.length > 0) {
                        data.append("MikeImages", files[0]);
                        data.append("EmployeeId", empNo);
                    }

                    $.ajax({
                        url: '@Url.Action(actionName: "SanctionDocumentSavingImage", controllerName: "TransactionSanction")',
                        type: "POST",
                        processData: false,
                        contentType: false,
                        data: data,
                        done: function (data) {
                            $("#viewid").html(data); //test
                        },
                        complete: function () {
                            alert('test'); //test
                        }
                    });
    });

So far I’ve tried doing a bunch of the things I saw it in here but none of them work.

GrammY telegram bot to do multiple selection and edit the Inline Keyboard button

I wanted to do the multiple selections for the grammY telegram bot but it seems not working

async function generatePayslipSelection(conversation: MyConversation, ctx: MyContext) {
    await ctx.reply(`Payslip Type`, {
        reply_markup: buildPayslipSelection()
    });

    // bot.editMessageReplyMarkup({
    //     reply_markup: buildPayslipSelection()
    // }, {
    //     chat_id: chat_id,
    //     message_id: msg_id
    // });
    console.log(ctx);
    bot.editMessageReplyMarkup(ctx.update.update_id, ctx.update.message.message_id, buildPayslipSelection())
}

I need to add in emoji while pressing button and remove an emoji while pressing button twice

export function buildPayslipSelection() {
    let inline_keyboard = new InlineKeyboard();
    let payslip = 0;
    for (const key in PayslipType) {
        const value = PayslipType[key];
        payslip++;

        inline_keyboard.text(value, value);

        // Move to next row when current row is filled up by 2 features
        if (payslip % 2 == 0) {
            inline_keyboard.row();
        }
    }
    return inline_keyboard;
}

the final data will stores in an array

ReactJS password field warning

In ReactJS, I have two password fields (password and confpassword) in a form. Corresponding code snippets as below.

State variable as below

  const [theUser, setTheUser] = useState(
    {
      firstname: '',
      lastname: '',
      email: '',
      password: '',
      confpassword: '',
    },
  );

UI code as below

<td>
  <input 
    type="password" 
    maxLength={15}  
    id="password" 
    name="password" 
    value={theUser.password}
    onChange={(e) => setPassword(e.target.value)}
  />
</td>

<td>
  Conf. password
</td>
<td>
  <input 
    type="password" 
    maxLength={15}  
    id="cnfpassword" 
    name="cnfpassword" 
    value={theUser.confpassword}
    onChange={(e) => setConfirmPassword(e.target.value)}
  />
</td>

onChange functions as below.

  function setConfirmPassword(value) {
    const newUser = {...theUser};
    newUser.confpassword = value;
    setTheUser(newUser);
  }

  function setPassword(value) {
    const newUser = {...theUser};
    newUser.password = value;
    setTheUser(newUser);
  }

So I have similar code for both password and confpassword.

When I access the page, in chrome devtools I get warning for password field as below, whereas no warning for confpassword field.

Warning: A component is changing a controlled input to be
uncontrolled. This is likely caused by the value changing from a
defined to undefined, which should not happen. Decide between using a
controlled or uncontrolled input element for the lifetime of the
component. More info: https://reactjs.org/link/controlled-components

at input

at td

My question: Even if I have same code for both password and confpassword why do I get warning only for password field?

withNextIntl and withPlaiceholder do not work together in NextJS

I am using the latest NextJS 14. And in next.config.mjs file as above, I wrapped my nextConfig in two plugins, but when I deployed them to Vercel, it simply cannot be built. I am relatively new to this situation, so I stop using plaiceholder so switched to Jimp to blur my image, which works smooth. Nevertheless, I would like to know what’s the solution here, in case I ever want to work in this setup again.

import createNextIntlPlugin from "next-intl/plugin";
import withPlaiceholder from "@plaiceholder/next";

const withNextIntl = createNextIntlPlugin();

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        hostname: "firebasestorage.googleapis.com",
      },
      {
        protocol: "https",
        hostname: "cdn.sanity.io",
      },
    ],
  },
  env: {
    POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL,
    POSTGRES_URL_NON_POOLING: process.env.POSTGRES_URL_NON_POOLING,
  },
};


export default withPlaiceholder(withNextIntl(nextConfig));

javascript pass parameter and receive event

Anyone can help me? How to pass parameter and receive event in one function?

I tried to use global variable, use another function to return event.

In handleUpload, I created variable columnNames and data, and received value. I want to pass the two parameters to handleVariableChange function and receive event to select variable and receive the corresponding data of that variable.

The current function of handleVariableChange show error “columnNames in handleVariableChange:undefined”. If I move “event” to the position after “data”, then show error”event is undefined”.

What should I do?

const handleUpload = async (event) => {
        const file = event.target.files[0];
        console.log("File:", file);
        const reader = new FileReader();

        reader.onload = async (e) => {
            const content = e.target.result;

            const csvResults = Papa.parse(content);
            console.log("CSV Results:", csvResults);

            const columnNames = csvResults.data[0];
            console.log("columnNames in handleUpload:", columnNames);

            const data = csvResults.data.slice(1);
            console.log("Column values in handleUpload:", data);

            setIsDataUploaded(true);

            setFilterVariableOptions(columnNames);
    
            handleVariableChange(columnNames, data);
            // setSelectedVariable(""); 
            // setSelectedData([]); 

            const formData = new FormData();
            formData.append('file', file);
            console.log("Data to be sent:", formData);

            await sendDataToBackend(formData);
        };
        reader.readAsText(file);
    };

    console.log("FilterVariableOptions in handleUpload:", filterVariableOptions);


    const handleVariableChange = (event, columnNames, data) => {
        
            console.log("event in handleVariableChange", event);
            const selectedVariable = event.target.value;
            console.log("SelectedVariable in handleVariableChange:", selectedVariable);
            console.log("columnNames in handleVariableChange:", columnNames);
            const selectedColumnIndex = columnNames.indexOf(selectedVariable);
            console.log("selectedColumnIndex in handleVariableChange:", selectedColumnIndex);
            if (selectedColumnIndex !== -1) {
                setSelectedVariable(selectedVariable);
                setSelectedData(data[selectedColumnIndex]);
         
                console.log("SelectedData in handleVariableChange:", selectedData);
            } else {
                console.error('Selected variable not found in handleVariableChange:', selectedVariable);
            }
    };

Why does my flip card animation not work properly on the first click of the button after the page loads, but works correctly after that first click?

I am currently working on a flip card animation using HTML, CSS, and JavaScript for my project. The animation works as expected when the “More” button is clicked and the card flips, revealing the back side. Similarly, clicking the “Back” button flips the card back to its original state.

However, I am facing an issue where the animation does not perform smoothly on the first click of the “More” button after the page loads. It flips but the animation effect is done partially, without 3d effect. Subsequent clicks work fine and trigger the animation in a proper way.

I have included my HTML, CSS, and JavaScript code below for reference:

<div id="meal-card" class="card">
                        <div id="meal-card-front" class="card-front">
                            <div class="inline">
                                <h3 id="meal-name"></h3>
                                <p id="btn-container"><a id="btn-see-more" href="#<strong>More</strong></a></p>
                            </div>
                            <div><img id="meal-image" src=""></div>
                            <h4>Ingredients</h4>
                            <p id="ingredients"></p>
                        </div>
                        <div id="meal-card-back" class="card-back">
                            <div class="inline">
                                <h4>Instructions</h4>
                                <p id="btn-get-back"><a href="#"><strong>Back</strong></a></p>
                            </div>
                            <p id="instructions"></p>
                        </div>
.card {
    perspective: 1000px;
}


.card-front, .card-back{
    background: #fffcec;
    border-radius: 5px;
    text-align: center;
    width: 480px;
    height: 470px;
    padding: 0;
    box-shadow: 4px 4px 9px rgba(0, 0, 0, 0.2);
    position: absolute;
    backface-visibility: hidden;
    transition: transform 0.6s;
}
  
.card-back {
    transform: rotateY(180deg);
}
  
/* This class is added to the card when it should flip */
.flipped .card-front{
    transform: rotateY(180deg);
}
  
.flipped .card-back {
    transform: rotateY(0deg);
}
var moreBtn = document.getElementById("btn-see-more");
var backBtn = document.getElementById("btn-get-back");

moreBtn.addEventListener("click", function(){
    mealCard.classList.add("flipped");
    $("#meal-card-back").show();
});

backBtn.addEventListener("click", function(){
    mealCard.classList.remove("flipped");
});

Can anyone provide insights or suggestions on how to ensure the flip card animation works smoothly even on the first click after page load?

Any help or guidance would be greatly appreciated. Thank you!

Python3-pip installation failing me countless times in ubuntu 22.04

I keep getting a security message that stops python3-pip from installing.
i tried almost everything i could but i still get ts same issueenter image description here error message:
Err:1 http://security.ubuntu.com/ubuntu jammy-updates/main amd64 libexpat1-dev amd64 2.4.7-1ubuntu0.2
404 Not Found [IP: 185.125.190.39 80]
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/e/expat/libexpat1-dev_2.4.7-1ubuntu0.2_amd64.deb 404 Not Found [IP: 185.125.190.39 80]
E: Unable to fetch some archives, maybe run apt-get update or try with –fix-missing?

error message

Not able to find api call made from main page in the page source

After loading page

https://www.moneycontrol.com/india/stockpricequote/miscellaneous/aurangabaddistillery/AD05

it makes a call to ( found through Network tab )

https://priceapi.moneycontrol.com/pricefeed/bse/equitycash/AD06

But above API entry / call is not to be found in the main page’s page source entry.

Please clarify this mystery, without api entry how does that one gets called and data is populated inside “Price Performance” table ?

enter image description here

Page refreshes after clicking a button that updates the page; test/assertion times out with two headings but not one

https://youtu.be/dpYMGGSmRaw

I created a simple test that clicks a button, which adds two headings to the pages. This works if I check the text with toHaveText(). However, if I check number of children with toHaveCount(), the test times out.

function addHeading() {
   const results = document.querySelector('#results');
   const h1 = document.createElement('h1')
   h1.textContent = 'heading1'
   results.appendChild(h1)
   const h2 = document.createElement('h1')
   h2.textContent = 'heading2'
   results.appendChild(h2)
}

const submitButton = document.querySelector('button')
submitButton.addEventListener('click',addHeading)
test (`empty search returns all results`, async ({page}) => {
   await page.getByRole('button', { name: 'Submit' }).click({delay: 70});
   await expect(page.locator('#results')).toHaveText('heading1heading2')
   await expect(page.locator('#results')).toHaveCount(2)
})

For the second expect, the page would refresh and I don’t think this should happen. If I add only one heading, both tests would pass but the page still refreshes and the heading disappears.

The closest post I found is this one. It mentions using click({delay: 70}), which I tried and did not make any difference.

Why would toHaveCount() time out with two headings but not one, and why would the page refresh?

trouble putting array in local storage

I have this code for one HTML page, then im trying to display the localStorage data on a second HTML page.

let arrayTest = ["FirstElement", "SecondElement", "ThirdElement"];

localStorage["dataArray"] = JSON.stringify(arrayTest);

let retString = localStorage.getItem("dataArray");

let retArray = JSON.parse(retString);
console.log(retArray);

when I log it, it returns only null. whats wrong? thanks

I tried the code above. I’m trying to see how to take an array and put it into localStorage and retrieve it.

Trying to codegen some zod types

So I’m trying to figure out a good solution to codegen zod types from object.

Objects when stringified look like this.

{
 Item: {
  Foo: 'z.string()',
  Bar: {
   IsBar: 'z.boolean()'
  }
 }
}

Goal is to remove any quotes for all values because when the file is written using fs, I will have zod objects.

I don’t think I can use the JSON.stringify replacer for this as the string values won’t have quotes to remove. Is the only way to use .replace on the stringified object, perhaps using regex? Seems like there should be a better way that I am not aware of.

Result should be this

{
 Item: {
  Foo: z.string(),
  Bar: {
   IsBar: z.boolean()
  }
 }
}

how can i streamed response to web client in cloudflare workers

i make a openai streaming service in fetch in cloudflare workers, but the response in web client will always be not-streaming response , it will always return the whole data after openai’s request totally finished. how can i make it streamed ?

here’s my test code in workers:

export default {
  async fetch(request: Request, env: any, ctx: ExecutionContext) {
    const openai = new OpenAI({
      apiKey: env.OPENAI_API_KEY,
      baseURL: env.OPENAI_API,
    });

    const stream = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: (await request.json()) || '' }],
      stream: true,
    });

    return new Response(stream.toReadableStream());
  },
};

and here’s my web client code:

export const fetchTest = async () => {
  const streamApiUrl = '/xxx/query'
  const response = await fetch(streamApiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      content: 'who are you'
    })
  })

  const bodyReader = response.body.getReader()
  while (true) {
    const { value, done } = await bodyReader.read()    // it won't return like stream , it will return all data once and for all after request finished
    if (done) break
    console.log(value)
  }
}

fetchTest()

here’s my chrome devtools screenshot:
enter image description here

enter image description here

try to streamed response to web client in cloudflare workers