Ler arquivo .TXT e passar como variável – HTML [closed]

Boa tarde pessoal,

Sou extremamente leigo no assunto, mas preciso passar um link que seja dinâmico para um iframe. Eu pesquisei e cheguei a dar uma olhada na fetch api, porém pelo que eu vi ela precisaria de um serviço pra rodar. É isso mesmo? Porque a ideia seria deixar um html em uma pasta no servidor da empresa que acesse um link de acordo com o usuario que executou. (A execução vem de um software interno que executa um script ahk e abre o arquivo.)

É uma gambiarra só para evitar que as pessoas acessem o link (do bi) a reveria, obviamente a segurança é muito falha, mas no mundo real do dia a dia da empresa essa vulnerabilidade seria aceitável no momento, dada as outras alternativas que foram propostas.

Hoje eu gravo o link em um arquivo .txt temporário, eu teria que ler esse arquivo e gravar no src.

Tenho outras preocupações: Eu abri o relatório, atualizei a página, filtrei… Se nesse meio tempo alguém executar o arquivo, vai impactar na minha “aplicação”? Queria algo que não perdesse o relacionamento com esse link até ser fechado.

Preciso dessa luz para saber se estou viajando muito ou se funcionaria. Se puderem me ajudar eu agradeço!

Bootstrap 5 (5.3.2-5.3.3) navbar problem with scroll spy

I got an issue with bootstrap 5 navbar scroll-spy.
Scroll-spy works fine when I remove data attributes.
And also when I try it on codeply I don’t have any problem over there what I don’t understand why.

This is my code:
“`

Test

</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light sticky-top">
        <div class="container">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#test1" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test1</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#test2" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test2</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#test3" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test3</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#test4" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test4</a>
                    </li>
                </ul>
                <form class="d-flex my-2 my-lg-0">
                    <input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                </form>
            </div>
        </div>
    </nav>
    <section style='padding: 450px' class='bg-dark' id='test1'>
        <h1 class="text-white">Test 1</h1>
    </section>
    <section style='padding: 450px' class='bg-white' id='test2'>
        <h1 class="text-dark">Test 2</h1>
    </section>
    <section style='padding: 450px' class='bg-dark' id='test3'>
        <h1 class="text-white">Test 3</h1>
    </section>
    <section style='padding: 450px' class='bg-white' id='test4'>
        <h1 class="text-dark">Test 4</h1>
    </section>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>

“`
Codeply code:
https://www.codeply.com/p/7ONKirE8Z2

Why is TBT on PSI so different from my local machine?

When I test the performance of my SSR SPA on localhost, I get a low TBT (total blocking time)
enter image description here

When I use PSI (pagespeed insights) to test the performance of the site, I get a very high TBT

enter image description here

How can I decrease the TBT on PSI? What might cause the main thread to be blocked only on PSI but not on lighthouse? Is it possible the service worker caches the main bundle and PSI doesn’t use SWs?

Can I work around this somehow?

Error loading preview on images saved to firebase storage

I’m developing a react native app and I am having a hard time reading an image saved to storage in firebase cloud. It says error loading preview and when I click on the link it also opens a missing image url. What am I doing wrong? According to other questions it has to do with the rules. And this was suggested.

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}

Yet, no cigar

I’m also following their suggested method to save the image, or at least it appears I am

const sendToBackend = () => {
  const metadata = {
    contentType: `image/${get_extension(image)}`
  };

  function get_extension(url) {
    let extension = url.toLowerCase().split(".").pop();

    return extension; // png, mp4, jpeg etc.
  }
  const filename = new Date().getTime() + image.substring(image.lastIndexOf("/")+1);

  console.log("image", filename);

  const storageRef = ref(storage, 'profileimages/' + filename);

  const uploadTask = uploadBytesResumable(storageRef, image, metadata );

  uploadTask.on('state_changed', 
    (snapshot) => {
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case 'paused':
          console.log('Upload is paused');
          break;
        case 'running':
          console.log('Upload is running');
          break;
      }
    }, 
    (error) => {
      console.error(error);
    }, 
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log('File available at', downloadURL);
        const userId = auth.currentUser.uid;
        const docRef = doc(db, 'useraccounts', userId);
        updateDoc(docRef, {
          image: downloadURL,
        })
        .then(() => {
          console.log("Document successfully updated!");
          getUser();
        })
        .catch((error) => {
          console.error("Error updating document: ", error);
        });
      });
    }
  );
};

My problem is simple.

I want to be able to select an image from my phone or camera – DONE
I want to save it to firestore cloud storage – DONE (It seems so at least)
I want to be able to pass the URL for the image to the document in firebase collection (DONE)
I want to be able to read the downloadURL when I read {user.image} – (NOT Working)

enter image description here

Unnecessary Rerender Using Memo React

i am trying to understand react memo and i created a simple interface in my react native app. the app consists of two elements:

MainApp.tsx -> controls the list of the user

User.tsx -> displays user object

my plan is to have all user information displayed on first render and each user should have some sort of “update” button which would case it to re-render. The user would be passed to the list item component along with a description. If the description changes, the whole list should be re-rendered. The current implementation looks like this:

mainapp:

// MainApp component
import React, { useState } from 'react';
import { StyleSheet, Button, SafeAreaView, FlatList } from 'react-native';
import User from './User';

export interface IUser {
  name: string;
  id: number;
  age: number;
}

const initialUsers: IUser[] = [
  { id: 1, name: 'Ivan', age: 20 },
  { id: 2, name: 'Elena', age: 25 },
  { id: 3, name: 'John', age: 30 },
];

export const MainApp = () => {
  const [users, setUsers] = useState<IUser[]>(initialUsers);
  const [description, setDescription] = useState<string>(
    'A passionate developer',
  );

  const updateUserAge = (userId: number) => {
    setUsers(
      users.map(user =>
        user.id === userId
          ? { ...user, age: Math.floor(Math.random() * (100 - 20 + 1)) + 20 }
          : user,
      ),
    );
  };

  const updateDescription = () => {
    setDescription(
      (Math.floor(Math.random() * (100 - 20 + 1)) + 20).toString(),
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={users}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => (
          <User
            user={item}
            description={description}
            onUpdateAge={updateUserAge}
          />
        )}
      />
      <Button onPress={updateDescription} title="Update Description" />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default MainApp;

user.tsx

import React, { memo } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { IUser } from './MainApp';

interface UserProps {
  user: IUser;
  description: string;
  onUpdateAge: (userId: number) => void;
}

export const User = memo(
  ({ user, description, onUpdateAge }: UserProps) => {
    console.log('Rendering User', user.name);

    const handleUpdateAge = () => {
      onUpdateAge(user.id);
    };

    return (
      <View style={styles.container}>
        <Text>Name: {user.name}</Text>
        <Text>Age: {user.age}</Text>
        <Text>Description: {description}</Text>
        <Button onPress={handleUpdateAge} title="Update Age" />
      </View>
    );
  },
  (prevProps, nextProps) => {
    return (
      prevProps.user.age === nextProps.user.age &&
      prevProps.description === nextProps.description
    );
  },
);

const styles = StyleSheet.create({
  container: {
    margin: 10,
    padding: 10,
    backgroundColor: '#eee',
  },
});

export default User;

since the object reference stays the same, i specify what props to compare. When i click on the first element i get:

LOG Rendering User Ivan

which is correct and the whole list was not re-rendered, only one item is updated.

however, if i click on another list item after that i get this:

 LOG  Rendering User Ivan
 LOG  Rendering User Elena

For some reason two list items were updated and it keeps going if i click on another users. Can you help me understand why the list items are re-rendered?

Issues Connecting WalletConnect in a React Application

community! I’ve been encountering issues when trying to integrate WalletConnect into my React application. Attempting to connect a wallet via WalletConnect, I face WebSocket connection errors and fail to load resources from bridge.walletconnect.org.

Ensured I’m using the latest version of @walletconnect/web3-provider.
Verified the bridge URL is correctly specified in my code (bridge: ‘https://bridge.walletconnect.org’).
Restarted the development server and cleared the browser cache.


import React, { useState } from 'react';
import Web3Modal from 'web3modal';
import WalletConnectProvider from '@walletconnect/web3-provider';

function WalletConnect() {
  const [account, setAccount] = useState('');

  const providerOptions = {
    walletconnect: {
      package: WalletConnectProvider,
      options: {
        bridge: 'https://bridge.walletconnect.org',
        rpc: {
          1: 'https://mainnet.infura.io/v3/мой_INFURA_API_KEY'
        }
      }
    }
  };

  async function connectWallet() {
    const web3Modal = new Web3Modal({
      network: "mainnet",
      cacheProvider: true,
      providerOptions
    });

    try {
      const connection = await web3Modal.connect();
      // дальнейшие действия
    } catch (error) {
      console.error("Connection to wallet failed:", error);
    }
  }

  return (
    <div>
      <button onClick={connectWallet}>Connect Wallet</button>
      {account && <p>Connected account: {account}</p>}
    </div>
  );
}

export default WalletConnect;

Errors I’m receiving:

WebSocket connection to ‘wss://bridge.walletconnect.org/?env=browser&…’ failed.
Failed to load resource: the server responded with a status of 404 ().
I’ve searched for solutions in the WalletConnect documentation and forums, but haven’t been able to resolve this issue. Any help or guidance on what I might be doing wrong would be greatly appreciated.

S3 bucket redirect object does not redirect, bus instead downloads a file

I am using the @aws-sdk/client-s3 package to use AWS APIs.
I try to upload redirect objects to my bucket using this code:

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
const s3Client = new S3Client({ region: process.env.AWS_REGION });
    const putS3Command = new PutObjectCommand({
        Bucket: process.env.S3_BUCKET,
        Key: hashedUrl,
        WebsiteRedirectLocation: validatedRequestBody.url,
    });
await s3Client.send(putS3Command);

The command indeed succeeds, and I see the object in the bucket when I browse AWS S3 service:
enter image description here

However, when I try to access the object (using presigned URL), I don’t get redirected, but I just get download file of size 0.

Is there anything wrong with my PutObjectCommand?

I configured this S3 bucket using Terraform:

module "urls_s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "4.1.0"

  acl                      = "private"
  force_destroy            = true
  attach_policy            = true
  policy                   = data.aws_iam_policy_document.urls_s3_policy.json
  control_object_ownership = true
  object_ownership         = "BucketOwnerPreferred"

  tags = merge(
    var.common_tags,
    {
      Name  = "${var.project}-Client-URLs-S3-Bucket"
      Stack = "Backend"
    }
  )
}

X axis on scatter plot being generated on highcharts

I am trying to a date-based scatter plot. I mean I want to add dates on the x-axis but it is not adding the dates. In my code, I have added a small portion of the data. The data points is over 500000. What is the most efficient way to do that?

My code:

const series = [{"name":"Page Views","id":"ABC-page_views","data":[["2024-02-26T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",3],["2024-02-29T00:00:00.000Z",1],["2024-02-29T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",7],["2024-03-01T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-03-01T00:00:00.000Z",1],["2024-02-29T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",5],["2024-02-28T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1]]}]

Highcharts.chart('container', {
  chart: {
    type: 'scatter',
    zoomType: 'xy'
  },
  xAxis: {
    type: 'datetime', 
    lineColor: "#000",
    lineWidth: 3,
    labels: {
      style: {
        color: "#000",
      },
    },
  },
  yAxis: {
    gridLineColor: "#283347",
    lineColor: "#fff",
    lineWidth: 3,
    labels: {
      style: {
        color: "#000",
      },
    },
    title: {
      text: "",
    },
    opposite: false,
  },
  legend: {
    enabled: true
  },
  plotOptions: {
    scatter: {
      marker: {
        radius: 2.5,
        symbol: 'circle',
        states: {
          hover: {
            enabled: true,
            lineColor: 'rgb(100,100,100)'
          }
        }
      },
      states: {
        hover: {
          marker: {
            enabled: false
          }
        }
      },
      jitter: {
        x: 0.005
      }
    }
  },
  tooltip: {
    formatter: function () {
      return 'Date: ' + Highcharts.dateFormat('%b %d, %Y', new Date(this.x)) + '<br/>PV: ' + this.y;
    }
  },
  series: series
});
#container {
    max-width: 800px;
    margin: auto;
}

.highcharts-figure,
.highcharts-data-table table {
    min-width: 360px;
    max-width: 800px;
    margin: 1em auto;
}

.highcharts-data-table table {
    font-family: Verdana, sans-serif;
    border-collapse: collapse;
    border: 1px solid #ebebeb;
    margin: 10px auto;
    text-align: center;
    width: 100%;
    max-width: 500px;
}

.highcharts-data-table caption {
    padding: 1em 0;
    font-size: 1.2em;
    color: #555;
}

.highcharts-data-table th {
    font-weight: 600;
    padding: 0.5em;
}

.highcharts-data-table td,
.highcharts-data-table th,
.highcharts-data-table caption {
    padding: 0.5em;
}

.highcharts-data-table thead tr,
.highcharts-data-table tr:nth-child(even) {
    background: #f8f8f8;
}

.highcharts-data-table tr:hover {
    background: #f1f7ff;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
    
</figure>

How do I make the x-axis display the dates? Also for a large dataset. Not sure how to optimize it.

Fiddle link: https://jsfiddle.net/nb_nb_nb/vymdkqzb/1/

Drilldown with Hyperlink support in React Highcharts barcharts

I am following below reference to create a column(bar) chart using React Highcharts with drilldown support.
https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/drilldown/basic/

Example:

    drilldown: {
        series: [{
            id: 'animals',
            data: [
                ['Cats', 4],
                ['Dogs', 2],
                ['Cows', 1],
                ['Sheep', 2],
                ['Pigs', 1]
            ]
        }, {
            id: 'fruits',
            data: [
                ['Apples', 4],
                ['Oranges', 2]
            ]
        }, {
            id: 'cars',
            data: [
                ['Toyota', 4],
                ['Opel', 2],
                ['Volkswagen', 2]
            ]
        }]
    }
`;`

However, I need to call an external URL on clicking Bar Chart or the Text on X-axis. (Customised Hyperlink for each plotted value)
I am open to use any other charting library also which supports the same.

Trie drilldown functionality available in React “Column” chart in highcharts. Also tried chart.js. But didn’t work.

Mongoose aggregatePaginate with population

I am trying to paginate an aggregation query using mongoose-aggregate-paginate
The field bookings is an array of ObjectId’s of collection “bookings”

BookingModel: model("booking", bookingSchema)

The model :

const tourGroupSchema = new Schema({
  product: String,
  date: String,
  time: String,
  bookings: [{ type: Schema.Types.ObjectId, ref: "booking" }], //need to be populated
  task: String,
  task_id: String,
  notes: String,
  notes_list: { type: Array, default: [] }, // -
  guide_id: String,
  guide_uds_id: String,
  guide_confirmation: String,
  guide_details: String,
  guides_asked: Array,
  guide_email_sent: Boolean,
  vehicle_id: String,
  index: {
    type: Number,
    default: 1,
  },
});

tourGroupSchema.plugin(mongoosePaginate);
tourGroupSchema.plugin(mongooseAggregatePaginate);


TourGroupModel: model("tour_group", tourGroupSchema),

My pipeline :

const pipeline = [];

   // Stage 1: Match documents based on product_ids
pipeline.push({
  $match: {
    product: { $in: product_ids },
       },
    });

//WHAT I HAVE TRIED

pipeline.push({
      $lookup: {
        from: "bookings",
        localField: "bookings",
        foreignField: "_id",
        as: "bookings",
      },
    });

const aggregation = await TourGroupModel.aggregate(pipeline);
const data = await TourGroupModel.aggregatePaginate(aggregation, {
  page: page,
  limit: 25,
  sort: { date: 1, time: 1, index: 1 },
        });

result :

    {
        "docs": [
            {
                "_id": "64cc8fa5fe9011604f2dca21",
                "product": "63958eaedaf242d73c7b9719",
                "date": "2022-04-08",
                "time": "15:00",
                "bookings": [
                    "641c46c8e0edc61fec97a830",
                    "641c46c9e0edc61fec97a83a",
                    "641c46c8e0edc61fec97a835"
                ],
                "index": 1,
                "__v": 2,
                "notes_list": []
            },
...rest

As you can see the bookings array of each TourGroup dont come with populated documents but still their ids instead, any ideas why ?

Get all checked boxes from datatable that are in different pages

I am using datatable plug-in to use pagination for my table. The first column of my table has checkboxes with value = some uniqueID.

I cannot seem to get all checkbox values including the ones that are already checked.

When I click on the “get checked records”, it should only display the unique checkbox values.
Any suggestions?



<!doctype html>
<html lang="en">
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
    <script type="text/javascript" language="javascript" src="//cdn.datatables.net/2.0.2/js/dataTables.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.2/css/dataTables.dataTables.min.css">    
  </head>
<body>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>

                <th><input type="checkbox" name='all' id="checkAll"> All</th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="1"></td>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011-04-25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="2"></td>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011-07-25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="3" checked></td>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009-01-12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="4"></td>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012-03-29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="5"></td>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008-11-28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="6"></td>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012-12-02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="7"></td>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012-08-06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="8"></td>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010-10-14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="9"></td>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009-09-15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="10"></td>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008-12-13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="11"></td>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>30</td>
                <td>2008-12-19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="12"></td>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2013-03-03</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="13"></td>
                <td>Charde Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>36</td>
                <td>2008-10-16</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="14"></td>
                <td>Haley Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>43</td>
                <td>2012-12-18</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="15"></td>
                <td>Tatyana Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>19</td>
                <td>2010-03-17</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="16"></td>
                <td>Michael Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>66</td>
                <td>2012-11-27</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="17"></td>
                <td>Paul Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>64</td>
                <td>2010-06-09</td>
                <td>$725,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="18"></td>
                <td>Gloria Little</td>
                <td>Systems Administrator</td>
                <td>New York</td>
                <td>59</td>
                <td>2009-04-10</td>
                <td>$237,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="19"></td>
                <td>Bradley Greer</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>41</td>
                <td>2012-10-13</td>
                <td>$132,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="20"></td>
                <td>Dai Rios</td>
                <td>Personnel Lead</td>
                <td>Edinburgh</td>
                <td>35</td>
                <td>2012-09-26</td>
                <td>$217,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="21"></td>
                <td>Jenette Caldwell</td>
                <td>Development Lead</td>
                <td>New York</td>
                <td>30</td>
                <td>2011-09-03</td>
                <td>$345,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="22"></td>
                <td>Yuri Berry</td>
                <td>Chief Marketing Officer (CMO)</td>
                <td>New York</td>
                <td>40</td>
                <td>2009-06-25</td>
                <td>$675,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="23"></td>
                <td>Caesar Vance</td>
                <td>Pre-Sales Support</td>
                <td>New York</td>
                <td>21</td>
                <td>2011-12-12</td>
                <td>$106,450</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="24" checked></td>
                <td>Doris Wilder</td>
                <td>Sales Assistant</td>
                <td>Sydney</td>
                <td>23</td>
                <td>2010-09-20</td>
                <td>$85,600</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="25"></td>
                <td>Angelica Ramos</td>
                <td>Chief Executive Officer (CEO)</td>
                <td>London</td>
                <td>47</td>
                <td>2009-10-09</td>
                <td>$1,200,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="26"></td>
                <td>Gavin Joyce</td>
                <td>Developer</td>
                <td>Edinburgh</td>
                <td>42</td>
                <td>2010-12-22</td>
                <td>$92,575</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="27"></td>
                <td>Jennifer Chang</td>
                <td>Regional Director</td>
                <td>Singapore</td>
                <td>28</td>
                <td>2010-11-14</td>
                <td>$357,650</td>
            </tr>
        </tbody>
    </table>
    <br/>
    <button id="get-values">get checked records</button>
    <br/>
    <div id="selected">
    </div>

    <script language="javascript" type="text/javascript"> 
        $(document).ready(function(){
            
            var table = new DataTable('#example', {
                responsive: true,
                "lengthMenu": [20, 40, 60, 80, 100],
                "pageLength": 10
            }); 

                             
            $('#example').on( 'click', '.select-employee', function () {
                var checked = $(this).prop('checked');  // Get checkbox state
                
                // Get row data
                var row = $( this ).closest( 'tr' );
                var data = table.row ( row ).data();
                
                //update the cell data with the checkbox state
                if ( checked ) {
                    data.check = 1;
                } else {
                    data.check = 0;
                }
            });  

            $('#get-values').on('click', function () {
                var checkedRows = [];
                table.rows().every( function(rowIdx, tableLoop, rowLoop ) {
                    var data = this.data();
                
                    if (data.check === 1) {
                        checkedRows.push(data);
                    }
                });
                console.log('Checked rows via API');
                console.log(checkedRows);
                $('#selected').html(checkedRows);
            });     
        });
    </script>
</body>
</html>

Move the points in the graph linearly when a point is moved up/down and edge values should be fixed in Javascript

I have a chart in which a line is plotted randomly and when we move a point up/down the other points should update the values such that a new linear plot should appear.

In the image the blue line is the original and when a point is moved up as you can see the red line. Now how to calculate the new points such that it forms the linear green line.

I think it should be something related to linear equation like calculating the slope and then adding it to the other values but I dont think its working. Maybe I’m doing something wrong

How to load pdf files in nextjs using webpack file-loader (404 Error)

In my nextjs app, I want to add a button which user clicks on it and a pdf file downloads. I added the pdf file to public/documents/ and imported it and added it to link href. But after clicking it, it shows a 404 page even the generated file is exist and i can watch it on Chrome inspect > sources (in _next). I am using webpack file-loader.

Next config:

const nextConfig = {
  output: "standalone",
  webpack: (config, options) => {
    config.module.rules.push({
      test: /.(png|gif|mp4|pdf)$/i,
      use: [
        {
          loader: "file-loader",
          options: {
            name: "[name].[ext]",
          },
        },
      ],
    });
    return config;
  },
};

My page code:

import LeaderInstructions from "@documents/leaders-instructions.pdf";

...
//other codes
...

<a
      href={LeaderInstructions}
      target="_blank"
>

Anyone knows what should I do?

How can i control error status in React router loader?

I am using react router dom 6.22.3

I have created browser router like this

{
    path: "/",
    element: <MainLayout />,
    errorElement: <Error />,
    children: [
      {
        path: "/",
        element: <Dashboard />,
        loader: DashbaordLoader,
        errorElement: <Error />,
      },
    ]
}

Inside the Dashboard Component I am fetching data.

export const DashbaordLoader = async () => {
  try {
    const data = await fetcher("http://localhost:3000/users", "GET");
    return data;
  } catch (err) {
    throw err;
  }
};

The fetcher is just the javascript fetch function

export const fetcher = async (url: string, method: string) => {
  try {
    const response = await fetch(url, {
      method, 
      headers: {
        "Content-Type": "application/json",
        Authorization: "",
      },
    });
    return response.json()
  } catch (err) {
    throw err;
  }
};

As you can see there is no Authorization token so the server is responding like this

With status code 401

In the body {error: 'Need to login'}

But the thing is in the dashboardLoader. even though the data is with statusCode 401

It doesn’t goes into the catch block. How can i make it show the error element when the response is 401

Here is the error response in postman

enter image description here

change value of a React input DOM using javascript code in a chrome extension or console

How to change react base input element using javaScript in an extension or in a chrome console debugger?

For example, i have put a sample React link here that has an input and submit button.
text
When i change input with keyboard it submits the right value but when i change input value by console “javaScript” it submits the old value yet and it doesn’t affect anything.
I will be grateful if you can help me. thank you.

When i change input with keyboard it submits the right value but when i change input value by console “javaScript” it submits the old value yet and it doesn’t affect anything.
I will be grateful if you can help me. thank you.

my js code:
inp=document.getElementsByClassName("input")[0].value=5 btn=document.getElementsByClassName("form-submit-button")[0] btn.click()