Why does Intellij Code Inspection tell me a selector is never used?

I have this mini-project. It is composed of 2 files in the same folder.

  1. App.css
.App-align-left {
    text-align: left;
}
  1. App.js
import React from 'react';
import 'App.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: ''
        }
    }

    render() {
        let contents = <h4>Contents</h4>;
        return (
            <div style={{ display: "inline-block" }}><br />
                <h3 style={{ display: "inline-block" }}>Header</h3>
                <div className="App-align-left">{contents}</div><br />
            </div>)
    }
}

export default App;

When I run code inspection on this, it gives me a warning for App being unused (unused global export), but also for Selector App-align-left is never used. Why is this? It is clearly used.

How to fix the black screen with canvas.toDataURL() on Safari browser?

I have a video player (video.js) in my application, and a function which takes a snapshot of the video.

The function create a canvas which draws the snapshot and convert the canvas into a DataURL.

But this doesn’t work in Safari.

I’m getting a black screen on Safari.

the video tag looks like:

<video crossorigin="anonymous" playsinline="playsinline" id="player_2140_html5_api" class="vjs-tech" data-setup="{ &quot;inactivityTimeout&quot;: 0 }" tabindex="-1" autoplay="autoplay" loop="loop"></video>

This is the function which creates the snapshot:

var canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
var ctx = canvas.getContext('2d');
var video = document.querySelector('video');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
this.snapshotVideo = canvas.toDataURL('image/jpeg', 2.0);

The generated dataUrl in Chrome is an image.
The generated dataUrl in Safari browser is a black rectangle.

In Safari the output is black instead of an image of the taken snapshot via the video, how can I solve this?

Trying to retrieve unique data through a json file

I’m looking for help I’m trying to get some data of json file from an api that I’m using for student project ( I’m very beginner on API stuff).

I’m at the beginning of the project and they asked me to get all of the json file data on the homepage with all informations associated with :

Those are the data that I extract for the API

It’s works fine and when the user click on one of the item it’s show the same information but only the for the one clicked and this is where I’m stuck.

When I click on an item each of them have an id related to a link showing their own id :

The small code use through a loop to get all items id

So I create another js file for the product page where I have to implement them only with Javascript Vanilla and this is what I’ve tried :

// API REQUEST
const connection = fetch ('http://localhost:3000/api/products')

/* *********CONNECION*********** */
connection.then((response) => {
    
    if(response.ok){
        return response.json();
    }

    else{
        console.log('Connection failed');
    }
    
})

/* ********END DE CONNEXION*********** */


.then((jsonArray) => {

    function JsDemo(myData){
      
   // TARGETING ON HTML SELECTORS
        const imgOfTheActualProduct = document.querySelector(".item__img > img");
        const titleOfTheActualProduct = document.querySelector(".item__content__titlePrice > #title");
        const priceOfTheActualProduct = document.querySelector(" .item__content__titlePrice #price");
        const colorOfTheActualProduct = document.querySelector("#colors");
        const descriptionOfTheActualProduct = document.querySelector('.item__content__description #description');
        // Loop to get json elements
        for(let i = 0 ; i < myData.length; i++){
            
            imgOfTheActualProduct.src=`${myData[i].imageUrl}`;
            titleOfTheActualProduct.innerHTML=`${myData[i].name}`;
            priceOfTheActualProduct.innerHTML=`${myData[i].price}`;
            descriptionOfTheActualProduct.innerHTML=`${myData[i].description}`
            // colorOfTheActualProduct.innerHTML=`${myData[i].colors}`;
        
            
    }
    
  
    }

    JsDemo(jsonArray);
})

The code above work(only with the api not here 🙂 ) but it’s showing only the last data of the json file and I retrieve the same thing when I’m selecting all of the item on homepage…

Just to get an idea of what I’m talking about for the JSON part :

[
    {
        "colors": ["Blue", "White", "Black"],
        "_id": "107fb5b75607497b96722bda5b504926",
        "name": "Kanap Sinopé",
        "price": 1849,
        "imageUrl": "http://localhost:3000/images/kanap01.jpeg",
        "description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "altTxt": "Photo d'un canapé bleu, deux places"
    },
    {
        "colors": ["Black/Yellow", "Black/Red"],
        "_id": "415b7cacb65d43b2b5c1ff70f3393ad1",
        "name": "Kanap Cyllène",
        "price": 4499,
        "imageUrl": "http://localhost:3000/images/kanap02.jpeg",
        "description": "Morbi nec erat aliquam, sagittis urna non, laoreet justo. Etiam sit amet interdum diam, at accumsan lectus.",
        "altTxt": "Photo d'un canapé jaune et noir, quattre places"
    },
    {
        "colors": ["Green", "Red", "Orange"],
        "_id": "055743915a544fde83cfdfc904935ee7",
        "name": "Kanap Calycé",
        "price": 3199,
        "imageUrl": "http://localhost:3000/images/kanap03.jpeg",
        "description": "Pellentesque fermentum arcu venenatis ex sagittis accumsan. Vivamus lacinia fermentum tortor.Mauris imperdiet tellus ante.",
        "altTxt": "Photo d'un canapé d'angle, vert, trois places"
    },
    {
        "colors": ["Pink", "White"],
        "_id": "a557292fe5814ea2b15c6ef4bd73ed83",
        "name": "Kanap Autonoé",
        "price": 1499,
        "imageUrl": "http://localhost:3000/images/kanap04.jpeg",
        "description": "Donec mattis nisl tortor, nec blandit sapien fermentum at. Proin hendrerit efficitur fringilla. Lorem ipsum dolor sit amet.",
        "altTxt": "Photo d'un canapé rose, une à deux place"
    },
    {
        "colors": ["Grey", "Purple", "Blue"],
        "_id": "8906dfda133f4c20a9d0e34f18adcf06",
        "name": "Kanap Eurydomé",
        "price": 2249,
        "imageUrl": "http://localhost:3000/images/kanap05.jpeg",
        "description": "Ut laoreet vulputate neque in commodo. Suspendisse maximus quis erat in sagittis. Donec hendrerit purus at congue aliquam.",
        "altTxt": "Photo d'un canapé gris, trois places"
    },
    {
        "colors": ["Grey", "Navy"],
        "_id": "77711f0e466b4ddf953f677d30b0efc9",
        "name": "Kanap Hélicé",
        "price": 999,
        "imageUrl": "http://localhost:3000/images/kanap06.jpeg",
        "description": "Curabitur vel augue sit amet arcu aliquet interdum. Integer vel quam mi. Morbi nec vehicula mi, sit amet vestibulum.",
        "altTxt": "Photo d'un canapé gris, deux places"
    },
    {
        "colors": ["Red", "Silver"],
        "_id": "034707184e8e4eefb46400b5a3774b5f",
        "name": "Kanap Thyoné",
        "price": 1999,
        "imageUrl": "http://localhost:3000/images/kanap07.jpeg",
        "description": "EMauris imperdiet tellus ante, sit amet pretium turpis molestie eu. Vestibulum et egestas eros. Vestibulum non lacus orci.",
        "altTxt": "Photo d'un canapé rouge, deux places"
    },
    {
        "colors": ["Pink", "Brown", "Yellow", "White"],
        "_id": "a6ec5b49bd164d7fbe10f37b6363f9fb",
        "name": "Kanap orthosie",
        "price": 3999,
        "imageUrl": "http://localhost:3000/images/kanap08.jpeg",
        "description": "Mauris molestie laoreet finibus. Aenean scelerisque convallis lacus at dapibus. Morbi imperdiet enim metus rhoncus.",
        "altTxt": "Photo d'un canapé rose, trois places"
    }
]

To be honest I don’t know what to I’m not looking for the solution just an hint.

I looked for URL search parameters on mdn but I don’t really understand on what it’s could be useful here because I already know that each Id is correctly linked ( Or maybe I’m wrong ?!)

Sorry its little long.

Thanks for reading !

What is best way to refreshing token and retry api calls?

When you got 401 status you can use simply Axios interceptors to retry your latest API calls or if you use fetch also you can retry on the catch method.

Though my question is how can I retry my latest function that is including setState or maybe some logic after API calls? I mean that retrying API calls just try network call not that context we gonna try use APIs.

what Is the best practice to retry last calls?

Convert the format of data in a list of dictionaries to fit a html chart

I want to add my own data in a sample HTML chart. The javascript codes of the data part is:

var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
   visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
   data.push({
       date: new Date(2018, 0, i),
       value: visits
        });
      }

chart.data = data

I ran the output of the data with console.log(data) and found the data is the following list of dictionaries:

[{"date":"2018-11-10T05:00:00.000Z","value":-459},
{"date":"2018-11-11T05:00:00.000Z","value":-459},
{"date":"2018-11-12T05:00:00.000Z","value":-464}, 
...
{"date":"2020-11-22T05:00:00.000Z","value":-493}]

I changed my own data to match the format of the above sample data list, the following list is my own data:

my_data = 
[{'date': '01/02/2020', 'value': 13}, 
{'date': '01/03/2020', 'value': 2}, 
{'date': '01/06/2020', 'value': 5},
...
{'date': '01/07/2020', 'value': 6}]

I realized the date format is different from the sample data, so I changed them to the format of mm-dd-yyyy. However, when I replace the sample data with my own data, the chart doesn’t show up any data. What did I miss?

How can I create a search feature for an array of divs with no text content?

Is there a way to create a search filter for HTML elements based on their values, IDs, or names etc. the same way you can create a search filter based on the elements text content? Here is my search filter for divs with text content. Is there a way to implement the search filter if the divs have no text content? Am I able to access the elements tag and use that somehow?

Javascript filter based on text content

let input = document.querySelector(`#input`);
let animalDivs = document.querySelectorAll(`.animal`);

input.addEventListener(`keyup`, function(e) {
  const term = e.target.value.toLowerCase();
  animalDivs.forEach(function(div) {
    const animal = div.textContent.toLocaleLowerCase();
    if (animal.includes(term)) {
      div.style.display = "block"
    } else {
      div.style.display = "none"
    }
  });
});
<input type="text" id="input">
<div class="container">
  <div tag="The Monkey" id="monkey" class="animal">The Monkey</div>
  <div tag="The Mongoose" id="mongoose" class="animal">The Mongoose</div>
  <div tag="The Mouse" id="mouse" class="animal">The Mouse</div>
  <div tag="The Moose" id="moose" class="animal">The Moose</div>
</div>

Vuetify Error: Property or method N is not defined on the instance but referenced during render

I am trying to create a component with a list of cards but it always throws an error:

Property or method “ac” is not defined on the instance but referenced during render.

I have check code looks like to be valid, but the error come every time. I have googled but unfortunately it did not help. Appreciate any help.

<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
  <div id="app">
      <vutify-main></vutify-main>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
  <script>

    Vue.component('vutify-main', {
        template: `
        <v-app>
            <v-main>
                <v-btn @click="show">test</v-btn>
                <accounts-list
                    :overlay="accountListOverlay"
                    :accounts="accountList"
                ></accounts-list> 
            </v-main>
        </v-app>
        `,
        data: function() {
            return {
                accountListOverlay: false,
                accountList: [{ "account_id": 1, "account_name": "1", "account_url": "1" }]
            };
        },
        methods: {
            show: function() {
                return this.accountListOverlay = !this.accountListOverlay;
            }
        }

    });
    
Vue.component('accounts-list', {
    template: `
    <v-overlay :value="overlay">
        <v-list color="transparent">
            <v-card v-for="ac in accounts" :key="ac.account_id" light style="margin-bottom: 10px;>
                <div>
                    <v-card-title class="font-weight-regular">Account Name:</v-card-title>
                    <v-card-subtitle class="font-weight-light body-1">
                        {{ ac.account_url }} - {{ ac.account_id }}
                    </v-card-subtitle>
                </div>
                <div>
                    <v-card-title class="font-weight-regular">Description:</v-card-title>
                    <v-card-subtitle class="font-weight-light body-1">
                        {{ ac.account_name }}
                    </v-card-subtitle>
                </div>
                <v-card-actions>
                    <v-btn
                        text color="#7ec3d8"
                        rounded
                        text
                    >Get data
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-list>
    </v-overlay>
    `,
    props: {
        overlay: {
            type: Boolean,
            required: true,
            default: false
        },
        accounts: {
            type: Array,
            required: false,
            default: []
        }
    },
});

    new Vue({
      el: '#app',
      vuetify: new Vuetify()
    });
  </script>
</body>
</html>

javascript function returns undefined when runs more than once [duplicate]

generateShipLocations returns ships if it runs once and there is no collision at first run . but when collision is true and it runs more than once , i can still see the ships inside the function and inside the else scope but it returns undefined .

generateShipLocations: function() {
    let ships = [];
    //Generates equivelant number of ships based on numships in the 
    // object and stores them in const ships array.
    for (let i = 0; i <= this.numShips - 1; i++) {
      ships.push(new model.shipObject());
    }
    // generate locations for each ship
    ships.forEach((ship) => {
      //generates ship locations
    });
    // logging the ships.it always logs.no problem here.ship locations are set correctly ; 
    console.log("ships", ships);
    //check locations if they overlap ;
    if (this.collision(ships) == true) {
      this.generateShipLocations();
    } else {
      //  i can see ships here too
      console.log("inside false if", ships)
      return ships;
    }
  },
  //collison works ok . 
  collision: function(shipObject) {
    for (let i = 0; i <= shipObject.length - 2; i++) {
      for (let j = i + 1; j <= shipObject.length - 1; j++) {
        if (condition) {
          return true;
        }
      }
    }
    return false;
  },

retrieving and rendering messages from sessionStorage from a form

If someone could help me with this I would be eternally grateful! In a course I’m taking my lecturer wrote the below code for submitting data from a form when the submit button is pressed. It stores this to sessionStorage and then renders the received messages below the form. I made sure to copy it exactly and mine doesn’t work. It seems to be because the .fullName, .emaill, .feedbackType and .comment are not being assigned a type. When I ran the lecturers code file from my vscode and checked it in the browser his worked fine. My work is identical to his bar some different CSS styles.

`function submitMessage(event) {
 event.preventDefault();
 const email = document.getElementById('email').value;
 const fullName = document.getElementById('fullName').value;
 const feedbackType = document.getElementById('feedbackType').value;
 const comment = document.getElementById('comment').value;
 const messageObject = {
   email,
   fullName,
   feedbackType,
   comment,
 };

 let currentMessages = [];

 if (window.sessionStorage.getItem('messages')) {
   currentMessages = JSON.parse(
     window.sessionStorage.getItem('messages')
   );
 }

 currentMessages.push({ messageObject });
 /*temporary fix, find a solution for this error, .push not working/recognised. Code matching lectures is currentMessages.push(messageObject)*/

 window.sessionStorage.setItem(
   'messages',
   JSON.stringify(currentMessages)
 );
 JSON.parse(window.sessionStorage.getItem('messages'));
 renderMessages();
}
function renderMessages() {
     let currentMessages = [];

     if (window.sessionStorage.getItem("messages")) {
         currentMessages = 
             JSON.parse(
                 window.sessionStorage.getItem("messages")
             );
     }

     let listItems = [];
     for (let i = 0; i < currentMessages.length; i++) {
         let listItem = " ";
         const currentMessage = currentMessages[i];
         listItem += `<dt>${currentMessage.fullName} - ${currentMessage.email}</dt>`;
         listItem += `<dd>${currentMessage.feedbackType}: ${currentMessage.comment}</dd>`;
         listItem += `<br />`;
         listItems.push(listItem);
     }
     let descList = document.getElementById('currentMessages');
     descList.innerHTML = listItems.join('');
 }

 renderMessages();`

Ajax form in foreach loop not working without first index

I am working on a ecommerce project. This is a part of shopping cart. The shopping cart looks like [this][1]. For the plus minus button in each product I am using ajax to increment or decrement. The products are called by loop and for each index there is plus minus button.

Blade file

 @foreach(AppModelCart::totalCarts() as $cart)
 <form id="minusForm">
 @csrf
 <input type="hidden" id="id" name="id" value="{{$cart->id}}">
 <button type="submit" data-id="{{ $cart->id  }}" class="minus-button">-</button> 
 </form>         
 <input id="num" type="text" name="cqty" value="{{ $cart['product_quantity']}}">
<span class="price" >৳- <p id="price">{{ $cart->product->price * $cart->product_quantity }}</p></span>
@endforeach

First I tried this way. But only first index of the loop is working. Its properly incrementing or decrementing the product quantity but only for first product. From 2nd index nothing is works.

<script>
    $("#minusForm").submit(function(e){
        e.preventDefault();
        let id = $("#id").val();
        $('#num').html('');
        $.ajax({
            url:'/carts/minus',
            
            type: "GET",
            data:{
                id : id,
            },
            success:function(data){
                $('#num').val(data.product_quantity);
            },
            error: function() {
                    alert("Error Cart");
                }
        })
    })

I tried with only class. If I click any plus or minus button. It return the same value for every product. So I tried without Id and changed this to

$(".minus-button").submit(function(e){  //----here id to class
        e.preventDefault(); 
        let id = $(this).data('id'); //-----here
        $('#num').html('');
        jQuery.ajax({
            url:'/carts/minus' + id, //-----here
            type: "GET",
            data:{
                id : id,
            },
            success:function(data){
                $('#num').val(data.product_quantity);
            },
            error: function() {
                    alert("Error Cart");
                }
        })
    })

Now nothing is working. How can I update the data using ajax inside a loop?
[1]: https://i.stack.imgur.com/8kcQJ.png

Display div based on scroll up and div from current position

I am working on small application

i want to display the div if the user scroll up to > 100px from the current position
and hide div if the user scroll down to > 50 px from current postion

example code

myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 200) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);
body {
  height: 2000px;
}
.bottomMenu {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
  transition: all 1s;
}
.hide {
  opacity: 0;
  left: -100%;
}
.show {
  opacity: 1;
  left: 0;
}
<div id="myID" class="bottomMenu hide"></div>

can any one help with code in javascript

Multiple values are getting selected in radio options

Created the multiple radio options, but it is allowing me to select more then one option.

 {item.responseType === "radio" && (
                          <div className="form-control-wrap">
                            {item.options.split(",").map((list, index) => (
                              <Form.Check
                                key={index}
                                label={list}
                                name={list}
                                type="radio"
                                id={list}
                              />
                            ))}
                          </div>
                        )}

What changes need to be done to select only one option ?

How to Link WooCommerce Guest Orders to Customer Account after registeration

Our scenario is:
The guest user enters the site and places one or more orders without the need to register.
And after a while, he decides to register on the site.
Now how to Link Guest Orders to Customer Account after registeration?
I found the following code, but this code only works for users who have already registered but did not log in at the time of purchase.

//assign user in guest order
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );
function action_woocommerce_new_order( $order_id ) {
    $order = new WC_Order($order_id);
    $user = $order->get_user();
    
    if( !$user ){
        //guest order
        $userdata = get_user_by( 'email', $order->get_billing_email() );
        if(isset( $userdata->ID )){
            //registered
            update_post_meta($order_id, '_customer_user', $userdata->ID );
        }else{
            //Guest
        }
    }
}

Unable to implement merge sort algorithm in Javascript

I am trying to write merge sort algorithm myself in javascript but is see that it is not working. I am taking a sample array [9,1,5,3] and trying to sort it. But it is giving me incorrect result but console shows me [3, undefined, undefined, 5]. I am unable to figure out myself where ut is going wrong.Can anyone help me in this

        function merge(arr,start, mid,end){
            const result=[];

            let first=start;
            let index=start;
            let midNext= mid+1;

            while(first<=mid && midNext<=end){
                if(arr[first]<=arr[midNext]){
                    result[index++]=arr[first++]            
                    
                     
                }else{
                    result[index++]=arr[midNext++]            
                    console.log(result)
                }

                while(first<=mid){
                    result[index++]=arr[first++]            
                    console.log(result)
                    }

                while(midNext<=end){
                    result[index++]=arr[midNext++]            
                    console.log(result)
                    }


            }
            for(let i=0;i<=end;i++){
                arr[i]=result[i];
            }
            console.log(arr)


        }
        function mergeSort(arr, start, end){
            if(start==end){return start;}

            let midIndex=Math.floor( start+ (end-start)/2);
            mergeSort(arr,start,midIndex);
            mergeSort(arr,midIndex+1,end);
             merge(arr,start,midIndex, end)
        }```