GPS data representation

I am working on a GPS with PHP and Leaflet (JS) that works by creating a route between the points I have in the database. The GPS works usually with high precision but the problem is that the points sometimes get out of the road a little bit.

I want to ask if your know a better solution for this kind of case, preferring the use of Leaflet for that, likewise, I’m open to other solutions.

Thanks,
Guille

How to handle multiple individual json response?

Actually I am doing some testing in which I am getting response from one of our endpoint which looks like multiple individual json objets and I need to convert them in such a form like a string or a single json object so that I can perform some action on them.

Json response Example :-

{"user_name":"testUser","email":"[email protected]"}
{"country":"Australia","Gender":"Male"}
{"type":"Customer_Account","membership":"Annual"}

Here the issue is I can not perform any operation until I convert it to some string or Json object.

And cannot control response as its coming from some third party application.

Any idea how to convert it using JavaScript to Java will be a great help.

Javascript modification, Sum in output with discount on more selection

Code:

function totalIt() {
  var input = document.getElementsByName("product");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
    }
  }
  document.getElementsByName("total")[0].value = "₹" + total.toFixed(2);
}

Conditions:

No discount on first select

50% discount on 2nd selection

After 3rd selection, each has 25% discount

Expected Output:
Each check(box)’s value is 100,

  • on selection 1, Output = 100 (No discount)
  • on selection 2, Output = 150 (50% discount in 2nd selection)
  • on selection 3, Output = 175 (50% discount in 2nd, 25% discount on 3rd selection)
  • on selection 4, Output = 200 (50% discount in 2nd, * 25% discount on 3rd selection selection)
  • on selection, Output = 225 (50% discount in 2nd, 25% discount on 3rd selection selection)

beforeunload event and Content-Disposition=attachment

I recently add on my code something like this:

$(window).on('beforeunload', function () {
    $('.whirly-loader').show(); //SPINER
})

So anytime the user go to another side of my web the spinner show up. And it works most of the time.
But, in some part of the app the client start going another side and the server response with this headers:

Cache-Control
    max-age=0, must-revalidate, private
Connection
    Keep-Alive
Content-Disposition
    attachment;filename=suministro.csv
Content-Type
    text/csv; charset=utf-8
[...]

This prevents the reload of the page and only show up the window to ask to download or open the document.
My problem is the spinner still show up even if the page stop load

Which should be the event to hide my spinner even if the page don’t reload because of the headers?

Javascript code modification in SUM and Discount on more selection

function totalIt() {
  var input = document.getElementsByName("product");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
    }
  }
  document.getElementsByName("total")[0].value = "₹" + total.toFixed(2);
}

I want modify this javascript code as per below requirement.

Each check(box)’s value is 100,

  • suppose I select 1 checked(box), then output(total) should be 100 (No discount)
  • I select 2 checked(box), then Output(total) should be 150 (50% discount in 2nd selection)
  • Suppose I select 3 checked(box), then Output should(total) be 175 (50% discount in 2nd, 25% discount on 3rd selection)
  • Suppose I select 4 checked(box), then Output should(total) be 200 (50% discount in 2nd, * 25% discount on 3rd selection selection)
    Suppose I select 5 checked(box), then Output should(total) be 255 (50% discount in 2nd, 25% discount on 3rd selection selection)

Conditions:

  • No discount on first select
  • 50% discount on 2nd selection
  • After 3rd selection, each has 25% discount

Last label on xaxis disappears when resize

I am trying to force highcharts to show last label on x-axis when “step” is enabled. Code below works but it hides last label when I change device width (let’s say open chrome console). Problem arises on mobile devices when I scroll down after the chart, last label disappears. Reproducible example – Working code

   chart:
   {
        renderTo: "container",
        type: "line",
        events:{
             load:function(){
                 var ticks = $.map(this.axes[0].ticks, function(t){return t;});
                   ticks[ticks.length-2].render(0);
            }
         }
    }

getting mysql syntax error while using parameters in mysql query

Getting sql syntax error in nodejs

Am using this code :

async function getNotificationFsql(data) {
    var query = "select * from notifications where id>${data.start} and receiver=${data.recId} limit 10";
    var record = await db.sequelize.query(query ,
        function (err,results) {
            if (err) {
                console.log('Error while getting data from MYSQL     :-   ' + err);
            } else {
                console.log('Notifications data which we got from MYSQL     :-   ' + results);
            }
        }
    );
    // console.log(record);
    console.log('Notifications      :-   ' + record[0]);
    return record[0];
};

And I got:

code: ‘ER_PARSE_ERROR’,
errno: 1064,
sqlState: ‘42000’,

sqlMessage: “You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘{data.start} and receiver=${data.recId} limit 10’ at line 1”,

sql: ‘select * from notifications where id>${data.start} and receiver=${data.recId} limit 10’,
parameters: undefined
},
sql: ‘select * from notifications where id>${data.start} and receiver=${data.recId} limit 10’,
parameters: undefined

What am I doing wrong?

Exclude edges from participating in the layout

Consider a graph like the one shown below:

Graph taken from the VisJS example site

I would like to be able to display/hide the red edges (forget that they are hand drawn) shown below when the user clicks a button or similar:

Same example with added red edges

I don’t want the red edges to participate in the layout but instead for them to be shown as a kind of overlay. It would be nice if the edges could try to avoid overlapping any nodes in their path, but its definitely not required.

I think if I could set a boolean flag on the edges telling the layout engine to either include or exclude them from the layout setup, it could work. There is a physics parameter on the edge that I can override, but it doesn’t seem to help – the edge still participates in the layout.

I could probably also write some scripting which tracks the nodes and draw the red edges in another graph above, but that is specifically what I want to avoid.

Uncaught Invariant Violation on saving to redux store second time

I’m relatively new to React-Redux and was facing an issue where the if i update the state of a reducer param for the first time, it executes perfectly, then if i execute it again with some different value it throws this exception in my try/catch block :

Invariant Violation: 
A state mutation was detected between dispatches, in the path "object1.object2.0.object3.0.value"

Now I’ve added another update for the state whenever it catches the exception, and after the first exception, the states are updated accordingly and doesn’t give any exception for any further updates.

Previously it was happening for every update call but following a few solutions online, now it only happens when the value is updated for the second time. Here is the code snippet that I’m using to update my state.


let tempObject3 = [
  
  {
    name : "param1",
    value = "",
  }
  {
    name : "param2",
    value = "",
  }
  {
    name : "param3",
    value = "",
  }

];
const component = (props) = {

 //this state variable is updated every time there is a change in the form
 const [formState, setFormState] = React.useState({
    value1 : "",
    value2 : "",
    value3 : "",
  });

  const updateState = async () = {
   const temp = async () = {
     // have used other cloning libraries like just-clone and spread operator and JSON.parse(JSON.stringify(object))
     let object2Copy = _.cloneDeep(props.object2);
     for(var i=0; i<object2Copy.length; i++)
     {
       let object2ElementCopy = _.cloneDeep(object2Copy[i]);
       if(object2ElementCopy.name === "desiredName")
       {
         //code for populating tempObject3, with modified data from formState state variable

         if('object3' in object2ElementCopy)
         {
           let object3Copy = _.cloneDeep(object2ElementCopy.object3)
           object2ElementCopy = {...object2ElementCopy, object3 : tempObject3}
         }
         else
         {
           object2ElementCopy.object3 = tempObject3;
         }
         object2Copy[i] = object2ElementCopy
       }
     }
     return object2Copy;
    }
    try 
    {
      props.updateObject2(await temp());
    }
    catch(e)
    {
      //update after which no  further exceptions are caught
      props.updateObject2(await temp());
      console.log(e);
    }
  }
}

Some methods and objects used here are passed to props via MapDispatchToProps and MapStateToProps.

The exception only arises when I update it for the second time, although the same reducer is working fine in other components without the need for async and await.

Yes i know the logic should be in the reducer but I’ve even tried doing that and the same exception keeps happening. I’ve even created a new object in the reducer to save this data to which has only one level, still it was giving me the same error.

How to grab only search terms from URL, ignoring multiple delimiters

How can I edit this code to handle multiple delimiters? Currently, it checks for either %7 or |relevance and removes it. But it does not handle multiple delimiters such as in the 2 URL examples below.

https://www.example.com/en-us/search?pq=marketing+agriculture%7Crelevance%7CbestSeller%3Atrue

https://www.example.com/en-us/search?pq=marketing+agriculture|Crelevance|CbestSeller%3Atrue

It should only grab the words: marketing agriculture from the two URLs above.

const params = new URLSearchParams(window.location.search);

if (params.has('pq')) {
  const pq = params.get('pq').split('&7').pop().replace('|relevance', '');
  console.log(pq);
}

Desired output: To get only the search terms from the URL.

JavaScript: Making an If statement adjust to a variable after adding to it

I am creating a HTML/JavaScript page that displays world clocks, However I ran into a problem with the clocks not adjusting to the AM/PM correctly, and also not staying in the standard time format. I realize this is because the if statement that makes the session change to = ‘PM’ only works for the time zone it gets. Also my code only gets the time and puts it in the California slot because that is the time zone I am in, so if you open this code in a time zone other than pacific time, all of the world clocks will be incorrect. Is it possible to keep my clocks in a standard time format and also be the correct AM or PM?

<body>
    <div id="container">
        <div id="clockContainer">
            <div id="titleContainer">
                <p id="title">California</p>
                <p id="clock" class='clock'></p>
            </div>
            <div id="titleContainer">
                <p id="title">New York</p>
                <p id="york" class='clock'></p>
            </div>
            <div id="titleContainer">
                <p id="title">Hawaii</p>
                <p id="hawaii" class='clock'></p>
            </div>
        </div>
        <div id="clockContainer">
            <div id="titleContainer">
                <p id="title">Dubai</p>
                <p id="dubai" class='clock'></p>
            </div>
            <div id="titleContainer">
                <p id="title">Seconds</p>
                <p id="seconds" class='clock'></p>
            </div>
            <div id="titleContainer">
                <p id="title">London</p>
                <p id="london" class='clock'></p>
            </div>
        </div>
        <div id="clockContainer">
            <div id="titleContainer">
                <p id="title">Tokyo</p>
                <p id="tokyo" class='clock'></p>
            </div>
            <div id="titleContainer">
                <p id="title">Paris</p>
                <p id="paris" class='clock'></p>
            </div>
            <div id="titleContainer">
                <p id="title">Moscow</p>
                <p id="moscow" class='clock'></p>
            </div>
        </div>
    </div>
  </body>
</html>

<script>

let clock = document.getElementById('clock');

function currentTime() {

    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let session = 'AM';

    if(hours == 0){
        hours = 12
    }
    if (hours > 12){
        hours = hours - 12
        session = 'PM'
    }

    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;
    
    let time = hours + ':' + minutes + ' ' + session;
    document.getElementById('clock').innerText = time;
    
    let york = (hours + 3) + ':' + minutes + ' ' + session;
    document.getElementById('york').innerText = york;

    let hawaii = (hours - 2) + ':' + minutes + ' ' + session;
    document.getElementById('hawaii').innerText = hawaii;

    let dubai = (hours + 12) + ':' + minutes + ' ' + session;
    document.getElementById('dubai').innerText = dubai;

    document.getElementById('seconds').innerText = ':' + seconds;

    let london = (hours + 8) + ':' + minutes + ' ' + session;
    document.getElementById('london').innerText = london;

    let moscow = (hours + 12) + ':' + minutes + ' ' + session;
    document.getElementById('moscow').innerText = moscow;

    let paris = (hours + 9) + ':' + minutes + ' ' + session;
    document.getElementById('paris').innerText = paris;

    let tokyo = (hours + 17) + ':' + minutes + ' ' + session;
    document.getElementById('tokyo').innerText = tokyo;

    let t = setTimeout(function(){  currentTime() }, 1000);
}

currentTime();

</script>

Firebase Auth Emulator Failing (auth/network-request-failed)

I am developing a react native app using expo and firebase and am trying to set up the local emulator for testing/debugging. Creating accounts and logging in/logging out work on the actual database, but when I run these functions with the auth emulator attached, I get the following:

Firebase: Error (auth/network-request-failed).
at [native code]:null in construct
at [native code]:null in construct
at node_modules/@firebase/component/dist/esm/index.esm2017.js:348:0 in <global>
at http://192.168.1.187:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&minify=false:182911:26 in FirebaseError
at node_modules/@firebase/util/dist/index.esm2017.js:564:0 in <global>
at node_modules/tslib/tslib.js:283:4 in <anonymous>
at http://192.168.1.187:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&minify=false:185674:17 in <unknown>
at node_modules/@firebase/logger/dist/index.cjs.js:103:8 in Logger
at node_modules/@firebase/logger/dist/index.cjs.js:3:54 in <global>
at http://192.168.1.187:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&minify=false:184314:35 in rejected
at [native code]:null in flushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

This occurs on both an android pixel 5 emulator and my actual phone (galaxy s8+).
Other solutions for this error seem to be for browser security reasons (i.e. CORS), but that doesn’t seem to be applicable here. The code connecting to the emulator is:

import { initializeApp } from "firebase/app";
import {getAuth, connectAuthEmulator} from "firebase/auth";
import {getFirestore, connectFirestoreEmulator} from "firebase/firestore";
import {getFunctions, connectFunctionsEmulator} from "firebase/functions";

const firebaseConfig = {/* config object */};

const fbApp = initializeApp(firebaseConfig);

export const fbAuth = getAuth(fbApp);
connectAuthEmulator(fbAuth, "http://localhost:9099");
export const fbFunctions = getFunctions(fbApp);
connectFunctionsEmulator(fbFunctions, 'localhost', 5001);
export const db = getFirestore(fbApp);
connectFirestoreEmulator(db, 'localhost', 8080);

The port is correct and the emulator interface shows that auth is running fine.

How to go about checking for updates in pages that load completely only infront of a user?

I am making a chrome extension that checks for the existence of a node in a page. I am using an event handler(DOMNodeInserted, it is deprecated but works for my purpose), but it doesn’t seem to work when the user does not have chrome open(they have it minimised). How should I approach this? Trying to periodically reload the page and check also doesn’t work(b/c the user is required to be present for the page to load completely, hence why I used an event handler in the first place).