ChartJS v4 – Using Points in a line chart will result in all x-values at 0

I am facing a rather strange problem with line charts and ChartJS. Given the following very simple code. I expect to have a line chart where 3 data points (at x: 0, x:1 and x: 2). But instead, all points are shown at x:0. According to the docs: https://www.chartjs.org/docs/latest/charts/line.html#data-structure it should be possible to use the given notation to draw the line graph.

var data = {
  datasets: [
    {
      label: "Bug Report",
      data: [
        { x: 0, y: 1 },
        { x: 1, y: 2 },
        { x: 2, y: 4 }
      ]
    }
  ]
};

const ctx = document.getElementById("myChart");
new Chart(ctx, {
  type: "line",
  data: data
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


<div>
  <canvas id="myChart"></canvas>
</div>

Whys is Old Iteration of Index.html Loading Over New?

Every time I try to redeploy to my site and make changes to my index.html it shows the new version for a split second and then loads the old version. Here is a list of things I have done to fix it but to no avail:

cleared the browser cache

done all if the service worker stuff (restarting service workers or preventing them from working on index.html)

made sure to have no caching in my server.js

I don’t use a CDN

I don’t have any volumes on my droplet

implemented nginx specifically to have it prevent caching

deleted all old docker images on my droplet to give it a pure restart

Any point in the right direction would be greatly appreciated!

Draw a polygon around the City and also hide the rest of the Map

I have an example of code where i tried to draw a Polygon around the Tajikistan, Dushanbe. Polygon drawing as expected but the rest of the map not hiding. In the other words i want to hide rest of the world in the map and show only Tajikistan, Dushanbe. Here is jsfiddle:

google.maps.event.addDomListener(window, 'load', initMap);
      var map;

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: {
            lat: 38.5894432,
            lng: 68.6576614
          },
          disableDefaultUI: true,
          mapTypeId: 'terrain'
        });

        // Define the LatLng coordinates for the polygon around Dushanbe
        var dushanbeCoords = [
        ];

        // Define a large outer polygon to cover the rest of the world
        var worldCoords = [{
            lat: -85,
            lng: -180
          },
          {
            lat: 85,
            lng: -180
          },
          {
            lat: 85,
            lng: 180
          },
          {
            lat: -85,
            lng: 180
          },
          {
            lat: -85,
            lng: -180
          }
        ];



        // Create the Dushanbe polygon itself
        var dushanbePolygon = new google.maps.Polygon({
          paths: dushanbeCoords,
          strokeColor: "#FF0000",
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: "#FF0000",
          fillOpacity: 0.35
        });

        dushanbePolygon.setMap(map);
      }

Argument of type ‘”bind”‘ is not assignable to parameter of type ‘keyof SinonStub’

I am trying to test that a function I’ve binded is stubbed, but when I expect(myStub).toHaveBeenCalled(); I get this error message:

Error: <toHaveBeenCalled> : Expected a spy, but got Function.
Usage: expect(<spyObj>).toHaveBeenCalled()

I found this Sinon GitHub issue trying to achieve the same thing. It includes an answer that used to work:

export default class A {
  makeRequest() {
    return new Promise(this._resolve.bind(this));
  }
  _resolve(resolve, reject) {
    // ...
  }
}
// ...
test('A#makeRequest', sinon.test(function (t) {
    var promiseConstructorStub = this.stub(window, 'Promise');
    var a = new A();

    sinon.stub(a._resolve, 'bind', () => a._resolve); // ERROR: no longer exists

    a.makeRequest();

    t.ok(promiseConstructorStub.firstCall.calledWith(a._resolve), 'cb passed'); // should work

    t.end();
}));

As the comment says, this sinon.stub(a._resolve, 'bind', () => a._resolve); function signature no longer exists.


Here’s my code which fails to compile for that reason:

  beforeEach(() => {
    myStub = sinon.stub(printError, 'bind').returns(myStub);
  });

The 'bind' has a compile time error that says:

Argument of type '"bind"' is not assignable to parameter of type 'keyof SinonStub<any[], any>'.

Here’s an excerpt of my production code:

export const addToDocument = (
  d: Document,
  printOnErrorOptions?: PrettyStringOptions
): void => {
  d.toPrettyString = toPrettyString;

  if (printOnErrorOptions !== undefined) {
    d.printError = printError.bind(d, printOnErrorOptions);
  } else {
    d.printError = () => {}; /* noop */
  }
};

// ...

export function printError(
  this: Document,
  printOnErrorOptions: PrettyStringOptions
): void {
  logger.error(this.toPrettyString(printOnErrorOptions));
}

Here’s my question: how do you rewrite the example to work in modern Sinon code?

Unexpected Error with invoking getChildIndex in Google Docs AppScript on Body (Parent Element Type: BODY_SECTION)

I’m working on a Google Apps Script to replace placeholders in a Google Docs template.

Unexpected error while getting the method or property getChildIndex on object DocumentApp.Body.

Here is the relevant code section:

const elementType = element.getType();
/** @type {GoogleAppsScript.Document.Text} */
let textElement;

if (elementType === DocumentApp.ElementType.PARAGRAPH ||
    elementType === DocumentApp.ElementType.TABLE_CELL ||
    elementType === DocumentApp.ElementType.LIST_ITEM ||
    elementType === DocumentApp.ElementType.TEXT) {
    textElement = element.editAsText();
}

if (textElement) {

    const parent1 = textElement.getParent();
    const parentType = parent1.getType();

    try {
        let index = parent1.getChildIndex(textElement);
            
        //further code below, but crashing at getChildindex in the line above…

    } catch (error) {
        console.error(`Error processing placeholder: ${error.message}`);
        throw error;
    }
}

My Understanding:

Any help would be appreciated!

Split text into lines without using line-clamp

I am generating multiple words from a JSON file and want to display only two lines at once, currently I am using line clamps but it truncates the last word of the second line. If the word is being truncated I want it to move to the next line. Is it possible to implement this?

                 <div className="box">
                    <p className="word">
                        {wordList.map((word, wordIndex) => {
                            const currWord = typedHistory[wordIndex] || "";
                            const isCurrentWord = wordIndex === typedHistory.length;
                            const hasWrongChars = currWord.split("").some((char, index) => char !== word[index]);
                            const isExcessLength = currWord.length > word.length;
                            const isIncomplete = currWord.length >= 0 && currWord.length < word.length && typedHistory.includes(currWord);
                            const shouldHighlightWordRed = hasWrongChars || isExcessLength || isIncomplete;
                            return (
                                <span key={wordIndex} ref={isCurrentWord ? currentWordRef : null}>
                                    {word.split("").map((char, charIndex) => {
                                        let charColor = "#fff";

                                        if (wordIndex < typedHistory.length) {
                                            charColor = shouldHighlightWordRed ? "red" : "var(--main-color)";
                                        } else if (isCurrentWord) {
                                            const typedChar = typedChars[charIndex] || "";
                                            charColor = typedChar === char ? "var(--main-color)" : typedChar !== "" ? "red" : "#fff";
                                        }
                                        return (
                                            <span key={charIndex} style={{ color: charColor }}>{char}</span>
                                        );
                                    })}
                                    {' '}
                                </span>
                            );
                        })}
                    </p>
                </div>

CSS:

.box {
  padding-left: 1.5rem;
  padding-right: 1.5rem;
  background-color: var(--sub-alt-color);
  border-radius: 10px;
  max-height: 8.5em;  
  height: 8.5em;
  user-select: none;

}
.box .word {
  display: block;
  font-size: 1.5rem;
  overflow-y: hidden;
  line-height: 1.8em;
  display: -webkit-box;
  -webkit-line-clamp: 2;
          line-clamp: 2; 
  -webkit-box-orient: vertical;
}

How I am generating text

 useEffect(() => {
        import("../../public/english.json").then((words) =>
            dispatch(setWordList(words.default))
        );
    }, [dispatch]);

I am expecting the behavior of text like in this case: typetest.io

How to Connect this Scrolling Feature & removing that gap?

Newbie here!

Easy Question for those with experienced eyes!

Okay, first the code (Pt 1 HTML, Pt 2 CSS, & Pt 3 JavaScript) and then my question (pt 4) at the end!

Pt 1 HTML code is:

    <!doctype html>
    <html>
    <head>
    <title>Why ain't it connecting? There's a gap. 1 should go after 5 and be a continuous loop. </title>
    <link rel="stylesheet" href="style.css">
    </head>
    <body>
    
    
    <div class="container">
    <div class="column"> <!-- Column 1 -->
    
    <img src="https://img.freepik.com/free-vector/shiny-golden-number-one-star-label-design_1017-27875.jpg?size=338&ext=jpg&ga=GA1.1.2008272138.1725667200&semt=ais_hybrid" width="50" height="50" alt="Column 1 Line 1" />  
                
    <img src="https://img.freepik.com/premium-photo/usa-flag-style-metallic-2-number-balloon-realistic-3d-white-background-generative-ai_69037-2774.jpg?w=900" width="50" height="50" alt="Column 1 Line 2" />              
     
    <img src="https://img.freepik.com/free-psd/pink-number-3-is-pink-background_220664-5637.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 1 Line 3" />              
     
    <img src="https://img.freepik.com/premium-photo/3d-blue-number-4-isolated-white-background_776894-170076.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 1 Line 4" />              
    
    <img src="https://img.freepik.com/premium-photo/hand-drawn-number-five-with-scribbles_1060494-68002.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 1 Line 5" />              
    </div>
    <div class="column"> <!-- Column 2 -->
    
    <img src="https://img.freepik.com/free-vector/shiny-golden-number-one-star-label-design_1017-27875.jpg?size=338&ext=jpg&ga=GA1.1.2008272138.1725667200&semt=ais_hybrid" width="50" height="50" alt="Column 2 Line 1" />              
    
    <img src="https://img.freepik.com/premium-photo/usa-flag-style-metallic-2-number-balloon-realistic-3d-white-background-generative-ai_69037-2774.jpg?w=900" width="50" height="50" alt="Column 2 Line 2" />              
    
    <img src="https://img.freepik.com/free-psd/pink-number-3-is-pink-background_220664-5637.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 2 Line 3" />              
    
    <img src="https://img.freepik.com/premium-photo/3d-blue-number-4-isolated-white-background_776894-170076.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 2 Line 4" />              
    
    <img src="https://img.freepik.com/premium-photo/hand-drawn-number-five-with-scribbles_1060494-68002.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 2 Line 5" />  
    </div>
    <div class="column"> <!-- Column 3 -->
    
    <img src="https://img.freepik.com/free-vector/shiny-golden-number-one-star-label-design_1017-27875.jpg?size=338&ext=jpg&ga=GA1.1.2008272138.1725667200&semt=ais_hybrid" width="50" height="50" alt="Column 3 Line 1" />  
                
    <img src="https://img.freepik.com/premium-photo/usa-flag-style-metallic-2-number-balloon-realistic-3d-white-background-generative-ai_69037-2774.jpg?w=900" width="50" height="50" alt="Column 3 Line 2" />  
                
    <img src="https://img.freepik.com/free-psd/pink-number-3-is-pink-background_220664-5637.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 3 Line 3" /> 
    
    <img src="https://img.freepik.com/premium-photo/3d-blue-number-4-isolated-white-background_776894-170076.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 3 Line 4" /> 
    
    <img src="https://img.freepik.com/premium-photo/hand-drawn-number-five-with-scribbles_1060494-68002.jpg?ga=GA1.1.842708263.1725738367&semt=ais_hybrid" width="50" height="50" alt="Column 3 Line 5" />  
    
    </div>
    </div>
    
    
    <script src="script.js">
    </script>
    </body>
    </html>

Pt 2 The CSS Code is:

    .container {
    display: flex;
    justify-content: space-around;
    overflow: hidden;
    height: 500px;
    /* Adjust as needed */ }
    
    .column {
    display: flex;
    flex-direction: column;
    animation: scroll 10s linear infinite; }
    
    .column img {
    width: 100px;
    /* Adjust as needed */
    height: 100px;
    /* Adjust as needed */ }
    
    @keyframes scroll {
    0% { transform: translateY(0);   }
    
    100% {transform: translateY(-500px);
    /* Adjust based on image height */  }
    }

Pt 3 The JavaScript is:

const columns = document.querySelectorAll('.column');  columns.forEach(column => { column.addEventListener('animationiteration', () => { const firstImage = column.querySelector('img:first-child'); column.appendChild(firstImage); }); });

Pt 4:> The question:

I want these images to appear in the background of a website. 3 columns of 1-2-3-4-5 appearing vertically. Did that.

I am trying to have it scroll like a wheel. It’s scrolling.

My Problem:

The “Number 1,” should appear, IMMEDIATELY after “the Number 5” there should not be a gap. (if you run the code/run the code snipbit you should see it) It should be continuous, like a wheel. I feel like I’m in too deep at the moment and I’m missing something really easy.

My question is how do I get “the 1,” right after “the 5,” (but continually looping into 2-3-4-5-1-2-3-4-5-1-2-3-4-5-1 &) to continue the loop endlessly with no gap.

I tried fiddling with the CSS and HTML but i’m not TOO experienced with JavaScript enough to comfortably toy with it. Is this more of a JavaScript thing?

Closing Note 1:> (this question was uncorrectly edited in the staging ground and messed up how its being asked by e t h a n. i have resetted the question back to its normalcy. The person who edited the first time did not do a good job and are not helping; just conducting powermoves. leave my question alone; I am already telling you “You are not helping. You are asking me to provide a gif of my code running (that’s weird) and not even asking what I want it to do. run my code (thats why its weird; you could just run the code rather than ask someone to show you a gif of their code) and you’ll see the problem instantly.” The 1 doesnt loop after the 5, there’s a gap after the 5. the problem is:> “how to get the 1 to come immediately after the 5”)

Closing Note 2: -Don’t Edit my question. I’m the one asking it; i know what im asking. the one who edited it edited it wrong and didnt get my question correct.

-Thanks

Firebase onsnapshot cost to obtain 3 documents among 1000+ documents? [duplicate]

I want to order by rating among all of the 1000+ users in my snapshot listener, and take the highest 3 of the results. I don’t know if it will be a plus to use limit() here. The docs are not clear enough to understand the costs. My code to fetch is:

const unsubscribe = onSnapshot(query(collection(db, "users"), where("city", "==", user.city), orderBy("rating", "desc")) ), 
(snapshot) => {....}

In this situation, how many read/write operations will I be charged for? Will it be 1000 or 3? Also, the second question is, what is the most cost-effective way to do this? If I need to obtain best 3 rating users, should I exactly have to make read operations for all 1000 documents and get charged for 1000 reads? I am trying to find a clear answer to this.

Discord ChatGPT Bot

I’ve made bot for my discord server and tried to make it use ChatGPT. After sending message on chat it only types error and in terminal it says error no.429

const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
const OPENAI_API_KEY = 'My code';
const DISCORD_BOT_TOKEN = 'My code';

const MIN_DELAY_BETWEEN_REQUESTS = 10000; // adjust this based on your rate limits

let lastRequestTime = 0;

const waitForRateLimit = () => {
    const now = Date.now();
    const delay = Math.max(0, MIN_DELAY_BETWEEN_REQUESTS - (now - lastRequestTime));
    return new Promise(resolve => setTimeout(resolve, delay));
};

client.on('messageCreate', async (message) => {
    if (message.author.bot) return;

    await waitForRateLimit(); // wait for appropriate delay
    lastRequestTime = Date.now();

    try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: 'gpt-3.5-turbo',
            messages: [{ role: 'user', content: message.content }]
        }, {
            headers: {
                'Authorization': `Bearer ${OPENAI_API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        const botReply = response.data.choices[0].message.content;
        message.reply(botReply);
    } catch (error) {
        if (error.response?.status === 429) {
            message.reply('I am receiving too many requests, please try again later.');
        } else {
            message.reply('An error occurred. Please try again.');
        }
        console.error('Error with OpenAI API:', error);
    }
});

client.login(DISCORD_BOT_TOKEN);

I tried to add delay for 3, 5 and even 10 seconds

Order icon overlapped with head text

I used to handle my table with dataTables and bootstrap 5. Everything is fine but the the order icon is overlapped with head text. How can I resolve this?

I tried to customize with the help of css but unable to handle that!

Jerky SVG Movement

I was working on an application to track movement in an SVG viewbox relative to the size of the SVG element itself. The sample code below has been reduced to remove any extra functions, variables, calculations, etc. as much as possible to demonstrate just the problem.

When moving the mouse cursor across the SVG, the green pointer tracker shits its x & y positions by 10px each when moving through the approximate zones marked by the red bands. Also moving left to right vs. right to left has slightly different trigger points.

const pointerMove = event => {
    // console.log(event.offsetX);
    const id = 'pointer';

    const pointerOld = document.getElementById(id);
    if (pointerOld) pointerOld.remove();

    const x = event.offsetX;
    const y = event.offsetY;

    const pointerNew = document.createElementNS(svg.namespaceURI, 'circle');
    pointerNew.setAttributeNS(null, 'id', id);
    pointerNew.setAttributeNS(null, 'cx', x * 0.25);
    pointerNew.setAttributeNS(null, 'cy', y * 0.5);
    pointerNew.setAttributeNS(null, 'r', '15px');
    pointerNew.setAttributeNS(null, 'stroke', 'green');
    pointerNew.setAttributeNS(null, 'stroke-width', '5px');
    pointerNew.setAttributeNS(null, 'fill', 'none');
    svg.append(pointerNew);
}
const svg = document.getElementById('svg1');
svg.addEventListener('pointermove', pointerMove);
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="400" height="200" style="border: 2pt solid;">
    <line x1="0" y1="0" x2="100px" y2="100" stroke="blue" />
    <line x1="100" y1="0" x2="0" y2="100" stroke="blue" />
    <rect x="14" y="0" width="1" height="100" fill="red"></rect>
    <rect x="16" y="0" width="1" height="100" fill="red"></rect>
    <rect x="18" y="0" width="1" height="100" fill="red"></rect>
    <rect x="20" y="0" width="1" height="100" fill="red"></rect>
    <rect x="22" y="0" width="12" height="100" fill="red"></rect>
    <rect x="75" y="0" width="1" height="100" fill="red"></rect>
    <rect x="77" y="0" width="12" height="100" fill="red"></rect>
</svg>

I found some “work-arounds” including:

  1. If I uncomment the console.log(event.offsetX); line, it performs fine.
  2. If I move the x & y constant declarations before the if (pointerOld) pointerOld.remove(); line, it also works fine.

However, I am trying to understand why it is behaving like this in the first place? Am I doing something wrong? Or is this a bug (in HTML/JavaScript/SVG/web browser/OS)?