scss file saved but not updating homepage

I am running into some problem about updating my front page. The scss file is saved only it won’t update my background color. It is in a file called full-width-split.scss. I also have a file called style-index.css in the build folder of the WordPress website. I don’t know why it isn’t updating my background color even though the scss file is saved. How do I solve this issue?

Inspect shows this:

  @include atMedium {
    display: flex;
  }

  &__one {
    flex: 1;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }

    .full-width-split__inner {
      @include atMedium {
        float: right;
      }
    }
  }

  &__two {
    flex: 1;
    background-color: $beige;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }
  }

  &__inner {
    @media (min-width: 1350px) {
      width: 610px;
    }
  }
}

But it needs to show this:

.full-width-split {
  @include atMedium {
    display: flex;
  }

  &__one {
    flex: 1;
    background-color: #ffffff;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }

    .full-width-split__inner {
      @include atMedium {
        float: right;
      }
    }
  }

  &__two {
    flex: 1;
    background-color: #faf0ca;
    padding: 1.6rem 16px;
    @include atMedium {
      padding: 40px;
    }
  }

  &__inner {
    @media (min-width: 1350px) {
      width: 610px;
    }
  }
}



  [1]: https://i.stack.imgur.com/IAO6k.png
  [2]: https://i.stack.imgur.com/leSek.png

React / Node – PayPal can’t capture a new subscription

I wan’t to capture a new paypal subscription from frontend in my backend and give response with the needed data for mongodb.

If I add a body with capture_type: ‘OUTSTANDING_BALANCE’ (I found that in the manual) I’m getting this error.
So I’m not sure either it’s just a wrong body or i totally mess up something else in the backend but so far I can’t capture the subscription even so I get a subscription Id from
createSubscription Controller

PayPalScriptProvider

<PayPalScriptProvider options={initialOptions}>
    <PayPalSubscriptionButton/>
</PayPalScriptProvider>

PayPal Button

      {isPending ? <LoadingMedium /> : null}
      <PayPalButtons
        createSubscription={(data, actions) => {
          return axios
            .post(
              '/api/subscription',
            )
            .then((response) => {
              return response.data.id;
            });
        }}
        onApprove={(data, actions) => {
          axios
            .post(`/api/subscription/${data.subscriptionID}/capture`)
            .then(() => {
              axios
                .patch(
                  `/api/activesubscription`,
                  {
                    id: activeSub[0]?._id,
                    subscriptionID: data.subscriptionID,
                  }
                )
                });
            });
        }}
      />

Route for createSubscription

router.route('/subscription').post(async (req, res) => {
  const searchPlan = await SubscriptionAmount.find();
  console.log(searchPlan[0]?.subscriptionAmount);
  const subscription = await paypalFee.createSubscription(
    searchPlan[0]?.subscriptionAmount
  );
  res.json(subscription);
});

Router for onApprove

router.post('/subscription/:subscriptionID/capture', async (req, res) => {
  const { subscriptionID } = req.params;
  console.log('subscriptionID', subscriptionID);
  const captureData = await paypalFee.captureSubscription(subscriptionID);
  console.log('captureData', captureData);
  res.json(captureData);
});

createSubscription Controller

async function createSubscription(planId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v1/billing/subscriptions`;
  const response = await fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
    body: JSON.stringify({
      intent: 'subscription',
      plan_id: planId,
    }),
  });
  const data = await response.json();
  console.log('data', data);
  return data;
}

captureSubscription Controller

async function captureSubscription(subscriptionId) {
  const accessToken = await generateAccessToken();
  const url = `${base}/v1/billing/subscriptions/${subscriptionId}/capture`;
  const response = await fetch(url, {
    method: 'post',
    body: JSON.stringify({
     // capture_type: 'OUTSTANDING_BALANCE',
    }),
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
  });
  const data = await response.json();
  console.log('data', data);
  return data;
}

I’m getting this logs for my data in captureSubscription if I do not pass a body in my captureSubscription Controller:

captureData {
  name: 'INVALID_REQUEST',
  message: 'Request is not well-formed, syntactically incorrect, or violates schema.',
  details: [
    {
      location: 'body',
      issue: 'MISSING_REQUEST_BODY',
      description: 'Request body is missing.'
    }
  ]
}

With body I’m getting this error

captureData {
  name: 'UNPROCESSABLE_ENTITY',
  message: 'The requested action could not be performed, semantically incorrect, or failed business validation.',

  details: [
    {
      issue: 'ZERO_OUTSTANDING_BALANCE',
      description: 'Current outstanding balance should be greater than zero.'
    }
  ],
}

How do you use map and reduce methods to return a key that contains a string? [duplicate]

Beginner JS programmer here(3 weeks): Not sure if my title accurately conveys my problem but I’ll print it out below. I was trying to get the longest name(title) in my array. I created the variable longestName which returns just the titles in the array as desired. I then wanted to use a reducer to reduce the array based on length but I received an error. I know the computer isn’t wrong and I am sure there is a way to do this, I just haven’t been able to put my finger on it yet so here I am.

const movieReviews = [
    {
       title : "Black Adam",
        score : 68,
        year : 2022
    },
    {
       title : "Black Panther",
       score : 99,
       year : 2018
    },
    {
       title : "SpiderMan FFH",
       score : 90,
       year : 2020
    },
    {
       title : "Avatar",
       score : 100,
       year : 2009
    },
    {
        title : "WonderWoman",
        score : 75,
        year : 2019
    },
]



const longestName = movieReviews.map(m =>{
    return m.title;
})
.reduce((name1, name2)=>{
    if(name1.length() > name2.length()){
        return name1;
    }
    return name2;
})



Accessing deeply nested content children in Angular?

Is there a way to get deeply nested directives within an Angular ng-content view ( Components declared within components declared within components …) from the top level component?

I tried using @ContentChildren(Type) … however it is not grabbing the elements with the Type declared (Which reside several layers down within the ng-content section of other child components).

And the Type might be in the view, but it could be nested several layers down within child ng-content sections.

How to display selected radio button value on the console? [duplicate]

So im working on creating a form on javascript, and one of the form criteria is selecting your favorite carbohydrate.
I want to display the selected option on the console, and i tried to create a function for it, but for some reasn when i log it, it says undefined.

My html:

<form>
        <label for="firstName">First Name</label><br>
        <input type="text" id="firstName" name="fname" required><br><br>
        <label for="lastName">Last Name</label><br>
        <input type="text" id="lastName" name="lname"><br><br>
        <label for="email">Email</label><br>
        <input type="email" id="email" name="email" required><br><br>
        <label for="comment">Comment</label><br>
        <textarea name="comment" id="comment" rows="6" cols="50"></textarea><br>
        <p>My favorite Carbohydrate is:</p>
        <input type="radio" id="pasta" name="favCarb" value="pasta" required>
        <label for="pasta">Pasta</label><br>
        <input type="radio" id="rice" name="favCarb" value="rice" required>
        <label  for="rice">Rice</label><br>
        <input type="radio" id="potatoes" name="favCarb" value="potatoes" required>
        <label for="potatoes">Potatoes</label><br>
        <br><input onclick="submitData" type="submit" id="submitButton" value="Submit">

    </form>

My Javascript:

let firstName = document.getElementById("firstName");
let lastName = document.getElementById("lastName");
let email = document.getElementById("email");
let comment = document.getElementById("comment");
let pasta = document.getElementById("pasta");
let rice = document.getElementById("rice");
let potatoes = document.getElementById("potatoes");
let faveCarb = document.getElementsByName("favCarb").value;
let submitButton = document.getElementById("submitButton");

submitButton.addEventListener("click", submitData);

function submitData(){
       console.log(
       "First Name: " + firstName.value +
       " Last Name: " + lastName.value +
       " Email: " + email.value +
       " Comment: " + comment.value +
       " Favorite Carb: " + faveCarb.value
       )
       
}; 

Thanks for the help!

i tried using the .value method, but it logged “undefined” into the console

Is there a way to check if another button is active on a button click?

So, I wanted to figure out if it was possible to check if another button was active when running an onClick function. I’m making a quiz type of thing and want to be able to make is so that when the submit button is pressed it sees what other button was active.

var btnContainer = document.getElementById("myDIV");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
@import url(https://fonts.googleapis.com/css?family=Chewy);
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-family: 'chewy';
  font-size: 20px;
}

.active,
.btn:hover {
  background-color: #3765a1;
  color: white;
}

.button-three {
  position: relative;
  background-color: #f39c12;
  border: none;
  padding: 20px;
  width: 400px;
  text-align: center;
  -webkit-transition-duration: 0.4s;
  /* Safari */
  transition-duration: 0.4s;
  text-decoration: none;
  overflow: hidden;
  border-radius: 15px;
  margin-top: 25px;
}

.button-three:hover {
  background: #fff;
  box-shadow: 0px 2px 10px 5px #97B1BF;
  color: #000;
}

.button-three:after {
  content: "";
  background: #f1c40f;
  display: block;
  position: absolute;
  padding-top: 300%;
  padding-left: 350%;
  margin-left: -20px !important;
  margin-top: -120%;
  opacity: 0;
  transition: all 0.8s
}

.button-three:active:after {
  padding: 0;
  margin: 0;
  opacity: 1;
  transition: 0s
}

.box {
  border: solid;
  width: 400px;
  padding: 10px;
  border-radius: 20px;
  border-width: 5px;
}
<div class="box">
  <h1> What is 2+2?

    <div id="myDIV">
      <p><button class="btn active">A</button>&#8195;2</p>

      <p> <button class="btn">B</button>&#8195;5</p>
      <p> <button class="btn">C</button>&#8195;4</p>
      <p> <button class="btn">D</button>&#8195;1</p>
    </div>



    <button class="button-three" onclick=""> Submit </button>
</div>

I think this would be a good example of what I’m trying to say:

document.getElementById('button').addEventListener("click", function() {
   alert("You clicked me");
}​);

If you can help me out then thanks!

How to get data from a screen in React-Native?

I have a Subscription screen that has a useEffect hook that updates a isSubbscribed useState.

I am implementing this screen in the ApprRoot as a subscription paywall. I simply need to get this useState variable isSubscribed and use it in the appRoot to see the data. How can I get this data from the Subscription screen?

for Example in my AppRoot.jsx:

const subbed =  *subScreen use State Variable* 
return (

{ subbed ? (
                        <Stack.Navigator>  
                            <Stack.Group>
                                <Stack.Screen
                                    name="SubScreen"
                                    component={SubScreen}
                                    initialParams={{ initialroute: 'Home' }}
                                />
                                </Stack.Group>
                            </Stack.Navigator>  
                        ) : (
                        <NavigationRoot /> 
                        )}
)

Subscreen.jsx has a variable such as this

  const [subbed, setSubbed] = useState([]);

How am I able to use this useState in the approot file? I cannot just simply export it?

I’m expecting to be able to get the useState variable subbed and use it to generate the proper screens.

Images in Leaflet don’t load correctly at first launch in a Flask server

I am developing a web server using Flask that have to run a simple HTML web page that embed a Javascript. The JS contains an interactive Leaflet map, it listens to a Kafka topic and displays custom markers on the map. The server seems receive correctly the requests and work in a good way, but the images of the floors I use in the Javascript are loaded after the first refresh. To be more clear, when at the first load of the page the static contents are retrieved(code 200) they are not displayed (the Leaflet object of the page have the correct dimensions but it is grey). When you refresh and I receive a code 304 the floor images are displayed correctly. In addition I can say that if you receive data from Kafka even if the map images are not loaded(at first load) you can see the image of the markers updated in a correct way (but the map still remains grey).
This is the Flask server:

from flask import Flask, render_template, Response
from gevent.pywsgi import WSGIServer
from pykafka import KafkaClient
from gevent import monkey
monkey.patch_all()

WEB_HOST = '0.0.0.0'
PORT = 5000


def get_kafka_client():
    return KafkaClient(hosts='broker:9093')

app = Flask(__name__)

@app.route('/')
def index():
    return(render_template('index.html'))

#Consumer API
@app.route('/topic/<topicname>')
def get_messages(topicname):
    client = get_kafka_client()
    def events():
        for item in client.topics[topicname].get_simple_consumer():
            yield 'data:{0}nn'.format(item.value.decode())
    return Response(events(), mimetype="text/event-stream")

if __name__ == '__main__':
    print('Server start')
    http_server = WSGIServer((WEB_HOST, PORT), app)
    print('WSGI start')
    http_server.serve_forever()

The HTML Index:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <!-- LEAFLET -->
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
      integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
        crossorigin=""/>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
      integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
      crossorigin=""></script>
    <!-- END LEAFLET -->
    <link rel="apple-touch-icon" sizes="57x57" href="../static/favicon.ico/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="../static/favicon.ico/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../static/favicon.ico/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../static/favicon.ico/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../static/favicon.ico/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../static/favicon.ico/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../static/favicon.ico/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../static/favicon.ico/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="../static/favicon.ico/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="../static/favicon.ico/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../static/favicon.ico/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="../static/favicon.ico/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../static/favicon.ico/favicon-16x16.png">
    <link rel="manifest" href="../static/favicon.ico/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="../static/favicon.ico/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <title>Live Map</title>
  </head>
  <body>
    <h1>Live Map</h1>

    <!-- LEAFLET -->
    <div id="map-template" style = "width:1700px; height:750px;"></div>
    <script src="../static/js/main.js"></script>
    <!-- END LEAFLET -->
  </body>
</html>

Finally the Javascript code:

// Definition of map marker style
var humanIcon = L.icon({
        iconUrl: '../static/images/human1.png',

        iconSize:     [40, 40], // size of the icon
        iconAnchor:   [22, 31], // point of the icon which will correspond to marker's location

        popupAnchor:  [-3, -40] // point from which the popup should open relative to the iconAnchor
    });

// Useful functions
//Generate a latLng object given cartesian coordinates
var pos = L.latLng;

var xy = function(x, y) {
    return pos(y, x);  // When doing xy(x, y);
};

//Create a marker object given cartesian coordinates and infos about marker
function createMarker(lat,long,id){
    var pos = xy(lat , long);
    return L.marker(pos,{icon: humanIcon}).bindPopup("ID: "+id);
  }


var  zeroFloorUrl='../static/images/zeroFloor.png',
     firstFloorUrl='../static/images/firstFloor.png',
     secondFloorUrl='../static/images/secondFloor.png',
     thirdFloorUrl='../static/images/thirdFloor.png';
const img0 = new Image();
     // get the image
     img0.src = zeroFloorUrl;
     let w0=img0.width;
     let h0=img0.height;
const img1 = new Image();
     img1.src = firstFloorUrl;
     let w1=img1.width;
     let h1=img1.height;
const img2 = new Image();
     img2.src = secondFloorUrl;
     let w2=img2.width;
     let h2=img2.height;
const img3 = new Image();
     img3.src = thirdFloorUrl;
     let w3=img3.width;
     let h3=img3.height;



// Definition of the layer of each floor
//FLOOR ZERO
    var boundsZeroFloor = [[0,0], [h0,w0]],
        // New layergroup, note it's not added to the map yet
        layerGroup0 = new L.LayerGroup(),
        // New imageoverlay added to the layergroup
        imageOverlay0 = new L.ImageOverlay(zeroFloorUrl, boundsZeroFloor).addTo(layerGroup0);
//FLOOR UNO
    var  boundsFirstFloor = [[0,0], [h1,w1]],
        layerGroup1 = new L.LayerGroup(),
        // New imageoverlay added to the layergroup
        imageOverlay1 = new L.ImageOverlay(firstFloorUrl, boundsFirstFloor).addTo(layerGroup1);
//FLOOR TWO
    var  boundsSecondFloor = [[0,0], [h2,w2]],
        layerGroup2 = new L.LayerGroup(),
        // New imageoverlay added to the layergroup
        imageOverlay2 = new L.ImageOverlay(secondFloorUrl, boundsSecondFloor).addTo(layerGroup2);
//FLOOR THREE
    var boundsThirdFloor = [[0,0], [h3,w3]],
        layerGroup3 = new L.LayerGroup(),
        // New imageoverlay added to the layergroup
        imageOverlay3 = new L.ImageOverlay(thirdFloorUrl, boundsThirdFloor).addTo(layerGroup3);


//Define a map object as Leaflet guidelines
// N.B. map-template refer to the div declaration of index.html
      var mymap = L.map('map-template',
      {
        zoomDelta:0.1,
        zoomSnap:0.1,
        crs: L.CRS.Simple,
        minZoom: 0,
        maxZoom:1,
        center:[150, 450],
        zoom: 0,

      }).setView(xy(Math.floor(w0/2), Math.floor(h0/2)),0);

      mymap.on('baselayerchange', function(e){

        let test1=e.layer._layers['1'] ;
        let test2=e.layer._layers['2'] ;
        let test3=e.layer._layers['3'] ;
        let test4=e.layer._layers['4'] ;

        if(test1 != null){
          var w=test1._bounds._northEast.lng;
          var h=test1._bounds._northEast.lat;

        } else if (test2 != null) {
          var w=test2._bounds._northEast.lng;
          var h=test2._bounds._northEast.lat;

        } else if (test3 != null) {
          var w=test3._bounds._northEast.lng;
          var h=test3._bounds._northEast.lat;
        }else if (test4 != null) {
          var w=test4._bounds._northEast.lng;
          var h=test4._bounds._northEast.lat;

        }

        mymap.setView(xy(Math.floor(w/2), Math.floor(h/2)),0);

      });
      var callBack = function () {
    console.log("Map successfully loaded");
    layerGroup0.addTo(mymap);
};

mymap.whenReady(callBack);



// Definition of the later control that make you able to change layers
    var layerControl= new L.control.layers(
      { 'Zero':layerGroup0,
        'First':layerGroup1,
        'Second':layerGroup2,
        'Third':layerGroup3
      }
      ,null,{ collapsed: true }).addTo(mymap);

// Definition of the FeatureGroups that will used to organise the markers
    var featureGroup0 = L.featureGroup();
    var featureGroup1 = L.featureGroup();
    var featureGroup2 = L.featureGroup();
    var featureGroup3 = L.featureGroup();

// Definition of the event source generator.
// This sentence will continously generate GET call to the given URL
      var source = new EventSource('/topic/testMap');
      //Attach a listener to the responses triggered by the source
      source.addEventListener('message', function(e){
        //Snippet of code launched each time an event arrive
        // MSG FORMAT [{'floor':int,'x':int,'y':int,'id':String},...]
        array = JSON.parse(e.data);
        var arrayLength = array.length;
        //remove all layers from FeatureGroups to make the map clean
        featureGroup0.clearLayers();
        featureGroup1.clearLayers();
        featureGroup2.clearLayers();
        featureGroup3.clearLayers();

        // Iterate over the message arrived
        for (var i = 0; i < arrayLength; i++) {
          // Check to which floor stand the information
          if(array[i].floor == '0') {
            // Add a marker to the selected layer
            featureGroup0.addLayer(createMarker(array[i].x, array[i].y,array[i].id)).addTo(layerGroup0);
          }
          if(array[i].floor == '1') {
              featureGroup1.addLayer(createMarker(array[i].x, array[i].y,array[i].id)).addTo(layerGroup1);
          }
          if(array[i].floor == '2') {
            featureGroup2.addLayer(createMarker(array[i].x, array[i].y,array[i].id)).addTo(layerGroup2);

          }
          if(array[i].floor == '3') {
            featureGroup3.addLayer(createMarker(array[i].x, array[i].y,array[i].id)).addTo(layerGroup3);
          }
        }


      }, false);

I can attach also the screenshots of the Network analysis at first load:
First view Second View

After the first refresh of the page:
First view Second view

filtering paginated query set containing no results in Django

when iam trying to filter paginated query set by certain params on a page distinct than the first but the result returned from the view is none i get this error :

Invalid page (2): That page contains no results

i am using some JS for the filtering:

function finalurl2() {
        var url = new URL(window.location.href);
        var search_params = url.searchParams;
        search_params.set('genres', document.getElementById('genres').value);
        url.search = search_params.toString();
        var new_url = url.toString()
        return new_url
    }

This is the filter dropdown:

<select id='genres' name='genres' onchange="location = finalurl2();" class="btn btn-dark">
    <option id='placeholder-genres' value="" disabled selected hidden>All</option>
    <option id='Action' value="Action">Action</option>
    <option id='Adventure' value="Adventure">Adventure</option>
    <option id='Comedy' value="Comedy">Comedy</option>
    <option id='Drama' value="Drama">Drama</option>
    <option id='Horror' value="Horror">Horror</option>
    <option id='horror' value="horror">Fantasy</option>
    <option id='Musicals' value="Musicals">Musicals</option>
    <option id='Mystery' value="Mystery">Mystery</option>
    <option id='Romance' value="Romance">Romance</option>
    <option id='Science' value="Science">Science</option>
    <option id='Fiction' value="Fiction">Fiction</option>
    <option id='Sports' value="Sports">Sports</option>
    <option id='Thriller' value="Thriller">Thriller</option>
    <option id='Western' value="Western">Western</option>
</select>

My view:

class Index(views.ListView):
    model = Movie
    template_name = 'index.html'
    paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['latest_uploads'] = get_latest_uploads()
        context['user_favourite_movies'] = get_user_favourite_movies(request=self.request)
        return context

    def get_queryset(self):
        queryset = super().get_queryset()
        genre = self.request.GET.get('genres')
        if genre:
            queryset = queryset.filter(genres__category__exact=genre)
        search_text = self.request.GET.get("searchbar")
        order_by = self.request.GET.get('filters')
        if order_by:

            if order_by in ['likes']:
                queryset = self.order_by_likes(queryset)

            elif order_by in ['rating']:
                queryset = self.order_by_rating(queryset)

            else:
                queryset = queryset.order_by(order_by)

        if search_text:
            return queryset.filter(title__icontains=search_text)

        return queryset

    def querystring_url(self):
        data = self.request.GET.copy()
        data.pop(self.page_kwarg, None)
        return data.urlencode()

    def order_by_likes(self, queryset):
        return queryset.annotate(likes=Count('like')).order_by('likes')

    def order_by_rating(self, queryset):
        return queryset.order_by('-averagereviewscore__score')

i have two types of filtering by likes , rating etc. and by movie genre but they are pretty much the same.

I think setting the page number to 1 by initial sorting/filtering will solve it , but i don’t know how to do it.

Function to receive sheet id as parameter and return the spreadsheet object

I am trying to define a function in google apps script that receives the sheet id as input and returns the spreadsheet object so I can do further stuff with it like get range and values.

function spreadsheetCall() {
    const ss = SpreadsheetApp.openById("1eZcZ0e1AQZ4DRLO9HQsF024qsmraIewY6LUkWYicYmY").getSheetByName("Semanal");
    return ss
};

Logger.log(spreadsheetCallString().getRange("A1").getValues());

When I try that it works like a charm, I can get the range and values I want, but the function is not dynamic since the sheet id is hardcoded into the function. I am trying to have something like this

function spreadsheetCall(sheetID) {
    const ss = SpreadsheetApp.openById(sheetID).getSheetByName("Semanal");
    return ss
};

where if I have a list of multiple sheets I do not have to make a function for each but rather apply the same one multiple times if needed to get what I want. any guidance is helpful, I know basic python so maybe javascript works different idk, just asking to see if it is possible to do what I am thinking of I should find another approach.
Thanks

Tried creating a string with the spreadsheet call and then taking away the quotation marks to return it in a function and then use another function to try and make the proper call but did not work.

How to get value of fetched nested json data from API?

    const Details = () => {
    const { id } = useParams();
    const dispatch = useDispatch();
    const [checkStatus, setSheckStatus] = useState('')

    const { detail, status } = useSelector(state => state.detail)

    useEffect(() => {
        dispatch(fetchDetail(id))
    }, [])

    console.log('this is syour stateus', STATUSES.LOADING)
    if (status === STATUSES.LOADING) {
        return <h6 className='max-w-[1240px] pt-20 mx-auto px-4 text-3xl'>Loading...</h6>
    }
    if (status === STATUSES.ERROR) {
        return <h3 className='max-w-[1240px] pt-20 mx-auto px-4 text-5xl'>Something went wrong!</h3>
    }

    return (

        <div className="container max-w-[1240px] mx-auto flex px-5 pt-28 md:flex-row flex-col text-gray-600 body-font ">
            <div className="lg:max-w-lg lg:w-full md:w-1/2 w-5/6 mb-10 md:mb-0">
                <img className="h-[460px] w-[460px] object-contain bg-white object-center rounded p-4 shadow-md" alt="hero" src={detail.image} />
            </div>
            <div className="lg:flex-grow md:w-1/2 lg:pl-10 md:pl-16 flex flex-col md:items-start md:text-left items-center text-center">
                <h4 className="font-bold text-blue-700 mb-2 title-font uppercase text-sm tracking-widest">{detail.category}</h4>
                <h1 className="text-black mb-4 font-bold text-3xl lg:text-4xl">{detail.title}</h1>
                <div className="flex mb-4">
                    <span className="flex items-center">
                        <AiFillStar className='className="w-4 h-4 text-red-500' />
                        <AiFillStar className='className="w-4 h-4 text-red-500' />
                        <AiFillStar className='className="w-4 h-4 text-red-500' />
                        <AiFillStar className='className="w-4 h-4 text-red-500' />
                        <AiFillStar className='className="w-4 h-4 text-red-500' />
                        <span className="text-gray-600 ml-3">{detail.rating.rate} Rating & {detail.rating.count} Reviwes</span>
                    </span>
                </div>
                <p className="text-dark-grayish mb-5 text-base sm:text-lg">{detail.description}</p>
                <h3 className="text-black font-bold text-3xl pb-4 inline-block">${detail.price}</h3>
                <div className="flex justify-center">
                    <button className="inline-flex text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded text-lg shadow-sm">ADD TO CART</button>
                    <button className="ml-4 inline-flex text-gray-700 border-2 border-indigo-500 py-2 px-6  hover:bg-indigo-500 hover:text-white rounded text-lg shadow-sm">BUY NOW</button>
                </div>
            </div>
        </div>
    )
}

here in this code im fetching data through api from fakestore.com.

fakestoreapi give five json output id, title, category, desc, image and last rating. but rating have two more nested json data. rating contains rate and count.

now i want to access the count form rating. so im doing in this way

{detail.rating.rate}

but it is showing error in console.

Uncaught TypeError: Cannot read properties of undefined (reading 'rate')

what should i do ??

Applying a regex to the result of a fetch function that is placed inside a useState?

I have a fetch function that produces a numbered list of uses (ie. 1. To Drive, 2. To Speed, …)

The function returns a string of text, which I am then applying a regex on to convert it into an array, where each value in the array is one of the points in the list.

I am using this regex, I know it works.

let input = '1. Hello. 2. Bye.'
llet regex = /(d+.d*)s?(.*?)(?=d+.|$)/gs;
let matches = input.match(regex);

It returns an array [‘1. Hello’, ‘2. Bye’].

I have tried to apply the regex to the response value within the fetch function. When I used console.log it was blank, so it seems like nothing has changed.

    const [inputMatches, setInputMatches] = useState([]);
    const getUses = async () => {
        openai.createCompletion({
            model: "text-davinci-003",
            prompt: "List four uses for a car",
            max_tokens: 256
        }).then((response) => {
            let regex = /(d+.d*)s?(.*?)(?=d+.|$)/gs
            setInputMatches((response.data.choices[0].text).match(regex))
        })
    };

The getUses starts when I click a button which is linked to another function within useEffect, I could share it if required but it seems unrelated.

Using the value of a loop outside of the loop

Im trying to get the data after I restrurce them in a loop.
So when the when the loop completes I could have a variable with the value in it so I could download it or whatever.



 const handleData = async (e) => {
    if (e.key === "Enter") {
      await fetch(`http://localhost:3000/api/getsubs`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ getInput }),
      })
        .then((res) => res.json())
        .then((res) => {
          let len = res.length;
          for (let i = 0; i < len; i++) {
            let subNum = i + 1;
            let start = res[i].start;
            let end = res[i].dur;
            let text = res[i].text;

            const secondsToHms = (start) => {  ** starting restructuring the text **
              var h = Math.floor(start / 3600);
              var m = Math.floor((start % 3600) / 60);
              var s = Math.floor((start % 3600) % 60);
              var ms = Math.round((start % 1) * 1000);
              return (
                (h < 10 ? "0" : "") +
                h +
                ":" +
                (m < 10 ? "0" : "") +
                m +
                ":" +
                (s < 10 ? "0" : "") +
                s +
                "," +
                (ms < 100 ? "0" : "") +
                (ms < 10 ? "0" : "") +
                ms
              );
            }; **still in the loop**

            const inputToSRT = () => {
              return (
                subNum +
                "rn" +
                secondsToHms(start) +
                " --> " +
                secondsToHms(end) +
                "rn" +
                text +
                "rnrn"
              );
           
            const srtData = inputToSRT();
            console.log(srtData);
                };  **here the loop ends**

          **Im looking to create a var here with the loop data stored in it so I could download it after**
   
     

            let blob = srtData;   **download function outside the loop**
            // console.log(blob);
            // const download = () => {
            // Create blob link to download
            if (fetchData != -1) {
              const url = window.URL.createObjectURL(new Blob([fetchData]));
              const link = document.createElement("a");
              link.href = url;
              link.setAttribute("download", `FileName.srt`);
              // Append to html link element page
              document.body.appendChild(link);
              // Start download
              link.click();
              // Clean up and remove the link
              link.parentNode.removeChild(link);
            }
          }
        });
    }
  };

I have tried adding the download function in the loop but it would download mulptie files with each loop instead of one with all the values

Why am I getting the error message about each list item should get a unique key when using the react-bootstrap with Nextjs?

Here is the current setup of the file right now below. You will see that my file does indeed have a key to each child component but its still flagging it and I think its more internal issues that I am not sure that I can fix.

export default function SecondaryNav(props:NavItems) {

    const router = useRouter();
    let [filteredSubNavItems, setFilteredSubNavItems] = useState<{}[]>([])



/* Filtering the props.navigation array and setting the filteredSubNavItems state to the filtered
array. */
    useEffect(() => {
         props.navigation.filter((item) => {
            if(item.link == router.route) {
                setFilteredSubNavItems(item.subLinks);
            }
        })
    })


    return (
        <>
            <Navbar className={[styles.SecondaryNav].join(' ')}>
                    <div className={['container', styles.secondaryNavContainer].join(' ')}>
                                {
                                    filteredSubNavItems.map((navItem, index) => {
                                        return (
                                            <>
                                            {
                                                !navItem.subLinksExist ?
                                                    <Nav.Link key={navItem.name} href={navItem.link}>{navItem.name}</Nav.Link>
                                                 :
                                                    <NavDropdown key={navItem.name} title={navItem.name} id={navItem.name}>
                                                        {
                                                            navItem.sublinks.map((item) => {
                                                                return (
                                                                    <NavDropdown.Item key={item.label}>{item.label}</NavDropdown.Item>
                                                                )
                                                            })
                                                        }
                                                    </NavDropdown>
                                            }
                                        </>
                                        )
                                    })
                                }
                    </div>
            </Navbar>
        </>
    )
}

And below is the file that I am pulling the data.

export const menuItems = [
    {
        primaryLink: 'Home',
        link: '/',
        subLinks: [
            {
                name: 'tutorial',
                subLinksExist: false,
                link: '/Home/Tutorial'
            },
            {
                name: 'contact',
                subLinksExist: false,
                link: '/Home/Contact'
            },
            {
                name: 'about',
                subLinksExist: false,
                link: '/Home/About'
            },
            {
                name: 'FAQ',
                subLinksExist: false,
                link: '/Home/Faq'
            },
            {
                name: 'version',
                subLinksExist: false,
                link: '/Home/Version'
            },
            {
                name: 'health check',
                subLinksExist: false,
                link: '/Home/Healthcheck'
            }
        ]
    },
    {
        primaryLink: 'Configuration',
        link: '/Configuration',
        subLinks: [
            {
                name: 'merchants',
                link: 'merchants',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'Billing Groups',
                        key: 'billing groups',
                        link: 'Configuration/Merchants/BillingGroup'
                    },
                    {
                        label: 'Billing Group Chain',
                        key: 'billing group chain',
                        link: 'Configuration/Merchants/BillingGroupChain'
                    },
                    {
                        label: 'Payment Channels',
                        key: 'payment channels',
                        link: 'Configuration/Merchants/PaymentChannels'
                    },
                    {
                        label: 'Relationship Managers',
                        key: 'relationship managers',
                        link: 'Configuration/Merchants/RelationshipManagers'
                    },
                    {
                        label: 'Fee Templates',
                        key: 'fee templates',
                        link: 'Configuration/Merchants/FeeTemplates'
                    },
                    {
                        label: 'Billing Group Disbursement Hold',
                        key: 'billing group disbursement hold',
                        link: 'Configuration/Merchants/BillingGroupDisbursementHold'
                    },
                ]
            },
            {
                name: 'partners',
                subLinksExist: false,
                link: 'Configuration/Partners'
            },
            {
                name: 'ODFIs',
                link: '/odfis',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'Bank Expenses',
                        key: 'bank expenses',
                        link: 'Configuration/ODFIs/BankExpenses'
                    },
                    {
                        label: 'Expense Batches',
                        key: 'expense batches',
                        link: 'Configuration/ODFIs/ExpenseBatches'
                    },
                    {
                        label: 'Routing Numbers',
                        key: 'routing numbers',
                        link: 'Configuration/ODFIs/RoutingNumbers'
                    },
                ]
            },
            {
                name: 'business units',
                link: '/businessunits',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'Support Contacts',
                        key: 'support contacts',
                        link: 'Configuration/BusinessUnits/SupportContacts'
                    }
                ]
            },
            {
                name: 'profile',
                link: '/profile',
                subLinksExist: true,
                ariaControls: false,
                ariaExpanded: false,
                sublinks: [
                    {
                        label: 'API Profiles',
                        key: 'api profiles',
                        link: 'Configuration/Profile/APIProfiles'
                    },
                    {
                        label: 'Heartland Users',
                        key: 'heartland users',
                        link: 'Configuration/Profile/HeartlandUsers'
                    },
                    {
                        label: 'External Users',
                        key: 'external users',
                        link: 'Configuration/Profile/ExternalUsers'
                    },
                ]
            },
            {
                name: 'system',
                subLinksExist: false,
                link: 'Configuration/System'
            }
        ]
    },
     {
        primaryLink: 'Support',
        link: '/Support',
        subLinks: [
            {
                name: 'automation',
                link: '/automation',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Alerts',
                        link: '/Support/Automation/Alerts'
                    },
                    {
                        label: 'Subscriptions',
                        link: '/Support/Automation/Subscriptions'
                    },
                    {
                        label: 'Jobs',
                        link: '/Support/Automation/Jobs'
                    },
                ]
            },
            {
                name: 'consumers',
                link: '/Consumers',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Blacklist',
                        link: '/Support/Consumers/Blacklist'
                    },
                    {
                        label: 'Whitelist',
                        link: '/Support/Consumers/Whitelist'
                    },
                    {
                        label: 'Provisional Whitelist',
                        link: '/Support/Consumers/ProvisionalWhitelist'
                    },
                ]
            },
            {
                name: 'invoices',
                link: '/Invoices',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Billing Group',
                        link: '/Support/Invoices/BillingGroup'
                    },
                    {
                        label: 'Partner',
                        link: '/Support/Invoices/Partner'
                    }
                ]
            },
            {
                name: 'logging',
                link: '/Logging',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Failed Api Calls',
                        link: '/Support/Logging/FailedApiCalls'
                    },
                    {
                        label: 'Logs',
                        link: '/Support/Logging/Logs'
                    },
                    {
                        label: 'Emails',
                        link: '/Support/Logging/Emails'
                    },
                ]
            },
            {
                name: 'ACH files',
                link: '/AchFiles',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'ACH Entry Finder',
                        link: '/Support/AchFiles/AchEntryFinder'
                    },
                    {
                        label: 'ACH Rejects',
                        link: '/Support/AchFiles/AchRejects'
                    }
                ]
            },
            {
                name: 'returns',
                link: '/Returns',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Return Files',
                        link: '/Support/Returns/ReturnFiles'
                    },
                    {
                        label: 'Return Details',
                        link: '/Support/Returns/ReturnDetails'
                    },
                    {
                        label: 'Exceptions',
                        link: '/Support/Returns/Exceptions'
                    },
                    {
                        label: 'Reinitiations',
                        link: '/Support/Returns/Reinitiations'
                    },
                    {
                        label: 'Notices Of Change',
                        link: '/Support/Returns/NoticeOfChange'
                    },
                    {
                        label: 'Return Reconciliations',
                        link: '/Support/Returns/ReturnReconciliations'
                    },
                ]
            },
            {
                name: 'bulwark',
                link: '/Bulwark',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Risk Rule Configuration',
                        link: '/Support/Bulwark/RiskRuleConfiguration'
                    },
                    {
                        label: 'Risk Rule Enforcement',
                        link: '/Support/Bulwark/RiskRuleEnforcement'
                    }
                ]
            }
        ]
     },
    {
        primaryLink: 'Terminal',
        link: '/Terminal',
        subLinks: [
            {
                name: 'virtual terminal',
                subLinksExist: false,
                link: '/VirtualTerminal'
            },
            {
                name: 'history log',
                subLinksExist: false,
                link: '/HistoryLog'
            }
        ]
    },
    {
        primaryLink: 'Sagacity',
        link: '/Sagacity',
        subLinks: [
            {
                name: 'management',
                link: '/Management',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Business Units',
                        link: '/Sagacity/Management/BusinessUnits'
                    },
                    {
                        label: 'Merchants',
                        link: '/Sagacity/Management/Merchants'
                    },
                    {
                        label: 'Users',
                        link: '/Sagacity/Management/Users'
                    },
                    {
                        label: 'Global',
                        link: '/Sagacity/Management/Global'
                    },
                    {
                        label: 'GIACT Invoices',
                        link: '/Sagacity/Management/GIACTInvoices'
                    },
                ]
            },
            {
                name: 'history',
                link: '/History',
                subLinksExist: true,
                sublinks: [
                    {
                        label: 'Bank Accounts',
                        link: '/Sagacity/History/BankAccounts'
                    },
                    {
                        label: 'Consumers',
                        link: '/Sagacity/History/Consumers'
                    },
                    {
                        label: 'Verification Requests',
                        link: '/Sagacity/History/VerificationRequests'
                    },
                    {
                        label: 'Authentication Requests',
                        link: '/Sagacity/History/AuthenticationRequests'
                    },
                    {
                        label: 'Statics',
                        link: '/Sagacity/History/Statics'
                    },
                    {
                        label: 'Failed API Calls',
                        link: '/Sagacity/History/FailedApiCalls'
                    },
                ]
            }
        ]
    }
]

It is primarily flagging just the dropdown menus only. If you remove the dropdown components I dont get the error message.