Button for enable or disable zoom and pan utils using chartjs, react-chartjs-2 and chartjs-plugin-zoom

Im trying to create a button for enable or disable zoom and pan options in my chart.

Part of my code

import { useRef, useState } from "react"
import { Line } from "react-chartjs-2"
import "chartjs-adapter-date-fns"
import zoom from "chartjs-plugin-zoom"
import { DataPicker } from "./index.js"
import { Alert, Button } from "react-bootstrap"
import { useApiSlice } from "../../../hooks/useApiSlice.js"
import { useTranslation } from "react-i18next"

import {
  Chart as ChartJS,
  LineElement,
  TimeScale,
  LinearScale,
  PointElement,
  Tooltip,
  Title,
  Legend,
} from "chart.js"

ChartJS.register(
  LineElement,
  PointElement,
  TimeScale,
  LinearScale,
  Tooltip,
  Title,
  Legend,
  zoom
)

export const Graph = () => {
  const [dataset, setDataset] = useState("1")
  
  
  // For zoom and pan utils
  const [utils, setUtils] = useState(false)
  const chartRef = useRef(null)
  
  
  
  const { logs, activeStation } = useApiSlice()
  const { name } = activeStation
  const { t } = useTranslation();

  if (logs.length === 0) {
    return (
      <Alert variant="secondary w-75 text-center" className="mt-2">
        {t("Station.logsError")}
      </Alert>
    )
  }

  const start_date = logs[logs.length - 1].created
  const end_date = logs[0].created
  const labels = logs.map((d) => d.created)

  const dataGraph = (value) => {
    setDataset(value)
  }

  let values = logs.map((d) => d.stage)
  let label = "Stage"

  switch (dataset) {
    case "1":
      if (name === "CANADA"){
        values = logs.map((d) => d.stage_dl)
      }else{
        values = logs.map((d) => d.stage)
      }
      label = "Stage"
      break

    case "2":
      values = logs.map((d) => d.voltage)
      label = "Voltage"
      break

    case "3":
      values = logs.map((d) => d.disk_usage)
      label = "Disk Usage"
      break

    case "4":
      values = logs.map((d) => d.discharge)
      label = "Discharge"
      break
  }

  const data = {
    labels,
    datasets: [
      {
        label,
        data: values,
        borderColor: "rgb(255, 99, 132)",
        backgroundColor: "rgba(255, 99, 132, 0.5)",
        borderWidth: "2",
        pointRadius: 5,
        z: 1,
      },
    ],
  }

  const options = {
    maintainAspectRatio: false,
    
    plugins: {
      zoom: {
        pan: {
          enabled: utils,
          mode: "xy",
        },
        zoom: {
          drag: {
            enabled: utils,
            modifierKey: "ctrl",
          },
          mode: "xy",
          wheel: {
            enabled: utils,
          },
          pinch: {
            enabled: utils,
          },
          limits: {
            x: {
              min: "original",
              max: "original",
            },
            y: {
              min: "original",
              max: "original",
            },
          },
        },
      },
    },

    scales: {
      x: {
        offset: true,
        type: "time",
        min: start_date,
        max: end_date,
        border: {
          width: 2,
          color: "black",
        },
        ticks: {
          maxTicksLimit: 5,
        },
      },
      y: {
        // min: 0,
        // max: 1,
        border: {
          width: 2,
          color: "black",
          z: 0,
        },
        ticks: {
          stepSize: 0.5,
        },
      },
    },
  }



  const handleResetZoom = () => {
    console.log(chartRef)
    if (chartRef && chartRef.current) {
      chartRef.current.resetZoom()
    }
  }

  const handleZoomUtils = (event) => {
    setUtils(!utils)
    chartRef.current.update()
  }

  return (
    <div className="graph-container">
      <h5 className="align-self-center graph-title"> {t("Station.graph")} </h5>
      <DataPicker dataGraph={dataGraph}></DataPicker>
      <div className="graph">
        <Line data={data} options={options} ref={chartRef}>
        </Line>
      </div>
      <div className="d-flex justify-content-center">
        <Button
          onClick={handleResetZoom}
          className="align-self-center resize-button me-3"
          size="sm"
          variant="dark"
        >
          Reset Zoom
        </Button>
        <Button 
        onClick={handleZoomUtils}
        size="sm"
        variant={utils ? "success" : "dark"}
        >
          Zoom
        </Button>
      </div>
    </div>
  )
}

and the page looks like this
enter image description here

The main problem here is when click the button (called zoom), zoom options works but pan don’t work in desktop view.

In the cell phone view this is worse, because nothing works, and basically I am creating this button to solve the conflicts with the scroll bar that is seen on the right of the graph.

Reset Zoom button works so fine!

Anyway, I hope someone from this community can help me.
And so sorry for my english! I’m studying for improve this

Adding a new Input field to a Thymeleaf form using J-Query

I’m trying to create an application in Spring in which the User designs a quiz. They create a quiz by submitting questions using a Thymeleaf form. ‘Question’ is a class with a few different attributes, but for simplicity I am just focusing on the adding the question itself i.e. a String called ‘quesitionPrompt’. Once the form is submitted each question should save in the next available index of questionList (an ArrayListtype attribute in the Quiz class) .

The number of questions added to the form is up to the User. Therefore, I’ve created a J query method where a new question can be generated by the user. When the ‘clone and append’ button is clicked, a new textbox is generated for the next question and the label and id are updated to be unique. This method works by cloning and appending a question template to an empty div.

The issue I’m facing is that I can’t successfully update th:field. Updating this field would allow me to save each question separately in the next available index in questionList. Instead, on form submission, the text in each individual text box is concatenated and saved as a single Question in the same index. E.g. Do you like long movies?,Do you like horror?

I assume my issue is related to J-Query being unable to properly work with Thymeleaf attributes, but I can’t figure out how to fix it. Any help would be much appreciated!

HTML:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Create Quiz</title>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function () {
            var questionCounter = 1;
            var originalExpression = "*{quiz.quizQuestion[0].prompt}";

            // When the document is ready, execute the following code
            $("#cloneButton").click(function () {
                // When the button with id "cloneButton" is clicked, execute the following code
                var originalDiv = $("#questionContainer");
                // .clone() clones the contents of #cloneContainer instead of the container itself.
                var clonedDiv = $("#cloneContainer").clone();
                var newId = "cloneContainer" + questionCounter;
                // var newLabel ="Question: " + questionCounter;
                clonedDiv.attr("id", newId);

                var newLabel = "Question: " + (questionCounter + 1);
                clonedDiv.find("label").text(newLabel);
                // clonedDiv.find("input").attr("th:field", "*{quiz.quizQuestion[" + questionCounter + "].prompt}");

                var targetElement = clonedDiv.find(":contains('" + originalExpression + "')");
                var newExpression = "*{quiz.quizQuestion[" + questionCounter + "].prompt}";
                alert(newExpression);
                clonedDiv.html(clonedDiv.html().replace(originalExpression, newExpression));
                clonedDiv.find("input").val("*{quiz.quizQuestion[" + questionCounter + "].prompt}");

                originalDiv.append(clonedDiv);
                questionCounter++;
            });
        });
    </script>
</head>

<body>
<form th:action="@{/api/v1/quiz/registerQuiz}" method="post">

    <div id="cloneContainer">
        <label> Question: 1 </label> <input type="text" th:field="*{quiz.quizQuestion[0].prompt}" />
    </div>
    <div id="questionContainer"></div>

    <div>
        <button type="button" id="cloneButton">Clone and Append</button>
    </div>
    <div>
        <input type="submit" value="Submit">
    </div>
</form>
</body>
</html>

How to export Multiple ag grids to single excel with each ag grid data as a different worksheet in excel in angularJS

I have to export 2 ag grids into a single excel sheet. with each ag grid data corresponding to a worksheet in excel

I tried this way but getsheetdataforexcel is not available in angularjs or i have to install something for that? I have 2 ag grids in 1 screen. USAOptions and IndiaOptions. I am using old angularJS. It seems i don’t have getSheetDataForExcel in angularJS ag grid. I get error getSheetDataForExcel is not a function. is there a way?

 vm.exportData = function (exportType) {
    

    var spreadsheets = [
      vm.USAOptions.api.getSheetDataForExcel({
        sheetName: "USA",
      }),
      vm.IndiaOptions.api.getSheetDataForExcel({
        sheetName: "INDIA",
      })
    ];

    vm.USAOptions.api.exportMultipleSheetsAsExcel({
      data: spreadsheets,
      fileName: 'Countries.xlsx'
    });
  }

Is it possible build a project, Admin with C# Visuial studio & and client side with JavaScript VSC

Certainly, let’s refine your message:


Hello everyone,

I’m embarking on a project and planning to build it from the ground up, utilizing two primary coding languages: C# and JavaScript.

In this architecture, the C# component will serve as the Admin side, running independently in Visual Studio. This aspect will specifically operate on desktop platforms.

On the other hand, the client side, developed with JavaScript, will run in a separate environment using Visual Studio Code. This part is intended to function as a website.

My main concern lies in data interaction. When data is submitted through the website, I want the Admin side to promptly reflect these changes. Additionally, I aim to enable the Admin side to interact further by updating or deleting the submitted data.

Both C# and JavaScript will interact with a common database hosted online, ensuring synchronization between the two components.

Do you think this approach is feasible?


Feel free to adjust the message according to your specific needs!
#C# #JavaScript

I am still thinking how the database will be sent to the client side when any change happend

React Native Reanimated 3, cancel/stop scrolling of ScrollView on button press

Basically I am trying to build a scrollable view in which i have a draggable container. When i drag the container to the bottom or top of the page i want the scroll view to start scrolling down or up. When i stop dragging or drag away from the boundary, then the scroll animation should stop.

I have tried to create a simplified version of this, via using two buttons one to start autoscrolling and one to stop it. The auto scrolling start, but i can’t cancel the animation. Moreover if i place an if statement in the animation, and make it false, the scrollView auto scrolls to the end imediatly. My guess is cancelAnimation stops the animation of scrolling but doesnt cause the scrollTo to stop.

I am new to react native and reanimated, but come from web development, where i have accomplished this before in a event calendar app.

Any help would be appreciated 🙂

import React from 'react';
import { Button, StyleSheet, View } from 'react-native';
import Animated, { scrollTo, useSharedValue, useAnimatedScrollHandler, cancelAnimation, useAnimatedReaction, useAnimatedRef } from 'react-native-reanimated';

const AnimatedScrollView = () => {
    const scrollY = useSharedValue(0);
    const scrollRef = useAnimatedRef();

    const scrollHandler = useAnimatedScrollHandler({
        onScroll: ({ contentOffset: { y } }) => {
          scrollY.value = y;
        },
      });

    const startScroll = () => {
        scrollY.value += 50;
        scrollTo(scrollRef, 0, scrollY.value, false);
    };

    const stopScroll = () => {
        cancelAnimation(scrollY);
    };

    useAnimatedReaction(
        () => scrollY.value,
        (scrollPosition) => {
            console.log(scrollPosition);
            scrollTo(scrollRef, 0, 1000, true);
        }
    );

    return (
        <>
            <Button title="Start Scrolling" onPress={startScroll} />
            <Button title="Stop Scrolling" onPress={stopScroll} />
            <Animated.ScrollView
                onScroll={scrollHandler}
                scrollEventThrottle={16}
                ref={scrollRef}
            >
                <View style={[styles.container, { backgroundColor: 'pink', }]}>

                </View>
                <View style={[styles.container, { backgroundColor: 'blue', }]}>

                </View>
                <View style={[styles.container, { backgroundColor: 'red', }]}>

                </View>
                <View style={[styles.container, { backgroundColor: 'pink', }]}>

                </View>
                <View style={[styles.container, { backgroundColor: 'blue', }]}>

                </View>
                <View style={[styles.container, { backgroundColor: 'red', }]}>

                </View>
            </Animated.ScrollView>
        </>
    );
};

export default AnimatedScrollView;


const styles = StyleSheet.create({
    container: {
        height: 300,
        width: '100%',
        backgroundColor: 'pink',
    }
})

How to use gifencoder and return dataurl?

Here is the sample from gifencoder:

    const GIFEncoder = require('gifencoder');
    const { createCanvas } = require('canvas');

    const encoder = new GIFEncoder(320, 240);
    encoder.start();
    encoder.setRepeat(0);   // 0 for repeat, -1 for no-repeat
    encoder.setDelay(500);  // frame delay in ms
    encoder.setQuality(10); // image quality. 10 is default.

    // use node-canvas
    const canvas = createCanvas(320, 240);
    const ctx = canvas.getContext('2d');

    // red rectangle
    ctx.fillStyle = '#ff0000';
    ctx.fillRect(0, 0, 320, 240);
    encoder.addFrame(ctx);

    // green rectangle
    ctx.fillStyle = '#00ff00';
    ctx.fillRect(0, 0, 320, 240);
    encoder.addFrame(ctx);

    // blue rectangle
    ctx.fillStyle = '#0000ff';
    ctx.fillRect(0, 0, 320, 240);
    encoder.addFrame(ctx);
    encoder.finish();

I am then doing:

const gifDataURL = 'data:image/gif;base64,' + encoder.out.getData('base64');
context.res = {
        body: gifDataURL
    };

I can’t get the gifDataURL to be a valid base64 string.

When I inspect gifDataURL, this is the output. What am I doing wrong? And is this the best route to go down when I could have 30 second animations?

“data:image/gif;base64,GIF89a@u0001�u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000!!!”””###$$$%%%&&&”'((()))+++,,,—…///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\]]]^^^___aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������!�u000bNETSCAPE2.0u0003u0001u0000u0000u0000!�u0004u00002u0000u0000u0000,u0000u0000u0000u0000@u0001�u0000u0000b�u0000!bu001cH����bu0013*\Ȱ�Çu0010#J�H��ŋu00183j�ȱ�Ǐ C�u001cI��ɓ(S�\ɲ�˗0cʜI��͛8s��ɳ�ϟ@�nu001dJ��ѣH�*]ʴ�ӧP�J�J��իX�j�ʵ�ׯ`Êu001dK��ٳhӪ]˶�۷p�ʝK��ݻx���˷�߿�u0003u000bu001eL���Èu0013+^̸��ǐ#K�L���˘3k�̹��ϠC�u001eM���ӨS�^ͺ��װc˞M���۸s��ͻ�����u000bu001fN����ȓ+_μ���УK�N����سk�ν�����ϋu001fO�����ӫ_Ͼ�����˟O��������Ͽ���u0000u0006(��u0004u0016h��b&���f6���u0010F(�u0014Vh�u0018f��u001cv�� �(�$�h�(���,���0�(�4�h�8��<���@u0006)�Du0016i�H&��L6��PF)�TVi�Xf��\v��`�)�d�i�h���l���p�)�t�i�x��|��矀u0006*蠄u0016j衤u0005u0004u0000!�u0004u00002u0000u0000u0000,u0000u0000u0000u0000@u0001�u0000�u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000!!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������b�u0000u0019bu001cH����bu0013Ȱ�Çu0010#J�H��ŋu00183j�ȱ�Ǐ C�u001cI��ɓ(S�ɲ�˗0cʜI��͛8s��ɳ�ϟ@�nu001dJ��ѣH�*]ʴ�ӧP�J�J��իX�j�ʵ�ׯÊu001dK��ٳhӪ]˶�۷p�ʝK��ݻx���˷�߿�u0003u000bu001eL���Èu0013+^̸��ǐ#K�L���˘3k�̹��ϠC�u001eM���ӨS�^ͺ��װc˞M���۸s��ͻ�����u000bu001fN����ȓ+_μ���УK�N����سk�ν�����ϋu001fO�����ӫ_Ͼ�����˟O��������Ͽ���u0000u0006(��u0004u0016h��b&���f6���u0010F(�u0014Vh�u0018f��u001cv�� �(�$�h�(���,���0�(�4�h�8��<���@u0006)�Du0016i�H&��L6��PF)�TVi�Xf��\v���)�d�i�h���l���p�)�t�i�x��|��矀u0006蠄u0016j衤u0005u0004u0000!�u0004u00002u0000u0000u0000,u0000u0000u0000u0000@u0001�u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�u0000u0000�!!!”””###$$$%%%&&&”'((()))+++,,,—…///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\]]]^^^___“`aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������b�u0000!bu001cH����bu0013*Ȱ�Çu0010#J�H��ŋu00183j�ȱ�Ǐ C�u001cI��ɓ(S�ɲ�˗0cʜI��͛8s��ɳ�ϟ@�nu001dJ��ѣH�*]ʴ�ӧP�J�J��իX�j�ʵ�ׯÊu001dK��ٳhӪ]˶�۷p�ʝK��ݻx���˷�߿�u0003u000bu001eL���Èu0013+^̸��ǐ#K�L���˘3k�̹��ϠC�u001eM���ӨS�^ͺ��װc˞M���۸s��ͻ�����u000bu001fN����ȓ+_μ���УK�N����سk�ν�����ϋu001fO�����ӫ_Ͼ�����˟O��������Ͽ���u0000u0006(��u0004u0016h��b&���f6���u0010F(�u0014Vh�u0018f��u001cv�� �(�$�h�(���,���0�(�4�h�8��<���@u0006)�Du0016i�H&��L6��PF)�TVi�Xf��\v���)�d�i�h���l���p�)�t�i�x��|��矀u0006*蠄u0016j衤u0005u0004u0000;”

Hide Google AdSense error from the browser

I’ve an AdSense error showing in my browser logs. This is badly affect my SEO as below

enter image description here

The ads are shwoing and I’m not blocked by AdSense, this issue from Google part and they don’t fix it ( i don’t know why)

Anyway, my issue is having these error logs are affecting my SEO becuase it shows error in the browser, and I want in some way to hide the errors and not shwoing. I do have a try catch and left the catch open but this doesn’t work.

import React, { useEffect } from 'react';
const AdSense = (props) => {
  const { adSlot } = props;  
  useEffect(() => {
      try {
          (window.adsbygoogle = window.adsbygoogle || []).push({});
      }
      catch (e) {
      }
  },[]);
  return (
      <>
          <ins className="adsbygoogle"
              style={{ display: "block", height: '280px' }}
              data-ad-client="{my_id_here}"
              data-ad-slot={adSlot}
              data-ad-format="auto"
              data-full-width-responsive="true">
      </>
  );
};
export default AdSense;

I want to hide the errors.

dropzone.js can only drag 2 files max

I’m trying to use dropzone.js for uploading images to the browser only (as blob), not to the server.

And it works for dragging 1 or 2 files at a time, but when I drag 3 or more files, only the first 2 are processed.

So in my code the transformFile function is executed only for the first 2 files even though I dragged 3.

this is my code, html:

<div id="picDropZone" style="background: gainsboro;">
    <h2>Drop zone</h2>
</div>

<div id="pictures">
</div>

and the js:

var picsPrev = $('#pictures');
var pics = [];

function updatePics(){
    picsPrev.empty();
    pics.forEach(function (pic) {
        var image = new Image(150);
        image.src = pic;
        picsPrev.append(image);                
    });
}

var myDropzone = new Dropzone("#picDropZone",
{
    url: '...', // not used, error when not set
    maxFiles: 10,
    transformFile: function (file, done) {                    
        var image = new Image();
        var imgurl = URL.createObjectURL(file);
        image.src = imgurl;
        
        pics.push(imgurl);
        updatePics();

        myDropzone.removeAllFiles(true);
    }
});

The game is not restarting when scores are equal

#When score is equal the game doesn’t restart.

In this Rock-Paper-Scissor game everything is working correctly but when the score comes to an equal number game will not restart. I want when the userScore is equal to compScore, the game restarts, in short when game draw, the game doesn’t restart. Here is my code –


const drawGame = () => {
    msg.innerText = "GAME WAS DRAW, PLAY AGAIN."
};

const showWinner = (userWin, userChoice, compChoice) => {
   if(userWin){
    userScore++;
    userScorePara.innerText = userScore;
    // console.log("YOU WIN");
    msg.innerText = `YOU WIN. Your ${userChoice} beats ${compChoice}`;
    // msg.style.backgroundColor = "green";
   } else {
    compScore++;
    compScorePara.innerText = compScore;
    msg.innerText = `YOU LOSE. ${compChoice} beats Your ${userChoice}`;
   }
}

const playGame = (userChoice) => {
    console.log("user choice = ", userChoice);
    // Generate Computer Choice 
    const compChoice = genCompChoice();
    console.log("computer choice = ", compChoice);
    if(userChoice === compChoice){
        // Draw Game
        drawGame();
    } else {
        let userWin = true;
        if(userChoice === "Rock"){
            // scissors, paper
            userWin = compChoice === "Paper" ? false : true;
        } else if(userChoice ==="Paper") {
            // rock, scissors
            userWin = compChoice === "Scissors" ? false : true;
        } else {
            // rock , paper 

            userWin = compChoice === "Rock" ? false : true;
        }
        showWinner(userWin, userChoice, compChoice);
    }
};

Correct way to use DataTable Templates in Flask

I am creating a considerably large Flask application. Many pages will have tables for the visualization of products, suppliers, etc.

I would like to create a table template so that whenever a new page is created, a pre-built and styled standard table is implemented. However, my difficulties lie in adding tables with search bars, “Delete” and “Edit” buttons in rows (if any field is “Pending” or similar)…

What is the correct way to do this with minimal hacks and maximum best practices? I have found several tutorials, but I cannot see any Jinja Template logic for this…

Currently, I am exploring alternatives in DataTable.js, but I have not been able to integrate the customization I desire.

How to alternate case of letters in a string?

I would like to alternate cases along the string for more than one word. Every word should start with capital letter. I’ve got stuck in the process and don’t know how sort it out.

Example: input: “hello world” / output: “HeLlO WoRlD”

function alternateCase(str) {

  if (str.length === 0) {
    return ""
  }
  const arrCapitalised = []

  const splitStr = str.split("")
  const indexSpace = splitStr.indexOf(" ")

  const joinStr = str.split(" ").join("")


  for (let i = 0; i < joinStr.length; i++) {
    if (i % 2 === 0) {
      arrCapitalised.push(joinStr[i].toUpperCase())
    } else {
      arrCapitalised.push(joinStr[i])
    }
  }
  console.log(arrCapitalised, "PREVIOUS ARRAY")
  const finalArr = arrCapitalised.splice(indexSpace, 0, " ")
  console.log(finalArr, "FINAL ARRAY")
  return arrCapitalised.join("").toString()
}

Find Repeat Sequence in an Array

I encountered a problem and have tried many solutions, but none have worked. Given an array of numbers [3, 2, 16, 16, 15, 1, 2, 16, 16, 16, 15, 1, 2], I would like to discover the repeated sequence in this array.

The expected output should be [16, 16, 15, 1, 2].

Best Practice for Managing Todo Item Completion State in React: Local vs. Global State?

I’m working on a React application that involves a todo list, and I’m trying to determine the best approach for managing the completion state of individual todo items. I’ve implemented two different approaches, and I’m curious to hear opinions on which one might be considered better in terms of best practices, maintainability, and scalability.

EXAMPLE ONE:

import './style.css';
import React, { useState, useEffect } from 'react';

const TodoList = () => {
  // Define state to store the list of todos
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    // Function to fetch the list of todos
    const fetchTodos = async () => {
      try {
        // Make a GET request to your API endpoint
        const response = await fetch(
          'https://jsonplaceholder.typicode.com/todos'
        );

        // Check if the request was successful (status code 200)
        if (!response.ok) {
          throw new Error('Failed to fetch todos');
        }

        // Parse the JSON response
        const data = await response.json();

        // Update the state with the list of todos
        setTodos(data);
      } catch (error) {
        console.error('Error fetching todos:', error.message);
      }
    };

    // Call the fetchTodos function when the component mounts
    fetchTodos();
  }, []); // The empty dependency array ensures that this effect runs once after the initial render

  return (
    <div>
      <h1>Todo List</h1>
      <ul>
        {/* Map through the todos and render them */}
        {todos.map((todo) => (
          <TodoItem key={todo.id} todo={todo} />
        ))}
      </ul>
    </div>
  );
};

const TodoItem = ({ todo }) => {
  // State to track the completion status of the todo
  const [completed, setCompleted] = useState(todo.completed);

  // Function to handle the checkbox change
  const handleCheckboxChange = () => {
    setCompleted(!completed);
  };

  return (
    <li style={{ marginBottom: '10px', display: 'flex', alignItems: 'center' }}>
      {/* Checkbox for todo completion */}
      <input
        type="checkbox"
        checked={completed}
        onChange={handleCheckboxChange}
        style={{ marginRight: '8px' }}
      />

      {/* Todo details */}
      <div style={{ textDecoration: completed ? 'line-through' : 'none' }}>
        <strong>{todo.title}</strong>
        <p>{todo.description}</p>
      </div>
    </li>
  );
};

export default TodoList;


EXAMPLE TWO:

import './style.css';
import React, { useState, useEffect } from 'react';

const TodoList = () => {
  // Define state to store the list of todos
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    // Function to fetch the list of todos
    const fetchTodos = async () => {
      try {
        // Make a GET request to your API endpoint
        const response = await fetch(
          'https://jsonplaceholder.typicode.com/todos'
        );

        // Check if the request was successful (status code 200)
        if (!response.ok) {
          throw new Error('Failed to fetch todos');
        }

        // Parse the JSON response
        const data = await response.json();

        // Update the state with the list of todos
        setTodos(data);
      } catch (error) {
        console.error('Error fetching todos:', error.message);
      }
    };

    // Call the fetchTodos function when the component mounts
    fetchTodos();
  }, []); // The empty dependency array ensures that this effect runs once after the initial render

  // Function to handle the checkbox change
  const handleCheckboxChange = (id) => {
    setTodos((todos) =>
      todos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  return (
    <div>
      <h1>Todo List</h1>
      <ul>
        {/* Map through the todos and render them */}
        {todos.map((todo) => (
          <TodoItem
            key={todo.id}
            todo={todo}
            onCheckboxChange={handleCheckboxChange}
          />
        ))}
      </ul>
    </div>
  );
};

const TodoItem = ({ todo, onCheckboxChange }) => {
  return (
    <li style={{ marginBottom: '10px', display: 'flex', alignItems: 'center' }}>
      {/* Checkbox for todo completion */}
      <input
        type="checkbox"
        checked={todo.completed}
        onChange={() => onCheckboxChange(todo.id)}
        style={{ marginRight: '8px' }}
      />

      {/* Todo details */}
      <div style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
        <strong>{todo.title}</strong>
        <p>{todo.description}</p>
      </div>
    </li>
  );
};

export default TodoList;

In Example One, each TodoItem component manages its own completion state using useState. In Example Two, the completion state is centralized in the TodoList component’s state, and a callback function is passed down to update the state.

I’m interested in hearing from the community about the pros and cons of each approach. Are there specific scenarios where one approach is preferred over the other? Any insights into performance, code maintainability, or potential issues with either method would be greatly appreciated.

Which approach do you think aligns better with React best practices, and why? Any real-world experiences or considerations that could help make an informed decision would be valuable.

Thanks in advance for your insights!

Pass command arguments to package.json scripts [duplicate]

I have a MERN app that’s divided into a server and a client folder, as well as a root package.json file:

"scripts": {
    "start": "concurrently "npm run server" "npm run client"",
    "server": "cd server && npm run start",
    "client": "cd client && npm start",
    "install": "cd server && npm install && cd ../client && npm install"
}

Then, inside my server file, I have another package.json with the following scripts:

"scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
},

What I want to do is to pass a IP address as a command argument to my main start script, to then use that IP inside my server’s app.js, like so:

npm start 0.0.0.0 // This is the 'start' in the root package.json file, not the one in my server

How can I archieve this?

The 1st video should turn off after clicking the 2nd video

While the 1st video is playing, click the 2nd video.

It should shut off, it does not.

https://jsfiddle.net/g34zmbuc/

You can see it working in this code: https://jsfiddle.net/m1e3qt2b/

const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

let players = [];
let videoIds = ['6bDmN0z74M8', '6bDmN0z74M8', '6bDmN0z74M8', '6bDmN0z74M8', '6bDmN0z74M8'];

function onPlayerReady(event) {
  player = event.target;
  player.setVolume(100);
}

function onYouTubeIframeAPIReady() {
  for (let i = 0; i < videoIds.length; i++) {
    players[i] = new YT.Player('ytplayer' + i, {
      height: '361',
      host: 'https://www.youtube-nocookie.com',
      width: '642',
      videoId: videoIds[i],
      playerVars: {
        autoplay: 0,
        cc_load_policy: 0,
        controls: 0,
        disablekb: 1,
        fs: 0,
        iv_load_policy: 3,
      },
      events: {
        'onReady': onPlayerReady
      }
    });
  }
}

}