How to print page exactly it looks on screen using window.print()?

I have designed a form for my project and I want to print the form. The form looks like below:
Actual Form

I was trying to use window.print() method to print it. But it changed the style in print preview like below: print preview

Here’s my code that I’ve done. Let me know if there any possible way to solve this issue and print exactly it shown in the window. Thanks in advance.

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <title></title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
    <link rel="stylesheet" type="text/css" href="Registrationform.css">
</head>
<body>



<div style="width:670px; padding:30px; box-shadow: 5px 5px 5px 5px #888888;" class="container">
        <table style="margin: auto;">
            <tr>
                <td><img width="60px" height="60px" src="imagesNSTU-logo.png"></td>
                <td>
                <div class = "header-name">
                <h6 style="text-align: center; margin: 0 auto;">NOAKHALI SCIENCE AND TECHNOLOGY UNIVERSITY</h6>
                <p style="text-align: center; margin:auto;">Noakhali-3814, Bangladesh</p>
                <h6 style="text-align: center;margin: auto;">COURSE REGISTRATION FORM</h6>
                </div>
            </td>
            </tr>
        </table>
        <hr>
        

    
        <form action="" method="POST">
            <!-- <div style=" align-content: center;" class = "std-header-info"> -->
                 <div>
                     <label>Name</label>
                     <input class="text" style = "width: 365px; text-align: center;" type="text" id = 'name' placeholder="" value="Khair" readonly>
                     <label>Roll</label>
                     <input class="text" style = "width: 160px; text-align: center;" type="text" id = 'roll' placeholder="" value="12" readonly> <br>
                 </div>
                 <div>
                    <label>Department</label>
                     <input class="text" style = "width: 230px; text-align: center;" type="text" id = 'department' placeholder="" value="IIT" readonly>
                     <label>Institute/Faculty</label>
                     <input class="text" style = "width: 165px; text-align: center;" type="text" id = 'institute' placeholder="" value="IIT" readonly>
                     <br/>
                 </div>

                 <div>
                     <label>Year</label>
                     <input class="text" style = "width: 120px; text-align: center;" type="text" id = 'year' placeholder="" value="2012" readonly>
                     <input type="hidden" name="year" value="" />

                     <label>Term</label>
                     <input class="text" style = "width: 150px; text-align: center;" type="text" id = 'term' placeholder="" value="2" readonly>

                     <label>Session</label>
                     <input class="text" style = "width: 200px; text-align: center;" type="text" id = 'session' placeholder="" value="2017" readonly>
                 </div>
                 <br/>


            


                 <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Course Code</th>
                                <th>Course Title</th>
                                <th>Credits</th>
                                <th>Remarks</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            
                        </tbody>
                    </table>
                 </div>
                 
                 <div>
                     <table style="font-size: 10px;" class="table table-bordered" id="table">
                        <tr class="borderless">
                            <td style="border: none;"></td>
                            <td style="border: none;"></td>
                            <td colspan="2">Year 1</td>
                            <td colspan="2">Year 2</td>
                            <td colspan="2">Year 3</td>
                            <td colspan="2">Year 4</td>
                            <td colspan="2">Year 5</td>
                        </tr>
                        <tr style="font-size: 8px">
                            <td style="border: none;"></td>
                            <td style="border: none;"></td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                        </tr>
                     
                        <tr>
                            <td colspan="2">Credit <br> Completed </td> 
                            
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">GPA</td>
                            <td>3.23</td>
                            <td>3.21</td>
                            <td>3.43</td>
                            <td>3.52</td>
                            <td>3.12</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>

                        </tr>

                     </table>
                 </div>
</form>
</div>

<script type="text/javascript">
    window.print()
</script>
</body>
</html> 

threejs 3d model textures not loading

hey guys i am new to threejs and i am trying to load a 3d animated model with textures, but i am facing issues trying to do so as the textures are not loading into gltf. both the files are in textures folder while index.html is in the main folder. thanks in advance!

textures/Material_diffuse.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

textures/Material_specularGlossiness.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <!-- <script src="three.js"></script> -->
    <!-- <script type="module" src="GLTFLoader.js"></script>  -->
    <script type="module">
      import * as THREE from 'https://cdn.skypack.dev/[email protected]/build/three.module.js';
      import { GLTFLoader } from 'https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js';

      var scene = new THREE.Scene();

      var camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.01,
        1000
      );
      var renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      var loader = new GLTFLoader();

      var obj;
      loader.load("scene.gltf", function (gltf) {
        obj = gltf.scene;
        scene.add(gltf.scene);
      });
      scene.background = new THREE.Color(0xffffff);
      var light = new THREE.HemisphereLight(0xffffff, 0x444444);
      scene.add(light);
      // camera.position.set(0, 5, 30);
      camera.position.set(0, 5, 20);

      function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
      }
      animate(); 

      function rotateFunction() {
        obj.rotation.y += 0.01;
      }

     document.addEventListener('scroll', function(e) { rotateFunction() });
    </script>
    <div>
      
    </div>
  </body>
</html>

Make fake multilanguage subfolders for website

I’d like to know if it is possible to make fake subfolders for my multilanguage website, right now I use this code to switch between the two languages I have (Italian and English)

<?php
session_start();

$langs = [ "en", "it" ];

$current_lang = "en";

if (isset($_GET["lang"]))
{
    $lang = $_GET["lang"];
    if (in_array($lang, $langs, true))
        $current_lang = $lang;
    
}
elseif (!isset($_SESSION["lang"]))
{
    
    if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
    {
        $acceptLang = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
        if (strlen($acceptLang) > 2)
        {
            $acceptLang = strtolower(substr($acceptLang, 0, 2));
            if (in_array($acceptLang, $langs, true))
                $current_lang = $acceptLang;
        }
    }
}
else
    $current_lang = $_SESSION["lang"];

$_SESSION["lang"] = $current_lang;


require_once "languages/$current_lang.php";
?>

So whenever I want to switch language I add to the end of the URL ?lang=neededLanguage.php

I also use these rewrite rules to hide the .php

Options +SymLinksIfOwnerMatch 

RewriteEngine on

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

This is what I have to do to switch language right now:
https://example.com/?lang=en
https://example.com/blog?lang=en

I’d like to know if it’s possible to make the previous two URLs look something like these:
https://example.com/en/
https://example.com/en/blog

Nodejs error “Callback was already called error.”

For some reason, this part of the code is causing a callback is already called issue, if it does not enter the “if” loop, it returns accurately. Unable to figure out why it partially works.
Why are the return statements acting differently?

   **if (!args.is_table) {
      return cbk(null, {peers: forwards.peers});
    }**

Here’s the error:

***if (fn === null) throw new Error("Callback was already called.");
                         ^
Error: Callback was already called.***



module.exports = (args, cbk) => {
  return new Promise((resolve, reject) => {
    return asyncAuto({

      // Final forwards table
      allForwards: ['forwards', ({forwards}, cbk) => {
        if (!args.is_table) {
          return cbk(null, {peers: forwards.peers});
        }

        const isWideSize = !size || size.get().width > wideSizeCols;

        return cbk(null, {
          peers: forwards.peers,
          rows: []
            .concat([notNull([
              'Alias',
              'Earned In',
              'Earned Out',
              'Inbound',
              'Outbound',
              !!isWideSize ? 'Public Key' : null,
            ]).map(n => !args.is_monochrome ? bold(n) : n)])
            .concat(forwards.peers.map(peer => {
              return notNull([
                chartAliasForPeer({
                  alias: peer.alias,
                  icons: peer.icons,
                  is_disconnected: peer.is_disconnected,
                  is_forwarding: peer.is_forwarding,
                  is_inactive: peer.is_inactive,
                  is_pending: peer.is_pending,
                  is_private: peer.is_private,
                  public_key: peer.public_key,
                }).display,
                formatTokens({
                  is_monochrome: args.is_monochrome,
                  tokens: peer.liquidity_outbound,
                }).display,
                !!isWideSize ? peer.public_key : null,
              ]);
            })),
        });
      }],
    },
    returnResult({reject, resolve, of: 'allForwards'}, cbk));
  });
};

Trying to get the SearchBar to get data from the API

Forgive me if the formatting didnt work. I am trying to use the SearchBar to get the data from the API. (left the AAPL symbol as an example) I would like I am missing something and cant quite figure it out. How can I get this to work? Any assistance to my first post is greatly appreciated.

import axios from "axios";

function SearchBar() {
  const [value, setValue] = useState("");
  // const [data, setData] = useState([]);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("form submitted", value);
  };
useEffect(() => {
   
      .get(`https://api.twelvedata.com/symbol_search?symbol=AAPL`)
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);


  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>Search:</label>
        <input type="text" value={value} onChange={handleChange}></input>
        <button type="submit" value={handleSubmit}>
          Submit
        </button>
      </form>
      {/*value from form so that works from display*/}
      <div>{value}</div>
    </div>
  );
}

export default SearchBar;```

Forward console to channel discord.js

I am trying to forward my bot’s console to a channel in Discord. I assume I would use process.stdout to get the console output, and client.channels.cache.get(id).send() to send the message, but how do I combine the two and send that to a channel?

Any help is appreciated, cheers!

Getting a bytecode error when packaging javascript

Hey so I am trying to package my node javascript application with pkg on my mac, but I keep getting met with a codesign utility error?

**Error! Cannot generate bytecode

pkg fails to run “codesign” utility. Due to the mandatory signing
requirement of macOS, executables must be signed. Please ensure the
utility is installed and properly configured.**

Also only trying to get this as a runnable file, not put it on the mac store or anything.

I have an error in my school javascript project

I have multiple errors in my code. When I run the code, it gives an error saying that there is an unexpected identifier. Here is the full error, “SyntaxError: Unexpected identifier at /script.js:46:16”. However, when I check through lines 46 through 16, I cant find any unclosed functions or methods. When I comment the if statement on line 46, it just gives an error on the other if statement. can someone help me.

Heres the code

function print(str){
    console.log(str)

}

function farhToKelvin(far){
    const cel = Math.floor(far / (9/5) - 32)
    const kel = cel + 273
    return kel

}

function farhToCelsius(far){
    const cel = Math.floor(far / (9/5) - 32)
    return cel

}

function convertToFarh(type, val){
    
    type.toLowerCase()
    val.toLowerCase()

    if (type == "kelvin"){
        return Math.floor(far / (9/5) - 32 - 273) 

    }
    else if(type == "celsius"){
        return Math.floor(far / (9/5) - 32)

    }

}


while (farh != "exit"){
    var farh = prompt("enter a farhanhite tempature: ")

    var type = prompt("convert it to celsius, or kelvin")

    type.toLowerCase()

    if (type == "celsius"){
        const c = farhToCelsius(farh)
        var val = convertToFarh(c)
        if (val > 50 or val == 50){
            print("it is cold, you should wear a coat")

        }
        if (val > 50 or val == 50){
            print("it is hot, you should wear a tank top")

        }

    }
    else if(type == "kelvin"){
        const k = farhToKelvin(farh)

        var val = convertToFarh(k)
        if (val > 50 or val == 50){
            print("it is cold, you should wear a coat")

        }
        if (val > 50 or val == 50){
            print("it is hot, you should wear a tank top")

        }

    }

}

Disabling a tablerow in react

When a user clicks a line on a tablerow on my website, it displays another page with a different table row. Here’s my code where I display the second mentioned table row:

        return (
            <>
            <TableRow key={this.props.rowData.dependency_id} onClick={() => this.setOpen(!this.state.isOpen)}>
                <TableCell>{this.props.rowData.name}</TableCell>
                <TableCell>{this.props.rowData.component}</TableCell>
                <TableCell>{this.props.rowData.version}</TableCell>
                <TableCell>{this.stringify_licenses(this.props.rowData.licenses)}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numLowVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numMediumVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numHighVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numCriticalVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.totalNumVulnerabilities}</TableCell>
                <TableCell>
                    {this.state.isOpen ? <FaAngleUp/> : <FaAngleDown/>}
                </TableCell>
            </TableRow>

I want to disable this table row if the line on the first table row has a certain tablecell value. How can I do this?

Why is <= returning false not true? [closed]

Hey so i have a little problem, which one is blowing my mind. maybe someone will enlighten me with this, because im done.

Here is code

function cashOut() {
  if (cashAmount.value<=cash && cashAmount.value % 50 === 0) {
        outCash.innerHTML = "Withdraw: " + cashAmount.value + "USD";
        withdrawCash = cashAmount.value;
    } else {outCash.innerHTML = "Failed to withdraw funds, the amount withdrawn must be divisible by 50 and not less than  " + cash;
    }
}

and problem is that cashAmount.value<=cash returns false not true as it should. Because your cashAmount which is amount of cash you want to withdraw, cant be bigger then your balance. I guess its stupid question but i lost my mind on this.

cash is simple variable, but cashAmount is taking value from input if that matters.

Trying to upload a ScreenCapture Video (JavaScript) onto a server (Java)

i wanted to write a javascript function that records the screen of the user and saves it onto a server.

It seems to work so far and records the user-selected screen (i printed most variables into the console for testing purpose but here deleted it for clarity, the ids etc are filled), but there is a problem when i am trying to upload it.

Since i am new to JavaScript programming, i seem to be stuck now, i tried to change mimeTypes/types in ajax since i am not sure if they are used right, did not help.

I run the JavaScript frontend on a local XAMPP and the Java backend on a local WildFly.

Would be so glad if anyone got helping ideas.

The code i wrote is integrated into a existing project, i will post the snippets i wrote.

1)

 // Create Recorder

var recorder;
var stream;
var chunks = [];
var blob = new Blob;
var start_recording_timestamp ;


this.startIntegratedScreenCapture = async function () {

    start_recording_timestamp = new Date(new Date().getTime() + 3600000).toISOString(); //add 1 hour because of Berlin-Timezone

   try {
        stream = await navigator.mediaDevices.getDisplayMedia({
            video: {mediaSource: "screen"},
            mimeType: 'video/webm;codecs=h264'
        });

    recorder = new MediaRecorder(stream);

    recorder.ondataavailable = e => chunks.push(e.data);
    recorder.onstop = e => {
        let that = this;
        blob = new Blob(chunks, { type: chunks[0].type });
      
        window.repositoryService.saveVideoForModel(window.modelId, start_recording_timestamp, blob);
        that.videoSaveCallbacks.forEach(callback => callback(blob));
    };

    recorder.start();

    }
    catch(e){console.log(e)}
};
     //stop Recording



 this.stopIntegratedScreenCapture = function () {
    if (recorder) {
  recorder.stop();
  stream.getVideoTracks()[0].stop();
    }

};
  // Integrated Screen Capture



this.saveVideoForModel = function (modelID, timestamp, video_content) {

    var reader = new  FileReader();

    reader.addEventListener('loadend', (event) => {
        var videoAsJSON = event.srcElement.result;
        var videoURI = this.videoURI;

        var data = new FormData();
      data.append("data", new Blob([videoAsJSON], {type: "application/octet-stream"}));
        data.append("modelID", modelID);
        data.append("startRecTimestamp", timestamp);


        this.uploadVideo("POST", videoURI, data, function (response) {
            try {
                response = JSON.parse(response);
            } catch (event) {
            }
            if (response === null || response === "") {
                window.showMessage("Error saving the video", "error", "Error");
                return;
            }
            window.showMessage("Video of model " + modelID + " successfully saved", "success", "Success");
        },function (error){console.log(error)});

    });

    reader.readAsArrayBuffer(video_content);
};
  1. //start upload
    
    
    
    
     this.uploadVideo = function (method, url, data, success, error) {
      var errorHandler = (error != null) ? error : this.defaultErrorHandler;
      var token = this.getToken();
      url = method === "DELETE" ? url + "?" + $.param(data) : url;
    
    
      $.ajax({
          url: url,
          type: method,
          data: data,
          enctype: 'multipart/form-data',
          cache: false,
          async: true,
          processData: false,
          contentType: false,
          beforeSend: function (xhr) {
              if (token != null) {
                  xhr.setRequestHeader("Authentication", "Bearer" + token);
              }
          },
          success: success,
          error: errorHandler
      }
      ).done(function(data){console.log(data)});
    

    };

The serverside code looks like this, it uses Spring framework:

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/integrated/saveVideo", method = 
     RequestMethod.POST)
     public ResponseEntity<VideoDto> saveVideo(@RequestParam("data") 
      MultipartFile file,
                                          @RequestParam("modelID") 
      String modelID,
                                          
     @RequestParam("startRecTimestamp") String startRecTimestamp) {
    HttpStatus status = HttpStatus.OK;
    startRecTimestamp = startRecTimestamp.replaceAll(":", "_");
    String fileName = env.getProperty("screenrecording.directory") + 
    modelID + "_Model_" + startRecTimestamp;
    try (FileOutputStream fosVideo = new FileOutputStream(fileName, 
   true)){
        byte[] bytes = file.getBytes();
        fosVideo.write(bytes);
    } catch (IOException ioe) {
        status = HttpStatus.CONFLICT;
        ioe.printStackTrace();
    }
    return new ResponseEntity<>(new VideoDto(), status);
}   

When i use developer mode in firefox, i see that the program seems to fail at the axaj query (the beforeSend in the ajax gets triggered, tried it with console.log to see if token has id)

The FunctionReponse gets not triggered using uploadVideo function in saveVideoForModel since uploadVideo function ends in error.

       Status
       409
         Conflict
       VersionHTTP/1.1
   Referrer Policystrict-origin-when-cross-origin

XHRPOST../saveVideo
[HTTP/1.1 409 Conflict 610ms]

POST
…/saveVideo
Status
409
Conflict
VersionHTTP/1.1
Übertragen533 B (81 B Größe)
Referrer Policystrict-origin-when-cross-origin

HTTP/1.1 409 Conflict

Expires: 0

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

X-XSS-Protection: 1; mode=block

Pragma: no-cache

X-Frame-Options: DENY

Date: Mon, 29 Nov 2021 23:31:07 GMT

Connection: keep-alive

Access-Control-Allow-Origin: *

Vary: Origin

Vary: Access-Control-Request-Method

Vary: Access-Control-Request-Headers

X-Content-Type-Options: nosniff

Transfer-Encoding: chunked

Content-Type: application/json; charset=UTF-8








   XHRPOST.../saveVideo
   [HTTP/1.1 409 Conflict 610ms]

    
   POST
    .../saveVideo
  Status
   409
  Conflict
   VersionHTTP/1.1
  Übertragen533 B (81 B Größe)
   Referrer Policystrict-origin-when-cross-origin
        
    HTTP/1.1 409 Conflict

    Expires: 0

    Cache-Control: no-cache, no-store, max-age=0, must-revalidate

    X-XSS-Protection: 1; mode=block

    Pragma: no-cache

    X-Frame-Options: DENY

    Date: Mon, 29 Nov 2021 23:31:07 GMT

    Connection: keep-alive

    Access-Control-Allow-Origin: *

    Vary: Origin

    Vary: Access-Control-Request-Method

    Vary: Access-Control-Request-Headers

    X-Content-Type-Options: nosniff

    Transfer-Encoding: chunked

    Content-Type: application/json; charset=UTF-8
        
    POST ...saveVideo HTTP/1.1

    Host: localhost:8080

    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0

    Accept: */*

    Accept-Language: de,en-US;q=0.7,en;q=0.3

    Accept-Encoding: gzip, deflate

    Authentication: BearereyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwcm9iYW5kIiwiZXhwIjoxNjM4Mjc1ODU0fQ.dy-e-gJtD3R-UlPD9FVnJ5YQmjko7tEqS-l9ocprk9vRpCXUKjelL78mafe9zTKJlDo_c8pElbiQWKdGIbfapw

    Content-Type: multipart/form-data; boundary=---------------------------188953772220050190214011980307

    Content-Length: 1090343

    Origin: http://localhost

    Connection: keep-alive

    Referer: http://localhost/

    Sec-Fetch-Dest: empty

    Sec-Fetch-Mode: cors

    Sec-Fetch-Site: cross-site

JSON is not properly turning an object into a string

I am making a game and am working on the accounts. When i have JSON stringify the object and save it to a file, it sometimes (occasionally and at random) writes:

{"[email protected]":{"email":"[email protected]","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >}< "[email protected]":{"email":"[email protected]","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}

when i am expecting:

{"[email protected]":{"email":"[email protected]","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >,< "[email protected]":{"email":"[email protected]","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}

My Code:

fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {});

What is going on?

How Node JS Map Of Values Adds Up to K

Given a list of numbers const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];and a number k say const k = 17;, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k = 17, we should return True, since 10 + 7 =17.

Wrote below code using key,values in Map,but seems not able to get the solution,can anyone suggest what code change is needed below ,want to solve especially using Maps

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
const k = 17;
let addInput = new Map(arr.flatMap((x) => Object.entries(x)));

addInput.forEach((v) => {
  for (var i = 0; i < addInput.size; i++) {
    if (v != addInput[i]) {
      if (addInput[i] + v == k) {
        console.log(`${v} + ${addInput[i]} = ${k} (true)`);
      }
    }
  }
});

Sort by date with isotope-layout in Next js

I can’t find any documentation on how to do a date sort with isotope-layout in my Next JS project. Here is how far I have got.
The date obviosuly sorts but it will sort alphabetically. I need to know how to write this in
date: function ($elem) { return Date.parse($elem.find('.date').text()); }

const KeyOutcomes = (props) => {
  const isotope = useRef()
  const [sortKey, setSortKey] = useState('date')

  // initialize an Isotope object with configs
  useEffect(() => {
    isotope.current = new Isotope('.news', {
      itemSelector: '.newsInner',
      layoutMode: 'fitRows',
      getSortData: {
        header: '.header',
        date: '.date',
      },
    })
    // cleanup
    return () => isotope.current.destroy()
  }, [])

  // handling sort key change
  useEffect(() => {
    isotope.current.arrange({ sortBy: `${sortKey}` })
  }, [sortKey])

  const handleSortKeyChange = (key) => () => setSortKey(key)
  return (
    <div className="container">
      <div className="row">
        <div className="col-12">
          <div className="sortAndFilter">
            <ul className="sortFilter">
              <li>Sort By:</li>
              <li
                onClick={handleSortKeyChange('header')}
              >
                Header
              </li>
              <li
                onClick={handleSortKeyChange('date')}
              >
                Date
              </li>
            </ul>
          </div>
          <div className="news">
            <div className="newsInner vege">
              <div className="newsText two">
                <h3 className="header">V News Header</h3>
                <p className="date">02/05/2020</p>
              </div>
            </div>
            <div className="newsInner one">
              <div className="newsText">
                <h3 className="header">D News Header</h3>
                <p className="date">26/05/2020</p>
              </div>
            </div>
            <div className="newsInner one">
              <div className="newsText">
                <h3 className="header">G News Header</h3>
                <p className="date">10/12/2021</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}