Are 4 for loops slower than a bigger one?

Which piece of code is faster number 1 or numbre 2 :

i can try setting up a timer and measure it myself. But with such a small loop count, it will be negligible and probably not meaningful.

**Number 1:
**

const container = document.getElementsByClassName("container");
const container_length = container.length;
for (let i = 0; i < container_length; i++) {
    const button = container[i].querySelectorAll("button");
    button[0].addEventListener("click", U);
    button[1].addEventListener("click", O);
    button[2].addEventListener("click", A);
    button[3].addEventListener("click", R);
}
function U() {
    //.....
}
function O() {
    //.....
}
function A() {
    //......
}
function R() {
    //.....
}

**Number 2:
**

const container = document.getElementsByClassName("container");
const container_length = container.length;
function U() {
    for (let i = 0; i < container_length; i++) {
        container[i].querySelectorAll("button")[0].addEventListener("click", function() {
            //....
        });
    }
}
function O() {
    for (let i = 0; i < container_length; i++) {
        container[i].querySelectorAll("button")[1].addEventListener("click", function() {
            //....
        });
    }
}
function A() {
    for (let i = 0; i < container_length; i++) {
        container[i].querySelectorAll("button")[2].addEventListener("click", function() {
            //....
        });
    }
}
function R() {
    for (let i = 0; i < container_length; i++) {
        container[i].querySelectorAll("button")[3].addEventListener("click", function() {
            //....
        });
    }
}

Thanks!

Connect to thermal printer on client from Flask web app deployed on cloud

I am working on a Flask-based restaurant ordering system that will be deployed on a cloud hosting service, in this case Render. On the admin panel of the ordering system, the admin user can enter the IP address and host of the thermal printer and store it in the system, and can perform a test print using the printer attributes the user entered.

If the Flask server is on a local computer, the server can print the receipt through the thermal printer that is connected to the local computer, be it using Ethernet, Wi-fi or Bluetooth. However, if the Flask server is deployed onto a cloud hosting service, how can the Flask server be able to tell the thermal printer that is connected to the client to print the receipt?

JavaScript

const testStatus = document.getElementById('test-status');
const btnTestPrinter = document.getElementById('btn-test');
btnTestPrinter.addEventListener('click', async function(event) {
    var name = document.getElementById('name').value;
    var ipAddress = document.getElementById('ip_address').value;
    var port = document.getElementById('port').value;

    printer = {
        "name": name,
        "ip_address": ipAddress,
        "port": port
    }

    const testPrinterUrl = window.location.origin+'{{ url_for("test_printer") }}';

    try {
        console.log("Testing printer: "+name);
        const placeOrderResponse = await fetch(testPrinterUrl, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(printer)
        });
        const testResult = await placeOrderResponse.json();
        
        var success = testResult.success;
        if (success) {
            testStatus.textContent = "Test print success";
        } else {
            testStatus.textContent = "Unable to perform test print";
        }
    } catch (error) {
        console.error("Error: ", error);
    }
});

Flask server

@route('/test_printer', methods=['POST'])
def test_printer():
    data:dict = json.loads(request.data)
    print("Printer info: "+data.__repr__())

    name        = data['name']
    ip_address  = data['ip_address']
    port        = int(data['port'])
    date_str    = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")

    try:
        p = printer.Network(ip_address, port=port, timeout=30)
        p.text("Receipt text goes here")

        p.cut() # Cut the paper

        p.close()

    except Exception as e:
        print(f"Error: {e}")
        return json.dumps({'success': False}), 500, {'ContentType':'application/json'}

    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

Sending data to PHP file using FETCH always returns an error [closed]

Environment:

  • Abyss Server
  • PHP – HTML JavaScript, CSS
  • MySQL
  • All PHP files used in this issue are in the same folder

Simple server only PHP stock system, for learning PHP in the most simplistic environment possible

I am creating the project as simplistically as possible, no 3rd party wrappers like JQuery/REACT, just pure: PHP, JavaScript, HTML and CSS and a mySQL backend

Trying To Do:
From one PHP file read saved data from data table using another PHP file and populate firsts HTML form elements with the data (if found). Should done when user clicks the “find” button after entering an item ID

For some reason FETCH API in the HTML form PHP file returns “error”, and I cannot see anything wrong with the call.
The PHP file in the URL is not even processed and is in the same folder.

The first PHP file:

This is in progress so to test the FETCH call disabled the HTML form code so does not POST anything and attached JavaScript function to btnFind onclick to execute the FETCH command to test the search/passback routine

<!--

   Edits stock item

   IF stock item exists of course!

-->
<?php
include('../../header.php');
?>
<div id="divOptionsHeader">
   Stock Item Maintenance - Edit
</div>

<!-- <form id="formStockSearch" action="findstockitem.php" method="POST"> -->
<!-- <label for="txtFindItemID" class="clsFormRequired" id="lbltxtFindItemID">Item ID:</label>
   <input type="text" id="txtFindItemID" class="clsFormRequired" name="fldFindItemID" maxlength="50">
   <p></p>
   <input type="submit" id="btnFind" value="Find"> -->
<!-- </form> -->


<!-- <form id="formStock" action="editstockitem.php" method="POST"> -->
<label for="txtFindItemID" class="clsFormRequired" id="lbltxtFindItemID">Item ID:</label>
<input type="text" id="txtFindItemID" class="clsFormRequired" name="STKI_ItemID" maxlength="50">
<!-- <input type="submit" id="btnFind" value="Find" formaction="findstockitem.php"> -->
<button id="btnFind" onclick="funcFind()">Find</button>
<p></p>
<label for="txtUOM" class="clsFormRequired">UOM:</label>
<input type="text" id="txtUOM" class="clsFormRequired" name="STKI_UOM" maxlength="20">
<p></p>
<label for="txtProdFam" class="clsFormRequired">Product Family:</label>
<input type="text" id="txtProdFam" class="clsFormRequired" name="STKI_ProductFamily" maxlength="20">
<p></p>
<label for="txtPrice" class="clsFormRequired">Price:</label>
<input type="number" value="0.00" min="0.00" max="9999.99" id="txtPrice" class="clsFormRequired" name="STKI_Price"
   min="0" max="999999" step="1">
<p></p>
<label for="chkLocLot">Loc/Lot Tracked?:</label>
<input type="checkbox" id="chkLocLot" name="STKI_LocLot" checked>

<p></p>
<p></p>
<p></p>
<p></p>
<div id="divOperations">
   <input type="submit" id="btnSave" value="Save">
   <input type="reset" id="btnReset" value="Clear">
</div>
<!-- </form> -->

<a id="linkBack" href="stockitem_maintenance.php">Previous Page</a>

<script>
   async function funcFind() {
      // alert("Item: " + document.getElementById("txtFindItemID").value);
      const frmData = new FormData();
      frmData.append('STKI_ItemID', document.getElementById("txtFindItemID").value);

      try {
         const response = await fetch("findstockitem.php", {
            method: "POST",
            body: frmData,
         })
            .then(response => response.json())
            .then(data => {
               alert(data);
               document.getElementById("txtItemID").value = data["STKI_ItemID"];
            })
            .catch(error => {
               alert('Error:', error);
            });
      }
      catch (error) {
         alert(error);
      }
   }

</script>
<?php
include('../../footer.php');
?>
<!-- <script src="stockmaintenance.js" type="module" defer></script> -->

PHP file that finds the data:

Findstockitem.php:


<!--
  Searches Stock_Items to find the stock item
  if exists!!
-->

<?php
$blnOk = true;

#this is never executed neither is rest of the code which actually works!
echo "alert('read');";

if (!empty($_POST)) {
    #validate required field completed
    if (empty($_POST['STKI_ItemID'])) {
        $blnOk = false;
    }
}

#if something specified to search for (all this code works)
if ($blnOk) {
    #open database 
    require('../../../../connect_db.php');
    #check if record already exists
    $itemID = $_POST["STKI_ItemID"];
    $query = "select * from Stock_Items where stki_itemid='$itemID';";
    $r = mysqli_query($dbc, $query);

    if ($r) {
        #   if ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
        if ($row = mysqli_fetch_array($r)) {
            #record found!

            #disabled as I not sure WHICH PHP file it will display on!
            # echo $row['STKI_UOM'];

            #return record as JSON this bit is a guess!
            echo json_encode($row);
        } else {
           #peachy!
            echo "alert('Item ID Does Not Exist!'); window.history.go(-1);";
        }
    } else {
        echo 'alert( mysqli_error( $dbc)); window.history.go(-1);';
    }

    mysqli_close($dbc);
} else {
    echo "alert('Cannot Search For NULL Value!'); window.history.go(-1);";
}
?>

Is there a built-in identity function in JavaScript?

Is there a function in JavaScript that accepts a single (or works with a single) variable and just returns it? It shouldn’t copy an object or anything.

I know that this is really easy to implement:

const identity = x => x;
// or
function identity(x) {
  return x;
}

but I’m curious to see if there’s already something built-in of that type.

My use case is to check if an array has a value true. I know I can use arr.some(Boolean), but if I needed something to pass the parameter as a return value, what would I use? x => x doesn’t look clean and I think it is stored additionally in memory because it’s not a primitive value.

I know about Boolean, Number, Object & similar constructor-functions, but is there something that accepts all types?

How to correctly use Redux Toolkit with redux-persist and Next.js App Router?

I’m trying to set up Redux Toolkit with redux-persist in a Next.js project (App Router). I want to persist some parts of my Redux state (e.g., api, form, appNo, user, cart) using redux-persist.

However, I’m getting the warning:
You are using legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore().

I tried following that, but now my app either breaks or doesn’t rehydrate the state properly. Here’s my current setup:

redux/store.js

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // Use sessionStorage if needed
import { createWrapper } from "next-redux-wrapper";
import apiReducer from "./features/apiSlice";
import formReducer from "./features/formSlice";
import appNoReducer from './features/applicationSlice';
import userReducer from './features/userSlice';
import cartReducer from "./features/cartSlice"

const rootReducer = combineReducers({
  api: apiReducer,
  form: formReducer,
  appNo: appNoReducer,
  user: userReducer,
  cart: cartReducer,
});

const persistConfig = {
  key: "root",
  storage,
  whitelist: ["api", "form", "appNo", "user", "cart"],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const makeStore = () => {
  const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== "production",
    middleware: getDefaultMiddleware =>
      getDefaultMiddleware({
        serializableCheck: {
          ignoredActions: ["persist/PERSIST", "persist/REHYDRATE"]
        }
      })
  });

  store.__persistor = persistStore(store);
  return store;
};

export const wrapper = createWrapper(makeStore);

pages/_app.js

import { PersistGate } from "redux-persist/integration/react";
import { useStore } from "react-redux";
import "../public/css/global.css";
import "../public/css/animate.css";
import "../public/css/font-awesome.min.css";
import "../public/css/style.css";
import { wrapper } from "../redux/store";

function MyApp({ Component, pageProps }) {
  const store = useStore();

  return (
    <PersistGate loading={null} persistor={store.__persistor}>
      <Component {...pageProps} />
    </PersistGate>
  );
}

export default wrapper.withRedux(MyApp);

Is this the correct way to integrate redux-persist with Redux Toolkit in Next.js using createWrapper?

How to properly boost links?

I want to use the hx-boost tag of htmx like this:

<div hx-boost="true">
    <a href="/">Homepage</a>
    <a href="/guestbook">Guestbook</a>
</div>

If my understanding is correct this should issue an ajax GET request to the URLs.

Using Fastify with SQLite3 this is my route.js:

app.get('/guestbook', async (request, reply) => {
    const guestbookEntries = db
    .prepare(sql`select * from guestbook_entries`)
    .all();
    const isHtmxRequest = request.headers['hx-request'];
    // full reload
    if (!isHtmxRequest) {
        // render component when request comes from external -> renders header and footer thanks to htmx
        return reply.render(Component, props);
    }
    // render whole layout when request comes from internal routing
    return reply.render(
        Layout((params) => {
            return Guestbook({ ...params, entries: guestbookEntries });
        })
    );
});

and this is the minified version of the component (don’t mind the function html, it just generates the code into valid HTML):

export const Guestbook = ({ entries }) => {
    return html`
        <main hx-target="this" hx-swap="outerHTML">
            <h1>Guestbook</h1>
        </main>
    `;
};

The setup like this works but I am unsure why I need to pass only Guestbook as the component when doing a full reload and why I need to pass the Layout too when doing a route via an hx boostest a ref. If doing it the other way then I end up with either two links rendered or none.

Am I using hx-boost the wrong way? How to use hx-boost so that a click on the link really only loads the new <main> content?

Deno import breaking path to a file

I ran into a strange problem. Lets say i have a folder named qwe} and it contains two files named asd!.js and asd#.js. I can import the file qwe}/asd!.js without any problems but when i try to import the second one – im getting an error: Module not found "qwe%7D/asd#.js". So, some testing later, it seems like when im using a string that contains symbol # as a path to a module, then all symbols } converting into %7D regardless of how far they are from a # symbol. Other symbols seems to not convert when # is around, even the { one. So what is going on and is this possible for me to import a file with a path that contains both # and }? Im using import() function by the way, not statement.

How can I properly integrate my custom type declarations into my compiled npm package?

I’m working on a Node.js library and I’ve defined some custom namespaces and interfaces in a .d.ts file that I use as types in my function signatures. However, I’m having trouble getting these types taken into account in my compiled library.

Here’s a minimal example. Our directory structure will be as follows:

test
├── package-lock.json
├── package.json
├── test.ts
├── tsconfig.json
├── dist
│   ├── index.d.ts
│   └── index.js
└── lib
     ├── index.ts
     └── types.d.ts

Here are the contents of the files:

package.json

{
  "name": "test",
  "version": "1.0.0",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "author": "",
  "license": "ISC",
  "description": ""
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["lib/**/*"]
}

lib/types.d.ts

declare namespace MyTypes {
    interface Bar {
        a: string;
    }

    interface SecondBar {
        a: number;
    }
}

lib/index.ts

function foo(bar: MyTypes.Bar): string;
function foo(bar: MyTypes.SecondBar): number;
function foo(bar: MyTypes.Bar | MyTypes.SecondBar): number | string {
    if (typeof bar.a === "string") {
        return "0";
    }

    return 1;
}


const MyModule = { foo };

export default MyModule;

Thus, our module will export a function that will have two different return value types depending on the type of its single argument.

The problem here is that when we use TypeScript to compile the library, the type declaration file is not included in the result, so the MyTypes namespace is marked as not found in the function type declaration once TypeScript has compiled it.

So, if we try the library: (file test.ts)

import MyModule from "./dist";

const result = MyModule.foo({ a: "string" })
// result will be a string but will be considered by TypeScript as a number

Thus, result will be considered to have the wrong type, since the MyTypes namespace is purely ignored in compiled files.

Preact-ISO routes render as `[object Object]` in Vitest/JSDOM

Problem

When testing a Preact application using preact-iso for routing with Vitest and JSDOM, components rendered by <Route /> appear as [object Object] in the debug output. Crucially, console.log statements placed within these routed components (or their direct page wrappers) do not fire, indicating the router isn’t matching routes or instantiating the components.

How to Recreate

  1. App Structure (main_app.tsx):
    import { h } from 'preact';
    import { Router, Route } from 'preact-iso';
    const LogComponent = (props: { id: string }) => {
      console.log(`LogComponent ID: ${props.id}`); // This log doesn't fire
      return <div data-testid="routed">{props.id}</div>;
    };
    const Page = (props: any) => <LogComponent id={props.path === '/test' ? 'test-page' : 'default-page'} />;
    export const App = () => <Router><Route path="/test" component={Page} /><Route default component={Page} /></Router>;
    
  2. Test (main_app.test.tsx):
    import { render, screen } from '@testing-library/preact';
    import { MemoryRouter } from 'preact-iso/router'; // Initially tried MemoryRouter
    import { App } from './main_app';
    
    it('renders /test', () => {
      render(<MemoryRouter initialEntries={['/test']}><App /></MemoryRouter>);
      screen.debug(); // Shows [object Object]
      expect(screen.getByTestId('routed')).toBeInTheDocument(); // Fails
    });
    
  3. Initial vitest.config.ts Attempts: Various combinations of server.deps.inline, ssr.noExternal, explicit esbuild JSX settings were tried without success in making the inner console.log fire.

Expected Behavior
The console.log inside LogComponent should fire, and screen.debug() should show the rendered HTML (e.g., <div>test-page</div>). The test assertion should pass.

Actual Behavior
screen.debug() shows <div>[object Object]</div>. The console.log inside LogComponent does not fire. Test assertions fail.

Can’t get the curriencies in the cid array to decrement when purchase has been made, cash register project

I have been stuck on this freeCodeCamp project for a while, when purchase is made it returns the exact change needed sorting the bills from the highest denomination to the lowest but when i purchase again for the second time the change return but this time it sort the bills from the lowest denomination to the highest and the cid(cash-in-drawer) doesn’t seem to run out. here is my code

const calculateChange = (price, cash, cid) => {
/* calculates the total amount in the cid array */
  let totalCid = Number(cid.reduce((sum, el) => sum + el[1], 0).toFixed(2));
/* calculate change to give to customer when purchase is made */
  let change = Number((cash - price).toFixed(2)); 
  if (totalCid < change) {
    changeDue.innerText = "Status: INSUFFICIENT_FUNDS";
  } else if (totalCid === change && price < cash) {
    changeDue.innerText = "Status: CLOSED " + cid;
  } else {
    let changeArr = [];
/* reverse cid array so it starts giving change from the highest denomination */
    cid.reverse().forEach((el) => {
      let coinName = el[0];
      let totalAmountInDrawer = Number(el[1]);
      let equivalentOfAmountInDrawer = Number(currencyUnit[coinName]);
      let availableAmount = Number((totalAmountInDrawer / equivalentOfAmountInDrawer).toFixed(2));
      let amountCollected = 0;
    
      while (change >= equivalentOfAmountInDrawer && availableAmount > 0) {
        change = Number((change - equivalentOfAmountInDrawer).toFixed(2));
/* tried to decrement the totalAmountInDrawer but to no avail */
        totalAmountInDrawer--;
        availableAmount--;
        amountCollected++;
      }

      if (amountCollected > 0) {
        const amount = Number((amountCollected * equivalentOfAmountInDrawer).toFixed(2));
        changeArr.push([` ${coinName}: ` + `$${amount}` ]);
        return changeArr;
      }
    });
   
  changeDue.innerText = "Status: OPEN " + changeArr;
  }
}

i tried to decrement the totalAmountInDrawer but the cid array doesn’t run out. I don’t understand what i’m doing wrong

How Can I Improve Performance for a Custom Element Simulation in Sandboxels Using JavaScript?

I’m developing a custom element simulation in JavaScript inspired by the sandboxels online game, where particles interact with heat, density, and chemical reactions. My current setup uses a 2D canvas with a pixel-based grid, but with 500+ elements, the update loop is slowing down significantly. Here’s a simplified version of my update function:

function updateGrid(grid) {
    for (let x = 0; x < grid.width; x++) {
        for (let y = 0; y < grid.height; y++) {
            if (grid[x][y].type !== 'empty') {
                grid[x][y].update(grid, x, y);
            }
        }
    }
}

The loop checks every pixel for updates (e.g., gravity, reactions), but it’s causing frame drops on larger grids. I’ve tried reducing update frequency, but it breaks the simulation’s realism. How can I optimize this loop for better performance without losing accuracy? Are there specific data structures or techniques (e.g., spatial partitioning) that could help? A minimal example would be great.

How to simulate a cloth falling over a cube (table) using Three.js and a physics engine? [closed]

I’m trying to create a realistic animation in Three.js where a tablecloth (plane mesh) falls naturally onto a table (cube mesh), with the edges hanging and folding due to gravity.

I want the cloth to:

React to physics and gravity

Collide with the cube (table) as it falls

Be textured with a tileable tablecloth pattern

I’ve read that I might need a physics engine like Ammo.js or Cannon.js, but I’m not sure how to simulate the cloth realistically or map the texture correctly on a dynamic mesh.

write <td style= in .css file [duplicate]

I have this element

<td style="text-align: center; font-size: 11px; background-color: <?php echo $color ?>;">xxx</td>

where $color changes according to the value of xxx.
Since its a long line I would like put it into a .css file
Is it possible?

How to pass column with variable to a component’s slot in Laravel blade?

Im using to Laravel blade’s component to make a dynamic table, in which user can pass in header, and corresponding rows. I wanna use this component to display many tables (permissions, reviews, etc…). I use it in my view like this

                <x-admin.data-table :items="$review" route="admin/users">
                    <x-slot:header>
                        <th>Name</th>
                        <th>Description</th>
                    </x-slot>
                    <x-slot:row :item="$item">
                        <td>{{$item->name}}</td>
                        <td>{{$item->description}}</td>
                    </x-slot:row>
                </x-admin.data-table>

The row slot is display in data-table.blade.php like this

<tbody>
@foreach ($items as $item)
   <tr>
      {{ $row(['item' => $item]) }}
   </tr>
@endforeach
</tbody>

This part

                    <x-slot:row :item="$item">
                        <td>{{$item->name}}</td>
                        <td>{{$item->description}}</td>
                    </x-slot:row>

this is where people want to reuse this component, can pass their own attribute, i.e <td>{{$item->content}}</td>.
But what i get is Undefined variable $item. I tried using {{ $row->with(['item' => $item]) }} too, but still a no. How should I pass the columns to my slot then?

Google’s Blogger V3 api oAuth not working anymore

I have been using the Blogger V3 api for many years. I use the official googleapis.com PHP library to retreive data and take care of the oAUth2 flow. Since a couple of days I cannot let users authorize my app anymore.

I did a lot of debugging and reading on the internet and here are my findings:

  • The access_token that I receive after a user has authorized us through the oAuth permission screen, is valid. I can use the Google library to fetch the userinformation with it. ( $oauth = new Google_Service_Oauth2($client); $userinfo = $oauth->userinfo->get(); )

  • The access_token is validated fine when using https://oauth2.googleapis.com/tokeninfo?access_token={token}

  • I can perfectly fetch Blogger information and content in the Google Playground when I enter the access_token that I have retreived using the oAuth flow on my server. So the access_token seems to work within the Google environment itself.

  • However, when I try to request the Blogger V3 api from my server, I keep bumping into an 403 error. For example: “Your client does not have
    permission to get URL /v3/blogs/byurl from this server. That’s all we know.”

  • Sending direct curl requests with the access_token as bearer in the Authorization header returns the same error.

I’m really lost. There are no notifications in my Google Cloud Console dashboard. It seems that the Blogger api just broke without a warning.

Anybody else have the same experience or can offer help? Thanks!