How can I access Vue 3 props in the section of my app

In this simple Vue 3 app, I would like to pass props to a component and access the values in the script section. I can’t because they are undefined.

I can access values in the template section, though the first time it renders, I have a v-if guard because the value is undefined the first time it is rendered.

In this screenshot of the app, you can see the value “Floretta” properly rendered in the template, and the console.log output showing that the value of props.pdata.table is undefined immediately after the defineProps() line. (See the Component.vue code below)

enter image description here

What I’ve tried:

  1. Accessing props in a function called from onMounted()
  2. Reading the data file (the one that contains “Floretta”) synchronously in the Electron main app

How can I get access to my data in the script section, for example to set up other parts of the UI, such as computing a list of dates displayed in a table? The dates differ depending on values in the props pdata object.

Here is the stripped down application.

App.vue:

enter image description here

Component.vue:

enter image description here

How to check significant values instead of decimals in jest?

Jest’s precision parameter in toBeCloseTo can only limit the amount of digits to check after the decimal point (e.g. a fixed 0.005 margin of error if you set it to 2 d.p), so it does not work for floating point precision errors on larger numbers

expect(received).toBeCloseTo(expected, precision)

    Expected: 1.66e+208
    Received: 1.6600000000000002e+208

    Expected precision:    1
    Expected difference: < 5e-2
    Received difference:   2.2812203088110976e+192

Is there a function to check for significant figures instead?

Cloudinary secure_url returning undefined but the img so get uploaded in cloudinary

on NEXTJS v15 Cloudinary secure_url returning undefined but the img do get uploaded in cloudinary

  1. Console IMG: onUpload full function

  2. Console IMG: onUpload full result

Code Issue:

    const onUpload = (result: { info?: string | { secure_url?: string } }) => {
        console.log('Upload result:', result); // Debug log
        const secureUrl = typeof result.info === 'string' ? result.info : result.info?.secure_url;
        if (secureUrl) {
            onChange(secureUrl);
        } else {
            console.error('secure_url not found in upload result:', result);
        }
    };

Image-upload.tsx

'use client';
// global import
import React, { useEffect, useState } from 'react';

import { CldUploadWidget } from 'next-cloudinary'; // Replace 'some-library' with the actual library name

// local import
import { Button } from '@/components/ui/button';
import { ImagePlusIcon, Trash } from 'lucide-react';
import Image from 'next/image';

interface ImageUploadProps {
    disabled?: boolean;
    onChange: (value: string) => void;
    onRemove: (value: string) => void;
    value: string[];
}

const ImageUpload: React.FC<ImageUploadProps> = ({
    disabled,
    onChange,
    onRemove,
    value,
}) => {
    // State to track if the component is mounted
    const [isMounted, setIsMounted] = useState(false);

    // useEffect hook to set the isMounted state to true after the component mounts
    useEffect(() => {
        setIsMounted(true);
    }, []);

    const onUpload = (result: { info?: string | { secure_url?: string } }) => {
        console.log('Upload result:', result); // Debug log
        const secureUrl = typeof result.info === 'string' ? result.info : result.info?.secure_url;
        if (secureUrl) {
            onChange(secureUrl);
        } else {
            console.error('secure_url not found in upload result:', result);
        }
    };

    // If the component is not mounted, return null to prevent server-side rendering
    if (!isMounted) return null;

    return (
        <React.Fragment>
            {/* Display the uploaded images */}
            <div className='mb-4 flex items-center gap-4'>
                {value.map(url => (
                    <div
                        key={url}
                        className='relative w-[200px] h-[200px] rounded-md overflow-hidden'
                    >
                        <div className='z-10 absolute top-2 right-2'>
                            <Button
                                key={`remove-${url}`}
                                id='image-remove'
                                data-testid='image-remove'
                                type='button'
                                onClick={() => {
                                    onRemove(url);
                                }}
                                variant='destructive'
                                size='sm'
                            >
                                <Trash className='h-4 w-4' />
                            </Button>
                        </div>
                        {url && (
                            <Image
                                layout='fill'
                                className='object-cover'
                                alt='Image'
                                src={url}
                                id='image'
                                data-testid='image'
                            />
                        )}
                    </div>
                ))}
            </div>
            {/* this is to open the image upload widget */}
            <CldUploadWidget onUploadAdded={onUpload} uploadPreset='ecommerce'>
                {({ open }) => {
                    const onClick = () => {
                        open();
                    };
                    return (
                        <Button
                            type='button'
                            onClick={onClick}
                            disabled={disabled}
                            variant='secondary'
                            id='image-upload'
                            data-testid='image-upload'
                        >
                            <ImagePlusIcon className='h-4 w-4 mr-2' />
                            Upload Image
                        </Button>
                    );
                }}
            </CldUploadWidget>
        </React.Fragment>
    );
};

export default ImageUpload;

**Useage **

const formSchema = z.object({
    label: z
        .string()
        .nonempty('Billboard label is required')
        .min(3, 'Billboard label is too short'),
    imageUrl: z.string().nonempty('Billboard image is required'),
});

type BillboardFormValues = z.infer<typeof formSchema>;

const form = useForm<BillboardFormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: initialData || { label: '', imageUrl: '' },
    });

<FormField
                        control={form.control}
                        name='imageUrl'
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel data-testid='Billboard-imageUrl'>
                                    Background image
                                </FormLabel>
                                <FormControl>
                                    <ImageUpload
                                        value={
                                            Array.isArray(field.value)
                                                ? field.value.map((image: { url: string }) => image.url)
                                                : []
                                        }
                                        disabled={loading}
                                        onChange={url => {
                                            const newValue = Array.isArray(field.value)
                                                ? [...field.value, { url }]
                                                : [{ url }];
                                            field.onChange(newValue);
                                        }}
                                        onRemove={url => {
                                            const newValue = Array.isArray(field.value)
                                                ? field.value.filter(
                                                        (current: { url: string }) => current.url !== url,
                                                  )
                                                : [];
                                            field.onChange(newValue);
                                        }}
                                    />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

Getting months in a localised calendar, using Nodejs?

We are looking to display different calendars (Persian, Buddhist, Japanese), along with their list of month names, the number of days in a month, day names and where the start of the year is relative to the Gregorian calendar.

I had done something equivalent in Java many years ago, using ICU4J, but I am not sure how to go about this in Javascript?

We looked at the Intl.Locale.getCalendars(), but it is not clear how we could leverage this API for what we want to do.

We generally use luxon for our date handling, but in this case it only seems suitable for outputting the formatted date for the given calendar. For example:

DateTime.now().reconfigure({ outputCalendar: "persian" }).toLocaleString() 

Does anyone have any suggestions on how to achieve what we are wanting to do?

Edit: Currently looking to see if the package world-calendars could do the job.

How to express bigint or number or undefined using Zod Schema

I need to validate an object with a field that may be bigint, number, or undefined.

const IdNumberSchemaNullable = z.union([
    z.number().nonnegative().optional(), // For floating-point numbers and integers
    z.bigint().nonnegative(),  // For big integers (BigInt type)
    z.undefined()
]);
const OrderDetailsSchema = BaseSchema.extend({
    _t: z.literal('my_something'),
    id_test: z.IdNumberSchemaNullable,

All works, except when an object does not contain id_test field – I get following exception:

TypeError: Cannot read properties of undefined (reading '_parse')
    at ZodObject._parse (file:////node_modules/zod/lib/index.mjs:2526:37)
    at ZodObject._parseSync (file:////node_modules/zod/lib/index.mjs:649:29)
    at ZodDiscriminatedUnion._parse (file:////node_modules/zod/lib/index.mjs:3010:27)
    at ZodDiscriminatedUnion._parseSync (file:////node_modules/zod/lib/index.mjs:649:29)
    at file:////node_modules/zod/lib/index.mjs:2373:29
    at Array.map (<anonymous>)
    at ZodArray._parse (file:////node_modules/zod/lib/index.mjs:2372:38)
    at ZodArray._parseSync (file:////node_modules/zod/lib/index.mjs:649:29)
    at ZodArray.safeParse (file:////node_modules/zod/lib/index.mjs:679:29)
    at ZodArray.parse (file:////node_modules/zod/lib/index.mjs:660:29)

Proper way to migrate @computed decorators

I have a model Post that used a @computed decorator like this

@hasMany('comment', {async: true}) comments;

@computed('[email protected]')
get authorNames(){
    let comments = this.comments;
    let authorNames = comments.mapBy('authorName');
    return authorNames.join(', ');
}

I want to migrate this so it no longer uses @computed. Instead I want to use @tracked and getters. The problem I am having is that the relationship @hasMany('comment', {async: true}) comments; is asynchronous but the get is not. For example:

@tracked names
get authorNames(){
  let comments = this.comments;
  if(!comments.isFulfilled){
     this.names = 'loading';
     return this.names;
  }
  this.names = comments.mapBy('authorName').join(',');
  return this.names;
}

does not work. Any idea?

Name in iframe Random string

In my application, i’m using iframe to view files but I have a problem. The file name is a random string and not its name. How could he manipulate that information? I need the name of the file itself to appear and when I download it the same.

I’m using the following.

Service

obtenerDoc(nodeId: string, token: string) {
      const url = `${environment.proxyConfig}${this.baseUrl}/nodes/${nodeId}/content?attachment=true&alf_ticket=${token}`;
      const headers = new HttpHeaders({
        'Authorization': `Bearer ${token}`,
        'accept': 'application/octet-stream',
      });
      
      return this.http.get(url, {
        headers: headers,
        responseType: 'blob',
        observe: 'response'
      });
    }

APP

 obtenerDocumentoNormal() {
    this.obtenerDoc.obtenerDoc(this.nodeId, this.token).subscribe(
      (response) => {
        const contentDisposition = response.headers.get('content-disposition');
        if (contentDisposition) {
          const matches = /filename="(.+)"/.exec(contentDisposition);
          const filename = matches && matches[1] ? matches[1] : 'desconocido.pdf';
        }
        const objectUrl = URL.createObjectURL(response.body);
        this.nodoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(objectUrl);
        this.isImage = false;
        this.isAudio = false;
        this.isFrame = true;
        this.isVideo = false;
        this.isNotVisualizable = false;
        this.isLoading = false;
      },
      (error) => {
        console.error(error);
        MessageUtil.showAlertMessage("No se puede visualizar este tipo de documento");
      }
    );
  }

HTML

<iframe *ngIf="isFrame" [src]="nodoUrl" class="container__frame" name="documento" title="nombre"></iframe>

In the content -disposition I have the name but that is not in the browser blob and I suppose that is why it takes a random name

Splitting a compound path in paperjs

Hi I’m trying to figure out the simplest way to split a compound path.

I have a simple case illustrated here http://sketch.paperjs.org/#V/0.12.18/S/pZHBCsIwEER/JcRDFYqkSi8RD9ofED1aDzFdbWi6W9qooPjvplgVPBVd2MPM4c0Oe+OoSuCSbwpwOuch15S1WhM2jmkqKzphxuYM4cKSTq6Uy4e3FJmfg7E2IUu1ZMFAiEMQfvz1yYK34QxIWRakeB+lmOKTXYN20aIjt8Tx2jsKjxZe7Ioa4wyhZNsoFqHfXUdvzNWTp0J0ulI1oJPvg8M2a/YVtvwrrDX7h016N4t/aeYfta9BFRUZdA2X2939AQ==.

The ideal result is rect1 becoming its own compound path instance and rect2 becoming a different path instance. I know I could probably sus it out eventually doing a bunch of hit tests and what have you but I’m wondering if there’s a simpler way.

Thanks

Go to page using class name

I’ve been trying to open a link using javascript from a class name, but I’ve had no luck so far

<body>
    <a href="https://example.com" class="1"></a>

    <script language="javascript">
        window.open(document.getElementById('1').className);
    </script>
</body>

Conditionally activate HTML for restricted page or for normal Tumblr blog based on current URL

When someone lands on my blog homepage (blog-name.tumblr.com), I want them to see a fake restricted page with a hidden link. The link leads to blog-name.tumblr.com/page/1 and shows the true blog homepage. Every other blog link (/post, /tagged…) should also work.

I am thus working with two HTML scripts:

  1. Restricted blog
  2. Normal blog

My question: Is there a way to conditionally activate the one or the other HTML script based on the current URL (blog-name.tumblr.com or blog-name.tumblr.com/[anything])?

HTML for restricted blog:

<style>
  body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #36465d;
    color: white;
    font-family: "Helvetica Neue", Arial, sans-serif;
    font-size: 18px;
    font-weight: bold;
    margin: 0;
    text-align: center;
  }
  a {
    color: #36465d; /* hidden link, same color as background */
    text-decoration: none;
    font-size: 8px;
  }
  .gif-container {
    margin-top: 20px; /* space and then gif for distraction */
  }
  img {
    max-width: 100%;
    height: auto;
    border-radius: 10px;
  }
</style>

<div class="restricted-message">
  <p>This blog is private.</p>
  <p><a href="https://blog-name.tumblr.com/page/1">.</a></span></p> /* link to true blog */
  <div class="gif-container">
    <img src="gif.gif" alt="Private Page GIF">
  </div>
</div>

The HTML for my normal blog is much longer (ca. 2000 lines). Consider a normal custom Tumblr HTML.

Thank you in advance.

Accessing AWS credentials from a javascript web app

I am writing a web app in vanilla javascript that uses AWS Bedrock. If I use the Bedrock CLI, all is well – I have a credentials file in .aws in my home directory and the necessary IAM Permissions to access the model. Similarly if I hard code the AWS credentials in the call to the API in my javascript code:

const client = new BedrockRuntimeClient({
  region: "eu-west-2",
  credentials: {
    secretAccessKey: "My secret key",
    accessKeyId: "My access key"
  } 
}); 

this works too.

However, if I remove the hard coded credentials from the code, as of course I should, where should I put the credentials file so that my web app can access it? It won’t find it in my home directory, because the server knows nothing about my home directory. The advice on the web is very confusing, not helped by the change from version 2 to version 3 of the AWS-SDK, thus making suggestions that work for version 2 no longer applicable (I am using version 3).

To complicate matters more, I am developing the app on MacOS, but intending to deploy it on an EC2 instance and would like any solution to be portable between these two. For both, the server is Apache2.4.

Scope Problems with Adobe Animate HTML 5 Canvas

in Adobe animate and HTML canvas, I made a simple digital keyboard on the stage with 60 keys, all with an instance name “key0” to “key59”. When a key is clicked, isPressed turns true and the key toggles green, and vice versa.

I have another button on the screen with an instance name “generateCode” that loops through all the keys and creates a long concatonized string with a 0 if the key is not toggled and a 1 if the key is toggled. The output should be a 60 digit code of 1’s and 0’s. However, when I write the click function, and try to access the stage or root and try to use this.getChildByName(‘key’ + i), or this.root.getChildByName(‘key +i’),I get an error that says getChildByname is not a function or cannot read properties of undefined. Its like I am not even in the scope of the stage or root. Even if I add this.stage or this.root, I get an error. I’ve run into other instances where I had to instantiate the movie clip in order to use it in different functions and it seemed like an odd work around. However I am not going to instantiate 60 buttons at the beginning. I am an amateur coder and elementary school teacher, so I am sure I’m missing something.

generateBtn.addEventListener("click", generateCode);

    function generateCode(){
        let code = "";
    
        for(let i = 0; i < NUM_KEYS; i++){
            let keyState = this.root.getChildByName('key' + i);
            if (keyState){
                if (keyState.isPressed){
                    code = code + "1";
                }else if(!keyState.isPressed){
                    code = code + "0";
                }
            }
        }
    
        codeText.text = "test";
        console.log(code);
        console.log(code.length);
    }

Django frontend detect if user is logged in

I use django at backend and html/javascript for frontend.

I am looking for a way to know in frontend if the user is logged in. If user is not logged in, upon pressing some buttons, the website shows a login overlay form.

By just checking whether sessionid exists in the cookies or not you can find it out. But, the problem is SESSION_COOKIE_HTTPONLY in django settings is True and I do not want to turn it off. Thus, the document.cookies does not include the sesstionid due to security reason. Is there still any way to find the user is logged in without contacting the backend?

Get the name on a FluentUI React spinbutton

I am designing an eventhandler to handle various inputs that are constructed using the FluentUI React component library.

Most of the components emit “standard” React.Changeevents (such as HTMLSelectElement, HTMLInputElement, etc..). I can use these events to get the name and type of the input via the event.target.name and the event.target.type properties.

The FluentUI React Spinbutton (https://react.fluentui.dev/?path=/docs/components-spinbutton–docs) seems to emit a custom event (SpinButtonChangeEvent) that seems to link to the up/down button of the spinbutton and therefore does not include the name property in the emitted event.

Is there any way to get the name of the spinbutton from the event (in the example below “alertTimeout”

<SpinButton
   defaultValue={settings.alertTimeout}
   size="small"
   name="alertTimeout"
   input={{ name: "alertTimeout" }}
/>

I tried looking into creating a custom event but first of all I cant get it to work and secondly there must be a better way to do this