问:
SearchView filtering wrong from my Recyclerview when an item change
First of all, I am Spanish so my english is not very good.

I have a list of items on a Recyclerview, and I also have a SearchView to filter those items.

Every item has a favourite button, so when you click, the item adds to favorite table.

The problem is that, when I filter something and I start clicking those buttons, odd things happens: some items dissapear from the filtered list. It doesn't happen always, only sometimes. How can I fix this?

My class:

```<code>class CoasterFragment : Fragment() {

    private val myAdapter by lazy { CoasterRecyclerViewAdapter(CoasterListenerImpl(requireContext(), viewModel),requireContext()) }
     private lateinit var searchView: SearchView
     private var _binding: FragmentCoasterBinding? = null
     private val binding get() = _binding!!

     private val viewModel: CoastersViewModel by viewModels()
     override fun onCreateView(
             inflater: LayoutInflater,
             container: ViewGroup?,
             savedInstanceState: Bundle?

         ): View {
         _binding = FragmentCoasterBinding.inflate(inflater, container, false)
         val root: View = binding.root
         val recyclerView = binding.recyclerCoaster
         recyclerView.adapter = myAdapter
         recyclerView.layoutManager = LinearLayoutManager(requireContext())

         viewModel.coasters().observe(viewLifecycleOwner){myAdapter.setData(it)}

         searchView = binding.search
         searchView.clearFocus()
         searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
             override fun onQueryTextSubmit(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                     searchView.clearFocus()
                 }
                 return true
             }
             override fun onQueryTextChange(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                 }
                 return true
             }
         })

         return root
     }

     fun searchDatabase(query: String) {
         val searchQuery = "%$query%"

         viewModel.searchDatabase(searchQuery).observe(viewLifecycleOwner) { myAdapter.setData(it)
         }
     }

     override fun onDestroyView() {
         super.onDestroyView()
         _binding = null
     }
 }
</code>```

My adapter:

```<code>class  CoasterRecyclerViewAdapter( val listener: CoasterListener,
                                  val context: Context  )  : RecyclerView.Adapter<CoasterRecyclerViewAdapter.ViewHolder>(){

    private var coasterList = emptyList<CoasterFavorito>()

    class ViewHolder private constructor(val binding: CoasterItemBinding, private val listener: CoasterListener,
                                         private val context: Context): RecyclerView.ViewHolder(binding.root){

        companion object{
            fun crearViewHolder(parent: ViewGroup, listener: CoasterListener,  context: Context):ViewHolder{
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = CoasterItemBinding.inflate(layoutInflater, parent, false)
                return ViewHolder(binding, listener, context )
            }
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.crearViewHolder(parent, listener, context)
    override fun onBindViewHolder(holder: ViewHolder, position: Int){
        holder.binding.nombre.text = coasterList[position].coaster.nombre
        holder.binding.parque.text = coasterList[position].coaster.parque
        holder.binding.ciudad.text = coasterList[position].coaster.ciudad
        holder.binding.provincia.text = coasterList[position].coaster.provincia
        holder.binding.comunidad.text = coasterList[position].coaster.comunidadAutonoma
        Glide
            .with(context)
            .load(coasterList[position].coaster.imagen)
            .centerCrop()
            .into(holder.binding.imagen)

        holder.binding.check.isChecked = coasterList[position].favorito
        holder.binding.check.setOnClickListener{
            if (coasterList[position].favorito) {
                listener.delFavorito(coasterList[position].coaster.id)
                holder.binding.check.isChecked = false

            } else {
                listener.addFavorito(coasterList[position].coaster.id)

                holder.binding.check.isChecked = true

            }
        }
    }
    override fun getItemCount(): Int{
        return coasterList.size
    }
    fun setData(coaster: List<CoasterFavorito>){
        coasterList = coaster
        notifyDataSetChanged()
    }
}

interface CoasterListener {
    fun addFavorito(id: Long)
    fun delFavorito(id: Long)
}
</code>```

I tried changing the focus, changing the notifydatasetchanged with notifyitemchanged, and nothing happens...

Body:
First of all, I am Spanish so my english is not very good.

I have a list of items on a Recyclerview, and I also have a SearchView to filter those items.

Every item has a favourite button, so when you click, the item adds to favorite table.

The problem is that, when I filter something and I start clicking those buttons, odd things happens: some items dissapear from the filtered list. It doesn't happen always, only sometimes. How can I fix this?

My class:

class CoasterFragment : Fragment() {

    private val myAdapter by lazy { CoasterRecyclerViewAdapter(CoasterListenerImpl(requireContext(), viewModel),requireContext()) }
     private lateinit var searchView: SearchView
     private var _binding: FragmentCoasterBinding? = null
     private val binding get() = _binding!!

     private val viewModel: CoastersViewModel by viewModels()
     override fun onCreateView(
             inflater: LayoutInflater,
             container: ViewGroup?,
             savedInstanceState: Bundle?

         ): View {
         _binding = FragmentCoasterBinding.inflate(inflater, container, false)
         val root: View = binding.root
         val recyclerView = binding.recyclerCoaster
         recyclerView.adapter = myAdapter
         recyclerView.layoutManager = LinearLayoutManager(requireContext())

         viewModel.coasters().observe(viewLifecycleOwner){myAdapter.setData(it)}

         searchView = binding.search
         searchView.clearFocus()
         searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
             override fun onQueryTextSubmit(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                     searchView.clearFocus()
                 }
                 return true
             }
             override fun onQueryTextChange(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                 }
                 return true
             }
         })

         return root
     }

     fun searchDatabase(query: String) {
         val searchQuery = "%$query%"

         viewModel.searchDatabase(searchQuery).observe(viewLifecycleOwner) { myAdapter.setData(it)
         }
     }

     override fun onDestroyView() {
         super.onDestroyView()
         _binding = null
     }
 }

My adapter:

class  CoasterRecyclerViewAdapter( val listener: CoasterListener,
                                  val context: Context  )  : RecyclerView.Adapter<CoasterRecyclerViewAdapter.ViewHolder>(){

    private var coasterList = emptyList<CoasterFavorito>()

    class ViewHolder private constructor(val binding: CoasterItemBinding, private val listener: CoasterListener,
                                         private val context: Context): RecyclerView.ViewHolder(binding.root){

        companion object{
            fun crearViewHolder(parent: ViewGroup, listener: CoasterListener,  context: Context):ViewHolder{
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = CoasterItemBinding.inflate(layoutInflater, parent, false)
                return ViewHolder(binding, listener, context )
            }
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.crearViewHolder(parent, listener, context)
    override fun onBindViewHolder(holder: ViewHolder, position: Int){
        holder.binding.nombre.text = coasterList[position].coaster.nombre
        holder.binding.parque.text = coasterList[position].coaster.parque
        holder.binding.ciudad.text = coasterList[position].coaster.ciudad
        holder.binding.provincia.text = coasterList[position].coaster.provincia
        holder.binding.comunidad.text = coasterList[position].coaster.comunidadAutonoma
        Glide
            .with(context)
            .load(coasterList[position].coaster.imagen)
            .centerCrop()
            .into(holder.binding.imagen)

        holder.binding.check.isChecked = coasterList[position].favorito
        holder.binding.check.setOnClickListener{
            if (coasterList[position].favorito) {
                listener.delFavorito(coasterList[position].coaster.id)
                holder.binding.check.isChecked = false

            } else {
                listener.addFavorito(coasterList[position].coaster.id)

                holder.binding.check.isChecked = true

            }
        }
    }
    override fun getItemCount(): Int{
        return coasterList.size
    }
    fun setData(coaster: List<CoasterFavorito>){
        coasterList = coaster
        notifyDataSetChanged()
    }
}

interface CoasterListener {
    fun addFavorito(id: Long)
    fun delFavorito(id: Long)
}

I tried changing the focus, changing the notifydatasetchanged with notifyitemchanged, and nothing happens...


来源: stackexchange

问:
How to add child record items to Advanced HTML pdf NetSuite?
I have a parent(P) and child(C) record in a Form. When there is more than 1 item in the child section, it does not appear on the html/pdf print out.

enter image description here

This is the javascript used to pull data

```<code>define(// jshint ignore:line

["N/record", "N/search", "N/format", "N/task"], function (record, search, format, task) {
  function afterSubmit(context) {
    if (context.type == context.UserEventType.CREATE) {

      var recId = context.newRecord.id;

      var rec = record.load({
        type: "customrecord_mbce_outbound_trip",
        id: recId,
      });

      var lineCount = rec.getLineCount("recmachcustrecord_otl_outbound_trip");

      log.debug({ title: "lineCount", details: lineCount });

      var arrData = [];
      for (var i = 0; i < lineCount; i++) {

        var lpn = rec.getSublistText({
          sublistId: "recmachcustrecord_otl_outbound_trip",
          fieldId: "custrecord_otl_lpn",
          line: i,
        });
        log.debug({ title: "lpn", details: lpn});

        var singleData = {
          lpn: lpn,
        };
        log.debug({ title: "singleData ", details: JSON.stringify(singleData) });

        arrData.push(singleData);
      }
      log.debug({ title: "array", details: JSON.stringify(arrData) });

      rec.setValue({
        fieldId: "custrecord_child_rec_outbound_trip",
        value: JSON.stringify(arrData),
      });

      rec.save();
    }
  }

  return {
    afterSubmit: afterSubmit,
  };
});
</code>```

And the way I call it in advanced html is

```<code> <#if record.custrecord_child_rec_outbound_trip?has_content>
          <#assign customrecord = record.custrecord_child_rec_outbound_trip?eval>
              <table border="0" cellpadding="1" cellspacing="1" style="width: 100%;">
                  <#list customrecord as customrecord_line>
                      <#if customrecord_line_index == 0>
                          <thead>
                              <tr>
                                  <th>LPN</th>
                              </tr>
                          </thead>
                              <tr>
                                  <td>${customrecord_line.lpn}</td>
                              </tr>
                      </#if>
                  </#list>
                </table>
        </#if>
</code>```

The way in look as pdf instead of 8 LPN only 1 coming enter image description here

How can I call all of them in the print out?

ContentLicense: CC BY-SA 4.0

Body:
I have a parent(P) and child(C) record in a Form. When there is more than 1 item in the child section, it does not appear on the html/pdf print out.

enter image description here

This is the javascript used to pull data

define(// jshint ignore:line

["N/record", "N/search", "N/format", "N/task"], function (record, search, format, task) {
  function afterSubmit(context) {
    if (context.type == context.UserEventType.CREATE) {

      var recId = context.newRecord.id;

      var rec = record.load({
        type: "customrecord_mbce_outbound_trip",
        id: recId,
      });

      var lineCount = rec.getLineCount("recmachcustrecord_otl_outbound_trip");

      log.debug({ title: "lineCount", details: lineCount });

      var arrData = [];
      for (var i = 0; i < lineCount; i++) {

        var lpn = rec.getSublistText({
          sublistId: "recmachcustrecord_otl_outbound_trip",
          fieldId: "custrecord_otl_lpn",
          line: i,
        });
        log.debug({ title: "lpn", details: lpn});

        var singleData = {
          lpn: lpn,
        };
        log.debug({ title: "singleData ", details: JSON.stringify(singleData) });

        arrData.push(singleData);
      }
      log.debug({ title: "array", details: JSON.stringify(arrData) });

      rec.setValue({
        fieldId: "custrecord_child_rec_outbound_trip",
        value: JSON.stringify(arrData),
      });

      rec.save();
    }
  }

  return {
    afterSubmit: afterSubmit,
  };
});

And the way I call it in advanced html is

 <#if record.custrecord_child_rec_outbound_trip?has_content>
          <#assign customrecord = record.custrecord_child_rec_outbound_trip?eval>

                  <#list customrecord as customrecord_line>
                      <#if customrecord_line_index == 0>

                                  LPN

                                  ${customrecord_line.lpn}

                      </#if>
                  </#list>

        </#if>

The way in look as pdf instead of 8 LPN only 1 coming enter image description here

How can I call all of them in the print out?


问:
What type of statistical test to use on zero-inflated, non-integer continuous data?
I have a dataset, with a response variable that describes the hourly rate of anthropomorphic disturbances on groups of birds. Each hourly rate is that of a day. The values range from 0 to 2.4, and seeing as many days went by without a disturbance, there a high presence of zeroes (34 out of 69 inputs are 0).

I want to compare the hourly rate between different categorical variables (weekend vs weekday, No holiday vs holiday, year 2020 vs 2022) and some continuous variables (water level, time of day).
I have been looking at some different types of models that could circumvent zero-inflated data such as mine. One example was the gamma-hurdle model, but I struggled a little to understand. I felt like a simple zero-inflated poisson wouldn't work because the data doesn't consist of integers. I realize that maybe my analysis is a little complex and it might be best to split it into multiple smaller analyses. However, I still need to find a way to best model such a response variable. Any help is appreciated!


问:
The type 'HttpRequestMessageExtensions' exists in both 'System.Net.Http.Formatting, and 'System.Web.Http
In my Azure Function app. I have the following error.

I also cant find the dependencies that it is referring to.

I've tried using an Alias on the dependency but that does not solve the issue when i try to make a POST call to azure.

```<code>    //extern alias Alias_2;

//alias for usings
//using namespace2 = Alias_2::System.Net.Http.HttpRequestMessageExtensions;
</code>```

I have tried using an alias but that gives me a 500 error message. (see my post)

Body:
In my Azure Function app. I have the following error.

I also cant find the dependencies that it is referring to.

I've tried using an Alias on the dependency but that does not solve the issue when i try to make a POST call to azure.

    //extern alias Alias_2;

//alias for usings
//using namespace2 = Alias_2::System.Net.Http.HttpRequestMessageExtensions;

I have tried using an alias but that gives me a 500 error message. (see my post)


问:
How to specify range of port while creating httpserver?
I am trying to create an http server using JDK's com.sun.net.httpserver. I am able to run the server with certain endpoints successfully. And it return some random ephemeral port ranging from 0 to 65536.

```<code>HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
</code>```

I was going through the documentation but I couldn't see a way to specify some range instead of specific port.
Is there any way passing range can be achieved?

One hack to the solution is try for all ports in range and see whichever works as specified in the solution - How to find an available port?

Body:
I am trying to create an http server using JDK's com.sun.net.httpserver. I am able to run the server with certain endpoints successfully. And it return some random ephemeral port ranging from 0 to 65536.

HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);

I was going through the documentation but I couldn't see a way to specify some range instead of specific port.
Is there any way passing range can be achieved?

One hack to the solution is try for all ports in range and see whichever works as specified in the solution - How to find an available port?


问:
getTGD function- GAMLSS PACKAGE
I am working with getTGD function in GAMLSS. But as soon as I run it on my data, I got the follwoing error

```<code> gg1 <-getTGD(m10, newdata=test)
new prediction
New way of prediction in pb()  (starting from GAMLSS version 5.0-3)
new prediction
New way of prediction in pb()  (starting from GAMLSS version 5.0-3)
Error in pnorm(z) : Non-numeric argument to mathematical function
</code>```

All columns in the data set are in numeric format. So I would be so thannkful if you let me know how I can fix this problem.

Title: getTGD function- GAMLSS PACKAGE

Body:
I am working with getTGD function in GAMLSS. But as soon as I run it on my data, I got the follwoing error

 gg1 <-getTGD(m10, newdata=test)
new prediction
New way of prediction in pb()  (starting from GAMLSS version 5.0-3)
new prediction
New way of prediction in pb()  (starting from GAMLSS version 5.0-3)
Error in pnorm(z) : Non-numeric argument to mathematical function

All columns in the data set are in numeric format. So I would be so thannkful if you let me know how I can fix this problem.


问:
Using cvzone HandDetector with a webcam in Django
I am working on a Django project that involves using a webcam to play a rock-paper-scissors game against a computer. I have implemented the HandDetector algorithm to detect a hand in the webcam video feed, and a Keras classifier to classify the hand gesture. However, I am running into an issue with getting the HandDetector to work properly with the webcam video.

I have tried using a single still image from the webcam, but the HandDetector does not work well with just one image. I think the solution is to use a video of the hand, but I am not sure how to implement this in my Django project.

Here is the code for my jQuery script that captures the video from the webcam and sends it to a Django view:

```<code><div class="container">
  <div class="row">
    <div class="col-md-6">
      <video id="webcam" width="640" height="480" autoplay></video>
    </div>
    <div class="col-md-6">
      <button id="play-button" class="btn btn-primary" onclick="play()">Play</button>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() { startWebcam(); });

var video = document.getElementById('webcam');
var stream;

function startWebcam() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
    .then(function(localMediaStream) {
        stream = localMediaStream;
        video.srcObject = localMediaStream;
        video.play();
    })
    .catch(function(err) {
        console.log("An error occurred: " + err);
    });
}

function play() {
    // Stop the video stream from the webcam
    var tracks = stream.getTracks();

    for (var i = 0; i < tracks.length; i++) {
        var track = tracks[i];
        track.stop();
    }
    // Start recording
    var chunks = [];
    var recorder = new MediaRecorder(stream);
    recorder.start();

    // Count down from 3 seconds
    var count = 3;
    var countdown = setInterval(function() {
        $('#countdown').html(count);
        count--;
        if (count === -1) {
            clearInterval(countdown);
            recorder.stop();
        }
    }, 1000);

    recorder.ondataavailable = function(e) {
        chunks.push(e.data);
    }

    recorder.onstop = function() {
        // Concatenate all the chunks
        var blob = new Blob(chunks, { type: 'video/webm' });
        chunks = [];

        // Send the video to the server
        var formData = new FormData();
        formData.append("video_data", blob);
        formData.append("csrfmiddlewaretoken", '{{ csrf_token }}');

        $.ajax({
            type: 'POST',
            url: '/process-video/',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                console.log(response);
                $('#result').html(response);
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
    };
}
</script>
</code>```

Here are the django views I use:

```<code>def process_video(request):
    if request.method != 'POST':
        return HttpResponse("Error: Invalid request method")

    # Get the video data from the request
    video_data = request.FILES.get('video_data')

    # Use OpenCV to read the video and extract the frames
    cap = cv2.VideoCapture(video_data)
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            # Process the frame and check for a hand
            prediction = process_image_data(frame)
            if prediction != "Error: No hand detected in the image":
                cap.release()
                return HttpResponse(prediction)
        else:
            break

    cap.release()
    return HttpResponse("Error: No hand detected in the video. Please try again.")

def process_image_data(image_data):
    # Initialize the hand detector, image processor, and classifier
    detector = HandDetector(maxHands=1)
    processor = ImageProcessor(detector, 300, 20)
    classifier = HandClassifier()
    # Find the hand in the image
    hands = detector.findHands(image_data, draw=False)

    # If a hand is detected in the image
    if hands:
        hand = hands[0]
        x, y, w, h = hand['bbox']
        img_white, img_resize = processor.process(image_data, hand)
        # Calculate the aspect ratio of the cropped image
        aspect_ratio = h / w
        # If the aspect ratio is greater than 1, add the resized image to the white image
        # with a gap at the top and bottom to center the image
        if aspect_ratio > 1:
            h_gap = math.ceil((300 - img_resize.shape[0]) / 2)
            img_white[h_gap:h_gap + img_resize.shape[0], :] = img_resize
        # If the aspect ratio is less than or equal to 1, add the resized image to the white image
        # with a gap at the left and right to center the image
        else:
            w_gap = math.ceil((300 - img_resize.shape[1]) / 2)
            img_white[:, w_gap:w_gap + img_resize.shape[1]] = img_resize

        # Classify the image and return the prediction
        return classifier.classify(img_white)
    else:
        return "Error: No hand detected in the image"
</code>```

The HandClassifier class

```<code>import cv2
import numpy as np
from PIL import Image, ImageOps
from keras.models import load_model
import os

class HandClassifier:
    def __init__(self):
        # Get the absolute paths to the model and labels files
        model_path = os.path.abspath('../keras/keras_model.h5')
        labels_path = os.path.abspath('../keras/labels.txt')

        # Load the model and labels
        self.model = load_model(model_path, compile=False)
        with open(labels_path, 'r') as f:
            self.labels = f.read().splitlines()

    def classify(self, image):
        # Resize the image to a 224x224 with the same strategy as in TM2:
        # resizing the image to be at least 224x224 and then cropping from the center
        image = Image.fromarray(image)
        image.convert('RGB')
        size = (224, 224)
        image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
        # Turn the image into a NumPy array
        image_array = np.asarray(image)
        # Normalize the image
        normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
        # Add the image to the data array
        data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
        data[0] = normalized_image_array
        # Use the model to make a prediction
        prediction = self.model.predict(data)
        # Get the index of the most likely class
        index = np.argmax(prediction[0])

        # run the inference
        prediction = self.model.predict(data)
        index = np.argmax(prediction)
        class_name = self.labels[index]
        confidence_score = prediction[0][index]

        return class_name

</code>```

And the ImageProcessor class

```<code>import cv2
import numpy as np

class ImageProcessor:
    def __init__(self, detector, img_size, offset):
        self.detector = detector
        self.img_size = img_size
        self.offset = offset

    def process(self, img, hand):
        # Crop the image based on the bounding box of the detected hand
        x, y, w, h = hand['bbox']
        img_crop = img[y - self.offset:y + h + self.offset, x - self.offset:x + w + self.offset]

        # Convert the image to grayscale
        img_crop = cv2.cvtColor(img_crop, cv2.COLOR_BGR2GRAY)

        # Convert the image data to depth 8 bits per pixel
        img_hog = cv2.normalize(img_crop, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

        # Apply median filtering to the image to remove noise
        img_hog = cv2.medianBlur(img_hog, ksize=5)

        # Resize the image to 300x300
        img_crop = cv2.resize(img_hog, (self.img_size, self.img_size))

        # Add a third dimension to the resized image to match the shape of the white image
        img_resize = np.expand_dims(img_crop, axis=2)

        # Create an empty white image of size 300x300
        img_white = np.ones((self.img_size, self.img_size, 3), np.uint8) * 255

        return img_white, img_resize

</code>```

Any help/tips on what would be the best most performant way to do this would be greatly appreciated

I have tried first to send a image taken from the webcam to the views.py but the problem here was that the handdetector never detected any hands. When i try my code out in a test class I wrote it works and classifies the hand live, but this is a live webcam feed in a seperate opencv window. this is the testing class btw

```<code>import cv2
from cvzone.HandTrackingModule import HandDetector
import math

from src.rps.hand_recognition.HandClassifier import HandClassifier
from src.rps.hand_recognition.ImageProcessor import ImageProcessor

cap = cv2.VideoCapture(0)
detector = HandDetector(maxHands=1)
classifier = HandClassifier()

offset = 20
img_size = 300

labels = ["paper", "rock", "scissors"]

while True:
    processor = ImageProcessor(detector, img_size, offset)
    success, img = cap.read()
    hands = detector.findHands(img, draw=False)

    if hands:
        hand = hands[0]
        x, y, w, h = hand['bbox']
        img_white, img_resize = processor.process(img, hand)
        # Calculate the aspect ratio of the cropped image
        aspect_ratio = h / w
        # If the aspect ratio is greater than 1, add the resized image to the white image
        # with a gap at the top and bottom to center the image
        if aspect_ratio > 1:
            h_gap = math.ceil((img_size - img_resize.shape[0]) / 2)
            img_white[h_gap:h_gap + img_resize.shape[0], :] = img_resize

        # If the aspect ratio is less than or equal to 1, add the resized image to the white image
        # with a gap at the left and right to center the image
        else:
            w_gap = math.ceil((img_size - img_resize.shape[1]) / 2)
            img_white[:, w_gap:w_gap + img_resize.shape[1]] = img_resize

        # improve with probability!!!!
        prediction = classifier.classify(img_white)

        cv2.rectangle(img, (x - offset, y - offset - 50),
                      (x - offset + 90, y - offset - 50 + 50), (255, 0, 255), cv2.FILLED)
        cv2.putText(img, prediction, (x, y - 26), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2)
        cv2.rectangle(img, (x - offset, y - offset),
                      (x + w + offset, y + h + offset), (255, 0, 255), 4)

        cv2.imshow("ImageWhite", img_white)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

</code>```

Body:
I am working on a Django project that involves using a webcam to play a rock-paper-scissors game against a computer. I have implemented the HandDetector algorithm to detect a hand in the webcam video feed, and a Keras classifier to classify the hand gesture. However, I am running into an issue with getting the HandDetector to work properly with the webcam video.

I have tried using a single still image from the webcam, but the HandDetector does not work well with just one image. I think the solution is to use a video of the hand, but I am not sure how to implement this in my Django project.

Here is the code for my jQuery script that captures the video from the webcam and sends it to a Django view:

      <video id="webcam" width="640" height="480" autoplay></video>

      <button id="play-button" class="btn btn-primary" onclick="play()">Play</button>

Here are the django views I use:

def process_video(request):
    if request.method != 'POST':
        return HttpResponse("Error: Invalid request method")

    # Get the video data from the request
    video_data = request.FILES.get('video_data')

    # Use OpenCV to read the video and extract the frames
    cap = cv2.VideoCapture(video_data)
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            # Process the frame and check for a hand
            prediction = process_image_data(frame)
            if prediction != "Error: No hand detected in the image":
                cap.release()
                return HttpResponse(prediction)
        else:
            break

    cap.release()
    return HttpResponse("Error: No hand detected in the video. Please try again.")

def process_image_data(image_data):
    # Initialize the hand detector, image processor, and classifier
    detector = HandDetector(maxHands=1)
    processor = ImageProcessor(detector, 300, 20)
    classifier = HandClassifier()
    # Find the hand in the image
    hands = detector.findHands(image_data, draw=False)

    # If a hand is detected in the image
    if hands:
        hand = hands[0]
        x, y, w, h = hand['bbox']
        img_white, img_resize = processor.process(image_data, hand)
        # Calculate the aspect ratio of the cropped image
        aspect_ratio = h / w
        # If the aspect ratio is greater than 1, add the resized image to the white image
        # with a gap at the top and bottom to center the image
        if aspect_ratio > 1:
            h_gap = math.ceil((300 - img_resize.shape[0]) / 2)
            img_white[h_gap:h_gap + img_resize.shape[0], :] = img_resize
        # If the aspect ratio is less than or equal to 1, add the resized image to the white image
        # with a gap at the left and right to center the image
        else:
            w_gap = math.ceil((300 - img_resize.shape[1]) / 2)
            img_white[:, w_gap:w_gap + img_resize.shape[1]] = img_resize

        # Classify the image and return the prediction
        return classifier.classify(img_white)
    else:
        return "Error: No hand detected in the image"

The HandClassifier class

import cv2
import numpy as np
from PIL import Image, ImageOps
from keras.models import load_model
import os

class HandClassifier:
    def __init__(self):
        # Get the absolute paths to the model and labels files
        model_path = os.path.abspath('../keras/keras_model.h5')
        labels_path = os.path.abspath('../keras/labels.txt')

        # Load the model and labels
        self.model = load_model(model_path, compile=False)
        with open(labels_path, 'r') as f:
            self.labels = f.read().splitlines()

    def classify(self, image):
        # Resize the image to a 224x224 with the same strategy as in TM2:
        # resizing the image to be at least 224x224 and then cropping from the center
        image = Image.fromarray(image)
        image.convert('RGB')
        size = (224, 224)
        image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
        # Turn the image into a NumPy array
        image_array = np.asarray(image)
        # Normalize the image
        normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
        # Add the image to the data array
        data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
        data[0] = normalized_image_array
        # Use the model to make a prediction
        prediction = self.model.predict(data)
        # Get the index of the most likely class
        index = np.argmax(prediction[0])

        # run the inference
        prediction = self.model.predict(data)
        index = np.argmax(prediction)
        class_name = self.labels[index]
        confidence_score = prediction[0][index]

        return class_name

And the ImageProcessor class

import cv2
import numpy as np

class ImageProcessor:
    def __init__(self, detector, img_size, offset):
        self.detector = detector
        self.img_size = img_size
        self.offset = offset

    def process(self, img, hand):
        # Crop the image based on the bounding box of the detected hand
        x, y, w, h = hand['bbox']
        img_crop = img[y - self.offset:y + h + self.offset, x - self.offset:x + w + self.offset]

        # Convert the image to grayscale
        img_crop = cv2.cvtColor(img_crop, cv2.COLOR_BGR2GRAY)

        # Convert the image data to depth 8 bits per pixel
        img_hog = cv2.normalize(img_crop, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

        # Apply median filtering to the image to remove noise
        img_hog = cv2.medianBlur(img_hog, ksize=5)

        # Resize the image to 300x300
        img_crop = cv2.resize(img_hog, (self.img_size, self.img_size))

        # Add a third dimension to the resized image to match the shape of the white image
        img_resize = np.expand_dims(img_crop, axis=2)

        # Create an empty white image of size 300x300
        img_white = np.ones((self.img_size, self.img_size, 3), np.uint8) * 255

        return img_white, img_resize

Any help/tips on what would be the best most performant way to do this would be greatly appreciated

I have tried first to send a image taken from the webcam to the views.py but the problem here was that the handdetector never detected any hands. When i try my code out in a test class I wrote it works and classifies the hand live, but this is a live webcam feed in a seperate opencv window. this is the testing class btw

import cv2
from cvzone.HandTrackingModule import HandDetector
import math

from src.rps.hand_recognition.HandClassifier import HandClassifier
from src.rps.hand_recognition.ImageProcessor import ImageProcessor

cap = cv2.VideoCapture(0)
detector = HandDetector(maxHands=1)
classifier = HandClassifier()

offset = 20
img_size = 300

labels = ["paper", "rock", "scissors"]

while True:
    processor = ImageProcessor(detector, img_size, offset)
    success, img = cap.read()
    hands = detector.findHands(img, draw=False)

    if hands:
        hand = hands[0]
        x, y, w, h = hand['bbox']
        img_white, img_resize = processor.process(img, hand)
        # Calculate the aspect ratio of the cropped image
        aspect_ratio = h / w
        # If the aspect ratio is greater than 1, add the resized image to the white image
        # with a gap at the top and bottom to center the image
        if aspect_ratio > 1:
            h_gap = math.ceil((img_size - img_resize.shape[0]) / 2)
            img_white[h_gap:h_gap + img_resize.shape[0], :] = img_resize

        # If the aspect ratio is less than or equal to 1, add the resized image to the white image
        # with a gap at the left and right to center the image
        else:
            w_gap = math.ceil((img_size - img_resize.shape[1]) / 2)
            img_white[:, w_gap:w_gap + img_resize.shape[1]] = img_resize

        # improve with probability!!!!
        prediction = classifier.classify(img_white)

        cv2.rectangle(img, (x - offset, y - offset - 50),
                      (x - offset + 90, y - offset - 50 + 50), (255, 0, 255), cv2.FILLED)
        cv2.putText(img, prediction, (x, y - 26), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2)
        cv2.rectangle(img, (x - offset, y - offset),
                      (x + w + offset, y + h + offset), (255, 0, 255), 4)

        cv2.imshow("ImageWhite", img_white)

    cv2.imshow("Image", img)
    cv2.waitKey(1)


Title: How can I convert By class nls model list into data frame in R?

Body:
I have been trying to run a modified two pooled exponential decay model:

mass_loss ~ m1*exp(-k*cdi*t) + m2*exp(-k2*cdi*t)

over a dataframe (decomp_Control) with multiple sites and then extract the model coefficients into a data frame.

Setting up data

        decomp_control <-
        structure(list(site_number = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L), site_code = c("CCPp1a", "CCPp1b", "CCPp1c", "CCPp1d",
"CCPp1e", "CCPp1f", "CCPp2a", "CCPp2b", "CCPp2c", "CCPp2d", "CCPp3a",
"CCPp3b", "CCPp3c", "CCPp3d", "CCPp5a", "CCPp5b", "CCPp5c", "CCPp5d",
"CMPp2a", "CMPp2b", "CMPp2c", "CMPp2d", "CMPp3a", "CMPp3b", "CMPp3c",
"CMPp3d"), days_between = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L), mass_remaining = c(100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100), cdi_mean = c(0.636176396, 0.636176396,
0.636176396, 0.636176396, 0.636176396, 0.636176396, 0.699725486,
0.699725486, 0.699725486, 0.699725486, 0.664880103, 0.664880103,
0.664880103, 0.664880103, 0.679079501, 0.679079501, 0.679079501,
0.679079501, 0.681828353, 0.681828353, 0.681828353, 0.681828353,
0.705206121, 0.705206121, 0.705206121, 0.705206121), m2 = c(43.65475,
43.65475, 43.65475, 43.65475, 43.65475, 43.65475, 43.98935, 43.98935,
43.98935, 43.98935, 44.08055, 44.08055, 44.08055, 44.08055, 44.3788,
44.3788, 44.3788, 44.3788, 45.22985, 45.22985, 45.22985, 45.22985,
45.41225, 45.41225, 45.41225, 45.41225), m1 = c(56.34525, 56.34525,
56.34525, 56.34525, 56.34525, 56.34525, 56.01065, 56.01065, 56.01065,
56.01065, 55.91945, 55.91945, 55.91945, 55.91945, 55.6212, 55.6212,
55.6212, 55.6212, 54.77015, 54.77015, 54.77015, 54.77015, 54.58775,
54.58775, 54.58775, 54.58775)), row.names = c(NA, -26L), class = "data.frame")

     str(decomp_control)
    structure(list(site_number = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L), site_code = c("CCPp1a", "CCPp1b", "CCPp1c", "CCPp1d",
"CCPp1e", "CCPp1f", "CCPp2a", "CCPp2b", "CCPp2c", "CCPp2d", "CCPp3a",
"CCPp3b", "CCPp3c", "CCPp3d", "CCPp5a", "CCPp5b", "CCPp5c", "CCPp5d",
"CMPp2a", "CMPp2b", "CMPp2c", "CMPp2d", "CMPp3a", "CMPp3b", "CMPp3c",
"CMPp3d"), days_between = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L), mass_remaining = c(100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100), cdi_mean = c(0.636176396, 0.636176396,
0.636176396, 0.636176396, 0.636176396, 0.636176396, 0.699725486,
0.699725486, 0.699725486, 0.699725486, 0.664880103, 0.664880103,
0.664880103, 0.664880103, 0.679079501, 0.679079501, 0.679079501,
0.679079501, 0.681828353, 0.681828353, 0.681828353, 0.681828353,
0.705206121, 0.705206121, 0.705206121, 0.705206121), m2 = c(43.65475,
43.65475, 43.65475, 43.65475, 43.65475, 43.65475, 43.98935, 43.98935,
43.98935, 43.98935, 44.08055, 44.08055, 44.08055, 44.08055, 44.3788,
44.3788, 44.3788, 44.3788, 45.22985, 45.22985, 45.22985, 45.22985,
45.41225, 45.41225, 45.41225, 45.41225), m1 = c(56.34525, 56.34525,
56.34525, 56.34525, 56.34525, 56.34525, 56.01065, 56.01065, 56.01065,
56.01065, 55.91945, 55.91945, 55.91945, 55.91945, 55.6212, 55.6212,
55.6212, 55.6212, 54.77015, 54.77015, 54.77015, 54.77015, 54.58775,
54.58775, 54.58775, 54.58775)), row.names = c(NA, -26L), class = "data.frame")

My nls model is as follows:

two_pool <- function(m1,k1,cdi,t,m2,k2){(m1*exp(-k1*cdi*t)+
                                           m2*exp(-k2*cdi*t))
}

nls(mass_remaining ~ two_pool(m1,k1,cdi_mean,days_between,
                                      m2,k2),
            start = list(k1 = 0.0121, k2 = 0.000000000001696), data = decomp_Control)

I have tried running the nls model across categories of site_code and have only found one way that works, which is probably not the best so any advice is welcome.

models <- by(decomp_Control, decomp_Control$site_code, function(x) {
  fm <- nls(mass_remaining ~ two_pool(m1,k1,cdi_mean,days_between,
                                      m2,k2),
            start = list(k1 = 0.0121, k2 = 0.000000000001696), data = decomp_Control)
  fm
})

I have tried to turn this model into a dataframe so I can easily extract the model coefficients which have all failed.  Below are my attempts with the respective errors:

mod_list <- list(models)

output_list <- mod_list %>%
  map(unlist) %>%
  do.call(cbind.data.frame, .)

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
cannot coerce class ‘"nls"’ to a data.frame

do.call(rbind,lapply(mod_list, function(x) as.data.frame.list(unlist(x))))

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
cannot coerce class ‘"nls"’ to a data.frame

I have tried a few other techniques which created data frames but saved the coefficients as the string "numeric".

Any help with either looping the nls model more efficiently or extracting the model coefficients is greatly appreciated.


问:
Fabric.js cannot be dragged
Using this code is draggable.

```<code><template>
  <!-- <div id="canvas"></div>
   -->
  <canvas
    width="600"
    height="600"
    id="canvas"
    style="border: 1px solid #ccc"
  ></canvas>
</template>

<script setup>
import { onMounted } from "vue";
import { fabric } from "fabric";

function init() {
  let canvas = new fabric.Canvas("canvas");

  // 矩形
  let rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: "orange",
    width: 100,
    height: 100,
  });
  canvas.add(rect);`your text`
  // canvas.selectable = true;
  // document.getElementById("canvas").replaceChildren(canvas.getElement());
}

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
</style>
</code>```

But the following paragraph doesn't work, it just creates the canvas dynamically.

```<code><template>
  <div id="canvas"></div>
  <!-- <canvas
    width="600"
    height="600"
    id="canvas"
    style="border: 1px solid #ccc"
  ></canvas> -->
</template>

<script setup>
import { onMounted } from "vue";
import { fabric } from "fabric";

function init() {
  let canvas = new fabric.Canvas(document.createElement("canvas"));

  // 矩形
  let rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: "orange",
    width: 100,
    height: 100,
  });
  canvas.add(rect);
  canvas.selectable = true;
  document.getElementById("canvas").replaceChildren(canvas.getElement());
}

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
</style>
</code>```

Differences.

html

```<code>First code  <canvas
    width="600"
    height="600"
    id="canvas"
    style="border: 1px solid #ccc"
  ></canvas>

Second code
<div id="canvas"></div>
</code>```

First code

```<code>let canvas = new fabric.Canvas("canvas");
</code>```

Second code

```<code>let canvas = new fabric.Canvas(document.createElement("canvas"));
canvas.selectable = true;
document.getElementById("canvas").replaceChildren(canvas.getElement());
</code>```

The second code cannot be dragged.
I don't know why.

codesendbox url:https://codesandbox.io/s/autumn-field-xzewvd

I would like to be able to drag, but in a second form.

Title: Fabric.js cannot be dragged

Body:
Using this code is draggable.

<template>

  <canvas
    width="600"
    height="600"
    id="canvas"
    style="border: 1px solid #ccc"
  ></canvas>
</template>

But the following paragraph doesn't work, it just creates the canvas dynamically.

<template>

</template>

Differences.

html

First code  <canvas
    width="600"
    height="600"
    id="canvas"
    style="border: 1px solid #ccc"
  ></canvas>

Second code

First code

let canvas = new fabric.Canvas("canvas");

Second code

let canvas = new fabric.Canvas(document.createElement("canvas"));
canvas.selectable = true;
document.getElementById("canvas").replaceChildren(canvas.getElement());

The second code cannot be dragged.
I don't know why.

codesendbox url:https://codesandbox.io/s/autumn-field-xzewvd

I would like to be able to drag, but in a second form.


问:
How to set default index when using viewpager2, using setCurrentItem initialises the viewpager with 0 index as default and then navigates to the index
I am using setCurrentItem , what it does is set's up my viewpager2 with the default 0 index and then it slides and opens the index which i pass in setCurrent Item . I want is to initialise and remain on the same index which i am passing.

currently i am using
viewPager.setCurrentItem(index,false)

what it does is sets up view pager and then navigates to the specified index.

i am looking for something which sets up viewpager to the specified index and not navigate after setting up.


问:
Scala project with metals can't recognize plugins
I have a pretty big project written in Scala 2.12.15

Tried to run it with NeoVim and VS Code, using metals

LSP log at .metals/lsp.trace.json contains the following errors while importing the project:

```<code>    "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value wartremoverWarnings"                                     "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value Warts"
    "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value Wart"                                                    "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value AssemblyPlugin"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value AssemblyPlugin"                                          "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assemblyJarName"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assembly"                                                "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assemblyMergeStrategy"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assembly"                                                "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value PathList"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value MergeStrategy"                                           "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value MergeStrategy"
...
</code>```

Seems that metals can't recognize the plugins.
All of the are specified at project/plugins.sbt:

```<code>  addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.1.0")
  addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.5")
  addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
  addSbtPlugin("org.wartremover" % "sbt-wartremover" % "3.0.6")
  addCompilerPlugin("org.scalamacros" %% "paradise" % "2.1.1" cross CrossVersion.full)
  addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "1.16")
  addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.3")
  addSbtPlugin("com.github.sbt" % "sbt-release" % "1.0.15")
  addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.2")
  addSbtPlugin("com.github.sbt" % "sbt-duplicates-finder" % "1.0.0")
</code>```

IDEA is working easily with this.

What may be wrong?

OS: Mac OS

Body:
I have a pretty big project written in Scala 2.12.15

Tried to run it with NeoVim and VS Code, using metals

LSP log at .metals/lsp.trace.json contains the following errors while importing the project:

    "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value wartremoverWarnings"                                     "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value Warts"
    "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value Wart"                                                    "message": "2023.01.11 13:19:02 ERROR <some_path_here> error: not found: value AssemblyPlugin"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value AssemblyPlugin"                                          "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assemblyJarName"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assembly"                                                "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assemblyMergeStrategy"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value assembly"                                                "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value PathList"
    "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value MergeStrategy"                                           "message": "2023.01.11 13:19:03 ERROR <some_path_here> error: not found: value MergeStrategy"
...

Seems that metals can't recognize the plugins.
All of the are specified at project/plugins.sbt:

  addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.1.0")
  addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.5")
  addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
  addSbtPlugin("org.wartremover" % "sbt-wartremover" % "3.0.6")
  addCompilerPlugin("org.scalamacros" %% "paradise" % "2.1.1" cross CrossVersion.full)
  addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "1.16")
  addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.3")
  addSbtPlugin("com.github.sbt" % "sbt-release" % "1.0.15")
  addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.2")
  addSbtPlugin("com.github.sbt" % "sbt-duplicates-finder" % "1.0.0")

IDEA is working easily with this.

What may be wrong?

OS: Mac OS


问:
API gets data but shows "index out of range" error when I try to extract a piece of data
I am new to python and I haven't found a similar problem on this platform that's why I decided to ask.

Help me point out the error.

This is the API Data from Tequila. I am working with several cities but only extracted two for illustration.

[{'id': 'cape-town_za', 'active': True, 'name': 'Cape Town', 'slug': 'cape-town-south-africa', 'slug_en': 'cape-town-south-africa', 'code': 'CPT', 'alternative_names': [], 'rank': 125, 'global_rank_dst': 39, 'dst_popularity_score': 1543371.0, 'timezone': 'Africa/Johannesburg', 'population': 3433441, 'airports': 1, 'stations': 0, 'hotels': 0, 'bus_stations': 0, 'subdivision': None, 'autonomous_territory': None, 'country': {'id': 'ZA', 'name': 'South Africa', 'slug': 'south-africa', 'code': 'ZA'}, 'region': {'id': 'southern-africa', 'name': 'Southern Africa', 'slug': 'southern-africa'}, 'continent': {'id': 'africa', 'name': 'Africa', 'slug': 'africa', 'code': 'AF'}, 'nearby_country': None, 'location': {'lat': -33.924869, 'lon': 18.424055}, 'tags': [{'tag': 'activities', 'month_to': -1, 'month_from': -1}, {'tag': 'beach', 'month_to': -1, 'month_from': -1}], 'alternative_departure_points': [{'id': 'CPT', 'distance': 18.55, 'duration': 1101.2}], 'providers': [1175, 1282], 'car_rentals': [{'provider_id': 1175, 'providers_locations': ['19065', '657388']}], 'type': 'city'}]
[{'city': 'Dubai ', 'iataCode': None, 'lowestPrice': 290, 'id': 2}, {'city': 'Namibia ', 'iataCode': None, 'lowestPrice': 42, 'id': 3}, {'city': 'Tokyo', 'iataCode': None, 'lowestPrice': 485, 'id': 4}, {'city': 'Sydney', 'iataCode': None, 'lowestPrice': 551, 'id': 5}, {'city': 'Istanbul', 'iataCode': None, 'lowestPrice': 95, 'id': 6}, {'city': 'Kuala Lumpur', 'iataCode': None, 'lowestPrice': 414, 'id': 7}, {'city': 'New York', 'iataCode': None, 'lowestPrice': 240, 'id': 8}, {'city': 'San Francisco', 'iataCode': None, 'lowestPrice': 260, 'id': 9}, {'city': 'Cape Town', 'iataCode': None, 'lowestPrice': 378, 'id': 10}]
```
<p>This is my code. I want to extract the "code" from the API data above.</p>
```import requests
from pprint import pprint

TEQUILA_API_KEY = MY_API KEY
TEQUILA_ENDPOINT = "https://api.tequila.kiwi.com"

class FlightSearch:

    def get_destination_code(self, city_name):
        location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
        headers = {"apikey": TEQUILA_API_KEY}
        query = {"term": city_name, "location_types": "city"}
        response = requests.get(url=location_endpoint, headers=headers, params=query)
        results = response.json()["locations"]
        code = results[0]["code"]
        pprint(results)
```
<p>Whenever I run the code, I get the code for the city in index 0, which is "CPT," followed by the following error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "C:\Users\helly\PycharmProjects\day44\main.py", line 23, in <module>
    row["iataCode"] = flight_search.get_destination_code(row["city"])
  File "C:\Users\Helly\PycharmProjects\day44\flight_search.py", line 23, in get_destination_code
    code = results[0]["code"]
IndexError: list index out of range
</code>```

Where is the error in this code?

Body:
I am new to python and I haven't found a similar problem on this platform that's why I decided to ask.

Help me point out the error.

This is the API Data from Tequila. I am working with several cities but only extracted two for illustration.

[{'id': 'cape-town_za', 'active': True, 'name': 'Cape Town', 'slug': 'cape-town-south-africa', 'slug_en': 'cape-town-south-africa', 'code': 'CPT', 'alternative_names': [], 'rank': 125, 'global_rank_dst': 39, 'dst_popularity_score': 1543371.0, 'timezone': 'Africa/Johannesburg', 'population': 3433441, 'airports': 1, 'stations': 0, 'hotels': 0, 'bus_stations': 0, 'subdivision': None, 'autonomous_territory': None, 'country': {'id': 'ZA', 'name': 'South Africa', 'slug': 'south-africa', 'code': 'ZA'}, 'region': {'id': 'southern-africa', 'name': 'Southern Africa', 'slug': 'southern-africa'}, 'continent': {'id': 'africa', 'name': 'Africa', 'slug': 'africa', 'code': 'AF'}, 'nearby_country': None, 'location': {'lat': -33.924869, 'lon': 18.424055}, 'tags': [{'tag': 'activities', 'month_to': -1, 'month_from': -1}, {'tag': 'beach', 'month_to': -1, 'month_from': -1}], 'alternative_departure_points': [{'id': 'CPT', 'distance': 18.55, 'duration': 1101.2}], 'providers': [1175, 1282], 'car_rentals': [{'provider_id': 1175, 'providers_locations': ['19065', '657388']}], 'type': 'city'}]
[{'city': 'Dubai ', 'iataCode': None, 'lowestPrice': 290, 'id': 2}, {'city': 'Namibia ', 'iataCode': None, 'lowestPrice': 42, 'id': 3}, {'city': 'Tokyo', 'iataCode': None, 'lowestPrice': 485, 'id': 4}, {'city': 'Sydney', 'iataCode': None, 'lowestPrice': 551, 'id': 5}, {'city': 'Istanbul', 'iataCode': None, 'lowestPrice': 95, 'id': 6}, {'city': 'Kuala Lumpur', 'iataCode': None, 'lowestPrice': 414, 'id': 7}, {'city': 'New York', 'iataCode': None, 'lowestPrice': 240, 'id': 8}, {'city': 'San Francisco', 'iataCode': None, 'lowestPrice': 260, 'id': 9}, {'city': 'Cape Town', 'iataCode': None, 'lowestPrice': 378, 'id': 10}]

This is my code. I want to extract the "code" from the API data above.

import requests
from pprint import pprint

TEQUILA_API_KEY = MY_API KEY
TEQUILA_ENDPOINT = "https://api.tequila.kiwi.com"

class FlightSearch:

    def get_destination_code(self, city_name):
        location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
        headers = {"apikey": TEQUILA_API_KEY}
        query = {"term": city_name, "location_types": "city"}
        response = requests.get(url=location_endpoint, headers=headers, params=query)
        results = response.json()["locations"]
        code = results[0]["code"]
        pprint(results)

Whenever I run the code, I get the code for the city in index 0, which is "CPT," followed by the following error:

Traceback (most recent call last):
  File "C:\Users\helly\PycharmProjects\day44\main.py", line 23, in <module>
    row["iataCode"] = flight_search.get_destination_code(row["city"])
  File "C:\Users\Helly\PycharmProjects\day44\flight_search.py", line 23, in get_destination_code
    code = results[0]["code"]
IndexError: list index out of range

Where is the error in this code?


问:
Open app from browser (chrome) doesnt work in some devices
Im working on a web app in Angular which has a link to open android/ios app if user has it installed.

It works on all of my devices, two android smartphones and on my colleagues devices too, but we have been reported from one person a bug which cant open the android app, showing an error message:

net::ERR_UNKNOWN_URL_SCHEME

This is the device env:

Samsung Galaxy A12
Android 12
Chrome version 108.0.5359.128

Im using this line to open the app:

```<code>window.location.replace(appName);
</code>```

Where appName is something like this:

```<code>'cdsapp://com.companyname.app/banner'
</code>```

The problem is that works in all of our devices but not in one. Do you know whats going on?

Thanks in advance

Body:
Im working on a web app in Angular which has a link to open android/ios app if user has it installed.

It works on all of my devices, two android smartphones and on my colleagues devices too, but we have been reported from one person a bug which cant open the android app, showing an error message:

net::ERR_UNKNOWN_URL_SCHEME

This is the device env:

Samsung Galaxy A12
Android 12
Chrome version 108.0.5359.128

Im using this line to open the app:

window.location.replace(appName);

Where appName is something like this:

'cdsapp://com.companyname.app/banner'

The problem is that works in all of our devices but not in one. Do you know whats going on?

Thanks in advance


问:
Foreign key get parent AND children in queryset
I have the following model:

```<code>class TopicModel(models.Model):

  topic = models.ForeignKey('self', on_delete=models.CASCADE)
  ... some more not relevant fields...
</code>```

I need to get a parent topic and its direct children in a queryset.

Currently I use it with this queryset:

```<code>TopicModel.objects.filter(
        Q(pk=10) |
        Q(topic__pk=10)
    )
</code>```

I was wondering whether I can do the same in a more simple query without using Q.

Body:
I have the following model:

class TopicModel(models.Model):

  topic = models.ForeignKey('self', on_delete=models.CASCADE)
  ... some more not relevant fields...

I need to get a parent topic and its direct children in a queryset.

Currently I use it with this queryset:

TopicModel.objects.filter(
        Q(pk=10) |
        Q(topic__pk=10)
    )

I was wondering whether I can do the same in a more simple query without using Q.


问:
magento 2 ui how to get values from grid in modal to display in a div
Below is code i use to create a form with a link that opens a modal with a customer grid, the user selects the customers and when the form is submitted the customers are sent with the posted data to the controller which all works.

What i'm struggling to work out is that once the modal is closed and customers are selected, how would i display the names of the selected customers in a div above the form? Right now they are hidden so it's not obvious what has been selected before the form is submitted:

```<code><?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">
                pillbox_textmessaging_campaigns_add_form.campaigns_add_form_data_source
            </item>
            <item name="deps" xsi:type="string">
                pillbox_textmessaging_campaigns_add_form.campaigns_add_form_data_source
            </item>
        </item>
        <item name="label" xsi:type="string" translate="true">Add New Campaign</item>
        <item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">pillbox_textmessaging_campaigns_add_form</item>
        </item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
        <item name="buttons" xsi:type="array">
            <item name="save" xsi:type="string">Pillbox\TextMessaging\Block\Adminhtml\Campaigns\Buttons\Save</item>

        </item>
    </argument>
    <dataSource name="campaigns_add_form_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Pillbox\TextMessaging\Model\Campaigns\FormDataProvider</argument>
            <argument name="name" xsi:type="string">campaigns_add_form_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="*/*/save"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
    </dataSource>

    <fieldset name="campaign_information">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="collapsible" xsi:type="boolean">false</item>
                <item name="label" xsi:type="string" translate="true">Campaign Information</item>
                <item name="sortOrder" xsi:type="number">10</item>
            </item>
        </argument>

        <modal name="customers_modal">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">

                    <item name="onCancel" xsi:type="string">
                        actionDone
                    </item>
                    <item name="options" xsi:type="array">

                        <item name="title" xsi:type="string">
                            All Customers
                        </item>
                        <item name="buttons" xsi:type="array">
                            <item name="0" xsi:type="array">
                                <item name="text" xsi:type="string">
                                    Selected
                                </item>
                                <item name="class" xsi:type="string">
                                    action-primary
                                </item>
                                <item name="actions" xsi:type="array">
                                    <item name="0" xsi:type="array">
                                        <item name="targetName" xsi:type="string">
                                            index = customer_listing
                                        </item>
                                        <item name="actionName" xsi:type="string">save</item>
                                    </item>
                                    <item name="1" xsi:type="string">
                                        closeModal
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </item>
            </argument>
            <insertListing name="customer_listing">
                <settings>
                    <dataLinks>
                        <exports>false</exports>
                        <imports>true</imports>
                    </dataLinks>
                    <autoRender>true</autoRender>
                    <selectionsProvider>
                        customer_listing.customer_listing.customer_columns.ids
                    </selectionsProvider>
                    <dataScope>customer_listing</dataScope>
                    <ns>customer_listing</ns>
                </settings>
            </insertListing>
        </modal>
        <button name="customers_button"
                component="Magento_Ui/js/form/components/button">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">
                        Select Customers
                    </item>
                    <item name="title" xsi:type="string" translate="true">
                        Customers
                    </item>
                    <item name="displayAsLink" xsi:type="boolean">true</item>
                    <item name="labelVisible" xsi:type="boolean">true</item>
                    <item name="template" xsi:type="string">
                        ui/form/components/button/container
                    </item>
                    <item name="actions" xsi:type="array">
                        <item name="0" xsi:type="array">
                            <item name="targetName" xsi:type="string">
                                pillbox_textmessaging_campaigns_add_form.pillbox_textmessaging_campaigns_add_form.campaign_information.customers_modal
                            </item>
                            <item name="actionName" xsi:type="string">
                                toggleModal
                            </item>
                        </item>
                    </item>
                </item>
            </argument>
        </button>
        <field name="name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Campaign Name</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="sortOrder" xsi:type="number">10</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>

        </field>
        <field name="message">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Message Content</item>
                    <item name="formElement" xsi:type="string">textarea</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
        <htmlContent name="sms_count_html_content">
            <argument name="block" xsi:type="object">
                Pillbox\TextMessaging\Block\Adminhtml\Shared\HtmlContent\TextFormCountHtml
            </argument>
        </htmlContent>
        <field name="ready_to_send" formElement="checkbox">
            <settings>
                <label translate="true">Ready To Send?</label>
                <tooltip>
                    <description translate="true">Check the box if you would like to send the campaign immediately.
                    </description>
                </tooltip>
            </settings>
            <formElements>
                <checkbox>
                    <settings>
                        <prefer>toggle</prefer>
                        <valueMap>
                            <map name="false" xsi:type="boolean">false</map>
                            <map name="true" xsi:type="boolean">true</map>
                        </valueMap>
                    </settings>
                </checkbox>
            </formElements>
        </field>
    </fieldset>
</form>
</code>```

Body:
Below is code i use to create a form with a link that opens a modal with a customer grid, the user selects the customers and when the form is submitted the customers are sent with the posted data to the controller which all works.

What i'm struggling to work out is that once the modal is closed and customers are selected, how would i display the names of the selected customers in a div above the form? Right now they are hidden so it's not obvious what has been selected before the form is submitted:

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">
                pillbox_textmessaging_campaigns_add_form.campaigns_add_form_data_source
            </item>
            <item name="deps" xsi:type="string">
                pillbox_textmessaging_campaigns_add_form.campaigns_add_form_data_source
            </item>
        </item>
        <item name="label" xsi:type="string" translate="true">Add New Campaign</item>
        <item name="config" xsi:type="array">
            <item name="dataScope" xsi:type="string">data</item>
            <item name="namespace" xsi:type="string">pillbox_textmessaging_campaigns_add_form</item>
        </item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
        <item name="buttons" xsi:type="array">
            <item name="save" xsi:type="string">Pillbox\TextMessaging\Block\Adminhtml\Campaigns\Buttons\Save</item>

        </item>
    </argument>
    <dataSource name="campaigns_add_form_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Pillbox\TextMessaging\Model\Campaigns\FormDataProvider</argument>
            <argument name="name" xsi:type="string">campaigns_add_form_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="*/*/save"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
    </dataSource>

    <fieldset name="campaign_information">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="collapsible" xsi:type="boolean">false</item>
                <item name="label" xsi:type="string" translate="true">Campaign Information</item>
                <item name="sortOrder" xsi:type="number">10</item>
            </item>
        </argument>

        <modal name="customers_modal">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">

                    <item name="onCancel" xsi:type="string">
                        actionDone
                    </item>
                    <item name="options" xsi:type="array">

                        <item name="title" xsi:type="string">
                            All Customers
                        </item>
                        <item name="buttons" xsi:type="array">
                            <item name="0" xsi:type="array">
                                <item name="text" xsi:type="string">
                                    Selected
                                </item>
                                <item name="class" xsi:type="string">
                                    action-primary
                                </item>
                                <item name="actions" xsi:type="array">
                                    <item name="0" xsi:type="array">
                                        <item name="targetName" xsi:type="string">
                                            index = customer_listing
                                        </item>
                                        <item name="actionName" xsi:type="string">save</item>
                                    </item>
                                    <item name="1" xsi:type="string">
                                        closeModal
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </item>
            </argument>
            <insertListing name="customer_listing">
                <settings>
                    <dataLinks>
                        <exports>false</exports>
                        <imports>true</imports>
                    </dataLinks>
                    <autoRender>true</autoRender>
                    <selectionsProvider>
                        customer_listing.customer_listing.customer_columns.ids
                    </selectionsProvider>
                    <dataScope>customer_listing</dataScope>
                    <ns>customer_listing</ns>
                </settings>
            </insertListing>
        </modal>
        <button name="customers_button"
                component="Magento_Ui/js/form/components/button">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">
                        Select Customers
                    </item>
                    <item name="title" xsi:type="string" translate="true">
                        Customers
                    </item>
                    <item name="displayAsLink" xsi:type="boolean">true</item>
                    <item name="labelVisible" xsi:type="boolean">true</item>
                    <item name="template" xsi:type="string">
                        ui/form/components/button/container
                    </item>
                    <item name="actions" xsi:type="array">
                        <item name="0" xsi:type="array">
                            <item name="targetName" xsi:type="string">
                                pillbox_textmessaging_campaigns_add_form.pillbox_textmessaging_campaigns_add_form.campaign_information.customers_modal
                            </item>
                            <item name="actionName" xsi:type="string">
                                toggleModal
                            </item>
                        </item>
                    </item>
                </item>
            </argument>
        </button>
        <field name="name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Campaign Name</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="sortOrder" xsi:type="number">10</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>

        </field>
        <field name="message">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Message Content</item>
                    <item name="formElement" xsi:type="string">textarea</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
        <htmlContent name="sms_count_html_content">
            <argument name="block" xsi:type="object">
                Pillbox\TextMessaging\Block\Adminhtml\Shared\HtmlContent\TextFormCountHtml
            </argument>
        </htmlContent>
        <field name="ready_to_send" formElement="checkbox">
            <settings>
                Ready To Send?
                <tooltip>
                    <description translate="true">Check the box if you would like to send the campaign immediately.
                    </description>
                </tooltip>
            </settings>
            <formElements>
                <checkbox>
                    <settings>
                        <prefer>toggle</prefer>
                        <valueMap>
                            <map name="false" xsi:type="boolean">false</map>
                            <map name="true" xsi:type="boolean">true</map>
                        </valueMap>
                    </settings>
                </checkbox>
            </formElements>
        </field>
    </fieldset>
</form>


问:
Linux options for a 32-bit MSI Atom
I have resurrected my MSI Atom running (from memory) 1GB of RAM and want to make use of it but not use the Windows XP that it came with. I have found many Linux distros and tried to install some but failed.
I wrote Ubuntu to a USB drive using Rufus and though I can run the Atom in Live mode I can't install it as it gets stuck at step 3/5. Steps 1 and 2 ask for geographic location and keyboard layout but it never gets to step 3 and the screen stays on the step 2/5 page. The mouse is responsive and I am able to click the menus.
I also tried a few others each time using Rufus to burn the .iso to USB. Was I correct to do that?
I'm now downloading Linux Mint and hope to get this to install again using Rufus to burn the .iso to USB.</p>

Title: Linux options for a 32-bit MSI Atom


问:
Permission popup does not show for Granular media permissions in android 13
I have upgraded project into sdk 33. My project has READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE. I have added Granular permission as per google docs. Issue is its not requesting for permission. permission popup doesn't appears. Following is my implemented code.

Androidmanifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.storagepermission">
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />

    <!-- Required to maintain app compatibility. -->
    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="32" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StoragePermission"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

MainActivity

```<code>class MainActivity : AppCompatActivity() {
    lateinit var button: Button

    private val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private val permissionsFor13 = arrayOf(
        Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO,
        Manifest.permission.READ_MEDIA_AUDIO)

    fun permissions(): Array<String>? {
        val p: Array<String>
        p = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Log.e("TAG", "permissions: permissionsFor13" )
            permissionsFor13
        } else {
            Log.e("TAG", "permissions: permission" )
            permissions
        }
        return p
    }

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private fun arePermissionsEnabled(): Boolean
    {
        for (permission in permissions()!!)
        {

            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)

                return false
        }

        return true
    }

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private fun requestMultiplePermissions()
    {
        val remainingPermissions = ArrayList<String>()
        for (permission in permissions()!!)
        {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
            {
                remainingPermissions.add(permission)
            }
        }
    }

    @RequiresApi(33)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button)

        button.setOnClickListener {
             val readImagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) Manifest.permission.READ_MEDIA_IMAGES else Manifest.permission.READ_EXTERNAL_STORAGE
            if(ContextCompat.checkSelfPermission(this, readImagePermission) == PackageManager.PERMISSION_GRANTED){
                Toast.makeText(applicationContext,"permission granted", Toast.LENGTH_LONG).show()
                arePermissionsEnabled()
            } else {
                requestMultiplePermissions()
                Toast.makeText(applicationContext,"permission Not granted", Toast.LENGTH_LONG).show()
            }
        }

    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="311dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I have upgraded project into sdk 33. My project has READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE. I have added Granular permission as per google docs. Issue is its not requesting for permission. permission popup doesn't appears. Following is my implemented code.

Androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.storagepermission">
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />

    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="32" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StoragePermission"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity

class MainActivity : AppCompatActivity() {
    lateinit var button: Button

    private val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private val permissionsFor13 = arrayOf(
        Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO,
        Manifest.permission.READ_MEDIA_AUDIO)

    fun permissions(): Array<String>? {
        val p: Array<String>
        p = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Log.e("TAG", "permissions: permissionsFor13" )
            permissionsFor13
        } else {
            Log.e("TAG", "permissions: permission" )
            permissions
        }
        return p
    }

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private fun arePermissionsEnabled(): Boolean
    {
        for (permission in permissions()!!)
        {

            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)

                return false
        }

        return true
    }

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private fun requestMultiplePermissions()
    {
        val remainingPermissions = ArrayList<String>()
        for (permission in permissions()!!)
        {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
            {
                remainingPermissions.add(permission)
            }
        }
    }

    @RequiresApi(33)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button)

        button.setOnClickListener {
             val readImagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) Manifest.permission.READ_MEDIA_IMAGES else Manifest.permission.READ_EXTERNAL_STORAGE
            if(ContextCompat.checkSelfPermission(this, readImagePermission) == PackageManager.PERMISSION_GRANTED){
                Toast.makeText(applicationContext,"permission granted", Toast.LENGTH_LONG).show()
                arePermissionsEnabled()
            } else {
                requestMultiplePermissions()
                Toast.makeText(applicationContext,"permission Not granted", Toast.LENGTH_LONG).show()
            }
        }

    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="311dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


问:
How to pass dynamic translations to forRoot
Currently I am passing an object to forRoot to provide translations like this:

```<code>@NgModule({
  declarations: [COMPONENTS, PIPES, DIRECTIVES],
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    FormsModule,
    TranslocoModule,
    NgxEditorModule.forRoot({
      locals: {
        openInNewTab: 'Open in tab',
        insert: 'Insert',
      },
    }),
  ],
  exports: [COMPONENTS, PIPES, DIRECTIVES],
})
</code>```

But what if I want to pass different object based on the current app language. I am using transloco and the user can toggle the language but I can't seem to figure how to pass dynamic values into forRoot

Body:
Currently I am passing an object to forRoot to provide translations like this:

@NgModule({
  declarations: [COMPONENTS, PIPES, DIRECTIVES],
  imports: [
    CommonModule,
    RouterModule,
    ReactiveFormsModule,
    FormsModule,
    TranslocoModule,
    NgxEditorModule.forRoot({
      locals: {
        openInNewTab: 'Open in tab',
        insert: 'Insert',
      },
    }),
  ],
  exports: [COMPONENTS, PIPES, DIRECTIVES],
})

But what if I want to pass different object based on the current app language. I am using transloco and the user can toggle the language but I can't seem to figure how to pass dynamic values into forRoot