Can Azure Functions prevent Heap Overflow attacks?

We are providing a typescript-based Azure Function to which customers can send their own js scripts to be executed at a later time.

If these customer scripts were to contain malicious code such as infinite loops trying to overflow the function’s heap, how would this affect our Service?

Would Azure just spawn another instance to keep our service available?

How to Resolve DOMException When Decrypting Files with Web Crypto API in a Streaming Manner?

I m trying to encrypt file in browser uisng webcrypto api. I m using chunking mechanism too so that i can encrypt and decrypt large files without crashing browser.

My provided code is working if i m not using chunking mechanism or the file size is less than chunk size ie 1 MB as it wont go to else part anyway

Please help me with it.

Code for encryption:

<!DOCTYPE html>
<html>
   <head>
      <title>Large File Encryption</title>
   </head>
   <body>
      <input type="file" id="fileInput" >
      <button id="encryptButton">Encrypt</button>
      <a id="downloadLink" style="display: none" download="encrypted-file.txt">Download Encrypted File</a>
      <script>
             // event listener which will listen to encrypt button
         document.getElementById("encryptButton").addEventListener("click", async () => {
             const fileInput = document.getElementById("fileInput");
             const file = fileInput.files[0];
             if (!file) {
                 alert("Please select a file.");
                 return;
             }
                
                    
             const chunkSize = 1024 * 1024; // 1 MB chunks
              
             // generating keys 
             const key = await window.crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt","decrypt"]);
         
             const keyData = await window.crypto.subtle.exportKey('jwk', key);
         
         // Create a data blob with the key data
         const keyBlob = new Blob([JSON.stringify(keyData)], { type: 'application/json' });
         
         // Create a download link for the key
         const keyUrl = URL.createObjectURL(keyBlob);
         const downloadLink = document.createElement('a');
         downloadLink.href = keyUrl;
         downloadLink.download = 'encryption-key.json';
         downloadLink.click();
         
         const iv=new Uint8Array(12);
    
         
         
         
         
             const reader = new FileReader();
              
              // chunks will be pushed in this array
             const fileData = [];
             let offset = 0;
         
             reader.onload = async function () {
                 const chunk = new Uint8Array(reader.result);
                          
                 // encrypting the chunk using AES-GCM alogorithm
                 const encryptedChunk = await window.crypto.subtle.encrypt(
                     { name: "AES-GCM", iv },
                     key,
                     chunk
                 );
                 
                 // pushing the chunk
                 fileData.push(encryptedChunk);
                 // updating offset
                 offset += chunk.length;
                            
                 // if remaining chunks are left to be read and encrypted           
                 if (offset < file.size) {
                     // calling readslice function to start reading remaining chunks
                     readSlice(offset);
                 } else {
                     // All chunks are encrypted; combine them and provide a download link.
                     const encryptedData = new Blob(fileData, { type: file.type });
                     const url = URL.createObjectURL(encryptedData);
                     const downloadLink = document.getElementById("downloadLink");
                     downloadLink.href = url;
                     downloadLink.style.display = "block";
                     console.log('finished')
                 }
             };
                    
             function readSlice(offset) {
                 // taking part of file
                 const slice = file.slice(offset, offset + chunkSize);
                 // to initiate reading the part of file
                 reader.readAsArrayBuffer(slice);
             }
         
             readSlice(0);
         });
      </script>
   </body>
</html>

 
Code for decryption

<!DOCTYPE html>
<html>
<head>
  <title>File Decryption</title>
</head>
<body>
  <h1>File Decryption</h1>
  
  <!-- Input for the encrypted file -->
  <input type="file" id="encryptedFileInput"  />
  
  <!-- Input for the encryption key (as JSON) -->
  <input type="file" id="keyInput" accept=".json" />
  
  
  
  <button id="decryptButton">Decrypt</button>
  
  <a id="downloadLink" style="display: none;">Download Decrypted File</a>
  
  <script>
    document.getElementById("decryptButton").addEventListener("click", async () => {
      // Get the encrypted file
      const encryptedFileInput = document.getElementById("encryptedFileInput");
      const encryptedFile = encryptedFileInput.files[0];
      
      // Get the encryption key 
      const keyInput = document.getElementById("keyInput");
      
      
      const keyFile = keyInput.files[0];
      
      
      if (!encryptedFile || !keyFile ) {
        alert("Please select the encrypted file and  key.");
        return;
      }
      
      // Read the key and IV as JSON
      const keyData = await keyFile.text();
   
      
      // Convert the JSON data to JavaScript objects
      const keyObj = JSON.parse(keyData);
      

     



const importAlgorithm = {
  name: "AES-GCM"
};


const keyUsage = ["encrypt","decrypt"];
            
     // importing the jwk key 
      const key = await crypto.subtle.importKey("jwk", keyObj, importAlgorithm, false, keyUsage)

      // 1 mb( chunk size while encrypting + 12 bytes(iv size in bytes) ) 
      const chunkSize= (1024*1024)+12
      
      // also tried with
      // const chunkSize= (1024*1024)
      // but no luck


       const reader = new FileReader();
            const fileData = [];
            let offset = 0;

        reader.onload = async function () {
          console.log('chunk loaded')
                const chunk = new Uint8Array(reader.result);
                const decryptedChunk = await window.crypto.subtle.decrypt(
                    { name: "AES-GCM", iv: new Uint8Array(12) },
                    key,
                    chunk
                );
                fileData.push(decryptedChunk);
                offset += chunk.length;

                if (offset < encryptedFile.size) {
                    readSlice(offset);
                } else {
                    // All chunks are decrypted; combine them and provide a download link.
                    const decryptedData = new Blob(fileData, { type: encryptedFile.type });
                    const url = URL.createObjectURL(decryptedData);
                    const downloadLink = document.getElementById("downloadLink");
                    downloadLink.href = url;
                    downloadLink.download="someting.dec"
                    downloadLink.style.display = "block";
                    downloadLink.click()
                    console.log('finished')
                }
            };

            function readSlice(offset) {
                const slice = encryptedFile.slice(offset, offset + chunkSize);
                reader.readAsArrayBuffer(slice);
            }

            readSlice(0);









      
    
    });
  </script>
</body>
</html>

For the file above 1MB(aka when chunking mechanism is used) i m getting the following error

DOMException: The operation failed for an operation-specific reason

I tried to simply decrypt without using chunks but still i m facing error. Maybe there is some issue with encryption part. I expect that just like the code works for file size less than 1 MB which is chunk size, it works too by encrypting and decrypting properly chunk by chunk.

Comparing times only within an interval in js

I am trying to compare only time (regardless of the date) in js. First I need a way to compare times so I came across the luxon library which works well.

But, there is a problem when comparing intervals across midnight. For example: 20:00 < 01:00 < 10:00 should evaluate to true, the luxon’s library returns a false. Which makes sense because 20:00 < 01:00 can evaluate differently when in different intervals. These is what I would be expecting:

20:00 < 01:00 < 10:00 == true // but it evaluates as false using luxon's interval

00:00 < 01:00 < 10:00 == true

This is the code I have so far:

const from = DateTime.fromISO('20:00');
const to = DateTime.fromISO('10:00');
const value = DateTime.fromISO('01:00');

const interval = Interval.fromDateTimes(from, to);

console.log(interval.contains(valueTime)); // returns false instead of true

“[object Object]” is not valid JSON [closed]

Hello I am getting this error when trying to fetchAPI of products and display them on my page. I got an object from the API but unable to use the map function to display them.

import * as React from 'react';
import { useEffect, useState } from "react";
import ProductItem from './ProductItem';

export default function LatestProducts() {
    const [products, setProducts] = useState([]);

    const fetchApi = async (url, body) => {
        const response = await fetch(url, body);

        const data = await response.json();

        return data;
    }


    useEffect(() => {
        const fetchProducts = () => {
            fetchApi("http://localhost:8000/product")
                .then((data) => {
                    console.log(data);
                    const products = JSON.parse(data);
                    setProducts(products);
                    console.log(typeof products);
                })
                .catch((error) => {
                    console.log(error.message);
                })
        }
        fetchProducts();
    }, []);

    return (
        <>
            <div className='row'>
                {products.map((product, index) => (
                    <ProductItem key={index}>
                        name={product.Name}
                        imageUrl={product.ImageUrl}
                        description={product.Description}
                        type={product.Type}
                        price={product.PromotionPrice}
                    </ProductItem>
                ))}
            </div>
        </>
    )
}

here is the object I got

I have tried JSON.parse(data) to change the above object to array but get the error Object is not valid JSON

How to build a tree from flat array of objects

I am trying to build a tree array from a flat array of objects.
The category field is structured as an array because it can have n categories

let data = [
  {
    category: [
      "Kat1"
    ],
    otherFields: [
      "Document 1"
    ]
  },
  {
    category: [
      "Kat1"
    ],
    otherFields: [
      "Document 2"
    ]
  },
  {
    category: [
      "Test",
      "Test 2"
    ],
    otherFields: [
      "Document 1"
    ]
  },
  {
    category: [
      "Test",
      "Test 2",
      "Test 3",
      "Test 4",
      "Test 5",
      "Test 6",
      "Test 7",
      "Test 8",
      "Test 9",
      "Test 10",
      "Test 11"
    ],
    otherFields: [
      "Document 1"
    ]
  }
]

It should be

let tree = [
  {
    label: "Kat1",
    children: [
      { label: "Document 1" },
      { label: "Document 2" },
    ]
  },
  {
    label: "Test",
    children: [
      { 
        label: "Test 2",
        children: [
          { label: "Document 1" },
          { 
            label: 'Test 3',
            children: [
              { 
                label: 'Test 4', 
                children: [
                  ...
                ]
              }
            ]
          }
        ]
      },
    ]
  }
]

Is there any article, link solving similar problem? In my last attempt I only got the main categories I fail every time at the documents and sub categories

How to render nothing on place of specific mesh in three js?

I am trying to do such thing: a 3d model of a laptop is opening and after it is opened user is able to see html content on display.
So i need to know how to do next: when a camera doesn’t see a mesh of a display everything renders as usual, but when it sees a mesh of display it doesn’t render it and anything behind it, leaving empty space in shape of a display mesh.
Note: i am writing code on vanilla js.

I tried to do this with portals but i think they won’t help me

My python code seems fine but the input function in the while loop seems to have a problem. A none is displayed in the terminal before accepting input

import random

compnum = random.randint(1,10)
userinput = “”

while userinput != “c”:
print(f”My guess is {compnum}”)
userinput = input(print(“Im I correct…? ‘l’ for low, ‘h’ for high and ‘c’ for correctn”))

if userinput == "l":
    compnum = compnum + 1

elif userinput == "h":
    compnum = compnum - 1

else:
print(f”Yes i guessed your number {compnum} correctly!!”)

I tried running it in the terminal but it shows python not found when i actually installed it and have been running other files in vs code and they were working well

how to set conditional render in nested array in react

I would like to set a conditional rendering in array. If user input “Open” in text box, it cannot render a button automatically. It only render for initial first time.

Also, React useState / setstate seem to be not suitable for array. Any other suggestion can implement for it?

Expected result will be render a button automatically when user input “Open” in any sub array list

Here is codesandbox

meteor run android, got this errorAndroid target: Command failed with ENOENT: avdmanager list target spawn avdmanager ENOENT

meteor run android

Your system does not yet seem to fulfill all requirements to build apps for Android.

Please follow the installation instructions in the mobile guide:
http://guide.meteor.com/cordova.html#installing-prerequisites

Status of the individual requirements:
✓ Java JDK
✓ Android SDK
✗ Android target: Command failed with ENOENT: avdmanager list target
spawn avdmanager ENOENT
✓ Gradle

i already searched on google and try to add export ANDROID_HOME=${HOME}/Android/Sdk export PATH=${PATH}:${ANDROID_HOME}/tools export PATH=${PATH}:${ANDROID_HOME}/platform-tools

does any body know how?

Should class variables be initilized before subscribe method or after in Angular

I have the method getAllDates that appends (inside the next handler) all the schedule dates from the server to class scope array variable this.futureScheduleDateStrings. My question is – should I initialize that array to empty content before subscribe method or at the beginning of the next handler – I have noticed that if I initialize it before subscribe it has some duplicates values.

getAllDates() {
    this.futureScheduleDateStrings = [];
    this.accountService.getAllDates()
      .pipe(first())
      .subscribe({
        next: (value: ScheduleDateTimes) => {
          //this.futureScheduleDateStrings = [];
          this.scheduleDateTime = value.scheduleDateTimes;

          ...
        },
        error: error => {
          console.log();
        }
      });

Problem parsing Javascript containing backtick with js2xml

I’m using Python/js2xml to parse JavaScript from a webpage but I’m getting an error message due to the inclusion of backticks in the JavaScript for example…

htmlBlock = `<option disabled selected value="0">Select lesson...</option>`;

…is raising the following error…

Traceback (most recent call last):
  File "Z:course_to_course_pkl.py", line 71, in <module>
    course_admin_parsed = js2xml.parse(course_admin_js) # js_course_structure.txt
  File "C:Program FilesPython311Libsite-packagesjs2xml__init__.py", line 17, in parse
    tree = _parser.parse(text, debug=debug)
  File "C:Program FilesPython311Libsite-packagescalmjsparseparserses5.py", line 115, in parse
    return self.parser.parse(
  File "C:Program FilesPython311Libsite-packagesplyyacc.py", line 331, in parse
    return self.parseopt(input, lexer, debug, tracking, tokenfunc)
  File "C:Program FilesPython311Libsite-packagesplyyacc.py", line 757, in parseopt
    lookahead = get_token()     # Get the next token
  File "C:Program FilesPython311Libsite-packagescalmjsparselexerses5.py", line 290, in _token
    tok = self._get_update_token()
  File "C:Program FilesPython311Libsite-packagescalmjsparselexerses5.py", line 355, in _get_update_token
    self._set_tokens(self.get_lexer_token())
  File "C:Program FilesPython311Libsite-packagescalmjsparselexerses5.py", line 242, in get_lexer_token
    token = self.lexer.token()
  File "C:Program FilesPython311Libsite-packagesplylex.py", line 386, in token
    newtok = self.lexerrorf(tok)
  File "C:Program FilesPython311Libsite-packagescalmjsparselexerses5.py", line 687, in t_error
    raise ECMASyntaxError(
calmjs.parse.exceptions.ECMASyntaxError: Illegal character '`' at 1299:23 after '=' at 1299:21

I can’t seem to find a solution – I’ve tried looking through the calmjs package to see if I can simply add the backtick in the list of recognised characters but it’s beyond me.

backslash in string json apiproperty

I try to create api and i stuck in a problem with backslash in filepath field(?)

here is a snippet of my code:

`@IsNotEmpty()
@IsString()
@ApiProperty({
  description: 'Path to .md file with data',
  type: String,
  example: "c:Usersivanov_iinotesnote1.md"
})
pathToFile: string;`

I need to get output of “example” in swagger like in apiproperty, but i get this:
“pathToFile”: “c:Usersivanov_iinotesnote1.md”

I tried different ways with double backslash or quotes, but i don’t get what i need.
output with double backslashes: “pathToFile”: “c:Usersivanov_iinotesnote1.md”

Cracking a Bitwise cipher

    var reverse_flag = [-63, -105, -103, -121, -95, -73, -39, -101, -83, -29, -125, -121, -95, -73, -225, -203, -213, -223, -213, -119];
    function check_flag()
    {
        var i, flag = document.getElementById('flag').value;
        if(flag.length != reverse_flag.length)
            return false;
        for(i=0;i<flag.length;i++)
        {
            var code = flag.charCodeAt(i);
            code = code<<1;
            code ^= 0xba;
            code = ~code;
            if(code != reverse_flag[i])
                return false;
        }
        return true;
    }

The Answer is checked via Form

    <form method="post" id="form"><input type="password" id="flag" name="flag"><input type="submit" value="Check" onclick="return check_flag()"></form>

In my Uni we have recently started this Bitwise topic, and as the first hometask we are given the cipher mentioned beforehand. I’ve read all the documentation there is about Javascript Bitwise but I am failing to understand what it has to do with this.

If anybody knows, how do you need to approach this question? And what books/ articles would you advise to crack such stuff?

Thank you in advance

Positions where #__PURE__ is meaningful/useful

https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free says

It is possible to tell webpack that a function call is side-effect-free (pure) by using the /*#__PURE__*/ annotation. It can be put in front of function calls to mark them as side-effect-free. Arguments passed to the function are not being marked by the annotation and may need to be marked individually. When the initial value in a variable declaration of an unused variable is considered as side-effect-free (pure), it is getting marked as dead code, not executed and dropped by the minimizer.

My questions:

  1. When is it useful to mark arguments as pure? Naively it seems we can either find the variable is unused and exclude it, or not. But I can’t think of a case where we could shake only some arguments.

  2. If I have

    const shape = /*#__PURE__*/ PropTypes.shape({
      x: PropTypes.array(...),
      ...
    });
    

    can it be useful to mark the PropTypes.array call as well? I don’t believe marking the argument of shape would have any effect since it isn’t a function call.

  3. Does export default /*#__PURE__*/ withSomeHOC(withAnotherHOC(...)) work as expected, or does it need to be written as

    const Component = /*#__PURE__*/ withSomeHOC(withAnotherHOC(...));
    export default Component;
    

    instead?

I have tested in some specific cases, but wanted to get a general answer. I’m focusing on Webpack, but answers for other bundlers are welcome as well.