What would a language learning app’s code look like? [closed]

So for my final year project, I am trying to build a language learning web application for indigenous languages where I am.
The problem is, I have no idea how the code would even look like.

Like how do they know when I type “bonjour”, it actually means “good day”?

Or for example if I type “je le veux” meaning “I want it” in French.

how do they know that is correct? Duolingo for example will mark me as wrong if I type “je veux le”

do they use like an JS object or python dictionary to store the data or something?

ChatGPT, says it would be something like this

// Define a dictionary of correct translations
const translations = {
    "hello": "bonjour",
    "goodbye": "au revoir",
    "I want it": "je le veux",
    // Add more translations as needed
};

// Function to check if user input is correct
function checkTranslation(userInput) {
    // Normalize user input (e.g., convert to lowercase)
    userInput = userInput.toLowerCase().trim();
    
    // Look up the correct translation for the user's input
    const correctTranslation = translations[userInput];
    
    // Check if the translation exists and matches the user's input
    if (correctTranslation && correctTranslation === userInput) {
        return true; // User input is correct
    } else {
        return false; // User input is incorrect
    }
}

// Example usage
const userInput1 = "Bonjour";
const userInput2 = "je veux le";

console.log(checkTranslation(userInput1)); // Output: true (correct)
console.log(checkTranslation(userInput2)); // Output: false (incorrect)`````

I would like a human opinion also.

what do you guys think?

How to write non-words characters in a JavaScript to build “Madlib” style game

I am on a challenge to use string concatenation in JavaScript. The challenge is perfectly defined such as

The ______ ______ looked around ______ then ______ into the house

These four blanks would be filled in this order: (adjective) (noun)
(adverb) (verb)

You will need to use string concatenation to build a new string,
result, using the variables myNoun, myAdjective, myVerb, and myAdverb.
These variables are passed to the function as parameters. Don’t change
these parameter names in the function.

Include additional strings and spaces (which will not change) in
between the provided variables to make a complete sentence.

I made the following code to this challenge

function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
  var result = "";
  // Your code below this line
  result = "The " + myAdjective + " " + myNoun + " looked around " + myAdverb + " then " + myVerb + " into the house";

  // Your code above this line
  return result;
}

// Change the words here to test your function
console.log(wordBlanks("dog", "big", "ran", "quickly"));
console.log(wordBlanks("cat", "little", "hit", "slowly"));

But the problem is following errors keep showing in tests results.

wordBlanks("dog", "big", "ran", "quickly") should contain all of the passed in words separated by non-word characters (and any additional words in your Madlib).

wordBlanks("cat", "little", "hit", "slowly") should contain all of the passed in words separated by non-word characters (and any additional words in your Madlib).

Could you review my code and show me what I have forgotten?

Updating form slider values that divide up a value between them

I need to add a form that allows a user to divide up a value between five options.

So they have a value of say 5000, and can move each slider to allocate some of that 5000 to something.

When slider A is moved to 3000, the initial value is dropped to 2000, and then if any of the other sliders are moved they will only be allowed to move by the remaining 2000.

If slider B is moved to 1000, the initial value goes down to 1000, and then slider c , d, and e can only be moved by 1000.

Basically, each slider is linked to the other, so a slider can only add the remaining value to that option, so to add more, another slider would need to be reduced.

So far from searching Stack Overflow I’ve got this…

    start: function () {

    document.getElementById('A').addEventListener('change', function (e) {
        document.getElementById('B').value = 5000 - (e.target.value - 1);
        document.getElementById('C').value = 5000 - (e.target.value - 1);
        document.getElementById('D').value = 5000 - (e.target.value - 1);
        document.getElementById('E').value = 5000 - (e.target.value - 1);
    })

    document.getElementById('B').addEventListener('change', function (e) {
        document.getElementById('A').value = 5000 - (e.target.value - 1);
        document.getElementById('C').value = 5000 - (e.target.value - 1);
        document.getElementById('D').value = 5000 - (e.target.value - 1);
        document.getElementById('E').value = 5000 - (e.target.value - 1);
    })

    document.getElementById('C').addEventListener('change', function (e) {
        document.getElementById('A').value = 5000 - (e.target.value - 1);
        document.getElementById('B').value = 5000 - (e.target.value - 1);
        document.getElementById('D').value = 5000 - (e.target.value - 1);
        document.getElementById('E').value = 5000 - (e.target.value - 1);
    })

    document.getElementById('D').addEventListener('change', function (e) {
        document.getElementById('A').value = 5000 - (e.target.value - 1);
        document.getElementById('B').value = 5000 - (e.target.value - 1);
        document.getElementById('C').value = 5000 - (e.target.value - 1);
        document.getElementById('E').value = 5000 - (e.target.value - 1);
    })

    document.getElementById('E').addEventListener('change', function (e) {
        document.getElementById('A').value = 5000 - (e.target.value - 1);
        document.getElementById('B').value = 5000 - (e.target.value - 1);
        document.getElementById('C').value = 5000 - (e.target.value - 1);
        document.getElementById('E').value = 5000 - (e.target.value - 1);
    })

}

it worked when I had two sliders, but with 5, it doesn’t…

Inline Javascript code not executed when JSP page crawled by Google bot

I have a JSP page p.jsp that contains an inline call to a Javascript function f():

<html>
  <body>
    <script type="text/javascript">
      my_namespace.f();
    </script> 
  </body>
</html>

This f() function sends a POST request to one of my Tomcat webapp servlets S:

s_url = "S";
xmlHttpRequest.open("POST", s_url, true);
xmlHttpRequest.onreadystatechange =  my_namespace.fEnd;
xmlHttpRequest.send();

In Tomcat’s log (localhost_access_log.<date>.txt), I observe the following line:

66.249.66.41 - - [date] "GET /my_webapp/p.jsp HTTP/1.1" 200 4264

Sometimes, I also observe:

66.249.66.41 - - [date] "POST /my_webapp/S?param=value HTTP/1.1" 200 125

But not systematically, rather barely actually…

Why is the Javascript code not always executed?
66.249... being a Google bot, is it possible that the GET it performs is not the same as the one that is performed when using a Web browser?

Quasar: QInput loses focus when used with QPopupProxy

I’m trying to combine a QField with a QPopupProxy. The proxy shows a QDate. After selecting a date, the field will be filled with a transformed value.

<template>
  <q-field
    label="Input date"
    v-model="date"
    :rules="[val => !!val || 'This field is required']"
    lazy-rules
  >
    
    <template #control="{ modelValue, emitValue }">
      <q-popup-proxy>
        <q-date
          mask="YYYY-MM-DD"
          :model-value="transformToString(modelValue)"
          @update:model-value="(value, reason) => transformToDate(value, reason)"
          v-close-popup
        ></q-date>
      </q-popup-proxy>
      
      <div v-if="date">{{ date }}</div>
    </template>
  </q-field>
</template>

<script setup>
// imports

const date = ref();

function transformToString(value) { /* implementation */ }

function transformToDate(value, reason) { /* implementation */ }
</script>

Problem

The issue with this is that the field loses focus as soon as the popup opens, which will trigger validation and render the error message.

Also there is some weirdness going on when clicking the field. When clicking above the label, the popup doesn’t open.

There is an issue for this on Github, which unfortunately was closed without giving a solution.

Here is a Codepen example

How can I open the popup without having the field lose focus?
Also, how can I open the popup, no matter where I click in the field?

Modifying InnerHTML breaks button [duplicate]

I am creating a table with variable amount of rows. On creation of the table, I also want to add in a button that calculates something with the data entered into the created table.

const go = document.querySelector("#go");
const table = document.querySelector("#table");

go.addEventListener('click',(event) => {
    const n = document.querySelector("#n").value;
    console.log(n);
    let calc = document.createElement('button');
    calc.className = "calc";
    calc.textContent = "calculate";
    table.appendChild(calc);
  
    table.innerHTML += "<div class='break'></div>";
    /* 
    ----Other elements added using innerHTML----
    */

    calc.addEventListener('click', () => {
        console.log("Test");
    })

});
Enter value of N:
<input type="text" id="n">
<button id="go">go</button>
<br>
<div id="table"></div>

The problem I am facing is if I add anything to the innerHTML of table div, The button stops working. The above button stops working if //table.innerHTML += "<div class='break'></div>"; is uncommented. Why does this happen and how do I fix this?

React Native Firebase Messaging Registering For Remote Messaging Error

I am getting contradictory error messages from "@react-native-firebase/messaging": "^18.6.2",

First Error:

[Error: [messaging/unregistered] You must be registered for remote
messages before calling getToken, see
messaging().registerDeviceForRemoteMessages().]

Okay easy enough let’s “registerDeviceForRemoteMessages” before calling “getToken”.

Code:

export const fetchMessagingToken = async (uid) => {
  await messaging()
    .registerDeviceForRemoteMessages()
    .then(async () => {
      await messaging()
        .getToken()
        .then((token) => {
          return saveTokenToUser(uid, token);
        });
    })
    .catch((error) => {
      console.log("FETCH MESSAGING TOKEN ERROR:", error);
    });
};

Second Error/WARN:

WARN Usage of “messaging().registerDeviceForRemoteMessages()” is not
required. You only need to register if auto-registration is disabled
in your ‘firebase.json’ configuration file via the
‘messaging_ios_auto_register_for_remote_messages’ property.

I don’t have a firebase.json file in my project, som I’m a bit confused here. I can’t seem to update my users device token. This was working as expected in "expo": "~49.0.15" however after updating to "expo": "^50.0.7" seems to be issues.

Getting a function’s name when the function is contained inside a TypeScript namespace

I would like to be able to obtain a TypeScript function’s own name from within the function. I have read through the Function: name documentation, but the following code does not work as expected.

Here is a simple test code (link to TS Playground)

const func = () => {
    return func.name;
}

namespace NS {
    export const func = () => {
        return NS.func.name;
    }
}

console.log(func()); // Expect output: 'func'
console.log(NS.func()); // Expect output: 'NS.func'

The actual output of the code is

'func'
''

Seems like if a function is contained within a namespace, the Function.name property is set to an empty string.

Is there a clever way to get around this?

Is there any way to include # in the CSV input without breaking the format

In my project I am trying to create CSV report by converting a JSON to comma seperated values enclosed with double quotes. But while in the JSON I have # as a value in some places.
So while downloading CSV report i am getting the only contents which are present before #. But I need to show # in my CSV report. Help me to solve this in Js.

Tried the escape sequence for # ‘#’ still it is not working

{name :apple#233}
If this is the input then the output in CSV should be apple#233 under the name column

But the current output is just apple under the name column

how to create a mac executable for my electronJs application that supports php with the ELECTRON-4-PHP-master project taken from github

when I run my application with the command “npm start” my application works fine but when I create the executable with the command “electron-packager. –overwrite –platform=darwin –arch=x64 –no-asar –icon=icons/logo.icns –prune=true –out=release-builds” the application that I created only works if my application executed with the command “npm start” remains running so the server of the application that I created does not start by itself

please help me

I tried to use the start() function of the PHPServer class so that the server runs directly

I want it to be created with a different name after copying the file to the folder I need

I take files from a spreadsheet in Excel and replace the substituted words in word, copying the file to a separate folder with the finished documents.

I work in Excel. I want it to be renamed to the name I need when copying the file.

Tell me how this can be done. I tried to find different methods, but not one came up

function myFunction() {
  const docFile = DriveApp.getFileById("1OLAGN_5NN1ZEudjlAjfnESu3auGHUxVHlwAktbm24OQ");
  const tempFolder = DriveApp.getFolderById("10AU7yahd5PogWHK0m_mOUZvFS-pbu2g8");
  const tempFile = docFile.makeCopy(tempFolder);
  const tempDocFile = DocumentApp.openById(tempFile.getId());
  const body = tempDocFile.getBody();

  var list = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var a = list.getRange(2, 3).getValue()
  var b = list.getRange(3, 3).getValue();
  var c = list.getRange(4, 3).getValue();

  body.replaceText("{Имя}", a);
  body.replaceText("{Дата}", b);
  body.replaceText("{Сумма}", c);

  tempDocFile.saveAndClose();
}

React – Optimize preview for large amount of photos

I am currently working on a React project where users can upload a substantial number of photos (around 400+) using the react-dropzone library. While the file upload functionality is working as expected, I am facing performance issues when it comes to generating and displaying photo previews.

Photos are loading slow and scroll lag is very strong with 400+ photos (5-6MB per photo is average). Photos are in jpg format.

In my onDrop handler, I have the following logic:

// ...imports
import {useDropzone} from "react-dropzone"

export const ImageDrop: React.FC<ImageDropProps> = ({}) => {
  const [files, setFiles] = useState<File[]>([])

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      if (acceptedFiles?.length) {
        setFiles((prevFiles) => {
          const newFiles = [];
          for (const file of acceptedFiles) {
            if (file.type === 'image/jpeg') {
              Object.assign(file, { preview: URL.createObjectURL(file) });
              newFiles.push(file);
            }
          }
  
          return [...prevFiles, ...newFiles];
        });
      }
    },
    [disabled, maxPhotoSize, maxPhotos, setFiles, t],
  );
  
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    disabled,
  });
  
  return (
    <>
      <form>
        <div {...getRootProps()}>
          {!disabled && <input {...getInputProps()} />}
        </div>
      </form>
      {files.map((file, index) => (
        <div
          className='relative h-32 w-32 cursor-zoom-in select-none items-center justify-center'
          key={file.name}
        >
          <div
            className='absolute inset-0 -left-2 -top-2 z-20 h-8 w-8 cursor-pointer rounded-full border-2 border-foreground bg-content1 opacity-75 transition-all duration-300 hover:scale-125 hover:opacity-100'
            onClick={() => onRemove(file.name)}
          >
            <TrashIcon className='mx-auto pt-1 text-foreground' />
          </div>{' '}
          <img
            src={file.preview}
            className='max-w-36 max-h-36 rounded-lg bg-content2 p-1'
            style={{
              objectFit: 'cover',
              objectPosition: 'center',
              aspectRatio: '1/1',
            }}
            alt={file.name}
          />
        </div>
      ))}
    </>
  );
}

I have tried this solution but when I drop many photos, it takes too long for them to show (no lag after tho).

The goal is to find a way to optimize the photo preview generation process, ensuring a smooth user experience even when dealing with a large number of photos. I want to avoid any lag or delays in the application due to the photo preview generation.

I’m open to suggestions. Thank you in advance!

While running npm run make I am getting ‘An unhandled rejection has occurred inside Forge’

Error: EPERM: operation not permitted, lstat ‘Pathnode_modules.electron-YTUFZ2J8distelectron.exe’

Can you please let me know how to solve this error?

It is weird that I am unable to send you the entire thing, but the thing once I run the command npm run make, it is giving above error, so that was the main error and so after going to that path I am getting the permission error to access that electron.exe so need help to solve this issue.

Scrolling on child doesn’t scroll the parent

I am building a sticker choosing keyboard for a chat app. The parent is set to overflow-x: scroll and the individual sticker containers are set to overflow-y: scroll.

Here is the HTML of the svelte code:

<div class="stickerKeyboardContainer" transition:fly|global={{y: 40, duration: 100}} use:stickersHandler>
    <div class="stickerKeyboard">
        <div class="headers">
            <button on:click={() => { moveHeads('left'); }} class="navBtn hoverShadow"><i class="fa-solid fa-chevron-left" /></button>
            <div class="stickersHeader" id="stickersHeader" bind:this={stickersHeader}>
                {#each Stickers as sticker}
                    <img loading="lazy" class="hoverShadow" data-group="{sticker.name}" class:selected={$selectedSticker == sticker.name} src="/stickers/{sticker.name}/animated/{sticker.icon}.webp" alt="{sticker.name}">
                {/each}
            </div>
            <button on:click={() => { moveHeads('right'); }} class="navBtn hoverShadow"><i class="fa-solid fa-chevron-right" /></button>
        </div>
        <div on:scroll={() => {console.log("scrolling")}} class="stickersBody" id="stickersBody" use:stickersBodyHandler>
            {#each Stickers as sticker}
                <div class="stickerBoard {sticker.name}" id="{sticker.name}">
                    {#each Array.from({ length: +sticker.count }) as _, i}
                        <img loading="eager" class="stickerItem" data-serial={i+1} src="/stickers/{sticker.name}/static/{i + 1}-mini.webp" alt="{sticker.name}">
                    {/each}
                </div>
            {/each}
        </div>
    </div>
</div>

enter image description here
enter image description here
enter image description here

I can only scroll by the scrollbar thumb. I implemented the same thing is vanilla js. But currently I’m re implementing the same thing using svelte.

I have compared both of my projects, they uses the exact same css and js. But I’m stuggling what is wrong with the code. Can you provide some suggestions that I can try?

I have compared both of my projects, they uses the exact same css and js. Scroll on child is not working on parent.

How to change a style of Leaflet markers selected with square area?

Does anyone know how to change a style of all markers located within boundaries obtained with area selection tool?

map.on('areaselected', (e) => {
console.log(e.bounds.toBBoxString()); // lon, lat, lon, lat

});

Do I need to somehow iterate through all markers on a map and check whether their coordinates lie within this rectangular area?

I am not so familiar with JS and I do not quite understand how to access all markers and how to do it in optimal way

I want to use smth like this by checking conditions for all markers on a map

name.on("mouseover", function(e) {
name.setIcon(style2);
});

Thanks for understanding!