How can I declare parameters for callback function via summary?

So I want to add a callback function to my other function, but the issue is since I want this code to be public, I want people to know what parameters to enter and what their types are.

I’ve tried to do it like Function<Event> and Function(ev:Event), but neither have worked, instead, it comes off as any.

This is my function:

/**
     * Adds an event listener to track scroll events
     * @param {void<Event>} callback 
     */
    static addScrollListener(callback) {
        Input.scrollListeners.push(callback);
    }

To be clear, by “summary” I’m referring to the description of the function.

Why am I getting this error? Please help me

const Home = () => {
  const dispatch = useDispatch();
  const {
    products: { list, filtered },
    categories,
  } = useSelector((state) => state);

  useEffect(() => {
    if (!list.length) return;

    dispatch(filterByPrice(100));
  }, 
  [dispatch, list.length]);

  return (
    <>
      <Poster />
      <Products products={list} amount={5} title="Trending" />
      <Categories products={categories.list} amount={5} title="Worth seeing" />
      <Banner />
      <Products products={filtered} amount={5} title="Less than 100$" />
    </>
  );
};

export default Home;

The error says that dispatch is not a functionenter image description here

Why dispatch is not a function I can’t find a solution

Fetching PHP script on localhost works via Postman but only inconsistently via browser

So I am building a webpage that calls a php script when you upload a file.
So when you upload a file, a javascript function is called that sends a post request with in it’s body the file to the php script on the server side. The pages are all in the root directory of the server on the same local host. This fetch request works only about 1 in 4 times. The other times it returns:

 Caught error: TypeError: Failed to fetch
    at uploadFile (main.js:38:12)
    at HTMLInputElement.<anonymous> (main.js:15:24)
(anonymous) @ main.js:56
Promise.catch (async)
uploadFile @ main.js:55
(anonymous) @ main.js:15

When I Post to this same PHP script via postman it works every time. I don’t think it is a cors issue because it sometimes does succeed, but I added lines to allow acces from anywhere to my PHP script anyways. The server side code works, I checked this using error logs and by logging what the response is.

This is my JS code:

function uploadFile(file) {
    let formData = new FormData();
    formData.append('fileToUpload', file);

    return fetch('http://localhost:[numbers]/matchingMain.php', {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (!response.ok) {
                // If the HTTP status code is not in the 200-299 range
                return response.text().then(text => {
                    throw new Error('Network response was not ok. Status Code: ' + response.status + '. Response Body: ' + text);
                });
            }
            return response.json(); // Parse JSON response
        })
        .then(data => {
            console.log('Response data:', data);
            return data; // You can further process the data or return it
        })
        .catch(error => {
            console.error("Caught error:", error);
            console.error("Error details:", error.message);
            // Optionally, handle the error further or display it to the user
        });
}

PayPal Save for Purchase Later – Save cards issue

I am creating a section on the checkout payment info where a customer should enter their card details so, in the case of market loss (*), we can charge him later on that card through PayPal.
I am implementing this using the PayPal SDK for saving cPayPalards and charging later and I am having an issue with “createVaultSetupToken” callback. I created both the frontend and backend logic with a call to my backend to create a setup token and to PayPal API (FE code below, BE API request is just like in documentation paymnet_source with an empty card object).

createVaultSetupToken: async (data) => {
     const result = await fetch("/PayPalExtended/setup/token", { method: "POST" })
              var jsonRes = await result.json()
              const { id } = jsonRes;
              return id;
            },

This is successful with 201 Created and I get the token back I return it to the callback, and the SDK never calls OnApprove callback because I receive an error from PayPal SDK.

graphql_UpdateVaultSetupToken_error 
Object { err: "Cannot get vault - no customer id found in id token", timestamp: "1703524904796", referer: "www.sandbox.paypal.com", sdkCorrelationID: "f137663e5663e", sessionID: "sessionID", clientID: "clientID", env: "sandbox" }
card-field:40:65202

OnError callback logs this:

Something went wrong: Error: Cannot get vault - no customer id found in id token
 https://www.sandbox.paypal.com/smart/card-field?type=cvv&clientID=clientID&sessionID=sessionID&clientMetadataID=uid_a55f4eb2d9_mtc6mdm6ntu&cardFieldsSessionID=cardFieldsSessionID&env=sandbox&debug=false&locale.country=GB&locale.lang=en&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jbGllbnQtaWQ9QVFIR2Vna3lsX2RjRmdnVmoxODFOZG80cG5id3U1YmhwaFRyRFRKWXVpdXBHZlE2RVVvaWtWQjV3WTRJMXZzTi1VeldFVVFTNU5ubnVsNWgmY3VycmVuY3k9VVNEJmludGVudD1hdXRob3JpemUmY29tbWl0PWZhbHNlJnZhdWx0PXRydWUmZGVidWc9ZmFsc2UmY29tcG9uZW50cz1idXR0b25zLGNhcmQtZmllbGRzIiwiYXR0cnMiOnsiZGF0YS1wYXJ0bmVyLWF0dHJpYnV0aW9uLWlkIjoiTm9wQ29tbWVyY2VfUFBDUCIsImRhdGEtdWlkIjoidWlkX3pqdnRodHZsZmFxaW9udGdhcGxyeHl1bnpsemp6cyJ9fQ&disable-card=¤cy=USD&intent=authorize&commit=false&vault=true&sdkCorrelationID=f137663e5663e:40

Card I used is from Card testing page for advanced checkout :

Number: 2223000048400011

date: 11/25

CCV:123

Name:  Mark Thomas

Response from API/my backend:

{
  "jsonRes ": {
    "id": "2DV308********",
    "payment_source": {
      "Card": null,
      "Token": null
    },
    "customer": {
      "id": "uCEH******"
    },
    "status": "CREATED"
  }
}

PayPal script src:

https://www.paypal.com/sdk/js?client-id=clientId&amp;currency=USD&amp;intent=authorize&amp;commit=false&amp;vault=true&amp;debug=false&amp;components=buttons,card-fields" data-partner-attribution-id="NopCommerce_PPCP" data-page-type="checkout" data-user-id-token="data-user-id"

No idea what is the issue, tried almost everything 🙂 .

* Since this is a Wire payment method, it can fail or a customer can blackout the trade after some time, and we have this policy where if this happens we charge the customer for the money lost on their credit card.

Tried almost everything.

  • With hardcoded card details (thought empty card was the problem)
  • adding billing address with card (thought missing address was the problem for customer)
  • tried different cards, names, expiry dates, ccv..
  • changing paypal script src query paramaters

Audio delay calculator / temperature maths script

So I’ve been trying to create an audio delay calculator which does some math with distance in meters and a temperature. Then I want to be able to click calculate and then the form will respond with the answer in Milliseconds.

Here is the only script I have found by scouting around and by adding bits together. The math is there. Now I just need to get it to work with a form and possibly take out some of the bits I don’t need there. Now this code is obviously been part of Something else in the past but i can’t find anything else like it online( only within a couple of iPhone apps) but I want this to be website based. I’m finding it hard to get it work so any help would be much appreciated

Here is a screen shot
Of what I’d like something like. This is not for an app but purely for a website

example of iPhone app setup

 "delay-calculator": function(e, t) {
                    var l,
                        r,
                        n = parseFloat(e[0].value),
                        o = parseFloat(e[1].value),
                        c = {},
                        d = t.dist,
                        v = t.temp;
                    if (n || (c.distance = "Please enter a distance"), o || (c.temperature = "Please enter a temperature"), n && o) {
                        if ("Feet" === d && (n *= .3048), l = o, "Fahrenheit" === v && (o = 5 / 9 * (o - 32)), o >= -273)
                            return r = 331.5 * Math.sqrt((o + 273.15) / 273.15), "Delay ".concat((n * (1e3 / r)).toFixed(2), "mS in dry air at ").concat(l, "° ").concat(v);
                        c.temperature = "Temperature must be above absolute zero"
                    }
                    return c
                },

Tailwind Utility Classes

Directory Structure and Tailwind Configuration

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js, ts, jsx, tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

The above code gives the following error when I try to run my project through npm run dev with a blank page opening up even though I’m just typing in “Hello World” right now –

warn – No utility classes were detected in your source files. If this is unexpected, double-check the content option in your Tailwind CSS configuration.
warn – https://tailwindcss.com/docs/content-configuration

I’d be glad if someone could help me with this. Thanks!

I am Running simple JQuery with Keyup event and animation but my animation is not working, why?

I have this simple JQuery addition program with animation on keyup event of 2nd #num2 input type text, I am getting proper answer but animation is not showing.

<!DOCTYPE html>
<html>
<head>
  <title>Addition using jQuery</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <input type="number" id="num1" placeholder="Enter first number">
  <input type="number" id="num2" placeholder="Enter second number">
  <h3 id="add"></h3><br/>
  <h3 id="sub"></h3><br/>
  <h3 id="mul"></h3><br/>
  <h3 id="div"></h3><br/>


  <script>
    $(document).ready(function() {
      $('#num2').keyup(function() {

        let num1 = parseFloat($('#num1').val());
        let num2 = parseFloat($('#num2').val());

        if (!isNaN(num1) && !isNaN(num2)) {
          let sum = num1 + num2;
          $('#add').text(sum);
          $('#add').slideDown(4000);
        } else {
          $('#add').text("Please enter valid numbers");
        }
    });
    
    });
    
  </script>
</body>
</html>

Joomla 4: Counting New Zoo CCK Articles Since Last Visit Using Cookies in Custom PHP Script

I have seen a unique function on a news website homepage. Whenever a new article is publish in the backend, and the user is browsing the homepage, a button shows up that “X number of new articles are available” (the ‘X’ is the numeric showing the number of new articles) E.g.: 3 new articles are available. When I click on that button, the homepage is refreshed. I also want the same function on my Joomla website homepage. I am using Zoo CCK for creating articles.

The HTML and CSS code is below:

.rf01{position:fixed;display:none;top:-195px;left:0;right:0;min-width:150px;max-width:200px;margin:auto;text-align:center;z-index:16;}.rf01.show{display:block;top:195px;}.rf02{position:relative;display:inline-block;min-width:150px;max-width:200px;height:32px;padding:4px 42px 4px 16px;background:#00aa5a;color:#fff;border:none;border-radius:16px;font:600 12px/1.0'Montserrat',sans-serif;text-transform:uppercase;box-shadow:0 4px 6px 0 rgba(0,0,0,.5);transition:all .7s ease;}
.rf02:after{content:"";position:absolute;display:inline-block;top:0;right:0;width:22px;height:22px;background-position:-749px -141px;margin:5px 12px 5px 8px;}.rf03{font-style:normal;}
<div id="refreshButton" class="rf01 show">
<button type="button" onclick="refreshPage()" class="rf02 spaf"><i id="newArticlesCount" class="rf03">0</i> New Article</button>
</div>

The JS code is:

<script>$(function(){function checkForNewArticles(){$.ajax({url:"/templates/bspk/refresh-count.php",type:"GET",success:function(response){$("#refreshButton").removeClass("show");if(response>0){$("#refreshButton").addClass("show");}$("#newArticlesCount").text(response);}});}setInterval(checkForNewArticles,5000);});function refreshPage(){location.reload(true);}</script>

Now the problem is with “/templates/bspk/refresh-count.php”. I am using Joomla 4 and Zoo CCK for article creation. The refresh-count.php, in response, should show the number of new zoo items from the time the user (all types of users; not only logged in) has visited the page (based on saved cookies).

IMPORTANT NOTE

  1. The CMS is Joomla 4
  2. The PHP version is 8.2.4
  3. The database prefix is “uzlei”
  4. The database table structure for the Zoo item is “uzlei_zoo_item”
  5. The Zoo Item Type is “article”
  6. I want this function available for all types of users (not only for logged-in users, so use cookie instead of Joomla session)

What is the simplest way to run a piece of JS code at UTC midnight? [duplicate]

I have found this answer, that runs a piece of code every midnight:

function runatmidnight(__func__) {
  var now = new Date();
  var night = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1, // the next day, ...
    0, 0, 0 // ...at 00:00:00 hours
  );
  var msToMidnight = night.getTime() - now.getTime();

  setTimeout(function() {
    __func__(); //  <==  This is the function being called at midnight.
    runatmidnight(); // Then, reset again next midnight.
  }, msToMidnight);
}

However, it runs the code at local midnight, not UTC midnight.

I tried to just naively add 'UTC+0000' to the midnight date, but that makes the .getTime() output NaN.

const runatmidnight=(__func__)=>{
  setTimeout(
    ()=>{ __func__(); runatmidnight(__func__) },

    new Date(
      new Date().getFullYear(),
      new Date().getMonth(),
      new Date().getDate()+1, 0, 0, 0, 'UTC+0000'
    ).getTime() - new Date().getTime()
    - (new Date().getTimezoneOffset() * 60000)
  )
}
runatmidnight(()=>{
  // Some piece of code.
})

Can I, perhaps, somehow get the user’s timezone and subtract that from the local midnight to get UTC midnight? Or is there a way more elegant and readable way to do this?

CORS Headers are not working with Icecast, despite sending the necessary headers

This issue could be specifically related to Icecast, but I think it’s more related to me not understanding how to solve this problem.

I’m running an Icecast server and I want to connect to it via Javascript client that is not on the same host.

It doesn’t work. I get the following in the client every time.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com:8000/live. (Reason: CORS request did not succeed). Status code: (null).

In the Icecast config, I have this.

<http-headers>
    <header name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    <header name="Access-Control-Allow-Origin" value="*" />
    <header name="Access-Control-Allow-Methods" value="GET POST PUT DELETE" />
</http-headers>

If I hit icecast with curl, here are the headers coming back.

< Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET POST PUT DELETE

If I take out the Access-Control-Allow-Headers and Access-Control-Allow-Methods, it still doesn’t work.

I feel like it should just work with the Access-Control-Allow-Orgin: *.

I’ve read the other answers on Stackoverflow and read numerous articles about CORS, but I can’t figure out what I’m missing.

Create custom parallax effect [closed]

I want to create a custom parallax effect like on this site: https://www.ghavamiplasticsurgery.com/ (when you scroll down a little bit, you will see their logo which loses opacity, below is an image, and then when scrolling more, there is a new block with text.
Probably something like combining css opacity and js scroll can do the job, but not sure how to do that exactly.

I tried to check the code of their website but didn’t manage to figure out how this is achieved. I saw that they using some plugin called jarallax on the website, but it’s not used for this effect. It must be some custom JS/CSS code.

How to transform an array into a newer one?

I have an array like this:

    var categories = [
        {
            "info": {"id": 1, "title": "cat1"},
            "products": [{"id": "1a", "title": "prod1"}, {"id": "1b", "title": "prod2"}]
        },
        {
            "info": {"id": 2, "title": "cat2"},
            "products": [{"id": "2a", "title": "prod3"}, {"id": "2b", "title": "prod4"}]
        },
        {
            "info": {"id": 3, "title": "cat3"},
            "products": [{"id": "3a", "title": "prod5"}, {"id": "3b", "title": "prod6"}]
        }
    ]

I want to transform this data into like this:

var categoriesNew = [
        {
            "id": 1,
            "title": "cat1",
            "products": [{"id": "1a", "title": "prod1"}, {"id": "1b", "title": "prod2"}]
        },
        {
            "id": 2,
            "title": "cat2",
            "products": [{"id": "2a", "title": "prod3"}, {"id": "2b", "title": "prod4"}]
        },
        {
            "id": 3,
            "title": "cat3",
            "products": [{"id": "3a", "title": "prod5"}, {"id": "3b", "title": "prod6"}]
        }
    ]

I have tried this code:

var categoriesNew = []
for(var i=0; i<categories[i].length; i++) {
    categoriesNew.push(categories[i].info)
    categoriesNew.push(categories[i].products)
}

But it doesn’t provide me my required output. How to solve this problem?