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()

Undefined when trying to access object in Javascript

I’m creating a javascript program that prompt users to input coordinates (x,y) of 2 points of each line to do further functions.

    const numOfLines = parseInt(prompt("Please enter number of lines: "));

    //point object
    function Point(x, y)
    {
        this.x = x;
        this.y = y;
    }

    let firstPoints = new Array(numOfLines);
    let secondPoints = new Array(numOfLines);

    for(let i = 0; i < numOfLines; i++)
    {
        let firstPointMessage = "Please enter the first point's coordinates x, y of line " + (i+1);

        // substring input to add (x,y) to an array
        let firstPoint = prompt(firstPointMessage).split(",");

         //add point(x,y) to firstPoints array
        let fp = new Point(parseInt(firstPoint[0]) ,parseInt(firstPoint[1]));
        firstPoints.push(fp);

        let secondPointMessage = "Please enter the second point's coordinates x, y of line " + (i+1);
        let secondPoint = prompt(secondPointMessage).split(",");
        let sp = new Point(parseInt(secondPoint[0]) ,parseInt(secondPoint[1]));
        secondPoints.push(sp);
    }

    while(num < numOfLines)
    {
        document.write(firstPoints[num].x);
        ....further action
        num++;
    }
</script>

Error Cannot read properties of undefined (reading ‘x’) occurred for line document.write(firstPoints[num].x);

And firstPoints[num] actually has values when I tried to debug, but I just can’t get the value out of it to use for further action. What should I do?
Thanks

How can I convert an URL image into Base64 string using JavaScript?

I am just starting to learn JavaScript and working on a HTML webform that will be use a signature device, I need to capture user signature, basically user will sign and after hit save, I want their signature to be display on the HTML webpage. I am trying to display the signature but image is broken, I need help and I do not know why my image is breaking…

            <script>

              async function addImage() {
                const imageUrl = 'http://localhost:12001/SigCaptureWait?ResponseType=API&UseReceiptDataList=1&ReturnSigType=PNG&CreateFile=false&TopazType=1';
                const response = await fetch(imageUrl);
                const imageBlob = await response.blob();
                const objectURL = URL.createObjectURL(imageBlob);
                const imageElement = new Image();
                imageElement.src = objectURL;

                console.log({objectURL})

                document.getElementById('imageContainer').appendChild(imageElement);
            }
            addImage();     

            </script>

merge PDF/A files. or manipulate them

I am using pdf-lib npm package to merge multiple PDF files. but when i try to merge PDF/A files i recieve the following error

error

code snippet

import { PDFDocument } from "pdf-lib";

/**
 * Merge multiple PDFs provided as an array of Buffers.
 * @param pdfBuffers Array of Buffers where each Buffer is a PDF file to be merged.
 * @returns A Promise that resolves with a Buffer of the merged PDF.
 */
export async function mergePdfs(pdfBuffers: Buffer[]): Promise<Buffer> {
  const mergedPdf = await PDFDocument.create();

  for (const pdfBuffer of pdfBuffers) {
    const pdfDoc = await PDFDocument.load(pdfBuffer, {
      ignoreEncryption: true,
    });

    const copiedPages = await mergedPdf.copyPages(
      pdfDoc,
      pdfDoc.getPageIndices(),
    );
    copiedPages.forEach((page) => mergedPdf.addPage(page));
  }

  const mergedPdfBytes = await mergedPdf.save();
  return Buffer.from(mergedPdfBytes);
}

i read PDF/A wiki, PDF/A conformance states that JS and executable file launches are forbidden.
but all these websites like smallPdf and I<3PDF seem to still be able to do it.

I am getting MultiValueDictKeyError when I am clicking on add to cart button

I created an add-to-cart function for my website so in my
product-detail.html:

        {%  for p in products  %}
        <div class="product-price">
          <span id="current-product-price">Our Price:{{p.price}}</span>
          <del>M.R.P: {{p.old_price}}</del>
        </div>
        <div class="button">
          <input type="hidden" value="{{p.id}}" class="product-id" name="">
          <input type="hidden" value="{{p.title}}" class="product-title" name="">
          <a href="#" class="btn" id="add-to-cart-btn">Add to cart</a>
          <a href="#" class="btn">Buy Now</a>  
        </div>
          {%  endfor  %}

In my function.js:

$("#add-to-cart-btn").on("click",function(){
    let quantity=$("#product-quantity").val()
    let product_title=$(".product-title").val()
    let product_id=$(".product-id").val()
    let product_price = $("#current-product-price").text()
    let product_image = $(".product-image").val() //#1
    let product_pid=$(".product-pid").val() //#2
    let this_val=$(this)


    console.log("Quantity:", quantity);
    console.log("Id:", product_id);
    console.log("PId:", product_pid);
    console.log("Image:", product_image);
    console.log("Title:", product_title);
    console.log("Price:", product_price);
    console.log("Current Element:", this_val);

    $.ajax({
        url: '/add-to-cart',
        data: {
            'id': product_id,
            'pid': product_pid,
            'image':product_image,
            'qty': quantity,
            'title': product_title,
            'price': product_price
        },
        dataType: 'json',
        beforeSend: function(){
            console.log("Adding products to cart");
        },
        success: function(res){
            this_val.html("Go to Cart")
            console.log("Added products to cart");
            $(".cart-items-count").text(response.totalcartitems)
        }
    })
})

In the above js program is anything is wrong for the value error in product_pid(#2) & product_image(#1) and in my…… views.py:

def add_to_cart(request):
    cart_product={}
    cart_product[str(request.GET['id'])]={
        'title': request.GET['title'],
        'qty': request.GET['qty'],
        'price': request.GET['price'],
        'image': request.GET['image'], #1
        'pid': request.GET['pid'], #2
    }

    if 'cart_data_obj' in request.session:
        if str(request.GET['id']) in request.session['cart_data_obj']:
            cart_data= request.session['cart_data_obj']
            cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty'])
            cart_data.update(cart_data)
            request.session['cart_data_obj']=cart_data
        else:
            cart_data=request.session['cart_data_obj']
            cart_data.update(cart_product)
            request.session['cart_data_obj']=cart_data
            request.session['total_cart_items'] = len(cart_data)
    else:
        request.session['cart_data_obj']=cart_product
        request.session['total_cart_items'] = len(cart_product)
    return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']})

I think the error is comming from views.py. U can see the #1 & #2 in view.py

When I am clicking on add-to-cart button I am getting a value error the error is:

Internal Server Error: /add-to-cart/
Traceback (most recent call last):
  File "C:UsersSagarmoy SadhukhanAppDataLocalProgramsPythonPython311Libsite-packagesdjangoutilsdatastructures.py", line 84, in __getitem__
    list_ = super().__getitem__(key)
            ^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'image'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersSagarmoy SadhukhanAppDataLocalProgramsPythonPython311Libsite-packagesdjangocorehandlersexception.py", line 56, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersSagarmoy SadhukhanAppDataLocalProgramsPythonPython311Libsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersSagarmoy SadhukhanDesktopdjango ecom webecomprjcoreviews.py", line 169, in add_to_cart
    'image': request.GET['image'],
             ~~~~~~~~~~~^^^^^^^^^
  File "C:UsersSagarmoy SadhukhanAppDataLocalProgramsPythonPython311Libsite-packagesdjangoutilsdatastructures.py", line 86, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'image'
[13/Mar/2024 08:42:06] "GET /add-to-cart/?id=7&qty=1&title=Apple&price=Our%20Price%3A1.99 HTTP/1.1" 500 75258