How to change the chunk size of an Axios stream?

I am trying to download a stream using Axios, currently doing it this way:

const config = {
    responseType: 'stream',
    url: "https://example.com",
    method: "GET",
    maxRedirects: 0,
    decompress: false,
};

const { status, headers, data } = await axios(config);

data.pipe(streamTarget);

Which is working perfectly. However I would like (if possible) to change the size of the chunks obtained from the stream by Axios.

Is this possible? How can I achieve it?

I use WordPress and would like to display the height and weight box on all product pages except for the accessories category,how to do the exception?

here is the i used to display height and weight boxes on product pages:



// Display custom field on single product page
    function d_extra_product_field(){
        $value = isset( $_POST['extra_product_field'] ) ? sanitize_text_field( $_POST['extra_product_field'] ) : '';
        printf( '<div><label>%s</label><br><textarea name="extra_product_field" value="%s"></textarea></div>', __( '<br><br><br> Enter your order notes' ), esc_attr( $value ) );
    }
    add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 );

    // validate when add to cart
    function d_extra_field_validation($passed, $product_id, $qty){

        if( isset( $_POST['extra_product_field'] ) && sanitize_text_field( $_POST['extra_product_field'] ) == '' ){
            $product = wc_get_product( $product_id );
            wc_add_notice( sprintf( __( '%s يرجى إدخال ملاحظات الطلب لإضافة المنتج الى السلة.' ), $product->get_title() ), 'error' );
            return false;
        }

        return $passed;

    }
    add_filter( 'woocommerce_add_to_cart_validation', 'd_extra_field_validation', 10, 3 );

     // add custom field data in to cart
    function d_add_cart_item_data( $cart_item, $product_id ){

        if( isset( $_POST['extra_product_field'] ) ) {
            $cart_item['extra_product_field'] = sanitize_text_field( $_POST['extra_product_field'] );
        }

        return $cart_item;

    }
    add_filter( 'woocommerce_add_cart_item_data', 'd_add_cart_item_data', 10, 2 );

    // load data from session
    function d_get_cart_data_f_session( $cart_item, $values ) {

        if ( isset( $values['extra_product_field'] ) ){
            $cart_item['extra_product_field'] = $values['extra_product_field'];
        }

        return $cart_item;

    }
    add_filter( 'woocommerce_get_cart_item_from_session', 'd_get_cart_data_f_session', 20, 2 );


    //add meta to order
    function d_add_order_meta( $item_id, $values ) {

        if ( ! empty( $values['extra_product_field'] ) ) {
            woocommerce_add_order_item_meta( $item_id, 'extra_product_field', $values['extra_product_field'] );           
        }
    }
    add_action( 'woocommerce_add_order_item_meta', 'd_add_order_meta', 10, 2 );

    // display data in cart
    function d_get_itemdata( $other_data, $cart_item ) {

        if ( isset( $cart_item['extra_product_field'] ) ){

            $other_data[] = array(
                'name' => __( 'Your extra field text' ),
                'value' => sanitize_text_field( $cart_item['extra_product_field'] )
            );

        }

        return $other_data;

    }
    add_filter( 'woocommerce_get_item_data', 'd_get_itemdata', 10, 2 );


    // display custom field data in order view
    function d_dis_metadata_order( $cart_item, $order_item ){

        if( isset( $order_item['extra_product_field'] ) ){
            $cart_item_meta['extra_product_field'] = $order_item['extra_product_field'];
        }

        return $cart_item;

    }
    add_filter( 'woocommerce_order_item_product', 'd_dis_metadata_order', 10, 2 );


    // add field data in email
    function d_order_email_data( $fields ) { 
        $fields['extra_product_field'] = __( 'Your extra field text' ); 
        return $fields; 
    } 
    add_filter('woocommerce_email_order_meta_fields', 'd_order_email_data');

    // again order
    function d_order_again_meta_data( $cart_item, $order_item, $order ){

        if( isset( $order_item['extra_product_field'] ) ){
            $cart_item_meta['extra_product_field'] = $order_item['extra_product_field'];
        }

        return $cart_item;

    }
    add_filter( 'woocommerce_order_again_cart_item_data', 'd_order_again_meta_data', 10, 3 );





add_action( 'wp_enqueue_scripts', 'custom_enqueue_wc_cart_fragments' );
function custom_enqueue_wc_cart_fragments() {
    wp_enqueue_script( 'wc-cart-fragments' );
}

The weight and height field is mandatory, so I used css code below and the box was actually hidden in the accessories category, but even though it disappeared, it is still mandatory and can’t add product to the cart for all products in accessories category:

schema.parseAsync is not a function?

I am trying to perform zod validation in nodeJS. But getting an error TypeError: schema.parseAsync is not a function. I tried everything,importing again and all but can’t get over it.
My auth-router.js:

const express = require('express')
const router = express.Router();
const authControllers = require("../controllers/auth-controller");
const signupSchema = require("../validator/auth-validator")
const validate = require('../middleware/validate-middleware');

router.route('/').get(authControllers.home);
router.route('/register').post(validate(signupSchema) ,authControllers.register);
router.route('/login').post(authControllers.login);

module.exports = router;

My validat-middleware.js:

const validate = (schema) => async (req, res, next) => {
    try {
        console.log(schema);
        const parsedBody = await schema.parseAsync(req.body);
        req.body = parsedBody;
        next();
    } catch (err) {
        console.log(err);
        // const message = err.error.message;
        res.status(400).json({ message: "Validation Failed" });
    }
};

module.exports = validate;

My zod-validation schema:

const { z } = require('zod')

const signupSchema = z.object({
    username: z
    .string({ required_error: "Username is required"})
    .trim()
    .min(3, {message: "Username must be at least 3 characters"})
    .max(255, {message: "Username must be less than 255 characters"}),

    email: z
    .string({ required_error: "Email is required"})
    .trim()
    .min(3, {message: "Email must be at least 3 characters"})
    .max(255, {message: "Email must be less than 255 characters"}),

    phone: z
    .string({reportError: "Phone no. is required"})
    .trim()
    .min(10, {message: "Phone no. must be at least 10 characters"})
    .max(20, {message: "Phone no. must be less than 20 characters"}),

    pasword: z
    .string({ required_error: "Password is required"})
    .min(7, {message: "Password must be at least 6 characters"})
    .max(1024, {message: "Password must be less than 1024 characters"}),
})

module.exports = { signupSchema };

so what’s am doing wrong, and how can i fix it? thanks for attention.

Getting Failed to Load resources on Apache webserver requesting files without file extension

I am trying to implement a small tetris base game i found on github into my webserver but the images for the tiles are not loading into the game and in the console it says failed to load resouce 404 not found and it describes the file it is looking for as the colors i listed in the array in the following code but missing the .png extensions even though the array explicitly should request the image source to be from within a resources folder with the .png extensions

Furthermore it is loading one color, blue but when i refresh the page to try get another color it says for example failed to find file “orange”

The file structure is withi the htdocs of the apache, whose service is running on localhost, and is like the following,

  1. Htdocs
  • index.html (with link to tetris.html)
  • tetris.html
  • tetris.js
  • tetris.css
  • resources folder (this includes all colors in .png form for example blue.png)
window.onload = () => {
    const
        background = document.getElementById("background"),
        scoreLbl = document.getElementById("score"),
        linesLbl = document.getElementById("lines"),
        canvas = document.getElementById("game-canvas"),
        ctx = canvas.getContext("2d");

    let audio = new Audio("resources/music.mp3");

    class Tetromino {
        static COLORS = [".resources/blue.png", ".resources/green.png", ".resources/yellow.png", ".resources/red.png", ".resources/orange.png", ".resources/light-blue.png", ".resources/purple.png"];
        static BLOCK_SIZE = 28;
        static DELAY = 400;
        static DELAY_INCREASED = 5;

        constructor(xs, ys, color = null) {
            this.x = xs;
            this.y = ys;
            this.length = xs.length;
            this.color = color;
            this.img = new Image();
            
    
            // Set up a promise to track image loading
            this.imgLoaded = new Promise((resolve, reject) => {
                this.img.onload = resolve;
                this.img.onerror = reject;
            });
    
            if (color !== null) {
                this.img.src = Tetromino.COLORS[color];
                console.log(this.img.src);
                console.log((TETROMINOES.COLORS[color]));
            }
        }

        update(updFunc) {
            for (let i = 0; i < this.length; ++i) {
                ctx.clearRect(
                    this.x[i] * Tetromino.BLOCK_SIZE,
                    this.y[i] * Tetromino.BLOCK_SIZE,
                    Tetromino.BLOCK_SIZE,
                    Tetromino.BLOCK_SIZE
                );

                updFunc(i);
            }

            this.draw();
        }

        draw() {
            if (!this.img.complete) {
                this.img.onload = () => this.draw();
                return;
            }
            // Print the current tetromine
            for (let i = 0; i < this.length; ++i) {
                ctx.drawImage(
                    this.img,
                    this.x[i] * Tetromino.BLOCK_SIZE,
                    this.y[i] * Tetromino.BLOCK_SIZE,
                    Tetromino.BLOCK_SIZE,
                    Tetromino.BLOCK_SIZE
                );
            }
        }

        collides(checkFunc) {
            for (let i = 0; i < this.length; ++i) {
                const { x, y } = checkFunc(i);
                if (x < 0 || x >= FIELD_WIDTH || y < 0 || y >= FIELD_HEIGHT || FIELD[y][x] !== false)
                    return true;
            }
            return false;
        }

        merge() {
            for (let i = 0; i < this.length; ++i) {
                FIELD[this.y[i]][this.x[i]] = this.color;
            }
        }

        rotate() {
            const
                maxX = Math.max(...this.x),
                minX = Math.min(...this.x),
                minY = Math.min(...this.y),
                nx = [],
                ny = [];

            if (!this.collides(i => {
                    nx.push(maxX + minY - tetromino.y[i]);
                    ny.push(tetromino.x[i] - minX + minY);
                    return { x: nx[i], y: ny[i] };
                })) {
                this.update(i => {
                    this.x[i] = nx[i];
                    this.y[i] = ny[i];
                });
            }
        }
    }

    const
        FIELD_WIDTH = 10,
        FIELD_HEIGHT = 20,
        FIELD = Array.from({ length: FIELD_HEIGHT }),
        MIN_VALID_ROW = 4,
        TETROMINOES = [
            new Tetromino([0, 0, 0, 0], [0, 1, 2, 3]),
            new Tetromino([0, 0, 1, 1], [0, 1, 0, 1]),
            new Tetromino([0, 1, 1, 1], [0, 0, 1, 2]),
            new Tetromino([0, 0, 0, 1], [0, 1, 2, 0]),
            new Tetromino([0, 1, 1, 2], [0, 0, 1, 1]),
            new Tetromino([0, 1, 1, 2], [1, 1, 0, 1]),
            new Tetromino([0, 1, 1, 2], [1, 1, 0, 0])
        ];

    let tetromino = null,
        delay,
        score,
        lines;



    (function setup() {

        canvas.style.top = Tetromino.BLOCK_SIZE;
        canvas.style.left = Tetromino.BLOCK_SIZE;

        ctx.canvas.width = FIELD_WIDTH * Tetromino.BLOCK_SIZE;
        ctx.canvas.height = FIELD_HEIGHT * Tetromino.BLOCK_SIZE;

        // Scale background
        const scale = Tetromino.BLOCK_SIZE / 13.83333333333;
        background.style.width = scale * 166;
        background.style.height = scale * 304;

        // Offset each block to the middle of the table width
        const middle = Math.floor(FIELD_WIDTH / 2);
        for (const t of TETROMINOES) t.x = t.x.map(x => x + middle);

        reset();
        draw();
    })();

    function reset() {
        // Make false all blocks
        FIELD.forEach((_, y) => FIELD[y] = Array.from({ length: FIELD_WIDTH }).map(_ => false));

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        delay = Tetromino.DELAY;
        score = 0;
        lines = 0;
    }
    
    function playMusic() {
        audio.play();
        
        
    }

    function draw() {
        if (tetromino) {

            // Collision?
            if (tetromino.collides(i => ({ x: tetromino.x[i], y: tetromino.y[i] + 1 }))) {
                tetromino.merge();
                // Prepare for new tetromino
                tetromino = null;

                // Check for completed rows
                let completedRows = 0;
                for (let y = FIELD_HEIGHT - 1; y >= MIN_VALID_ROW; --y)
                    if (FIELD[y].every(e => e !== false)) {
                        for (let ay = y; ay >= MIN_VALID_ROW; --ay)
                            FIELD[ay] = [...FIELD[ay - 1]];

                        ++completedRows;
                        // Keep the same row
                        ++y;
                    }

                if (completedRows) {
                    // Print againt the table
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    for (let y = MIN_VALID_ROW; y < FIELD_HEIGHT; ++y) {
                        for (let x = 0; x < FIELD_WIDTH; ++x) {
                            if (FIELD[y][x] !== false) new Tetromino([x], [y], FIELD[y][x]).draw();
                        }
                    }

                    score += [40, 100, 300, 1200][completedRows - 1];
                    lines += completedRows;
                } else {
                    // Check if player has lost
                    if (FIELD[MIN_VALID_ROW - 1].some(block => block !== false)) {
                        alert("Game Over! n nScore: "+ score + "nLines Cleared: " + lines);
                        reset();
                    }
                }


            } else
                tetromino.update(i => ++tetromino.y[i]);
        }
        // No tetromino failing
        else {

            scoreLbl.innerText = score;
            linesLbl.innerText = lines;

            // Create random tetromino
            tetromino = (({ x, y }, color) =>
                new Tetromino([...x], [...y], color)
            )(
                TETROMINOES[Math.floor(Math.random() * (TETROMINOES.length - 1))],
                Math.floor(Math.random() * (Tetromino.COLORS.length - 1))
            );

            tetromino.draw();
        }

        setTimeout(draw, delay);
    }

    // Move
    window.onkeydown = event => {
        playMusic();
        switch (event.key) {
            
            case "ArrowLeft":
                if (!tetromino.collides(i => ({ x: tetromino.x[i] - 1, y: tetromino.y[i] })))
                    tetromino.update(i => --tetromino.x[i]);
                
                break;
            case "ArrowRight":
                if (!tetromino.collides(i => ({ x: tetromino.x[i] + 1, y: tetromino.y[i] })))
                    tetromino.update(i => ++tetromino.x[i]);
                break;
            case "ArrowDown":
                delay = Tetromino.DELAY / Tetromino.DELAY_INCREASED;
                break;
            case " ":
                tetromino.rotate();
                break;
            case "ArrowUp":
                tetromino.rotate();
                break;
        }
    }
    window.onkeyup = event => {
        if (event.key === "ArrowDown")
            delay = Tetromino.DELAY;
    }

}

I tried to load the tetris file and expect the game to be playable (it has worked before but it wasnt on apache it was on an esp32 webserver were i posted the file ) but after a lot of troubleshooting the only color that was loading was blue

React multiple filter functionality on an API call

I am working on this React JS assignment in which I am fetching data and displaying it on my screen. Here’s my code:

const Home = () => {
  const [jobs, setJobs] = useState();
  const [filteredJobs, setFilteredJobs] = useState();

  const jobData = async () => {
    const data = await fetch(" http://localhost:3031/jobs");
    const json = await data.json();
    setJobs(json);
    setFilteredJobs(json);
  };

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

  const cityFilter = (e) => {
    if (e.target.value === "All") {
      setFilteredJobs(jobs);
    } else {
      const newJobs = jobs.filter((val) => val.location === e.target.value);
      setFilteredJobs(newJobs);
    }
  };

  const expFilter = (e) => {
    if (e.target.value === "All") {
      setFilteredJobs(jobs);
    } else {
      const newJobs = jobs.filter((val) => val.yoe === e.target.value);
      setFilteredJobs(newJobs);
    }
  };

  return (
    <div>
      <Header />
      <div>
        <select name="select city"  onChange={cityFilter}>
          <option value="All"> All</option>
          <option value="Bengaluru">Bengaluru</option>
          <option value="Pune">Pune</option>
          <option value="Hyderabad">Hyderabad</option>
          <option value="New Delhi">New Delhi</option>
          <option value="Gurugram">Gurugram</option>
        </select>
      </div>
      <div>
        <select name="select experience" onChange={expFilter}>
          <option value="All">All</option>
          <option value="Internship">Internship</option>
          <option value="Fresher">Fresher</option>
          <option value="Early Professional">Early Professional</option>
          <option value="Professional">Professional</option>
        </select>
      </div>
      <div
        style={{
          display: "flex",
          flexWrap: "wrap",
          padding: "8px",
          gap: "4px",
          justifyContent: "center",
          marginTop: "8px",
        }}
      >
        {filteredJobs?.map(({ id, title, img, location, role, yoe }) => {
          return (
            <JobCard
              key={id}
              id={id}
              title={title}
              
              location={location}
              role={role}
            />
          );
        })}
      </div>
    </div>
  );
};

export default Home;

Currently I am stuck on applying multiple filters at the same time e.g, say a particular city is selected from filter option, a filtered city list is shown but when I go on to select another filter it filters from all my fetched API rather than selecting from city filtered data. I was trying to solve this issue by using useeffect but I am getting errors.

how can I find documents that aren’t referenced by a document from another collection

I have two models called session and unreadcount. I need to get that particular session count from another table. below are my two Mongodb models.

var UnreadCountSchema = new mongoose.Schema({
    userId: { type: String, required: true },
    sessionId: { type: String, required: true},
    unreadCount: { type: Number, required: true, default: 0  },
    isDeleted: { type: Boolean, required: true, default: 0 },
}, { timestamps: true });

module.exports = mongoose.model("UnreadCount", UnreadCountSchema);

var SessionSchema = new mongoose.Schema({
    name: { type: String, required: false },
    subject: { type: String, required: false },
    sessionCode: { type: String, required: false },
}, { timestamps: true });
module.exports = mongoose.model("Session", SessionSchema);

I have not used referencing and relation. I need to get a count when I fetch the session. I have tried lookup it doesn’t work. suggest me a way to do this

The following is my code that i executed. count is there but iam not getting the result.

const response = await SessionModel.aggregate([
            {
                $match: query,
            },
            {
                $lookup: {
                    from: "UnreadCount",
                    localField: "_id",
                    foreignField: "sessionId",
                    as: "unreadCounts",
                },
            },
            {
                $addFields: {
                    unreadCount: {
                        $cond: {
                            if: { $gt: [{ $size: "$unreadCounts" }, 0] },
                            then: { $arrayElemAt: ["$unreadCounts.unreadCount", 0] },
                            else: 0,
                        },
                    },
                },
            },
            // Optionally sort the sessions by lastMessage createdAt
            // { $sort: { "lastMessage.createdAt": -1 } },
        ])

Route.get() requires a callback function but got object string

I have gone through the other similar posts but not sure or experienced enough to relate the resolution suggestions on my project.
I have created a simple app with two main routes as part of my learning through a udemy course, however, i cannot get around this issue of Error: Route.get() requires a callback function but got a [object String]. I know that that main aim is to export the router object containing all the nested routes for a root route but the fact that the error is asking for a callback doesn’t make sense to me. Also the source of the error is the route.js file in the main node_modules library, node_modulesexpresslibrouterroute.js:211:15.

Tried a new test controller, same issue when running that file even without importing any of the route files. Deleted the route.js file from the library, new error shows up, Error: Cannot find module ‘./route’. Officially stuck.

Insights and suggestions would be absolutely appreciated .
I have added the route, controller and package.json files below for reference.

controller (app.js)

const express = require('express');
const ejs = require('ejs');
const Joi = require('joi');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const session = require('express-session');
const path = require('path');
const ejsMate = require('ejs-mate');
const app = express();

mongoose.connect('mongodb://127.0.0.1:27017/yelp-camp-new')
    .then(
        console.log('Connected to YelpCamp New db')
    )
    .catch(e => {
        console.log('error');
        console.log(e);
    }
    );

app.get('view engine', 'ejs')
app.engine('ejs', ejsMate);
app.set('views', path.join(__dirname, '/views'));
app.use(express.json()) // parse json api data
app.use(express.urlencoded(({ extended: true }))); // parse form data encoded in body
app.use(methodOverride('_method')); // method over-ride for post requests


//Session and flash
const sessionConfig = { 
    secret: 'Thi$i$m7secret',
resave: false, 
saveUninitialized: false,
cookie:{
   httpOnly: true, // extra layer of security
   _expires: Date.now() + 1000 *60*60*24*7,
   maxAge: 1000*60*60*24*7
}
};
app.use(session(sessionConfig));
app.use(flash()); // flash middleware


// Serving Static files from public dir, like js and css files.
app.use(express.static(path.join(__dirname, '/public')));

// importing the routes
const campRoute = require('./routes/campRoutes');
app.use('/campgrounds', campRoute);


// =========================
// error middleware
app.use((err, req, res, next) => {
    const {message = 'Something went wrong.', status = 500} = err;
    res.status(status);
    res.render('error', {err, status})
    next(err);
})


// middleware for all the other routes not defined in this app
app.use('*', (req, res) =>{
    res.send('This page does not exist')
})

app.listen(3000, ()=>{
    console.log('Listening on port 3000')
})

//==================================================================================================
route file (campRoutes.js)

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

// pott.get('/', async (req, res)=>{
//    const camps = await Campground.find({});
//    res.render('showAllCamps', {camps});

// });


router.get('/new', (req, res)=>{
    res.render('new');
});

router.post('/', async(req, res)=>{
    const {campground} = req.body;
    console.log(campground);
})

module.exports = router;

//==================================================================================================

package.json file

{
  "name": "yelpcamp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {

    "connect-flash": "^0.1.1",
    "ejs": "^3.1.9",
    "ejs-mate": "^4.0.0",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "joi": "^17.11.0",
    "method-override": "^3.0.0",
    "mongoose": "^8.0.1"
  }
}

Custom Css on Theme APEX 23.1 won’t apply

I’ve added a custom css on my theme for JSON Configuration section of theme.
and Here’s what I do :

 {"customCSS":"",
"vars":{"@g_Accent-BG":"#505f6d",
"@g_Accent-OG":"#ececec",
"@g_Body-Title-BG":"#dee1e4",
"@l_Link-Base":"#337ac0",
"@g_Body-BG":"#f5f5f5"}}

But some of color like #505f6d won’t apply at all . Where did I go wrong ?

scrollIntoView go to section instantly

I was trying to make a simple full page scroll effect with the scrollIntoView method. But it just jump to the section instantly instead of ‘smooth scrolling’ although I have already set this in the option behavior: "smooth".

I’m using the latest version of Edge, I have also tested on Firefox, both are not working. The reason why I test on different browser is because I have try Google relevant tutorial, weirdly their example are not working too, so I wonder is it my code is wrong or something is wrong with my browser or laptop:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_scrollintoview
https://www.javascripttutorial.net/javascript-dom/javascript-scrollintoview/

Watch my record: https://streamable.com/xbfh31

Below is the minimal code that you can test:

document.addEventListener("DOMContentLoaded", () => {
  const sections = document.querySelectorAll(".section");
  let currentSection = 0;

  function scrollToSection(index) {
    sections[index].scrollIntoView({ behavior: "smooth" });
    currentSection = index;
  }

  // Mouse Wheel Event
  document.addEventListener("wheel", (event) => {
    if (event.deltaY > 0 && currentSection < sections.length - 1) {
      scrollToSection(currentSection + 1);
    } else if (event.deltaY < 0 && currentSection > 0) {
      scrollToSection(currentSection - 1);
    }
  });

  // Touch Events for Mobile Devices
  let touchStartY = 0;
  let touchEndY = 0;

  document.addEventListener("touchstart", (event) => {
    touchStartY = event.touches[0].clientY;
  });

  document.addEventListener("touchend", (event) => {
    touchEndY = event.changedTouches[0].clientY;

    const deltaY = touchEndY - touchStartY;

    if (deltaY > 0 && currentSection > 0) {
      scrollToSection(currentSection - 1);
    } else if (deltaY < 0 && currentSection < sections.length - 1) {
      scrollToSection(currentSection + 1);
    }
  });
});
body,
html {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

.section {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2em;
}

#section1 {
  background-color: blue;
}

#section2 {
  background-color: green;
}

#section3 {
  background-color: gray;
}
<div id="section1" class="section">
  <h2>Section 1</h2>
</div>
<div id="section2" class="section">
  <h2>Section 2</h2>
</div>
<div id="section3" class="section">
  <h2>Section 3</h2>
</div>

How can I iterate over anchors assigned to JavaScript functions in Selenium using python?

I am working on a web scraping project using Selenium in Python. I have successfully scraped a set of anchors from a website, and I want to iterate over these anchors, click each link, run some code to extract data from the webpage, and then move to the next anchor in the set.

The anchors I’m working with look like this:

    <a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$GridView1','Page$2')">2</a>
    <a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$GridView1','Page$3')">3</a>

I have stored these anchors in a variable as follows:

    anchors = d.find_elements(By.XPATH, '//*[@id="ContentPlaceHolder1_GridView1"]/tbody/tr/td/table/tbody/tr/td/a')

When I attempt to iterate over the anchors and click each link, I encounter a StaleElementReferenceException. Here’s a simplified version of my code:

    i = 0
    for a in anchors:
        anchors[i].click()
        *Code to extract data from the webpage*
        i += 1

I have tried various versions of this code, including more robust solutions found in other Stack Overflow threads, but the issue persists. The error message I receive is:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found

I have checked that the table containing the anchors and the anchors themselves do not change when navigating between pages. The XPaths for both remain the same.

I have referred to the following Stack Overflow threads without success:

Fetch all href link using selenium in python
Selenium: Iterating through groups of elements

I would greatly appreciate any guidance or solutions to resolve this issue. Thank you in advance.

hey guys, How can I get an auto incrementing ID that is created when sending data via AJAX and PHP?

I want the buyer_id data to display through SQL on another page. This is how I try to get it from the other page

 
<?php
include(“bd_con.php”);
$buyer-id= $_GET[‘buyer-id’];

       echo "<script>                  alert('$buyer_id')</script>";

    $query = "SELECT name, email,               city, province, identification, address, 

          extra-details, image, title, description, id_type FROM `purchased_property` inner join 

property ON purchased_property.property-id = property.id WHERE buyer-id=’$buyer-id'”;

            $linking = mysqli_query($bd_con, $query);

              $info = mysqli_fetch_assoc($linking);

?>
 
this is the form from the page I send data through AJAX
 

                <div class="form">
                    <h2>Personal data</h2>
                   <input type="text"    placeholder="Full name" id="full_name"
        name="full_name"></input>
                   <label>Date of birth</. label>
                  <input type="date"     id="date_birth" name="date_birth">
                  <div   id="paypal-button-container"></div>
       
               </div>
              </form>

 

Just as I showed you up guys, I tried by $_GET but didn’t work. I hope you can help me:)

Delay in Updated Metadata Reflection on SEO Engines and Social Media Platforms: Seeking Insights on Timelines and Expedited Updates [migrated]

Hello Stack Overflow community,

Despite correctly implementing metadata tags within my web application, I’ve noticed a delay in their reflection on SEO engines and social media platforms like Facebook. The meta tags appear accurately when inspected within the section of the HTML. I’ve employed a code snippet that updates meta tags using the setMetaTags function triggered by the useEffect hook when currentPost is available. However, I’m curious about the time it takes for these changes to take effect in search engine results and platform previews. Any insights or estimated durations for when these platforms typically update their indexes and caches after metadata changes are made would be greatly appreciated. Below is the snippet of code used to update the meta tags:

useEffect(() => {
    if (currentPost) {
        setMetaTags();
    }
}, [currentPost]);

const setMetaTags = () => {
    if (typeof window !== 'undefined') {
        document.title = currentPost.title;

        // Setting description meta tag
        const descriptionMeta = document.querySelector(
            'meta[name="description"]'
        );
        if (descriptionMeta) {
            descriptionMeta.setAttribute(
                'content',
                currentPost.shortdescription
            );
        } else {
            const newDescriptionMeta = document.createElement('meta');
            newDescriptionMeta.setAttribute('name', 'description');
            newDescriptionMeta.setAttribute(
                'content',
                currentPost.description
            );
            document.head.appendChild(newDescriptionMeta);
        }

        // Setting image meta tag
        const imageMeta = document.querySelector(
            'meta[property="og:image"]'
        );
        if (imageMeta) {
            imageMeta.setAttribute('content', currentPost.image);
        } else {
            const newImageMeta = document.createElement('meta');
            newImageMeta.setAttribute('property', 'og:image');
            newImageMeta.setAttribute('content', currentPost.image);
            document.head.appendChild(newImageMeta);
        }
    }
};

Thank you in advance!

Make selected element stay at one place while scrolling the neighbouring elements in a carousel like setting

I’m trying to create a lightbox,

I have a thumbnail carousel at the bottom of the images that you click on to change the displayed image. I want to make it so that when you click on any thumbnail, it scrolls to the center of the page making it seem like the selected element remains constantly at the center of the screen.

What I’ve done till now is I’ve added a dynamic left padding to the ThumbnailViewer container.

const ThumbnailViewer = (props) => {
const {
    images = [],
    currentImage = 0,
    thumbnailWidth
} = useContext(LightboxContext);

const getThumbnailViewerPaddingLeft = () => {
    if (thumbnailWidth) {
        return `calc(95vw - ${(thumbnailWidth * (currentImage + 1))}px)`
    }

}
const getThumbnailViewerPaddingRight = () => {
    if (thumbnailWidth) {
        return `calc(95vw - ${thumbnailWidth}px)`
    }

}

return (
    <div className={styles.thumbnailViewer} style={{ paddingLeft: getThumbnailViewerPaddingLeft() }}>
        {images.map((el, i) => <ThumbnailIcon img={el.src} alt={el.alt} selected={i == currentImage} current={i} />)}
    </div>
)

}

I’m unable to get it centred as you can see in this gif below and I’m not sure if this approach is right. I’m thinking to dynamically reduce left padding and then add right padding to it constantly so that when clicking on the right most element it gets to the center too.

enter image description here

Can someone help me if I’m on the right path or there is a better way to do this?

SCEditor: Dropdown is out of place

When I create the sceditor like in the example, the dropdowns that appear when clicking on the font icon appears in its normal place.

        var textarea = document.getElementById('example');
        sceditor.create(textarea, {
            format: 'bbcode',
            icons: 'monocons',
            autofocus: true,
            style: '../minified/themes/content/default.min.css'
        });

However, once I specify my own toolbar, the dropdown is moved off screen and I have to scroll down for ages to find it.

        var textarea = document.getElementById('example');
        sceditor.create(textarea, {
            format: 'bbcode',
            icons: 'monocons',
            autofocus: true,
            style: '../minified/themes/content/default.min.css',
            toolbarContainer: document.getElementById('toolbar')
        });

Any way to correct the positioning while having a custom toolbar?