Modify object property passed as a prop

In my parent component, I have a ref:

const person = ref({ name: 'John Doe', parent: { name: 'Jane Doe' } })

In my child component, I recieve the entire object:

<parent-picker :person="person" />

Is it ok to alter the person’s “parent” property inside child-component, or does it fall under the prop modification anti-pattern?

Splitting CryptoJS word array to extract the IV before decryption

I receive a base64 encoded string. The first 16 bytes are the IV. I need to extract them before I decrypt with CryptoJS.

I am failing to split data from CryptoJS.enc.Base64.parse

In a nutshell, please help me fill this:

/*
 * ivAndcipheredDataBase64: first 16 bytes are iv the rest is the cipheredData
 */
function decipherData(ivAndcipheredDataBase64, key) {

    var ivAndCipheredDataBytes = CryptoJS.enc.Base64.parse(ivAndcipheredDataBase64);
    var iv = // What do I put here to get cipheredIVAndDataBytes[0:16]
    var cipheredData = // What do I put here to get cipheredIVAndDataBytes[16:len(cipheredIVAndDataBytes)]
   

    var plainDataBytes = CryptoJS.AES.decrypt({ ciphertext: cipheredData }, key, {
        iv: iv
    });
    return plainDataBytes.toString(CryptoJS.enc.Utf8)

}

Thanks, I am having trouble to know the type returned by CryptoJS.enc.Base64.parse, the documentation says WordArray object but i am not sure how to deal with that

Incomplete Land Cover Classification in Google Earth Engine for Specific Areas

I’m doing a supervised land cover classification on Google Earth Engine (GEE). While the code works for most of my ROIs, it fails to classify the entire area for one specific forest (Forest 21), leaving parts unclassified. Only a portion of the area is classified correctly, while the rest remains unclassified.This is happening for a few of the areas that I need to classify.

enter image description here

https://code.earthengine.google.com/037726a46c1084b29b14529e52a2ce47

  • Verified the geometry of forest21.
  • Checked cloud cover filter to ensure high-quality images are used.
  • Chnaged date ranges.
  • Tried different satellites (landsat 5 and 7)

enter image description here

How to turn off encoding in NestJs

I have some troubles with encoding files in NestJs. I’m sending files named IEGS1-2026, and fetch it throught GET, and got IEGS1-2026-a92e.pdf.
I changes my files.utils.ts file. Now it looks like this

import { extname } from 'path';

export const fileName = (req, file, callback) => {
  const originalName = file.originalname;
  callback(null, originalName);
};

But anyway there is random words and numbers in the name of the file.

How to prevent hidden HTML Input fields from pushing other elements down the page using JQUERY

I have an HTML form that hides certain Select boxes based on another selection. The code works but the hidden input fields still occupy blank page space and push other elements down. Here is a simplified version of the code I plan to use. I figure I need to also change the ‘Display’ to ‘None’ but I can’t find information online on how to do that in a case like this one. Is it possible?

$(document).ready(function() {
  $('#autoid, #techid, #govid').hide();

  $('#catid').change(function() {
    $('#autoid').toggle($(this).val() == "1");
    $('#techid').toggle($(this).val() == "2");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form id="selectid" name="selections" action="" method="POST" target="_self">

  <select id="catid" name="category" size="1">
    <option value="0">Choose one ...</option>
    <option value="1">Automobiles</option>
    <option value="2">Technology</option>
  </select>

  <br />

  <select id="autoid" name="topics[]" size="1">
    <option value="1">Cars</option>
    <option value="2">Trucks</option>
    <option value="3">RVs</option>
  </select>

  <br />

  <select id="techid" name="topics[]" size="1">
    <option value="1">Development</option>
    <option value="2">Gaming</option>
    <option value="3">Hardware</option>
  </select>

  <br />

  <input id="submit" name="Continue" type="submit" value="Continue">
</form>

If you run this code, you’d see that the first hidden Select box (autoid) shows up right under the catid box. However, when changing the Category to the second choice (techid), the second hidden Select box appears below the first (now hidden) autoid select box. Problem is that my application will have ten of these hidden boxes so the page layout will be terrible filled with empty space between input fields.

How can I fix this problem? Thank you for any suggestions!

how can I make a js script to ensure user fills the form feilds and then submiting it? [closed]

my has three pages, with navigation buttons, next page buttons and prev page button.
I wrote a js that handles that matter for me and works without any problem.

let current_page = 1;

function showPage(pageNumber){
    // Hides all pages:
    const pages = document.querySelectorAll('.page');
    pages.forEach(page => {
        page.classList.remove('active');
    });

    // Shows the current page:
    document.getElementById(`page${pageNumber}`).classList.add('active');
}

function nextPage(pageNumber){
    if(validatePage(pageNumber)){
        current_page++;
        showPage(current_page);
    }
}

function prevPage(pageNumber){
    current_page--;
    showPage(current_page);
}

function validatePage(pageNumber){
    // Simple validation for demonstration
    const currentInput = document.querySelectorAll(`#page${pageNumber} input`);
    let valid = true

    currentInput.forEach(input =>{
        // Only validate <input> elements:
        if (!input.checkValidity()){
            input.reportValidity();
            valid = false;
        }
    });

    return valid;
}

document.getElementById('multiPageForm').addEventListener('submit', function (event){
    event.preventDefault();

    // Collect data from all pages:
    const formData = new FormData(this);

    // Sending data to server:
    fetch('/record', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
        alert('Reort sent successfully');
    })
    .catch(error => {
        console.error('Error:', error);
        alert('error while sending data');
    })
});

I want user to fill the information, or check that radio inputs, if not, shouldn’t let user go to next page, for further feilds and submiting button. but this hasn’t implemented with my code and I can easliy move throght pages without filling feilds or checking radios!

FileReader returns garbage after a certain number of files in mobile safari

Been really stumped by this problem. I’ve searched the web and haven’t found traces of info on it, but I believe it is a widespread issue.

See the HTML in this post. If I select more than 350 (the bounding value works for my iPhone, but it may vary based on device) photos the first 350 will upload just fine. For photos after 350 each one will fail. When this fails, the data returned is what appears to be an empty plist and the FileReader doesn’t error. Here is a sample of the bytes returned when it fails (appears to be an empty plist):

"bplist00�
X$versionY$archiverT$topX$objects��_NSKeyedArchiver�    Troot��U$null$)27ILQSU["

So, the question is: Is this a known issue I just haven’t found Apple’s documentation for? Is there a way to work around this without putting an arbitrary limit on the number of files you can select?

The HTML is below. I hosted it somewhere and debugged from my iPhone tethered to my Mac. I am looking at the image header to avoid dumping out more bytes than necessary and overloading the debugger console. I only log the contents of the first failure, but believe that all failure have the same contents.

<html>
<head>
    <title>Tester</title>
</head>
<body>
    <button id="selectButton">Select Photos</button>
    <input type="file" id="fileInput" style="display: none;" accept="image/*"  multiple>
    <script>
        document.getElementById('selectButton').addEventListener('click', function() {
            document.getElementById('fileInput').click();
        });

        document.getElementById('fileInput').addEventListener('change', function(event) {
            const files = event.target.files;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                testImage(file);
            }
        });
    
        var savedOutput = false;

        function testImage(file) {
            var _reader = new window.FileReader(),
                _fn = file.slice || file.mozSlice || file.webkitSlice || function(){return;},
                _slice = _fn.call(file, 0, 3);

                _reader.onloadend = function(_evt) {
                        var _isValid = false,
                            _bytes;
                        if (!_evt.currentTarget.error) {
                            _bytes = new window.Uint8Array(_evt.currentTarget.result);

                            if (
                                    (_bytes[0] == 0xFF && _bytes[1] == 0xD8 && _bytes[2] == 0xFF) ||    //Check for jpg
                                    (_bytes[0] == 0x42 && _bytes[1] == 0x4D) ||    //Check for BMP
                                    (_bytes[0] == 0x89 && _bytes[1] == 0x50 && _bytes[2] == 0x4E)    //Check for png
                                ) {
                                _isValid = true;
                            } else {
                                if (_bytes[0] == 0xFF && _bytes[1] == 0xD8 && _bytes[2] == 0xFF) {
                                    _isValid = true;
                                }
                            }

                            if(_bytes[0] == 0x00 && _bytes[1] == 0x00 && _bytes[2] == 0x00) {  //Check for heic
                                _isValid = true;
                            }
                        }

                        console.log('File: ' + file.name + ' is a JPEG: ' + _isValid);

                        if (savedOutput === false && _isValid === false) {
                            savedOutput = true;

                            const decoder = new TextDecoder();
                            const text = decoder.decode(_bytes);
                            console.log('Failed Output: ', text);
                        }
                }

                _reader.readAsArrayBuffer(file); 
            
        }
    </script>
</body>
</html>

I have tried this from more involved applications and it always fails. The failure seems related to file access.

React Router 404 Error on Vercel Deployment Despite Custom Rewrites in vercel.json

Basically I was trying to use react router in my vite project. But the problem is when I found that React router is not properly working in Varcel when I refresh webpages. It shows me 404: NOT FOUND error

I have read many solutons over internet & stackoverlow but none of them work for my project. I don’t understand why these solutions is not working for me?

My app.jsx routes –

<BrowserRouter>
        <div className='App'>
          <Routes>
            <Route path="/" element={<LandingPage />} />
            <Route path="/bookSeat" element={<BookTicket />}/>
            <Route path="/contact" element={<Contact />} />
          </Routes>
        </div>
</BrowserRouter>

varcel.json –

{
  "routes": [
    { "src": "/bookSeat", "dest": "/" },
    { "src": "/contact", "dest": "/" },
    { "src": "/", "dest": "/" }
  ]
}

I have also tried with this code inside varcel.json –

{
  "rewrites":  [
    {"source": "/(.*)", "destination": "/"}
  ]
}

but none of them worked & I am still getting this 404 error.

But here is the more interesting part. I used this react router for my another portfolio project & there it worked without using any varcel.json. There I can refresh webpages multiple time & navigate pages multiple times without having any error. The only difference is I used npm create-react-app for my portfolio project & here I am using vite to build my project.

So what should be the correct way to fix this issue?

I tried with various code from stackoverflow inside varcel.json & those are not working and I am expecting to have a solution that will work universally.

Error setting a cookie from backend with Gin Gonic

Good afternoon. I’m having a problem trying to set a cookie from my backend with Golang and Gin Gonic.

I have 2 html files (index.html, register.html)
I run the index.html file from VSC with the live server extension:
This has a button which when pressed performs a fetch to my backend, the backend sets a cookie and responds with status code 200.
When receiving the response from the “frontend” a window.location.href = register.html is performed
If I don’t do the window.location.href, from the Google Chrome developer tools I can see the cookie set by my backend, but when I do the window.location.href the cookie disappears.
Why does this happen and how can I fix it so that the cookie is set and doesn’t disappear when changing the html file?

Try changing all the settings by setting the cookie with *gin.Context.
Try setting ctx.SetSameSite
(Just in case the fetch from the html file has credentials: “include” set)

How to get Task Id passed back to Twilio function using plugin

To begin, the work here is based off of this write up for transfering Flex calls back to IVR Flows.
https://www.twilio.com/en-us/blog/transfer-calls-back-to-your-ivr-from-flex

That being said when when using the plugin file included in this github
https://github.com/bruno222/twilio-flex-plugin-transfer-to-ivr/blob/main/src/TwilioFlexTransferToIvrPlugin.tsx

You may noticed that it is pulling the task from the props object being passed through to the TransferToIVR function. From that task it is pulling the relevant call_sid or transferToIvrUrl to get us back to the flow. I need to get the task_sid from this task.

I was thinking I could just add the sid to the Propsinterface under task. And then when the request in made in OnClick() just pass through that additional value. This is not working as I expected. When logging the event object back in my twilio function only the call_sid and transferToIVRMenu are shown.

requireNativeComponent: “ViewManagerAdapter_ExpoAppleAuthentication” was not found in the UI Manager

I am trying to setup Apple authentication in a React Native build.

I have installed expo-apple-authentication (this seems to be the version compatible with Expo 49, which I am using, but I have also tried 6.4.2 with the same results)

"expo-apple-authentication": "~6.1.0"

I have tried running npx expo prebuild, npx expo run:ios, etc.

I am using a managed build, which as far as I can tell is supported by expo-apple-authentication.

Has anyone experienced this and figured out a way to solve it? I’m searching everywhere and while other people occasionally have this error, none of it seems related to this particular package

iPhone simulator error

Google Custom Search Element appears over div element containing a drop-down menu

I am trying to add the Google Custom Search Element to a web page. This is the code that I’m using:

<div class="gcse-searchbox-only" 
     data-resultsUrl="https://example.com/search-results/" 
     data-newWindow="false" 
     data-queryParameterName="q"
     id="search"></div>   

The widget itself works well, however the widget is placed below a div element containing other div elements that dynamically appear in order to present a drop-down menu. The drop-down menu appears behind the widget. How can I have the drop-down menu appear in front of the widget?

So far I’ve tried to address this by changing the z-index of the drop-down menu, and the z-index of the div element containing the widget, but it hasn’t had any effect.

Understanding TypeScript Compilation Errors in My Project

I have a lint-staged which works after pre-commit. Everything works correctly except tsc. I’ve already tried a lot with the settings with tsconfig but no result.File tsconfig lies in the same directory as project in the picture.

Settings lint-stager
package.json

  "lint-staged": {
    "src/**/*.{ts,tsx}": ["tsc --skipLibCheck --noEmit"]
  }

Settings that are currently used in my project
tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "esnext",
    "target": "es5",
    "strict": true,
    "jsx": "react-jsx",
    "allowJs": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "paths": {
      "@/*": ["*"]
    }
  },
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}

Error

✖ tsc --skipLibCheck --noEmit:
src/pages/main/ui/main.tsx(1,28): error TS2307: Cannot find module '@/shared/ui/typography' or its corresponding type declarations.
src/pages/main/ui/main.tsx(5,5): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
src/pages/main/ui/main.tsx(6,7): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
src/pages/main/ui/main.tsx(12,7): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
src/shared/ui/typography/ui/typography.tsx(3,8): error TS1259: Module '"C:/Users/Happy/Desktop/front-cn/node_modules/clsx/clsx"' can only be default-imported using the 'esModuleInterop' flag
src/shared/ui/typography/ui/typography.tsx(25,5): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.

File error

import './typography.css';

import clsx from 'clsx';
import { ComponentProps, ReactNode } from 'react';

type TypographyVariant = 'title';
type TypographyTag = 'h1' | 'h2' | 'h3' | 'h4' | 'span' | 'div' | 'p';

export type TypographyProps<Tag extends TypographyTag> = ComponentProps<Tag> & {
  variant: TypographyVariant;
  as?: TypographyTag;
  children: ReactNode;
};

export const Typography = <Tag extends TypographyTag = 'div'>({
  variant,
  as = 'div',
  children,
  className,
  ...props
}: TypographyProps<Tag>) => {
  const Component = as as string;

  return (
    <Component
      className={clsx(variant, className)}
      {...props}
    >
      test
      {children}
    </Component>
  );
};

File use Typography

import { Typography } from '@/shared/ui/typography';

export const Main = () => {
  return (
    <div className="flex flex-col gap-10">
      <Typography
        variant="title"
        as="h1"
      >
        Hello
      </Typography>
    </div>
  );
};

enter image description here

showing the sum of the digits in JS

I get a number from the user and i want to calculate the sum of its digits. here’s the code:

let num = Number(prompt("Enter a number to see the sum of its digits:"));
if (isNaN(num)) {
    alert("please enter a number");
} else {
    let sum = 0;
    for (let i = 0; i < num.length; i++) {
        sum = sum + num[i];
    }
    console.log(sum);
    alert("The result is : " + sum);
}

the program resulted in 0 number as the sum of digits and it’s, it’s just not working