Solve my argv.json in VS Code. I’m a beginner [closed]

When I opened my VS Code after installing it, it showed me this (I also installed Node.js):enter image description here

please tell me what should I do next? And I also tried to run JavaScript ignoring this message but it gave me a output of Running and Done and nothing else. I also tried code runner.

I will be thankful if you show me with screen shots or something that will be easier for me.(as I’m a beginner)

JS scroll listener for animation causing page jump during mobile scroll

I have written some custom code for an ‘animation’. The animation counts for 0 to a certain number as specified in the function. This works fine on desktop but on my android phone it is causing the page to jump back up a little bit when you scroll down to this section of the page. You also cannot see the animation. It seems like it:

  • Triggers the animation
  • Jumps back up the back the page a little as the animation runs
  • User scrolls down again and it shows the updated numbers after the count up animation is done

This is the page I have the problem on: https://quedamoslanguages.com/ so you can see the bug here.

The section to look at is the ‘YEARS EXPERIENCE’, ‘STUDENTS’ etc. It is 2/3 down the page.

This is the custom function

import { runOnScroll, throttle } from './common.js';

function doCountAnimation(element, targetNumber, duration = 1000) {
    if (!element) {
        console.error(`Element with selector '${elementSelector}' not found.`);
        return;
    }
    const startTime = performance.now();
    function updateCount(currentTime) {
        const elapsedTime = currentTime - startTime;
        const progress = Math.min(elapsedTime / duration, 1);
        const currentNumber = Math.floor(progress * targetNumber);
        element.textContent = currentNumber;
        if (progress < 1) {
            requestAnimationFrame(updateCount); // requestAnimationFrame() is build in browser function
        }
    }
    requestAnimationFrame(updateCount);
}


function triggerCountAnimation(element){
    doCountAnimation(element.querySelector('div.wp-block-group:nth-child(1) p:nth-child(1)'), 31);
    doCountAnimation(element.querySelector('div.wp-block-group:nth-child(2) p:nth-child(1)'), 7);
    doCountAnimation(element.querySelector('div.wp-block-group:nth-child(3) p:nth-child(1)'), 14);
    doCountAnimation(element.querySelector('.wp-block-group:nth-child(4) p:nth-child(1)'), 1000);
    window.removeEventListener('scroll', throttledScrollHandler);
}

const throttledScrollHandler = throttle(() => runOnScroll('.big-numbers-container-home .wp-block-group', triggerCountAnimation), 300);

// Throttling the function with an anonymous wrapper to pass the selector
window.addEventListener('scroll', throttledScrollHandler, { passive: true });


And these are the 2 functions which I am importing

export const throttle = (fn, delay) => {
    // Set up the throttlerconst throttle = (fn, delay) => {
    let time = Date.now();
    return () => {
        if ((time + delay - Date.now()) <= 0) {
            fn();
            time = Date.now();
        }
    };
}

export function runOnScroll(selector, animationFn) {
    const element = document.querySelector(selector);
    if (element) {
        if(isInViewport(element)){
            animationFn(element)
        }
    } else {
        console.log('Element not found for selector:', selector);
    }
}

As you can see I have throttled the function so that the scroll function does not run all the time in order to improve performance.

I did try taking the throttle function out so did this –
window.addEventListener(‘scroll’, () => runOnScroll(‘.big-numbers-container-home .wp-block-group’, triggerCountAnimation), { passive: true });

But was still seeing the same issue. Of course I just want the page to scroll from top to bottom without jumping around anywhere in the process.

Any ideas would be much appreciated !

When I open my update modal, the selected role does not appear in my dropdown

enter image description here

The first value in my dropdown appears selected. I do not want this, I want the value in the row I selected to appear in my dropdown. Can anyone check my codes and help me with this?
I have a table where I display user data and a modal to update the user’s information. When I click the “Update” button, the modal opens, but the first value in my dropdown is always selected by default. However, I want the role value from the selected row to appear in the dropdown.

Here’s my code:



$('#usersUpdateModal').on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget); 
   var id = button.data('id'); 
   var role = button.data('role');
   var modal = $(this);
   
   // Populate the input fields with the selected row's data
   modal.find('input[name="users.Id"]').val(id);
   modal.find('select[name="users.Role"]').val(role);  // Here is where the role should be selected
});
@foreach (var k in Model.users)
{
    <tr class="text-nowrap">
        <td>@k.Id</td>
        <td>@k.Role</td>
        <td>
            <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#kullaniciGuncelleModal" data-id="@k.Id" data-role="@k.Role">
                Güncelle
            </button>
        </td>
    </tr>
}

<div class="row mb-3">
    <div class="col-md-5">
        <label class="col-form-label">Role</label>
    </div>
    <div class="col-md-7">
        <select asp-for="users.YetkiId" class="form-select" required>
            @foreach (var y in Model.yetkiler)
            {
                <option value="@y.Id">@y.Role</option>
            }
        </select>
    </div>
</div>
[enter image description here](https://i.sstatic.net/AsK52b8J.jpg)

The roles in the dropdown are pulled from the “Yetki” table, which contains role information.
YetkiId is a foreign key (FK).
What could be causing the first value to always appear selected, and how can I fix this so the selected row’s role appears in the dropdown when the modal opens?

How can I find the origin of a rejected promise

Recently, we saw a steep increase of errors titled Event CustomEvent (type=unhandledrejection) captured as promise rejection in Sentry. Based on the research so far, it looks like a promise gets rejected somewhere in the code, but we have not yet been able to find where this happens. I’ve already added below piece of code to log a trace entry with some information about the rejected event, but apparently the reason is undefined. I know there is also a promise property on the listener argument, but I don’t know how to get any useful information from that object. Is it possible to determine the source of a promise, and if so, how?

window.addEventListener('unhandledrejection', ({ reason }) => {
  ErrorManagement.addTrace({
    data: { reason },
    level: 'info',
    message: 'unhandledrejection caught',
    category: 'error',
  });
});

Issue with modern-screenshot library when filtering nodes

When using the modern-screenshot library (https://www.npmjs.com/package/modern-screenshot) and filtering out some nodes, the resulted image has the original height element resulting in whitespace on the image.

I tried setting the height manually but that just cuts the image.

I am curios if someone else had this issue and if there is a fix for it.

When I filter nodes I expect the image to not have whitespace, instead, the image has original element height with whitespace where the filtered node was placed.

Here is a sandbox with reproduction: https://codesandbox.io/p/sandbox/modern-screenshot-forked-sp2j8g

Toggle animation to show/hide Div by slidding style

I want to paly second div animation within its parent row only. Right now the second div is moving out of the row boundary. How can I handle this? This is my first time trying first time animation. Thanks in advance.

function test(event) {
  var checkbox = document.getElementById('toggle');
  var firstDiv = document.getElementById('firstDiv');
  var secondDiv = document.getElementById('secondDiv');

  if (checkbox.checked) {
    secondDiv.classList.remove('col-lg-12')
    secondDiv.classList.remove('slide-in');
    secondDiv.classList.add('col-lg-7')
    secondDiv.classList.add('slide-out');
    //firstDiv.style.display = 'block';
    secondDiv.addEventListener('animationend', function() {
      firstDiv.style.display = 'block';
    }, {
      once: true
    });
  } else {
    firstDiv.style.display = 'none';
    secondDiv.classList.remove('slide-out');
    secondDiv.classList.remove('col-lg-7')
    secondDiv.classList.add('col-lg-12')
    secondDiv.classList.add('slide-in');
  }
}
.slide-in {
  animation: slide-in 3s forwards;
}

.slide-out {
  animation: slide-out 3s forwards;
}

@keyframes slide-in {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slide-out {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100%);
  }
}

.row {
  border: 1px solid black;
  /* Added row border */
  width: 500px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="row">
  <div id="firstDiv" style="background-color:palegreen" class="col-lg-5">first</div>
  <div id="secondDiv" style="background-color:yellow" class="col-lg-7">Second</div>
</div>
<div>
  <input type="checkbox" id="toggle" checked="checked" onchange="test(event)">
  <label for="toggle">Toggle Animation</label>
</div>

Animate height based on content height

I have this simple example, where I am toggling between 10 and 1 items. I want the height change to be animated:

<script setup>
import { ref } from "vue";

const items = ref([1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 0]);
const itemList = ref(items.value);

const toggle = () => {
  itemList.value = itemList.value.length === 1 ? items.value : [items.value[0]];
};
</script>

<template>
  <button class="bg-gray-400 text-white p-2" @click="toggle">Toggle</button>

  <div class="bg-red-100 transition-all m-20 p-4 rounded-md text-center">
    <div v-for="(item, index) in itemList" :key="index">
      {{ item }}
    </div>
  </div>
</template>

In IMAP , if i use imap.move with valid uids i get “this socket has been ended by the other party” error in imap.once(“error”)

firstly i try get imap by ,

    `let imap = new Imap({
         user: username,
         password: appPassword,
         host: host,
         //authentication: appPassword,
         port: 993,
         autotls: "always",
         tls: true,
         ssl: true,
         tlsOptions: { rejectUnauthorized: false, servername: host },
         connTimeout: 30000,
         authTimeout: 30000,
   });`

then i pass the imap and connect using

  `imap.connect();
      imap.once("ready", () => {
      resolve(imap);
      });  
  imap.once("error", async (error) => {
      if(error.message.toLowerCase() === "this socket has been ended by the other party") {
      imap.end();
      }
      });`

the connection is made successfully,
after this i get the valid uids to delete , valid trash label.
then i open the correct mailbox to move from , then i use

      `imap.move(uids, trashFolderName, async function (err) {
          if (err) {
            reject(err);
            return;
          }
          }`

here the problem starts – the uids get moved to trash but i get error “this socket has been ended by the other party” and the code after imap.move doesnot gets executed.
i dont know how to solve it .

if you already experienced in this , kindly help.

Why does Google Map restrict the zoom if the origin and destination are the same places?

I have a use case for a map that requires showing a marker with the same lat/lng for it’s origin and destination.

However, I find that it often results in these:

Image

where the marker is not centered and if I’m using it on mobile it just cannot be seen.

Is there a way to control the zoom in this scenario?

This is the current code I'm using. I've tried using LatLng Bounds but no luck with that.
<!doctype html>
<html>
  <head>
    <meta name='viewport' content='initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, shrink-to-fit=no' />
    <title>Simple Map</title>
    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      .custom-marker {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 20px;
      height: 20px;
      background-color: #32a852;
      color: #FFFFFF;
      border-radius: 50%;
      font-size: 16px;
      font-family: Arial, sans-serif;
      text-align: center;
      line-height: 10px; 
      white-space: nowrap;
    }
    
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      let map;
      
      //remove when replacing with actual values
      let lat1 = 1.452728;
      let lng1 =  103.816431;
    
      let lat2 = 1.452728;
      let lng2 = 103.816431;

      async function initMap() {
        // Request needed libraries.
        const { Map } = await google.maps.importLibrary("maps");
        const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

        map = new Map(document.getElementById("map"), {
          center: { lat: (lat1 + lat2) / 2, lng: (lng1 + lng2) / 2 },
          zoom: 1,
          mapTypeId: "roadmap",
          streetViewControl: false,
          mapTypeControl: false,
          rotateControl: false,
          mapId: "4504f8b37365c3d0",
        });

       const originMarker = document.createElement('div');
       originMarker.className = 'custom-marker';

      //customize originMarker 
      /*
       originMarker.style.background = "blue";
       originMarker.style.color = "white";
       originMarker.style.fontSize = "";
       originMarker.textContent = "You"
       */

      // Marker
        const origin = new AdvancedMarkerElement({
          map,
          position: { lat: lat1, lng: lng1 },
          content: originMarker
        });
      
        
        const destination = new AdvancedMarkerElement({
          map,
          position: { lat: lat2, lng: lng2 },
        });
        
        const directionsService = new google.maps.DirectionsService(); 
        const directionsRenderer = new google.maps.DirectionsRenderer({ 
          map: map,
          suppressMarkers: true, 
          polylineOptions:{
            strokeColor: "#F33F33",
                strokeOpacity: 1,
                strokeWeight: 5,
          }
        });
        
        const request = {
          origin: new google.maps.LatLng(lat1, lng1),
          destination: new google.maps.LatLng(lat2, lng2),
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.METRIC
        };

        directionsService.route(request, (response,status) => {
          if (status === 'OK') {
            directionsRenderer.setDirections(response);
          } else {
            console.error('Directions request failed due to the following error: ' + status);
          }
        });
      }
      initMap();
    </script>
    <script async
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
    </script>

  </body>
</html>
 

Material UI Collapse / React-Spring transition bug ( When Expanding / Collapsing – Whole page scrolls )

I been facing this bug for some time now, the issue is when collapsing/expanding with the Mui Collapse transition, the whole browser page scrolls when the animation happens:

https://imgur.com/a/NPvhdHb

This is my code for Mui Collapse:

<Collapse in={overTitle}>

    <Box
        sx={{
            // color: "#FFC121",
            color: "#FFF",
            fontSize: "20px",
            fontWeight: 600,
            paddingBottom: "20px",
            marginRight: "40px",
        }}
    >
    
        {"Subtitle Text Here"}
    
    </Box>


</Collapse>

This is my code using react-spring:

// React Spring
const [measureRef, { height }] = useMeasure();

const collapse_styles = useSpring({
    config: config.stiff,
    from: {
        height: 0
    },
    to: {
        height: overTitle ? height : 0
    }
});


<animated.div style={{ overflow: "hidden", ...styles }}>

        <div
          ref={measureRef}
        >
        
          {"Subtitle Text Here"}
          
        </div>
        
</animated.div>

both are simple examples yet both face the same scrolling issue,

can anyone explain why this is happening? is this a known bug?

How do I add aria-dialog-name attribute to PrimeNg dynamicdialog?

I am using the primeng dynamic dialog like this:

private dialogService: DialogService
...
...
this.dialogService.open(MyComponent, {
  showHeader: false,
  modal: true,
  autoZIndex: true,
  data: {
    key: "value"
  }
});

However, some of my accessibility tests fail as they are not able to find the aria-dialog-name attribute in the div that has role=dialog.

The project has several dialogs and so it would be impossible to refactor them into a different type of mode and I need to use dynamic model. How can I add this attribute?

Express JS/HTML Form Submission Issue

I am trying to submit a form to an express js server but I am not getting any form data on the backend.

Here is my HTML.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Uploader</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            display: flex;
            justify-content: space-between;
        }
        .column {
            width: 45%;
        }
        #response1, #response2 {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
    <script>
        async function submitForm(event) {

            const formData = new FormData(document.getElementById('form'));
            try {
                const response = await fetch('/submit', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('Failed to submit Form 1');
                }

                const result = await response.json();
                document.getElementById('response').innerText = result.message;
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('response').innerText = 'Error: ' + error.message;
            }
        }
    </script>
</head>
<body>

<div class="column">
    <h2>Form 1</h2>
    <form id="form" onsubmit="submitForm(event)">
        <label for="id">Id:</label><br>
        <input type="text" id="id" name="id" required><br><br>
        <label for="filename">File Name:</label><br>
        <input type="text" id="filename" name="filename" required><br><br>
        <label for="filepath">File Path:</label><br>
        <input type="text" id="filepath" name="filepath" required><br><br>
        <button type="submit">Submit</button>
    </form>
    
    <div id="response"></div>
</div>

</body>
</html>

Here is the express JS app

import { ExtService } from "./extService";
var express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors')

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors());
app.use(express.json())

const PORT = 3000;

app.post('/submit', async (req, res) => {
  const { id, filename, filepath } = req.body;

  console.log(id);
  const params = req.body;
  console.log(params);
  console.log('id: '+ params.id);

  const extService = new ExtService();
  const response = await extService.create(id, filename, filepath);

  res.send(response);
});

app.listen(PORT, function () {
  console.log('Example app listening on port 3000!');
});

I always get undefind when I am trying to print the values of id or params.
What am I missing in this code?

The HTML file is placed inside public folder as index.html.

Unable to Send POST Request from Dockerized Service to Another Dockerized Service

I am working on a project with multiple microservices using Docker Compose. I have two services, matching_service and collaboration_service. The matching_service sends a POST request to the collaboration_service to create a room. However, the request fails with the following error:

Error creating room: request to http://localhost:4000/create-room failed, reason: 
Response from createRoom: undefined
Response from createRoom: {
  status: 500,
  message: 'request to http://localhost:4000/create-room failed, reason: '
}

The matching_service can recieve post request but cannot send a GET or POST request. But the POST api works from postman and other backend services, except matching_service.

docker-compose.yml


matching-service:
    build: ./backend/matching-service # Path to the directory containing the Dockerfile for building the backend/question-service image.
    ports:
      - 3002:3002
      - 8080:8080
    env_file:
      - ./backend/matching-service/.env
    depends_on:
      rabbitmq:
        condition: service_healthy

  rabbitmq:
    image: rabbitmq:3-management
    ports:
      - "5672:5672"
      - "15672:15672"
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "status"]
      interval: 5s
      timeout: 10s
      retries: 5

  collaboration-service:
    build: ./backend/collaboration-service # Path to the directory containing the Dockerfile for building the backend/user-service image.
    ports:
      - 4000:4000 # Maps port 3001 on the host to port 3001 in the container, making the app accessible on the host.
    env_file:
      - ./backend/collaboration-service/.env

matching_service

import fetch from "node-fetch";
import { v4 as uuidv4 } from "uuid";

const createRoom = async ({ participants }) => {
  const url = "http://collaboration-service:4000/create-room"; // Using Docker service name
  const requestBody = {
    roomId: uuidv4(),
    participants: participants,
  };

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Server error: ${response.statusText}, ${errorText}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error creating room:", error.message);
    return { status: 500, message: error.message };
  }
};

export { createRoom };

collaboration_service

import express from "express";
import dotenv from "dotenv";
import cors from "cors";

dotenv.config();

const app = express();
app.use(express.json());

// Configure CORS to allow requests only from specific origins
const allowedOrigins = ['http://matching-service:3002']; // Origin of matching_service
app.use(cors({
  origin: function (origin, callback) {
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
}));

const Room = require("./models/Room");

app.post("/create-room", async (req, res) => {
  const { roomId, participants } = req.body;
  try {
    let existingRoom = await Room.findOne({ roomId });
    if (existingRoom) {
      return res.status(400).json({ message: "Room already exists" });
    }

    const newRoom = new Room({ roomId, participants });
    await newRoom.save();
    return res.status(201).json({ message: "Room created", room: newRoom });
  } catch (err) {
    return res
      .status(500)
      .json({ message: "Error creating room", error: err.message });
  }
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Why does the term “hook” exist in both Java and React, and do they share any similarities?

Is there a similarity between them that everyone is overlooking, or are they just named that way by coincidence?

I didn’t find any significant similarity between hooks in Java and React. Though both are termed ‘hooks,’ they serve distinct purposes. In Java, hooks are often lifecycle callbacks, while in React, they manage state and effects in functional components. It seems the use of the term ‘hook’ in both contexts is more related to naming rather than any fundamental functional similarity.

Javascript API for Navigation for Google Maps Go

Is Google providing an accessible API for “Navigation for Google Maps Go” or are they going to maintain monopoly access to the holy grail for PWA Background Geolocation?

As someone who’s been begging for Built in Service Worker Geolocation events for inactive PWAs for over 10 years I am amazed to see “Navigation for Google Maps Go” in the wild!

  • How can my bike trip tracker PWA use it?
  • How can my Geofencer PWA use it?
  • How can my grain harvester tracker use it?

This is outstanding!!!

See Brotkrumen for the reason behind my passion and that of many others.