How do you reverse a string? [closed]

convert the string to a character array char_array.

call the recursive function reverse string helper with char_array,o ans char_array. length -1 as input

convert the character array back to a string and return it.,

i tried many time . i didn’t get it

web-программирование. Как можно прописать симуляцию нажатия клавиш при входе на сайт? [closed]

На личном google диске хранится самописный сайт, и все вносимые в него изменения не отображаются в браузере просто так, потому что это не сторонний хост, а моё облако, то есть часто не видно части контента, отсутствуют фото, другие медиафайлы, и нужно постоянно прожимать Ctrl + F5 для жесткой перезагрузки чтобы обновления вступали в силу, но делать это постоянно вручную долго, есть ли какой-нибудь скрипт чтобы всё это дело автоматизировать, и при заходе на мой сайт у пользователя программно
сразу прожималось сочетание Ctrl+f5?


What is the best way to check if a nested property exists in Javascript?

I’m making an API call that 99% of the time has this value defined: awayTeam.record[0].displayValue

The one percent of the time, however, record is not defined or some other nested object is not defined. Is there a clean one line solution to check wether record exists?

I have tried things like this:

<h1> {awayTeam.record[0]?.displayValue || "0-0"} </h1>

and

<h1> {awayTeam.record[0].displayValue ?? "0-0"} </h1>

I have quite a lot of properties like this, so I would like to find a clean solution for this issue. Thanks!

How do websites handle “dynamically generated HTML”

So I am learning how to create webapps, but i need a bit of guidance.

Most web apps have most of the HTML already loaded when accessing a url, i never see things like <script src="some_script.js"></script>, I often see only the information already there, is it all down to “serverside rendering”? Basically have the HTML pre created on svside and just serve it to whoever calls the url?

Or is there another aproach that does this on the client side?

I idealy would like to have on svside only apis that server information and use that somewhere in the client itself

Matrix alphabet highlighting

I’m working on a JavaScript project where I need to create a matrix of alphabet letters displayed in a table. I want to implement a feature where users can enter text, and the letters in the matrix matching this text will be highlighted. How can I achieve this functionality using HTML, CSS, and JavaScript? Specifically, I’d like to generate a matrix of letters and enable highlighting cells that match the user-entered text in the matrix. Can you provide guidance or code snippets to help me implement this feature?

i tried with javascript but it doent work at all

Is it possible to have a curried function which accepts generic arguments?

I want to make an auto-curried function which has an arity of 3. It operates over a list of objects, and finds the first object in that list which has a property that is equal to the key/value provided

  1. The first argument should be a key of the object that is passed in
  2. The second argument should be a value at that key
  3. The third argument should be a list of data

Effectively, I would want a function like this, but curried:

function findByProp<T extends object, K extends keyof T>(prop: K, value: T[K], data: Collection<T>) {
  return find(propEq(prop, value), data);
}

However, I am having a bit of trouble here when I encapsulate it in a curry function

const findByProp = curry(function findByProp<T extends object, K extends keyof T>(prop: K, value: T[K], data: Collection<T>) {
  return find(propEq(prop, value), data);
});

Predictably, it drops the generics. I was wondering, is there a way to make this work with generics? Ideally, I would be able to do this:

const findById = findByProp<{ id: string }, "id">("id");

Create gradient between four colors in JavaScript

In JS, I display a chart with a value in the range [0,1].
I would like to change the color of the chart according to its value:

  • 0 => red (#e83c4b)
  • 1/3 => orange (#F08700)
  • 2/3 => yellow (#bbdb06)
  • 1 => green (#0cca4a)

My problem is that I would like to create gradients between these values.

I would like to write a function where the input is the value in the range [0,1] and the output are RGB components.

I have absolutely no idea how to calculate the gradient.

With Vim, how can I wrap properly a code with a JavaScript function argument?

I want to easily wrap my code in an argument. For example:

1 + 1;

I want this to be in console.log() after wrapping: console.log(1+1);

I tried using Surround Vim, but it’s for HTML and not really suitable for JavaScript, because it does not move semicolon which is wrapped :

V (shift + v) for select entire line.
S (shift + s) for enter in

console.log(1 + 1;)

Do you know a better way or Vim plugin ?

This link does not apply to my specific case :
Wrapping a code block around code in VIM

I’m learning Vim 9 (in terminal). I’m going back to learning programming (with JS and soon PHP). Excuse me for being a newbie. Thanks a lot in advance

Can anyone help me figure out why VScode is saying that it cannot find module?

node:internal/modules/cjs/loader:1051
throw err;
^

Error: Cannot find module ‘/Users/ben/Desktop/GA/unit2/week5/GA_Project_2/QuotaQuest/index.js’
at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15)
at Module._load (node:internal/modules/cjs/loader:901:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47 {
code: ‘MODULE_NOT_FOUND’,
requireStack: []
}

Node.js v20.8.0
[nodemon] app crashed – waiting for file changes before starting…

I am trying to make a simple “to-do” app using vanilla JS and express, mongoose and mongoDB. I am trying to start my server but I keep getting this error. My server was working fine for most of the project and I honestly don’t know when it stopped working. I am also using webpack. I have a backend that was connecting fine until I started having this error. I am also using VScode, I have tried doing another “npm i”, double checked dependencies and tried different “PORT” numbers as well.

Has anyone else run into these issues?

Importing React Components

I have php page and import React as s file

<div id="app"></div>

<script src="/assets/app.js"></script>

in app.js file

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

app.js use jsx so I render it by console command

npx babel ./views/post/app.js -d –out-file ./web/assets/app.js –plugins=@babel/plugin-transform-react-jsx

everything works but app.js became bigger. because I write many components, so I decide devcide it on modules
I made SeoKeywords.js file

export default function SeoKeywords() {
    return (......)
}

And now I try to import it as it say here https://react.dev/learn/importing-and-exporting-components

I added import SeoKeywords from ‘./SeoKeywords’; in top of app.js
now in asset folder I have app.js ad SeoKeywords.js

when page is load I have error
Uncaught SyntaxError: Cannot use import statement outside a module (at app.js:1:1)

How to disable typescript check for whole project in an Angular?

I want to disable the type check for whole project and my for my use case I cannot use commands meant for disabling it for each file/line like // @ts-nocheck etc.

It will be better If I can use some config option that can be added in tsconfig.json

I tried below options but none of them worked

"compilerOptions": {
"noImplicitAny": false,
"strict": false,
"noEmitOnError": true,
"checkJs": false,
}

"linteroptions": {
"exclude": ["src/**"],
}

"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": false,
"strictInputAccessModifiers": true,
"strictTemplates": false
},

Disabling Extentions [closed]

I’m needing help disabling certain filter extentions on my school chromebook, would there be a way to use a javascript to remove them or allow me to access certain sites without having it blocked?

I’ve looked at other posts on here but it doesnt seem to work, I had a script that allowed me to “Switch off” the extentions but it ended up not working.

Express.js large file download freezes / hangs

I’m having some trouble with downloading large CSV files from a Node.js Express server, which freezes / hangs at times in the browser. I’m using the res.sendFile() function on the server (using res.download also yields the same issue). The network tab does not report any errors when the download is triggered in the browser. Is there anything important that I’m missing here?

Server-side js:

        try {
            res.setHeader('Content-type', 'text/csv');
            res.setHeader("Content-Disposition", `attachment;filename=${filename}`);
            res.sendFile(filename); 
        }
        catch (e) {
            console.log(e);
            res.send(e).end(); //ERROR
            return;
        }

Client js:

let anchorElement = document.createElement('a');
anchorElement.href = '/report/' + report_id + '/download';
anchorElement.download = export_filename;
anchorElement.target = '_blank';
document.body.appendChild(anchorElement);
anchorElement.click();

Chrome:

Chrome

Firefox:

Firefox

Double login issue after logout after following documentation

I’m trying to follow the Expo documentation for the Authentication process: https://docs.expo.dev/router/reference/authentication/#example-authentication-context .

I have basically copy-pasted everything in the documentation.

The login flow works as intended, with the context provided as the documentation says — the only change I’ve made is for the Sign-In function. The Sign-in function calls an API, retrieve the JSON and then save the whole data into the session:

    return (
    <AuthContext.Provider
        value={{
            signIn: async (username, password) => {
                await AuthResp(username, password).then((promise) => {
                    if (promise) {
                        const sessionDecode = JSON.parse(promise)
                        console.log(sessionDecode.usr_type)

                        switch (sessionDecode.usr_type) {
                            case "usr":
                                router.replace({pathname: `/user`})
                                break;
                            case "admin":'
                                router.replace({pathname: `/admin`})
                                break;
                        }
                    }
                })
            },

            signOut: () => {
                setSession(null)
            },

            session,
            isLoading,
        }}>
        {props.children}
    </AuthContext.Provider>
);

const AuthResp = async(username, password) => {
    console.log(`Trying login for ${username}:${password}...`)
    let userSessionJSON = null

    try {
        const knackPromise = await fetch(`APILINK`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                "email": username,
                "password": password
            })
        })

        await knackPromise.json().then(async (promise) => {
            console.log(promise.session)
            if (promise) {
                if (promise.errors && promise.errors[0]) {
                    alert(promise.errors[0].message)
                } else {
                    const userSessionData = {
                        //sessionData
                    }
                    userSessionJSON = JSON.stringify(userSessionData)
                    await SecureStore.setItemAsync("session", userSessionJSON).then( () => {
                        setSession(userSessionJSON)
                    })
                }
            }
        });

        setSession(userSessionJSON)
        return userSessionJSON

    } catch (error) {
        alert(error)
        console.error(error)
    }
}

This works as intended, but I have some issues when the user decides to log-out. When the log-out button is pressed, the session is deleted as intended. However, when the user then decide to log-in again, the session is always “null” the first time and it requires to login again, then it redirect as normal. I’m not sure where I’m going wrong, but I’m quite sure this is some async function I’ve messed up.

What am I doing wrong?

(please ignore the multiple “setSession” i’ve put in the code, it was just for testing)