Node js Child process event emitter vs callbacks

Is there any difference between attaching callbacks or event listeners for child process in nodejs. like –

const execute = require('child-process').exec;
const process = execute('ping -n 1 www.google.com'); // or ping -c 1 www.google.com for mac

process.stdout.on('data', data => {
    console.log(data)
})  

In the above code i am using event listener for the output and i am getting stdout data in windows but can’t get the output in macos. But if i use callback like –

const execute = require('child-process').exec;

execute('ping -c 1 www.google.com', (error, stdout, stderr) => {
   console.log(stdout);
})

I am getting the output data in both windows and mac.. Is there any difference using callback or event listeners(both are asynchronous)?

How to place widgets next to each other for photography website

I am using a site to create before and after slider widgets, I than want to use the widget for my website. The code is:

<script src="https://apps.elfsight.com/p/platform.js" defer></script>
<div class="elfsight-app-738dcbf9-2e16-40e0-8b87-d21a5fa6a201"></div>

This results in the two widgets being in a vertical line, how do
I make it so the widgets are next to each other in horizontal line?

Converting geoJson to shapfile as batch using GDAL ogr2ogr in Node JS

I want to convert all the geojsons in a file to shapefiles in a single batch using ogr2ogr library in NodeJS. I know it can be done directly from the terminal using the gdal cli, but I want do know how to do it in Node. Thanks alot!

**I have this code to convert a single file:

// Using CommonJS modules
const ogr2ogr = require('ogr2ogr').default;
const fs = require('fs') ;

// Promise API
(async() => {

   

  // Convert path to GeoJSON.
  let {data} = await ogr2ogr('/Users/MihaiB/Desktop/test_josm/test22.geojson' );
  console.log(data);

  
 
  let {stream} = await ogr2ogr( data, {format: 'ESRI Shapefile'}, {destination:'/Users/MihaiB/Desktop/shapefile2.shx'});
    console.log(stream)

   
        
  
})()





Leaflet Center Marker Numbers

Does anyone have an idea how to center numbers inside markers? This is the current situation.

Marker with Number

Creating a Marker

    return L.divIcon({
  className: "green-icon",
  iconSize: [25, 41],
  iconAnchor: [10, 44],
  popupAnchor: [3, -40],
  html: markerNumber,
});

CSS

.green-icon {
 background-image: url("../GreenIcon.png");
 background-repeat: no-repeat;
 margin: 0 auto;
 text-align: center;
 color: white;
 font-weight: bold;
 }

How to sort an array of object given multiple conditions?

Given an array of objects as such –

item= [
{
 "id": "1",
 "name": "Book",
 "price": "100",
 "status" : "Disabled"
},
{
 "id": "2",
 "name": "Pen",
 "price": "0",
 "status" : "Enabled"
},
{
 "id": "3",
 "name": "Pencil",
 "price": "20",
 "status" : "Enabled"
},
{
 "id": "4",
 "name": "Tape",
 "price": "50",
 "status" : null
},
{
 "id": "5",
 "name": "Paper",
 "price": "10",
 "status" : "Enabled"
},
...
];
if (item.price == '0' || item.status!= 'Enabled'): the item is greyed out. 

How can the item be sorted such that the non greyed items are shown first and then the greyed out items

array.sort() works for prices but don’t seem to work for status

How to connect two components in a same component created on click of add button

I am creating multiple counters on click and I want to connect the two counters, When I increase the value in the first counter it should automatically decrease in the second counter. Can you suggest any solution where I can communicate with multiple counters as I can generate multiple counters on click?

import React from "react";
import ReactDOM from "react-dom";

const Counter = ({ value, onIncrement, onDecrement, hideIncrement }) => {
  return (
    <div>
      <span>{value}</span>
      {value > 0 && (
        <button
          onClick={() => {
            onDecrement();
          }}
        >
          -
        </button>
      )}
      {hideIncrement === false && value < 10 && (
        <button
          onClick={() => {
            onIncrement();
          }}
        >
          +
        </button>
      )}
    </div>
  );
};

const Counters = () => {
  const [counters, setCounters] = React.useState([4, 0, 0, 5]);

  const sum = counters.reduce((acc, item) => acc + item, 0);

  return (
    <div>
      <p>Sum: {sum}</p>
      <button
        onClick={() => {
          setCounters([...counters, 0]);
        }}
      >
        Add counter
      </button>
      <br />
      <div>
        {counters.map((value, index) => (
          <Counter
            value={value}
            hideIncrement={sum >= 20}
            onIncrement={() => {
              const countersCopy = [...counters];
              countersCopy[index] += 1;
              setCounters(countersCopy);
            }}
            onDecrement={() => {
              const countersCopy = [...counters];
              countersCopy[index] -= 1;
              setCounters(countersCopy);
            }}
          />
        ))}
      </div>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Counters />, rootElement);

“user validation failed: passsword: Path `passsword` is required.”

Here is my Mongoose model:

    const mongoose=require('mongoose')

const userSchema=new mongoose.Schema({
    firstName:{
        type:String,
        required:true
    },
    middleName:{
        type:String,
    },
  
    lastName:{
        type:String,
        required:true,
    },
    passsword:{
        type: String,
        required: true,
    },
    email:{
        type:String,
        unique:true,
        sparse:true
    },
    phoneNumber:{
        type:Number
    },
    address:{
        permanentAddress:String,
        temporaryAddress:[String]
    },
    gender:{
        type:String,
        enum:['male','female','others']
    },
    dob:{
        type:Date
    },
    country:{
        type:String,
        default:'Nepal'
    },
    image:{
        type:[String]
    },
    role:{
        type:Number,
        default:2
    },
    isArchived:{
        type:Boolean,
        default:false
    },
    status:{
        type:String,
        enum:['active','inactive','frequent'],
        default:'active'
    },
    passwordResetTOken:String,
    passwordResetTokenExpiry:String
})


const userModel=mongoose.model('user',userSchema)
module.exports=userModel

The controller is:

    function insert(data){
    return new Promise(function(resolve,reject){
        const newUser=new userModel
        newUser.password = passwordHash.generate(data.password)
        newUser.firstName=data.firstName
        newUser.lastName=data.lastName
        newUser.dob=data.dob
        console.log("new user is",newUser.password)
        console.log("mapped user is",newUser)
        newUser.save(function(err,done){
             if(err){
                 return reject(err)
             }
             console.log("user is",done)
             resolve(done)
         }) 
    })

}

I am getting error:


                    "name": "ValidatorError",
                "message": "Path `passsword` is required.",

But req.body has:

     {
  firstName: 'rajiv',
  lastName: 'dahal',
  password: 'admin',
  dob: '2021/03/03'
}

What is my mistake?

Shoutcast artwork image

I am trying to create a custom artwork image using shoutcast server information and api services, that updates itself automatically about the title and artwork of the current streaming audio/artwork.

I would like to put the artwork on my website in circle 150x150px with blue border of 7px and with small cube 50x50px into cube png/jpg image for radio channel.

I would like visitors to see the current streaming audio information: singer name – song title and artwork from singer.

Shoutcast does have an API but in some case i was using already some php codes and plugins but most of them didn’t recronize the artwork image only some players like luna player recronize all images but in my case i dont need player. I searched around internet and most of the answes for the shoutcast code etc i found on this site.

Also i try to find does anyone asking for the same solution like mine on this site but i didnt found any solution and thats why im asking for help/solution and how can i make that.

I know there are some PHP solution, but since I do not know the language I could not find out their solution how to do that.

Most of the people which i try to get help from other sites like freel**cer they first time listen for shoutcast server, most of them ask me does shoutcast has php asp or zlib extentions, most of them think that shoutcast is some php server.
Thats why i registered here and i hope guys you can help me.

Could please provide some examples or hints about how to get the current track title, artwork, even possibly the artwork image from some api service, and if artimage was not found to be shown by default radio logo?

Im showing example how I would like to make it.

Thanks in advance.

Uncaught TypeError: Cannot read properties of undefined (reading ‘items’)

I’m testing the call but I keep getting the error uncaught type Error. it says the error is when i call data.tracks.items.

It says the error is at Object.success, at i, at Object.fireWith, at z, at XMLHttpRequest

  console.log('hello world');

  $('form').submit(function(event) {
    event.preventDefault();
    
    let query = $('input').val();
    let context = $('input[name="context"]:checked').val();
    
    $.get('/search?' + $.param({context: context, query: query}), function(data) {
      $('#results').empty();
      $('input[type="text"]').val('');
      $('input').focus();
      
      data.tracks.items.forEach(function(track, index) {
        let trackSearch = "https://open.spotify.com/track/";
        let newElement = $('<a onClick="getFeatures(&apos;' + track.id + '&apos;)" target="_blank"></a><br>').text(track.name + '   |   ' + track.artists[0].name).attr('href', trackSearch + track.id);
        $('#results').append(newElement);
      });
    });
  });
}); ```

How to display text when hover over videos/images

My image and videos are blurred whenever they are hovered over. Now, I also want them to both blur and display text whenever I hover over. I have tried to use hover for both but only the blur part is applicable so far. I also want the text to be able to resize accordingly with the video box so that when scaling down, it will resize accordingly. Thank you very much !

Code so far:

html{
    margin:0;
    padding: 0;
    font-size:62.5%;
    box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
    -moz-font-smoothing: grayscale;
}

*{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.header{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    padding: 1rem;
    z-index: 100;
}

.wrapper1{
    display:flex;
    flex-direction: row;
    justify-content: flex-start | center | flex-end;
    margin: 0;
    height: 100%;
    width:100%;
}

h4{
    display:block;
    font-size: 1.5em;
    margin-block-start: 0.83em;
    margin-block-end: 0.83em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-family: 'Roboto Mono', monospace;
    z-index:50;
}

.type2{
    text-align: left;
    margin-left: 10rem;
    margin-right: 10rem;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
    -o-animation: fadein 2s; /* Opera */
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

body{
    margin:0;
    padding: 0;
    width: 100%;
}

.main{
    padding:0;
    margin:0;
}

.wrapper{
    overflow-y:hidden;
    overflow-x:auto;
    margin: 0;
    height: 100%;
    width:100%;
}









@media only screen and (max-width: 1000px){
    .type2{
       display: none;
    }

    .type1{
        font-size: 24px;
    }
}


video{
    display: block;
    margin-bottom: 1em;
    object-fit: contain;
}

.main-section{
    display:flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    padding: 0;
    margin: 0;
    top: 25%;

}

.main-section div{
    flex:1;
}



.vid_vertical{
    position: absolute;
    height: auto;
    width: 20%;
}

.vid_1{
    position: absolute;
    left: 25.5%;

    z-index: 1;

}

.vid_1:hover {
    filter:blur(10px);
}

.type_ins: hover{
    display: block;
}



.type_ins{
    font-size: 0.7vw;
    position: absolute;
    left: 30%;
    z-index: 50 !important;
    text-align: center;
    display: none;    
}
.vid_2{
    positon: absolute;
    left: 50% ;
    z-index:2;
}

.vid_3{
    positon: absolute;
    left: 148%  ;
    z-index:3;

}

.vid_4{
    positon: absolute;
    left: 74%  ;
    z-index:3;

}

.vid_5{
    positon: absolute;
    left: 98%  ;
    z-index:3;

}

.vid_6{
    positon: absolute;
    left: 122.5%  ;
    z-index:3;

}


.img1{
    position: absolute;
    height: auto;
    width: 20%;
    left: 0;
    z-index:0;
}
<html>
    <head>
        <meta name="viewport" content="user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width">        
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <meta charset="utf-8">
        <link rel="stylesheet" href="Interactive story.css">
        <title>Interactive Storytelling</title>
       
    </head>

    <body>
      
        <div class="main">
            <div class="header">
                <div class="wrapper1">
                    <div class="type1">
                        <h4>2019</h4>
                    </div>
                    <div class="type2">
                         <h4>I came to Toronto in August 2018 so we (me and my friend)
                            adopted Hershey when we were still in our first year. <br>
                            Before adopting Hershey, we nearly got scammed by buying a dog with a cheaper price so we decided to adopt rather than buying.<br>
                            She was actually our second choice, the first one having a lot of medical issues so we had to move on.<br>
                            I think she chose us actually because of all the people who wanted her, we were the only one whom she didn't hiss at. </h4>


                    </div>
                </div>
            </div>


        <section>
            <div class="wrapper">
                
                <div class="main-section">
          
                   
                  
                    <video class="vid_vertical vid_1" autoplay loop muted preload playsinline>
                        <source src="IMG_1362.mp4" type="video/mp4">    
                    </video>

             

                
                    <video class="vid_vertical vid_2"  autoplay loop muted preload playsinline>
                        <source src="IMG_1364.mp4" type="video/mp4">
                    </video>

                    <video class="vid_vertical vid_3"  autoplay loop muted preload playsinline>
                        <source src="IMG_1832.mp4" type="video/mp4">
                    </video>
                    
                    <video class="vid_vertical vid_4"  autoplay loop muted preload playsinline>
                        <source src="1080p.mp4" type="video/mp4">
                    </video>

                    <video class="vid_vertical vid_5"  autoplay loop muted preload playsinline>
                        <source src="IMG_1381.mp4" type="video/mp4">
                    </video>

                    <video class="vid_vertical vid_6"  autoplay loop muted preload playsinline>
                        <source src="IMG_1391.mp4" type="video/mp4">
                    </video>






                    <img src="IMG_1275_2.jpg" class="img1">

                </div>
            </div>

        </section>
        
        </div>  

       
              

        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script src="Interactive story.js"></script>

        <!-- <section>
            <div class="wrapper">
                <div class="vid">
                    <iframe id="vid_vertical" class="vid_2" autoplay loop muted preload playsinline>
                        <source src="IMG_1363.MOV" type="video/mp4">
                    </iframe>
                </div>
            </div>
        </section> -->


    </body>

Pushing items into array not working inside of jquery POST [duplicate]

my post was just deleted and they linked AJAX asynchronosity which didn’t help at all and is completely unrelated to my problem.

My problem is that I cannot push ITEMS, into my array using .push when it’s inside of a POST and not ajax…

CODE:

var rolearray = [];
$.post(
  "https://URL/getRoleData", 
  JSON.stringify({ businessid: $(this).data('businessid') }), 
  function(roles){
    $(roles).each(function(e) {
      rolearray.push({label: roles[e].role, value: roles[e].role})
    })
  }
)

This time please don’t just dismiss it. Cause the thread linked didn’t help.

Also yes the post is returning data.. For each is working as intended but it won’t push my values after it’s returned the result.

Timestamp field from firestore showing an invalid date if the field does not exist

These are my codes. selectedDate is a timestamp field:

<ListItemText
                          primary={
                            new Date(
                              user.items?.selectedDate?.seconds * 1000
                            ).toDateString() +
                            " at " +
                            new Date(
                              user.items?.selectedDate?.seconds * 1000
                            ).toLocaleTimeString()
                          }
                    />

It does show the data correctly. However, if the selectedDate does exist, it will show:

Invalid date at Invalid date

How can I fix this?

Is there a way to find only unused JSDoc type definitions?

For example:

/**
 * A number, or a string containing a number.
 * @typedef {(number|string)} NumberLike
 *
 * Dummy type
 * @typedef {(string|null)} StringLike
 */

/**
 * Set the magic number.
 * @param {NumberLike} x - The magic number.
 */
function setMagicNumber(x) {
}

As you can see NumberLike is used, but the StringLike type is not used and I’d like to find all such unused type definitions on our project. It’s a Nodejs project with typescript installed.

Here’s our tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": ".",
    "jsx": "react",
    "allowJs": true,
    "checkJs": true,
    "target": "ESNext",
    "noEmit": true,
    "moduleResolution": "node",
    "isolatedModules": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "strictNullChecks": true,
  },
}