Halving processing speed inside of a FOR loop

In JavaScript I have a simple function I used to reverse a string, but my trainer at work says that I can cut the processing time in half within my for loop. My trainer doesn’t want me to use the split/reverse/join functions. So that is why I am doing this in a for loop.

At first I thought using the charAT() function was the best way to achieve this, then I switched to just using brackets + the index position.

Currently scratching my head on how to make this more optimal and am wondering if it is maybe not a problem of the contents of the for loop, but maybe how I structured it in the first place?

function reversalFunct(initString) {

   let reverseString = '';

    for (let i = initString.length - 1; i >= 0; i--){
        reverseString += initString[i];
       
    }
    

    return reverseString;
  
}

What language/library should I use for a graphing calculator project?

For some background, I am a rising sophomore CS major. I have a decent knowledge of Java, Python, html/css and js. This will be my first completely independent project.

I’ve been working on building a desmos-style graphing calculator passively for about a year, and have rewritten it a couple times from the ground up in python with tkinter. The approach I used was plotting discrete points as opposed to lines, because I want it to be able to graph stuff like the logistic map in the future.

Each iteration in python ended up being too slow, or runs into some problem with plotting new points with different zoom levels. I know python is pretty slow, so I suppose this would be a good excuse to learn c++, but I am also in the process of building a portfolio website and it would be nice to build it in JS so it could be easily displayed on there. I want to finish this project for good this summer, so any other perspectives and advice would be appreciated.

I am also not entirely sure this is the right/best place to ask this type of question, so if it isn’t I would appreciate a suggestion for where to ask it.

How do I remove “GMT+0500 (Pakistan Standard Time)” and change the format of date & time on google docs?

I am bulk creating google documents from a google sheet. The date & time are being added onto the google document in a different format with “GMT” added, compared to the google sheets.
Google sheets: [Sat], February 4, 2023 at 8:34PM
Google document: Sat Feb 04 2023 20:34:37 GMT+0500 (Pakistan Standard Time)

My desired outcome is for the exact format of the google sheets:” [Sat], February 4, 2023 at 8:34PM ”
to be copied into the google documents as it bulk creates them. Please not that I do not want to post the current time, only the time that is mentioned in google sheet.

The coding coding for the google sheet [for LOGEVENT.GS]:
function logEvent(action) {

// get the user running the script
var theUser = Session.getActiveUser().getEmail();

// get the relevant spreadsheet to output log details
var ss = SpreadsheetApp.getActiveSpreadsheet();
var logSheet = ss.getSheetByName(‘Log’);

// create and format a timestamp
var dateTime = new Date();
var timeZone = ss.getSpreadsheetTimeZone();
var niceDateTime = Utilities.formatDate(dateTime, timeZone, “dd/MM/yy @ HH:mm:ss”);

// create array of data for pasting into log sheet
var logData = [niceDateTime, theUser, action];

// append details into next row of log sheet
logSheet.appendRow(logData);

}

I am new to google scripts, so I don’t know exactly how to code this according to this sheet.
Thankyou!

typeorm generating wrong migrations files

I ask him to create the migration based on my entity and the sql code of the migration seems normal, but when I migrate he creates a table called migrations and with the columns id, name, timestamp. So that’s not what I’m asking

I tried reverting migrations, asking gpt chat for help but nothing.

How to call mongoose static method using get router

I have been trying to use a mongoose static method for my model to route it using get method but I can not find out how to do this.

Here is my model written in JS:

const mongoose = require('mongoose')
const ShelterSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    address: {
        city: {
            type: String,
            required: true
        },
        addressDetail: {
            type: String,
            required: true
        }
    },
    maxCapacity: {
        type: Number,
        required: true
    },
    residents: [{
        type: mongoose.SchemaTypes.ObjectId,
        ref: 'Survivor',
        autopopulate: {
            maxDepth: 1
        }
    }]
})

ShelterSchema.plugin(require('mongoose-autopopulate'))

ShelterSchema.statics.showAvailableShelters = function () {
    return ShelterModel.find({
        maxCapacity: { $gt: this.residents.length }
    })
}

const ShelterModel = mongoose.model('Shelter', ShelterSchema)

module.exports = ShelterModel 

Here is the get router for show-available-shelters that I need to use my static method which I can not find out how:

const express = require('express')
const router = express.Router()

const ShelterService = require('../services/shelter-service')

router.get('/all', async (req, res) => {
    const shelters = await ShelterService.findAll()
    res.render('shelter', { shelters })
})
router.get('/show-available-shelters', async (req, res) => {
    // res.send(availableShelters) ??
})

How to enable CORS when using the MARS REST API Library with Delphi?

I made a very simple API with a very simple POST endpoint using the MARS-Curiosity Delphi REST Library and my endpoint is working perfectly fine in Postman, but as soon as I try to use the endpoint in JavaScript, then I get a CORS policy error.

Here’s exactly what I get:

Access to fetch at ‘http://localhost:8080/rest/person/profile/get’ from origin ‘http://localhost’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

POST http://localhost:8080/rest/person/profile/get net::ERR_FAILED 200 (OK)

Access to fetch at 'http://localhost:8080/rest/person/profile/get' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I suspect this is because I don’t have CORS Enabled in my Delphi MARS REST API, but how and where do I enable this?


For some added info, this is my exact code used to do the JavaScript Fetch:

const requestOptions = {method: 'POST'};

fetch("http://localhost:8080/rest/person/profile/get", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

React setState function don’t update state in useEffect hook [duplicate]

I have an issue that useEffect function call works as should until it face setState function.

useEffect(() => {
    transformVisitsRequests();
  }, []);

I even exaggerated a bit the code with Promise.resolve() but I wanted to make sure that each line is updated with fully calculated data.

const transformVisitsRequests = async () => {
    await visit.loadVisits({ page: 1 });

    const visitsData = toJS(visit.visits);
    console.log('visitsData', visitsData);

    const data = visitsData?.filter((singleVisit) => singleVisit.visitRequest.status === 'PAID');
    console.log('data', data);

    await Promise.resolve();
    setPaidVisits(data);

    await Promise.resolve();
    console.log('paidVisits', paidVisits);
  };

console.log(visitsData) and console.log(data) shows me properly calculated data, but console.log(paidVisits) show empty array, so state update is not called.

const [paidVisits, setPaidVisits] = useState<IVisit[] | undefined>([]);

Terminal don’t throw me any error.

Can You please suggest how this issue should be solved and state will update as it should ?

thanks

validate dynamic form of inputs

i have this problem with dynamic inputs all inputs with name txt attribute are supposed to
with the add button it adds these input dynamically

for what is appreciated, it does not show the message “empty fields” every time the button is clicked.

each time an empty field is found, focus should be placed on the empty input.

si estan todos los inputs con datos este debiese ejecutar el mensaje todos los campos llenos.

// Constantes para el div contenedor de los inputs y el botón de agregar
const contenedor = document.querySelector('#dinamic');
const btnAgregar = document.querySelector('#agregar');

// Variable para el total de elementos agregados
let total = 1;

/**
 * Método que se ejecuta cuando se da clic al botón de agregar elementos
 */
btnAgregar.addEventListener('click', e => {
  let div = document.createElement('div');
  div.innerHTML = `<label>${total++}</label> - <input type="text" name="nombre[]" placeholder="Nombre" required><button onclick="eliminar(this)">Eliminar</button>`;
  contenedor.appendChild(div);
})

/**
 * Método para eliminar el div contenedor del input
 * @param {this} e 
 */
const eliminar = (e) => {
  const divPadre = e.parentNode;
  contenedor.removeChild(divPadre);
  actualizarContador();
};

/**
 * Método para actualizar el contador de los elementos agregados
 */
const actualizarContador = () => {
  let divs = contenedor.children;
  total = 1;
  for (let i = 0; i < divs.length; i++) {
    divs[i].children[0].innerHTML = total++;
  } //end for
};


function ValidarVacios() {
  var f = document.forms['form1'];
  var text = "";
  var alerta = false;

  for (var i = 0; i <= parseInt(f.numTexts.value); i++) {

    text = 'txt'
    if (([text] + '.value') == '') {
      alerta = true;
    }
  }
  if (alerta == true) {
    alert('Campos Vacios');
    return false;
  } else {
    return true;
  }
}
<!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>Inputs dinámicos</title>
</head>

<body>
  <button id="agregar">Agregar</button>
  <div id="dinamic"></div>


  <input type="submit" value="Pik 1" onclick="javascript:ValidarVacios();">
  <script src="./main.js"></script>
</body>

</html>

It works halfway if I add 5 times the 4th is null, it is the closest thing to dynamic input

var counter = 0;

function addInput(divName) {
  counter++;
  var Ai8ousa = document.createElement('div');
  Ai8ousa.innerHTML = "Field: " + (counter + 1) + "<input type='text' name='field[]'>";
  document.getElementById(divName).appendChild(Ai8ousa);

}

function validations(form) {
  var field;
  var i = 0;
  do {
    field = form[i];
    if (field.value == '') {
      alert('The field is null!!!');
      return false;
    }
    i++;
  } while (i < counter);
}
<form action="" method="post" onsubmit="return validations(this)">
  <div id="dynamicInput">
    Field : <input type="text" name="field[]" /> <br />
  </div>
  <input type="button" value="New field" onClick="addInput('dynamicInput');">
  <input type="submit" value="Submit" />

</form>

Using duckdb in node.js not able to close database — Error: IO Error: Cannot open file “./foobar.db”

I would really like to use duckdb instead of sqlite3 in a project I am working on, but I have hit a snag I can’t solve. Sqlite promise is fulfilled and db.close() closes the database but Duckdb promise remains pending and db.close() seems to do nothing.

What works:

//In Back End 

import Database from 'better-sqlite3'

globalThis.myRecords = async function () {
  const db = await new Database('./foobar.db')
  const rows = await db.prepare('select * from names').all()
  db.close()
  return rows
}
//In FrontEnd

globalThis.myRecords()
 .then((res) => {
   console.log(res)
})

//In browser console

(2)[{...},{...}]  //got two records yeah!!
Promise {<fullfilled>} 

Note: If I call the same function again I get the same result as expected.


What doesn’t work:

import { Database } from 'duckdb-async'

globalThis.familyRecord2 = async function () {
  const db = await Database.create('./foobar2.db')
  const rows = await db.all('select * from names')
  db.close()
  return rows
}
//In FrontEnd

globalThis.myRecords()
 .then((res) => {
   console.log(res)
})

//In browser console

(2)[{...},{...}]  //got two records yeah!!
Promise {<pending>} // <-- Why is this pending?

Note: If I call the same function again I get the following error as well

Error: IO Error: Cannot open file "./foobar2.db": The process cannot access the file because it is being used by another process.

The only way to close the database is to stop and restart node/server

payload failing at DTO level – nest js

I have an incoming payload like below:

{
“name”: “time”,
“value”: {
“from”: “USD”,
“to”: “CAD”
}
}

but it is not being validated getting destructor error that from does-not exist data basically contructor unable to get value

this is what i have at controller level

  @UsePipes(new ValidationPipe({
    transform: true
  }))
  @UseFilters(new GeneralExceptionFilter())
  public async checkPayload(
    @RabbitPayload() payload: RateDto,
  ): Promise < void > {

  }

Following is my dto which is RateDto

export class RateDto {
    @IsNotEmpty()
    @IsString()
    public name: string;

    @ValidateNested()
    @IsObject()
    @Type(() => Pair)
    value: Pair;
}

export interface PairType {
    from: string;
    to: string;
}

export class Pair {

    @IsString()
    @IsNotEmpty()
    @Length(3, 3)
    from: string;

    @IsString()
    @IsNotEmpty()
    @Length(3, 3)
    to: string;

    constructor(data: PairType) {
        const {
            from,
            to
        } = data;
        console.log(from);
        this.from = from;
        this.to = to;
    }
 }

sending events to GA4 before calling config now causes the configuration to fail

attempting to report data to a tracker before its configured has started producing an error.

i have some plugins that report based on a GA tracker ID, i also install that tracker on my site. the problem is that if any plugin produces an event before the tracker is configured, gtag.js adds a separate https://www.googletagmanager.com/gtag/destination?id=G-XXX tag to the page, and then when the actual tracker config gets called, the script https://www.googletagmanager.com/gtag/js?id=G-XXXX which gets added then produces an error: Duplicate container installation abandoned: G-XXX and does nothing.

i’m pretty sure this was not causing an error a few weeks ago.

i have tried both settings for the “Additional Settings” > “ignore duplicate instances of on-page configuration (recommended)” option, it doesn’t seem to be related to this issue.

this code produces the issue:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  const trackerId = 'G-XXXXX'

  gtag('event', 'test', {send_to: trackerId})
  gtag('config', trackerId);
</script>

<script async src="https://www.googletagmanager.com/gtag.js"></script>

(in real life i’m not controlling where the events are coming from, and the config call is being done in GTM. the code does occasionally pass, i think there is a race condition having to do with the injected scripts loading)

i’m going to try to organize it so the plugins are only loaded after the tracker is configured, but i’m pretty sure this used to work, and it seems really problematic that it happens like this. for instance one of the plugins causing the issue is google optimize, which is installed according to the instructions.

is there something i can do to make it just reconfigure the tracker and not error when config is called?

PHP Dom to map html classes

i am learning PHP and i want to ask , what is the best solution to map HTML class names with new classes from JSON files

<div class="class1 class2 class3"></div>

to be like

<div class="newclass1 newclass2 newclass3"></div>

i used JS but there’s a delay of applying the styles since i didn’t want to change the original class names in my code , and i want the new classes be generated in the client, and i need to know if using PHP Dom will be effective and fast for many elements? or there’s another Solution!!