Call A Function Inside Of Other File

I’m Trying To Create A Npm Module That When You Call It, It’s Supposed To Execute The main()
Function In The index.js (file that calls the module) File.

But When I Try To Run It It Says :

Error: 
 ReferenceError: main is not defined

Here Is The Files

(module) index.js:

try {
    main()
} catch (error) { 
    console.log(`Error: n ${error}`) 
} 

(test file) test.js

var js = require("./index")

function main() {
    console.log("Better JS Working")

    return 0
}

(Why) Is lodash slow?

I was stunned by the reults described in this answer and supported by this two benchmarks that compare that solution (native JavaScript) with the one I proposed (Lodash).

I’ve also compared the proposed solution:

const obj = {
  name: undefined,
  age: 15,
  school: 'Some school'
}

const hasOnly = (obj,props) => {
    var objProps = Object.keys(obj)
    return objProps.length == props.length && props.every(p => objProps.includes(p))
}

console.log(hasOnly(obj,['name','age'])) //return false
console.log(hasOnly(obj,['name','age','city'])) //return false
console.log(hasOnly(obj,['name','age','school'])) //return true

with one where I truly simply switch from every native function to the corresponing function in Lodash,

hasOnly = (obj,props) => {
    const objProps = _.keys(obj)
    return _.size(objProps) == _.size(props) && _.every(_.includes(objProps), props);
}

and the result is still disappointly in favour of the native solution.

Now, the one above might be a silly example, but still… > 90% slower? Then what am I using Lodash for? I mean, in different scenarios it can improve readability, expecially when funtions have to be partially applied and passed around, where Lodash saves you from a lot of x => x. (classic example arrayOfarrays.map(_.map(fOnTheElements)) instead of arrayOfarrays.map(arr => arr.map(fOnTheElements))), but if the peformance is so low, then it’s a bit hard to make the expressivity enough to choose Lodash over native code.

I’m new to JavaScript and Lodash (just not totally new to functional programming), so I don’t even know the reliability of the benchmark tool that was used in the linked answer, but I can’t believe it makes such a bad job that reverses the result.

Live Telemetry for Racing Cars

So I’m making a Real-time Telemetry WebApp for tracking data from a car. I’ am using React for frontend and Node.js for backend. It works like this. A device sends data to the webpage using the MQTT protocol. When the data is received on the web page, it is decoded, parsed and stored in the data base for further use.

My question is: What is the best way to store the data in the database? I’m using MySQL. For now I’m using a timer on the frontend that will mount/unmount the component so the POST request is triggered, but that is not a good solution because I need data to be stored when it’s received so what I need is some sort of “trigger” that will launch a POST request to store the data. I was thinking of using websockets but I have no idea how to make it work. I’m looking for tips or a better solution if there is any.

convert Jquery code to javascript – click not working

This is the code where I need to convert Jquery code to javascript code but converted javascript code not working. please check code –

HTML

<nav class='animated bounceInDown'>
<ul>
    
    <li class='sub-menu'><a href='#settings'>Settings<div class='fa fa-caret-down right'></div></a>
        <ul>
            <li><a href='#settings'>Account</a></li>
            <li><a href='#settings'>Profile</a></li>
            <li><a href='#settings'>Secruity &amp; Privacy</a></li>
            <li><a href='#settings'>Password</a></li>
            <li><a href='#settings'>Notification</a></li>
        </ul>
    </li>
    
</ul>

CSS

 body {
    background-color: #fff;
    font-size: 14px;
}
nav {
    position: relative;
    margin: 50px;
    width: 360px;
}
nav ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
nav ul li {
  /* Sub Menu */
}
nav ul li a {
    display: block;
    background: #ebebeb;
    padding: 10px 15px;
    color: #333;
    text-decoration: none;
    -webkit-transition: 0.2s linear;
    -moz-transition: 0.2s linear;
    -ms-transition: 0.2s linear;
    -o-transition: 0.2s linear;
    transition: 0.2s linear;
}
nav ul li a:hover {
    background: #f8f8f8;
    color: #515151;
}
nav ul li a .fa {
    width: 16px;
    text-align: center;
    margin-right: 5px;
    float:right;
}
nav ul ul {
    background-color:#ebebeb;
}
nav ul li ul li a {
    background: #f8f8f8;
    border-left: 4px solid transparent;
    padding: 10px 20px;
}
nav ul li ul li a:hover {
    background: #ebebeb;
    border-left: 4px solid #3498db;
}

jQUERY code

   $('.sub-menu ul').hide();
$(".sub-menu a").click(function () {
  $(this).parent(".sub-menu").children("ul").slideToggle("100");
  $(this).find(".right").toggleClass("fa-caret-up fa-caret-down");
});

CONVERTED javascript code

document.querySelectorAll(".sub-menu ul").style.display = "none";
document.querySelectorAll(".sub-menu a").click(function () {
  this.parent(".sub-menu").children("ul").slideToggle("100");
  this.find(".right").toggleClass("fa-caret-up fa-caret-down");
});

The problem is javascript code is not working dropdown not hide and also click is not working..
please check it onces.

Styles doesn’t load in astro

I’ve been using scss modules with React in Astro. Styles doesn’t wanna load when passed “client:only” prop to react component wchich is required for app to work correctly. This strange bug only occures in production.

Also when I pass that prop to any other react component styles in this component doesn’t work anymore in production.

When i create 2 functions in java script and initialize a variable A in function 1, can I use this variable in function2?

I am a beginner in java script, and I have got a problem here and would really appreciate the help.

I created a function called menu and I want to get a value from the user in an excel sheet and do an action based on that value in another function. So I have two questions:-

1- When i create 2 functions in java script and initialize a variable A in function 1, can I use this variable in function2? I couldn’t test that because I’m using google app script and I can only run one function.

2- (In the code) –> How to get the value from the use and use it in another function (If my first question is true). The value I’m trying to get is the wn, and i tried to Logger.log(wn) twice and they had the same values(348-372)!

function menu(){
        //get the good week number
        var date = new Date();
        var wn = [(Math.floor(WEEKNUMBER(date))+3).toFixed(0)]
        do {  
            wn.push((wn[wn.length-1]-1).toFixed(0))
        } while(wn[wn.length-1] != 348);
        var line = "<select style='width:60px;height:40px;' id='select'>"
        for ( var x in wn ) // thats the loop taht is going to show all the weeks for the user
          line +="<option>" + wn[x] + "</option>"
        line +="</select>"
        Logger.log(wn);
        var ui = SpreadsheetApp.getUi();
        var html = HtmlService.createHtmlOutputFromFile('Selector')
            .setWidth(200)
            .setHeight(150).setContent("<div>"+line + "</div><br>.  <div><button onclick='reset()'>Confirm</button> </div>.  <script>function  reset(){var wn = document.getElementById('select').value;document.getElementsByTagName('Body')[0].style.cursor = 'wait';google.script.run.withSuccessHandler(function (){google.script.host.close();}).readWP2(wn);}</script>")
        SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
            .showModalDialog(html, 'Please select a week number');
Logger.log(wn);
}

If you need more explanation please let me know

Running an individual .spec file from the command line in Mocha

I’m trying to run a Mocha .spec file separately through the command line, however I am struggling to do this properly.

I am needing to run a separate file using the command line:
npm run-script test:component:file then pass in a .spec file that needs running separately, e.g. test_file.spec

I’ve been trying to use –grep then a match using the * character to try and match against the test in the describe block of the .spec file.

Is there a way to do this in Mocha?

Angular Request-Response Cycle

I created an Angular app which has 1 Home Component & 6 other Component. All 6 Component contains only html text(Articles on some topic) not any js/ts code. in home component, I use router-outlet to switch between 6 components. Then I build and deploy.

I want to know that how actually Angular request-response cycle works. When I switch between 6 components of article it call request every time to front-end server OR at first time, it loads all data of website and javascript files only change the article texts.

Firebase Cloud function-Get document snapshot field which is the URL of a file in firebase storage and delete the file from firebase storage – js

I want to retrieve the field value from a document snapshot which is the URL of a file in firebase storage and delete the file from firebase storage also the firestore document if the time of creation of the doc is before 24 hrs.

I am able to delete expired firestore documents successfully with the code below:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { firestore } = require("firebase-admin");
admin.initializeApp();

exports.removeExpiredDocuments = functions.pubsub.schedule("every 1 hours").onRun(async (context) => {
  const db = admin.firestore();
  const now = firestore.Timestamp.now();
  const ts = firestore.Timestamp.fromMillis(now.toMillis() - 86400000); // 24 hours in milliseconds = 86400000

  const snap = await db.collection("photos").where("timestamp", "<", ts).get();
  let promises = [];
  snap.forEach((snap) => {
    promises.push(snap.ref.delete());
  });
  return Promise.all(promises);
});

but I don’t know how to retrieve the field value(URL of file) from the document snapshot within the forEach block and delete the file from firebase storage.

Here’s the firestore database:

enter image description here

The field value of photourl is to be retreived.

Deleting with React Redux delete request

I need help, I’m new to this.
When i click on delete product button i get DELETE error http://localhost:4000/characteristics-values 401 (Unauthorized)
ProductItem.tsx

const product: IGetProductById = useSelector((state: RootState) => state.products.currentProduct); 


    
const handleDeleteProduct = () => {
        dispatch(deleteProductRequest(product));
        goBack();
      };

product.action.tsx

// delete product
export const deleteProductRequest = (product: IGetProductById): IActions => ({
  type: DELETE_PRODUCT_REQUEST,
  data: product,
});

How to fetch nearest locations from mongodb using nodejs?

Note: $near returns empty array instead of nearest locations in mongoose

Basically, I am trying to return the nearest locations from the given location in nodejs.
I’ve tried to implement several answers from S.O. but they didn’t work.

I’m able to post data in this schema and also able to fetch it. But when I pass some long, lat in Get request of postman URL, it returns me an empty array instead of actual data.

Here is my schema looks like

Model.js

const ShopSchema = new Schema({
  shop_name: {
   type: String,
   required: true 
  },
  location: {
    type: {
      type: String,
      enum: ['Point'],
      default: 'Point',
     },
     coordinates: {
       type: [Number],
       default: [0,0],
     }
  }
});

ShopSchema.index({location: "2dsphere"});

const Shops = mongoose.model('Shops', ShopSchema);

module.exports = Shops;

Controller.js

exports.getNearestShops = async (req, res) => {
  // trimming to get only values after = sign and parse it to float
  const long = parseFloat(req.params.long.split("=").pop());
  const lat = parseFloat(req.params.lat.split("=").pop());

  try {
   // Shops is model imported from model.js
   const resData = await Shops.find({
     location: {
       $near: {
         $maxDistance: 5000,
         $geometry: {
            type: "Point",
            coordinates: [long, lat]
         },
       },
     },
   });
   console.log(resData);
   return res.send(resData)
  } catch (err) {
      console.log(err);
      return res.send(err);
    }
}

On passing the longitude and latitude in the postman URL, it returns me []. Even though I have stored coordinates that fulfill the $maxDistance: 5000

pm2 start config.js file which only starts some of the processes

So currently we have a config.js file which exports a list of {apps} which pm2 takes and starts up (pm2 start core.config.js).

However some of these must not actually be started. In other words it must start in a downed state.
This is cause if a client manually sets certain services(processes) to be off, pm2 must not start them but they should still be visible on pm2 status but as “Stopped” or “disabled”

pm2 status with a process down

Example would be the integrationMicroService in the image

Send JSON request to backend – seeing some unicode chars and weird info in wire shark

I am writing a simple sample code to send some JSON data to our C++ backend data – this excercise is to write a backend handler to receive, process and generate a response from backend for a specified JSON request. I have written a sample front end script but I see some un-expected issue – below is the same:

HTML Script:

<html>
<head><title>Json Test</title></head>
<script>
// Sending and receiving data in JSON format using GET method
//     
function submitform(){
var xhr = new XMLHttpRequest();
var url = "http://199.167.110.185?jsdata=" +  JSON.stringify({"name" : document.forms["JSForm"].fname.value, "surname" : document.forms["JSForm"].lname.value, "email": "[email protected]", "password": "xxxxxxx"});
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
alert("Sending Json : " + url); 
xhr.send();
}
</script>

<body>
    <form name="JSForm">
        <p><label for="first_name">First Name:</label>
        <input type="text" name="first_name" id="fname"></p>

        <p><label for="last_name">Last Name:</label>
        <input type="text" name="last_name" id="lname"></p>

        <input value="Submit JSON Request" type="Submit" onclick="submitform()">
    </form>
</body>
</html>

Here’s what I see as alert – I entered ‘First Name Data’ as First name and ‘Last Name Data’ against Last name inputs:

enter image description here

And in wireshark logs:

enter image description here

As you can see that in wireshark info section I see:

OPTIONS /?jsdata={%22name%22:%22First%20Name%20Data%22,%22surname%22:%22Last%20Name%20Data%22,%22email%22:%[email protected]%22,%22password%22:%22xxxxxxx%22} HTTP/1.1 

What is this ‘OPTIONS‘ and ‘%22‘ tag means in wireshark and where it is comming from? Is it possible to remove them see as I see in alert message box or it is expected?