Trouble passing a button to about page in my playwright test

I’m Fairly new to playwright and I’m wondering why my code:

< Link href="/about" >< button aria-label="About Us" >About Us</ button ></ Link>

< Link href="/contact" >< button aria-label="Contact Us" >Contact Us</ button ></ Link>

Fails to pass this test:

test('Button to link to about page', async ({ page }) => {
        await page.getByRole('button').click();

        await page.getByRole('link', { name: 'About' }).first().click();
    });

this is my error message:

home.spec.js:61:5 › Testing for button(s) › Button to link to about page

originally I had role="button" but I tried removing the role="button" attribute and it still gave me the same error message.

Form submission issue: data not inserting into database

I’m encountering an issue with my web form where the submitted data is not getting inserted into the database. I’ve manually added data to the database, but when I submit the form, nothing happens.

I have three files: index.php, script.js, and submit.php.

Could someone please assist me in troubleshooting this issue and identifying where the problem might be coming from?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Registration Form</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h2>Student Registration Form</h2>
        
        <!-- Display Error Message -->
        <?php
        if (isset($_GET['error'])) {
            echo "<p class='error'>{$_GET['error']}</p>";
        }
        ?>

        <form id="registrationForm" method="post" action="./submit.php">
            <div class="form-group">
                <label for="firstName">First Name:</label>
                <input type="text" id="firstName" name="firstName" required>
            </div>
            <div class="form-group">
                <label for="lastName">Last Name:</label>
                <input type="text" id="lastName" name="lastName" required>
            </div>
            <div class="form-group">
                <label for="phoneNumber">Phone Number:</label>
                <input type="tel" id="phoneNumber" name="phoneNumber" pattern="[0-9]{11}" required>
                <small>Format: 11 digits without spaces or dashes</small>
            </div>
            <div class="form-group">
                <label for="password">Password:</label>
                <input type="password" id="password" name="student_password" required>
            </div>
            <button type="submit">Submit</button>
        </form>
    </div>

    <script type="text/javascript" src="script.js"></script>
</body>
</html>

document.getElementById("registrationForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent the form from submitting

    // Get form values
    let firstName = document.getElementById("firstName").value;
    let lastName = document.getElementById("lastName").value;
    let phoneNumber = document.getElementById("phoneNumber").value;
    let password = document.getElementById("password").value;

    // Do something with the form values (e.g., send them to a server)
    console.log("First Name:", firstName);
    console.log("Last Name:", lastName);
    console.log("Phone Number:", phoneNumber);
    console.log("Password:", password);

    // Clear the form
    document.getElementById("registrationForm").reset();
});

<?php
// Database connection
$servername = "localhost";
$username = "root";
$db_password = ""; 
$dbname = "student_registration_portal";

// Create connection
$conn = new mysqli($servername, $username, $db_password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Form data
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$phoneNumber = $_POST['phoneNumber'];
$userPassword = $_POST['student_password']; 

// Insert data into database
$sql = "INSERT INTO students (first_name, last_name, phone_number, student_password)
        VALUES ('$firstName', '$lastName', '$phoneNumber', '$userPassword')";

// Execute SQL query
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    // Log error
    error_log("Error: " . $sql . "n" . $conn->error);
    
    // Output error message
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close database connection
$conn->close();
?>

the xampp mysql database and table

I’m encountering an issue with my web form where the submitted data is not getting inserted into the database. I’ve manually added data to the database, but when I submit the form, nothing happens.

I have three files: index.php, script.js, and submit.php.

Could someone please assist me in troubleshooting this issue and identifying where the problem might be coming from?

Added logs to check errors and its clean. enter image description here

I have added logs in script.js and error catching in submit.php but they are clean. I am using php 8.2.16 version and vs code

Increased memory usage with frequent useState calls in React Native Mobile application

In my React Native(JavaScript/TypeScript) mobile app, I have a component where I utilize the useState hook to update data every second. However, after running for 2 hours, the app exceeds its memory usage, leading to crashes in the iOS app when observed through Xcode.

The application crashes without giving any output.

For instance, when I set a constant variable, the memory usage remains stable:

setData(1);

But when I replace the data with different values, the memory usage starts to increase:

setData(previousData => previousData + 1);

OR

let test = Math.random(); setData(test);

How can I prevent or control the memory increase? Are there any optimizations I can apply to reduce memory usage with useState? Thanks.

Problems with JavaScript adding newlines forward

Environment

Edge: 122.0.2365.66
JQuery: 1.2

Problem Description

$("#xodv3fdv25gz span:nth-child(2)").before("<br>")
$("#xodv3fdv25gz span:nth-child(3)").before("<br>")

failure effect

The effect is in front of the second span

$("#xodv3fdv25gz span:nth-child(3)").before("<br>")
$("#xodv3fdv25gz span:nth-child(2)").before("<br>")

After swapping locations, it can operate normally.

success effect

I wish I knew why.

I’d appreciate it if you’d help me.

Get response headers before sending the response

How can I get the response headers before sending the request?

For example:

router.get("/", someMiddlewareThatSetsAHeader(), (req, res) => {
    console.log(res.getHeaders()["set-cookie"]); // undefined
    
    res.redirect("/anotherPage");

    console.log(res.getHeaders()["set-cookie"]); // the header value
})

Trying to log the header before sending the response causes the header to be undefined.

Chrome Extension waiting for ajax data to load before returning [duplicate]

I am writing a chrome extension which loads a specific page, gets some detail from it, then needs to click a button, wait for the data to load, then scrape the details, then click another button and so. The data loading is an ajax request and updates a section of the page.

async function processPage() {
    let [tab] = await chrome.tabs.query({active: true, currentWindow: true});

    chrome.scripting.executeScript({
        target: {tabId: tab.id},
        function: processHTML,
    },
        (results) => {
            doStuffWithTheResults(results[0].result);
        
    });
}

function processHTML() {
    var buttons = document.getElementsByClassName("c_carousel_button");
    
    processButton(0);
    
    let data = [];
    
    function processButton(buttonIdx) {
        buttons[buttonIdx].click();
        
        setTimeout(function() {
            const results = process()); //will read the data on the loaded elements
            data.push(results);
            
            buttonIdx++;
            
            if (buttonIdx < dateButtons.length) {
                processButtonDay(buttonIdx); //call the same function to work on the next button               
            } else {
            
            /*****
            *
            *  I WANTO RETURN data FROMHERE
            *            
            ******/
        },1000); // wait a second for the data to load after the button click
    }
    
    /* Its is returning from here before the data is loaded and processed in the code above
}

Because the timeout is async, it is returning bwefore this is complete. If I do a loop to wait for complete to be set, it bungs up the script and doesn;t do anything.

How can I return the data when all the processess are complete?

Error: SyntaxError: Unexpected end of JSON input

enter image description here

public static postStudent = async function (req: Request, res: Response) {
        const user = await AppDataSource.getRepository(User).create(req.body)
        const results = await AppDataSource.getRepository(User).save(user)
        return res.json(createSuccessResponse({ results }, "Add a students success"));
    }

    //edit a student
    public static putStudent = async function (req: Request, res: Response) {
        const user = await AppDataSource.getRepository(User).findOneBy({
            id: req.params.id,
        })
        AppDataSource.getRepository(User).merge(user, req.body)
        const results = await AppDataSource.getRepository(User).save(user)
        return res.json(createSuccessResponse({ results }, "Edit a student success"));
    }

This is my code, I don’t understand why when I run it it comes out like this

how bypass kleinanzeigen js-detected input in email?

I am doing an autoregistration on the site kleinanzeigen.de I ran into a problem, I bypassed the playwright/selenium detection in the browser, but there is a script that tracks text input with keys, do you have any ideas to get around this? When pressing a key, a script is called that writes something somewhere and does something, if I turn it off, registration does not go further (the registration button does not press), I make these accounts to promote my business.
PYTHON / JS

I’ve tried the standard input methods playwright/selenium, pyatogui

Resolving ‘Uncaught ReferenceError: require is not defined’ in JavaScript for DNS Server Change Script

I’m currently tackling a project aimed at creating a program to facilitate changing Windows DNS server settings. However, I’ve hit a snag in implementing my code. Whenever I attempt to utilize the code within my script file, I encounter the error message “Uncaught ReferenceError: require is not defined.

main.js :

const path = require('path');

function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 400,
        height: 600,
        resizable: false,
        frame: false,
        webPreferences: {
            // preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: false // Add this line
        }
    });

    mainWindow.loadFile('src/index.html');

    // Uncomment the line below if you want to open DevTools automatically
    // mainWindow.webContents.openDevTools();
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});

script.js :


function setDnsServers(preferredDNS, alternateDNS, connection) {
    try {
        // Set preferred and alternate DNS servers on Windows
        execSync(`netsh interface ipv4 set dns name="${connection}" static ${preferredDNS} primary`);
        execSync(`netsh interface ipv4 add dns name="${connection}" address=${alternateDNS} index=2`);
        console.log(`Preferred DNS server set to ${preferredDNS} and alternate DNS server set to ${alternateDNS}`);
    } catch (error) {
        console.error('Error setting DNS servers:', error);
    }
}

// Example usage:
// setDnsServers('8.8.8.8', '8.8.4.4', 'Wi-Fi');
setDnsServers('8.8.8.8', '8.8.4.4', 'Ethernet');

I’ve attempted several approaches to resolve the “Uncaught ReferenceError: require is not defined” issue in my JavaScript script for changing the DNS server. Initially, I explored various methods of including external modules or libraries within my script file, such as utilizing Node.js’s require function as demonstrated in my main.js file. However, despite my efforts, I continue to encounter the same error.

Ideally, I expected that by properly including the necessary modules or configuring my project setup appropriately, I would be able to seamlessly execute the code for changing the DNS server without encountering any runtime errors related to undefined references.

I’m eager to learn about alternative strategies or potential solutions that could help me overcome this obstacle and successfully execute my script.

Using chart.js to create bar chart where one record can have multiple colors

I am creating bar chart using chart.js which represents what medicine patient was taking and if it was working. X-axis is represented as timestamp.

In the image below you can see how it is supposed to look:
enter image description here

Green represents that medicine is working, red represents that it is not.
As you can one medicine can be working for a while and then stop (see Metotrexat in the image).

Do you have any idea how this can be done using chart.js?

As of now, I have implemented it as separate records but I face these issues:

  1. How to put that label over all parts that belongs under one medicine when it has multiple records?
  2. How to achieve that border-radius as it can be multiple separate records which just act as one?

Thank you for your opinions.

I have an issue with the result of additions and subtractions if the result is less than 5. Top many decimals [duplicate]

This is a Calculator I’m building. Whenever I try to do small subtractions or addition (e.g. 7.8 – 7.6) it shows up a very long strand of unnecessary decimals (0.20000000000000018).

You can find the entire code here https://github.com/Fallingstar-0/Calculator.

I have tried Math.floor, Math.ceil; but nothing works. I looked up on the internet and it seems it’s one of JS’s shenanigans.

For easier readability I’ll post the snippet below:

const formatter = new Intl.NumberFormat(undefined, {
  maximumFractionDigits: 0,
})

const format = (number) => {
  if (number == null) return
  const [integer, decimal] = number.split(".")
  if (decimal == null) return formatter.format(integer)
  return `${formatter.format(integer)}.${decimal}`
}

export const ACTIONS = {
  ADD_DIGIT: "add-digit",
  ADD_OPERATION: "add-operation",
  EVALUATE: "evaluate",
  CLEAR: "clear",
  DELETE_DIGIT: "delete-digit",
}

const reducer = (state, { type, payload }) => {
  if (type === ACTIONS.ADD_DIGIT) {
    if (state.overwrite) {
      return {
        ...state,
        currentOperand: payload.digit,
        overwrite: false,
      }
    }
    if(!state.currentOperand && payload.digit === ".") {
      return {
        ...state,
        currentOperand: `0.`
      }
    }
    if (payload.digit === "0" && state.currentOperand === "0") return state
    if (payload.digit === "." && state.currentOperand.includes(".")) {
      return state
    }
    return {
      ...state,
      currentOperand: `${state.currentOperand ?? ""}${payload.digit}`,
    }
  }
  if (type === ACTIONS.CLEAR) {
    return { state }
  }
  if (type === ACTIONS.ADD_OPERATION) {
    if (state.currentOperand == null && state.previousOperand == null) {
      return state
    }
    if (state.operation && state.currentOperand == null) {
      return {
        ...state,
        operation: payload.operation,
      }
    }
    if (state.previousOperand && state.currentOperand) {
      return {
        ...state,
        previousOperand: evaluate(state),
        operation: payload.operation,
        currentOperand: null,
      }
    }
    return {
      ...state,
      previousOperand: state.currentOperand,
      operation: payload.operation,
      currentOperand: null,
    }
  }
  if (type === ACTIONS.DELETE_DIGIT) {
    if (state.overwrite) {
      return {
        ...state,
        currentOperand: null,
        overwrite: false,
      }
    }
    if (!state.currentOperand) {
      return state
    }
    if (state.currentOperand.length === 1) {
      return {
        ...state,
        currentOperand: null,
      }
    }
    return {
      ...state,
      currentOperand: state.currentOperand.slice(0, -1),
    }
  }
  if (type === ACTIONS.EVALUATE) {
    if (!state.currentOperand && !state.previousOperand) {
      return state
    }
    if (state.currentOperand && state.previousOperand) {
      return {
        ...state,
        currentOperand: evaluate(state),
        previousOperand: null,
        operation: null,
        overwrite: true,
      }
    }
  }
}
// evaluate function
const evaluate = ({ currentOperand, previousOperand, operation }) => {
  const prev = parseFloat(previousOperand)
  const curr = parseFloat(currentOperand)

  let computation = ""
  if (isNaN(prev) || isNaN(curr)) {
    return ""
  }
  switch (operation) {
    case "/":
      computation = prev / curr
      break
    case "*":
      computation = prev * curr
      break
    case "+":
      computation = prev + curr
      break
    case "-":
      computation = prev - curr
      break
  }
  return computation.toString()
}

function App() {
  const [{ currentOperand, previousOperand, operation }, dispatch] = useReducer(
    reducer,
    {}
  )
  return (
    <div>
       ...Rest of code

I want to change the default color for the Fill and Border Color in the DrawerJs library

Is anyone here familiar with the DrawerJs library?

here is the link:
https://github.com/carstenschaefer/DrawerJs/wiki

I am using this library in my web application, and my problem is that I want to change the default color for the fill and border-color of shapes. I have already managed to change the default color in the color-picker, but I still need to click the color in the color-picker for it to change its color.

I am using the drawerJs.standalone.js

I already tried modifying some default colors in the drawerJs.standalone.js and managed to change the default color for the color-picker, but I cannot find the click event that triggers the color change for the default.

like these one.

  ShapeBorder.prototype.updateColorFromObject = function (object) {
    var color = null;
    color = object.get('stroke');
    if (color) {
      this.currentColor = color;
    } else {
      this.currentColor = pluginsNamespace.ColorpickerControl.TRANSPARENT;
      //changed this part to black;
    }
  };

also this one.

// setup colorpicker for border color
    this.colorpicker = new pluginsNamespace.ColorpickerControl(this.drawer, this.options);

    this.currentColor = this.options.color;
    //// change this one also to black
    this.currentBorder = this.options.borderTypes[this.options.defaultBorder];

but still I need to click the color-picker to change the color.

How to Append the values to React State variable

hello every one im new to js and react frame work
i want to know how the state variables in react get updated this is my code
import React, { useState } from ‘react’;

export default function Crud() {

const intital_setup = {
  name:'',
  email:''
}

const [formstate, setformstate] = useState({...intital_setup});

const handlestate = (e) => {
    setformstate({...formstate,[e.target.name]:e.target.value});
};

const submited = (e) => {
    e.preventDefault();
    console.log(formstate);
};

return (
    <>
        <form onSubmit={submited}>
            <div style={{ display: 'flex', flexDirection: 'row', gap: '10px', paddingLeft: '20px', paddingTop: '30px' }}>
                <label>Enter Name</label>
                <input type='text' name='name' value={formstate.name} onChange={handlestate} /><br />
            </div>
            <div style={{ display: 'flex', flexDirection: 'row', gap: '10px', paddingLeft: '20px', paddingTop: '30px' }}>
                <label>Enter Email</label>
                <input type='text' name='email' value={formstate.email} onChange={handlestate} /><br />
            </div>
            <div style={{ display: 'flex', flexDirection: 'row', gap: '10px', paddingLeft: '100px', paddingTop: '30px' }}>
                <input type='submit' />
            </div>
        </form>
    </>
);

}

from the code i can see the values which i have entered in text box in state variable
but here i have used spread operator so state variable need to be appended with the new values but previous values are overwritten by new values why?

How to hide API routes in Next JS frontend

I have made a NextJS application I want to protect/hide their /api routes as any user can access API routes just by typing URL/api/**/*. This is a security issue, I am using those API(s) in my app as backend.

I want to hide /api route from user so that no one can access that route from front end.