SVG filter patterns mix randomly and use as pattern again

I want to blend two SVG patterns randomly inside an SVG filter, and use them as pattern again to fill an element (the only output rectangle). My patterns are sized 12*12. The JavaScript first draws rectangles of size 12*12, then fills each of them with a random pattern, creating a mixed result.

Something wrong with the script. This is the code I tried, problem is they don’t mix together, but fill the whole thing with one of them, randomly changes every time the page is refreshed. No error messages.

The whole HTML code:

const mixedPattern = document.getElementById('mixed-pattern');

function getMixedPattern() {
  const svgNS = "http://www.w3.org/2000/svg";

  // Add rectangles of the patterns(12*12)
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      const rect = document.createElementNS(svgNS, "rect");
      rect.setAttribute("x", i * 3);
      rect.setAttribute("y", j * 3);
      rect.setAttribute("width", "3");
      rect.setAttribute("height", "3");

      // Randomly fill the rectangles
      const randomFill = Math.random() < 0.5 ? "url(#dark_pattern)" : "url(#dark_pattern2)";
      rect.setAttribute("fill", randomFill);

      mixedPattern.appendChild(rect);
    }
  }
}

mixedPattern.setAttribute('href', getMixedPattern());
<svg width="100%" height="500" >

  <pattern id="dark_pattern" patternUnits="userSpaceOnUse" width="12" height="12">
    <rect x="0" y="0" width="3" height="3"/>
    <rect x="6" y="0" width="3" height="3"/>
    <rect x="3" y="3" width="3" height="3"/>
    <rect x="0" y="6" width="3" height="3"/>
    <rect x="6" y="6" width="3" height="3"/>
  </pattern>

  <pattern id="dark_pattern2" patternUnits="userSpaceOnUse" width="12" height="12">
    <rect x="0" y="0" width="3" height="3"/>
    <rect x="6" y="0" width="3" height="3"/>
    <rect x="0" y="6" width="3" height="3"/>
    <rect x="6" y="6" width="3" height="3"/>
  </pattern>

  <pattern id="mixed-pattern" patternUnits="userSpaceOnUse" width="12" height="12">
    <rect x="0" y="0" width="12" height="12" fill="url(#dynamically-mixed-pattern)" />
  </pattern>

  <rect x="0" y="0" width="100%" height="100%" fill="url(#mixed-pattern)" />
</svg>

The mixed pattern should randomly choose one pattern every 12*12, and then fill the element.
Hope it will look like this:
random pattern example

Thanks in advance!

Highlighting text in input at runtime

JavaScript application.
There is an input where text is entered.
How to fill the text (only text) of this input if the color comes at runtim?
That is, how to correctly set the style of a pseudo-class of the type at runtime?

input::first-line { background-color: "red" } // instead of "red" - the value from the variable

Or any other solution if there is one.

Checking my understanding of beforeunload

I’m trying to understand what I can and can’t do with onbeforeunload. I’ve read the docs in MDN and feel I have… some understanding.

The problem I’m trying to solve:

I have this form with lots of records on it. I’m auto-saving as records are edited. However, if there’s an error that prevents saving, users don’t always notice while they’re making lots of updates.

So, naturally, I want to tell them.

My real problem is that I want to present a list of unsaved changes – lots of records, users shouldn’t have to scroll through trying to spot the highlighted ones with errors. Or even search for a string, really.

I’ve managed to do this but am a little confused. Thus, my question.

I know that I don’t control the contents of the message in the confirm alert that is triggered from the onbeforeunload handler.

But do I have any control over what happens in the case of either response (leave or stay)?

My div with unsaved changes shows, regardless of what they choose. It won’t prevent leaving, of course, if they choose to leave… but they’re confused about why it’s showing at all.

With your usual confirm prompt, you control what happens in either case, but this isn’t a normal prompt.

Am I understanding correctly? If I am, I’ll just endeavor to train them about what’s happening. They’d rather see it when they’ve already said peace and are just waiting for it to happen than not get the prompt at all.

Thanks all!

Nodejs server running on localhost properly but problem is the Vercel app api not working any routers, how can I fix it? [closed]

Currently I am building a backend server for E-commerce applicaion. Everything is good on localhost server. But vercel api not working and not showing any error on console.

when I switch a router like https://ecommerce-backend-sand-eight.vercel.app/products showing 404 NOT_FOUND but perfactly work on localhost.

no errors on vercel.
enter image description here

only showing home page
enter image description here

vercel.json

 {
   "version": 2,
   "builds": [
      {
         "src": "./index.js",
         "use": "@vercel/node"
      }
   ],
   "routes": [
      {
         "src": "/(.*)",
         "dest": "./index.js",
         "methods": [
            "GET,HEAD,PUT,PATCH,POST,DELETE"
         ]
      }
   ]
}

package.json

{
  "name": "ecommerce-backend",
  "version": "2.2.0",
  "main": "index.js",
  "engines": {
    "node": "18.x"
  },
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js",
    "build": "netlify deploy --prod",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "Md Yousuf",
  "license": "ISC",
  "description": "Ecommerce server app",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.7",
    "ejs": "^3.1.6",
    "express": "^4.21.2",
    "http": "^0.0.1-security",
    "mongodb": "^6.13.1",
    "multer": "^1.4.5-lts.1",
    "netlify-cli": "^20.0.2",
    "netlify-lambda": "^2.0.16",
    "nodemon": "^3.1.0",
    "serverless-http": "^3.2.0"
  },
  "devDependencies": {
    "nodemon": "^3.1.0"
  }
}

index.js

const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion } = require('mongodb');
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');

dotenv.config();

const app = express();
const port = process.env.PORT || 5000;

// Enable CORS
app.use(cors({
   origin: '*',
   methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
   preflightContinue: false,
   optionsSuccessStatus: 204
}));

// Parse JSON bodies
app.use(express.json());

// Ensure 'uploads' directory exists and serve it statically
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
   fs.mkdirSync(uploadDir, { recursive: true });
}
app.use('/uploads', express.static(uploadDir));

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

// Environment validation
const uri = process.env.NEW_URL;
if (!uri) {
   console.error('Error: Missing MongoDB connection string (NEW_URL) in .env');
   process.exit(1);
}

// MongoDB client
const client = new MongoClient(uri, {
   serverApi: {
      version: ServerApiVersion.v1,
      strict: true,
      deprecationErrors: true,
   },
});

async function startServer() {
   try {
      // Connect to MongoDB
      await client.connect();
      console.log('Successfully connected to MongoDB');

      const db = client.db('insertDB');

      // Register routes with injected database
      app.use('/products', require('./routes/products')(db));
      app.use('/orders', require('./routes/orders')(db));
      app.use('/sliders', require('./routes/sliders')(db));
      app.use('/categories', require('./routes/categories')(db));

      // Home route
      app.get('/', (req, res) => {
         res.sendFile(path.join(__dirname, 'public', 'home.html'));
      });

      // Start listening
      app.listen(port, () => {
         console.log(`Server is running at http://localhost:${port}`);
      });

   } catch (error) {
      console.error('Failed to start server:', error);
      process.exit(1);
   }
}

startServer();

// Graceful shutdown
process.on('SIGINT', async () => {
   console.log('nGracefully shutting down');
   await client.close();
   process.exit(0);
});

routescategories.js

const express = require("express");
const { ObjectId } = require("mongodb");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const router = express.Router();

// -------------------
// Multer Configuration
// -------------------
const storage = multer.diskStorage({
   destination: (req, file, cb) => {
      cb(null, "uploads/");
   },
   filename: (req, file, cb) => {
      const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
      cb(null, uniqueSuffix + path.extname(file.originalname));
   },
});

// File filter for images only
const fileFilter = (req, file, cb) => {
   if (file.mimetype.startsWith("image/")) {
      cb(null, true);
   } else {
      cb(new Error("Only image files are allowed!"), false);
   }
};

const upload = multer({
   storage: storage,
   fileFilter: fileFilter,
   limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
});
// -------------------
// End of Multer Config
// -------------------

module.exports = (database) => {
   const categoriesCollection = database.collection("categories");

   // Get all categories
   router.get("/", async (req, res) => {
      try {
         const categories = await categoriesCollection.find({}).toArray();
         res.json(categories);
      } catch (error) {
         res.status(500).json({ error: "Failed to fetch categories" });
      }
   });

   // Create a new category
   router.post("/", upload.single("image"), async (req, res) => {
      try {
         const newCategory = {
            name: req.body.name,
            slug: req.body.slug,
            description: req.body.description,
            image: req.file ? `/uploads/${req.file.filename}` : null,
            createdAt: new Date(),
            updatedAt: new Date(),
         };

         const result = await categoriesCollection.insertOne(newCategory);
         // Fetch the newly inserted category
         const insertedCategory = await categoriesCollection.findOne({
            _id: result.insertedId,
         });
         res.status(201).json(insertedCategory);
      } catch (error) {
         res.status(400).json({ error: "Category creation failed" });
      }
   });

   // Update an existing category
   router.put("/:id", upload.single("image"), async (req, res) => {
      try {
         const updateData = {
            ...req.body,
            updatedAt: new Date(),
         };

         if (req.file) {
            updateData.image = `/uploads/${req.file.filename}`;
         }

         const result = await categoriesCollection.updateOne(
            { _id: new ObjectId(req.params.id) },
            { $set: updateData }
         );

         if (result.modifiedCount === 0) {
            return res.status(404).json({ error: "Category not found" });
         }
         // Fetch the updated category
         const updatedCategory = await categoriesCollection.findOne({
            _id: new ObjectId(req.params.id),
         });
         res.json(updatedCategory);
      } catch (error) {
         res.status(400).json({ error: "Update failed" });
      }
   });

   // Delete a category
   router.delete("/:id", async (req, res) => {
      try {
         const result = await categoriesCollection.deleteOne({
            _id: new ObjectId(req.params.id),
         });
         if (result.deletedCount === 0) {
            return res.status(404).json({ error: "Category not found" });
         }
         res.json({ message: "Category deleted successfully" });
      } catch (error) {
         res.status(400).json({ error: "Deletion failed" });
      }
   });

   return router;
};

The backend server is working on localhost but not on the vercel app [closed]

I am building the backend of an ecommerce website. My work is almost finished but the vercel app is not working. It is a Node.js project. My full code is here on [Github][1].

https://github.com/ItsMdYousuf/ecommerce-backend
This problem occurred when I used a router. I can’t solve it now.

vercel.json

 {
   "version": 2,
   "builds": [
      {
         "src": "./index.js",
         "use": "@vercel/node"
      }
   ],
   "routes": [
      {
         "src": "/(.*)",
         "dest": "./index.js",
         "methods": [
            "GET,HEAD,PUT,PATCH,POST,DELETE"
         ]
      }
   ]
}

package.json

{
  "name": "ecommerce-backend",
  "version": "2.2.0",
  "main": "index.js",
  "engines": {
    "node": "18.x"
  },
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js",
    "build": "netlify deploy --prod",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "Md Yousuf",
  "license": "ISC",
  "description": "Ecommerce server app",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.7",
    "ejs": "^3.1.6",
    "express": "^4.21.2",
    "http": "^0.0.1-security",
    "mongodb": "^6.13.1",
    "multer": "^1.4.5-lts.1",
    "netlify-cli": "^20.0.2",
    "netlify-lambda": "^2.0.16",
    "nodemon": "^3.1.0",
    "serverless-http": "^3.2.0"
  },
  "devDependencies": {
    "nodemon": "^3.1.0"
  }
}

index.js

const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion } = require('mongodb');
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');

dotenv.config();

const app = express();
const port = process.env.PORT || 5000;

// Enable CORS
app.use(cors({
   origin: '*',
   methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
   preflightContinue: false,
   optionsSuccessStatus: 204
}));

// Parse JSON bodies
app.use(express.json());

// Ensure 'uploads' directory exists and serve it statically
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
   fs.mkdirSync(uploadDir, { recursive: true });
}
app.use('/uploads', express.static(uploadDir));

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

// Environment validation
const uri = process.env.NEW_URL;
if (!uri) {
   console.error('Error: Missing MongoDB connection string (NEW_URL) in .env');
   process.exit(1);
}

// MongoDB client
const client = new MongoClient(uri, {
   serverApi: {
      version: ServerApiVersion.v1,
      strict: true,
      deprecationErrors: true,
   },
});

async function startServer() {
   try {
      // Connect to MongoDB
      await client.connect();
      console.log('Successfully connected to MongoDB');

      const db = client.db('insertDB');

      // Register routes with injected database
      app.use('/products', require('./routes/products')(db));
      app.use('/orders', require('./routes/orders')(db));
      app.use('/sliders', require('./routes/sliders')(db));
      app.use('/categories', require('./routes/categories')(db));

      // Home route
      app.get('/', (req, res) => {
         res.sendFile(path.join(__dirname, 'public', 'home.html'));
      });

      // Start listening
      app.listen(port, () => {
         console.log(`Server is running at http://localhost:${port}`);
      });

   } catch (error) {
      console.error('Failed to start server:', error);
      process.exit(1);
   }
}

startServer();

// Graceful shutdown
process.on('SIGINT', async () => {
   console.log('nGracefully shutting down');
   await client.close();
   process.exit(0);
});

routescategories.js

const express = require("express");
const { ObjectId } = require("mongodb");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const router = express.Router();

// -------------------
// Multer Configuration
// -------------------
const storage = multer.diskStorage({
   destination: (req, file, cb) => {
      cb(null, "uploads/");
   },
   filename: (req, file, cb) => {
      const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
      cb(null, uniqueSuffix + path.extname(file.originalname));
   },
});

// File filter for images only
const fileFilter = (req, file, cb) => {
   if (file.mimetype.startsWith("image/")) {
      cb(null, true);
   } else {
      cb(new Error("Only image files are allowed!"), false);
   }
};

const upload = multer({
   storage: storage,
   fileFilter: fileFilter,
   limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
});
// -------------------
// End of Multer Config
// -------------------

module.exports = (database) => {
   const categoriesCollection = database.collection("categories");

   // Get all categories
   router.get("/", async (req, res) => {
      try {
         const categories = await categoriesCollection.find({}).toArray();
         res.json(categories);
      } catch (error) {
         res.status(500).json({ error: "Failed to fetch categories" });
      }
   });

   // Create a new category
   router.post("/", upload.single("image"), async (req, res) => {
      try {
         const newCategory = {
            name: req.body.name,
            slug: req.body.slug,
            description: req.body.description,
            image: req.file ? `/uploads/${req.file.filename}` : null,
            createdAt: new Date(),
            updatedAt: new Date(),
         };

         const result = await categoriesCollection.insertOne(newCategory);
         // Fetch the newly inserted category
         const insertedCategory = await categoriesCollection.findOne({
            _id: result.insertedId,
         });
         res.status(201).json(insertedCategory);
      } catch (error) {
         res.status(400).json({ error: "Category creation failed" });
      }
   });

   // Update an existing category
   router.put("/:id", upload.single("image"), async (req, res) => {
      try {
         const updateData = {
            ...req.body,
            updatedAt: new Date(),
         };

         if (req.file) {
            updateData.image = `/uploads/${req.file.filename}`;
         }

         const result = await categoriesCollection.updateOne(
            { _id: new ObjectId(req.params.id) },
            { $set: updateData }
         );

         if (result.modifiedCount === 0) {
            return res.status(404).json({ error: "Category not found" });
         }
         // Fetch the updated category
         const updatedCategory = await categoriesCollection.findOne({
            _id: new ObjectId(req.params.id),
         });
         res.json(updatedCategory);
      } catch (error) {
         res.status(400).json({ error: "Update failed" });
      }
   });

   // Delete a category
   router.delete("/:id", async (req, res) => {
      try {
         const result = await categoriesCollection.deleteOne({
            _id: new ObjectId(req.params.id),
         });
         if (result.deletedCount === 0) {
            return res.status(404).json({ error: "Category not found" });
         }
         res.json({ message: "Category deleted successfully" });
      } catch (error) {
         res.status(400).json({ error: "Deletion failed" });
      }
   });

   return router;
};

Can find an input value throught its id in a django generated table

I’m very new to javascript and must use it for a project in which i’m using a table and want to extract the value of an input field with id generated trough a Django function. i don’t know if that could be relevent but i’m using datatable in this project.

The HTML code looks like this:

<head>
     <script src="{% static 'myProject/jQuery/jquery-3.7.1.js' %}"></script>
     <script src="{% static 'myProject/javaScript/datatables.min.js' %}"></script>
     <script src="{% static 'myProject/javaScript/checkFunc.js' %}" defer></script>

     <link rel="stylesheet" href="{% static 'myProject/CSS/checkStyle.css' %}">
     <link rel="stylesheet" href="{% static 'myProject/CSS/datatables.min.css' %}">
</head>

<table id="myTable">
    <thead>
        <tr>
            <th>Head Value</th>
            <th>Another head Value</th>
        </tr>
    </thead>
    <tbody>
         {% for value in list_of_value %}
            <tr>
                <td><input type="number" id="amount{{ value.id }}" value="1"></td>
                <td><button onclick="check(value.id)">Check input box</button></td>
            </tr>
         {% endfor %}
    </tbody>
</table>

And the JS like this:

function check(value_id){
     const amount= document.getElementById("amount"+wallet_id);
     console.debug(amount);
}

In the console all i get is “null” as if it doesn’t exist but i tried modifying it with CSS and it worked just fine. I also tried using jQuery as so:

function check(value_id){
    var actionTable = $("#amount" + value_id +"");
    console.debug(actionTable);
    console.debug(actionTable.value);
}

And on this one i don’t get a null i get an object:

Object {  }
​
<prototype>: Object { jquery: "3.7.1", constructor: jQuery(selector, context)
, length: 0, … }
​​
DataTable: function DataTable(e)​​
add: function add(selector, context)​​
addBack: function addBack(selector)​​
addClass: function addClass(value)​​
after: function after()​​
ajaxComplete: function type(fn)​​
ajaxError: function type(fn)​​
ajaxSend: function type(fn)​​
ajaxStart: function type(fn)​​
ajaxStop: function type(fn)​​
ajaxSuccess: function type(fn)​​
animate: function animate(prop, speed, easing, callback)​​
append: function append()​​
appendTo: function name(selector)​​
attr: function attr(name, value)​​
before: function before()​​
bind: function bind(types, data, fn)​​
blur: function name(data, fn)​​
change: function name(data, fn)​​
children: function name(until, selector)​​
clearQueue: function clearQueue(type)​​
click: function name(data, fn)​​
clone: function clone(dataAndEvents, deepDataAndEvents)​​
closest: function closest(selectors, context)​​
constructor: function jQuery(selector, context)​​
contents: function name(until, selector)​​
contextmenu: function name(data, fn)​​
css: function css(name, value)​​
data: function data(key, value)​​
dataTable: function V(e, P)​​
dataTableExt: Object { buttons: {}, builder: "dt/dt-2.2.2", errMode: "alert", … }
​​
dataTableSettings: Array [ {…} ]
​​
dblclick: function name(data, fn)​​
delay: function delay(time, type)​​
delegate: function delegate(selector, types, data, fn)​​
dequeue: function dequeue(type)​​
detach: function detach(selector)​​
each: function each(callback)​​
empty: function empty()​​
end: function end()​​
eq: function eq(i)​​
even: function even()​​
extend: function extend()​​
fadeIn: function name(speed, easing, callback)​​
fadeOut: function name(speed, easing, callback)​​
fadeTo: function fadeTo(speed, to, easing, callback)​​
fadeToggle: function name(speed, easing, callback)​​
filter: function filter(selector)​​
find: function find(selector)​​
finish: function finish(type)​​
first: function first()​​
focus: function name(data, fn)​​
focusin: function name(data, fn)​​
focusout: function name(data, fn)​​
get: function get(num)​​
has: function has(target)​​
hasClass: function hasClass(selector)​​
height: function funcName(margin, value)​​
hide: function name(speed, easing, callback)​​
hover: function hover(fnOver, fnOut)​​
html: function html(value)​​
index: function index(elem)​​
init: function init(selector, context, root)​​
innerHeight: function funcName(margin, value)​​
innerWidth: function funcName(margin, value)​​
insertAfter: function name(selector)​​
insertBefore: function name(selector)​​
is: function is(selector)
​​
jquery: "3.7.1"
​​
keydown: function name(data, fn)​​
keypress: function name(data, fn)​​
keyup: function name(data, fn)​​
last: function last()
​​
length: 0
​​
load: function load(url, params, callback)​​
map: function map(callback)​​
mousedown: function name(data, fn)​​
mouseenter: function name(data, fn)​​
mouseleave: function name(data, fn)​​
mousemove: function name(data, fn)​​
mouseout: function name(data, fn)​​
mouseover: function name(data, fn)​​
mouseup: function name(data, fn)​​
next: function name(until, selector)​​
nextAll: function name(until, selector)​​
nextUntil: function name(until, selector)​​
not: function not(selector)​​
odd: function odd()​​
off: function off(types, selector, fn)​​
offset: function offset(options)​​
offsetParent: function offsetParent()​​
on: function on(types, selector, data, fn)​​
one: function one(types, selector, data, fn)​​
outerHeight: function funcName(margin, value)​​
outerWidth: function funcName(margin, value)​​
parent: function name(until, selector)​​
parents: function name(until, selector)​​
parentsUntil: function name(until, selector)​​
position: function position()​​
prepend: function prepend()​​
prependTo: function name(selector)​​
prev: function name(until, selector)​​
prevAll: function name(until, selector)​​
prevUntil: function name(until, selector)​​
promise: function promise(type, obj)​​
prop: function prop(name, value)​​
push: function push()
​​
pushStack: function pushStack(elems)​​
queue: function queue(type, data)​​
ready: function ready(fn)​​
remove: function remove(selector)​​
removeAttr: function removeAttr(name)​​
removeClass: function removeClass(value)​​
removeData: function removeData(key)​​
removeProp: function removeProp(name)​​
replaceAll: function name(selector)​​
replaceWith: function replaceWith()​​
resize: function name(data, fn)​​
scroll: function name(data, fn)​​
scrollLeft: function method(val)​​
scrollTop: function method(val)​​
select: function name(data, fn)​​
serialize: function serialize()​​
serializeArray: function serializeArray()​​
show: function name(speed, easing, callback)​​
siblings: function name(until, selector)​​
slice: function slice()​​
slideDown: function name(speed, easing, callback)​​
slideToggle: function name(speed, easing, callback)​​
slideUp: function name(speed, easing, callback)​​
sort: function sort()
​​
splice: function splice()
​​
stop: function stop(type, clearQueue, gotoEnd)​​
submit: function name(data, fn)​​
text: function text(value)​​
toArray: function toArray()​​
toggle: function name(speed, easing, callback)​​
toggleClass: function toggleClass(value, stateVal)​​
trigger: function trigger(type, data)​​
triggerHandler: function triggerHandler(type, data)​​
unbind: function unbind(types, fn)​​
undelegate: function undelegate(selector, types, fn)​​
uniqueSort: function uniqueSort()​​
unwrap: function unwrap(selector)​​
val: function val(value)​​
width: function funcName(margin, value)​​
wrap: function wrap(html)​​
wrapAll: function wrapAll(html)​​
wrapInner: function wrapInner(html)​​
Symbol(Symbol.iterator): function values()
​​
<prototype>: Object { … }```
**but** that object don't have a value and don't seems to be corresponding to my input field.
So my question is is there something i don't understand or am I doing something wrong ? And if so how do i do it right ?

Needed React native payment integration

I am trying to integrate the payment system for react native but got deadlock. I am able to creat it in react but successurl and failure I couldn’t make it. Is is possible as like the react or do I need other ways to create it. Help me guys.

Error in final stage of React Native environment configuration. (Build of mobile app)

I have a problem with starting a mobile app build on the emulator. (React Native) The loading process – “Executing” reaches 83% and then an error appears informing that the android.jar file is corrupted (unable to load resources in the file). I once tried to reinstall Android 35 in the SDK Manager in Android Studio, but it didn’t help. There was also information about a compatibility problem with the SDK version (SDK version is 35) with the Gradle version (Gradle version is 7.5 and 8.13) and Android Gradle Plugin (Android Gradle Plugin version is 7.3.1). Has anyone had a similar problem? It’s not much left to start the mobile app project, it’s the final stage. Does anyone have any ideas how to fix this?

I’m posting the entire error from Windows PowerShell:

“PS D:AplikacjaTripify> yarn android
yarn run v1.22.22
$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using “–no-jetifier” flag.
Jetifier found 1066 file(s) to forward-jetify. Using 4 workers…
info JS server already running.
info Installing the app…
WARNING:We recommend using a newer Android Gradle plugin to use compileSdk = 35

This Android Gradle plugin (7.3.1) was tested up to compileSdk = 33

This warning can be suppressed by adding
android.suppressUnsupportedCompileSdk=35
to this project’s gradle.properties

The build will continue, but you are strongly encouraged to update your project to
use a newer Android Gradle Plugin that has been tested with compileSdk = 35

Task :app:processDebugResources FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use ‘–warning-mode all’ to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.5/userguide/command_line_interface.html#sec:command_line_warnings
26 actionable tasks: 1 executed, 25 up-to-date

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:app:processDebugResources’.

A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
Android resource linking failed
aapt2.exe E 04-15 22:53:16 15644 8352 LoadedArsc.cpp:94] RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data.
aapt2.exe E 04-15 22:53:16 15644 8352 ApkAssets.cpp:149] Failed to load resources table in APK ‘D:SDKplatformsandroid-35android.jar’.
error: failed to load include path D:SDKplatformsandroid-35android.jar.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

BUILD FAILED in 18s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:app:processDebugResources’.

A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
Android resource linking failed
aapt2.exe E 04-15 22:53:16 15644 8352 LoadedArsc.cpp:94] RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data.
aapt2.exe E 04-15 22:53:16 15644 8352 ApkAssets.cpp:149] Failed to load resources table in APK ‘D:SDKplatformsandroid-35android.jar’.
error: failed to load include path D:SDKplatformsandroid-35android.jar.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

BUILD FAILED in 18s

at makeError (D:AplikacjaTripifynode_modulesexecaindex.js:174:9)
at D:AplikacjaTripifynode_modulesexecaindex.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:AplikacjaTripifynode_modulesreact-nativenode_modules@react-native-communitycli-platform-androidbuildcommandsrunAndroidrunOnAllDevices.js:94:5)
at async Command.handleAction (D:AplikacjaTripifynode_modulesreact-nativenode_modules@react-native-communityclibuildindex.js:186:9)

info Run CLI with –verbose flag for more details.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.”

I once tried to reinstall Android 35 in the SDK Manager in Android Studio, but it didn’t help.

Clarification on Computed Properties

I’m studying TypeScript and came across this pattern:

type Animal = { [key: string]: number };
 
let Tiger: Animal = { legs: 4, age: 5, tail: 1, eyes :2 };

From what I understand, this allows adding unlimited properties, as long as the key is a string and the value is a number.

My question is:

Is this approach considered idiomatic in TypeScript?

Would there be a better way to type known + unknown properties with more structure?

Xdebug: [Step Debug] Time-out connecting to debugging client, waited: 200 ms. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port)

I’m using Xdebug v3.4.0 (with PHP 8.3.9).

I get this error for every request.

I tried other Xdebug versions but still got the issue.

Here my php.ini :

[XDebug]
zend_extension = xdebug
xdebug.mode=debug
xdebug.start_with_request=trigger 

My PhpStorm settings :

Phpstorm settings

Phpstorm settings 2

Don’t hesitate if you need more info.

Thanks

PHP/SQL (MariaDB) – Transaction with self instanciation

I have a method that kill a character and if this character is married to another character, it also kill them.

public function kill(string $reason): void
{
    $this->update(array(
        'character_status'        => "Dead",
        'character_death_reason'  => $reason
    ));

    // To ensure it doesn't make an infinite loop.
    if($this->isMarried() && $reason != "wedding") {
        $husband = $this->getHusband();
        $husband->kill('wedding');
    }
}

This method is called on a code, 300 lines after the transaction started, but can be resumed precisely like that :

// For context, every Character() belong to a City(), and I'm doing a transaction per City.
$city->beginTransaction();

[...]

foreach($characterAlive as $character) {
    $character->kill('because_i_want_to');
}

[...]

$city->commitTransaction();

It does work for every character alive. But if a character have a husband, the transaction goes on a “locked table” issue:

ERROR: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction.

All my concerned tables are in InnoDB storage config and I’m using a Singleton. As I’m acting on different rows (character_id being my PRIMARY KEY A_I), I don’t understand why it does work on the foreach, but not if a Character class instantiates another Character class.

I need this dependence as there is more than 30 ways to reach the kill method.

No, you cannot directly run a PHP script on an Amazon S3 bucket? is that true [closed]

Want to create a simple form that stores information in to a csv file, could it be done using a S3 bucket or does it need proper compute like EC2 or Lambda?

AWS Lambda (serverless approach) – Great for lightweight processing. You can trigger a Lambda function when the form is submitted, process the data, and save the CSV file to S3.

EC2 Instance (traditional approach) – If you need more control over the environment and a persistent application, an EC2 instance can run a web app that handles form submissions and writes CSV files to S3.

AWS API Gateway + Lambda – A more serverless approach where the form submits data via an API, the API Gateway triggers a Lambda function, and the function processes the data into a CSV and saves it in S3.

WordPress Plugins update generates a critical error and I can’t access wp-admin since

I’ve been working on this project for a couple of days, I’m completely new to WordPress and this is a legacy project.

After stating this, I’m completely lock-out from wp-admin. I’ve been handling this project from https://mywebsite.com/wp-admin/, I was about to finish it and then I updated the plugins (silly me), specifically the WooComerce one and since then I can’t regain access to https://mywebsite.com/wp-admin/. I got a 307 error in the process

I’ve scout the internet for answers so I will make a list of what I’ve already try

  1. Change the name of the plugins folder at public_html/wp-content/plugins to public_html/wp-content/plugins.hold to make my plugins inactive and regain access

  2. Change the name of the plugins folder at public_html/wp-content/languages/plugins to public_html/wp-content/languages/plugins-_- to be certain about inner calls to the plugins

  3. Change the row [option_id:35 , option_name:active_plugins] from the wp_options table setting [option_value:a:0:{}] straight from the DB with phpMyAdmin, so it can’t pick the plugins neither from the plugin folder nor the DB

  4. Rename the files with ** .htaccess** string from public_html/ to resolve the 307 error

  5. Change
    define( 'WP_CACHE', true );
    to
    define( 'WP_CACHE', false );
    at public_html/wp-config.php

  6. Change
    define( 'WP_DEBUG', false );
    to
    define( 'WP_DEBUG', true );
    at public_html/wp-config.php

  7. Uncomment the lines

      define('WP_DEBUG_LOG', true);
      define('WP_PROXY_HOST', '192.168.14.1'); 
      define('WP_PROXY_PORT', 3128);

at public_html/wp-config.php

  1. rename the traveler folder at public_html/wp-content/themes/ to traveler.nani to avoid using it as a theme if this was the one producing the error

  2. Change
    define('WP_USE_THEMES', true);
    to
    define('WP_USE_THEMES', false);
    at public_html/index.php

As you can see I’ve tried a couple of things but nothing seems to work, here it’s the screenshot of the problem itself (In Spanish because the webpage it’s on Spanish)

https://mywebsite/wp-admin/

On this message says I should have received an email with instructions to fix the bug. I’ve not received anything. Anyone have encounter the same problem or knows how to fix this situation?

Typescript Path Resolution Problem on tsconfig

//ts config file

 {
  "compilerOptions": {
    "target": "ES6",
    "module": "ESNext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "checkJs": false,
    "skipLibCheck": true,
    "noImplicitAny": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "strictNullChecks": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": "./src",
    "paths": {
      "@casweb-base/*": ["*"]
      // Add other aliases as needed
    }
  },
  "include": ["./src", "./packages", "assets.d.ts"],
  "exclude": ["node_modules", "public"]
}

//js config file

{
  "compilerOptions": {
    "jsx": "react",
    "baseUrl": "./src",
    "paths": {
      "@web-packages/*": ["./packages/*"],
      "@web-base/*": ["./src/*"]
    }
  },
  "include": ["./src", "./packages"]
}

Hello, i have two configuration files, respectively ts and js config json. But in ts config i cant truly manage path aliases, when i revert baseUrl to be same with jsconfig, it cant find files on import.

Profile stats are not updating in localstorage

I’m currently working on updating a function in my code that tracks user stats based on the number of posts they’ve made and the likes they’ve received. However, I’m running into an issue that I need help resolving. Below is a partial section of the code related to the stats update. Could you help me identify and fix the error?

HTML:

<div class="stat-item">
  <span class="stat-number" id="account-posts-count">0 Posts</span>
  <span class="stat-label">Posts</span>
</div>
<div class="stat-item">
  <span class="stat-number" id="account-likes-count">0 Likes Received</span>
  <span class="stat-label">Likes Received</span>
</div>

Javascript:

function initAccountStats() {
  if (!auth.currentUser) return;
  
  const user = db.getUserByEmail(auth.currentUser.email);
  if (!user) return;

  // Initialize counts if undefined
  user.postCount = user.postCount || 0;
  user.likesReceived = user.likesReceived || 0;
  db.updateUser(auth.currentUser.email, user);

  // Update DOM elements
  const postsElement = document.getElementById('account-posts-count');
  const likesElement = document.getElementById('account-likes-count');
  
  if (postsElement) postsElement.textContent = `${user.postCount} Posts`;
  if (likesElement) likesElement.textContent = `${user.likesReceived} Likes Received`;
}


function clearUserInterface() {
  // Clear profile information
  document.getElementById('profile-name').textContent = '';
  document.getElementById('profile-email').textContent = '';
  document.getElementById('profile-picture').src = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLXVzZXIiPjxwYXRoIGQ9Ik0xOSAyMXYtMmE0IDQgMCAwIDAtNC00SDlhNCA0IDAgMCAwLTQgNHYyIi8+PGNpcmNsZSBjeD0iMTIiIGN5PSI3IiByPSI0Ii8+PC9zdmc+';
  
  // Clear account form
  document.getElementById('account-name').value = '';
  document.getElementById('account-email').value = '';
  document.getElementById('account-bio').value = '';
  document.getElementById('pfp-preview').src = '';
  
  // Clear statistics
  document.getElementById('account-posts-count').textContent = '0 Posts';
  document.getElementById('account-likes-count').textContent = '0 Likes Received';
  
  // Clear posts container
  document.getElementById('nearbyPostsContainer').innerHTML = '';
  
  // Clear any active popups
  closeAllPopups();
  closeProfilePopup();
  closeFullscreenPopup();
  
  // Clear user location
  userLocation = DEFAULT_CENTER;
  
  // Reset map view if it exists
  if (map) {
    map.setCenter(DEFAULT_CENTER);
    map.setZoom(8);
  }
}

function updateProfileStats(email) {
  const user = db.getUserByEmail(email);
 if (!user) return;

 // Update posts count
 const postsCountElement = document.getElementById('account-posts-count');
 if (postsCountElement) {
   postsCountElement.textContent = `${user.postCount || 0} Posts`;
 }

 // Update likes received
 const likesCountElement = document.getElementById('account-likes-count');
 if (likesCountElement) {
   likesCountElement.textContent = `${user.likesReceived || 0} Likes Received`;
 }

 // Log stats to console for debugging
 console.log(`[updateProfileStats] User: ${user.email}, Posts: ${user.postCount || 0}, Likes Received: ${user.likesReceived || 0}`);


 const userPosts = db.getPostsByUser(email);
 const likesReceived = db.getLikesReceived(email);

 // Update stats in the profile popup if it's open
 if (currentProfileEmail === email) {
   document.getElementById('popup-posts-count').textContent = `${userPosts.length} Posts`;
   document.getElementById('popup-likes-count').textContent = `${db.getLikesReceived(email)} Likes Received`;
 }

 // Update stats in the account page if viewing own profile
 if (auth.currentUser?.email === email) {
   document.getElementById('profile-posts-count').textContent = `${userPosts.length} Posts`;
   document.getElementById('profile-likes-count').textContent = `${db.getLikesReceived(email)} Likes Received`;
 }
}

Additionally, if there are any optimizations to make the logic more efficient, I’d appreciate those as well. Thanks!