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

Leaflet-FreehandShapes Not Working in Angular 17 Production Build

I’ve been working with the leaflet-freehandshapes npm package by bozdoz in an Angular 17 project. Everything works as expected in development mode when I use ng serve. However, I encounter issues when switching to production mode.

  • Angular 17
  • Leaflet
  • leaflet-freehandshapes npm package

The code:

import * as L from 'leaflet';
import 'leaflet-freehandshapes';
import { AfterViewInit, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [],
  styleUrl: './app.component.scss',
  template: '<div id="map" style="height: 400px;"></div>',
})
export class AppComponent implements AfterViewInit {
  ngAfterViewInit(): void {
    const map = L.map('map', {
      center: [51.505, -0.09],
      zoom: 13,
    });
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data &copy; OpenStreetMap contributors',
    }).addTo(map);
    
    const freeHandShapes = new L.FreeHandShapes({
      polygon: {
        color: 'red'
      }
    }).addTo(map);
    
    freeHandShapes.setMode('add');
  }
}

Steps to Reproduce:

  • Run ng build to build the project for production.
  • Serve the production build using serve -s dist/browser/my-project.

Error:

enter image description here

Please let me know if you have some tips

Thanks

monaco editor How to correctly match highlighted keywords

I have a list of rules

const keywords = [Stop,.............]

monaco.languages.register({ id: "mySpecialLanguage" });

monaco.languages.setMonarchTokensProvider("mySpecialLanguage", {
    tokenizer: {
        root: [
            [/(?<!w)Stop(?!w)/, 'keyword']
        ],
    },
});

monaco.editor.defineTheme("myCoolTheme", {
    base: "vs",
    inherit: false,
    rules: [
        { token: 'keyword', foreground: 'f1d710' },
    ],
    colors: {
        "editor.foreground": "#000000",
    },
});


monaco.editor.create(document.getElementById("container"), {
    theme: "myCoolTheme",
    value: `Stop
QdStop
qdStop
11Stop
StopSS
Stop11
Stopdd 
    `,
    language: "mySpecialLanguage",
});

I expected all keywords to be highlighted, but now Stop is included in the keywords list, but words ending in Stop will still be highlighted

The effect at the beginning of Stop is correct, but the effect at the end of Stop is wrong and should be shown in black, not yellow

How do I make it highlighted as a keyword only for Stop words, it shouldn’t be highlighted if there are letters or words before and after it

Vuetify 3 v-file-input, clickable chips

I want to use the v-file-input from Vuetify, but it seems there was a strange regression in Vuetify3 ?

In Vuetify 2, you can use the selection slot to custom the display of the selected files. This still works in both versions, as said in the documentation => V3, V2

But when I try to do a basic closable chip, the hover or click does not trigger at all, like the answer in this previous post in Vuetify2.

It seems the input always take priority over the chips, which are now in another element than the input itself, preventing any user interactions with the chips, like deleting one of 50 imported files. Or any basic hover events

Any workaround other than downgrading to Vuetify 2 ? Here‘s the playground i’m testing

Images are vertical instead of horizontal

I can’t get my images to align horizontally. Instead they align under one another.
I am making this code from W3Schools.com.
I tried flex, float and other solutions on the web.
I am making this for my homepage to showcase some of my photos.

.column {
  float: left;
  width: 500px;
  padding: 10px;
}

.column img {
  opacity: 0.8;
  width: 150px;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.container {
  position: relative;
  display: none;
}

#imgtext {
  position: absolute;
  bottom: 15px;
  left: 15px;
  color: white;
  font-size: 20px;
}

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}
<div class="row">
  <div class="column">
    <img src="https://picsum.photos/150/150" alt="F35C Parked" onclick="myFunction(this);">
  </div>
  <div class="column">
    <img src="https://picsum.photos/150/150" alt="F16 Venom" onclick="myFunction(this);">
  </div>
  <div class="column">
    <img src="https://picsum.photos/150/150" alt="EuroFighter Landing" onclick="myFunction(this);">
  </div>
</div>
<div class="container">
  <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>

  <img id="expandedImg" style="width:100%">

  <div id="imgtext"></div>
</div>

how to adjust categoryXField and valueYField position in radar chart?

I just want adjust categoryXField and valueYField in same position, like this photo.
enter image description here
Here is my code.

`

function amchart_on_libload(objInst, chart_type){createRadarChart();}

function createRadarChart(){

var root = this.RadarChart_1.getroot();

// Create chartlet chart = root.container.children.push(am5radar.RadarChart.new(root, {panX: false,panY: false,wheelX: “panX”,wheelY: “zoomX”}));

// Add cursorlet cursor = chart.set(“cursor”, am5radar.RadarCursor.new(root, {behavior: “zoomX”}));

cursor.lineY.set(“visible”, false);

// Create axes and their rendererslet xRenderer = am5radar.AxisRendererCircular.new(root, {

});xRenderer.labels.template.setAll({textType: “adjusted”,radius: 20,

});let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {maxDeviation: 0,categoryField: “country”,renderer: xRenderer,tooltip: am5.Tooltip.new(root, {})}));

var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {renderer: am5radar.AxisRendererRadial.new(root, {}),min: 0,max: 100}));

// Create serieslet series = chart.series.push(am5radar.RadarLineSeries.new(root, {name: “Series”,xAxis: xAxis,yAxis: yAxis,valueYField: “litres”,categoryXField: “country”,tooltip:am5.Tooltip.new(root, {labelText:”{valueY}”})}));

series.strokes.template.setAll({strokeWidth: 1

});

// Set datalet data = [{“country”: “Lithuania”,”litres”: 100}, {“country”: “Czechia”,”litres”: 90}, {“country”: “Ireland”,”litres”: 50}, {“country”: “Germany”,”litres”: 40}, ];series.data.setAll(data);xAxis.data.setAll(data);

series.appear(1000);chart.appear(1000, 100);

}

`

Server sent events in pedestal returns empty response

I am currently implementing server sent events (SSE) in an web application using Clojure, Pedestal and Jetty.

When I print the message in the backend the channel is open and when I invoke io.pedestal.http.sse/send-event it returns true, however in the frontend I get no console.log() prints in Javascript in the browser console. as if there is no data received. I tested the SSE connection in Postman and it is successful but the response is (empty).

Backend:

    (def SSE-REGISTRY (atom {}))
     
     (defn get-user-channel [token]    
       (get @SSE-REGISTRY token))
     
     (defn test-print [channel]    
       (println "channel:" channel) ;; channel:#object[clojure.core.async.impl.chan...]   
       (println "channel opened:" (not (chan/closed? channel))) ;; channel opened: true  
       (println "sent-event:" 
       (sse/send-event channel "status"
         (json/write-str {:id 1
                          :workflowId 3
                          :status :GOOD}) ;; sent-event: true
     
     (defn send-sse-msg [name data id]   
       (when-let [sse-channels (vals @SSE-REGISTRY)]
         (doseq [channel sse-channels] 
           (when-not (chan/closed? channel)
             (test-print channel)
             (sse/send-event channel name data id)))))   

(def sse-route ["/rest/sse" :get 
                  (sse/start-event-stream send-sse-msg 10 100) 
                  :route-name :sse])
     
     (defn create-sse-channel []   
        (async/chan (async/sliding-buffer 100)))

enter image description here

Frontend:

 const protocol = window.location.protocol;
const host = window.location.port; 
const sseUrl = protocol + '//'+ host + '/rest/sse';
const RUN_BUTTON_STATUS_TIME = 2000;
const sseInitOptionsMap = {
                            headers: {
                                       'Content-Type': 'text/event-stream; charset=utf-8',
                                       'Connection': 'keep-alive', 
                                       'Cache-Control': 'no-cache' 
                                      },
                            withCredentials: true,
                            https: {rejectUnauthorized: true}
                          };

export const eventSource = new EventSource(sseUrl, sseInitOptionsMap);
eventSource.addEventListener('integrationStatus', sendStatusHandler);
eventSource.addEventListener('stopAction', sendStopActionHandler);

eventSource.onopen = (e) => {
  console.log("SSE connection opened:" + e);
};

eventSource.onerror = (e) => {
  console.log("error:" + e);
  if (e.readyState == EventSource.CLOSED) {
      console.log("connection closed:" + e);
  } else {
    eventSource.close();
    console.log("SSE connection closed:" + e);
  }
};

export function sendStatusHandler(event) {
  const data = JSON.parse(event.data);
  console.log("data:" + data);
  let id = data.id;
  let workflowId = data.workflowId;
  let status = data.status;
  cljsDisp("set-global-operation-status", id, workflowId, status);
  configurtorActionRunButtonStatus(id, workflowId, status);
  setTimeout(cljsDisp("get-last-run-action-data", id, workflowId, status),
             300);
}

function configurtorActionRunButtonStatus (id, workflowId, status) {
  if (status === "GOOD") {
    showStatus(id, workflowId, true);
  } else if (status === "BAD") {
    showStatus(id, workflowId, true);
    cljsDisp("configurator-error-message-show", id, workflowId, true);
  } else {
    cljsDisp("configurator-action-run-button-status-visible?", id, workflowId, false);
  }
}

export function sendStopWorkflowHandler(event) {
  const data = JSON.parse(event.data);
  console.log("data:" + data); // prints nothing
  let workflowId = data.workflowId;
  cljsDisp("stop-action-by-sse-msg", workflowId);
}

function showStatus(integrationId, operationId, showStatus) {
  setTimeout(cljsDisp("configurator-action-run-button-status-visible?", 
                      integrationId, operationId, showStatus),
             RUN_BUTTON_STATUS_TIME);
}

export function closeSse() {
  if (eventSource.readyState != eventSource.CLOSED) {
    eventSource.close();
  }
}

enter image description here

It seems I am missing something. Can you help. The problem is that there are not much examples of Clojure with Pedestal implementation of SSE. Most are in JavaScript and other languages.

Default Value in a select box (MUI) not showing unless an onChange event is fired

I am fetching data from an API in order to render a Select box. The value in the select box contains a users details. My problem is that on initial load even when data is fetched correctly a default / initial user is not rendered within the select box even though the data is there.

The onchange event and the select box itself works as expected otherwise. I have added a default value. A key to show the DOM its a new element and unsure what else to try

import { Avatar, Grid, MenuItem, SelectChangeEvent, Select } from "@mui/material";
import {iconMap} from './iconMap.ts'

const SocialSelectDropdown = () => {

    const [selectedAccount, setSelectedAccount] = useState<IConnectionData | null>(connectionData?.[0] ?? null)

    useEffect(() => {
        if (connectionData) {
            setSelectedAccount(connectionData?.[0])
        }
    }, [connectionData])

    const handleSelectedConnection = (e: SelectChangeEvent<string | unknown>) => {
        setSelectedAccount((prevState: IConnectionData | null) => {
            const selectedSocial = connectionData?.find((connection) => connection?.id === e?.target?.value);
            return selectedSocial || prevState;
        });
    };


    if (!selectedAccount?.id) {
        return <Loader />
    }

    return (
        <Grid item xs={12}>
            <Select
                key={selectedAccount?.id}
                size="small"
                sx={{ maxWidth: "fit-content" }}
                value={selectedAccount?.id}
                onChange={handleSelectedConnection}

            >
                {connectionData
                    ?.filter((item: any) => !["facebook_user"].includes(item?.platform))
                    ?.filter((item) => (role_id === 5 ? item : item?.platform !== "linkedin"))
                    ?.map((social: IConnectionData, index: number) => (
                        <MenuItem key={social?.id} selected={selectedAccount?.id === social?.id} value={social.id}>
                            <Grid container flexDirection="row" alignItems="center" gap={1}>
                                <Grid item position="relative">
                                    <Avatar src={social?.profile_pic_url} />
                                    <Grid item position="absolute" bottom={-5} right={-5}>
                                        <GetPlatformIcon platform_id={iconMap(social)} size={20} />
                                    </Grid>
                                </Grid>
                                <Typography>
                                    {social?.username}
                                </Typography>
                            </Grid>
                        </MenuItem>
                    ))}
            </Select>
        </Grid>
    );
};

export default SocialSelectDropdown

wn;