If a point in lng and lat is on line Segment or it only 2 meters away

Here is what I am trying to achieve,( please do not put duplicate has I cannot ask questions),I want to find if the point cLng, cLat is on the Segment line aLng,alat to bLng,bLng. My problem is that my distance check is not working at 2.00 meters which is EPSILON.
Any help in improving this code would be much appreciated.

        var crossProduct = (cLat - aLat) * (bLng - aLng) - (cLng - aLng) * (bLat - aLat);
        if (Math.Abs(crossProduct) == 0)
        {
            return true;
        }
        
        var dotProduct = (cLng - aLng) * (bLng - aLng) + (cLat - aLat) * (bLat - aLat);

        var squaredLength = (bLng - aLng) * (bLng - aLng) + (bLat - aLat) * (bLat - aLat);
        

        var param = -1d;
        if (squaredLength != 0) //in case of 0 length line
        {
            param = dotProduct / squaredLength;
        }

        double xx = param < 0 ? aLng : param >  1 ? bLng: aLng + param * bLng - aLng;
        double yy = param < 0 ? aLat : param >  1 ? bLat: aLat + param * bLat - aLat; 
        var dx = cLng - xx;
        var dy = cLat - yy;
        var sqrt = Math.Sqrt(dx * dx + dy * dy);
        return sqrt < EPSILON;

Place string based on the format on an Array

Hi all sorry if the title is not right but i don’t know how to put it in a title haha, my first post!

explanation: I have a javascript code in a file and i want to put it as text in an Array!
also heads up, i am using React-ts

Basically the js file:

console.log('test me')
const data = 'my data'
const numbData = 1233
const myObj = {data: 123123}
const myArr = ['ewqeqw', '132312']
function myFunc(param) {
    console.log(param)
}
myFunc('testFunc')

What i tried:

  const [updated, setUpdate] = useState<boolean>(false);
  const [file, setFile] = useState();
  const areaRef = useRef<HTMLTextAreaElement | null>(null);
  const codeRef = useRef<HTMLParagraphElement | null>(null);

  const reader = new FileReader();

  function handleChange(event: any) {
    setFile(event.target.files[0]);
  }

  reader.addEventListener('loadend', function () {
    document.getElementById('newText').innerHTML = reader.result;
    setUpdate(true);
  });

  if (file) {
    reader.readAsText(file);
  }

  if (updated) {
    let data = codeRef.current?.innerText;
    let bodyTextArray = data?.split(/(n)/);
    console.log(data);
    console.log(bodyTextArray);
  }

What i get :
Console Log result

What i want:

[“console.log(‘test me’)”, “const data = ‘my data'”, “const numbData = 1233”, “const myObj = {data: 123123}”, “const myArr = [‘ewqeqw’, ‘132312’]”, “function myFunc(param) {
console.log(param)
}”, “myFunc(‘testFunc’)”]

Basically every peice of code (variable declaration, functions…) on it’s own!

Thank you and any solution would be be appreciated!

Passing two spread objects as props on a conditional basis

I have a component which is currently taking in a object value as a prop which is being spread.

const primaryProps = {/* about 10 key/values in here */}

<Component
  {...primaryProps}
/>

This works as intended. But now I am try to add an OR to it and add another object which is spread. But this is throwing syntax errors. Is there a way around it? Thanks.

Tried following which doesn’t work.

const primaryProps = {/* about 10 key/values in here. Can also be empty/null */}
const secondaryProps = {/* about 10 key/values in here */}

<Component
  {...primaryProps || ...secondaryProps}
/>


<Component
  `${primaryProps.join(",") || secondaryProps.join(",")}`
/>

Passing data form parent to Child with the value fetch form API

I wanna passing the selectedCategory (it is State hook) to the Child Item,
First of all, I use the getServiceCatoriesAsync API (redux toolkit) and pass props.serviceCategories[0]?._id to State to fetch initialState (ID of Category).

In Child Component, I receive selectedCategory with the value: undefined

How to fix this.

const ServicesScreen = (props) => {
    //! props: navigation, route,
    //! props Redux: serviceCategories, getServiceCategoriesAsync

    const nCount = React.useRef(0);
    console.log(`ServicesScreen - render `, (nCount.current += 1));

    const [selectedCategory, setSelectedCategory] = React.useState(props.serviceCategories[0]?._id);

    React.useEffect(() => {
        let isSubscribed = true;
        if (isSubscribed) {
            props.getServiceCategoriesAsync();
        }
        return () => {
            isSubscribed = false; //! Cancel the subscription
        };
    }, [selectedCategory]);

return (
    <View style={styles.container}>
        <PanelServiceCategory
            theme={theme}
            style={styles.containerPanelCategory}
            setSelectedCategory={setSelectedCategory}
            selectedCategory={selectedCategory}
            serviceCategories={props.serviceCategories}
            {...props}
        />
        <PanelServices style={styles.containerPanelService} />
    </View>
);

};

How do I display a metafield property only if the field is filled, else hide it?

This code snippet should display the metafield only if the field is filled.

{%- if line_item.properties != empty -%}
<ul class="CartItem__PropertyList">
{%- for property in line_item.properties -%}
{%- assign first_character_in_key = property.first | truncate: 1, '' -%}
{%- if property.last == blank or first_character_in_key == '_' -%}
{%- continue -%}
{%- endif -%}
<p class="CartItem__Variant">Ringgröße: {{ property.last }}</p>
{%- endfor -%}
</ul>

firebase error html file, can’t read the file in html and won’t add just got an error

I’m trying to run firebase using html file, it is necessary to use install http server cause that is the only thing i did not have in the video, and also i did not have the 3 array in the console that show in the video when i run live service in browser, that show that vscode did not read the file from firebase, i run the html live server from safari mac

error at 5:58 / 9:20min

Getting Started with Firebase 9 #5 – Adding & Deleting Documents

https://www.youtube.com/watch?v=s1frrNxq4js&list=PL4cUxeGkcC9jERUGvbudErNCeSZHWUVlb&index=5

Failed to load resource: the server responded with a status of 404 (Not Found)
http://192.168.1.7:5500/favicon.ico

[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (favicon.ico, line 0)

Folder-dist

File-bundle.js

/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
/******/ (() => { // webpackBootstrap
/******/    var __webpack_modules__ = ({

/***/ "./scr/index.js":
/*!**********************!*
  !*** ./scr/index.js ***!
  **********************/
/***/ (() => {

eval("console.log('hello from index.js')nn//# sourceURL=webpack://firebase9dojo/./scr/index.js?");

/***/ })

/******/    });
/************************************************************************/
/******/    
/******/    // startup
/******/    // Load entry module and return exports
/******/    // This entry module can't be inlined because the eval devtool is used.
/******/    var __webpack_exports__ = {};
/******/    __webpack_modules__["./scr/index.js"]();
/******/    
/******/ })()
;

File-index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Firebase 9</title>
</head>
<body>
    <h1>Getting started with Firebase 9</h1>




    <h2>Firebase Firestore</h2>
    <form class="add">
        <label for="title">Tittle:</label>
        <input type="text" name="title" required>
        <label for="author">Author:</label>
        <input type="text" name="author" required>

        <button>add a new book</button>
    </form>

    <form class="delete">
        <label for="id">Document id:</label>
        <input type="text" name="id" required>

        <button>delete a book</button>
    </form>





    <script src="bundle.js"></script>
</body>
</html>

Folder-node_modules

Folder-scr

File-index.js

import { initializeApp } from 'firebase/app'
import {
  getFirestore, collection, getDocs,
  addDoc
} from 'firebase/firestore'//using "Firestore Database" from firebase -2

const firebaseConfig = {
    apiKey: "12345",//use your own firebase for this
    authDomain: "12345.firebaseapp.com",//use your own firebase for this
    projectId: "12345",//use your own firebase for this
    storageBucket: "12345ea.appspot.com",//use your own firebase for this
    messagingSenderId: "12345",//use your own firebase for this
    appId: "12345"//use your own firebase for this
  };

//init firebase app
  //method.firebase object
initializeApp(firebaseConfig)

//init services-2
const db = getFirestore()

//collection ref-2
const colRef = collection(db, 'books')

//get collection data-2
getDocs(colRef)
  .then((snapshot) => {
    //console.log(snapshot.docs)
    let books = snapshot.docs.forEach((doc) => {
        books.push({ ...doc.data(), id: doc.id })
    })
    console.log(books)
  })
  .catch(err => {
      console.log(err.message)
  })





  //adding documuments
  const addBookForm = document.querySelector('.add')
  addBookForm.addEventListener('submit', (e) => {
      e.preventDefault()
    addDoc(colRef, {
        title: addBookForm.title.value,
        author: addBookForm.author.value,
    })
    .then(() => {
        addBookForm.reset()
    })
  })

//deleting documents
const deleteBookForm = document.querySelector('.delete')
deleteBookForm.addEventListener('submit', (e) => {
    e.preventDefault()
})

File-package-lock.json

File-package.json

{
  "name": "firebase9dojo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.70.0",
    "webpack-cli": "^4.9.2"
  },
  "dependencies": {
    "firebase": "^9.6.8"
  }
}

File-webpack.config.js

const path = require('path')

module.exports = {
  mode: 'development',
  entry: './scr/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  watch: true
}

Map over string array and create property’s for an object in Javascript

Apologies I know this is a basic question for Senior developers out there, but I am trying to create a data structure that is baffling me at the moment.

I have a string array like so:

let stringArray = ['Core', 'Regional'];

And I would like to create this data structure:

[
  {'key': 'Core', 'text': 'Core'},
  {'key': 'Regional', 'text': 'Regional'}
]

Please can somebody help me .map over the stringArray to create the datacstructure above? ^

Move all elements with class inside div

I’m brand new to js, and tried to move every elements with certain class inside a certain div.
I made some research and saw a solution that works with id, but when I tried to change it to classNames it didn’t work anymore.
Is there anything more to write ?

Here is my HTML

<div class="bottom">bottom 1</div>
<div class="bottom">bottom 2</div>
<div id="top">top</div>

and my script so far

document.getElementById('top').appendChild(document.getElementsByClassName('bottom'))
console.log(document.getElementById('top').innerHTML)

I understood that appendChild didn’t work because document.getElementsByClassName(‘bottom’) is an array string instead of a node, but I have absolutely no idea what a node is, neither how to change my code for it to work.

I would really appreciate any help at all !
Thanks.

Can we access single javascript object from two nodejs files [closed]

tester.mjs:

var instance = null;
export default class tester {
  constructor() {
   this.name = null;
  }
  static getInstance(){
    if(!instance){
      console.log("Creating instance")
      instance = new tester();
    }
    return instance;
  }
  
  setName(name) {
   this.name = name
  }
  
  getName() {
   return this.name
  }
}

file1.mjs:

import tester from './tester';
var obj = tester.getInstance();
obj.setName("seetha")

file2.mjs:

import tester from './tester';
var obj1 = tester.getInstance();
console.log(obj1.getName())

I am trying to set the name from file1.mjs and get the name from file2.mjs.First I run file1.mjs then it creates one javascript object for tester.mjs.Second I run file2.mjs then it again creating new javascript object for tester.mjs.But I want to use single javascript object of tester in both file1.mjs,file2.mjs and I want to run file1.mjs and file2.mjs independently.
Can anyone suggest me to achieve this.

How to smooth scrolling when clicking an japanese anchor link

My anchor link generated automatically:

<a class="" href="#Heading_3" title=">Heading 3</a>
<a class="" href="#%E3%81%A8%E3%80%81%E3%82%B2%E3" title=">ゲゲームのフ</a>

and anchor to

<h4><span class="" id="Heading_3"></span>Heading 3<span class=""></span></h4>
<h4><span class="" id="#%E3%81%A8%E3%80%81%E3%82%B2%E3"></span>ゲゲームのフ<span class=""></span></h4>

I use Javascrip & JQuery to smooth scrolling.

$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});

So, only heading 3 working ok, but link Japanese not working. How to scroll to link have Japanese smoothly?

Problem with button activation with v-slot activator

I’m using v-slot:activator with v-btn in my Vuejs project. it works fine but the button stays hovered as if it was pressed

       <v-dialog v-model="dialog" max-width="600px">
        <template v-slot:activator="{ on, attrs }">
          <v-btn color="#F65C38" dark class="mt-1 mr-2" width="209px" v-on="on" v-bind="attrs"> Example Btn </v-btn>
        </template>
        <v-card>
          <v-card-title>
            <span class="text-h5">{{ formTitle }}</span>
          </v-card-title>

          <v-card-text>
            <v-form ref="form" v-model="valid">
              <v-container>
                <v-row>
                 

                  
               
           
                </v-row>
              </v-container>
            </v-form>
          </v-card-text>

          <v-card-actions class="d-flex justify-center">
            <v-btn color="#f66037" plain @click="close" elevation="4" dark width="209" class="mb-6"> No </v-btn>
            <v-btn color="#F65C38" @click="save" dark width="209" class="mb-6"> save </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

data:

dialog: false

watch:

  dialog(val) {
      val || this.close();
    },

method:

    close() {
  this.dialog = false;
  this.$nextTick(() => {
    this.editedItem = Object.assign({}, this.defaultItem);
    this.editedIndex = -1;
  });

before click
enter image description here

after clickenter image description here