LangChain and HuggingFace in javascript: how does it work?

I’m creating a server in javascript and i want to use it comunicate with an LLM on HuggingFace with LangChain.
I can’t find how the class HuggingFaceInferenceEmbeddings works. If you know it or you can link a proper documentation please let me know.

index.js

import express from 'express';
import mistral from './mistralClient.js';
import { configDotenv } from "dotenv";

configDotenv();

const app = express();
const PORT = process.env.PORT || 8080;

app.use(express.json());

app.post('/api/query', async (req, res) => {
  try {
    const response = await mistral.call({ //what should i use to interrogate Mistral?
      inputs: req.body.message,
    });
    console.log("Answer:", response);
    return response;
  } catch (error) {
    console.error("Error in Mistral call:", error);
  }
});

app.listen(PORT, () => {
  console.log(`Server avviato su http://localhost:${PORT}`);
});

mistralClient.js

import { HuggingFaceInferenceEmbeddings } from "@langchain/community/embeddings/hf";
import { configDotenv } from "dotenv";

configDotenv();

const apiKey = process.env.HUGGINGFACE_API_KEY;

console.log(apiKey)

const mistral = new HuggingFaceInferenceEmbeddings({
  apiKey: apiKey,
  
  model: 'mistralai/Mistral-7B-v0.1',
  temperature: 0.7,
  maxTokens: 200,
});

export default mistral;

Deactivate externally integrated Javascript file with Javascript

I have included the following in my header code (Google AdSense).

Now I am looking for a way to deactivate this line via Javascript:

<script type="text/javascript" src="https://domain.tld/javascript-file.js"></script>

Using CSS (Display:None) does not work because this code will be executed anyway.

I want to deactivate this line using an external JS (so that it is no longer executed) if this is defined in this external JS.

Thanks.

how can i remove unpermitted intrinsics

Good day, everyone. I am working on a project. React/js/vite and stumbled upon this error of

“X [ERROR] Two output files share the same path but have different contents: node_modules.vitedeps_temp_eeee2960react.j

The above error occurs in my terminal

The below error occurs in my chrome console
Removing unpermitted intrinsics
client:556 [vite] server connection lost. Polling for restart…
:5173/node_modules/.vite/deps/react-dom_client.js?v=edb49463:1

   Failed to load resource: net::ERR_CONNECTION_RESETUnderstand this errorAI

:5173/node_modules/.vite/deps/react-router-dom.js?v=1f4580c2:1

   Failed to load resource: net::ERR_CONNECTION_RESET

i expect to get the server running back after resolving this I have deleted my node modules, package.json, change the port, and also cleared my cache, but nothing is working.

Table and filter columns different in MUI Data Grid

In the Student Details column, I want to stack data values from three columns: Name, Major, and Year. Is it possible to do this while still maintaining the ability to filter by the individual columns? See image for an example where I want to filter by the Name and Major columns.

If not, is there another data grid library that would allow me to do this?

enter image description here

How can I generate an animated svg for website

I’m trying to find a solution for animating svg images like the next one:
lines. Idea of animation here is looped trasformation of lines, like it is a towel on the waves.

I know that it’s possible to do with after effects (AE) than export json than using lottie player, but I want to find a solution to do it with JS / WebGL / Three js etc. Don’t know what to do and how to start. As I understand, I need to generate this image with WebGL or canvas. Than use something like requestAnimationFrame… But i can’t find any similar examples which could help me with it.

It’s very important, that such animated SVGs will be used on the website like a backgrounds or illustrations, so it should be optimized lightweight solution. The website uses HTML (PUG), SCSS, JS. WordPress in future…

I tried to do it with AE + bodymovin, but there were a lot of difficulties and restrictions to prepare this image for json. Animation didn’t work because when I draw this picture in Adobe Illustrator, I used some features, which conflicts with next steps. For example, it turns out that only keyframes may be used for bodymovin and JSON. But I did the animation through the expression. Than I found that I can’t use effects of AE, some instruments in AI etc.

After that I tried to find a similar solution without AE, just JS + SVG, or only JS, or SMIL. But all I found was great difficult projects with Three.js like here: https://threejs.org/examples/#webgl_points_waves
Visually it’s close to my task if we are speaking about exapmle image in this topic, but I think it’s much more global and difficult than I need, especially if you consider that there may be 5 — 10 such animated images on the page of the future website, and such solutions like above use much more resources, than I need. I really hope that there should be easier way.

Real-Time Cloud Animation with Satellite Imagery like zoom.earth and accuweather

I’m trying to create a web application that shows real-time cloud animations using satellite imagery, similar to zoom.earth. The main challenge is finding reliable satellite imagery sources and implementing smooth animations with proper time controls. The application needs to:

Display global cloud coverage
Update in real-time or near real-time
Allow users to scrub through timeline
Provide smooth transitions between different time intervals
Maintain high-resolution imagery at various zoom levels

I’ve tried multiple satellite imagery sources:

Himawari – no document and implementation also not working
NASA GIBS – Complex implementation, delayed updates , imagery black layers
GOES – Limited coverage area
Meteomatics – API limitations
RAMMB Slider – Integration challenges
OpenWeather – Resolution not suitable for requirements
Expected Behavior:

Seamless cloud animation similar to zoom.earth
Real-time updates as new satellite data becomes available
Smooth transitions between time intervals
High-resolution imagery at all zoom levels
User-friendly timeline controls
Actual Results:

Gaps in coverage
Delayed updates
Choppy transitions between layers
Limited resolution at certain zoom levels
Basic timeline functionality
Questions:

Are there alternative satellite imagery sources I haven’t explored?
What techniques would work best for smooth layer transitions?
How can I implement real-time updates efficiently?
Are there specific libraries for timeline controls in this context?
Are there less-known APIs that might better suit this project?
Any guidance and code/documentation on these aspects would be greatly appreciated. Thank you!

Accessing User-Agent from Next.js Route Handler?

I’m trying to access a request’s User-Agent header from a route handler I have on my next.js project.
Here is an example:

import { userAgent } from "next/server";
export const dynamic = "force-static";
export async function GET(req: Request) {
  console.log(userAgent(req))
  return Response.json({ error: false, message: "Hello, world!" });
}

The console.log function returns this:

{
  ua: '',
  browser: { name: undefined, version: undefined, major: undefined },
  engine: { name: undefined, version: undefined },
  os: { name: undefined, version: undefined },
  device: { vendor: undefined, model: undefined, type: undefined },
  cpu: { architecture: undefined },
  isBot: false
}

The above code is using the userAgent function, which I know is designed for middleware, but for some reason middleware doesn’t seem to have an effect on Route Handlers.
I’ve also tried:

  1. the headers function
  2. Using req.headers.get(“User-Agent”)

and all of the approaches return a null/empty string value. I know the request doesn’t send a null user-agent because if I send a request to the same hosted project on Vercel and open up the Logs, the request shows a valid User-Agent column.

Aline.js x-data not reactive

I’m using Alpine.js to render a list of videos from an API. After making the API call, the response data populates my videos array successfully, but the page doesn’t update to show the new data.

Here’s a breakdown of what’s happening:

I’m making an Axios API request and pushing the resulting videos to the videos array.
I’ve confirmed via console log that videos is populated with the correct data.
Despite this, the template does not render the updated array.

Thank you!

  <template x-for="video in videos" :key="video.id">
    <!--video content-->
    <div>Test Video</div>
  </template>
      const app = {
            triggerElement: null,
            page: 1,
            lastPage: 24,
            itemsPerPage: 24,
            observer: null,
            isObserverPolyfilled: false,
            videos: [],
            debug: true,
            loaded: false,

            init: function () {

                window.addEventListener('urlChange', () => {
                    app.getItems();
                });

                app.triggerElement = document.querySelector('#infinite-scroll-trigger');

                document.addEventListener('DOMContentLoaded', function () {
                  //  app.getItems();
                    app.loaded = true;
                });

                app.infiniteScroll();

                (app.debug) ? console.log('init' )  : '';


            },
            infiniteScroll: function () {

                (app.debug) ? console.log('infiniteScroll' )  : '';

                // Check if browser can use IntersectionObserver which is waaaay more performant
                if (!('IntersectionObserver' in window) ||
                    !('IntersectionObserverEntry' in window) ||
                    !('isIntersecting' in window.IntersectionObserverEntry.prototype) ||
                    !('intersectionRatio' in window.IntersectionObserverEntry.prototype)) {
                    // Loading polyfill since IntersectionObserver is not available
                    this.isObserverPolyfilled = true

                    // Storing function in window so we can wipe it when reached last page
                    window.alpineInfiniteScroll = {
                        scrollFunc() {
                            var position = app.triggerElement.getBoundingClientRect()

                            if (position.top < window.innerHeight && position.bottom >= 0) {
                                if (app.loaded) {
                                    (app.debug) ? console.log('getItems 1' )  : '';

                                    app.getItems();
                                }

                            }
                        }
                    }

                    window.addEventListener('scroll', window.alpineInfiniteScroll.scrollFunc)
                } else {
                    // We can access IntersectionObserver
                    this.observer = new IntersectionObserver(function (entries) {
                        if (entries[0].isIntersecting === true) {
                            if (app.loaded) {
                                (app.debug) ? console.log('getItems 2' )  : '';

                                app.getItems();
                            }
                        }
                    }, {threshold: [0]})

                    this.observer.observe(this.triggerElement)
                }
            },
            getItems: function () {
                // TODO: Do fetch here for the content and concat it to populated items
                // TODO: Set last page from API call - ceil it

                let currentURL = new URL(window.location.href);
                currentURL.hostname = 'api.' + currentURL.hostname;


                axios.post(currentURL, {
                    page: this.page,
                    perPage: this.itemsPerPage,

                })
                    .then(response => {
                        const data = response.data;
                        //  this.lastPage = data.total_pages;
                        app.videos = data.data.videos;
                        //  this.page++;
                        (app.debug) ? console.log(response)  : '';

                    })
                    .catch(error => {
                        console.error('Error loading videos:', error);
                        (app.debug) ? console.log(error)  : '';
                        this.loading = false;
                    });


                // Next page
                this.page++

                // We have shown the last page - clean up
                if (this.lastPage && this.page > this.lastPage) {
                    if (this.isObserverPolyfilled) {
                        window.removeEventListener('scroll', window.alpineInfiniteScroll.scrollFunc)
                        (app.debug) ? console.log('alpineInfiniteScroll')  : '';

                    } else if (this.observer && this.triggerElement) {
                        try {
                            this.observer.unobserve(this.triggerElement);
                        } catch (e) {
                            console.error('Failed to unobserve element:', e);
                        }
                    }

                    if (this.triggerElement && this.triggerElement.parentNode) {
                        this.triggerElement.parentNode.removeChild(this.triggerElement);
                        this.triggerElement = null; // Prevent further access to the removed element
                    }

                }
            }
        };

Using this.$nextTick() after updating videos to ensure Alpine.js updates.
Manually triggering Alpine.js reactivity.
Directly manipulating the DOM as a temporary workaround (not ideal).
None of these approaches resolved the issue. I’d appreciate any insight into why Alpine.js might not be re-rendering the updated data or any alternative solutions.

Javascript – How to add a select option value without duplicating an existing value?

I’m using an text input bar to add values to a select options without using a value that already exists. I created a for loop, which test if the text in the input bar matches any value in the select options. It stops at two options of the same value but I’m trying to stop all duplication. How can I fix this?

enter image description here

https://jsfiddle.net/xb82n1d9/

window.onload = function() {
  const selectStoryBy = document.querySelector("select#story_by");
  const selectStoryByOptions = selectStoryBy.options;
  const addStoryByInput = document.querySelector(".add_story_by");
  const addStoryByButton = document.querySelector(".add_story_button");

  addStoryByButton.addEventListener("click", function(e) {
    addStory();
    e.preventDefault();
  });

  function addStory() {
    let addStoryByInputText = document.querySelector(".add_story_by").value;
    let newOption = document.createElement("option");
    let isNameAvailable = true;
    if (addStoryByInputText) {
      newOption.value = selectStoryByOptions.length;
      newOption.text = addStoryByInputText;

      for (let i = 0; i < selectStoryByOptions.length - 1; i++) {
        if (selectStoryByOptions[i].text == addStoryByInputText) {
          isNameAvailable = false;
          break;
        }
      }
      if (isNameAvailable == false) {} else {
        selectStoryByOptions.add(newOption);
      }

    }
  }
}
<div id="upload_flex_row">
  <label for="story_by">Story By:</label>
  <select id="story_by" name="story_by" size="10" multiple>
    <option value=""></option>
    <option value="my_username">Me</option>
    <option value="partner_no1">Partner One</option>
    <option value="partner_no2">Partner Two</option>
    <option value="partner_no3">Partner Three</option>
    <option value="partner_no4">Partner Four</option>
    <option value="partner_no5">Partner Five</option>
  </select>
  <span class="add_writer_span">
      <input type="text" name="add_story_by" class="add_story_by">
      <input type="submit" class="add_story_button" name="add" value="Add"/>
  </span>
</div>

Validating a Shopify Webhook

In Shopify, webhooks can be created for certain events that take place in the admin such as updating a product and they provide a note that says:

Your webhooks will be signed with
6574fb9832abafa73b29d30f6f200264b063669592b993b23369a2793a3db8e6

According to the Shopify docs for validating a webhook, it gives the following example:

app.post('/webhooks', express.text({type: '*/*'}), async (req, res) => {
  const {valid, topic, domain} = await shopify.webhooks.validate({
    rawBody: req.body, // is a string
    rawRequest: req,
    rawResponse: res,
  });

  if (!valid) {
    // This is not a valid request!
    res.send(400); // Bad Request
  }

  // Run my webhook-processing code here
});

If we don’t want to use Shopify’s library for this, and instead use a Netlify serverless function, node:crypto can be imported, and the request contains an x-shopify-hmac-sha256 header which has the following format.

'x-shopify-hmac-sha256': 'rgru9agBDpdwRFeKtp0+ez3PXj9yL7J0YMfsn8f0bBs='
import crypto from 'node:crypto'

export default async (req) => {
  const secret = '6574fb9832abafa73b29d30f6f200264b063669592b993b23369a2793a3db8e6'
  const shopifyHmac = req.headers.get('x-shopify-hmac-sha256')
}

How can we validate the webhook given the x-shopify-hmac-sha256 and secret?

How to get what the user entered in Contact Form 7 and change it before sending?

How to get what the user entered in Contact Form 7 and change it before sending? I have an input field, when the user submits the data I have to validate it and if there is anything to change, I tried many options but couldn’t find what I need.

For example, user write something, I need to compare it with JS variable, and change it in sending.

For minimal instance:
You need WordPress, plugin ContactForm7, and for JS I used WoodySnippets.
Create Contact Form with two fields and button.

<label>Doesn't need[text* text-564 placeholder ""]</label>
<label>Need[text* text-276 id:myform "5"]<label>
<button onclick="coinsCheck()">
<label>[submit "Submit"]</label>
</button>

and:

<script>
    myfor = document.getElementById("myform").value;
    function coinsCheck(){
        alert(myfor);
        if(myfor !== '6'){
            alert(myfor);
        }
    }
</script>

Here I output the variable, the first time just to know the value, the second time if it is not equal to 6.
But alert shows “null” twice(if snippet above form) or four times “[object HTMLInputElement]” if snippet below the form. And in console I have this error: Failed to load resource: too many HTTP redirects: http://1.gravatar.com/avatar/459d16a800ceb49fe2871a22c7041252?s=52&d=mm&r=g

Impossible to debug javascript freeze with devTools

Using devTools and adding logs everywhere didn’t help me debug a particular page.

I am working on a web component framework, and without going into the details or the way things work, I have my Chrome-based browser freezing during around 30 sec to 1 minute when I perform a particular action, and I can’t find any way to see where it is stuck. The same action in Firefox is immediate and has no consequence.

I have put a debugger just before the crash happens but it didn’t help.

Do anyone know a better way or wanna have a look ?

https://cp.bbn.io/computed.php

Just click the checkbox (it should change the number of the last entry of the list – called Chiara – at the bottom of the scroll).

Thanks!

How to get what the user entered in Contact Form 7 and change it before sending/after sending?

How to get what the user entered in Contact Form 7 and change it before sending? I have an input field, when the user submits the data I have to validate it and if there is anything to change, I tried many options but couldn’t find what I need.

For example, user write something, I need to compare it with JS variable, and change it in sending.

For minimal instance: You need WordPress, plugin ContactForm7, and for JS I used WoodySnippets. Create Contact Form with two fields and button.

Before sending:

<label>Doesn't need[text* text-564 placeholder ""]</label>
<label>Need[text* text-276 id:myform "5"]<label>
<button onclick="coinsCheck()">
<label>[submit "Submit"]</label>
</button>

and:

<script>
    myfor = document.getElementById("myform").value;
    function coinsCheck(){
        alert(myfor);
        if(myfor !== '6'){
            alert(myfor);
        }
    }
        function redCoin(decr){
           a = 5;
           decr = parseInt(decr)
           a -= decr;
           alert(a);
    }
</script>

Here I output the variable, the first time just to know the value, the second time if it is not equal to 6.
But alert shows “null” twice(if snippet above form) or four times “[object HTMLInputElement]” if snippet below the form. And in console I have this error: Failed to load resource: too many HTTP redirects: http://1.gravatar.com/avatar/459d16a800ceb49fe2871a22c7041252?s=52&d=mm&r=g

After sending:
When I added updated script(because send_ok is deprecated) in additional settings of Contact Form 7 for checking variables, that I have, it didn’t work

wpcf7Elm.addEventListener( 'wpcf7mailsent', function( event ) {
        alert( "Fire!" );
        redCoin(myfor);
    }, false );

What I am trying to do: check if input equals ‘6’, after mail is sent successfully, substact decr(decrease) from a(5)