TensorFlow.js model history being malformed after model save checkpoint

I have been experimenting with TensorFlow.js in a node.js application. I have a dataset of 8000 images I am using for training, and I ran into some memory limitations. I am trying to set up my program such so that it saves the model after X number of iterations, so if (when) it runs out of memory at least I have saved the results of some of the run.

If I define 6 epochs, it should run 3, save where it’s at, and then continue training. It will run for the first 3, save the model, but then when it passes over ‘history’ something isn’t right and it errors out. The error is in the validateModel function, where it’s trying to access the .acc property of the history object but it’s not there so it stops. Logging the model before and after, it drops the properties even though it just loaded in the model it just saved.

Initially I was compiling the model during every iteration of the for loop, but I added an if statement that should only compile it once. I get the same error afterwards, and from the log I can see that it is just not retaining the learning from the previous epochs. I’ve messed with scope of the history variable, removing layers, reducing batch size and different ones of those parameters, have not been able to get it to continue after a save point. I am using the rsmprop optimizer. Thanks in advance, I’m at my wits end trying to get this to work.

This is the log output:

Checking for model at: C:Usersaldasnode.js projectsaved_modelmodel.json
Loading existing model
Layer name: conv2d_Conv2D1
Input shape: undefined
Output shape: [null,148,148,32]
Layer name: max_pooling2d_MaxPooling2D1
Input shape: undefined
Output shape: [null,74,74,32]
Layer name: conv2d_Conv2D2
Input shape: undefined
Output shape: [null,72,72,64]
Layer name: max_pooling2d_MaxPooling2D2
Input shape: undefined
Output shape: [null,36,36,64]
Layer name: dropout_Dropout1
Input shape: undefined
Output shape: [null,36,36,64]
Layer name: flatten_Flatten1
Input shape: undefined
Output shape: [null,82944]
Layer name: dense_Dense1
Input shape: undefined
Output shape: [null,125]
Layer name: dense_Dense2
Input shape: undefined
Output shape: [null,97]
Epoch 1 / 3
eta=0.0 ========================================================================>
347004ms 174286us/step - acc=0.0545 loss=4.41 
Epoch 2 / 3
eta=0.0 ========================================================================>
394713ms 198249us/step - acc=0.0545 loss=4.38 
Epoch 3 / 3
eta=0.0 ========================================================================>
412389ms 207126us/step - acc=0.0545 loss=4.35 
Layer name after: conv2d_Conv2D1
Input shape after: undefined
Output shape after: [null,148,148,32]
Layer name after: max_pooling2d_MaxPooling2D1
Input shape after: undefined
Output shape after: [null,74,74,32]
Layer name after: conv2d_Conv2D2
Input shape after: undefined
Output shape after: [null,72,72,64]
Layer name after: max_pooling2d_MaxPooling2D2
Input shape after: undefined
Output shape after: [null,36,36,64]
Layer name after: dropout_Dropout1
Input shape after: undefined
Output shape after: [null,36,36,64]
Layer name after: flatten_Flatten1
Input shape after: undefined
Output shape after: [null,82944]
Layer name after: dense_Dense1
Input shape after: undefined
Output shape after: [null,125]
Layer name after: dense_Dense2
Input shape after: undefined
Output shape after: [null,97]
{
  "validationData": null,
  "params": {
    "epochs": 3,
    "initialEpoch": null,
    "samples": null,
    "steps": null,
    "batchSize": null,
    "verbose": 1,
    "doValidation": false,
    "metrics": [
      "loss",
      "acc"
    ]
  },
  "epoch": [
    0,
    1,
    2
  ],
  "history": {
    "loss": [
      4.406312465667725,
      4.3756232261657715,
      4.34819221496582
    ],
    "acc": [
      0.05450892075896263,
      0.05450892075896263,
      0.05450892075896263
    ]
  }
}
Model improved. Saving model at epoch 3
Checking for model at: C:Usersaldasnode.js projectsaved_modelmodel.json
Loading existing model
[nodemon] restarting due to changes...
Layer name: conv2d_Conv2D1
Input shape: undefined
Output shape: [null,148,148,32]
Layer name: max_pooling2d_MaxPooling2D1
Input shape: undefined
Output shape: [null,74,74,32]
Layer name: conv2d_Conv2D2
Input shape: undefined
Output shape: [null,72,72,64]
Layer name: max_pooling2d_MaxPooling2D2
Input shape: undefined
Output shape: [null,36,36,64]
Layer name: dropout_Dropout1
Input shape: undefined
Output shape: [null,36,36,64]
Layer name: flatten_Flatten1
Input shape: undefined
Output shape: [null,82944]
Layer name: dense_Dense1
Input shape: undefined
Output shape: [null,125]
Layer name: dense_Dense2
Input shape: undefined
Output shape: [null,97]
Layer name after: conv2d_Conv2D1
Input shape after: undefined
Output shape after: [null,148,148,32]
Layer name after: max_pooling2d_MaxPooling2D1
Input shape after: undefined
Output shape after: [null,74,74,32]
Layer name after: conv2d_Conv2D2
Input shape after: undefined
Output shape after: [null,72,72,64]
Layer name after: max_pooling2d_MaxPooling2D2
Input shape after: undefined
Output shape after: [null,36,36,64]
Layer name after: dropout_Dropout1
Input shape after: undefined
Output shape after: [null,36,36,64]
Layer name after: flatten_Flatten1
Input shape after: undefined
Output shape after: [null,82944]
Layer name after: dense_Dense1
Input shape after: undefined
Output shape after: [null,125]
Layer name after: dense_Dense2
Input shape after: undefined
Output shape after: [null,97]
{
  "validationData": null,
  "params": {
    "epochs": 3,
    "initialEpoch": null,
    "samples": null,
    "steps": null,
    "batchSize": null,
    "verbose": 1,
    "doValidation": false,
    "metrics": [
      "loss",
      "acc"
    ]
  },
  "epoch": [],
  "history": {}
}
An error occurred validateModel: TypeError: Cannot read properties of undefined (reading 'length')
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
2023-11-01 18:05:46.521366: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Server running on http://localhost:3000

Here is my training endpoint and variable declarations:

const IMAGE_WIDTH = 150;
const IMAGE_HEIGHT = 150;
const BATCH_SIZE = 4; // Number of images? used per session/layer?
const chunkSize = 3; // Number of epochs to run before saving a checkpoint
const totalEpochs = 6; // Total number of iterations to run
const LEARNING_RATE = 0.001; // Original/default value is .0001
// const optimizer = tf.train.adam(LEARNING_RATE);  Best results: .06 accuracy
//const optimizer = tf.train.sgd(LEARNING_RATE); not used yet
const optimizer = tf.train.rmsprop(LEARNING_RATE);
const SAVE_PATH = 'file://C:/Users/aldas/node.js project/saved_model';


const trainingDir = 'C:\Users\aldas\node.js project\image_dump';
const { images, labels } = readAndLabelImages(trainingDir);


let NUM_CLASSES, model, speciesLabels, labelIndex, lastEpochAcc, history;



app.post('/train', async (req, res) => {
  try {

    let bestValidationMetric = 0; 
    const stepsPerEpoch = Math.ceil(images.length / BATCH_SIZE);

    for (let startEpoch = 1; startEpoch <= totalEpochs; startEpoch += chunkSize) {
      // console.log('Memory info at start of chunk:', tf.memory());

      const localSavePath = SAVE_PATH.replace('file://', '');
      const checkPath = path.join(localSavePath, 'model.json');
      console.log(`Checking for model at: ${checkPath}`);
      if (fs.existsSync(checkPath)) {
        console.log('Loading existing model');
        model = await tf.loadLayersModel(`${SAVE_PATH}/model.json`);
        if (!model.optimizer){ // If optimizer attached, good sign model was compiled already. Only compile once
          await compileModel();
        }
      } else {
        console.log('No existing model found, using a new one');
        await initializeModel();
      }


        try {
        ds = tf.data.generator(() => imageBatchGenerator(images, labels)); 

        model.layers.forEach(layer => {
          console.log(`Layer name: ${layer.name}`);
          console.log(`Input shape: ${JSON.stringify(layer.inputShape)}`);
          console.log(`Output shape: ${JSON.stringify(layer.outputShape)}`);
        });
        

        history = await model.fitDataset(ds, {
          epochs: chunkSize,
          initialEpoch: startEpoch - 1,
          stepsPerEpoch: stepsPerEpoch
        });

        model.layers.forEach(layer => {
          console.log(`Layer name after: ${layer.name}`);
          console.log(`Input shape after: ${JSON.stringify(layer.inputShape)}`);
          console.log(`Output shape after: ${JSON.stringify(layer.outputShape)}`);
        });
        

        // Validate
        console.log(JSON.stringify(history, null, 2))
        const currentValidationMetric = await validateModel(history);
              
          // Check if we should save this model
          if (currentValidationMetric > bestValidationMetric) {
            bestValidationMetric = currentValidationMetric;
            await model.save(SAVE_PATH);
            console.log(`Model improved. Saving model at epoch ${startEpoch + chunkSize - 1}`);
          }

        } catch (err) {
          console.error(`An error occurred history: ${err}`);
        }
        
        }
        // Save the labelIndex to a JSON file
  fs.writeFileSync(path.join(__dirname, '/saved_model/speciesLabels.json'), JSON.stringify(labelIndex));
  

    
    res.json({ status: 'Training complete', code: 0 });
  } catch (err) {
    console.error(`An error occurred: ${err}`);
    res.json({ status: 'Training failed', code: 1, error: err.message });
  }
});


async function validateModel(history) {
  // Assume the last epoch's accuracy is the final element in the history object

  try {
  lastEpochAcc = history.history.acc[history.history.acc.length - 1];
  
  return lastEpochAcc;
  } catch (err) {
    console.error(`An error occurred validateModel: ${err}`);
  }

}

async function* imageBatchGenerator(imagePaths, labels) {
  let index = 0;
  // console.log('imagePaths length: ', imagePaths.length)
  // console.log('labels length: ', labels.length)
  while (index < imagePaths.length) {
      const batchImagePaths = imagePaths.slice(index, index + BATCH_SIZE);
      const batchLabels = labels.slice(index, index + BATCH_SIZE);

      const imageTensors = (await Promise.all(batchImagePaths.map(async (imgPath, i) => {
          const parsedResult = await parseImage(imgPath, batchLabels[i]);
          return parsedResult ? parsedResult.xs : null;
      }))).filter(tensor => tensor !== null);

      const xsBatch = tf.stack(imageTensors);

      imageTensors.forEach(tensor => tensor.dispose());

    
      const validLabelIndices = batchLabels.slice(0, imageTensors.length).map(label => labelIndex[label]);
      const ysBatch = tf.oneHot(validLabelIndices, NUM_CLASSES);

      yield { xs: xsBatch, ys: ysBatch };

      //ysBatch.dispose();

      index += BATCH_SIZE;
  }
}

Cannot retrieve images from Mysql to show on html menu section

I am working on an e-commerce website and I’m having trouble displaying images from mysql database to be rendered in my html products section, as a newbie to programming, I’d like this explained to me in the most easiest way possible, here is my html loop that is in charge of displaying the images from mysql.

<div class="row special-list">
        <% result.forEach(function(product) { %>
        <div class="col-lg-3 col-md-6 special-grid best-seller">
          <div class="products-single fix">
            <div class="box-img-hover">
              <div class="why-text">
                <h4><%= product.name %></h4>
                <h5>Ksh <%= product.price %>.00</h5>
                <form id="add-to-cart-form-<%= product.id %>" class="add-to-cart-form" data-product-id="<%= product.id %>">
                  <input type="hidden" name="product_id" value="<%= product.id %>">
                  <input type="hidden" name="product_name" value="<%= product.name %>">
                  <input type="hidden" name="product_price" value="<%= product.price %>">
                  <input type="hidden" name="product_sale_price" value="<%= product.sale_price %>">
                  <input type="hidden" name="product_quantity" value="1" min="1">
                  <input type="hidden" name="product_image" value="<%= product.image %>">
                  <button type="button" class="btn btn-primary add-to-cart-button" data-product-id="<%= product.id %>">Add to Cart</button>
                </form>
                <div class="add-to-cart-success-message" style="display: none;">
                  Item added to the cart
                </div>
              </div>
              <img src="/images/<%= product.image%>.jpg" alt="<%= product.name %>">
            </div>
          </div>
        </div>
        <% }); %>
      </div>

I have tried setting up static file to use my public folder in my server:

app.use(express.static(path.join(__dirname, 'public')));

Here is where my image is hosted and this is the link I have in mysql database:
http://localhost/images/blog-img-02.jpg

is there a node.js lib/package that allows me to generate an executable python file?

So, I’ve got this web project in which a user inputs some info to a form and a python file is generated containing that info.

What I want to do is send that file to my node.js server so that it transforms it into an executable python file, containing it’s dependencies, and sends it back to the user so he can download it. With that said, is there any library/package that allows me to do that with Node.Js?

ps: I am also considering using Django instead of Node.Js if it turns out to be too complicated or less efficient than Django.

How to transfer data through a props function on React?

I’m working with a code that was written by a front-end developer and am trying to figure out how to transfer some data to open a pop-up menu with.

I want to transfer item.name to the opening Modal

I want to use that data for SHOP ITEM NAME

I am not super experienced with React so the only choice seemed like making that modal a child and transfer the data through that but would love to hear it in case there is a shorter way to it.

error (cannot read properties of undefined (reading state)) add this.state.a in render()

import React from “react”;

import Tovars from ‘./tovar’

export default class Tovar extends React.Component{
constructor(props){
super(props)
this.state={
a:true
}

}
render() { 
    const classtovars = new Tovars()
    const Tovar = classtovars.render
    return (
        <>
        {this.state.a}
        <h1>Product Shop</h1>
            <table>
                <tr>
                    <th>Product</th>
                    <th>Price</th>
                    <th>Image</th>
                    <th>Quantity</th>
                    <th>Control</th>
                </tr>
                
                <Tovar /> 
                
            </table>
        </>
    )     
}

}

I get different result for stack method and recursion method in dfs implementation

/* adj matrix */
const MAX = 50;
class GraphType {
  constructor() {
    this.n;
    this.adj_mat = new Array(MAX)
    this.visited = new Array(MAX)

    for (let i = 0; i < MAX; i++) {
      this.adj_mat[i] = new Array(MAX);
      this.visited[i] = false;
    }

  }
  Init() {
    this.n = 0;
    for (let i = 0; i < MAX; i++) {
      for (let j = 0; j < MAX; j++) {
        this.adj_mat[i][j] = 0;
      }
    }
  }
  Insert() {
    if (this.n + 1 > MAX) {
      return -1;
    }
    this.n++;
  }
  InsertEdge(start, end) {
    if (start >= this.n || end >= this.n)
      return;

    this.adj_mat[start][end] = 1;
    this.adj_mat[end][start] = 1;
  }
  PrintMat() {
    for (let i = 0; i < this.n; i++) {
      process.stdout.write(i + ": ");
      for (let j = 0; j < this.n; j++)
        process.stdout.write(this.adj_mat[i][j] + " ");
      console.log();
    }
  }
  dfsMat(v) {
    if (v < 0 || v >= this.n) return;
    this.visited[v] = true;
    process.stdout.write(v + " -> ");

    for (let i = 0; i < this.n; i++)
      if (this.adj_mat[v][i] && !this.visited[i])
        this.dfsMat(i);
  }
  dfsMatStack(v) {
    let stack = [];

    stack.push(v);
    while (stack.length > 0) {
      let c = stack.pop();
      if (!this.visited[c]) {
        this.visited[c] = true;
        process.stdout.write(c + " -> ")
        for (let i = 0; i < this.n; i++)
          if (this.adj_mat[c][i] === 1 && !this.visited[i])
            stack.push(i);
      }

    }
  }
}
let graph = new GraphType();

graph.Init();
for (let i = 0; i < 4; i++)
  graph.Insert();

graph.InsertEdge(0, 1);
graph.InsertEdge(0, 2);
graph.InsertEdge(0, 3);
graph.InsertEdge(1, 0);
graph.InsertEdge(1, 3);
graph.InsertEdge(2, 0);
graph.InsertEdge(2, 3);
graph.InsertEdge(3, 0);
graph.InsertEdge(3, 1);
graph.InsertEdge(3, 2);

graph.PrintMat();

graph.dfsMat(0);
//graph.dfsMatStack(0);

dfs using rescursion and stack. is it normal to have different result?
dfsMat and dfsMatStack should produce same result right?

I tried to implement dfs that traverse a graph. I used both stack and recursion but those two function produce difference result

so graph looks like this

0: 0 1 1 1              0
1: 1 0 0 1           /  |  
2: 1 0 0 1          1   |   2
3: 1 1 1 0             |  /
                        3

when i use dfsMat(0)
0 -> 1 -> 3 -> 2 ->
when i use dfsMatStack(0)
0 -> 3 -> 2 -> 1 ->

is this normal?

Planets with mouse click function didn’t work

I have the following problem with the mouse click function as it didn’t work correspond to the function click. When I click to the planet, it just randomly shows different planet and the data information didn’t show correctly as well. Can someone please help? You can access all the file through this: https://github.com/vlam7/planets

I think part of mouseClicked function didn’t right and since because the planet is overlapping for one and each other and also moving in a circle. That might a reason it isn’t working?

let numPlanets = 11; // Number of planets
let radius = 400; // Set a larger radius for the circular orbit to increase spacing
let planetTextures = [];
let planetAngles = [];
let isRotating = true;
let saturnRingsTexture;
let data;
let url = "Solar System data.csv";
let planetSizes = [];
let expandedPlanet = -1;
let planetVisible = [];
let planetInfoDiv; // Div element for displaying planet information
let typewriterSpeed = -1; // Typing speed in milliseconds
let typewriterIndex = 10;
let planetInfoText = "";

function preload() {
  // Load planet textures
  planetTextures[0] = loadImage("Earth.jpg");
  planetTextures[1] = loadImage("Mars.png");
  planetTextures[2] = loadImage("Mercury.jpg");
  planetTextures[3] = loadImage("Jupiter.jpg");
  planetTextures[4] = loadImage("Venus.jpg");
  planetTextures[5] = loadImage("Sun.jpg");
  planetTextures[6] = loadImage("Saturn.jpg");
  planetTextures[7] = loadImage("Uranus.jpg");
  planetTextures[8] = loadImage("Neptune.jpg");
  planetTextures[9] = loadImage("Pluto.jpg");
  planetTextures[10] = loadImage("Moon.jpg");

  saturnRingsTexture = loadImage("Saturn Ring.png");
  data = loadTable(url, 'csv', 'header');
}

function setup() {
  createCanvas(window.innerWidth, window.innerHeight, WEBGL);
  noStroke();

  for (let i = 0; i < numPlanets; i++) {
    let angle = (TWO_PI / numPlanets) * i;
    planetAngles.push(angle);
    planetSizes.push(70);
    planetVisible.push(true);
  // Create a div element for displaying planet information
  planetInfoDiv = createDiv('');
  planetInfoDiv.position(width / 2 + 20, 270);
  planetInfoDiv.style('color', 'white');
  planetInfoDiv.style('font-size', '16px');
}
}

function draw() {
  background("rgba(0, 0, 0, 0)");
  orbitControl();

  if (isRotating) {
    for (let i = 0; i < numPlanets; i++) {
      planetAngles[i] += 0.005;
    }
  }

  for (let i = 0; i < numPlanets; i++) {
    if (planetVisible[i]) {
      push();
      let x = radius * cos(planetAngles[i]);
      let z = radius * sin(planetAngles[i]);

      translate(x, 0, z);
      rotateY(planetAngles[i]);

      if (i === expandedPlanet) {
        texture(planetTextures[i]);
        sphere(500, 500, 500);
      } else if (i === 6) {
        texture(planetTextures[i]);
        sphere(planetSizes[i]);
        texture(saturnRingsTexture);
        rotateX(PI / 2 + radians(20));
        scale(1, 1, 0.1);
        torus(120, 35, 48, 10);
      } else {
        texture(planetTextures[i]);
        sphere(planetSizes[i]);
      }
      pop();
    }
  }
}

function mouseClicked() {
  let clickX = mouseX - width / 2;
  let clickY = mouseY - height / 2;
  let distanceFromCenter = dist(0, 0, clickX, clickY);

  if (expandedPlanet !== -1) {
    // Close the expanded planet view
    planetVisible[expandedPlanet] = true;
    expandedPlanet = -1;
    planetInfoDiv.html(''); // Clear the displayed planet information
  } else if (distanceFromCenter <= radius + 200) {
    // Check if the click is within the planet area
    expandedPlanet = getClickedPlanet(clickX, clickY); // Pass clickX and clickY
    for (let i = 0; i < numPlanets; i++) {
      if (i !== expandedPlanet) {
        planetVisible[i] = false;
      }
    }
    if (expandedPlanet !== -1) {
      displayPlanetInfo(data.get(expandedPlanet, 'Name'));
    }
  }
}

function getClickedPlanet(x, y) {
  let closestPlanet = -1;
  let closestDistance = Number.MAX_VALUE;

  for (let i = 0; i < numPlanets; i++) {
    if (planetVisible[i]) {
      // Calculate the current position of the planet
      let angle = planetAngles[i];
      let planetX = radius * cos(angle);
      let planetZ = radius * sin(angle);

      // Reverse the rotation transformation
      let clickXRotated = cos(-angle) * x - sin(-angle) * y;
      let clickYRotated = sin(-angle) * x + cos(-angle) * y;

      // Calculate the distance between the rotated click point and the planet
      let d = dist(planetX, planetZ, clickXRotated, clickYRotated);

      if (d < closestDistance) {
        closestDistance = d;
        closestPlanet = i;
      }
    }
  }

  return closestPlanet;
}

function displayPlanetInfo(planetName) {
  planetName = planetName.toLowerCase().trim();

  let matchedPlanet = data.rows.find((row) => {
    return row.obj.Name.toLowerCase().trim() === planetName;
  });

  if (matchedPlanet) {
    // Clear the div content and initialize variables
    planetInfoDiv.html('');
    typewriterIndex = 0;
    planetInfoText = createPlanetInfoText(matchedPlanet.obj);
    
    // Create a function for the typewriter effect
    function typeWriter() {
      if (typewriterIndex < planetInfoText.length) {
        planetInfoDiv.html(planetInfoText.substring(0, typewriterIndex + 1));
        typewriterIndex++;
        setTimeout(typeWriter, typewriterSpeed);
      }
    }

    // Start the typewriter effect
    typeWriter();
  }
}

function createPlanetInfoText(planetData) {
  let planetInfoHTML = '<b>' + planetData.Name + '</b><br>';
  planetInfoHTML += 'Diameter (miles): ' + planetData['Diameter (miles)'] + '<br>';
  planetInfoHTML += 'Rotation Period (hours): ' + planetData['Rotation Period (hours)'] + '<br>';
  planetInfoHTML += 'Length of Day (hours): ' + planetData['Length of Day (hours)'] + '<br>';
  planetInfoHTML += 'Primary: ' + planetData.Primary + '<br>';
  planetInfoHTML += 'Distance from Primary (10^6 miles): ' + planetData['Distance from Primary (10^6 miles)'] + '<br>';
  planetInfoHTML += 'Perihelion (10^6 miles): ' + planetData['Perihelion (10^6 miles)'] + '<br>';
  // planetInfoHTML += 'Aphelion (10^6 miles): ' + planetData['Aphelion (10^6 miles)'] + '<br>';
  // planetInfoHTML += 'Orbital Period (days): ' + planetData['Orbital Period (days)'] + '<br>';
  // planetInfoHTML += 'Orbital Velocity (miles/s): ' + planetData['Orbital Velocity (miles/s)'] + '<br>';
  // planetInfoHTML += 'Orbital Inclination (degrees): ' + planetData['Orbital Inclination (degrees)'] + '<br>';
  // planetInfoHTML += 'Orbital Eccentricity: ' + planetData['Orbital Eccentricity'] + '<br>';
  // planetInfoHTML += 'Obliquity to Orbit (degrees): ' + planetData['Obliquity to Orbit (degrees)'] + '<br>';
  
  return planetInfoHTML;
}


function keyReleased() {
  if (keyCode === 27) {
    for (let i = 0; i < numPlanets; i++) {
      planetVisible[i] = true;
    }
    expandedPlanet = -1;
    planetInfoDiv.html(""); // Clear the displayed planet information
    clearTimeout(typewriterTimeout); // Stop the typewriter effect
  }
}

let typewriterTimeout; // Declare typewriterTimeout as a global variable

function displayPlanetInfo(planetName) {
  planetName = planetName.toLowerCase().trim();

  let matchedPlanet = data.rows.find((row) => {
    return row.obj.Name.toLowerCase().trim() === planetName;
  });

  if (matchedPlanet) {
    // Clear the div content and initialize variables
    planetInfoDiv.html('');
    typewriterIndex = 0;
    planetInfoText = createPlanetInfoText(matchedPlanet.obj);
    
    // Create a function for the typewriter effect
    function typeWriter() {
      if (typewriterIndex < planetInfoText.length) {
        planetInfoDiv.html(planetInfoText.substring(0, typewriterIndex + 1));
        typewriterIndex++;
        
        typewriterTimeout = setTimeout(typeWriter, typewriterSpeed); // Set typewriterTimeout
      }
    }

    // Start the typewriter effect
    typeWriter();
  }
}

React.js – Images after build don’t show

after npm run build my images dont show in dist folder. In code I have path to images via json file like this:

    {
      "name": "Moon",
      "images": {
        "png": "./src/assets/destination/image-moon.png",
        "webp": "./src/assets/destination/image-moon.webp"
      },
    },

In code it look like this:

            src={data.destinations[i].images.png}
            alt=""
            className="w-44 h-44 my-10"
          />
        </div>

Where can be problem ? In development it run good, but after build images are lost.
That is my folder structure. Images are in folder ./src/assets/destination. JSON file is save in folder constants (data.json). In my app I import data.json and use this paths. Example above.

enter image description here

My JS is not loaded when building with Netlify

My website deployment : https://spiffy-swan-2cdde9.netlify.app
When I build locally and develop locally there is not a problem with loading JS.However when i try to deploy via netlify using the following build command:
parcel build index.html –dist-dir ./dist
my website won’t interact as any of my javascript is not working properly.

https://github.com/RobicaCodeaza/PropertyNexter

I tried to specify the type = ‘module’ and still not an improvement. I downloaded the files separately after deployment and indead JS is not loaded because of the path specification. How would i make it work via netlify in order to find my file that was already built?

Issue with Express.js: CSS and JS files not loading from the ‘public’ folder

I’m currently working on a web project using Express.js, and I’m facing issues with loading CSS and JavaScript files from the ‘public’ folder. I’ve followed the common practices, but it seems something is not working correctly. Here’s the structure of my project:

  • public

    • style.css

    • script.js

  • views

    • index.ejs

    • AboutMe.ejs

    • ContactMe.ejs

  • Other Express.js files (app.js, routes, etc.)

In my EJS templates, I’m linking to my CSS and JavaScript files like this:

<link rel="stylesheet" type="text/css" href="/styles/style.css">
<script src="/scripts/script.js"></script>

But my styles and scripts are not being applied to my pages as expected. I’ve verified the file paths, and everything seems correct.

Is there something specific I need to configure in my Express.js application to make sure the files in the ‘public’ folder are served correctly? I’ve tried various approaches and searched for similar issues but haven’t found a solution yet.

Any guidance or suggestions would be greatly appreciated. If you need more information about my project setup or configuration, please let me know.

Thank you in advance for your help!

What I’ve Tried:

I’ve double-checked the file paths and the file location of my style.css.
I’ve ensured that I’m using the correct path in my EJS templates.
I’ve checked that the express.static middleware is correctly configured.

What I Expect: I expect the CSS styles to be applied to my EJS templates when I load my Express.js app

Django – For a DecimalField with 4 decimal places how to only allow 2 decimal places in the form?

This is my first question on Stack Exchange so please let me know if I could write questions better in future.

I have a django project where the user edits a DecimalField form.
I have created a currency field in my models.py file as follows:

from django.db import models


class Transactions(models.Model):
    transaction = models.DecimalField(max_digits=19,decimal_places=4)

From reading online I’ve read that it’s best to use 4 decimal places not 2 for currency.

When the user needs to edit the field in a form the field displays for example -589.0000, which is confusing for a currency input.

<input type=”number”> element for currency, too many decimal places

I want only two decimal places to show in the input element ie -589.00 even better if the user can’t input more than two decimal places.

This is how I am making the form in the views.py file, I added an onclick attribute testing if javascript could solve this issue, but this isn’t working:

class TransactionsUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):

    model = Transactions
    # form_class = TransactionsUpdateForm
    fields = ['transaction']
    success_url = '/' # Trying to redirect user to the home page after creating a transaction
    def get_form(self):
        form = super().get_form()
        form.fields['transaction'].widget.attrs = {'onclick': 'commas(self)

        return form

template (html) also see the javascript function which isn’t working currently…

{% extends "forecast/base.html" %}
{% load crispy_forms_tags %}
{% load humanize %}
{% block content %}
{{ form.media }}
<div class="content-section">
    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Transaction</legend>
            {{ form|crispy }}
            <script>
               function commas(input){
                   input.value = Number(input.value).toLocaleString();}
            </script>
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Save</button>
        </div>
    </form>
</div>


{% endblock content %}

I know that this is possible with javascript if it’s <input type=”text”> but I would prefer to keep as a number type as when on a phone the number keypad opens automatically. Also, I don’t know how to change the input type from the default “number” to “text”

Connecting fonts using javascript

I want to know if it is possible to include fonts using JavaScript without using libraries

I saw an approximate implementation, but I can’t repeat it. And I noticed that connecting using javascript is more convenient and works faster than using css

SASS: Using @forward and @use, then configuring preprocessorOptions in vite.config.js

I don’t quite understand how to use the scss syntax – @use and @forward.
I have a few problems with this:

Problem 1. I have two folders: 1) src/assets/scss/base and src/assets/scss/util, in each of these folders there is a corresponding scss file, for example, _variables.scss or _container.scss. Then, I create _index.scss in each of these two folders and add there @forward 'variables' and @forward 'container'. Then, in src/assets/scss/main.scss I use @use 'base' as *; and @use 'util' as *;. However, I get an error that one of the variables is not found, as if these instructions don’t work. Where is the mistake?

Problem 2: I also use Vite, and when I used @import instead of @use and @forward before, I had to include all scss files in preprocessorOptions in vite.config.js. But now that I’m using @use and @forward, do I add these options correctly?

export default defineConfig({
    css: {
        preprocessorOptions: {
            scss: {
                additionalData: `@use '@/assets/scss/main' as *;`,
            },
        },
    },
});

Why doesn’t TypeORM skip() and take() function work?

The Delivery table has got more than 4 million rows. I used MySQL database.

async adminDeliveriesViewCount (data) {
 try {
   const batchSize = 10;
   let batchIndex = 0, totalDeliveries = 0;
   while(true) {
     let total = await Delivery.createQueryBuilder().skip(batchIndex * batchSize).take(batchSize)
       .getCount();

     if(total == 0) break;
     totalDeliveries += total;
     ++ batchIndex;
   }

   return totalDeliveries;
 } catch (e) {
   new ErrorHandler(e, 'adminDeliveriesViewCount');
 }
}

This function is not working. The “total” value is always the total number of rows in the table.

I tried changing the “batchSize” and “batchIndex”, but it didn’t help.
Can anyone help me?