Laravel Livewire set is Removing Map Marker

I am using Laravel 8 with Livewire and am displaying a Mapbox map in my page.
When I click on the map, I am getting the coordinates of the click and placing a marker on the point where clicked. All working well up to this point.

What I am then trying to do is emit the coordinates to the Livewire component ready for saving along with other form details. However, when I click the map, the marker quickly appears then disappears; although the coordinates are emitted correctly and stored.

map.on('click', function(e){
            var coord = e.lngLat;

            updateCoords(coord);

            addMarker(coord);

        });

        function addMarker(coord) {
            if(newMarker != undefined) {
                newMarker.remove();
            }

            newMarker = new mapboxgl.Marker()
                .setLngLat([coord.lng, coord.lat])
                .addTo(map);
        }

        function updateCoords(coord) {
            @this.set('latitude', coord.lat);
            @this.set('longitude', coord.lng);
        }

I’ve tried emitting with a listener and using @this.set, both have the same effect.

The component isn’t doing anything special at the moment, but I can see that the coordinates are being passed correctly. Just the issue being that the map marker disappears from the map.

Any ideas?

having issues adding functionality to skip, play and pause a react music player

Below is the code with the react component, there is functionality to the play and pause button also the ability to skip to the next track or previous track.
Scenario: pressing ‘play button’
given ‘play’ button is displayed
when the ‘play’ button is clicked it should be replaced with ‘pause’.

Scenario: pressing ‘pause button’
given ‘pause’ button is displayed
when the ‘pause’ button is clicked it should be replaced with ‘play’.

Scenario: clicking ‘next button’
given some not last track is selected
when the ‘next’ button is clicked the next track on the list is selected.

Scenario: clicking ‘previous button’
given some not last track is selected
when the ‘previous’ button is clicked the previous track on the list is selected.

<!DOCTYPE html>
<html>
  <body class="main">
    <div id="app"></div>
  </body>
</html>




    const PlayButton = () => (
      <button
        aria-label="Play button"
        type="button"
        className="player-controls__btn player-controls__play-btn"
      />
    );
    
    const PauseButton = () => (
      <button
        aria-label="Pause button"
        type="button"
        className="player-controls__btn player-controls__pause-btn"
      />
    );
    
    const NextButton = () => (
      <button
        aria-label="Next button"
        type="button"
        className="player-controls__btn player-controls__next-btn"
      />
    );
    
    const PreviousButton = () => (
      <button
        aria-label="Previous button"
        type="button"
        className="player-controls__btn player-controls__prev-btn"
      />
    );
    
    const App = () => {
      const tracks = [
        {
          id: 1,
          name: 'Yesterday',
          artist: 'Beatles',
        },
        {
          id: 2,
          name: 'Nothing else matters',
          artist: 'Metallica',
        },
        {
          id: 3,
          name: 'Always',
          artist: 'Bon Jovi',
        },
        {
          id: 4,
          name: 'Waka Waka',
          artist: 'Shakira',
        },
      ];
      const [selectedTrack, setSelectedTrack] = React.useState({ ...tracks[0] });
      const [isPaused, setPaused] = React.useState(true);
    
      const onNextButtonClick = () => {
        // TODO: Write your code here
      };
      const onPreviousButtonClick = () => {
        // TODO: Write your code here
      };
    
    
      const renderTracks = () => tracks.map((track) => (
        <div className={`tracks-list__item ${selectedTrack.id === track.id ? 'tracks-list__item--selected' : ''}`} key={track.id}>
          <span className="tracks-list__name">{track.name}</span>
          <span className="tracks-list__artist">
            &nbsp;—&nbsp;
            {track.artist}
          </span>
        </div>
      ));
    
      return (
        <main>
          <div className="tracks-list">
            <h2 className="tracks-list__title">Tracks</h2>
            {renderTracks()}
          </div>
          <div className="player-controls">
            <PreviousButton />
            <PlayButton />
            <PauseButton/>
            <NextButton />
            <div className="player-controls__track">
              <span className="track__name">{selectedTrack.name}</span>
              <span className="track__artist">{selectedTrack.artist}</span>
            </div>
          </div>
        </main>
      );
    };
    
    ReactDOM.render(
      <App />,
      document.getElementById('app')
    );

Socket.IO : connect_error event not emitted

i have a simple socket.IO server, and a client that connects to it :

    socket = io('http://localhost:' + port + '/chat', {
        reconnection: false,
        query: {
            name: username
        }
    })

it works perfectly fine, but when i tried implementing the behavior of that client when the server cannot be found (which i simply test by just loading the page without starting the server), i faced a simple issue : the connect_error event is not emitter. Right after i initialize the socket, i have this code :

socket.on('connect_error', ()=>{
    console.log("Error! ")
})

as i said, this callback is never called, i get an error message in the console stating that the request returned 404 (http://localhost:5454/socket.io/?name=AA&EIO=4&transport=polling&t=O2__7JM), but my custom error message is never printed.
So, what am i doing wrong ? Isn’t this event supposed to be fired if the connection with the server couldn’t be established ? If not, how do i handle this situation (i.e. how do i make socket.io call a certain callback if the connection failed ?)

PHP file is not reading my js script file

I am trying to make sure my php file is reading my js file and when I click my decrease button, my console says

Uncaught ReferenceError: decrease is not defined
onclick http://localhost:3000/index.php:1

I know this is indicating that my decrease() function does not exist when I click the button which is not true. I made sure that I included the html script tag as well.

Here are both of my files

index.php

  <?php
  $price = 3;
  $quantity = 5;
  $total = $price * $quantity
?>

<!DOCTYPE html>
<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <p>Total: <?php echo $total; ?> </p>
    <button onclick='decrease();'>Click Me</button>
    <input type='text' id = 'num' value="0"></input>
    
    <script type='text/javascript' src='./index.js'></script>
  </body>
</html>

index.js

let i = null;

 
  function decrease(){
    i = i - 1;
    document.getElementById('num').value = i;
    console.log(i)
  }

I’ve tried to restart my webserver a few times and it did not work. What am I missing that its preventing it from seeing the function in my external js script file?

Defining multiple encrypted parameters

I have encrypted parameters in my url, for example:

encrypted
example.com/?auth= “encrypted data here including other paramaters like &username=helloworld&date=today”
example.com/?auth=WlJWm3+Sbv6P326v8L59gJyrCmnsjMUOa0sUw0WSPEA=

decrypted
example.com/?auth=succes&username=helloworld&date=today

Now would I like to do is define those usernames without showing the decrypted version on the client side. If the parameters would not be decrypted i know i can use

$username=$_GET['username'];

but now since the parameter + variable is encrypted i think i can not use it. What would be the best way to define a decrypted parameter without showing it in the url? I thought it myself and it might be possible with recognizing the & and = and have some script that recognizes, for example, the username because its between & and = and the hello world because its between the = and &, however I am not familiar with this type of coding.

eventlistner Uncaught TypeError: Cannot read properties of null [duplicate]

I have tried eveything in link

I am trying create some desktop app using electron. Kind of like a sound board thing.

In the index.html is some buttons that will play sound after a click.
renderer.js has the eventlistener for each of the button implemented.
However, all buttons were rendered and only button 1 and button 2 event listener are working
the eventlistener will failed for the button 3 and button 6, with an error

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at loadButtons (renderer.js:28:12)

index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
  <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">

  <link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.min.css">
  <title>LiveHelper</title>
</head>

<body id="main">
  <div class="container">
    <div class="row">
      <div class="col"><button id="sound1" type="button">Sound 1</button></div>
      <div class="col"><button id="sound2" type="button">Sound 2</button></div>
      <div class="col"><button id="sound3`" type="button">Sound 3</button></div>
    </div>  
    <div class="row">
      <div class="col"><button id="sound4" type="button">Sound 4</button></div>
      <div class="col"><button id="sound5" type="button">Sound 5</button></div>
      <div class="col"><button id="sound6`" type="button">Sound 6</button></div>
    </div>  
    <div class="row">
      <div class="col"><button id="sound7" type="button">Sound 7</button></div>
      <div class="col"><button id="sound8" type="button">Sound 8</button></div>
      <div class="col"><button id="sound9`" type="button">Sound 9</button></div>
    </div>  
    <div class="row">
      <div class="col"><button id="sound10" type="button">Sound 10</button></div>
      <div class="col"><button id="sound11" type="button">Sound 11</button></div>
      <div class="col"><button id="sound12`" type="button">Sound 12</button></div>
    </div>  
  </div>


  <script src="./renderer.js"></script>
</body>

</html>

main.js

const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')

const createWindow = () => {
    const win = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
        preload: path.join(__dirname, 'preload.js')
      }
    })
  
    win.loadFile('index.html')

    win.center();
    win.show();

  }

app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

renderer.js

const sound1 = document.getElementById('sound1')
const sound2 = document.getElementById('sound2')
const sound3 = document.getElementById('sound3')
const sound4 = document.getElementById('sound4')
const sound5 = document.getElementById('sound5')
const sound6 = document.getElementById('sound6')


window.onload = loadButtons;


function loadButtons() {
    sound1.addEventListener('click', () => {
        a = new Audio("./asset/a.mp3.mpeg")
        a.play();
    });
    
    sound2.addEventListener('click', () => {
        a = new Audio("./asset/a.mp3.mpeg")
        a.play();
    });
    
    // sound3.addEventListener('click', () => {
    //     a = new Audio("./asset/a.mp3.mpeg")
    //     a.play();
    // });
    
    sound4.addEventListener('click', () => {
        a = new Audio("./asset/a.mp3.mpeg")
        a.play();
    });
    
    sound5.addEventListener('click', () => {
        a = new Audio("./asset/a.mp3.mpeg")
        a.play();
    });
    
    // sound6.addEventListener('click', () => {
    //     a = new Audio("./asset/a.mp3.mpeg")
    //     a.play();
    // });
    

}

Metamask – switch to ropsten network using react js

i’m developping a web 3.0 app and i want when users connect there metamask, if the network i not ropsten then metamask ask them to switch it cause my smart contract was deployed into ropsten network and i want all the transactions pass in ropsten network, but i faced some problemes and i didn’t found the solution anywhere else
[enter image description here][1]

This is the function which handle the switch network function : https://i.stack.imgur.com/R6QpY.png

This is the error that i faced : https://i.stack.imgur.com/76DbN.png

Any Help pleaaaase !

How can I iterate in a object with differents types of elements? [duplicate]

I’ll receive different requests from an API.
Then I wanna save the keys, but most of the requests have the next structure:

{
    element1: string, 
    element2: Array of Objects
    ...
}

so, How can I get the name of the keys even when the elements are inside of the Array of objects and save it in an Array?

For example:

{
    name: 'John', 
    addresses: [{
        street:'Fleet Street',
        number:'331',
        configuration: {
            enable:true,
        }
    }],
    country:'Albania'
}

and then save the keys. It doesn’t matter if it’s in an array or object.

How to get attribute of dynamically generated element ASP.NET

I know there are tons of questions on this topic and I’ve tried many of them to no avail. If anyone has any suggestions, it would be greatly appreciated. I’m trying to get the inputs’ id attribute. I’ve stripped the code to just focus on the issue.

The cshtml:

@for (var i = 0; i < Model.DieRouteChecks.Count; i++) 
{
    <div class="col-9">
       <div class="form-group newThresholdInput">
          <input asp-for="@Model.DieRouteChecks[i].NewDieThresh" class="form-control" id="@Model.DieRouteChecks[i].Description">
       </div>
    </div>
}

My javascript:

$(".newThresholdInput input").click(() => {

        console.log($(this).attr("id")); //To see what's being returned

        switch ($(this).attr('id')) {
            case "Order Value":
                  //Do stuff
                  break;
            case "Order Quantity":
                  //Do stuff
                  break;
            }
        })

I keep getting undefined logged when clicking the input. I’ve tried

$(".newThresholdInput").click(() => {
    console.log($(this).find("input").attr("id"));
}

And it printed out only the first input element’s id.
I’ve also tried using onclick="function(this)" and creating an event-handler that’s called in the script tags but still nothing.

I’m not sure if it has something to do with ASP.NET tag helpers but nothing seems to be working.

TurfJS: Efficiently locate the nearest point on a line string

CODESANDBOX

SITUATION

I have a line string with up to 2000 points. I am trying to find the nearest point on the line from the user’s location. This operation is executed roughly every 5 seconds and failing to optimise it would unnecessarily drain the users battery.

The source code shows that the distance operation is conducted on every point on the line string – not good for my users.

I would like to implement a quick-sort style algorithm to get the nearest point and reduce the number of the operations. The example below is working quite well and produces a point on the line with far fewer operations (for a list of 1700 points it takes 14 operations to locate the closest point).

PROBLEM

I cannot determine an elegant way to track the index of the result. Once I have the nearest point, I do not want to have to search the original list again to find it’s index.

first operation – 0 | median

second – fHalf (0 | median of fHalf) | sHalf (median of list | median of sHalf)

third – at this point it becomes a mess to track

What I have so far:

import distance from "@turf/distance";
import { point } from "@turf/helpers";

const user = point([-77.037076, 38.884017]);

function getMedian(list) {
  return Math.ceil(list.length / 2);
}

function getHalves(list) {
  const median = getMedian(list);
  const firstHalf = list.slice(0, median);
  const secondHalf = list.slice(-median);
  return { firstHalf, secondHalf };
}

function getClosest(list) {
  const to = point(list[0]);
  const meters = distance(user, to, { units: "meters" });
  return meters;
}

let operations = 0; // used in development to track operations

function selectHalf(list) {
  operations += 1;
  const { firstHalf, secondHalf } = getHalves(list);
  const firstDistance = getClosest(firstHalf);
  const secondDistance = getClosest(secondHalf);
  const nextList = firstDistance < secondDistance ? firstHalf : secondHalf;
  if (list.length === 1)
    console.log("operations:", operations, "closest point:", nextList);
  else selectHalf(nextList);
}

const morePoints = `-37.0467378013181,145.1634433308106
-37.04674949407303,145.1634394751351
-37.04676521014147,145.1634369605642
-37.04678021374815,145.1634352003645
-37.04679207414114,145.1634343621742
-37.04680510800057,145.1634334401648
// Full list is available in the codesandbox link below
`
  .split("n")
  .map((p) => p.split(",").map((n) => parseFloat(n)));

selectHalf(morePoints);

Parse/Display nested JSON array with Jquery

I am looking to pull data from a job board API. I’d like to have headings for the departments (pulled from JSON level 1) and under each department the current open positions (JSON level 2). I have tinkered with this 50 different ways and ran through all the related articles I can find, but just can’t quite get the dominoes to fall in my brain.

So far my attempts get undefined or a result listing out a department 20 times with one job nested under it. I would be eternally grateful if somebody could help me navigate the JSON tree and correctly parse this out.

This is what I have to work with.

<div id="jsonpResult"></div>

<script>
$(function() {
  $.ajax({
    url: 'https://boards-api.greenhouse.io/v1/boards/agilityrobotics/departments',
    data: {
      check: 'one'
    },
    dataType: 'jsonp',
    success: function(result) {
      $.each(result.data , function(key , value){ // First Level
         $.each(value.jobs , function(k , v ){  // Second Level into Jobs



              //HELP! What can I put here to properly append something to #jsonpResult



         });     
      });
    }
  });
});


</script>

Early return from a subscribe block in a function

I am new to JavaScript. I am trying to do an early return on error from a subscribe block.

This is what I have

public doSomething() {
   this.updateData(data)
     .subscribe((result) => {
                   // do something
                }, 
                (err) => {
                   console.error("Error");
                   return;
                   // require an early return from the block
                   // so rest of the function isn't executed. 
     });
   // do other work
}

Any pointers will be appreciated.

displaying dropdown list in a Row displays [objectHTMLSelectElement] on UI

I have created a dropdown with the elements from a splits array, how can i get the select element to be dispalyed on the row on the UI? I keep getting a [objectHTMLSelectElement] on the UI

var select = document.createElement("select");
                for (var i = 0; i < splits.length; i++) {
                    var optn = splits[i];
                    var element = document.createElement("option");
                    element.textContent = optn;
                    element.value = optn;

                    select.appendChild(element);
                    console.log(select);
                   
                }
                
                row += select;

Setting state in React useEffect hook

In my app I fetch data from my API after a button is clicked that changes the state of endpoint. Until the data is fetched I want to display a loading icon. After MUCH testing, I finally got it to work. This is what it looks like:

  const [endpoint, setEndpoint] = useState('products');
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
    setLoading(true);

    fetch(`/api/${endpoint}`, {
      method: 'GET',
    })
    .then(res => res.json())
    .then(data => {
      setData(data);
    })
    .catch(e => {
      setData([]);
    })
    .finally(() => setLoading(false));

  }, [endpoint]);

  const onSelect = (option) => {
    setEndpoint(option);
  }

  return (
    <>
      <Sidebar onSelect={onSelect}/>
      <div className="main">
        <Banner />
        {loading ? 'Loading...' : JSON.stringify(data)}
      </div>
    </>
  );

Even though I get the result that I want, I’m a bit confused as to how it all fits together because I’m new to React. Please correct me If I’m wrong, but this is my understanding:

setEndpoint triggers a re-render, which causes useEffect to execute because it has a dependency on endpoint. Each set state call inside useEffect also causes a re-render. For instance when setLoading(true) is called, the screen is re-rendered to show ‘Loading…’. Once the state of loading is set to true, fetch gets called. As soon as the promise is resolved, setData(data) causes another re-render. However, my data isn’t displayed on screen until setLoading(false) is called, re-rendering the screen yet again, displaying my data. So in total, the screen is re-rendered 3 times (right?).

I’m still confused because I was under the impression that hooks like useEffect are asynchronous so why would it wait for the state to be set before continuing to execute the next lines of code?

What wrong with Vue scroll modal?

Im trying since yesterday find a way to screen a modal on Vuejs, when i scrolling down a page, the problem is i got nothing on my screen when i compile the code.

  <p>
Cupidatat master cleanse carles small batch VHS. Brooklyn umami odio, post-ironic selvage hella farm-to-table. Brooklyn DIY cardigan cosby sweater marfa. Gastropub bicycle rights in seitan non small batch. Placeat non street art umami, yr wolf sed skateboard
cupidatat direct trade seitan put a bird on it occaecat small batch. Hoodie marfa umami, enim scenester cred synth vero gastropub aliqua brunch mlkshk ut. Sed brunch pop-up irony quis. Etsy stumptown 3 wolf moon in carles, vinyl chillwave. Beard sapiente
nulla banh mi cosby sweater 8-bit craft beer, ethical art party portland tumblr godard quinoa occaecat et. Stumptown art party ea bushwick. Cardigan DIY non cred ullamco duis. Id gastropub pop-up narwhal culpa fanny pack voluptate, street art gluten-free
eiusmod quis aute lo-fi. Nostrud ethical irure keffiyeh umami lomo. Twee swag nihil culpa odd future.
</p>

</template>

<script>
import ModalComponent from '/ModalComponent.vue';
export default {
 components: {
 ModalComponent,
 },
  data: () => ({
  showModal: false,
  scrollHeight: 0,
  interval: null,
   }),
   methods: {
    handleScroll() {
    this.handleDebouncedScroll = window.scrollY > 0;
    },
  },
mounted() {
this.interval = setInterval(() => {
  this.scrollHeight = document.body.scrollHeight;
 }, 100);
},
unmounted() {
 clearInterval(this.interval);
},
watch: {
scrollHeight() {
  if (this.scrollHeight === 450) this.showModal = true;
  },
 },
};
</script>