app crashed – waiting for file changes before starting… and showing typescript error even code is in JS

I am getting below error when I’m start server npm start.

Error: try {
^
SyntaxError: Unexpected token ‘{‘
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1178:20)
at Module._compile (node:internal/modules/cjs/loader:1220:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

Node.js v18.17.1
[nodemon] app crashed – waiting for file changes before starting…

Screenshot:
Error screenshot

Code:

index.js

const express = require('express');
const Razorpay = require( 'razorpay' );
const cors = require( "cors" );
require('dotenv').config();

const PORT = process.env.PORT;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.post('/order', async (res, req) = {
    try {
        const razorpay = new Razorpay({
            key_id: process.env.RAZORPAY_KEY_ID, 
            key_secret: process.env.RAZORPAY_KEY_SECRET,
        });
        
        const options = req.body;
        const order = await razorpay.orders.create(options);
        if(!order){
            return res.status(500).send("Error");
        }
        res.json(order);

    } catch (err) {
        console.log(err);
        res.status(500).send("Error");
        
    }
});

app.listen(PORT, () =>{
    console.log('Listening on the port',PORT);
});

Package.json:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "nodemon": "^3.1.0",
    "razorpay": "^2.9.3"
  }
}

I don’t know why this code is showing typescript error even it’s in javascript.

Can someone help on this.

Tried renaming the file but it’s not working.

Using reduce() alters the original array in JavaScript depite docs claiming otherwise

I’m declaring the following array.

let arr = [
  { id:"aa", vals:[1,2,3] }, 
  { id:"cc", vals:[3,4,5] }, 
  { id:"bb", vals:[2,3,4] }];

Printing it in the console confirms the expectation as each element has two fiels: a string id and a number array vals. Then, I perform reduce(...) on it like this.

let reduction = arr.reduce((a,b) => a[b.id] = b, {});

My expectation is a single object with the fields corresponding to the ID values of the iterated array, i.e. aa, bb and cc, where each of those three fields contains the corresponding element from the original array.

What I get is only the last one element following the expectation, while the first two get convoluted somehow, being equipped with additional fields. Please note that I’m talking about changes in the original array! According to the docs: The reduce() method does not change the original array.

What am I missing?

The end-game desire is to simply convert an array to a dictionary by reducing it to a single instance but with arbitrarily added fields. There’s a bunch of resources to get inspiration from out there. So this question relates only to this unexpected behavior.

for…in with arrays in JavaScript

I’ve been reading that you should not use for…in with arrays in JavaScript. However, in the course I’m taking we were given the following example and it works… in code pen but not in the browser inspector (at least not for me).

Am I doing something wrong?

var players = [
  'PlayerOne',
  'PlayerTwo',
  'PlayerThree',
  'PlayerFour'
];

for (player in players) {
  console.log(players[player]);
}

for (var i = 0; i < players.length; i++) {
  console.log(players[i]);
}

players.forEach(function(element) {
  console.log(element);
});

It is supposed to iterate the array and print the players one by one. Once it gets to the last one, it starts over. However, when I use the inspector it only prints undefined. I don’t know if I am doing it wrong or what.

Shelly get voltage

I am struggeling to get the current voltage out of Shelly via script.

I added an event, whenever the power changes, the current voltage should be printed. But result is always undefined.

Shelly.addEventHandler(
  function(apower_change,ud){
    
    print('Power: ' + apower_change.info.apower);
    
    Shelly.call("Voltmeter.GetStatus",{id: 0},
      function(result,error_code,error_message,ud){
        print(result);
      },null
    );
  },null
);

Unable to call google maps js api

I’m trying to use the google maps api on the following page, which is a stripped down django template:

{% load static %}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  function myMap() {
    var map_properties = {
      center: new google.maps.LatLng(40, -100),
      zoom: 17, MapId: '<...>' }
    var map = new google.maps.Map(document.getElementById("google_map_div"), map_properties);
    map.setMapTypeId("satellite"); 
  } // myMap function
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<...>&callback=myMap"></script>
</head>
<body>
  <div id="google_map_div" style="width: 600px; height: 600px; border: 5px solid black;"></div>
</body>
</html>

I’m not getting any results and the myMap function is not executing so I’m guessing an error with the script load? I do have a registered api key and map id.

useSelector hook is not providing data on time upon requesting from strapi server

Catalogue Component where all product cards are rendered.

import {useSelector} from 'react-redux'
function Catalogue (){

    let storeProducts = useSelector(state => state.productStore.products)
    
    useEffect(()=>{
        console.log(storeProducts[0].data)
    }, [])

    return (
        <>
         <div className="product-section">
                         
            <ProductCard image={casualWear} id = {1} name={'Bebas White Oversized Shirt'} stats={{category : 'Tops & Apparels', color : 'red'}}/>
        </>
    )
}

Store Slice

import { createSlice } from "@reduxjs/toolkit";

let storeSlice = createSlice({
    name : "store",
    initialState : {
        products : []
    },
    reducers : {
        setStoreProducts : (state, action)=>{
            state.products = [...state.products, action.payload]
        }
    }
})


export default storeSlice.reducer

export const {setStoreProducts} = storeSlice.actions

Store Page Component

Here I’m using strapi 4 and you can see I’m making a simple fetch request to get data. I use dispatch function to pass data to redux state.

import React, { useEffect, useState } from "react";

import Header from "../components/header";
import Footer from "../components/footer";
import ActionMenu from "../components/actionMenu";
import Catalogue from "../components/catalogue";

import { useDispatch } from "react-redux";
import { setStoreProducts } from "../state-manager/Slices/storeSlice";



function Store (){
    let [shopProducts, setShopProducts] = useState([])
    let dispatch = useDispatch()
    useEffect(()=>{
        
        document.title = 'TRAX - Catalogue'
        
        
        fetch('http://localhost:1337/api/shopping-products?populate=*').then(res =>{
            return res.json()
        }).then(data =>{
            console.log(data)
            dispatch(setStoreProducts(data))
        }).catch(error => {
            console.log(error)
        })
        
        
    }, [])

    return (
        <>
            <Header />
            <ActionMenu />
            <Catalogue/>
            <Footer/>
        </>
    )

}
export default Store;

I’m not sure but I think since catalogue is rendered with the store component and maybe state is updated after the component has mount. That’s why I’m getting this issue.

Please let me know.

I’d really appreciate the help.

How to safely remove an item from a dictionary in manifest.json?

I’m trying to tweak an app for work and need to remove an option that is being displayed in the webconsole of this app. The app itself is in C and the webapp part is in JS (I’m not familiar with JS or any of its frameworks). My understanding is that I simply need to remove the menu option given in its manifest.json file. The menu part looks something like this:

.
.
.
"menu": {
        "index": {
            "label": "Name of Section",
            "order": 30,
            "docs": [
                {
                    "label": "Menu item 1",
                    "url": "https://documentation_url"
                },
                {
                    "label": "Menu item 2",
                    "url": "https://documentation_url"
                },
                {
                    "label": "Menu item 3",
                    "url": "https://documentation_url"
                },
                {
                    "label": "Menu item 4",
                    "url": "https://documentation_url"
                }],
              }
    },
   "config": { //some config related stuff here
.
.
.

Now in this, I want to delete “menu item 3”. If I simply delete it, the compilation itself is faiing (of the C files) but I cannot figure out how is the manifest.json related to something in the c files. I did do a search of the “Menu item 3” but I could not see any links to that in any of the C files.

What else should I be checking before simply deleting the Menu item from manifest.json, is there any other way for me to hide this menu item without deleting it from the json file ?

(javascript object), set same value to next value if greater than previous value, And versa

i have list of object ,

i want to compare value id to next value, if less than previous value, assign new key named IDS and set value to "1", why exactly (1), because its started from first object in array.

is same thing in case the next value is greater than previous value.

This is what I can explain.
For parts (4, 5) and (2 ,3) I find it difficult to explain this part.

and thank you in advance.

let lists = [
  { price:10, id:1},
  { price:11, id:2},
  { price:12, id:3},
  { price:13, id:4},
  { price:14, id:5},

  { price:12, id:4},//this part
  { price:12, id:5},//this part

  { price:11, id:4},
  { price:10, id:3},
  { price:9,  id:2},

  { price:12, id:3},//this part
  { price:12, id:2},//this part
]

Result:

let lists = [
  { price:10, id:1, IDS:1 },
  { price:11, id:2, IDS:1 },
  { price:12, id:3, IDS:1 },
  { price:13, id:4, IDS:1 },
  { price:14, id:5, IDS:1 },

  { price:12, id:4, IDS:2 },
  { price:12, id:5, IDS:2 },

  { price:11, id:4, IDS:3 },
  { price:10, id:3, IDS:3 },
  { price:9,  id:2, IDS:3 },

  { price:12, id:3, IDS:4 },
  { price:12, id:2, IDS:4 },
]

Implementing a Creeping Line Ahead (CLA) to Tasking Area Search Pattern Transition in Leaflet.js

I have a requirement to draw a Creeping Line Ahead (CLA) pattern using Leaflet.js over a tasking area (squares, rectangles, and generic polygons). The CLA pattern includes parallel lines with shorter straight-line segments than the total width of the area to be searched.

Here’s an example of the CLA pattern: enter image description here.

The search pattern options include:

  • Track spacing (distance between each parallel line segment)
  • Initial heading
  • First turn direction
  • Distance from the edge of the search area

Here’s the relevant code I’ve written:

<!DOCTYPE html>
<html>
<head>
    <title>Leaflet Creeping Line Ahead Pattern</title>
    <!-- Include Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <!-- Include Leaflet JavaScript -->
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <style>
        /* Set the size of the map */
        #map {
            height: 500px;
            width: 100%;
        }
    </style>
</head>
<body>
    <h2>Leaflet Creeping Line Ahead Pattern</h2>
    <!-- Create a div element to hold the map -->
    <div id="map"></div>

    <script>
        // Initialize the map and set its view to a given location and zoom level
        var map = L.map('map').setView([9.5415, 35.2651], 14);

        // Add an OpenStreetMap layer to the map
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // Define the coordinates of the rectangle
        const rectangleCoords = [
            [9.531347, 35.25444], // top-left corner (latitude, longitude)
            [9.552678, 35.25444], // top-right corner (latitude, longitude)
            [9.552678, 35.27577], // bottom-right corner (latitude, longitude)
            [9.531347, 35.27577]  // bottom-left corner (latitude, longitude)
        ];

        // Create a polygon (rectangle) using the provided coordinates
        const rectangle = L.polygon(rectangleCoords, {
            color: 'blue', // Color of the rectangle border
            weight: 3, // Thickness of the rectangle border
            fillColor: 'blue', // Fill color of the rectangle
            fillOpacity: 0.2 // Opacity of the fill color
        }).addTo(map);

        // Function to draw the creeping line ahead pattern
        function drawCLA(bounds, start, initialHeading, firstTurn, trackSpacing, distanceFromEdge) {
            // Get the start and end points of the rectangle's longer side (e.g. east-west direction)
            let startPoint = start;
            let endPoint = [
                start[0] + (bounds.getNorthEast().lng - bounds.getSouthWest().lng) * Math.cos(initialHeading * Math.PI / 180),
                start[1] + (bounds.getNorthEast().lng - bounds.getSouthWest().lng) * Math.sin(initialHeading * Math.PI / 180)
            ];
            
            // Calculate the length of the rectangle's longer side
            const lineLength = bounds.getNorthEast().lng - bounds.getSouthWest().lng;

            // Initialize an array to hold the drawn lines
            const lines = [];
            const greyColor = 'grey';

            // Draw parallel lines
            while (startPoint[0] <= bounds.getNorthEast().lat) {
                // Draw a line from the current start point to the end point
                const line = L.polyline([startPoint, endPoint], {
                    color: greyColor,
                    weight: 2
                }).addTo(map);
                lines.push(line);

                // Calculate the next start and end points
                startPoint = [
                    startPoint[0] + trackSpacing,
                    startPoint[1]
                ];
                
                endPoint = [
                    endPoint[0] + trackSpacing,
                    endPoint[1]
                ];
            }

            return lines;
        }

        // Define the commence search point (CSP)
        const csp = [9.531347, 35.25444]; // CSP at the top-left corner of the rectangle

        // Set the initial heading, first turn, and track spacing
        const initialHeading = 90; // East direction (heading in degrees)
        const firstTurn = 'left'; // Direction of the first turn ('left' or 'right')
        const trackSpacing = 0.0003; // Spacing between each parallel line segment
        const distanceFromEdge = 0.0005; // Distance from the edge

        // Draw the creeping line ahead pattern inside the rectangle
        drawCLA(rectangle.getBounds(), csp, initialHeading, firstTurn, trackSpacing, distanceFromEdge);

        // Zoom the map to fit the bounds of the rectangle
        map.fitBounds(rectangle.getBounds());
    </script>
</body>
</html>

However, my current implementation does not produce the expected CLA pattern. Any help on how to correctly implement the CLA pattern using Leaflet.js would be greatly appreciated.

Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError Missing semicolon

    app.directive('scroll-bottom', {
      mounted(el, binding) {
        let timer: ReturnType<typeof setTimeout> | null = null;
        let preScrollTop = 0;
        el.addEventListener('scroll', () => {
          if (el.scrollHeight - el.scrollTop - 20 <= el.clientHeight && el.scrollTop > preScrollTop) {
            console.log('bottom');
            if (timer) {
              clearTimeout(timer);
            }
            timer = setTimeout(() => {
              binding.value();
            }, 300);
          }
          preScrollTop = el.scrollTop;
        });
      },
    });

enter image description here

Why is this error reported? I have a semicolon at the end of line 59.

I checked all the lines in this file and there is a semicolon at the end of each line.

dia anyone can help me?

Hope the code runs correctly.

Sync’ing cannon js bodies with three js

When I add a cannon body I have to manually adjust its position to cover with three js, and then when the body collides with another cannon and three bodies fall apart from eachother. What can I do to fix this?

I created cannon body from 3dmodel using threeToCannon and copy position and rotation from cannon to three every animation frame.

vthis.model_.scene.position.x=this.physBody_.position.x-5;
this.model_.scene.position.y=this.physBody_.position.y;
this.model_.scene.position.z=this.physBody_.position.z-10;


this.model_.scene.quaternion.copy(this.physBody_.quaternion);