Fill container with random width/height elements leaving least gaps [closed]

Objective is a fixed w/h div container, filled with elements of random width and height in a such way that they’ll leave the least visual gaps between them.

Sides and top/bottom don’t need to be even.

There are examples of “css masonry” but they mostly deal with fixed size columns and rows.
If it’s not best to use js, wasm i an option.

Any solutions for this?

How can I use a variable in the javascript ‘collection.style.width = “100%”‘ to replace the fixed value for width (here “100%”)

On a blog-type webpages (like on this page), photos are presented mainly in groups of two or four (in 1 or 2 lines of photos). Each photo container is centered and has a width calculated in such a way that portrait photos do not look bigger than landscape photos, with a last visual adjustment. To do that, I need to set the width of the photos container in accordance with the five classes “2 landscape photos”, “1 landscape and i portrait”, or “two portrait” plus the occasional “single landscape” and “single portrait”.

Five styles are used and I want to determine their respective “width” value with a javascript for the page. Depending on the final look of the webpage, the container width for two landscape photos could be set anywhere between 66% and 100% of the page width, and all others need to be adjusted in proportion.

Elaborating on a w3schools page, i have succeeded to set a fixed value to the width of each class value, which is a quite complex equivalent to simply setting the value for width in the style sheet. The problem is:
Whenever I try to replace, in the command ‘collection.style.width = “100%”‘, the fixed value “100%” by a variable, I fail.

What can i do to correct the script ?

Setting React state within handleSubmit callback using react-hook-form

I’m building some user inputs for a client-side application with react-hook-form.

Users should be able to update an input. Then onBlur, react-hook-form is to validate the input and update an react useState object. If validation fails, the external state is not updated.

The following code fails to keep the external state object up to date onBlur.

As the handleSubmit() function is async, i’m unable to set the state.

function App() {
  const [value, setValue] = useState({
    name: "",
  });

  const { register, handleSubmit } = useForm({ mode: "onBlur" });

  return (
    <>
      {errors?.name ? <p>{errors.name.message}</p> : null}
      <label htmlFor="name">Name</label>
      <input
        {...register("name", {
          onBlur: handleSubmit((data) => {
            setValue((prev) => ({ ...prev, name: data.name }));
          }),
          minLength: { value: 2, message: "Name is too short" },
          required: { value: true, message: "Name is required" },
        })}
        id="name"
        type="text"
      />
    </>
  );
}
  • I’ve tried wrapping handleSubmit in async / await – however this doesn’t yield anything as the handleSubmit method will only expose the result to the callback function.
  • useEffect on the react-hook-form watch() function; issue with this is you dont get the validation.
  • Creating my own synchronous methods to validate seem to defeat the purpose of using react-hook-form.

Code Signing using Electron Forge for Windows

I want to code sign my electron application using sectigo EV USB which is using electron forge to package the app and wix-msi maker.

After referring to wix-msi config options I was able to make use of signWithParams options to sign the created msi but since the packager itself is not signing the exe(s) & dll(s), the wix maker just makes those into a msi installer.

Post installation of the msi the app remains unsigned since forge is not signing the app, How can I solve this problem?

I have tried the following:

  • Using postpackage hook to sign, but it is not a reliable solution
    since i’ll have to mention paths for code signing, and regardless the electron-windows-sign did not work because i was not able to import it since it is ES Module and i need to require a module in my forge.config.js. I can’t use electron osx or notarize as it is for MacOS.
const sign = require('electron-windows-sign');

const appPath = 'sample/Path'; 
const certificateSubjectName = 'certificateSubjectName';

// Sign all .exe and .dll files in the packaged app
await sign({
  appPath,
  certificateSubjectName, /
});
  • Adding signing config to packagerConfig but i suppose it doesn’t have that option in forge config:
win: {
          // The subject name of the certificate
          certificateSubjectName: 'Name of certificate',
          signWithParams: '/v /td sha256 /fd sha256 /n "Name of certificate"',
        },

P.S. I do not wish to use electron-builder.

Security tags break event handling

    <!DOCTYPE html>
<html>
<head>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');

    body {
    background-color: #121212;
    color: #8bc34a;
    font-family: 'Press Start 2P', monospace;
    padding: 20px;
    line-height: 1.6;
    margin: 0;
    }

    .terminal {
    max-width: 800px;
    margin: 20px auto;
    background-color: #000;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
    cursor: text;
    }

    .terminal-header {
    background: linear-gradient(to right, #333, #111);
    padding: 10px;
    border-radius: 10px 10px 0 0;
    margin: -20px -20px 20px -20px;
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    }

    .prompt {
    color: #8bc34a;
    margin-bottom: 10px;
    }

    .user {
    color: #ffc107;
    }

    .hostname {
    color: #03a9f4;
    }

    .directory {
    color: #e91e63;
    }

    .command-input {
    background: transparent;
    border: none;
    color: #8bc34a;
    font-family: inherit;
    font-size: inherit;
    width: 80%;
    outline: none;
    margin-left: 5px;
    cursor: text;
    line-height: 1.6; /* Adjust line height to prevent overlap */
    padding: 2px;
    }

    .output {
    color: #8bc34a;
    margin-left: 10px;
    margin-bottom: 20px;
    white-space: pre-wrap;
    }

    .hidden {
    display: none;
    }

    .cursor {
    animation: blink 1s infinite;
    display: inline-block;
    width: 8px;
    height: 16px;
    background: #8bc34a;
    margin-left: 5px;
    vertical-align: middle;
    }

    @keyframes blink {
    0%, 100% { opacity: 1; }
    50% { opacity: 0; }
    }

    .help-text {
    color: #999;
    font-style: italic;
    }

    .error {
    color: #ff5555;
    }

    .success {
    color: #8bc34a;
    }

    .highlight {
    color: #ffc107;
    }
</style>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';">
</head>
<body>
<div class="terminal">
    <div class="terminal-header">Mohammad Abir Abbas - Retro CV</div>
    <div id="terminal-content">
    <div class="output">Welcome to my portfolio! I am eager to explore potential opportunities. Please type 'help' to see the available commands.</div>
    <div id="command-history"></div>
    <div class="prompt">
        <span class="user">abir</span>@<span class="hostname">portfolio</span>:<span class="directory">~</span>$ <input type="text" class="command-input" id="command-input" autofocus>
    </div>
    </div>
</div>

<script>
    const commandHistory = document.getElementById('command-history');
    const commandInput = document.getElementById('command-input');

    const data = {
    profile: `Full Name: Mohammad Abir Abbas
Location: Chattogram, Bangladesh
Contact:
- Phone: +8801841603542
- Email: [email protected]
- LinkedIn: www.linkedin.com/in/abir-abbas
- Portfolio: linktr.ee/uknowWhoAb1r

Top Skills:
- Start-up Leadership
- Start-up Ventures
- Rust Jobs

Languages:
- Bengali (Native or Bilingual)
- German (Goethe Zertifikat A2) (Elementary)
- English (IELTS 7.5) (Native or Bilingual)

Certifications:
- Docker Training Course for the Absolute Beginner
- Langchain x Autonomous GPT Agents Hackathon Certificate
- Jira Fundamentals Badge
- Master In-Demand Professional Soft Skills
- Leading with a Growth Mindset

Honors and Awards:
- Certificate of Proficiency in Digital Competence
- Goethe A2 Certification
- Wolfsburg Homie Certificate of Appreciation
- Certificate of Achievement
    `,

    experience: `Experience:
Deep Blue Digital (Co-Founder) - September 2024 to Present
- Explore our established digital goods marketplace
- Instant access to all purchases
- Seller-friendly environment with global visibility
- Secure transactions
- Wide range of digital products
Techstack: WordPress, CMS
Newest Addition: PC Web App

HNM IT Solutions (IT Support Technician) - October 2023 to January 2024
- Update router software to enhance security, improve functionality, and ensure compatibility
- Troubleshoot network issues using diagnostics and verifying configurations
- Systematically eliminate potential sources of network problems

MTC (AV Hannover Messe) - April 2023 to April 2023
- Spearheaded kitchen operations, crafting diverse dishes while prioritizing quality and safety
- Demonstrated teamwork & time management excellence in a fast-paced environment, boosting customer service & culinary standards

Fieldsports GmbH (Data Miner) - July 2020 to October 2020
- Mined 3,000 travel contacts & info using Python (Beautiful Soup & HTML), launching a travel website!`,

    education: `Education:
42 Wolfsburg (Computer Software Engineering, Peer Programming on C and C++) - April 2022 to July 2024
Chittagong University of Engineering & Technology (Bachelor's degree, Mechanical Engineering) - 2013 to 2017
Dhaka College (HSC) - 2010 to 2012
Chittagong Collegiate School (SSC) - 2005 to 2010
42 The Network - 2022 to 2024`
    };

    const commands = {
    help: 'Available commands:n' +
            'profile   - Display personal informationn' +
            'skills    - List technical and soft skillsn' +
            'exp       - Show work experiencen' +
            'certs     - View certificationsn' +
            'awards    - Show honors and awardsn' +
            'motto     - Display personal motton' +
            'edu       - Show educational backgroundn' +
            'clear     - Clear the terminaln' +
            'contact   - Show contact informationn' +
            'ls        - List all available commandsn' +
            'whoami    - Display current user info',
    
    ls: 'profile  skills  exp  certs  awards  motto  edu  contact',
    whoami: 'abir - AI Developer | Rust | Creator of Rusty',
    contact: `Contact Information:
    - Phone: <a href="tel:+8801841603542">+8801841603542</a>
    - Email: <a href="mailto:[email protected]">[email protected]</a>
    - LinkedIn: <a href="https://www.linkedin.com/in/abir-abbas" target="_blank">www.linkedin.com/in/abir-abbas</a>
    - Portfolio: <a href="https://linktr.ee/uknowWhoAb1r" target="_blank">linktr.ee/uknowWhoAb1r</a>`
    };

    // Function to sanitize output to prevent XSS
    function sanitizeHTML(str) {
    const div = document.createElement('div');
    div.innerText = str;
    return div.innerHTML;
    }

    function addToHistory(command, output, isError = false) {
    const promptHtml = `<div class="prompt"><span class="user">abir</span>@<span class="hostname">portfolio</span>:<span class="directory">~</span>$ ${sanitizeHTML(command)}</div>`;
    const outputHtml = `<div class="output ${isError ? 'error' : ''}">${sanitizeHTML(output)}</div>`;
    commandHistory.innerHTML += promptHtml + outputHtml;
    }

    function handleCommand(command) {
    const cmd = command.toLowerCase().trim();
    
    if (cmd === '') return;
    
    let output;
    switch(cmd) {
        case 'help':
        output = commands.help;
        break;
        case 'profile':
        output = data.profile;
        break;
        case 'skills':
        output = data.profile.split('nnTop Skills:')[1].trim();
        break;
        case 'exp':
        output = data.experience;
        break;
        case 'certs':
        output = data.profile.split('nnCertifications:')[1].trim();
        break;
        case 'awards':
        output = data.profile.split('nnHonors and Awards:')[1].trim();
        break;
        case 'motto':
        output = "Precision Engineering, Visionary Innovation - Ignite Your Tech Ascent";
        break;
        case 'edu':
        output = data.education;
        break;
        case 'clear':
        commandHistory.innerHTML = '';
        return;
        case 'ls':
        output = commands.ls;
        break;
        case 'whoami':
        output = commands.whoami;
        break;
        case 'contact':
        output = commands.contact;
        break;
        default:
        output = `Command not found: ${sanitizeHTML(cmd)}. Type 'help' for available commands.`;
        addToHistory(command, output, true);
        return;
    }
    
    addToHistory(command, output);
    }

    commandInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        const command = this.value;
        handleCommand(command);
        this.value = '';
        window.scrollTo(0, document.body.scrollHeight);
    }
    });

    // Auto-focus input when clicking anywhere in the terminal
    document.querySelector('.terminal').addEventListener('click', function() {
    commandInput.focus();
    });

    // Initial help message
    addToHistory('help', commands.help);
</script>
</body>
</html>

Output from above

“I implemented a Content Security Policy (CSP) to enhance security on my website, but it caused my website to break. Specifically, external fonts, inline scripts, and some commands are not functioning correctly. I’ve tried multiple ways to fix the handling logic, but nothing seems to work. Below, I’ll share the original output and the changes I made. Can someone help me resolve this issue?”

javascript express body has no contents

My problem is that req.body is returning ‘Object’. In the code below I get the TypeError message. The ‘req’ variable seems to contain nothing.

First, this is my curl testing command. I would like ‘here-again’ to show up in the file ‘/home/dave/test.txt’. I have tried putting ‘here-again’ in quotes.

curl -X PUT http://localhost:8008/config/ --data here-again

Below is my js code.

app.put('/config/',  function (req, res)  {
    const filename = '/home/dave/test.txt';
    const data = req.body;
    //res.send('body ' + data + ' ' + filename );
    console.log(data)
    fs.writeFile(filename, data, (err) => {
    if (err) {
        console.error(err);
        res.status(500).send('Error writing file');
    } else {
        res.send('Data saved successfully');
    }
  });
  // 
})

Below is my error message.

TypeError [ERR_INVALID_ARG_TYPE]: The “data” argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object

React js ‘beforeunload’ event does not work when closing tab or browser

In React.js when I close the form page either by selecting on nav menu(redirect using hyperlink) or back arrow or others, I need send a request to server that current login user is not working on this page
hence I use this code

window.addEventListener('beforeunload', async function (e) {
                //e.preventDefault();

                await fetch('/connetion',{
                    headers : { 
                      'Content-Type': 'application/json',         
                     }
                  }) 
                   .then(res => res.json())
                   .then((data) => {
                        console.log('You left this page');
                   })
                  
            }); 

/connection is one of the server function which shows(on console/Terminal) when the request received.
like below

Listening on port 3500
[ { message: 'database connected on08-12 07:20:47' } ]
[ { message: 'database connected on08-12 07:20:57' } ]
[ { message: 'database connected on08-12 07:20:57' } ]
[ { message: 'database connected on08-12 07:25:55' } ]
[ { message: 'database connected on08-12 07:26:56' } ]

this event sends request when we refresh or back arrow ‘previous URL’ or redirect using hyperlink except when the tab or browser is closed.

I tried ‘e.preventDefault();’ statement but it stopped sending request when we refresh or back arrow ‘previous URL’ on this page.
is there any solution?

How can this event send request while the tab or browser is closed?

checking for CSP and iframe embedding – Chrome Extension

I’m writing a very simple Chrome Extension that aims to check whether an endpoint could
be embedded as an Iframe
If it is – write “Success” in green in dev console, if not write it in red.

More context –
My goal is here to check whether an iframe could be embedded in my local extension without violating the CSP.

So once the user click on “Check Endpoint” the checking process will go in the background.

Currently i’m using ChatGPT, and my code did append a new iframe with the designated endpoint to the page, but than either it –
Blocked by inline script policy or providing False Positive whether it got embedded or not.

This is the current code the ChatGPT provide me with –

function checkEndpointCommunication(endpoint, button) {
    console.log(`Checking communication for endpoint: ${endpoint}`);

    let communicationEstablished = false;

    // Create an iframe and embed it
    const iframe = document.createElement("iframe");
    iframe.src = endpoint;
    iframe.style.display = "none"; // Hide the iframe from view
    document.body.appendChild(iframe);

    // Timeout to handle embedding failures
    const timeout = setTimeout(() => {
        if (!communicationEstablished) {
            console.warn(`[TIMEOUT] Iframe communication timeout for: ${endpoint}`);
            button.classList.remove("default", "green");
            button.classList.add("red"); // Mark as failure
            cleanup();
        }
    }, 5000); // 5-second timeout

    // Cleanup function
    const cleanup = () => {
        if (iframe.parentNode) iframe.remove();
        clearTimeout(timeout);
    };

    // Iframe onload handler
    iframe.onload = () => {
        clearTimeout(timeout); // Cancel timeout if iframe loads
        try {
            // Try to access the iframe content
            const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
            const iframeBody = iframeDocument.body;

            if (iframeBody) {
                console.log(`[INFO] Iframe content loaded successfully for: ${endpoint}`);
                communicationEstablished = true;
                button.classList.remove("default", "red");
                button.classList.add("green"); // Mark as success
            } else {
                console.warn(`[FAILURE] Iframe content is inaccessible for: ${endpoint}`);
                button.classList.remove("default", "green");
                button.classList.add("red"); // Mark as failure
            }
        } catch (err) {
            console.warn(`[ERROR] Iframe access failed for: ${endpoint}, Error: ${err.message}`);
            button.classList.remove("default", "green");
            button.classList.add("red"); // Mark as failure
        } finally {
            cleanup();
        }
    };

    // Iframe onerror handler
    iframe.onerror = () => {
        console.warn(`[FAILURE] Iframe failed to load for: ${endpoint}`);
        button.classList.remove("default", "green");
        button.classList.add("red"); // Mark as failure
        cleanup();
    };
}

Incorrect format problem when converting a BMP image file from Base-64 to binary

I am trying to convert the Base-64 data contained in the “data” returned by toDataURL of a fabric.Canvas into a file with its corresponding extension (BMP). The result is a “The file is not in the correct format” error.

The steps I follow are the following.

  1. I get the dataURL variable from the fabric.Canvas with the toDataURL method.

    dataURL = canvas.toDataURL({
    format: ‘bmp’,
    quality: 1.0

});

  1. I extract only the string that contains the “data”.

    dataURLto64 = dataURL.substr(dataURL.lastIndexOf(‘,’) + 1, dataURL.length –
    dataURL.lastIndexOf(‘,’) – 1);

  2. The above is done on the client. On the server I needed to save the string in segments in a TXT text file. I have verified that the final content of the text file is identical to the original dataURLto64 (in Base-64).

  3. I extract the content of the text file.

string strtextfile64 = File.ReadAllText([path]);

  1. I convert that string into a byte array with the method

    byte[] fileBinary = null;

    fileBinary = Convert.FromBase64String(strtextfile64);

    File.WriteAllBytes([path], fileBinary);

I have verified that both, dataURLto64 and strtextfile64 have the same characters and the same number.
To verify that the Base-64 string is correct, I have included the following verification on the server.

 int mod4 = strtextfile64.Length % 4;   

 if (mod4 > 0) {
    strtextfile64 += new string('=', 4 - mod4);
 }

It was not necessary to modify strtextfile64 because mod4 = 0.

I am attaching two text files in which the initial (client) and final (server) Base-64 strings are contained.

Inicial cliente
Final servidor

Could someone tell me the reason why that Base-64 data converted to binary data does not comply with the original BMP format from the original BMP file created from the fabric.Canvas?

How to add user’s sprite sheet with phaser framework when he logs in to the websocket connection?

I created a logic to add new users’ sprite sheet and than remove them if they logged out from the page. It works like I want, problem is when they logged in back, their sprite sheet is not appears in the page. How can I make their sprite sheet appear when they logged in back?

I tried to remove their record from the slicer so inactiveUsers array would cleaned after deletion of sprite sheets. I thought that would cause sprite sheet to added if user comes back but it didn’t worked.

Update method where I created this logic,

update(time, delta) {
        const state = store.getState();
        const avatar = state.communities.avatar;
        const inactiveUsers = state.websocket.inactiveUsers;
        this.activeUsers = state.communities.activeUsers;
        
        const currentUser = this.activeUsers.find((user) => user.id === this.userid);
    
        // Ensure we only act on the current user's character
        if(!currentUser) return;
    
        const distance = Phaser.Math.Distance.Between(
            this.character?.x,
            this.character?.y,
            this.targetX,
            this.targetY
        );
    
        if(distance > 5) {
            // Move the character smoothly towards the target
            const angle = Phaser.Math.Angle.Between(
                this.character.x,
                this.character.y,
                this.targetX,
                this.targetY
            );
            this.character.x += Math.cos(angle) * this.speed * (delta / 1000);
            this.character.y += Math.sin(angle) * this.speed * (delta / 1000);
    
            // Adjust character orientation based on movement direction
            if(this.targetX < this.character.x) {
                this.character.setScale(avatar === 'defaultgirl' ? -1.2 : -1.2, 1.2);
            }
            else {
                this.character.setScale(avatar === 'defaultgirl' ? 1.2 : 1.2, 1.2);
            }
        }
        else {
            // Stop movement animation when the character reaches the target
            if(this.character?.anims?.isPlaying) {
                this.character.stop(`walk_${avatar}`);
                this.character.setTexture(`${avatar}idle`, 0);
            }
        }

        // Sync other users' positions from activeUsers
        this.activeUsers.forEach((user) => {
            if(user.id !== this.userid) {
                const { avatar: otherAvatar, character_position_x, character_position_y } = user;

                // Use spriteMap to track the sprite for each user
                let otherCharacters = this.spriteMap[user.id];
                if(!otherCharacters) {
                    otherCharacters = this.add.sprite(this.cameras.main.width / 2, this.cameras.main.height / 2, `${otherAvatar}idle`);
                    this.spriteMap[user.id] = otherCharacters; // Save the reference
                    otherCharacters.setDepth(1);
                    otherCharacters.setScale(1.2);
                    otherCharacters.setOrigin(0.5, 0.9);
                    otherCharacters.play(`walk_${otherAvatar}`);
                }
    
                // Update position if valid
                if(character_position_x && character_position_y) {
                    const distanceToTarget = Phaser.Math.Distance.Between(
                        otherCharacters.x,
                        otherCharacters.y,
                        character_position_x,
                        character_position_y
                    );
    
                    if(distanceToTarget > 5) {
                        const angleToTarget = Phaser.Math.Angle.Between(
                            otherCharacters.x,
                            otherCharacters.y,
                            character_position_x,
                            character_position_y
                        );
                        otherCharacters.x += Math.cos(angleToTarget) * this.speed * (delta / 1000);
                        otherCharacters.y += Math.sin(angleToTarget) * this.speed * (delta / 1000);
                    }
                    else {
                        otherCharacters.setTexture(`${otherAvatar}idle`, 0);
                    }
                }

                if(inactiveUsers.includes(user.id)) {
                    otherCharacters.destroy();
                    delete this.spriteMap[user.id];
                }

                //this.dispatch(removeFromInactiveUsersArray(user.id));
            }
        });
    
        // Update the position of the speech bubble
        if (this.targetX) {
            const bubbleX = this.character?.x - 0; // Adjust for center alignment
            const bubbleY = this.character?.y - 80; // Position above the character
            this.speechBubbleElement.setPosition(bubbleX, bubbleY);
        }
    }

Google apps script to limit access on edit so that only the owner and the one who edited the cell have access

Hello I am looking for a specific functionality in google sheets. I tried to make a script that on every edit, if the cell is empty everyone has access to edit it. If someone edits it, only that person and the owner can edit it. I have to mention that every user is anonymous, and I can’t get the emails. This script’s scope is to limit the access of an edited cell so that users can’t modify each other’s cells, the first who types in that cells has control over it.

I tried to use a workaround with the protections, but that worked partially, nobody could edit the owner’s cells but everyone could write on top of each other’s cells. Got errors on the trigger for every person except the owner: you can’t remove yourself as an editor and Cannot read properties of undefined (reading ‘columnStart’) and the parameters (String,number) doesn’t correspond with the signature of the method SpreadsheetApp.Spreadsheet.getRange. at onEdit

This is the code I tried to edit it to make it work. The code was taken from this stackoverflow post and was written by Wim den Herder: Get the user that changed specific cell

// Test it with colors
// var edittedBackgroundColor = "RED"; // makes the change visible, for test purposes
// var availableBackgroundColor = "LIGHTGREEN"; //  makes the change visible, for test purposes

function onEdit(e) {
  Logger.log(JSON.stringify(e));
  var alphabet = "abcdefghijklmnopqrstuvwxyz".toUpperCase().split("");
  var columnStart = e.range.columnStart;
  var rowStart = e.range.rowStart;
  var columnEnd = e.range.columnEnd;
  var rowEnd = e.range.rowEnd;
  var startA1Notation = alphabet[columnStart-1] + rowStart;
  var endA1Notation = alphabet[columnEnd-1] + rowEnd;
  var range = SpreadsheetApp.getActive().getRange(startA1Notation + ":" + endA1Notation);

  if(range.getValue() === "") {
    Logger.log("Cases in which the entry is empty.");
    if(typeof availableBackgroundColor !== 'undefined' && availableBackgroundColor) 
      range.setBackground(availableBackgroundColor)
    removeEmptyProtections();
    return;
  }

  // Session.getActiveUser() is not accesible in the onEdit trigger
  // The user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger
  // Source: https://developers.google.com/apps-script/reference/base/session#getActiveUser()

  var protection = range.protect().setDescription('Cell ' + startA1Notation + ' is protected');
  if(typeof edittedBackgroundColor !== 'undefined' && edittedBackgroundColor)
    range.setBackground(edittedBackgroundColor);

  // Though neither the owner of the spreadsheet nor the current user can be removed
  // The next line results in only the owner and current user being able to edit

  protection.removeEditors(protection.getEditors());
  Logger.log("These people can edit now: " + protection.getEditors());

  // Doublecheck for empty protections (if for any reason this was missed before)

  removeEmptyProtections();
}

function removeEmptyProtections() {
  var ss = SpreadsheetApp.getActive();
  var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  for (var i = 0; i < protections.length; i++) {
    var protection = protections[i];
    if(! protection.getRange().getValue()) {
      Logger.log("Removes protection from empty field " + protection.getRange().getA1Notation());
      protection.remove();
    }
  }
  return;
}

function isEmptyObject(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return JSON.stringify(obj) === JSON.stringify({});
}

Why am I not receiving transcription results from Google Speech API in my React Native app?

I am building a React Native app that records audio on an Android device, streams it to my native module, and then sends the recorded audio to the Google Speech API for transcription. However, despite getting a response from the Google Speech API, I am not able to retrieve any transcription text. The API response includes a status: 429, but no transcription data is returned.

Here’s the code I’m using in my React Native app:
React Native Component (SpeechMode.js):

import React, { useEffect, useState } from 'react';
import { NativeEventEmitter, NativeModules, View, Text, StyleSheet, Button } from 'react-native';
import axios from 'axios';

const { AudioInputModule } = NativeModules;
const audioEventEmitter = new NativeEventEmitter(AudioInputModule);

const SpeechMode = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [transcription, setTranscription] = useState('');

  useEffect(() => {
    const subscription = audioEventEmitter.addListener('AudioData', (data) => {
      processAudioChunk(data);
    });

    return () => {
      AudioInputModule.stopAudioStream();
      subscription.remove();
    };
  }, []);

  const startRecording = () => {
    setIsRecording(true);
    setTranscription(''); // Clear previous transcription
    AudioInputModule.startAudioStream();
  };

  const stopRecording = () => {
    setIsRecording(false);
    AudioInputModule.stopAudioStream();
  };

  const processAudioChunk = async (base64Data) => {
    try {
      const transcriptionResult = await transcribeAudio(base64Data);
      if (transcriptionResult) {
        setTranscription((prev) => prev + ' ' + transcriptionResult);
      }
    } catch (error) {
      console.error('Error in transcription:', error);
    }
  };

  const transcribeAudio = async (base64Data) => {
    const GOOGLE_API_KEY = 'api key';
    const url = `https://speech.googleapis.com/v1/speech:recognize?key=${GOOGLE_API_KEY}`;

    const requestBody = {
      config: {
        encoding: 'LINEAR16',
        sampleRateHertz: 16000,
        languageCode: 'en-US',
      },
      audio: {
        content: base64Data,
      },
    };

    try {
      const response = await axios.post(url, requestBody);
      if (response.data && response.data.results) {
        return response.data.results
          .map((result) => result.alternatives[0].transcript)
          .join(' ');
      }
    } catch (error) {
      console.error('Google API Error:', error.response || error.message);
    }
    return '';
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Real-Time Speech-to-Text</Text>
      <Button
        title={isRecording ? 'Stop Recording' : 'Start Recording'}
        onPress={isRecording ? stopRecording : startRecording}
      />
      <Text style={styles.subtitle}>
        {isRecording ? 'Listening...' : 'Ready to Record'}
      </Text>
      <View style={styles.outputContainer}>
        <Text style={styles.outputLabel}>Transcription:</Text>
        <Text style={styles.output}>{transcription}</Text>
      </View>
    </View>
  );
};

export default SpeechMode;

Native Module Code:
AudioInputModule.java (Java Code):

package com.webrtcexample;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Base64;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;

public class AudioInputModule extends ReactContextBaseJavaModule {
    private static final int SAMPLE_RATE = 16000;
    private boolean isRecording = false;
    private Thread recordingThread;

    public AudioInputModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "AudioInputModule";
    }

    @ReactMethod
    public void startAudioStream() {
        if (isRecording) return;

        isRecording = true;
        recordingThread = new Thread(() -> {
            AudioRecord audioRecord = new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                AudioRecord.getMinBufferSize(
                    SAMPLE_RATE,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT
                )
            );

            if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                sendEvent("onError", "AudioRecord initialization failed");
                return;
            }

            audioRecord.startRecording();
            byte[] buffer = new byte[2048];
            while (isRecording) {
                int read = audioRecord.read(buffer, 0, buffer.length);
                if (read > 0) {
                    // Convert PCM data to Base64 and send to React Native
                    String base64Audio = Base64.encodeToString(buffer, 0, read, Base64.NO_WRAP);
                    sendEvent("AudioData", base64Audio);
                }
            }

            audioRecord.stop();
            audioRecord.release();
        });
        recordingThread.start();
    }

    @ReactMethod
    public void stopAudioStream() {
        isRecording = false;
        if (recordingThread != null) {
            try {
                recordingThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            recordingThread = null;
        }
    }

    private void sendEvent(String eventName, Object data) {
        getReactApplicationContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, data);
    }
}

I guess the problem is with the audio input I am taking what should , and I know of limit but ever before the limit it was not giving the text

Draggable window lagging on movement

So I’m trying to create draggable-resizable iframe which will work on any site.
I created one. On some websites works perfectly, but on others – very laggy. When i move this window around, it just very slow and not following mouse speed.

I don’t know why this happens… What should i do?

My code (which could be completely wrong):

import React, { useState, useEffect } from 'react';
import { Rnd } from 'react-rnd';

const style = {
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  justifyContent: "center",
  border: "solid 1px #402791",
  background: "#000000bf",
  zIndex: 9999998,
  overflow: "hidden",
  pointerEvents: "auto",
  position: "absolute",
} as const;

const dragHandleStyle = {
  width: "100%",
  height: "30px",
  background: "#402791",
  cursor: "move",
  zIndex: 9999999,
};

const DraggableResizableWindow = () => {
  const [dragging, setDragging] = useState(false);

  useEffect(() => {
    if (dragging) {
      const overlay = document.createElement('div');
      overlay.id = 'drag-overlay';
      overlay.style.position = 'fixed';
      overlay.style.top = '0';
      overlay.style.left = '0';
      overlay.style.width = '100%';
      overlay.style.height = '100%';
      overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
      overlay.style.zIndex = '9999997';
      overlay.style.pointerEvents = 'none';
      document.body.appendChild(overlay);

      document.body.style.pointerEvents = 'none';
    } else {
      const overlay = document.getElementById('drag-overlay');
      if (overlay) {
        document.body.removeChild(overlay);
      }

      document.body.style.pointerEvents = 'auto';
    }

    return () => {
      const overlay = document.getElementById('drag-overlay');
      if (overlay) {
        document.body.removeChild(overlay);
      }
    };
  }, [dragging]);

  const handleDragStart = () => {
    setDragging(true);
  };

  const handleDragStop = () => {
    setDragging(false);
  };

  return (
    <Rnd
      style={style}
      default={{
        x: 400,
        y: 400,
        width: 400,
        height: 300,
      }}
      dragHandleClassName="drag-handle"
      bounds="window"
      onDragStart={handleDragStart}
      onDragStop={handleDragStop}
    >
      <div className="drag-handle" style={dragHandleStyle}></div>
      <iframe
        src="https://example.com/"
        width="100%"
        height="100%"
        style={{ border: "none" }}
        title="Example iframe"
      />
    </Rnd>
  );
};

export default DraggableResizableWindow;

React To do app not updating after delete [duplicate]

Thanks for the help in advance. I have a to-do app the items get deleted on clicking the delete. But on submitting the new item along with the new item the deleted item is also listed. Provided the code with this. Please help to sort this issue. On the console, the data is listed correctly but not updating the state

App.js

import { useState } from "react";
import Input from "./Inputs/Input";
import Items from "./Items/Items";

import "./styles/App.scss";

export default function App() {
  const [formData, setInitFormData] = useState([]);
  const inputHandler = (data) => {
    setInitFormData(data);
  };
  const dataAftrDelInPar = (delData) => {
    console.log("After Deleted:", delData);
    setInitFormData(delData);
    console.log("Form Data:", formData);
  };

  return (
    <div className="container w-[70%] mt-5">
      <h1>To Do App</h1>
      <Input FrmData={inputHandler} />
      <Items listData={formData} deletedDataToPr={dataAftrDelInPar} />
    </div>
  );
}

Item.js

import { useState, useEffect, useRef } from "react";
import { CheckIcon, PencilIcon } from '@heroicons/react/24/solid';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrashAlt  } from '@fortawesome/free-solid-svg-icons';

export default function Items({ listData,deletedDataToPr }) {
  const [frmValue, setFrmVal] = useState(listData);
  const [selected, setSelected] = useState(null);
  const [updateInp, setUpdateInp] = useState(null);
  const [editVal, setEditVal] = useState(null);
  const updatedFrmRef = useRef(null);

  useEffect(() => {
    setFrmVal(listData);
  }, [listData]);

  const deleteHandler = (val) => {
    const BefrdeleteData = [...frmValue];
    const AftrdeleteData = BefrdeleteData.filter((currFl, ind) => ind !== val);
    setFrmVal(AftrdeleteData);
    deletedDataToPr(AftrdeleteData)
    setSelected(null);
  }

  const doneHandler = (doneVal) => {
    setSelected(doneVal);
  }

  const updateHandler = (updateVal) => {
    console.log(`currently clicked is ${updateVal}`);
    setUpdateInp(updateVal);
    setEditVal(frmValue[updateVal]);
  }

  const editFrmSave = (saveFrmVal) => {
    const updatedData = [...frmValue];
    updatedData[saveFrmVal] = updatedFrmRef.current.value;
    setFrmVal(updatedData);
    setUpdateInp(null);
  }

  return (
    <>
      {frmValue.map((currEl, index) => (
        <div className="justify-between flex items-center rounded-md bg-blue-50 my-3 px-2 py-2 ring-1 ring-inset ring-blue-700/10" key={index}>
          {updateInp === index ?
            (
              <div className="grid grid-cols-12 gap-4 items-center">
                <div className="col-span-9">
                  <input type="text" className="border border-gray-300 p-1" defaultValue={editVal} ref={updatedFrmRef} />
                </div>
                <div className="col-span-3 px-2">
                  <button type="submit" className="w-full px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600" onClick={() => { editFrmSave(index) }}>
                    Submit
                  </button>
                </div>
              </div>
            )
            :
            (<>
              <h2 className={`text-lg font-medium text-blue-700 ${selected === index ? 'line-through text-red-500' : ''}`}>{currEl}</h2>
              <div className="justify-between flex items-center">
                <button className="p-1.5 flex items-center space-x-2 text-red-500 rounded" onClick={() => { deleteHandler(index) }}>
                  <FontAwesomeIcon icon={faTrashAlt} />
                </button>
                <button onClick={() => { doneHandler(index) }} className="p-1.5">
                  <CheckIcon className="w-6 h-6 text-green-500" />
                </button>
                <button onClick={() => { updateHandler(index) }} className="p-1.5">
                  <PencilIcon className="h-4 w-4 text-blue-500" />
                </button>
              </div>
            </>)
          }

        </div>
      ))}
    </>
  );
}

How to check if a cell contains an integer value in onlyoffice macros?

I’m trying to check if a cell in an only office spread sheet contains an integer in an only office macro.

I already checked the API-Documentation but couldn’t find anything. However since I keep finding seemingly undocumented functions in blog posts (and similar), I hope that someone knows the answer. Perhaps I’m also missing something basic regarding calculation functions in oo-macros. (I’m relatively new to js)

Alternatively I could implement this as a custom function, however I would find it strange, that I’d have to resort to this for a seemingly easy task. If this is required, how would I go about that?

(function()
{   
    var sheet = Api.GetActiveSheet();  // Get the active sheet
    var cellValue = sheet.GetRangeByNumber(row, 6).GetValue(); // get the value 
      
     if (MOD(cellValue) === 0) { //<-- WHAT needs to go here?
          alert("value is integer");
         }  
})();