Can I pre-scale and cache Images?

I have a game which is drawing 324 tiles to an HTML5 canvas at 60 frames per second.
It was working great when the tilesize was set to a fixed number of pixels and matched the pixels of the source image file.
I updated the game to resize to the user’s screen upon load. Everything still works fine, but the game has a bit of lag now. My assumption is that this is caused by the resizing of the images on every draw.
I am using the drawImage() method as follows:

ctx.drawImage(image, xCoord, yCoord, tileSize, tileSize);

I have tried modifying the width and height of each of the tile images after the new tileSize is obtained:

tiles.forEach((tile) => {
   tile.image.height = tileSize;
   tile.image.width = tileSize;
}

The values are retained in the object, but if I call drawObject without specifying width and height, they are drawn back at their naturalHeight and naturalWidth.

How can I resize the images and store the resized versions for use throughout the program?

Need help to refresh periodically a webcam snapshot in a webpage – not the whole webpage

I have searched intensive for a solution of my problem but found noting helpful in my case. What i try to archive is to refresh a screenshot from my webcam in a webpage continously. Not the whole page. This is my current code which only shows a screenshot without to refresh it. Any help is appreciated.

<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var myImageElement = document.getElementById('camshot');
myImageElement.src = 'api.jpg?rand=' + Math.random();

setInterval(function() {
    var myImageElement = document.getElementById('canshot');
    myImageElement.src = 'api.jpg?rand=' + Math.random();
}, 10000);
</script>

</body>
<img src="http://192.168.0.168/cgi-bin/api.cgi?cmd=Snap&channel=0&rs=wuuPhkmUCeI9WG7C" id="camshot" >
</html>

React portfolio copying images in ubuntu

I am getting a no file found error when trying to copy over images from my download folder to my project directory. I am running an ubuntu 22.04 LTE environment in windows.

I am using this command

cp helvetica-neu.ttf c/users/myname/portfolioapp/src/assets/images

achievements.filter is not a function error

Trying to filter and map a react state out but getting this error. Tried having a look online for soloutions but didnt seem to work. I have tried similar code in a different project it works fine. the only difference i see is in this code i have used props to passdown the state and in the other project it was initialised in the same file.

here is the code

import React, { useEffect } from "react";
import styled from "styled-components";
import { useLocation } from "react-router-dom";
import { motion } from "framer-motion";
import { pageAnimation } from "../animation";
import ScrollTop from "../components/ScrollTop";

const AchievementDetail = (
  currentAchievement,
  achievements,
  setAchievements,
  setCurrentAchievement
) => {
  const url = useLocation();

  useEffect(() => {
    const currentAchievement = achievements.filter(
      (stateAchievement) => stateAchievement.url === url.pathname
    );
    setAchievements(currentAchievement);
  }, [achievements, url]);
  return (
    <>
      {currentAchievement && (
        <Details
          exit="exit"
          variants={pageAnimation}
          initial="hidden"
          animate="show"
        >
          <ScrollTop />
          <HeadLine>
            <h2>{currentAchievement.title}</h2>
            <img src={currentAchievement.mainImg} alt="currentAchievement" />
          </HeadLine>
          <Awards>
            {currentAchievement.infos?.map((info) => (
              <Award
                title={info.title}
                description={info.description}
                key={info.title}
              />
            ))}
          </Awards>
        </Details>
      )}
    </>
  );
};


export default AchievementDetail;

the error

console log

iOS Safari Extension – Additional Permissions Requested banner

I’ve developed iOS Safari extension and a little confused how extension, like Honey shows top Additional Permissions Requested banner when user enables extensions and has to provide allow tracking web sites.

Manifest example

{
    "manifest_version": 3,
    "default_locale": "en",

    "name": "Extension_name",
    "description": "Extension_desc",
    "version": "1.0",

    "icons": {
        "48": "images/icon-48.png",
        "96": "images/icon-96.png",
        "128": "images/icon-128.png",
        "256": "images/icon-256.png",
        "512": "images/icon-512.png"
    },

    "background": {
        "scripts": [ "background.js" ],
        "persistent": false
    },

    "content_scripts": [
        {
            "run_at": "document_idle",
            "all_frames": true,
            "match_about_blank": true,
            "js": [ "***.js" ],
            "css": [ "***.css" ],
            "matches": [ "<all_urls>" ]
          },
        {
        "js": [ "content.js" ],
        "matches": [ "<all_urls>" ]
    }],

    "action": {
        "default_popup": "popup.html",
        "default_icon": {
            "16": "images/toolbar-icon-16.png",
            "19": "images/toolbar-icon-19.png",
            "32": "images/toolbar-icon-32.png",
            "38": "images/toolbar-icon-38.png",
            "48": "images/toolbar-icon-48.png",
            "72": "images/toolbar-icon-72.png"
        }
    },

    "permissions": [
        "activeTab",
        "nativeMessaging",
    ]
}

screenshot

Export OpenAPI to native/plain javascript

Friends convinced me to use OpenAPI to document the REST API for my embedded web server project.
Now I struck at the point to generate/export javascript code that I can integrate into my embedded server to deliver it to clients.
Until now I could not find a tool that can generate native javascript modules, that I can easily embed into my webserver.

I used the openapi-generator to generate javascript code. Unfortunately all generators that I found require node.js or other additional platforms: openapi generators.

With searching the internet I could not find suitable tools that can generate plain/native javascript. I started to read openapi-generator manual about creating custom extensions. But I recognized that my friend’s request to provide a well defined API specification gets more and more complex and I think about switching back to a non-specified API with custom/propriatory/handwritten javascript code.

Does anyone know if there are OpenAPI code generators that can generate native javascript (without any additional libraries)?

Thank you

Attempting to Bundle a Require Command For a Chrome Extension

I want to create a chrome extension that will print out accessibility errors to the console using the axe-core library. My plan was I originally thought I could do this with Browserify to bundle the axe-core library, but to simply add a content.js to the manifest, perform a require line in the contest.js, ‘Browserify’ content.js, and be ready to go. However, when I load up my extension and view the console, I see the Uncaught ReferenceError: require is not defined still in the console.

Here is content.js:

const axe = require('axe-core');
axe.run().then(results =>{console.log(results)});

Bundle.js is in place as one would expect. All the tutorials show browserify used to bundle node modules for scripts embedded in the html, can it not be used for content_scripts? What is an alternative method for achieving this?

Jest + JavaScript ES Modules

I’ve built a command-line tool in JavaScript. I want to write tests for it. I thought of Jest as the first option.

I’m getting the following error when running the tests:
SyntaxError: Cannot use import statement outside a module.

Here’s what I’ve tried:

  • I’ve installed Jest and its dependencies via npm install --save-dev jest @babel/core @babel/preset-env babel-jest
  • I created a babel.config.cjs file with the following content:
module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }]],
};

  • I’ve updated the following sections in my package.json:
  "type": "module",
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\.js$": "babel-jest"
    }
  },
  • My tests are inside of a __tests__ folder, and the test files have the following naming convention fileName.test.js

node-forge rsa encrypt not working after storage, get error “Encryption block is invalid”

When I encrypt and then decrypt, all works well. But when I encrypt then save as json then retrieve and decrypt I get error ” Encryption block is invalid”

this below works. Encrypt, encode to base64, decoode form base64, then decrypt.

const publicKey = process.env.PUBLIC_KEY;
const privateKey = process.env.PRIVATE_KEY;

// Convert the public key string to a Forge key object
const publicKeyObj = forge.pki.publicKeyFromPem(publicKey);
const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
//encrypt, encode64, decode64, decrypt
try {
  let encryptedData = publicKeyObj.encrypt("hello world");
  encryptedData = forge.util.encode64(encryptedData);
  console.log(encryptedData);
  encryptedData = forge.util.decode64(encryptedData);
  let d = {};
  d.data = encryptedData;
  let decryptedData = privateKeyObj.decrypt(d.data,);
  console.log(decryptedData);
} catch (e) {
  console.log("e: ", e);
}

but when I encode and decode seperately I get error “Encryption block is invalid”

encode no error

function encryptDoc(doc) {    
    const publicKey = process.env.PUBLIC_KEY;
    
      // Convert the public key string to a Forge key object
    const publicKeyObj = forge.pki.publicKeyFromPem(publicKey);
      // console.log(privateKeyObj);
    
    try {
      let encryptedData = publicKeyObj.encrypt(doc);
      console.log("encryptedData: ", encryptedData);
      // const base64EncryptedData = forge.util.encode64(encryptedData);
      const base64EncryptedData = encryptedData;
      console.log(base64EncryptedData);
      return base64EncryptedData;
    } catch (e) {
      console.log("e: ", e);
    }
}

After encode the data is saved as json in nosql DB.

on decode I get the error

async function decryptData(data) {
  console.log("data: ", data);
  const privateKey = process.env.PRIVATE_KEY;
  console.log("privateKey: ", privateKey);
  const privateKeyObj = forge.pki.privateKeyFromPem(privateKey);
  
  try {
    // Decode the base64 string to binary
    const encryptedData = forge.util.decode64(data);
    console.log("encryptedData: ", encryptedData);
    // Decrypt the data using the private key
    console.log("privateKeyObj: ", privateKeyObj);
    const decryptedData = privateKeyObj.decrypt(encryptedData);

    console.log("Decrypted data:", decryptedData);
    return decryptedData;
  } catch (e) {
    console.log("e: ", e);
    alert(e);
  }
}

Performance difference between two JavaScript code snippets for comparing arrays of strings

I’m working on a JavaScript function that compares two arrays of strings to see if their concatenated contents are equal. I’ve written two versions of the function, one using explicit variables and another more concise version. Surprisingly, I noticed a slight performance difference between the two implementations.

Here are the two versions of the function:

version 1

var arrayStringsAreEqual = function(word1, word2) {
    let a = word1.join('');
    let b = word2.join('');
    if (a == b) {
        return true;
    } else {
        return false;
    }
};

version 2

var arrayStringsAreEqual = function(word1, word2) {
    return word1.join('') == word2.join('');
};

Could someone explain why there might be a performance difference between these two versions, even though they’re functionally equivalent? Is it related to how JavaScript engines optimize code, or are there other factors at play?

While both versions achieve the same result, I found that version 1 (with explicit variables) is marginally faster in some cases. I’m curious why this might be the case.

Have a script work multiple times with the same class

I am working on an element which fades in & out. Plus, its display goes to ‘none’. Preventing it can still be clicked, when it doesn’t show.

The idea is that, when the element is faded in, a seperate, second button, allows it to fade out.

I am working wit the following code:

const chat = document.getElementById('chatclouds'),
      
    btn = document.querySelector('.fadechat');

btn.addEventListener('click', function () {
  ////----
  
  if (chat.classList.contains('hidden')) {
    chat.classList.remove('hidden');
    setTimeout(function () {
      chat.classList.remove('visuallyhidden');
    }, 20);
  } else {
    chat.classList.add('visuallyhidden');    
    chat.addEventListener('transitionend', function(e) {
      chat.classList.add('hidden');
    }, {
      capture: false,
      once: true,
      passive: false
    });
  }
  
}, false);

Why is it that the this code will only work on one object using the class; .fadechat?
The second button, using the same class, doesn’t trigger the code.

How to configure items spacing in gridstack.js?

I’m using gridstack and I’m trying to set a gap spacing between items. I tried using margin: 10px, but its not working.

My code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Advanced grid demo</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="demo.css" />

  <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule="" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>

  <!-- support for IE -->
  <script src="../dist/es5/gridstack-poly.js"></script>
  <script src="../dist/es5/gridstack-all.js"></script>

  <style type="text/css">
    .grid-stack-item-removing {
      opacity: 0.8;
      filter: blur(5px);
    }
    #trash {
      background: rgba(255, 0, 0, 0.4);
    }
  </style>
</head>

<body>
  <h1>Advanced Demo</h1>
  <div class="row">
    <div class="col-md-2 d-none d-md-block">
      <div id="trash" style="padding: 5px; margin-bottom: 15px;" class="text-center">
        <div>
          <ion-icon name="trash" style="font-size: 300%"></ion-icon>
        </div>
        <div>
          <span>Drop here to remove!</span>
        </div>
      </div>
      <div class="newWidget grid-stack-item">
        <div class="grid-stack-item-content" style="padding: 5px;">
          <div>
            <ion-icon name="add-circle" style="font-size: 300%"></ion-icon>
          </div>
          <div>
            <span>Drag me in the dashboard!</span>
          </div>
        </div>
      </div>
    </div>
    <div class="col-sm-12 col-md-10">
      <div class="grid-stack"></div>
    </div>
  </div>

  <script type="text/javascript">

    let grid = GridStack.init({
      cellHeight: 70,
      acceptWidgets: true,
      removable: '#trash', // drag-out delete class
    });
    GridStack.setupDragIn('.newWidget', { appendTo: 'body', helper: 'clone' });

    let items = [
      {x: 0, y: 0, w: 4, h: 2, content: '1'},
      {x: 4, y: 0, w: 4, h: 4, noMove: true, noResize: true, locked: true, content: 'I can't be moved or dragged!<br><ion-icon name="ios-lock" style="font-size:300%"></ion-icon>'},
      {x: 8, y: 0, w: 2, h: 2, minW: 2, noResize: true, content: '<p class="card-text text-center" style="margin-bottom: 0">Drag me!<p class="card-text text-center"style="margin-bottom: 0"><ion-icon name="hand" style="font-size: 300%"></ion-icon><p class="card-text text-center" style="margin-bottom: 0">...but don't resize me!'},
      {x: 10, y: 0, w: 2, h: 2, content: '4'},
      {x: 0, y: 2, w: 2, h: 2, content: '5'},
      {x: 2, y: 2, w: 2, h: 4, content: '6'},
      {x: 8, y: 2, w: 4, h: 2, content: '7'},
      {x: 0, y: 4, w: 2, h: 2, content: '8'},
      {x: 4, y: 4, w: 4, h: 2, content: '9'},
      {x: 8, y: 4, w: 2, h: 2, content: '10'},
      {x: 10, y: 4, w: 2, h: 2, content: '11'},
    ];
    grid.load(items);
    
    grid.on('added removed change', function(e, items) {
      let str = '';
      items.forEach(function(item) { str += ' (x,y)=' + item.x + ',' + item.y; });
      console.log(e.type + ' ' + items.length + ' items:' + str );
    });
  </script>
</body>

</html>

How can I override navigator.userAgentData?

I’m doing web scraping but the website detects me. I changed the userAgent, platform, appName etc using Object.defineProperty(navigator, “example”). But the last thing is the navigator.userAgentData.platform and navigator.userAgentData.getHighEntropyValues.

Is there any way for the getHighEntropyValues to return the data that was defined after Object.defineProperty?

How the website detects inconsistencies

Using navigator.userAgentData.platform and navigator.userAgentData.getHighEntropyValues(["architecture", "platform"]) the website can compare with navigator.platform and navigator.userAgent etc.

Add newly added record to select2 element

I have an add form, which adds a record in a table and get back the newly createdId of that record.

On the same page, I have another form which has a select2 element and I would like to perform the search automatically using the new createdId without to ask from the user to search in the select2 element. The goal is, as soon as I add the new record, second script to search for the data of that record and to display it in the select2 element.

I have this JavaScript:

    var createdId;
    // Ajax call to add new foreas or contact
    $('#add_form').submit(function (event) {
        // Prevent default form submission
        event.preventDefault();

        // Serialize form data
        var formData = $(this).serialize();

        // AJAX call
        $.ajax({
            type: 'POST',
            url: "<?php echo site_url('my/addContact');?>",
            data: formData,
            dataType: 'json',
            success: function (response) {
                // Handle the response from the server
                if (response.success) {
                    // Data insertion successful
                    createdId = response.created_id;
                } else {
                    // Data insertion failed
                    console.error('Failed to insert data: ' + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred during AJAX request: ' + error);
            }
        });
    });

    console.log('Here, createdId is ' + createdId); // Id is printed in the console

    // Retrieve records from contacts
    $('.ajax-requests-select3').select2({
        language: {
            searching: function () {
                return "Searching...";
            },
            loadingMore: function () {
                return "Loading more results..."
            }
        },
        placeholder: "Select - Search",
        allowClear: true,
        ajax: {
            delay: 250,
            allowClear: true,
            url: '<?= base_url("contacts/search_contacts") ?>',
            dataType: 'json',
            cache: true,
            data: function (params) {
                var query = {
                    term: params.term || createdId, // <<< Here I am assigning the id
                    page: params.page || 1
                }
                return query;
            },
        }
    });

My question is: Is there any way that I could trigger the second script somehow to find the createdId?

In the network tab I can see only the first AJAX request, but second is never fired. I have spent many hours over this code and any help will be deeply appreciated.

NextJs 14. Intercepting Routes. Modal. Routing Problem

Is it possible to navigate from OrderPage (/orders/n) to (/payments/n) using NextJs Link without activating @modal from parent directory (/orders)?

I recreated the problem in codesandbox

Order listing page (/orders) has list of orders and corresponding payments. If you open either links, modal is opened that is in fact expected behavior. But if you open /orders/n page directly one can expect to navigate to /payments/n page instead of /payments/n modal after clicking on the /payments/n link. Is it default behavior or am I missing something?

What I want:
In page /orders/1 -> go to /payments/1 [Open in it as normal page];

What is happening:
In page /orders/1 -> go to /payments/1 [Is opening as @modal];