How can i test my projects without HTTPS?

every time i want to test a project in my phone or another laptop the brwsr say


Error accessing media devices: DOMException: The request is not allowed by the user agent or the platform in the current context.


and say the Connection isn’t secure and this website don’t have SSL cert
enter image description here
SORRY FOR VIBE CODED CSS

i tried to disable HTTPS only mod and i changed many things from setting

how to bind data to a listening rectangle in a d3 line chart

I’m working on creating a tooltip in a D3 line chart. A tutorial I was following (https://www.youtube.com/watch?v=uyPYxx-WGxc) gave me some code, but the tutorial handled data differently than I have. In my code, the data is bound to the chart line, not to the entirety of the D3 code.

I think I got the data also bound to the rectangle, but I’m not sure. I put in the tutorial’s code for the listeningRect mouseover method, but when I run the page, the variable xPos is the same no matter where I put my mouse.

What am I doing wrong please? Did I handle the data binding improperly?

See my code: https://codepen.io/lschneiderman/pen/VYemXyv

html:

<div id="container"></div>

css:

.x.label, .y.label {
    font-weight: bold;
    font-size: 1rem;
}
.x.label {
    margin-left: -50%;
}

rect {
    pointer-events: all;
    fill-opacity: 0;
    stroke-opacity: 0;
    z-index: 1;
    background-color: transparent;
}

.tooltip {
    position: absolute;
    padding: 10px;
    background-color: steelblue;
    color: white;
    border: 1px solid white;
    border-radius: 10px;
    display: none;
    opacity: .5;
}

js:

var data = [ {'year':'2007', 'percent':'.05'}, {'year':'2008', 'percent':'.10'}, {'year':'2009', 'percent':'.15'}, {'year':'2010', 'percent':'.25'} ];
        sendData(data);
        function sendData(data) {
            const width = 1140;
            const height = 400;
            const marginTop = 20;
            const marginRight = 20;
            const marginBottom = 50;
            const marginLeft = 70;
            
            //var data = [ {'year':'2007', 'percent':'.05'}, {'year':'2008', 'percent':'.10'}, {'year':'2009', 'percent':'.15'} ]
            
            const x = d3.scaleUtc()
                .domain([new Date("2007-01-01"), new Date("2023-01-01")])
                .range([marginLeft, width - marginRight]); //same as .range([70,1120])

            const y = d3.scaleLinear()
                .domain([0, .5])
                .range([height - marginBottom, marginTop]); //same as .range([350, 20])
                
            const svg = d3.create("svg")
                .attr("width", width)
                .attr("height", height);

            svg.append("g")
                .attr("transform", `translate(0,${height - marginBottom})`)
                .call(d3.axisBottom(x)
                    .ticks(d3.utcYear.every(1))
            );

            svg.append("text")
                .attr("class", "x label")
                .attr("text-anchor", "end")
                .attr("x", width/2)
                .attr("y", height - 6)
                .text("Year");

            svg.append("text")
                .attr("class", "y label")
                .attr("text-anchor", "end")
                .attr("x", -height/3)
                .attr("y", 6)
                .attr("dy", ".75em")
                .attr("transform", "rotate(-90)")
                .text("Percent");

            svg.append("g")
                .attr("transform", `translate(${marginLeft},0)`)
                .call(d3.axisLeft(y));
            
            var heightOfY = height-marginBottom;
            var Xmin = 2007;
            var Xmax = 2023;
            var numTicks = Xmax - Xmin + 1; //have to count the 0 point, so add 1
            var XmaxRange = width - marginRight;
            var eachTickWidth = XmaxRange / numTicks;
                
            let path=svg.append("path")
              .datum(data)
              .attr("fill", "none")
              .attr("stroke", "steelblue")
              .attr("stroke-width", 1.5)
              .attr("d", d3.line()
                .x(function(d) { 
                    //return x(d.year) 
                    var mine = ((d.year - Xmin)*eachTickWidth) + marginLeft; 
                    //return x(d.year); 
                    return(mine); console.log(d.year); 
                    })
                .y(function(d) { 
                    return y(d.percent) 
                    })  
            );
            
            const tooltip = d3.select("svg")
                .append("div")
                .attr("class", "tooltip");
            
            const circle = svg.append("circle")
                .attr("r", 0)
                .attr("fill","steelblue")
                .style("stroke","white")
                .attr("opacity", .70)
                .style("pointer-events","none");
            
            const listeningRect = svg.append("rect")
                .datum(data)
                .attr("width", width)
                .attr("height", height);
                
            listeningRect.on("mousemove", function(event){
                const [xCoord] = d3.pointer(event, this);
                const bisectData = d3.bisector(d => data.year).left;
                const x0 = x.invert(xCoord);
                const i = bisectData(data, x0, 1);
                const d0 = data[i-1];
                const d1 = data[i];
                const d = x0 - d0.year> d1.year- x0 ? d1 : d0;
                const xPos = x(d.year);
                const yPos = y(d.percent);
                
                circle.attr("cx", xPos)
                .attr("cy", yPos);
                
                console.log(xPos); //always gives the same variable
            });
            
            container.append(svg.node());
     
        } //end function sendData

What security practices should a beginner React developer follow when contributing to open-source apps? [closed]

I am learning React and contributing to small open-source projects. While working on issues, I want to ensure my code does not introduce security risks. Specifically:

  • How should I handle user input validation (XSS, injection risks) in React forms?
  • Are there recommended patterns for securely storing API keys in open-source projects?
  • When working with authentication (JWT, OAuth, Firebase), what pitfalls should I avoid?
    Since all contributions are reviewed, I’d like to make sure I follow secure coding standards from the start.

I’ve been contributing to small React projects and tried a few approaches already:

  • For input validation, I’ve used basic on Change checks and libraries like validator.js, but I’m not sure if that’s enough to prevent XSS or injection attacks.
  • For API keys, I tried storing them in .env files (with .gitignore), but I see some projects exposing keys in frontend code, and I’m confused about what’s truly secure for open source apps.
  • For authentication, I experimented with JWTs in localStorage/sessionStorage, but I’ve read that it may have XSS risks, so I’m unsure what the safer alternative is.

I was expecting to find a clear set of best practices that beginner contributors can follow consistently across open-source React projects. Instead, I’m finding mixed advice, and I’d like guidance from experienced developers on what’s actually recommended in 2025.

error in counting the repeated words in a Java program

I wrote a a program to count the occurrences of words in a
paragraph but it shows all counting 1.

    for (String word : words) {
        // Increment count if word exists, else start with 1
        wordCount.put(word, 1);
    }

but I got the output
A: 1
a: 1
for: 1
My: 1
horse!: 1
kingdom: 1

can anyone please help me to fix this

Multiple Slick Slider and the inital slider display should be 1 only

I am using slick slider in my project and here’s the scenario. In my project there are multiple slider 3 items but the initial slider display should be 1 only on right side.
Example image:
enter image description here

After clicking the right button then will display two items
enter image description here

and if continue clicking of right button it will display the 3 items and so on. I tried the initialSlide but no luck with it, can someone please help me with this?
enter image description here

Also, clicking the left button will also go back to his orginal state:
enter image description here

My “for loop” doesn’t work in Playwright.js Part2

https://enotes.pointschool.ru/login On this website (login test, password test).
I need to add to cart 1 product without discount.test('Тест-кейс 2. Переход в корзину с 1 неакционным товаром.', async({ page }) => {await page.type('css = [placeholder="Логин клиента"]', 'test') await page.type('css = [placeholder="Пароль клиента"]', 'test') await page.locator('xpath = //button[text()="Вход"]').click() for (const row of await page.locator('.note-item.card.h-100').all()){const classes = (await row.getAttribute('class'))?.split(' ') ?? []; if(!classes.includes('hasDiscount')){await page.locator('button.actionBuyProduct ').first().click()}}})
My logic was for loop should check all product on page and if find product without class discount, should click on button buy
product
button Buy
I tried many times, but item not added to cart

Error: ENOENT: no such file or directory, open ‘public/temp/1.png’

I am trying to upload files from local storage to cloudinary using multer and even though I have the folder public/temp created and the Image added to it, when I try to post the information using postman to test my code I get the following error.

multer.middleware.js

import multer from "multer"

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/temp")
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

export const upload = multer({
        storage,
}) 

user.routes.js

import {Router} from 'express'
import {registerUser} from '../controllers/user.controller.js'
import {upload} from '../middlewares/multer.middleware.js'

const router = Router()

router.route("/register").post(
    upload.any(),
    registerUser
)

export default router

user.controller.js

import {asyncHandler} from '../utils/asyncHandler.js'
import {apiError} from '../utils/apiError.js'
import {User} from '../models/user.model.js'
import {uploadOnCloudinary} from '../utils/cloudinary.js'
import {apiResponse} from '../utils/apiResponse.js'

const registerUser = asyncHandler(async (req,res)=>{
    const {username,password,email,fullName} = req.body
    console.log("Email: ",email);

    console.log("req.files:", req.files);
    console.log("req.body:", req.body);

    if([fullName,username,email,password].some((field)=>field?.trim()==="")){
        throw new apiError(400, "All fields are required")
    }

    const existedUser = await User.findOne({
        $or: [{ username },{ email }]
    })

    if(existedUser){
        throw new apiError(409, "User with email or password already exists")
    }

    const avatarLocalPath = req.files?.avatar[0]?.path;
    let coverimageLocalPath;
    if (req.files && Array.isArray(req.files.coverimage) && req.files.coverimage.length > 0) {
        coverimageLocalPath = req.files.coverimage[0].path
    }
    

    if(!avatarLocalPath){
        throw new apiError(400,"Avatar file is required")
    }

    const avatar = await uploadOnCloudinary(avatarLocalPath);
    const coverimage = await uploadOnCloudinary(coverimageLocalPath);

    if(!avatar){
        throw new apiError(400,"Avatar file is required");
    }

    const user = await User.create({
        fullName,
        avatar:avatar.url,
        coverImage: coverimage?.url||"",
        email,
        password,
        username: username.toLowerCase()
    })

    const createdUser = await User.findById(user._id).select(
        "-password -refreshToken"
    )

    if(!createdUser){
        throw new apiError(500,"Something went wrong while registering the user")
    }


    return res.status(201).json(
        new apiResponse(200, createdUser, "User registered Successfully")
    )
})

export {registerUser}

clodinary.js

import {v2 as cloudinary} from "cloudinary"
import fs from "fs"

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

const uploadOnCloudinary = async(localFilePath)=>{
    try{
        if(!localFilePath) return null;

        const response = await cloudinary.uploader.upload(localFilePath,{
            resource_type:"auto"
        })

        console.log("file has been uploaded to cloudinary: ",response.url);
        return response

    }catch(error){
        fs.unlinkSync(localFilePath);
        return null;
    }
}

export {uploadOnCloudinary}

I’ve tried a lot of resources to fix this code but nothing seems to work

I changed the user.routes.js from

upload.fields([
        {
            name: "avatar",
            maxCount: 1
        }, 
        {
            name: "coverImage",
            maxCount: 1
        }
    ])

to the one above but the error still persists,I’ve checked the casing of “avatar” and “coverImage” in postman and in my code and it is the same but the error still stays the same. Any suggestions on how to fix this.

Why does document.getElementById(“product-details”).innerHTML throw “null” error in my product detail function? [closed]

I’m working on a simple e-commerce front-end in JavaScript where I dynamically render a list of products on the index page, and when a product link is clicked, it should take the user to a product detail page.

All the scripts are written in the same JavaScript file.

Render All products on Index Page

productList.innerHTML = products.map((product) => `
  <div class="product">
    <img src="${product.image}" alt="${product.name}">
    <h2>${product.name}</h2>
    <p>${product.price}</p>
    <label for="size${product.id}">Size:</label>
    <select id="size${product.id}">
      ${product.sizes.map((size) => `<option value="${size}">${size}</option>`).join("")}
    </select>
    <label for="quantity${product.id}">Quantity:</label>
    <input type="number" id="quantity${product.id}" min="1" value="1">
    <button onclick="addToCart(${product.id})">Add to Cart</button>
    <a prod_id="${product.id}" class="details-link">View Details</a>
  </div>
`).join("");

Detail Page Renderer function

document.addEventListener('DOMContentLoaded', function () {
  function detailPageRender(productId) {
    console.log(productId);
    let productDetails = document.getElementById("product-details");

    // Find the product by ID
    let product = products?.filter((p) => p.id == parseInt(productId))[0];

    // Render product details
    if (product) {
      productDetails.innerHTML = `
        <div class="product">
          <img src="${product.image}" alt="${product.name}">
          <h2>${product.name}</h2>
          <p>${product.price}</p>
          <p>${product.description}</p>
          <label for="size">Size:</label>
          <select id="size">
            ${product.sizes?.map((size) => `<option value="${size}">${size}</option>`).join('')}
          </select>
          <label for="quantity">Quantity:</label>
          <input type="number" id="quantity" min="1" value="1">
          <button onclick="addToCart(${product.id})">Add to Cart</button>
        </div>
      `;
    } else {
      productDetails.innerHTML = "<p>Product not found.</p>";
    }
  }
});

When I try to open the product detail page, I get the following error:

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
    at detailPageRender

I’m also trying to handle clicks on the product links like this:

let detailLinks = document.getElementsByClassName('details-link');

for (let link of detailLinks) {
  link.addEventListener('click', function (e) {
    e.preventDefault();
    const productId = this.getAttribute('prod_id');
    detailPageRender(productId);
  });
}

Let me know if you’d like a refactored version of your code that handles page-specific scripts safely.

Does having scripts for multiple pages in one JS file cause this issue?

How can I prevent document.getElementById(“product-details”) from being null?

Is there a better way to separate page-specific logic?

I’m still learning JavaScript and I’d appreciate a clean explanation or a recommended approach for managing scripts across multiple pages.

Why if else operator does work incorrect or smth another? [closed]

I’ve write automatic switch for active menu item on page scroll used IntersectionObserver() But it don’t worked correct with different window height. I decided to add “if else” which will switch threshold value on different window height.
But now, when I use a conditional value, when the page refreshes, the second menu item lights up first, and the threshold count appears to start from the second menu item. If I specify a value without a conditional operator, everything works correctly.

Code:

let threshold

const observer = new IntersectionObserver((entries) => {

    if (window.innerHeight < 1080) {
        threshold = [0.5, 1, 0.5, 0.5]
    } else {
        threshold = [0.5, 1, 0.9, 1]
    }

    console.log(window.innerHeight)
    console.log(threshold)

    entries.forEach((entry) => {
        if (entry.isIntersecting) {
            document.querySelectorAll('.header__nav-menu__list__item').forEach((link) => {
                let id = link.getAttribute('href').replace('#', '')
                if (id === entry.target.id) {
                    link.classList.add('header__nav-menu__list__item--active')
                } else {
                    link.classList.remove('header__nav-menu__list__item--active')
                }
            })
        }
    })
}, {
    rootMargin: "-100px 0px 0px 0px",
    threshold: threshold
})

document.querySelectorAll('.block').forEach(block => { observer.observe(block) })

I tried adding smth like a zero element to the array to shift the counting order, but it didn’t work.

Firebase onCall function returning null even though await is there

I was able to successfully send this email with a onRequest call, but I would like to convert these on onCall Firebase calls. Here in my function below.

For the sake of privacy, I removed the company information and the HTML code.

exports.emailCall = functions.https.onCall(async (data, context) => {
    const name = data.name;
    const message = data.message;
    const email = data.email;
    const subject = data.subject;

    const myEmail = "[email protected]";


    const mailOptions = {
        from: 'Company <[email protected]>',
        to: myEmail,
        subject: 'You got an email from Company!',
        html: 'HTML_CODE'
    };

    await transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.send({
                ack: "success",
                success: false
            });
        }
        return res.send({
            ack: "success",
            success: true
        });
    });
})

This is how I am calling it from the app….

async function sendEmail(name, email, message, subject) {
    const contactForm = httpsCallable(fbFunctions, 'emailCall');

    const data = {
        name: name,
        email: email,
        message: message,
        subject: subject
    };

    try {
        const result = await contactForm(data);
        console.log('Function response:', result.data);    
    } catch (error) {
        console.error('Error calling function:', error);
    }
}

Result is coming back as null. Inside of the firebase function, I can add the return after the transporter call and it works fine, but I need to send the response within the transporter.

What am I doing wrong here?

I saw this post: Firebase Cloud onCall function return always null but I feel like I am using async/await properly

Streaming Response Shows PADDING Text in Answer

I’m implementing a streaming chat interface that receives real-time responses from a server, but I’m getting unwanted __PADDING__ text in the answers that should be filtered out.

Problem

My streaming response sometimes includes __PADDING__ markers with large whitespace blocks that appear in the final displayed answer. Here’s an example of what I’m seeing:

SmartQuest is an intelligent search assistant that helps users locate information quickly and effectively. It leverages advanced language understanding to interpret queries and deliver relevant, context-sensitive answers.
__PADDING__ 

__PADDING__ 
. The assistant is built to be intuitive and works seamlessly across multiple platforms, including desktop and mobile devices.

Key Features:

Intelligent Search: Uses AI-driven algorithms to provide accurate and meaningful results
__PADDING__ 

__PADDING__ 
.
2. Cross-Platform Access: Works on web browsers and mobile apps.
3. Instant Responses: Delivers answers in real-time.
4
__PADDING__ 

__PADDING__ 
. Customizable Options: Users can tailor search preferences, including depth and response format.

Relevant Code:

Frontend JavaScript (Streaming Handler):

function readStream() {
    return reader.read().then(({ done, value }) => {
        if (done) {
            console.log('Streaming complete!');
            isStreaming = false;
            $('#chatgpt-submit').removeClass('loading').prop('disabled', false);
            $('.streaming-cursor').remove();
            
            const finalFormatted = formatResponseText(accumulatedText);
            responseElement.html(finalFormatted);
            addCopyButton(responseElement);
            return;
        }
        
        chunkCount++;
        // Process new chunk and remove padding markers
        let chunk = decoder.decode(value);
        
        // Strip out padding sections
        chunk = chunk.replace(/n__PADDING__n[s]+n__PADDING__n/g, '');
        
        console.log(`Chunk #${chunkCount} received:`, chunk);
        
        accumulatedText += chunk;
        
        // Update display with formatted text and streaming cursor
        const formatted = formatResponseText(accumulatedText);
        responseElement.html(formatted + '<span class="streaming-cursor"></span>');
        
        return readStream();
    });
}

Backend PHP (Streaming Implementation):

private function stream_external_api($url, $data) {
    // ... setup code ...
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $post_data,
        CURLOPT_HTTPHEADER => [
            'Content-Type: 'application/json',
            'Content-Length: ' . strlen($post_data),
            'Accept: text/plain',
            'Cache-Control: no-cache'
        ],
        CURLOPT_RETURNTRANSFER => false,
        CURLOPT_HEADER => false,
        CURLOPT_TIMEOUT => 300,
        CURLOPT_BUFFERSIZE => 128,
        CURLOPT_WRITEFUNCTION => function($curl, $data) {
            // Output the actual chunk
            echo $data;
            
            // Use a unique delimiter + padding that client can strip
            echo "n__PADDING__n" . str_repeat(' ', 2048) . "n__PADDING__n";
            
            if (ob_get_level() > 0) {
                ob_flush();
            }
            flush();
            
            if (connection_aborted()) {
                return 0;
            }
            
            return strlen($data);
        }
    ]);
    
    // ... execute request ...
}

The Issue

The padding is added by the server to maintain connection flow, but it’s not being completely filtered out on the client side. Sometimes the padding appears in the middle of sentences, breaking up the answer.

How can I reliably remove all __PADDING__ markers and their associated whitespace from the streaming response without affecting the actual content? Is there a better approach to handle this server-side padding?

My “for loop” doesn’t work in Playwright.js

I need choose опе book without a sale. In the page I have 9 products in page and some of them have the class hasDiscount.

I need to choose the first product without the class hasDiscount. But: I need to click on te button Buy, because if I click on all products I can’t add them to the basket.

My code:

for(const row of await page.locator('.note-item.card.h-100').all())
{
  if (row.not.toHaveClass('hasDiscount'))
  {
    await page.locator('.actionBuyProduct').first().click()
  }
}

In the first row of my code I choose all 9 products, and if one of them doesn’t have the class hasDiscount then click on the button “Buy”.

But my code doesn’t work. What is wrong with it?

Product with class “hasDiscount”:

button “Buy”:

How I can fix it?

AWS pre-signed URL needs application/octet-stream to work with AJAX [closed]

I have the following C# code to generate pre-signed URLs, and it works (client is an AmazonS3Client object):

        public static string GetPreSignedURL(string filename, string displayFilename)
        {
            GetPreSignedUrlRequest request = new();

            request.Verb = HttpVerb.PUT;
            request.BucketName = BucketName;
            request.Key = filename;
            request.Expires = DateTime.UtcNow.AddHours(24);
            request.ContentType = "application/octet-stream";       //this is needed so we can upload using AJAX

            request.ResponseHeaderOverrides.ContentDisposition = "attachment; filename=" + displayFilename;

            return client.GetPreSignedURL(request);
        }

Now I have Jquery to make the PUT request:

                    $.ajax(
                    {
                        url: response1.preSignedURL,
                        type: 'PUT',
                        data: file,
                        processData: false,
                        contentType: "application/octet-stream",
                        success: function(response)
                        {
                            console.log(JSON.stringify(response));
                        }
                    });

It works fine. However if I remove application/octet-stream from the URL generator and the AJAX code, I get a dreaded SignatureDoesNotMatch error.

It would be nice to be able to remove the Content-Type header as it seems a bit hacky.

JS snippets are not working on chromium browsers [migrated]

Getting an error on stackoverflow when running any snippet on chromium browsers (tested on chrome and edge) it is working on firefox though.

(index):1  Refused to display 'https://stacksnippets.net/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

console.log("stacksnippets.net refused to connect");