Create circular text using fabric js React js

I am trying to make a circular text on fabric js. I just done it by using the path property and now I need to control the radius of the circle I didn’t get any Idea after searching on the internet, i s there any methods to control the circular text radius or create a new circular text, I am providing the code below

 useEffect(() => {
    // Update font family of active text object when font state changes

    if (activeText) {
      const getPath = (value: string)=> {
        const path = new fabric.Path(
          value, {
          fill: "transparent",
          hasControls: true
        });
        return path;
      };

      if (transformation === "circle") {
        activeText.set("path", getPath("M 25, 50 a 25,25 0 1,1 50,0 a 25,25 0 1,1 -50,0"));
      }
     
      activeText.set("fontFamily", font);
      activeText.set("fill", textColor);
      activeText.set("opacity", textOpacity);
      activeText.set("stroke", strokeColor);
      activeText.set("strokeWidth", strokeWidth);
      activeText.set("fontSize", fontSize);
      activeText.set("linethrough", line);
      activeText.set("charSpacing", textCharSpacing); //! char spacing is limited to 100
      activeText.set("lineHeight", textLineHeight);
      activeText.set("textAlign", textAlignment);
      activeText.set("underline", textUnderLine);
      activeText.set("fontWeight", textWeight);
      canvasRef.current?.renderAll();
    }
  }, [
    font,
    activeText,
    textColor,
    textLineHeight,
    textOpacity,
    line,
    strokeColor,
    strokeWidth,
    fontSize,
    shadowBlur,
    transformation,
    shadow,
    shadowColor,
    textAlignment,
    textCharSpacing,
    textUnderLine,
    textWeight,
  ]);

Running my script in ChromeDevTools getting Error code: SIGILL, how do I resolve it

I have a requirement to

  1. take a bunch of id’s from the user (100 or more)
  2. create a URL from those id’s
  3. open each URL as a separate tab and scrape info from it
  4. store all the scrapped info as a json obj
  5. write the json obj into a csv file

I am trying to achieve this by running a js script in my chromedevtools environment, however keep ending up with Error code: SIGILL
Error code: SIGILL after the script performs the above actions for 20-30 Id’s

how do I resolve this

My code is as follows:-

// Function to prompt user for input and convert it to an array of strings
function promptAndConvertToArray() {
    // Prompt the user for input
    const userInput = prompt('Enter a list of IDs separated by new lines:');

    // Check if user clicked cancel or entered nothing
    if (!userInput) {
        console.log('No input provided.');
        return [];
    }

    // Split the input string by new line characters to get an array
    const idArray = userInput.split('n').map(id => id.trim());

    return idArray;
}

    // Function to generate links
function generateLinks(ids) {
    const prefix = ''; // removing the prefixes as its proprietary info
    const suffix = ''; // removing the suffixes as its proprietary info

    return ids.map(id => prefix + id + suffix);
}

// Function to write output to a CSV file
function downloadCSV(data) {
    const csvHeaders = ['Link'];
    const csvRows = [];

    // Extract all possible keys from the inner objects
    const allKeys = Object.values(data).reduce((keys, innerData) => {
        return keys.concat(Object.keys(innerData.spans));
    }, []);

    // Remove duplicate keys and sort them
    const uniqueKeys = [...new Set(allKeys)].sort();

    // Add headers for each key in the CSV
    csvHeaders.push(...uniqueKeys);

    // Generate rows for each link
    for (const [link, innerData] of Object.entries(data)) {
        const row = [link];

        // Populate row with values for each key
        for (const key of uniqueKeys) {
            row.push(innerData.spans[key] || '');
            console.log(row)
        }

        csvRows.push(row.join(','));
    }

    // Combine headers and rows
    const csvContent = [csvHeaders.join(','), ...csvRows].join('n');

    // Create CSV file and download
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = url;
    link.download = 'data.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

// Function to scrape data from a single page
async function scrapeDataFromPage(link) {
    // Open a new window or tab for the link (you may need to adjust this depending     on your environment)
    const page = window.open(link);

    // Wait for the page to load (you might need to add more sophisticated waiting logic)
    await new Promise(resolve => setTimeout(resolve, 1800000)); // Adjust the delay as needed

    // Inject the scrapeData function into the opened window/tab
    await page.eval(`
        function scrapeData() {
            const spanElements = document.querySelectorAll('span.classname');

            const data = {
                spans: {}
            };

            // Scrape data from span elements and count unique elements
            spanElements.forEach(span => {
                const text = span.textContent.trim();
                data.spans[text] = (data.spans[text] || 0) + 1;
            });

            return data;
        }
`    );

    // Extract the scraped data using the injected function
    const scrapedData = await page.eval('scrapeData()');

    // Close the current page
    page.close();

    return scrapedData;
}

// Function to throttle requests
function throttle(delay) {
    let lastCall = 0;
    return function(fn) {
        const now = Date.now();
        if (now - lastCall < delay) {
            return new Promise(resolve => setTimeout(() => resolve(fn()), delay -   (now - lastCall)));
        }
        lastCall = now;
        return fn();
    };
}

 // Function to scrape data from multiple webpages in parallel
async function scrapeDataFromMultiplePages(links) {
    //const throttledScrape = throttle(10000); // Throttle to one request per second
    //const scrapePromises = links.map(link => throttledScrape(() => scrapeDataFromPage(link)));
    const scrapePromises = links.map(link => scrapeDataFromPage(link));

    // Wait for all scraping tasks to finish
    const scrapedDataArray = await Promise.all(scrapePromises);

    const resultObject = {};

    // Combine results from all scraping tasks into a single object
    links.forEach((link, index) => {
        resultObject[link.split('-')[1]] = scrapedDataArray[index];
        console.log(resultObject)
    });

    return resultObject;
}

// Example usage:
(async function() {
    sessionStorage.clear()
    const ids = promptAndConvertToArray();
    const links = generateLinks(ids);
    const batchSize = 9;

    // Initialize session storage
    sessionStorage.setItem('scrapedData', JSON.stringify({}));

    for (let i = 0; i < links.length; i += batchSize) {
        const batchLinks = links.slice(i, i + batchSize); // Get a batch of links

        try {
            // Scrape data for the current batch
            const result = await scrapeDataFromMultiplePages(batchLinks);

            // Merge the result into the session storage
            const storedData = JSON.parse(sessionStorage.getItem('scrapedData'));
            Object.assign(storedData, result);
            sessionStorage.setItem('scrapedData', JSON.stringify(storedData));
        } catch (error) {
            console.error('Error:', error);
        }
    }

    // Once all scraping is done, retrieve data from session storage and download CSV
    const scrapedData = JSON.parse(sessionStorage.getItem('scrapedData'));
    console.log(scrapedData);
    downloadCSV(scrapedData);
})();

Render block body until head script has finished running

Is there a way to prevent HTML body from rendering and executing scripts until a script loaded in the header has both loaded and executed. I know script tags can be render blocking while downloading, but I also want it to render block until finished execution.

E.g.

<html>
  <head>
    <!-- I have full control over what is in the head and this script -->
    <script type='text/javascript' src='some-script.js' />
  </head>
  <body>
    <!-- I have no control over what is in the body -->
    <script type='text/javascript' src='some-other-script.js' />
  </body>
</html>

some-script.js – will load and do some JS execution which will x amount of time. I want to prevent some-other-script.js from downloading until the first script is complete.

I am unable to render the updated task. Is it because I did not pass the updated task? Shouldn’t the DB update automatically?

I am unable to render the updated task. Is it because I did not pass the updated task? Shouldn’t the DB update automatically? I am able to redirect but the task is not updated.

 app.patch("/task/:id/edit", async (req, res) => {
    const { id } = req.params
    await Task.findByIdAndUpdate(id, req.body, { runValidators: true, new: true })

    res.redirect("/task")
})

I think the task should have been updated

Unable: Fetch zip file from server, convert to base64 and push to git

I am calling an API (“/path/file.zip”) in my SAP nodejs application which returns data as

var jobDetails = await cpi.send({ path: `/path/file.zip`, method: "GET" });

API response

I cannot use external libraries(axios, http etc.) to make this http request due to framework restrictions.
I can convert above response/data to base64 using below and push to git

let bufferObj = new Buffer.from(jobDetails,'utf8');
let encodeddata = jobDetails.toString("base64");

but when i download file from git it gives error that zip file is invalid:

I tired to perform above steps via postman but postman allows me download the zip file from (‘/path/file.zip’) and then used online base64 converter uploading this zip file. On uploading this base64 string to git it worked and downloaded zip file from git also opened

Fivem JS not updating UI

I’m having trouble getting my script to update the UI with Lua data. I’ve handled the JavaScript part to the best of my ability as I’m reacquainting myself with frontend development. My friend and I are collaborating on an RZ script—I’ve handled the frontend UI, and he’s tackled the Lua. We’re attempting to pass Lua data to the JavaScript for UI updates, but it seems like something’s faulty. So i was able to do everything but trying to handle the data for the top 4 players which is not updating i setup console logs and I’m still confused.
enter image description here enter image description here
I tried many ways but still not work this is my current js

 function clearText(ids) {
    ids.forEach(function(id) {
        $('#' + id).text('');
    });
}

window.addEventListener('message', function(event) {
    const type = event.data.type;
    const playerData = event.data.PlayerData;
    const zonedata = event.data.zonedata;
    

    updateUI(playerData, zonedata);
});

function updateUI(playerData, zonedata) {
    // Get UI elements
    const leaderElement = document.getElementById("leader");
    const leaderKillsElement = document.getElementById("leaderkills");
    const killStreakNameElement = document.getElementById("killstreakname");
    const killStreakNumberElement = document.getElementById("killstreaknumber");
    const rewardOnKillElement = document.getElementById("rewardonkill");
    const totalKillsElement = document.getElementById("totalkills");
    const killsElement = document.getElementById("kills");
    const deathsElement = document.getElementById("deaths");
    const top1NameElement = document.getElementById("top1name");
    const player1KillsElement = document.getElementById("player1kills"); 
    const top2NameElement = document.getElementById("top2name");
    const player2KillsElement = document.getElementById("player2kills"); 
    const top3NameElement = document.getElementById("top3name");
    const player3KillsElement = document.getElementById("player3kills");
    const top4NameElement = document.getElementById("top4name");
    const player4KillsElement = document.getElementById("player4kills");

    // Update UI elements based on received data


    if (zonedata) {
        
        leaderElement.textContent = zonedata && typeof zonedata.leader !== 'undefined' && zonedata.leader !== null ? zonedata.leader : '';
        leaderKillsElement.textContent = zonedata && typeof zonedata.leaderkills !== 'undefined' ? zonedata.leaderkills : '';
        killStreakNameElement.textContent = zonedata && typeof zonedata.killStreakName !== 'undefined' ? zonedata.killStreakName : '';
        killStreakNumberElement.textContent = zonedata && typeof zonedata.killStreakNumber !== 'undefined' ? zonedata.killStreakNumber : '';
        rewardOnKillElement.textContent = '$ ' + (zonedata && typeof zonedata.rewardOnKill !== 'undefined' ? zonedata.rewardOnKill : '');
        totalKillsElement.textContent = zonedata && typeof zonedata.totalKillsToWin !== 'undefined' ? zonedata.totalKillsToWin : '';
        
        // Update other UI elements from zonedata as needed
    }

    if (playerData) {
        killsElement.textContent = playerData && typeof playerData.kills !== 'undefined' ? playerData.kills : '';
        deathsElement.textContent = playerData && typeof playerData.deaths !== 'undefined' ? playerData.deaths : '';
        
        // Update other UI elements from playerData as needed
    }

    // Update top players if available
    console.log('Received top players:', zonedata?.topplayers);
    if (zonedata?.topplayers?.length >= 4) {
        for (let i = 0; i < 4; i++) {
            const nameElement = document.getElementById(`top${i}name`);
            const killsElement = document.getElementById(`player${i}kills`);
            if (zonedata.topplayers[i]) {
                nameElement.textContent = zonedata.topplayers[i].name || '';
                killsElement.textContent = zonedata.topplayers[i].kills || '';
            }
        }
    }
}

$(document).ready(function() {
    window.addEventListener('message', function(event) {
        console.log('Message received:', event.data); // Log the received message
        console.log('Message data:', JSON.stringify(event.data)); // Log the received data as JSON string

        if (typeof event.data.zonedata !== 'undefined') {
            console.log('Type of zonedata:', typeof event.data.zonedata); // Log the type of zonedata

            // Check if zonedata is a string and parse it
            if (typeof event.data.zonedata === 'string') {
                console.log('zonedata is a string, parsing...');
                try {
                    const zonedata = JSON.parse(event.data.zonedata);
                    // Now zonedata is an object, you can proceed to use it
                    updateUI(event.data.playerData, zonedata);
                } catch (error) {
                    console.error('Error parsing zonedata:', error);
                }
            } else {
                
                updateUI(event.data.playerData, event.data.zonedata);
            }
        }

        if (event.data.type === 'updateUI') {
            console.log('Updating UI with data:', event.data); // Log the received data

            updateUI(event.data.message);

        } else if (event.data.type === 'showUI') {
            console.log('Showing UI');
            $(".container").fadeIn('fast');
        } else if (event.data.type === 'hideUI') {
            console.log('Hiding UI');
            $(".container").fadeOut('fast');
        } else {
            console.log('Unknown message type:', event.data.type);
        }
    });

`

and here is my server.lua

function SetupZoneData()
    for k,v in pairs(Config.RedZones) do
        ZoneData[k] = {
            routingbucket = v.routingbucket, 
            totalKillsToWin = Config.DeafultKillsToWin,
            Players = {},
            leader = 'None',
            killStreakName = 'None',
            killStreakNumber = 0,
            rewardOnKill = Config.KillRewardMoney,
            topplayers = {}
        }
    end

    print(json.encode(ZoneData))
end
SetupZoneData()

Citizen.CreateThread(function()
    while true do
        -- Loop through each zone
        for zoneName, zoneData in pairs(ZoneData) do
            if ZoneData[zoneName].Players then
                -- Sort players by kills
                local sortedPlayers = {}
                for playerId, stats in pairs(ZoneData[zoneName].Players) do
                    table.insert(sortedPlayers, { playerId = stats.source, kills = stats.kills, deaths = stats.deaths, killstreak = stats.killstreak, zonename = stats.zonename })
                end
 
                table.sort(sortedPlayers, function(a, b)
                    return a.kills > b.kills
                end)

                -- Update top 4 players in topplayers field
                local topPlayers = {}
                for i = 1, 4 do
                    if sortedPlayers[i] then
                        local playerId = sortedPlayers[i].playerId
                        local playerName = GetPlayerName(playerId)
                        local playerKills = sortedPlayers[i].kills
                        table.insert(topPlayers, { name = playerName, kills = playerKills })
                    end
                end
                
        
                print('Top Players for Zone ' .. zoneName .. ': ' .. json.encode(topPlayers))
                
                -- Find player with the highest kill streak
                local highestKillStreak = 0
                local playerWithHighestStreak = nil
                
                for _, player in ipairs(PlayerData) do
                    if player.killstreak > highestKillStreak then
                        highestKillStreak = player.killstreak
                        playerWithHighestStreak = player.source
                    end
                end
                 -- Set ZoneData with highest kill streak player
                 if playerWithHighestStreak then
                     ZoneData[zoneName].killStreakName = GetPlayerName(playerWithHighestStreak)
                     ZoneData[zoneName].killStreakNumber = highestKillStreak
                 else
                     ZoneData[zoneName].killStreakName = 'None'
                     ZoneData[zoneName].killStreakNumber = 0
                 end

                -- Update ZoneData with top players
                ZoneData[zoneName].topplayers = topPlayers
                print(json.encode(topPlayers))

                  -- Update clients with the latest player and zone data
                  for _, data in pairs(PlayerData) do
                    TriggerClientEvent('mtf-redzone:Client:RequestZoneSync', data.source, json.encode(ZoneData[zonename].Players[data.source]), json.encode(ZoneData[zoneName]))
                end
            end
        end

        -- Sleep for a minute before updating again (adjust as needed)
        Citizen.Wait(1000)
    end
end)

and here is the client.lua


local ActiveZones = {}
local InActiveZone = false
local display = false

function SetDisplay(bool)
    display = bool

    if bool then
        SendNUIMessage({
            type = "showUI",
            -- PlayerData = PlayerData,
            -- zonedata = zonedata,
            status = bool,
        })
    else
        SendNUIMessage({
            type = "hideUI",
            status = bool,
        })
    end
end

function UpdateUIThread(zonedata, playerData)
    while InActiveZone do
        Wait(500)
        SendNUIMessage({
            type = "updateUI",
            PlayerData = playerData,
            zonedata = zonedata,
          })
    end
end



-- [ Zone / Blip Creation ] --

Citizen.CreateThread(function()
    for k,v in pairs(Config.RedZones) do
       ActiveZones[k] = lib.zones.sphere({
        coords = v.coords,
        radius = v.zonesize,
        debug = Config.Debug,
        onEnter = function(self)
            TriggerServerEvent('mtf-redzone:Server:EnterZone', v.routingbucket, k)
            InActiveZone = true
            if Config.DisableInventory then exports.ox_inventory:weaponWheel(true) end
            GiveWeaponToPed(PlayerPedId(), v.issueweapon, 99999, false, true)
            SetDisplay(true)
        end,

        onExit = function(self)
            TriggerServerEvent('mtf-redzone:Server:LeftZone', v.routingbucket, k)
            RemoveAllPedWeapons(PlayerPedId())
          --  RemoveWeaponFromPed(PlayerPedId(), v.issueweapon)
            InActiveZone = false
            if Config.DisableInventory then exports.ox_inventory:weaponWheel(false)  end
            SetDisplay(false)
        end,
       })

        if Config.ShowZoneRadius then
            local radius = AddBlipForRadius(v.coords, v.blipradius)

            SetBlipSprite(radius, 1)
            SetBlipColour(radius, 1)
            SetBlipAlpha(radius, 65)
         end
    end
end)

RegisterNetEvent('mtf-redzone:SetCurrentWeapon', function()
    SetCurrentPedWeapon(PlayerPedId(), GetHashKey('weapon_pistol'), true)
end)

RegisterNetEvent('mtf-redzone:Client:RequestZoneSync', function(playerData, zoneData)
    print('Received zone data:', json.encode(zoneData)) -- Check the received data
    print('Received player data:', json.encode(playerData)) -- Check the received data
    -- Further processing, if needed
    UpdateUIThread(zoneData, playerData) -- Pass the zone data to the UI update function
end)

RegisterNetEvent('mtf-redzone:client:DeathHandler', function(nearestPoint)
    local player = PlayerPedId()
    DoScreenFadeOut(1000)
    Wait(1000)

    SetEntityCoords(PlayerPedId(), nearestPoint.x, nearestPoint.y, nearestPoint.z)

    Wait(2500) -- Wait for the player to be teleported

    SetEntityMaxHealth(player, 200)
    SetEntityHealth(player, 200)
    ClearPedBloodDamage(player)
    SetPlayerSprint(PlayerId(), true)

    -- qb-ambulancejob specific events to revive player
    TriggerEvent('hospital:client:Revive')

    DoScreenFadeIn(1000)

end)

AddEventHandler('onResourceStop', function()
    -- for k,v in pairs(Config.RedZones) do
    --     RemoveBlip(k)
    --     lib.zones.remove(k)
    -- end

end)

and here is the html for the top 4 players that i waant updated with the lua data

    <h2>TOP 4</h2>
        </div>
        <div class="red-zone">
            <div class="red-card left-card">
                <span class="badge">1
                </span >
                <p id="top1name">Josh</p>
            </div>
            <div class="red-card right-card">
                <i class="icon skull-icon"></i>
                <span id="player1kills">30</span>
            </div>
        </div>
        <div class="red-zone">
            <div class="red-card left-card">
                <span class="badge">2
                </span>
                <p id="top2name">Vinny</p>
            </div>
            <div class="red-card right-card">
                <i class="icon skull-icon"></i>
                <span id="player2kills">10</span>
            </div>
        </div>
        <div class="red-zone">
            <div class="red-card left-card">
                <span class="badge">3
                </span>
                <p id="top3name">llyty</p>
            </div>
            <div class="red-card right-card">
                <i class="icon skull-icon"></i>
                <span id="player3kills">9</span>
            </div>
        </div>
        <div class="red-zone">
            <div class="red-card left-card">
                <span class="badge">4
                </span>
                <p id="top4name">Bob</p>
            </div>
            <div class="red-card right-card">
                <i class="icon skull-icon"></i>
                <span id="player4kills">5</span>
            </div>
        </div>
        <div>

Integrating OpenLayers in Yew with Rust: Module specifier error

I am quite new to Yew. I’ve found tutorials and documentation useful, but I encounter problems when I try to integrate OpenLayers into my application. Specifically, I am encountering a module specifier error when attempting to load a JavaScript file. Below is the relevant part of my Rust code where I use wasm_bindgen to interface with JavaScript.

map.rs

use wasm_bindgen::prelude::*;
use yew::prelude::*;

#[wasm_bindgen(module = "js/ol_setup.js")]
extern "C" {
    fn setupMap();
}

pub struct MapComponent;

impl Component for MapComponent {
    type Message = ();
    type Properties = ();

    fn create(_ctx: &Context<Self>) -> Self {
        Self
    }

    fn view(&self, _ctx: &Context<Self>) -> Html {
        html! {
            <div id="map" style="width: 100%; height: 400px;"></div>
        }
    }

    fn rendered(&mut self, _ctx: &Context<Self>, first_render: bool) {
        if first_render {
            setupMap();
        }
    }
}

When I run the application, the JavaScript console throws the following error:

Uncaught TypeError: Failed to resolve module specifier "js/ol_setup.js". Relative references must start with either "/", "./", or "../".

The file ol_setup.js is part of my project structure and is located under static/js. My index.html is set up as follows:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>App title</title>
    <link data-trunk rel="scss" href="static/css/main.scss"/>
    <link data-trunk rel="copy-dir" href="static/img"/>
    <link data-trunk rel="copy-dir" href="static/js"/>
</head>
<body>
</body>
</html>

I suspect the issue might be related to how the module path is resolved in the wasm_bindgen attribute. Somehow, it is not able to load it when it is moved to the folder dist. How should I correctly specify the path to ensure the JavaScript file is properly loaded? Also, is there a specific setup or configuration in Yew or Trunk that I might be missing to handle external JS files correctly?

I hope someone can provide a clue 🙂

FastAPI POST endpoint runs 4 times per single POST request

When running my FastAPI server, I have a POST endpoint that, for some reason, runs 4 times per POST request.

FastAPI backend code:

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
[...]
@app.post("/create_new_session")
async def create_session(session_id: str, user_id: int = -1):
    create_new_session(session_id, user_id)
    logger.info(
        "created new session", extra={"session_id": session_id, "user_id": user_id}
    )

React frontend code:

function APP():
  [...]
  useEffect(() => {
    const dontUseSessionIdCookie = process.env.REACT_APP_DONT_USE_USER_ID_COOKIE === "true";
    datadogLogs.logger.info(`using session_id cookie: ${!dontUseSessionIdCookie}`, {'session-id': sessionId})
    const foundSessionId = dontUseSessionIdCookie ? undefined : Cookies.get('session_id');
    if (foundSessionId) {
      setSessionId(foundSessionId);
    } else {
      const sessionId = uuidv4();
      datadogLogs.logger.info('New session started', {'session-id': sessionId});  // Logs a new UUID
      Cookies.set('session_id', sessionId, { expires: 7 });
      setSessionId(sessionId);
      fetch(`${api_server_url}/create_new_session?session_id=${sessionId}`, {
        method: 'POST',
        redirect: 'follow',
      })
        .then(response => response.json())
        .then(data => datadogLogs.logger.info('Created new session', { 'data': data, 'session-id': sessionId }))
        .catch((error) => {
          datadogLogs.logger.error('Error while creating a new session:', { 'error': error, 'session-id': sessionId });
        });
    }
  }, [])

To be sure there was only one post request I’ve captured all HTTP traffic in Wireshark, and indeed saw only one request.
When inserting a breakpoint at the BE entrypoint I see the same src port for the request, the same session-id, and differences of ~800ms between calls.
This happens both locally, and when we run in production (over Herkou).

Any ideas??
Thanks 😀

I’ve inspected both the frontend and backend logs and saw that there was indeed one log from the frontend and 4 logs from the backend. I used wireshark to make sure there wasnt some retry logic I wasnt aware of. I’ve inserted breakpoints in the entry point and manually inspected each ingress request to try and find clues.

Datatable big data around 40k takes too long to filter

I am currently using the latest version of jQuery DataTables.
I have multiple filters and a search bar.
However, when I use any of them, it takes about 30 seconds to display the results. According to Google’s performance check, the long task is within the DataTable script.
Sometimes it gets stuck while filtering rows, causing the browser to crash.
The Datatable function that takes too long is _fnFilter which runs couples of time with each filter.
I have tried everything but nothing seems to help.
This issue occurred on Google Chrome but not in Firefox.

How to open multiple links on a page at once in new tabs or window from chrome’s dev tool console?

Assume a website containing links:

<a href="https://www.google.com">google</a>
<a href="https://www.yahoo.com">yahoo</a>
<a href="https://www.bing.com">bing</a>

I want to open each one of them in a new tab from chrome’s dev tool console.

I though I could achieve this via running the following from the console:

const as = document.querySelectorAll('a');
as.forEach(a => a.setAttribute('target', '_blank'));
as.forEach(a => a.click())

Yet it only opens the first one, then stops.

I also tried window.open:

[...document.querySelectorAll('a')].map(a => a.href).forEach(window.open)

or

[...document.querySelectorAll('a')].map(a => a.href).forEach(href => window.open(href, '_blank'));

This too only opens the first link, not the others.

How do I open all links in a new tab or window from chrome’s dev console?

react native canvas scratch game not working nor showing

i am trying to create a small scratchable game in react native. but i dont know why it is not showing up and when i add canvasRef.current in the useeffect i get this error ReferenceError: Property ‘regeneratorRuntime’ doesn’t exist. can someone help out. i dont know where i should change. i’ve been doing the same way with normal react apps for web developments and till now not faced any problem. but when i wanted to start doing it on react native for mobile devices purposes it showed me this error.

i have attached the code in the snippet below.

import React, { useState, useRef, useEffect } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import Canvas from 'react-native-canvas';

const ScratchCard = () => {
const [isScratched, setIsScratched] = useState(false);
const canvasRef = useRef(null);

const handleCanvas = (canvas) => {
if (canvas) {
const ctx = canvas.getContext('2d');
// Set the size of the canvas
canvas.width = 300;
canvas.height = 200;

// Draw the scratchable area
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Draw the text beneath the scratchable area
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Scratch to reveal!', 50, canvas.height / 2);
}
};

useEffect(() => {
handleCanvas(canvasRef.current);
}, []);

const handleTouchMove = (event) => {
if (isScratched) return; // If already scratched, no need to continue

const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
const rect = event.target.getBoundingClientRect();
const touchX = event.nativeEvent.locationX - rect.left;
const touchY = event.nativeEvent.locationY - rect.top;

// Scratch off the area
ctx.globalCompositeOperation = 'destination-out';
ctx.arc(touchX, touchY, 10, 0, 2 * Math.PI);
ctx.fill();
};

const handleTouchEnd = () => {
setIsScratched(true);
};

return (
<View style={styles.container}>
<Canvas
ref={canvasRef}
style={styles.canvas}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
/>
{isScratched && <Text style={styles.message}>You've revealed the content!</Text>}
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
canvas: {
width: 300,
height: 200,
},
message: {
marginTop: 20,
fontSize: 18,
fontWeight: 'bold',
},
});

export default ScratchCard;

Issue with signing JSON web tokens

I am using node version v16.3.2, and trying to generate a bearer token using the jsonwebtoken library.

Here is my code:

require("dotenv").config();
const jwt = require("jsonwebtoken");

// this throws an error (secretOrPrivateKey must be an asymmetric key when using RS256)
const token = jwt.sign(
      { iss: process.env.ID, client_id: process.env.ID },
      process.env.TOKEN,
      { algorithm: "RS256" },
    );

// the second time around, this works fine!
const token2 = jwt.sign(
      { iss: process.env.ID, client_id: process.env.ID },
      process.env.TOKEN,
      { algorithm: "RS256" },
    );

I am not sure what could be happening. The first attempt to call jwt.sign fails, while the second succeeds in generating a valid token. I have verified that the process.env.ID and process.env.TOKEN variables are properly loaded after the require("dotenv") line.

Is it possible to convert a class with a constructor to functional component with same props defined?

I am newly started using matter-js and react-native-game-engine and trying to figure out why class definition is used. I observed such questions in stack but couldn’t find the exactly similar answer. I am confused to migrate this part especially: this.entities = this.setupWorld();. My whole class definition is as follows:

import Matter from "matter-js";
import { GameEngine } from "react-native-game-engine";

export default class GameApp extends Component {
    constructor(props){
        super(props);

        this.state = {
            running: true,
            score: 0,
        };

        this.gameEngine = null;

        this.entities = this.setupWorld();
    }

    setupWorld = () => {
        let engine = Matter.Engine.create({ enableSleeping: false });
        let world = engine.world;
        world.gravity.y = 0.0;

        let bird = Matter.Bodies.rectangle( Constants.MAX_WIDTH / 2, Constants.MAX_HEIGHT / 2, Constants.BIRD_WIDTH, Constants.BIRD_HEIGHT);

        let floor1 = Matter.Bodies.rectangle(
            Constants.MAX_WIDTH / 2,
            Constants.MAX_HEIGHT - 25,
            Constants.MAX_WIDTH + 4,
            50,
            { isStatic: true }
        );

        let floor2 = Matter.Bodies.rectangle(
            Constants.MAX_WIDTH + (Constants.MAX_WIDTH / 2),
            Constants.MAX_HEIGHT - 25,
            Constants.MAX_WIDTH + 4,
            50,
            { isStatic: true }
        );


        Matter.World.add(world, [bird, floor1, floor2]);
        Matter.Events.on(engine, 'collisionStart', (event) => {
            var pairs = event.pairs;

            this.gameEngine.dispatch({ type: "game-over"});

        });

        return {
            physics: { engine: engine, world: world },
            floor1: { body: floor1, renderer: Floor },
            floor2: { body: floor2, renderer: Floor },
            bird: { body: bird, pose: 1, renderer: Bird},
        }
    }

    onEvent = (e) => {
        if (e.type === "game-over"){
            //Alert.alert("Game Over");
            this.setState({
                running: false
            });
        } else if (e.type === "score") {
            this.setState({
                score: this.state.score + 1
            })
        }
    }

    reset = () => {
        resetPipes();
        this.gameEngine.swap(this.setupWorld());
        this.setState({
            running: true,
            score: 0
        });
    }

    render() {
        return (
            <View ...
         )
    }
}

My outcome is something like this but there is problem about passing props I think:

export default GameApp = () =>  {
    const [running, setRunning] = useState(true)
    const [score, setScore] = useState(0)
    let gameEngine = null
    let entities = null

    useEffect(()=>{
        entities = setupWorld()
    },[])

    const setupWorld = () => {
        let engine = Matter.Engine.create({ enableSleeping: false });
        let world = engine.world;
        world.gravity.y = 0.0;

        let bird = Matter.Bodies.rectangle( Constants.MAX_WIDTH / 2, Constants.MAX_HEIGHT / 2, Constants.BIRD_WIDTH, Constants.BIRD_HEIGHT);

        let floor1 = Matter.Bodies.rectangle(
            Constants.MAX_WIDTH / 2,
            Constants.MAX_HEIGHT - 25,
            Constants.MAX_WIDTH + 4,
            50,
            { isStatic: true }
        );

        let floor2 = Matter.Bodies.rectangle(
            Constants.MAX_WIDTH + (Constants.MAX_WIDTH / 2),
            Constants.MAX_HEIGHT - 25,
            Constants.MAX_WIDTH + 4,
            50,
            { isStatic: true }
        );


        Matter.World.add(world, [bird, floor1, floor2]);
        Matter.Events.on(engine, 'collisionStart', (event) => {
            var pairs = event.pairs;

            gameEngine.dispatch({ type: "game-over"});

        });

        return {
            physics: { engine: engine, world: world },
            floor1: { body: floor1, renderer: Floor },
            floor2: { body: floor2, renderer: Floor },
            bird: { body: bird, pose: 1, renderer: Bird},
        }
    }

    const onEvent = (e) => {
        if (e.type === "game-over"){
            setRunning(false)
        } else if (e.type === "score") {
            setScore(score+1)
        }
    }

    const reset = () => {
        resetPipes();
        gameEngine.swap(setupWorld());
        setRunning(true)
        setScore(0)
    }

        return (
            <View style={style
    ...

    )
    }

Is there a way to access a Sharepoint file that requires credentials through a live server using Javascript?

Context: I have a web application (html/js/css) that uses Highcharts library to generate data visualisation. Currently the visualisation is built with data from a local JSON file.

Goal: I want to replace this local JSON file because I need to access a JSON file stored in a Sharepoint folder instead.

Issue / What I have done:: I launched a development local Server with live reload feature and I replaced the filepath of my local JSON file to the Sharepoint link.

However, I got the following error:

Access to XMLHttpRequest at sharepoint_link (redirected from 'second_link') from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Question: Is there a way for me to access the file from my application? If so, how can I do it?