Issue with dynamic SVG rendering from JavaScript

I am foraying back into the world of web development, so there is a good chance that this is something silly I have overlooked.

I have been able to dynamically create all the HTML components for the SVG I am trying to create, however the resulting image isn’t displayed in it’s container. My aim is to create an SVG element with a random number of circles, this needs to be repeatable so that I can display more than one on the page at a time.

This is an example of what my code outputs:

<svg class="canvas" id="gen1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
 <filter id="shadow">
   <feDropShadow dx="0" dy="10" stdDeviation="2" flood-opacity="0.4"></feDropShadow> 
 </filter>
 <radialGradient id="highlight" cx="50%" cy="50%" r="50%" fx="50%" fy="25%">
  <stop offset="0%" stop-color="#FF4D4D"></stop>
  <stop offset="100%" stop-color="#8B0000"></stop>
 </radialGradient>
 <circle id="circle1" cx="500" cy="166.66666666666666" r="83.33333333333333" fill="url(#highlight)" filter="url(#shadow)"></circle>
 <circle id="circle2" cx="500" cy="666.6666666666666" r="83.33333333333333" fill="url(#highlight)" filter="url(#shadow)"></circle>
 <circle id="circle3" cx="166.6666666666669" cy="744.0169358562925" r="83.33333333333333" fill="url(#highlight)" filter="url(#shadow)"></circle>
 <circle id="circle4" cx="750.0000000000001" cy="599.6793685588859" r="83.33333333333333" fill="url(#highlight)" filter="url(#shadow)"></circle>
</svg>

If I take the above code and paste it into an online SVG viewer the output is exactly what I expect it to be. However inside the basic page I have built it doesn’t show any of the circles, even though when I inspect the HTML I can see all these elements there.

This is the code I am using to generate the SVG:

function buildCanvas(canvasNumber) {
    let canvas = buildNode(new Node("div", [new Attribute("class", "canvas"), new Attribute("id", "gen" + canvasNumber)], undefined, [
        new Node("h1", [new Attribute("class", "canvasTitle"), new Attribute("id", "canvas" + canvasNumber + "Title")], "Canvas " + canvasNumber),
        new Node("svg", [new Attribute("ns", "http://www.w3.org/2000/svg"), new Attribute("class", "canvas"), new Attribute("id", "canvas" + canvasNumber + "Layout"), new Attribute("xmlns", "http://www.w3.org/2000/svg"), new Attribute("viewBox", "0 0 1000 1000")], undefined,  [
            new Node("filter", [new Attribute("ns", "http://www.w3.org/2000/svg"), new Attribute("id", "shadow")], undefined, [
                new Node("feDropShadow", [new Attribute("ns", "http://www.w3.org/2000/svg"), new Attribute("dx", "0"), new Attribute("dy", "10"), new Attribute("stdDeviation", "2"), new Attribute("flood-opacity", "0.4")])
            ]),
            new Node("radialGradient",  [new Attribute("ns", "http://www.w3.org/2000/svg"), new Attribute("id", "highlight"), new Attribute("cx", "50%"), new Attribute("cy", "50%"), new Attribute("r", "50%"), new Attribute("fx", "50%"), new Attribute("fy", "25%")], undefined, [
                new Node("stop", [new Attribute("ns", "http://www.w3.org/2000/svg"), new Attribute("offset", "0%"), new Attribute("stop-color", "#FF4D4D")]),
                new Node("stop", [new Attribute("ns", "http://www.w3.org/2000/svg"), new Attribute("offset", "100%"), new Attribute("stop-color", "#8B0000")])
            ])
        ].concat(drawHole(canvases[canvasNumber - 1]))),
        new Node("h3", [new Attribute("class", "canvasTarget"), new Attribute("id", "canvas" + canvasNumber + "Target")], "Target " + canvases[canvasNumber - 1].target),
        new Node("div", [new Attribute("class", "canvasScores"), new Attribute("id", "canvas" + canvasNumber + "Scores")])
    ]));
    return canvas;
}

function drawHole(canvas) {
    const circlePositions = canvas.circles;
    let circleNum = 1;
    let circles = [];
    ballPositions.forEach(ball => {
        balls.push(new Node("circle", [
            new Attribute("ns", "http://www.w3.org/2000/svg"),
            new Attribute("id", "ball" + circleNum),
            new Attribute("cx", ball.x),
            new Attribute("cy", ball.y),
            new Attribute("r", 1000/12),
            new Attribute("fill", "url(#highlight)"),
            new Attribute("filter", "url(#shadow)")]))
        circleNum++;
    });

    return balls;
}

function buildNode(node = new Node("div")) {
    let nodeComp = document.createElement(node.type);
    if (node.attributes != null && typeof node.attributes !== "undefined" && node.attributes.length > 0) {
        let ns;
        for (let position = 0; position < node.attributes.length; position++) {
            if (node.attributes[position].type == "ns") {
                ns = node.attributes[position].value;
                nodeComp = document.createElementNS(ns, node.type);
                continue;
            }
            if (ns != null && typeof ns !== "undefined") {
                try {
                    nodeComp.setAttributeNS(ns, node.attributes[position].type, node.attributes[position].value);
                    continue;
                }
                catch (err) {

                }
            }
            let attribute = document.createAttribute(node.attributes[position].type);
            attribute.value = node.attributes[position].value;
            nodeComp.setAttributeNode(attribute);
        }
    }
    if (node.content != null && typeof node.content !== "undefined") {
        nodeComp.innerHTML = node.content;
    }
    if (node.childNodes != null && typeof node.childNodes !== "undefined" && node.childNodes.length > 0) {
        for (let childNode = 0; childNode < node.childNodes.length; childNode++) {
            nodeComp.insertAdjacentElement("beforeend", buildNode(node.childNodes[childNode]));
        }
    }
    return nodeComp;
}

If anyone can spot my mistake or niggle to make the circles display on the canvas please put me out of my misery.

Decoding encrypted API payload and response in client-side web application

I’m working on understanding the data flow in a web application for educational purposes. I’ve noticed some interesting behavior regarding an API endpoint and I’m trying to figure out how it works.

The scenario:

When the page loads, user information is displayed in plain text.
This information is fetched via a POST request to the /v1/account/user/basic endpoint. (allegedly)
Both the request payload and the API response appear to be encoded/encrypted.

My questions:

Given that the information is displayed in plain text on the page, but the API request/response are encoded, does this imply that the decoding is happening client-side using JavaScript?

Is there a way to determine the decoding method being used? I’ve tried using Burp Suite and Param Miner but haven’t had success so far.

Are there any recommended approaches or tools for analysing this kind of setup to understand how the data is being processed?

I’m relatively new to API analysis and would appreciate any insights or suggestions on how to approach this problem. Thanks in advance for any help!

Here is a screenshot from my Burp session displaying the API request/response

What I’ve Tried:

I’ve searched through the JavaScript files for decryption keys, am I looking in the wrong files? I’m not sure if I’m missing something obvious here.
I’ve used Param Miner to try and guess query parameters, but haven’t had any success.
I attempted to decode the payload/response using Base64, but it doesn’t seem to be that simple. The encoding looks more complex, possibly some form of SHA256.

How do you capture Mic as well as speaker audio at the same time in Chrome Extension via JavaScript

I have managed to get a working app that captures audio from speakers. Tested it on Youtube. But I want to capture the scenario where Mic is also working. Example? Google Meet and other Video conferencing.

I want to capture both the parties. Found a bit of a code at official documentation

Not sure how to merge the two codes. Can someone please help.

Note: Only want to do it in pure JavaScript as I have zero to very little knowledge of JS let alone React and others.

Thanks in advance

Issue with scandir, path, and undefined Error discord.js

Issue with scandir, path, and undefined Error

When using the scandir function in PHP, you might encounter an “undefined” error when looping through the result with foreach. This usually happens if the specified path is incorrect or if the scandir call returns an empty result.

To resolve this, ensure that the path is correct and add checks to handle cases where the directory cannot be read.


Error: ENOENT: no such file or directory, scandir ‘C:UsersAksaçlıDesktopdiscord-v14-bots-mainsrcbeş_trackers’
7|Supervis | syscall: ‘scandir’,
7|Supervis | path: ‘C:UsersAksaçlıDesktopdiscord-v14-bots-mainsrcbeş_trackers’
7|Supervis | }

Error: ENOENT: no such file or directory, scandir ‘C:UsersAksaçlıDesktopdiscord-v14-bots-mainsrcbeş_commands’
7|Supervis | errno: -4058,
7|Supervis | code: ‘ENOENT’,
7|Supervis | syscall: ‘scandir’,
7|Supervis | path: ‘C:UsersAksaçlıDesktopdiscord-v14-bots-mainsrcbeş_commands’
7|Supervis | }

TypeError: Cannot read properties of undefined (reading ‘forEach’)
7|Supervis | at C:UsersAksaçlıDesktopdiscord-v14-bots-mainSupervisorbeş.js:20:9
7|Supervis | at FSReqCallback.oncomplete (node:fs:187:23)

Unexpected error: TypeError: Cannot read properties of undefined (reading ‘forEach’)
7|Supervis | at C:UsersAksaçlıDesktopdiscord-v14-bots-mainSupervisorbeş.js:20:9
7|Supervis | at FSReqCallback.oncomplete (node:fs:187:23)


daha bir şey çıkmadıgı için

How to produce a string using JavaScript that contains a correctly escaped “&” character for LaTeX tables?

I am trying to write code to generate a LaTeX table using JavaScript. The problem is that I can’t find a way to escape ampersand characters in the resulting LaTeX. The result has either been an unescaped ampersand or an ampersand with 2 backslashes. This is part of a website and is on the client side, so it would be preferable not to have to use an NPM package.

I tried using replace and replaceAll. When I use replace like string.replace("&", "&"), it does not change anything with the string. When I use replace like string.replace("&", "\&"), it replaces the ampersand with “&” (a string with 2 backslashes). What I want is for it to replace the ampersand with “&”, aka a string with 1 backslash.

Why is Python slower than Javascript at calculating time

I know Python is supposed to be faster than Javascript.

Javascript:

console.log(Date.now());

VS (Python):

import time
print(int(time.time() * 1000))

I want to know how to speed this up.

The code is the same, but Python is slower than Javascript. How should I go about fixing this?

I would like to speed the Python code up to the same time as Javascript.

I have a few functions in my code that require this but the Python code is too slow for it.

Invalid hook call in react native

im tring to call this hook but im receiving this error

Possible Unhandled Promise Rejection (id: 6):
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

this is my code:

const handleEvento = async (dayy) => {
  useEffect(()=>{
    axios.get(`http://192.168.15.11:8085/api/readEventsByDate/${dayy}`)
         .then(response =>{
           //Ordenar os dados pelo id em ordem crescente
           const sortData= response.data.sort((a,b) => a.id - b.id);

    
           setData2(sortData);

           console.log(data2)
      
         })
       .catch(error => {
         console.log(JSON.stringify(error));
        });
  },[]);
}




onDayPress={day => {
    handleEvento(day.dateString)        
}}

i really dont know what im missing here if soomeone can helps i would be really glad

the indicator not work on tradingview show problem , i need solve it

//@version=5

İndicator(‘Nas Infinity Algo [ZZ Algo]’, overlay=true, format=format.price, precision=2)

Periods = 40

Src = hl2

Multiplier = input.float(title=’Sensitivity’, step=0.1, defval=7.2)

changeATR = true

showsignals = input(title=’Show Buy/Sell Signals ?’, defval=true)

highlighting = input(title=’Highlighter On/Off ?’, defval=false)

atr2 = ta.sma(ta.tr, Periods)

atr = changeATR ? ta.atr(Periods) : atr2

up = src – Multiplier * atr

up1 = nz(up[1], up)

up := close[1] > up1 ? math.max(up, up1) : up

dn = src + Multiplier * atr

dn1 = nz(dn[1], dn)

dn := close[1] < dn1 ? math.min(dn, dn1) : dn

trend = 1

trend := nz(trend[1], trend)

trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend

upPlot = plot(trend == 1 ? up : na, title=’Up Trend’, style=plot.style_linebr, linewidth=2, color=highlighting == true ? #4caf50 : #ffffff00)

buySignal = trend == 1 and trend[1] == -1

plotshape(buySignal and showsignals ? up : na, title=’Buy’, text=’Buy’, location=location.absolute, style=shape.labelup, size=size.normal, color=#4caf50, textcolor=color.new(color.white, 0))

dnPlot = plot(trend == 1 ? na : dn, title=’Down Trend’, style=plot.style_linebr, linewidth=2, color= highlighting == true ? #ff5252 : #ffffff00)

sellSignal = trend == -1 and trend[1] == 1

plotshape(sellSignal and showsignals ? dn : na, title=’Sell’, text=’Sell’, location=location.absolute, style=shape.labeldown, size=size.normal, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))

mPlot = plot(ohlc4, title=’’, style=plot.style_circles, linewidth=0)

longFillColor = highlighting ? trend == 1 ? #4caf4f0b : #ffffff00 : #ffffff00

shortFillColor = highlighting ? trend == -1 ? #ff52520e : #ffffff00 : #ffffff00

fill(mPlot, upPlot, title=’UpTrend Highligter’, color=longFillColor, transp=90)

fill(mPlot, dnPlot, title=’DownTrend Highligter’, color=shortFillColor, transp=90)

alertcondition(buySignal, title=’SuperTrend Buy’, message=’SuperTrend Buy!’)

alertcondition(sellSignal, title=’SuperTrend Sell’, message=’SuperTrend Sell!’)

changeCond = trend != trend[1]

alertcondition(changeCond, title=’SuperTrend Direction Change’, message=’SuperTrend has changed direction!’)

// Peak Profit

İmport protradingart/pta_plot/6 as pp

pp.peakprofit(buySignal, sellSignal)

// Bar Colors

Var color barColor = na

İf (sellSignal)

barColor := color.red

else if (buySignal)

barColor := color.green

else

barColor := barColor[1]

barcolor(barColor)

i need rewrite the script

Can I test fetch timeout using Jest?

  • node: 20.15.1
  • jest: 29.7.0
  • jest-environment-jsdom: 29.7.0
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });

I want to unit test the above line of javascript using Jest. Specifically the timeout behaviour. But is that actually possible?

No matter what I do, I have to mock the fetch function. I can make it reject or timeout or whatever, but I’m really just testing the functionality of the mock.

I kinda feel like this is where JS hands over to the web API. Therefore I can’t unit test it?

CSS button clock effect

I am currently developing a browser game, and I have a button to provide hints. I want to authorize the player to click on the “Hint” button after 60 seconds, and to show the loading time I would like the background of the button to show a “clock” effect, starting at 12 and rotating anti-clockwise until the time is up, with two colors showing . I have been looking online to try to find similar stuff, but I couldn’t find anything.

Here’s an example of what I had in mind:

enter image description here

Thanks for your help!

Getting an error on my webpage “Can not GET /”

I’m building a web development project and my server is running properly and my application is getting connected to MongoDB as well but when i open the local server in this case i’m using localhost:5001 then instead of getting the desired output i’m getting the text “Cannot Get /” and when i tried inspecting as well there is nothing, I restarted the server several time and refreshed my MongoDB and restarted my Postman application as well before it was running properly but after i did some code for nav bar it is happening since and i tried everything but no luck

import express from "express";
import dotenv from "dotenv";
import { connectDB } from "./config/db.js";
// import req from "express/lib/request.js";
// import res from "express/lib/response.js";
import productRoutes from "./routes/product.route.js"
import cors from "cors";

dotenv.config();

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

app.use(cors());

app.use(express.json()); // allows us to accept json data in the req.body

app.get('/', (req, res) => {
    console.log('Root route accessed'); // This will log to the console
    res.send('API is running...');
});

app.use((req, res, next) => {
    console.log(`Request Method: ${req.method}, Request URL: ${req.url}`);
    next();
});

app.use("/api/products", productRoutes);

app.listen(PORT, () => {
    connectDB();
    console.log('Server Started at http://localhost:'+ PORT);
});

This is my server.js file

Refused to execute inline event handler due to Content Security Policy (CSP) in Chrome extension

I’m building a Google Chrome extension that manages bookmarks on the new tab page. Everything works fine except for an issue with the removal of bookmarks from the favorites list. When I click the “delete” option in the dropdown, nothing happens, and I noticed that my console is throwing a Content Security Policy (CSP) error.

I understand that Chrome extensions enforce a strict CSP and disallow inline event handlers, but I’m struggling to find the correct way to resolve this issue. I would like to avoid using unsafe-inline due to security concerns.

Here is the specific error I’m receiving in the console:

Refused to execute inline event handler because it violates the
following Content Security Policy directive: “script-src ‘self'”.
Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce
(‘nonce-…’) is required to enable inline execution. Note that hashes
do not apply to event handlers, style attributes, and javascript:
navigations unless the ‘unsafe-hashes’ keyword is present.

I understand that this happens due to the use of inline event handlers (like onclick), but I’m not sure how to restructure my code to avoid this problem.

What I’ve tried:

  1. I attempted to modify my manifest.json to allow inline scripts by adding unsafe-inline, but I want to avoid this due to security risks.

  2. I tried using external JavaScript (script.js) to handle events via addEventListener(), but something seems to be missing or incorrectly set up.

    {
     "manifest_version": 3,
     "name": "My Bookmarks Manager",
     "version": "1.0",
     "description": "Manage your bookmarks on the new tab page.",
     "permissions": ["bookmarks"],
     "chrome_url_overrides": {
     "newtab": "newtab.html"
     },
     "content_security_policy": {
     "extension_pages": "script-src 'self'; object-src 'self';"
     }
     }
    
    
     <div id="favoritesContainer" class="mt-4"></div>
    
     <!-- Dropdown in card for deletion -->
     <ul class="dropdown-menu">
     <li><a class="dropdown-item text-danger" href="#" id="delete-123">Delete</a>. 
     </li>
     </ul>
    
    
     document.getElementById('delete-123').addEventListener('click', function(event) 
     {
     event.preventDefault();
     event.stopPropagation();
     deleteFavorite('123');  // Call the function to delete the bookmark
     });
    
     function deleteFavorite(url) {
     let favorites = getFavorites();
     favorites = favorites.filter(fav => fav.url !== url);
     localStorage.setItem('favorites', JSON.stringify(favorites));
     renderFavorites(); // Refresh the list
     }
    

I believe the issue lies with the CSP blocking inline event handlers, and possibly how I’m trying to remove bookmarks. I’m not sure if there’s a better way to add event listeners in my script.js or if I need to restructure my code to comply with the security policy.

How can I solve this issue without using unsafe-inline in my CSP?

Any guidance or suggestions would be greatly appreciated!

I want to detect in the client-side script that I have gotten a 401 error when fetching data with bad PAT (Using Azure DevOps REST API)

When I use an expired PAT attempting to access the REST end-point, in the browser’s Dev Tools console window I will get:

GET https://dev.azure.com/contoso/_apis/connectionData net::ERR_FAILED 401 (Unauthorized)

But it is impossible to get the fact that there’s a 401 status code from inside JavaScript. I’ve tried fetch with “then” / “catch” / and await with try/catch. I’ve also tried XMLHttpRequest. The only error I get is:

TypeError: Failed to fetch

Since the browser is clearly seeing the 401 (Unauthorized), I’d like to be detect that status code.

The browser Dev Tools console also has the following:

Access to fetch at 'https://dev.azure.com/contoso/_apis/connectionData' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

enter image description here

The Network tab shows the 401 status as well:

enter image description here

Using no-cors hides makes everything opaque, and you don’t get the 401 status.

Here’s a runnable sample:

<!DOCTYPE html>
<html>
  <body>
    <script>
(async function () {
  "use strict";

  const API_ORGANIZATION="contoso"

  const expiredPat = 'ts44tplifj4hbbzeitcz5dg5az4q3mpqcxqmrxo4zwlgy3scobzq'
  const pat = expiredPat

  // Fetch data from Azure DevOps
  async function ado(api) {
    const url = `https://dev.azure.com/${API_ORGANIZATION}/_apis/${api}`
    console.log(`url: ${url}`)
    const response = await fetch(url, {
      method: 'GET',
      cache: 'no-cache',
      mode: 'cors',
      headers: {
        Authorization: 'Basic ' + btoa(':' + pat),
        Accept: 'application/json',
      }
    })
    return await response.json()
  }

  // get the connectionData from Azure DevOps
  async function getConnectionData() {
    return await ado('connectionData')
  }

  function topText(text) {
    var p = document.createElement('p');
    p.innerHTML = text
    document.body.prepend(p)
    return p
  }

  // show the connection Data at the top of the window
  async function showConnectionData() {
    try {
      const result = await getConnectionData();
      topText(`Azure DevOps access authenticated as: ${result.authenticatedUser.providerDisplayName}`)
    } catch(err) {
      const p = topText(`${err} - See console`)
      p.style.color = "red";
      p.style.fontWeight = "999"
    }
  }

  async function tryFetch() {
    try {
      await showConnectionData()
    } catch(err) {
      console.log(err);
    }
  }

  document.addEventListener("DOMContentLoaded", function(event) {
    tryFetch()
  });

})();


    </script>
  </body>
</html>

How can I send data from an API form (with Javascript) to the functions.php file in WordPress e-commerce website?

I am using the Pledge API charity search widget that shows up on a product page so that the user can select a charity which is then sent to the functions.php. For now, I just want the functions.php to display the charity.
My code is as follows:

function add_charity_hidden_field() {
    echo '<input type="hidden" name="charity_data" id="charity_data" value="" />';
}
add_action('woocommerce_after_order_notes', 'add_charity_hidden_field');
add_action('woocommerce_before_add_to_cart_button', 'my_custom_checkout_field');

function my_custom_checkout_field() {
    echo '<div id="Charity"><h3>Charity</h3>';
    echo  '<div class="plg-search" data-partner-key="DATA_PARTNER_KEY">
</div><script>
document.addEventListener("DOMContentLoaded", function () {
    // Create a hidden input to store charity data
    const charityInput = document.createElement("input");
    charityInput.type = "hidden";
    charityInput.name = "charity_data";  // The name will be used to reference in PHP
    charityInput.id = "charity_data";    // Optional: Assign an ID to the input

    // Append the hidden input to the WooCommerce checkout form
    const checkoutForm = document.querySelector("form.checkout");
    if (checkoutForm) {
        checkoutForm.appendChild(charityInput);
    }

    // Function to handle charity data updates
    const updateEvent = data => {
        // Convert the charity data to a string and set it as the value of the hidden input
        charityInput.value = JSON.stringify(data);
        console.log("Charity data updated:", data);  // Debugging: Log the data for confirmation
    }

    // Function to handle the removal of charity data (if applicable)
    const removeEvent = () => {
        charityInput.value = "";  // Clear the hidden input if the event is removed
        console.log("Charity data removed");  // Debugging: Log the removal
    }

    // Function to handle the incoming message from the widget
    const handleMessage = e => {
        // Ensure the message is coming from the correct origin
        if (e.origin !== "https://www.pledge.to") return;

        // Parse the incoming message
        const message = JSON.parse(e.data);

        // Handle the actions based on the message type
        switch (message.action) {
            case "updateEvent":
                return updateEvent(message.data);
            case "removeEvent":
                return removeEvent();
        }
    }

    // Add the message event listener to listen for the charity widgets data
    addEventListener("message", handleMessage);
});
</script>
';
    echo '</div>';
}

// Store custom field
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
    
    if (isset($_POST['charity_data']) && !empty($_POST['charity_data'])) {
        // Sanitize the charity data
        $cart_item_data = sanitize_text_field($_POST['charity_data']);
        echo $cart_item_data;
    } else {
        echo "No charity";
    }
    return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );

It constantly displays “No Charity” even after I select a charity. I know that selecting a charity has worked because it displays the charity in the console.