How to send a a variable to npm package [duplicate]

I am learning to build npm package locally as I can’t get good tutorial regarding this situation I am here to ask

Here is my app.js code

const axios = require('axios')
 const user ={}
  user.id = async function (){
  let res = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=shyft-network-2&vs_
  return res;
 
 }
 module.exports = user

Here is my question how can I pass url that is on axios.get in app.js file from my index.js file.

Here is my index.js code

const app = require('./lib/app')
 app.id().then((r) => {
   console.log(r.data)
  }).catch((e) => {
   console.log(e)
})

I want to manually set the url from index.js do axios.get there and get result here. Any help would be greatly appreciated.

How to convert tree json to nested Object in js

I converted a nested object into tree JSON format but now I need to convert it back to a nested object I tried so many ways but not working as expected. while converting nested object JSON I used recursion to achieve but here is how to operate it with the object.

I really appreciate your help, Thanks

input : 
     [
      {
        "name": "DI",
        "children": [
          {
            "name": "t",
            "children": [
              {
                "name": "tID",
                "ir": true,
                "is": false
              },
              {
                "name": "tTime",
                "ir": false,
                "is": false
              }
            ],
            "ir": false,
            "is": false
          },
          {
            "name": "i",
            "idx": 0,
            "children": [
              {
                "name": "idu",
                "ir": false,
                "is": false
              },
              {
                "name": "il",
                "ir": false,
                "is": false
              },
              {
                "name": "ibId",
                "children": [
                  {
                    "name": "ib1",
                    "ir": false,
                    "is": false
                  },
                  {
                    "name": "ib2",
                    "ir": false,
                    "is": false
                  }
                ],
                "ir": false,
                "is": false
              }
            ],
            "ir": false,
            "is": false
          }
        ]
      }
    ]

expected o/p:

{
   "DI":{
      "t":{
         "tID":{
            "ir":true,
            "is":false
         },
         "tTime":{
            "ir":false,
            "is":false
         },
         "ir":false,
         "is":false
      },
      "i":{
         "idu":{
            "ir":false,
            "ir":false
         },
         "il":{
            "ir":false,
            "is":false
         },
         "ibId":{
            "ib1":{
               "ir":false,
               "is":false
            },
            "ib2":{
               "ir":false,
               "is":false
            },
            "ir":false,
            "is":false
         },
         "ir":false,
         "is":false
      }
   }
}

How to elegantly get a particular value from highly nested json object in JavaScript?

This is my json object by name data

{
"data": {
    "id": "---------",
    "type": "licenses",
    "attributes": {
        "name": "Floating Point Lic",
        "key": "-----------",
        "expiry": "2022-07-30T19:11:30.738Z",
        "status": "ACTIVE",
        "uses": 0,
        "suspended": false,
        "scheme": "ED25519_SIGN",
        "encrypted": false,
        "strict": true,
        "floating": true,
        "protected": true,
        "maxMachines": 10,
        "maxProcesses": null,
        "maxCores": null,
        "maxUses": null,
        "requireHeartbeat": false,
        "requireCheckIn": false,
        "lastValidated": "2022-07-07T08:33:58.195Z",
        "lastCheckIn": null,
        "nextCheckIn": null,
        "metadata": {         
            "role": "sde"
        },
        "created": "2022-06-30T19:11:30.736Z",
        "updated": "2022-07-07T08:33:58.199Z"
    },
    "relationships": {
        "account": {
            "links": {
                "related": "------------"
            },
            "data": {
                "type": "accounts",
                "id": "------------"
            }
        },
        "product": {
            "links": {
                "related": "------------------"
            },
            "data": {
                "type": "products",
                "id": "This I need"
            }
        },
        "policy": {
            "links": {
                "related": "---------"
            },
            "data": {
                "type": "policies",
                "id": "---------------"
            }
        },
        "group": {
            "links": {
                "related": "------------"
            },
            "data": null
        },
        "user": {
            "links": {
                "related": "---------------"
            },
            "data": null
        },
        "machines": {
            "links": {
                "related": "-------------------"
            },
            "meta": {
                "cores": 0,
                "count": 0
            }
        },
        "tokens": {
            "links": {
                "related": "----------------"
            }
        },
        "entitlements": {
            "links": {
                "related": "------------------"
            }
        }
    },
    "links": {
        "self": "-------------"
    }
},
"meta": {
    "ts": "2022-07-07T08:33:58.204Z",
    "valid": false,
    "detail": "must have at least 1 associated machine",
    "constant": "NO_MACHINES"
}

}

Their is data then their is relationships then product then data then id which I want

I am currently getting it by writing
r[‘data’][‘data’][‘relationships’][‘product’][‘data’][‘id’]

r here is this object but this does not looks elegant at all. Is their any way to fetch this in a better manner?

Managing internal state in an RxJS observable

I’m new to RxJS and wondering about internal state.

Our use case is a promise that returns an initial state (a list of items with ids) and an observable that streams mutations (deleted ids) to that state. The updated list of items is then a persistent state and should be used in building the result.

I can hack something together using a global variable but as expected it behaves weirdly:

import { combineLatest, from } from "rxjs";
import { startWith } from "rxjs/operators";

...

const initialObservable = from(initialPromise);

const mutationObservableWithStart = mutationObservable.pipe(startWith(null));

const globalDeletedIds: string[] = [];

return combineLatest([initialObservable, mutationObservableWithStart]).pipe(
  map(([items, mutation]) => {
    if (mutation && mutation.deleted) {
      globalDeletedIds.push(mutation.id);
    }

    const currentItems = items.filter(doesNotIncludeIds(globalDeletedIds));

    return buildResult(currentItems);
  })
);

My question is how to correctly manage internal state in an observable? I suspect I need to use a BehaviourSubject but not sure if this is the correct approach and how.

Show div or change URL based on date

I have a YouTube playlist with 371 videos in it that each are meant to be shown on a particular day of the year.

The code looks like this for any one video:

<iframe width="560" height="315" src="https://www.youtube.com/embed/z7plt65m0Ts" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

But I’d need to switch out the URL parameter immediately after the embed/ spot with the corresponding piece from the video of that day.

Is there a way to do this that will enable me to set the first video’s date from year to year so that the days continue to match up each subsequent year as well?

Not sure if this info is needed, but the link for each story’s day is here and the link for the entire youtube playlist is here

Thanks for absolutely any help. I truly hope this is possible.

React making onClick event spesific for each element

I want to add a border when the class is “transporation active” but when I click one of the icons, all of them become active. I want only the clicked one to become active. This is for selecting categories. My react code is like this:

const [transportationClick, setTransportationClick] = useState(false);
  const handleTransportationClick = () => setTransportationClick(!transportationClick);

/* where I use it */

<div className="transportation-types">
              <div className={transportationClick ? "transportation active" : "transportation"} onClick={handleTransportationClick}>
                <div className="transportation-icon">
                  <FaCar />
                </div>
              </div>
              <div className={transportationClick ? "transportation active" : "transportation"} onClick={handleTransportationClick}>
                <div className="transportation-icon">
                  <FaBus />
                </div>
              </div>
              <div className={transportationClick ? "transportation active" : "transportation"} onClick={handleTransportationClick}>
                <div className="transportation-icon">
                  <FaWalking />
                </div>
              </div>
            </div>

how to compare two arrays with third array check in best possible way in Javascript?

I want to perform below operations with three arays and required it to be solved in the best way

  var finalSelect = [80,1,75,20];
  var activeselection = [20];
  var temp = [75,20];

if activeSelection elements are present in finalSelect arrray, remove the other elements from temp array in finalSelect array

  for example above activeSeelction [20] is matching in finalSelect array, I want [75] other than [20] from temp to be removed from finalSelect array.  
  final array should be [80,1,20]

Also in other case activeSeelction [20] is not present in finalSelect array, I want it to be inserted such as

    [80,1,75,20]

I have tried using multiple includes like

   var x  = temp.filter(a => !activeSelection(a);
  if(finalSelect.filter(a => x.includes(a)){
     arr =  finalSelect.filter(a => !x.includes(a)
     } else{
     arr = [...finalSelect,activeselection]
     }

I want this solution to be rewritten in best perfomable way / not using too many filters and includes to check. Please suggest

Confusion about sending a 100GB file from front-end to back-end

Background

We know that web browsers have memory limitations per tab, which can be raised to 4GB for example.

Assume there is a web app. This web app cannot load files larger than around 4GB in its memory. If there is a 100GB file, it cannot be loaded by the web app onto the memory.

Approach

I’m going to send a 100GB file from front-end to the back-end by this approach. Basically, the user is prompted to select the 100GB file from her/his computer:

<form class="upload">
   <input type="file" name="uploadFile" accept=".stl" required />
   <br/><br/>
   <input type="submit" />
</form>

The file is sent from front-end to back-end by a POST request using fetch API:

const uploadForm = document.querySelector('.upload')

uploadForm.addEventListener('submit', function(e) {
   e.preventDefault()
   let file = e.target.uploadFile.files[0]
   let formData = new FormData()
   formData.append('file', file)
   fetch('http://localhost:3000/upload_files', {
      method: 'POST',
      body: formData
   })
   .then(resp => resp.json())
   .then(data => {
      if (data.errors) {
         alert(data.errors)
      }
      else {
         console.log(data)
      }
   })
})

Question

I didn’t test the above approach with the actual 100GB file. But before testing, I wonder if I’m missing something with the above setup? Is something wrong with it? Is there a standard approach to so such things? Is there a better approach?

How can I avoid loading the 100GB onto the JS memory? How can I send it to the back-end without going beyond the browser memory limitations?

MongoDB – slow query on old documents (aggregation and sorting)

I have two DBs for testing and each contains thousands/hundreds of thousand of documents.
But with the same Schemas and CRUD operations.

Let’s call DB1 and DB2.

I am using Mongoose
Suddenly DB1 became really slow during:

    const eventQueryPipeline = [{
          $match: {
            $and: [
              { userId: req.body.userId },
              { serverId: req.body.serverId }
            ]
          }
        },
        {
          $sort: {
            sort: -1
          }
        }];
    
    const aggregation = db.collection.aggregate(eventQueryPipeline).allowDiskUse(true);
    aggregation.exect((err, result) => {
    res.json(result)
    })

In DB2 the same exact query runs in milliseconds up to maximum a 10 seconds
In DB1 the query never takes less than 40 seconds.

I do not understand why. What could I be missing?
I tried to confront the Documents and the Indexes and they’re the same.
Deleting the collection and restrting saving the documents, brings the speed back to normal and acceptable, but why is it happening? Does someone had same experience?

How do I ensure that DOM operations in a single tick happen at once?

DOM operations are synchronous but their rendering to the screen is often clubbed together. How do I ensure that they are always processed as a single transaction in terms of rendering on the screen?

I tried requestAnimationScreen and inserted an alert() to see the state in-between. It works as a single transaction for Chrome and Safari but not Firefox. Moreover, is there any spec that defines this behaviour or is this completely browser dependent?

FWIW, if I remove alert() it works as a single transaction even on Firefox.

Here is the code snippet:

function f(showAlert) {
  const boxes = document.querySelectorAll('.box');
  const firstBox = boxes[0];
  const secondBox = boxes[1];

  firstBox.remove();

  if (showAlert) {
    alert("Check");
  }

  const div = document.createElement('div');
  div.classList.add('box');
  div.classList.add('new');

  secondBox.parentElement.insertBefore(div, secondBox);
}

document.querySelector('.btn1').onclick = () => {
  requestAnimationFrame(() => {
    f(true);
  });
};

document.querySelector('.btn2').onclick = () => {
  requestAnimationFrame(() => {
    f(false);
  });
};
.box {
  height: 500px;
  width: 500px;
  background-color: blue;
}

.box.default {
  background-color: pink;
}

.box.new {
  background-color: green;
}

.btn-bar {
  position: fixed;
  right: 0;
}
<div class="box">Box 1</div>
<div class="box default">Box 2</div>
<div class="box">Box 3</div>
<div class="box default">Box 4</div>
<div class="box">Box 5</div>
<div class="btn-bar">
  <button class="btn1">Alert</button>
  <button class="btn2"> No alert</button>
</div>

Is it possible to change the button CSS class state from “.ripple” to “ripple:active” by using js without manually clicking the button?

Using js simulator click does not work for CSS pseudo-class :active ❌, after I tried some classList methods still not work. I just wonder if there are some possible ways to realize that?

question situation

auto-click to show the CSS ripple effect in the demo.

codes

<button class="ripple highlight">ripple button</button>
.ripple {
 // ...
}

.ripple:after {
  // ...
}
.ripple:active:after {
  // ...
}
const btn = document.querySelector(`button`);

btn.addEventListener(`click`, (e) => {
  console.clear();
  // try to manually set pseudo-class `:active` ❓
  btn.classList.toggle('ripple', 'ripple:active');
  // btn.classList.replace("ripple", "ripple:active");
  console.log('classList =', e.target.classList);
});

setInterval(() => {
  // js simulator click not work for css pseudo-class `:active` ❌
  btn.click();
}, 1000);

demo

https://codepen.io/xgqfrms/pen/zYWrmob?editors=1011

refs

https://developer.mozilla.org/en-US/docs/Web/CSS/:active

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

making primary key and foreign key relation in nestjs

I have 2 tables in nestjs. User table has a column ID which will be foreign key in the owner column of certificate table.
I am writing below code for
User entity.

export class User {
  
    @Column()
    @OneToMany(
        () => Certificate,
        (certificate) => certificate.owner
    )
    @JoinColumn()
    @PrimaryGeneratedColumn()
    @Generated('rowid')
    id: string;

    displayName: string;
}

in the certificate entity I am writing below code

export class Certificate  {
    @PrimaryGeneratedColumn('uuid')
    id: string;

   
    @Generated('rowid')
    certificateNo: string;

    @ApiProperty()
    @ManyToOne(
        () => User,
       (user) => user.id,
        { eager: false }
    )
    @Column({ type: 'varchar', nullable: true })
    @JoinColumn({ name: 'id' })
    owner: User[];

}

The above code working fine. but somewhere in my service class I am updating the value of owner in certificate table.

  async changeOwner(id: string, userId: string) {
        const certificate = await this.certificateRepository.findOne(id);

        if (!certificate) {
            throw new NotFoundException('Certificate not found');
        }
        certificate.owner = userId;

        return this.certificateRepository.save(certificate);
    }

It is throwing error.

enter image description here

what changes I should do in entity class or method code to rectify the above issue.

how to get distance and angle of fingers using handpose-detection and fingerpose.js

I’m working on my project in javascript and trying to classify sing lauguage using hand-pose-detection and fingerpose.

hand-pose-detection provides an array of 2D(x, y) and 3D(x, y, z) keypoints on both hands.

Keypoint Diagram

With those information, fingerpose estimaties the direction and curl of each individual finger and compare the result to a set of gesture descriptions.

There are some directions to descride fingers (Vertical Up, Vertical Down, Horizontal Left, Horizontal Right, Diagonal Up Right, Diagonal Up Left, Diagonal Down Right, Diagonal Down Left).

But, it cannot distinguish a finger pointing forward.

finger pointing forward

How can i know whether specific finger is pointing forward with x, y and z value?

For example, x, y and z values of a index of finger pointing forward are listed as below.

{x: -0.02796991445929134, y: 0.03894214548382162, z: 0.07931135594844818, name: 'wrist'}
{x: -0.0031516597405593883, y: -0.017228609866314533, z: 0.004605844616889954, name: 'index_finger_mcp'}
{x: 0.015075504014443127, y: -0.01720325430679768, z: -0.000788380391895771, name: 'index_finger_pip'}
{x: 0.03130624044208889, y: -0.015456470592300948, z: 0.011150432750582695, name: 'index_finger_dip'}
{x: 0.024286197701579672, y: -0.009673149553890061, z: 0.02902831882238388, name: 'index_finger_tip'}

Here ia a link of code sandbox.
https://codesandbox.io/s/fervent-lederberg-3flepp?file=/index.html

It could be help to adjust pointing forward direction in fingerpose.

delay JavaScript on input, so function does fire for each character inputted into a search field

I have a search field to allow users to filter the results that are returned from the database. I have it set so that the search field has a .on('input', function() { which will trigger another function.

This poses a problem in which if a user was to search for “crumble” the ajax request will be triggered for each character the user types in.

Is there a way to delay the JavaScript so that if the user is searching for a product, the function isn’t fired for each character inputted, but will trigger when detected that the user hasn’t typed something further in. I.E. when the user is done typing in what that are searching.

Code:

$(document).ready(function () {
  $('#cards-search').on('input', function() {
    cards_page = ''
    cards_search = this.value;
    get_card_data()
  });
});

Convert Sentence case string

i want ask how to Convert Sentence case string in PHP

i have variable string

$sring = "hello world,world,world heloo";

i want convert Sentence case per “,” to

$string = "Hello World,World,World Heloo";

how to make this
please help all experts