How can I create a simple heatmap with only javascript? [closed]

Im trying to create a 2 dimensional heatmap with only javascript using react. Im really lost as how to possibly do it. Appologies for the code, but this is where Im at, not understanding how I can do it. Would be very helpful of some tips on how to approach this.

const data = [
    {y: "jan", y: 2020, value: "bad"},
    {y: "feb", y: 2020, value: "good"},
    {y: "mar", y: 2020, value: "bad"},
    {y: "apr", y: 2020, value: "bad"},
    {y: "jan", y: 2021, value: "bad"},
    {y: "feb", y: 2021, value: "good"},
    {y: "mar", y: 2021, value: "bad"},
    {y: "apr", y: 2021, value: "good"},
    {y: "may", y: 2021, value: "good"},
    {y: "mar", y: 2022, value: "bad"},
    {y: "apr", y: 2023, value: "bad"},
];

const xAxis = ["jan", "feb", "mar", "apr", "may"];
const yAxis = data.map(item => item.y);

const App = () => {
    return (
        <div>
            {months.map(month => {
                return years.map(year=> {
                    return <div><h1>year</h1></div>
                })
            })}
        </div>
    )
}

The map Im trying to create:
enter image description here

Google Analytics from a third party script

I am developing a widget that can be added to a host website via snippet of js code that once rendered will add an iframe to the host website.

Now my customers want to give me their GA tracking id so that I can send events from my widget to their GA4 account.

How should I handle this ?

  1. Add GA4 tag to the widget code and send the events from within the iframe, regardless of any GA4 tag that the host / parent page has
  2. Post messages from within the iframe page to the parent window and then intercept them on parent window and send them to GA4 from there. I will have to check if the parent window already has GA4 tag and if so, use it. If not, I will have to add the tag to the parent window.

Couple of things to note:

  1. My customer has added my widget code into their website so I can do dom manipulation on their site.
  2. My widget iframe is running on my domain which is different from my customer’s parent window domain

React – pass returned value to different component

I’m trying to be able to load a product in a separate child component (which is enabled when a user clicks a product from a product list rendered map on the parent component).

I’ve set up a function to .filter through the list of products so just the product at the index value (that matches the ID of the product clicked from the product list) and return it in a variable.

In Parent Component

let focussedProduct = "";

const viewProduct = (productID) => {
  focussedProduct = focusProduct.filter((e, index, array)=>{
    return index == productID
  })
  console.log(focussedProduct[0]);
};
<div className='product' key={product.id} onClick={() => viewProduct(product.id)}>

Which console logs this, so it’s returning what I need when clicking random items:

enter image description here

However I’m really struggling to pass the returned value/data to the child component to map it and start rendering that product, I thought it would be as easy as passing the variable like this.

Parent component

<Product 
  focussedProduct = {focussedProduct}
/>

Child component

import React, {useState} from "react";

const Product = (props) => {  
    console.log(props.focussedProduct)  
}

export default Product;    

But it’s not returning anything in the console to use/map. So I’m guessing I’m doing something wrong and I’m sure it’s simple but I’m not getting there even after doing a bit of googling. Help is much appreciated.

Server reconciliation issue with mousemove system

Context

I’m having trouble figuring out exactly how to implement server reconciliation in my game, which uses JavaScript, Node.js, and WebSockets. I’m creating an Agar.io-type game where the player is a circle that controls their movement with their mouse. When the player moves their mouse, it calculates the direction they are moving in and applies that value to the player on each frame.

TL;DR / ESSENTIAL QUESTIONS

My current implementation of server reconciliation is creating a choppiness/jittering effect on the player’s screen, so I’m doing something wrong.

I’m wondering how to fix the disparity between the number of frames the server runs and the number of frames the client runs — the client runs more times than the server, which I track with a variable. This discrepancy seems to be causing issues with reconciliation — how would a loop running at the same rate give different values on the server vs. the client?

Additionally, I’m wondering if there are any overarching ideas on how I can more effectively implement server reconciliation in my game. The examples I’ve seen don’t fit my exact scenario as several factors influence the exact position the player is in at a given time. I’m tracking the number of mouse movements the player makes the how many frames they move in that direction for, and I don’t see any other way to do it, but are there any other ideas? Especially because I’m not sure how to allow the server to be authoritative while allowing client prediction (because of the difference between how many frames run according to the server and according to the player).

Problem

While I understand the concept of server reconciliation, I’m having a tough time implementing it in my game as there are several factors that play into the player’s position at any given moment: their current X/Y positions, speed, direction they are moving in (determined by the mouse’s movements), and their velocity (velocity occurs when the players bump into each other).

When I first tried implementing server reconciliation, I just tracked the user’s mouse movements and made the server process those events. However, I realized that this doesn’t really track the player’s position at all because what matters is how many frames the user runs while going in the specific direction the mouse dictates. So, I decided to count the number of frames that run with each mouse movement on the client side. Here is just the game loop code that runs on each frame and the incrementing of the number of frames:

const fps = 66.67;
const msPerFrame = 1000 / fps;

function gameLoop() {
    window.requestAnimationFrame(gameLoop);

    const msNow = window.performance.now();
    const msPassed = msNow - msPrev;

    if (msPassed < msPerFrame) return; //limit client-side frame rate as different screens can have different rates

    framesWithCurrentDirection++; // add 1 to frames that have run with current direction player is moving in
...

Then, when the mouse moves, it adds the player’s current position information to an array along with the number of frames that ran while the player was moving in that direction:

$(canvas).on('mousemove', (event) => {
    ...
    sequenceNumber++; //keep track of sequence number
    //add all relevant player info to use when server responds with its sequence number
    playerInputs.push({ 
        sequenceNumber: sequenceNumber,
        framesWithCurrentDirection: framesWithCurrentDirection, //tracks # of frames run
        movingDirection: { x: xMovingDirection, y: yMovingDirection}, //calculated with each mouse move
        speedMultiplier: multiplier, //how fast player should go (based on how far mouse is from player)
        vx: localPlayer.vx, //x velocity
        vy: localPlayer.vy, //y velocity
        speed: localPlayer.speed, //player speed
        radius: localPlayer.radius //player radius
    });

    //send the direction the player moves in to the server
    const moveData = {
        playerID: localPlayer.id,
        xMovingDirection: xMovingDirection,
        yMovingDirection: yMovingDirection,
        speedMultiplier: multiplier,
        sequenceNumber: sequenceNumber
    };
    socket.emit('playerMove', moveData);

    framesWithCurrentDirection = 0; //reset frames with current direction
});

On the server, the player’s mouse movements are acknowledged and the server updates the player’s sequence number to track how many mouse move events have been processed (which is stored in the Player class):

socket.on('playerMove', (data) => {
       const sequenceNumber = data.sequenceNumber;
        player.sequenceNumber = sequenceNumber;
        player.framesWithCurrentDirection = 0; //reset # of frames moving in current direction
    });

Additionally, the server has a gameLoop() running at the same FPS (66.67) as the client side, which does several things, including emitting player’s positions to all connected players in a given room and updating the number of frames the game runs while the player is going in the direction their mouse dictates:

const frameRate = 1000 / 66.67;
setInterval(() => {
    rooms.forEach((room, roomId) => {
        gameLoop(room, roomId);
    });
    
}, frameRate);

function gameLoop() {
     ...

    room.players.forEach((player) => {
     player.framesWithCurrentDirection++; //increase frames moving in current direction for each player

    ...

    //emits player positions to all room’s connected players
    const playerPositions = Array.from(room.players.values()).map(player => ({
        playerID: player.id,
        x: player.x,
        y: player.y,
        speed: player.speed,
        sequenceNumber: player.sequenceNumber,
        frames: player.framesWithCurrentDirection
    }));
    io.to(roomId).emit('playerPositionsUpdate', playerPositions);
}

Back on the client side, when ‘playerPositionsUpdate’ is received, it checks the received sequenceNumber against the stored mouse movements input array and splices the sequenceNumber values that are less than what the server provided. It then applies the unfinished mouse movements to move the player from the server’s last processed position to their correct position. The idea is that, for each unprocessed mouse movement, the client checks the number of frames the server gives back against the number of frames it was keeping track of on its own. For each unprocessed frame, it runs the move() method for the player:

socket.on('playerPositionsUpdate', (playerPositions) => {
    playerPositions.forEach(({ playerID, x, y, speed, sequenceNumber, frames }) => {
        //set player’s position to whatever server says
        player.x = x;
        player.y = y;
        player.speed = speed;
            
        //find the index of the last event that the server has processed
        const lastBackendIndex = playerInputs.findIndex(input => input.sequenceNumber === sequenceNumber);
            
        //if the index exists (if something is unprocessed), remove everything up to that point from the playerInputs array, which stores the player’s mousemove info   
        if (lastBackendIndex > -1) {
            playerInputs.splice(0, lastBackendIndex + 1);
        }

        // Apply any unprocessed inputs
        playerInputs.forEach(input => {
            const framesLeft = input.framesWithCurrentDirection - frames;
            const framesStartingPoint = Math.max(0, input.framesWithCurrentDirection - framesLeft);
            //start at the frame that has not been processed yet
            for (let i = framesStartingPoint; i < input.framesWithCurrentDirection; i++) {
                const velocity = { vx: input.vx, vy: input.vy };
                const coordinates = { x: x, y: y };
                player.move(input.movingDirection, input.speedMultiplier, input.speed, velocity, coordinates); //normal player movement method
            }
        });
    } else {
        // For other players, smoothly interpolate to the server position
        gsap.to(player, {
            x: x,
            y: y,
            speed: speed,
            duration: 0.05,
            ease: 'linear'
        });
    });
});



With all of this said, I’m finding that the server gives a lower number of frames than the client does. It seems that the frames need to match up exactly for this to work. For example, after about 2 seconds, the server says that much fewer frames have run than the client says. This is an issue because it makes it difficult to track how many frames have truly run. And it means that extra frames are being processed, leading to choppiness in player movement.

Question

This code is creating choppiness (my game is smooth on my local computer without server reconciliation, but I have to implement it because my live server is a lot slower). Any ideas how to fix this issue with the inconsistency in the frames? Additionally, do you see anything wrong with the way I’m going about server reconciliation? It’s the type of issue where something small could be wrong and fixing that would fix the whole issue, but I’m not sure if that’s the case or if I’m just completely off. Any suggestions?

Re-exporting antd components while keeping /es direcory available

I am using yarn workspaces for my project, with following structure

root
   packages
      app1
          tsconfig.json
      app2
      ui-kit
          ant-design
              index.d.ts
          tsconfig.json
   tsconfig.json

in index.d.ts I am re-exporting antd component wrapped with additional props, but antd has a lot of types in antd/es/* I need to use in my project.
I dont want to re-export all of them (because there is a lot of them and structure might change).

So I modified ui-kit/tsconfig.json to be

{
    "extends": "@my-config-lib/tsconfig.base.json",
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "ant-design/es/*": ["node_modules/antd/es/*"]
        },
    },
    "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"],
    "exclude": ["dist", "node_modules"]
}

While this help me to import from within ui-ki using ./ant-design/es/menu/etc
This does not work when this ui-kit is used in app1 or app2.
I tried setting references in app1/tsconfig.json but that does not seem to help.
Also i have tried adding paths in app1/tsconfig.json to be "@fineapp/ui-kit/antd-design/es*" : "../ui-kit/node_modules/antd/es/*"
but also no luck.

Is there a way to tell app1/tsconfig to look for paths in ui-kit/tsconfig.json while trying import code from it ?

Unable to consume the shared library by HOST in Module Federation

I am working on Module Federation, and I have built One host app and several remote apps.
The thing is I have installed some dependencies at host side and want to share it its remotes, so that the remotes does not need to install these dependencies again.

From my host app webpack.config.js, I’m sharing the dependencies, show below:

shared: {
...deps,
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
"react-router-dom": {
singleton: true,
requiredVersion: deps["react-router-dom"],
},
"react-redux": {
singleton: true,
requiredVersion: "9.1.2",
},
"@reduxjs/toolkit": {
singleton: true,
requiredVersion: "2.2.7",
},
},

and in the remote apps, I'm consuming it as:
shared: {
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
"react-router-dom": {
singleton: true,
requiredVersion: false,
},
"react-redux": {
singleton: true,
requiredVersion: false,
},
"@reduxjs/toolkit": {
singleton: true,
requiredVersion: false,
},
},

The thing is whenever I build all the apps, using npm run build command, I get
at host that it shared the libraries:
provide-module modules 210 bytes
provide shared module (default) @reduxjs/[email protected] = ./node_modules/@reduxjs…(truncated) 42 bytes [built] [code generated]

  • 4 modules:

But at while building the remote apps, I get:

consume-shared-module modules 84 bytes
consume shared module (default) react@* (singleton) 42 bytes [built] [code generated]
consume shared module (default) react-redux@* (singleton) 42 bytes [built] [code generated]

ERROR in resolving fallback for shared module react-redux

What I see is, the host is sharing the dependencies and remotes are receiving it, but still on building the remote apps, it is looking for the libraries in inside its node_modules directory

What I see is, the host is sharing the dependencies and remotes are receiving it, but still on building the remote apps, it is looking for the libraries in inside its node_modules directory

How can I create a list in SAPUI5 where each line contains data from multiple entities?

I’m trying to create a page with a questionnaire, where users are presented a list of questions and have to answer them. There are multiple types of answers (multiple choice, textfields, numeric ratings, etc.).

I managed to load the questions correctly from my odata service and the view (including the different answer fields) is rendered correctly. But now I’m struggling to actually bind the answer fields to the data.

I have a relation between the questions and the answers in my database, but since the list is auto-generated using the question items, I don’t know how to correctly associate and fill the fields.

I’ve bound the questions like this to the list:

this.getView().bindElement({
    path: "/Questionnaire(ID=" + sID + ",IsActiveEntity=true)",
    parameters: {
        expand: "questions" // Include the questions association
    },
    events: {
        dataReceived: function (oData) {
            console.log("Data received:", oData);
        },
        dataRequested: function () {
            console.log("Data requested...");
        }
    }
});

I’ve already tried multiple things, but I didn’t even manage to retrieve the data and log it to the console or something like that.
Most things I’ve found when searching for a solution use OData v2 where you could use the ‘read’ function of the model to get the data, but since I’m using an OData v4 service this isn’t available to me as far as I understood.

Any help or tips would be greatly appreciated

Visual Studio Script Documents Delay

Working on javascript projects in Visual Studio is frustrating due to all library scripts being opened in Script Documents. Whenever I make a change to a source file (JS,TS,HTML,CSS etc) all scripts must reload, which will freeze Visual Studio for some time.

This is more tolerable when using the inbuilt React template, as changes to TSX are hot-reloaded. I am currently trying out Lit + Shoelace with Vite, and the experience is almost unusable.

Anyway to get the hot-reload behaviour on non-React projects? Or anyway in general to mitigate delay?
Script Documents

Create a link having JSTL variable

I try to create a link by using javascript and I got some errors

document.addEventListener("DOMContentLoaded", function() {
  const token = localStorage.getItem('token'); // Lấy token từ localStorage
  const navLinks = document.getElementById('nav-links'); // Lấy phần tử nav chứa các liên kết
  const contextPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2)); // Lấy context path

  if (token) {
    fetch('/api/jwt/getName', {
        method: 'GET',
        headers: {
          'Authorization': 'Bearer ' + token,
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(data => {
        if (data && data.username) {
          const name = data.username; // Assign username from API
          console.log(name);

          navLinks.innerHTML = '';

          // Sử dụng template literals để chèn giá trị `name` từ JavaScript
          const profileLinkValue = `<a class="nav-link" href="${contextPath}/profile">${name}</a>`;

          // Tạo phần tử `li` chứa liên kết profile
          const profileLink = document.createElement('li');
          profileLink.classList.add('nav-item');
          profileLink.innerHTML = profileLinkValue;
          navLinks.appendChild(profileLink);

          // Tạo phần tử giỏ hàng và logout
          const cartLink = document.createElement('li');
          cartLink.classList.add('nav-item');
          cartLink.innerHTML = `
                    <a class="nav-link" href="${contextPath}/shopping_cart">
                        <img src="/image/shopping-cart.png" alt="Shopping cart" width="35" height="30">
                    </a>
                `;
          navLinks.appendChild(cartLink);

          const logoutLink = document.createElement('li');
          logoutLink.classList.add('nav-item');
          logoutLink.innerHTML = `<a class="nav-link" href="${contextPath}/logout">Logout</a>`;
          navLinks.appendChild(logoutLink);
        }
      })
      .catch(error => {
        console.error('Error fetching user info:', error);
      });
  }
});

When I run the web server,the page look like this

enter image description here

The problem here is, the profileLink should show the real account name, not the word ‘name’.

I have tried to log something, and I found the api works fine.
The problem I think is just the jstl variable ${name} in the link.
Could someone tell me the proper syntax for this? Thanks!

Edit : I have hardcored the value of the link as Example Name, and it’s the result

https://drive.google.com/file/d/1Wh1uUq0CMO8ExZv_soqMMsyIjQkwx968/view?usp=sharing

 navLinks.innerHTML = `
   <li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/profile">ExampleName</a></li>
   <li class="nav-item">
     <a class="nav-link" href="${pageContext.request.contextPath}/shopping_cart">
       <img src="/image/shopping-cart.png" alt="Shopping cart" width="35" height="30">
     </a>
   </li>
   <li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/logout">Logout</a></li>
  `;
}

and it showed like the pic above, so I think the real problem is ${data.username}.

[Create a link having JSTL varible]

I try to create a link by using javascript and I got some errors

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const token = localStorage.getItem('token');  // Lấy token từ localStorage
        const navLinks = document.getElementById('nav-links');  // Lấy phần tử nav chứa các liên kết
        const contextPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2)); // Lấy context path

        if (token) {
            fetch('/api/jwt/getName', {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data && data.username) {
                        const name = data.username; // Assign username from API
                        console.log(name); 

                        navLinks.innerHTML = '';

                        // Sử dụng template literals để chèn giá trị `name` từ JavaScript
                        const profileLinkValue = `<a class="nav-link" href="${contextPath}/profile">${name}</a>`;

                        // Tạo phần tử `li` chứa liên kết profile
                        const profileLink = document.createElement('li');
                        profileLink.classList.add('nav-item');
                        profileLink.innerHTML = profileLinkValue;
                        navLinks.appendChild(profileLink);

                        // Tạo phần tử giỏ hàng và logout
                        const cartLink = document.createElement('li');
                        cartLink.classList.add('nav-item');
                        cartLink.innerHTML = `
                    <a class="nav-link" href="${contextPath}/shopping_cart">
                        <img src="/image/shopping-cart.png" alt="Shopping cart" width="35" height="30">
                    </a>
                `;
                        navLinks.appendChild(cartLink);

                        const logoutLink = document.createElement('li');
                        logoutLink.classList.add('nav-item');
                        logoutLink.innerHTML = `<a class="nav-link" href="${contextPath}/logout">Logout</a>`;
                        navLinks.appendChild(logoutLink);
                    }
                })
                .catch(error => {
                    console.error('Error fetching user info:', error);
                });
        }
    });

</script>

When I run the web server,the page look like this
enter image description here
The problem here is, the profileLink should show the real account name, not the word ‘name’.

I have tried to log something, and I found the api works fine.
The problem I think is just the jstl variable ${name} in the link.
Could someone tell me the proper syntax for this? Thanks!

Edit : I have hardcored the value of the link as Example Name, and it’s the result

https://drive.google.com/file/d/1Wh1uUq0CMO8ExZv_soqMMsyIjQkwx968/view?usp=sharing

 navLinks.innerHTML = `
                                           <li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/profile">ExampleName</a></li>
                        <li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/shopping_cart">
                            <img src="/image/shopping-cart.png" alt="Shopping cart" width="35" height="30">
                        </a></li>
                        <li class="nav-item"><a class="nav-link" href="${pageContext.request.contextPath}/logout">Logout</a></li>
                    `;
                    }

and it showed like the pic above, so I think the real problem is ${data.username}.

How can I properly use CKEditor in a Blazor ssr project?

The component I wrote is as follows.
This Blazor component integrates CKEditor into a Blazor project using JavaScript interop (IJSRuntime).
A simple element is defined with an id that defaults to “editor”, but the EditorId can be passed as a parameter to allow multiple CKEditor instances.
Value: The current value of the editor, bound to the content in CKEditor.
ValueChanged: An EventCallback that notifies the parent component of content changes in CKEditor.
EditorId: The id of the editor, which defaults to “editor”, used for JavaScript interop to link CKEditor to the right element.

@using Microsoft.JSInterop

<textarea id="@EditorId"></textarea>

@code {
    [Inject] private IJSRuntime JS { get; set; }

    [Parameter] public string Value { get; set; }
    [Parameter] public EventCallback<string> ValueChanged { get; set; }
    [Parameter] public string EditorId { get; set; } = "editor";

    private DotNetObjectReference<CkEditor> _objRef;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _objRef = DotNetObjectReference.Create(this);
            await JS.InvokeVoidAsync("initializeCkEditor", EditorId, _objRef);
        }
    }

    [JSInvokable]
    public async Task UpdateValue()
    {
        var content = await JS.InvokeAsync<string>("getEditorContent", EditorId);
        if (content != Value)
        {
            Value = content;
            await ValueChanged.InvokeAsync(Value);
        }
    }

    public void Dispose()
    {
        _objRef?.Dispose();
    }

}

Also, the javascript code is according to the following code

window.initializeCkEditor = (editorId, dotNetObject) => {
    if (CKEDITOR.instances[editorId]) {
        CKEDITOR.instances[editorId].destroy();
    }

    CKEDITOR.replace(editorId);

    CKEDITOR.instances[editorId].on('change', function () {
        dotNetObject.invokeMethodAsync('UpdateValue');
    });
};

window.getEditorContent = (editorId) => {
    if (CKEDITOR.instances[editorId]) {
        return CKEDITOR.instances[editorId].getData();
    }
    return '';
};


window.setEditorContent = (editorId, content) => {
    const interval = setInterval(() => {
        if (CKEDITOR.instances[editorId]) {
            CKEDITOR.instances[editorId].setData(content);
            clearInterval(interval);
        }
    }, 100); 
};

Sometimes when loading the component page it doesn’t work properly.

How to get red/green solid candlestick in eCharts graph

I’m trying to get red/green candlesticks in a eCharts graph starting by the example on eCharts site.

The starting example it’s called “Large Scale Candlestick” that generates random data from a custom function called generateOHLC.

ORIGINAL EXAMPLE LINK

In an other example there’s a link that gets data from a JSON file also from eCharts site you can see at this link: https://echarts.apache.org/…

The values ​of each array (in the big array) ​are respectively [date ,open, close, low, high, volume]

Now, I have taken some of this value and I have adapted it to get an other value in the inners array with this small easy JavaScript code:

data.forEach(function (point, point_index){
  point.push (   getSign(data, point_index, point[1], point[2], 2)   )
  //console.log(point)
})

by using the same function getSign used from the previous example.

So the last value added (pushed in the array as 1 or -1) should make the candle turn red or green.

You can see the result of the adapted example here:

ADAPTED ECHART EXAMPLE

So, why the candles are always red and the ones in the first example are red and green?

Where’s my error and what I’m doing wrong?

why bracket change my out on line 7 in javaScript [closed]

While working with arrays in JavaScript, Here I tried to calculate average using reduce method.
My question is at line 3: without using bracket avg + num/ arr.length gives correct output but using bracket (avg + num) / arr.length gives wrong output.

Can anyone explain what’s the reason behind this wired behavior?

const calcAverage = function (nums) {
  const average = nums.reduce(
    (avg, num, i, arr) => (avg + num) / arr.length,
    0
  );
  return average;
};
const avg = calcAverage([1, 1, 1, 1, 1]);
console.log(avg);

how to conditionally extend ticksize length in Echarts

I am trying to create a charts multiple bar in echarts, i want when there is jan(01) first month then its ticks extend 2X then normal size means conditionally
how i can increase ticksize conditionally as i am doing for x axis label in echarts
Is there any way to make itb possible in javascript
Is echarts not support custom function on all property as done in d3.js

const colors = ['#5470C6', '#EE6666'];
option = {
  color: colors,
  tooltip: {
    trigger: 'none',
    axisPointer: {
      type: 'cross'
    }
  },

  legend: {},
  grid: {
    width: 1200
  },
  xAxis: [
    {
      type: 'category',
      axisLabel: {
        formatter: function (value, index) {
          // Convert timestamp to a Date object
          const date = new Date(value);
          const month = date.getMonth() + 1; // Months are zero-based
          const year = date.getFullYear();

          // Check if the month is January
          if (month === 1) {
            // Increment the year and format as needed
            const nextYear = year + 1;
            return `${echarts.format.formatTime(
              'MM',
              date
            )}n${year}&&${nextYear}`;
          } else {
            // Format the label for other months
            return echarts.format.formatTime('MM', date);
          }
        }
      },
      axisTick: {
        show: true,
        length: 20
      },
      // "offset": 10,
      axisLine: {
        onZero: false,
        lineStyle: {
          color: colors[1]
        }
      },

      data: [
        '2016-1',
        '2016-2',
        '2016-3',
        '2016-4',
        '2016-5',
        '2016-6',
        '2016-7',
        '2016-8',
        '2016-9',
        '2016-10',
        '2016-11',
        '2016-12',
        '2017-1'
      ]
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Precipitation(2015)',
      type: 'bar',
      smooth: true,
      emphasis: {
        focus: 'series'
      },
      data: [
        10, 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3
      ]
    }
  ]
};

Error in Fetching Streaming Response from RetrievalChain javascript

I created the pipeline using langchain inside the JavaScript, when I am using chain.invoke() method its working precisely but when I am trying to call the chain by chain.stream() method I am getting issues as nothing prints on the console. Is there anyone facing the same issues?


    const prompt = ChatPromptTemplate.fromMessages([
      ["system", systemPrompt],
      new MessagesPlaceholder("chat_history"),
      ["user", "{input}"],
      ["user", userPrompt],
    ]);


    // console.log("Prompt is : ");
    // console.log(prompt);

    // Chain creation using prompt and model
    const chain = await createStuffDocumentsChain({
      llm: modelInstance,
      prompt,
    });


    // Initialize retriever with the vector store
    const startTimeInner = Date.now();
    const retriever = vectorStore.asRetriever({
      search_type: "mmr",
      search_kwargs: { k: 3 },
    });


    // console.log(vectorStore);
    const endTimeInner = Date.now();
    console.log(
      "Total time taken by retriever to fetch data from db: ",
      (endTimeInner - startTimeInner) / 1000
    );

    // Create a retrieval chain with the retriever and document chain
    const retrievalChain = await createRetrievalChain({
      retriever,
      combineDocsChain: chain,
    });

calling a streaming response

const response = await chain.stream({
    chat_history: chatHistory,
    input: question,
    
  });
  let firstResponse = false;
  for await (const chunk of response) {
    console.log(chunk);
    yield chunk.answer;
  }