问:
Url Action not working properly on .Net 6 (not generating link)
So i'm trying to authenticate my email in .Net 6 core application but without front end (without cshtml), only by sending email,clicking the link and changing the EmailConfirmed box on the user from false to true.
However i have some problem with generating link form Url.Action which i use to send email with the link

```<code>            var confirmationLink = Request.Scheme + "://" + Request.Host + Url.Action("ConfirmEmail", "Register",new { code = code,userId = userToAdd.Id });
            Console.WriteLine(confirmationLink);

</code>```

When i do this i get this output

and nothing else.

This is my ConfirmEmail action which the email should redirect to but when i do this i get 404 and no action from this controller is triggered.

```<code>       [HttpPost]
        [Route("ConfirmEmail/{token}/{userId}")]
        public async Task<IActionResult> EmailAuthentication([FromRoute]string token, [FromRoute]string userId) {
            var user = await _userManager.FindByIdAsync(userId);
            Console.WriteLine(user.Email);
            Console.WriteLine(user.UserName);
            Console.WriteLine(token);
            Console.WriteLine(user.EmailConfirmationToken);
            Console.WriteLine(token == user.EmailConfirmationToken);
            if(user == null)
            {
                return NotFound();
            }
            if (token == user.EmailConfirmationToken)
            {
                user.EmailConfirmed = true;
                return Ok();
            }
            return BadRequest();
        }
</code>```

And this is the email sender:

```<code>    public async Task SendEmailAsync(string toEmail, string subject, string message)
    {
        if (string.IsNullOrEmpty(Options.SendGridKey))
        {
            throw new Exception("Null SendGridKey");
        }
        await Execute(Options.SendGridKey, subject, message, toEmail);
    }

    public async Task Execute(string apiKey, string subject, string message, string toEmail)
    {
        var client = new SendGridClient(apiKey);
        var emailPass = _config["emailPassword"];
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("employmentlyy@gmail.com", "wlqegxqlkepwrguh"),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(toEmail));

        // Disable click tracking.
        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(false, false);
        var response = await client.SendEmailAsync(msg);
        _logger.LogInformation(response.IsSuccessStatusCode
                               ? $"Email to {toEmail} queued successfully!"
                               : $"Failure Email to {toEmail}");
    }
}
</code>```

Body:
So i'm trying to authenticate my email in .Net 6 core application but without front end (without cshtml), only by sending email,clicking the link and changing the EmailConfirmed box on the user from false to true.
However i have some problem with generating link form Url.Action which i use to send email with the link

            var confirmationLink = Request.Scheme + "://" + Request.Host + Url.Action("ConfirmEmail", "Register",new { code = code,userId = userToAdd.Id });
            Console.WriteLine(confirmationLink);

When i do this i get this output

and nothing else.

This is my ConfirmEmail action which the email should redirect to but when i do this i get 404 and no action from this controller is triggered.

       [HttpPost]
        [Route("ConfirmEmail/{token}/{userId}")]
        public async Task<IActionResult> EmailAuthentication([FromRoute]string token, [FromRoute]string userId) {
            var user = await _userManager.FindByIdAsync(userId);
            Console.WriteLine(user.Email);
            Console.WriteLine(user.UserName);
            Console.WriteLine(token);
            Console.WriteLine(user.EmailConfirmationToken);
            Console.WriteLine(token == user.EmailConfirmationToken);
            if(user == null)
            {
                return NotFound();
            }
            if (token == user.EmailConfirmationToken)
            {
                user.EmailConfirmed = true;
                return Ok();
            }
            return BadRequest();
        }

And this is the email sender:

    public async Task SendEmailAsync(string toEmail, string subject, string message)
    {
        if (string.IsNullOrEmpty(Options.SendGridKey))
        {
            throw new Exception("Null SendGridKey");
        }
        await Execute(Options.SendGridKey, subject, message, toEmail);
    }

    public async Task Execute(string apiKey, string subject, string message, string toEmail)
    {
        var client = new SendGridClient(apiKey);
        var emailPass = _config["emailPassword"];
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("employmentlyy@gmail.com", "wlqegxqlkepwrguh"),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(toEmail));

        // Disable click tracking.
        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(false, false);
        var response = await client.SendEmailAsync(msg);
        _logger.LogInformation(response.IsSuccessStatusCode
                               ? $"Email to {toEmail} queued successfully!"
                               : $"Failure Email to {toEmail}");
    }
}


来源: stackexchange

问:
Connect Multiple docker containers using Java Socket Programming
I have two containers connected on same network. I am able to ping containers. I am trying to share data using java socket programming. How can I connect using java and share data between containers.

Below I have attached code for client and server. Both files are running on same host machine and on the same container(ntu-vm-soft40051).HostName is the container ID to whom I have to share data and port I have mapped.

5071de43f576   22/tcp, 0.0.0.0:3390->3389/tcp   ntu-vm-soft40051
a6d4bc5dadf0   0.0.0.0:4848->22/tcp             soft40051-simple-container1

```<code>public class Client
{

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        try (Socket socket = new Socket("a6d4bc5dadf0", 22))
        {
            //InputStream input=socket.getInputStream();

            //BufferedReader reader=new BufferedReader(new InputStreamReader(input));
            //TODO add code here

            //String line;
            //System.out.println("Print received the following message:\n");

            //while((line=reader.readLine())!= null)
            {
                //System.out.println(line);
            }

        } catch (UnknownHostException ex) {

            System.out.println("Server not found: " + ex.getMessage());

        } catch (IOException ex) {

            System.out.println("I/O error: " + ex.getMessage());
        }
    }
}

</code>```
```<code>public class Server {

    //socket server port on which it will listen

    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        int port = 22;
        try (ServerSocket serverSocket = new ServerSocket(port))
        {

            while (true)
            {

                //ServerSocket serversoc=new ServerSocket(port);
                Socket socket=serverSocket.accept();
                //System.out.println("Hi");
                System.out.println("New Client is connected");

                //OutputStream output= socket.getOutputStream();

                //PrintWriter writer=new PrintWriter(output, true);
                //writer.println("Hello this is a message sent by the server!");
                //writer.println("This is second string sent by server");
                //writer.println("Third string");
                //writer.println(new Date().toString());
            }

        } catch (IOException ex) {
            System.out.println("Server exception: " + ex.getMessage());
            ex.printStackTrace();
        }

    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two containers connected on same network. I am able to ping containers. I am trying to share data using java socket programming. How can I connect using java and share data between containers.

Below I have attached code for client and server. Both files are running on same host machine and on the same container(ntu-vm-soft40051).HostName is the container ID to whom I have to share data and port I have mapped.

5071de43f576   22/tcp, 0.0.0.0:3390->3389/tcp   ntu-vm-soft40051
a6d4bc5dadf0   0.0.0.0:4848->22/tcp             soft40051-simple-container1

public class Client
{

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        try (Socket socket = new Socket("a6d4bc5dadf0", 22))
        {
            //InputStream input=socket.getInputStream();

            //BufferedReader reader=new BufferedReader(new InputStreamReader(input));
            //TODO add code here

            //String line;
            //System.out.println("Print received the following message:\n");

            //while((line=reader.readLine())!= null)
            {
                //System.out.println(line);
            }

        } catch (UnknownHostException ex) {

            System.out.println("Server not found: " + ex.getMessage());

        } catch (IOException ex) {

            System.out.println("I/O error: " + ex.getMessage());
        }
    }
}

public class Server {

    //socket server port on which it will listen

    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        int port = 22;
        try (ServerSocket serverSocket = new ServerSocket(port))
        {

            while (true)
            {

                //ServerSocket serversoc=new ServerSocket(port);
                Socket socket=serverSocket.accept();
                //System.out.println("Hi");
                System.out.println("New Client is connected");

                //OutputStream output= socket.getOutputStream();

                //PrintWriter writer=new PrintWriter(output, true);
                //writer.println("Hello this is a message sent by the server!");
                //writer.println("This is second string sent by server");
                //writer.println("Third string");
                //writer.println(new Date().toString());
            }

        } catch (IOException ex) {
            System.out.println("Server exception: " + ex.getMessage());
            ex.printStackTrace();
        }

    }

}


问:
Running Keypirinha plugin code got error: ModuleNotFoundError: No module named 'keypirinha_api'
I'm getting "ModuleNotFoundError: No module named 'keypirinha_api'" (inside Keyprinha.py file, "import keypirinha_api" command)

when I trying to run sample plugin file that imports "import keypirinha as kp".

Here's plugin sample I got error in the very beginning:
https://github.com/Keypirinha/SDK/blob/master/examples/YesNo/yesno.py

*I downloaded the sdk from here:
https://github.com/Keypirinha/SDK

** Pip install doesn't find Keypirinha

What I'm doing wrong?

Thanks

```<code>
# Keypirinha launcher (keypirinha.com)

import keypirinha as kp

import keypirinha_util as kpu

from collections import namedtuple

import datetime

import os

AnswerTuple = namedtuple('AnswerTuple', ('value', 'datetime'))

class YesNo(kp.Plugin):

    """A simple "Yes or No" plugin"""

    ITEMCAT_RESULT = kp.ItemCategory.USER_BASE + 1

    history = []

    def __init__(self):

        super().__init__()

    def on_start(self):

        self.history = []

        self.set_actions(self.ITEMCAT_RESULT, [

            self.create_action(

                name="copy",

                label="Copy",

                short_desc="Copy the name of the answer")])

    def on_catalog(self):

        self.set_catalog([self.create_item(

            category=kp.ItemCategory.KEYWORD,

            label="YesNo",

            short_desc="Yes or No",

            target="yesno",

            args_hint=kp.ItemArgsHint.REQUIRED,

            hit_hint=kp.ItemHitHint.NOARGS)])

    def on_suggest(self, user_input, items_chain):

        if not items_chain or items_chain[-1].category() != kp.ItemCategory.KEYWORD:

            return

        if not user_input:

            self.history = []

        # compute a new answer

        self.history.append(AnswerTuple(

            os.urandom(1)[0] % 2,

            datetime.datetime.now()))

        # suggest this new answer as well as the previous ones

        suggestions = []

        for idx in range(len(self.history) - 1, -1, -1):

            answer = self.history[idx]

            desc = "{}. {} (press Enter to copy)".format(

                idx + 1, answer.datetime.strftime("%H:%M:%S"))

            suggestions.append(self.create_item(

                category=self.ITEMCAT_RESULT,

                label=self._value_to_string(answer.value),

                short_desc=desc,

                target="{},{}".format(answer.value, idx),

                args_hint=kp.ItemArgsHint.FORBIDDEN,

                hit_hint=kp.ItemHitHint.IGNORE))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)

    def on_execute(self, item, action):

        if item and item.category() == self.ITEMCAT_RESULT:

            value = int(item.target().split(',', maxsplit=1)[0])

            kpu.set_clipboard(self._value_to_string(value))

    def _value_to_string(self, value):

        return "Yes" if value else "No"
</code>```

Body:
I'm getting "ModuleNotFoundError: No module named 'keypirinha_api'" (inside Keyprinha.py file, "import keypirinha_api" command)

when I trying to run sample plugin file that imports "import keypirinha as kp".

Here's plugin sample I got error in the very beginning:
https://github.com/Keypirinha/SDK/blob/master/examples/YesNo/yesno.py

*I downloaded the sdk from here:
https://github.com/Keypirinha/SDK

** Pip install doesn't find Keypirinha

What I'm doing wrong?

Thanks

# Keypirinha launcher (keypirinha.com)

import keypirinha as kp

import keypirinha_util as kpu

from collections import namedtuple

import datetime

import os

AnswerTuple = namedtuple('AnswerTuple', ('value', 'datetime'))

class YesNo(kp.Plugin):

    """A simple "Yes or No" plugin"""

    ITEMCAT_RESULT = kp.ItemCategory.USER_BASE + 1

    history = []

    def __init__(self):

        super().__init__()

    def on_start(self):

        self.history = []

        self.set_actions(self.ITEMCAT_RESULT, [

            self.create_action(

                name="copy",

                label="Copy",

                short_desc="Copy the name of the answer")])

    def on_catalog(self):

        self.set_catalog([self.create_item(

            category=kp.ItemCategory.KEYWORD,

            label="YesNo",

            short_desc="Yes or No",

            target="yesno",

            args_hint=kp.ItemArgsHint.REQUIRED,

            hit_hint=kp.ItemHitHint.NOARGS)])

    def on_suggest(self, user_input, items_chain):

        if not items_chain or items_chain[-1].category() != kp.ItemCategory.KEYWORD:

            return

        if not user_input:

            self.history = []

        # compute a new answer

        self.history.append(AnswerTuple(

            os.urandom(1)[0] % 2,

            datetime.datetime.now()))

        # suggest this new answer as well as the previous ones

        suggestions = []

        for idx in range(len(self.history) - 1, -1, -1):

            answer = self.history[idx]

            desc = "{}. {} (press Enter to copy)".format(

                idx + 1, answer.datetime.strftime("%H:%M:%S"))

            suggestions.append(self.create_item(

                category=self.ITEMCAT_RESULT,

                label=self._value_to_string(answer.value),

                short_desc=desc,

                target="{},{}".format(answer.value, idx),

                args_hint=kp.ItemArgsHint.FORBIDDEN,

                hit_hint=kp.ItemHitHint.IGNORE))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)

    def on_execute(self, item, action):

        if item and item.category() == self.ITEMCAT_RESULT:

            value = int(item.target().split(',', maxsplit=1)[0])

            kpu.set_clipboard(self._value_to_string(value))

    def _value_to_string(self, value):

        return "Yes" if value else "No"


问:
Vue.js ailed to resolve component: b-button
I want to make a modal using bootstrap in vue.js.

I got the warning error

'[Vue warn]: Failed to resolve component: b-button' and here is my code

<template>

    Open Modal
    Toggle Modal

Hello From My Modal!

      Close Me
      Toggle Me

</template>

```

i try to solve my problem by looking for the answer from their website bootstrap-vue.org but still it did not work on my project.

Body:
I want to make a modal using bootstrap in vue.js.

I got the warning error

'[Vue warn]: Failed to resolve component: b-button' and here is my code

<template>

    Open Modal
    Toggle Modal

Hello From My Modal!

      Close Me
      Toggle Me

</template>

i try to solve my problem by looking for the answer from their website bootstrap-vue.org but still it did not work on my project.


问:
How to snooze An alarm clock in javascript?
I've been working on an alarm clock 'app' project to practice JavaScript. I'm fairly new to it so maybe I'm just not understanding clearInterval() correctly, and I was hoping someone could help.

JavaScript:

```<code>// Global variables and objects //

const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var timer =[];
var i = 0;

var alarms_ul = document.getElementById('alarms_ul');

// Display clock function //
let displayClock = () => {
    let today = new Date();
    let hours = today.getHours();
    let minutes = today.getMinutes();
    let seconds = today.getSeconds();
    let format = hours < 12 ?"A.M" :'P.M';
    let clock = document.getElementById('clock');
    let currentHour = hours < 10 ? '0' + hours : hours ;
    //Insert current time to the clock div as innerHTML
    clock.innerHTML = `
    ${hours > 12 ? hours - 12 : currentHour }
    : ${minutes < 10 ? '0' + minutes : minutes}
    : ${seconds < 10 ? '0' + seconds : seconds}
    : ${format}
    `;
    //create a setTimeout to call displayClock function for Working Clock Display
    setTimeout(displayClock,1000);
}

let setAlarm = () => {
    let alarmsInput = document.getElementById('alarm_input');
    let alarm = alarmsInput.value;
    alarmsInput.value="";
    if(alarm!==""){
        let curr_time = new Date();
        //create alarm_time object
        let alarm_time = new Date(alarm);
        let duration = alarm_time - curr_time ;
        if(duration < 0){
            alert('Time has already passed');
        }else{
            displayAlarms(alarm_time);
            // console.log("remaining time in seconds",duration/1000);
            timer[i++] = setTimeout(() => {
            alert('Times up');
            //console.log("Alarm Deleted");
             // remove the alarm from dom
            // document.getElementById(alarm_time).remove();
             i--;

            },duration);

        }
    }else{
        alert('Select Alarm Time !!!')
    }

}

// Display Alarm List //
let displayAlarms = (time) => {

    //clear alarms_ul innerHTml to avoid already append duplicated lists every time a new alarm is added
    // create necessary variables for every alarm_time object in the array ...
    let alarmTime = time;
    let hours = alarmTime.getHours();
    let minutes = alarmTime.getMinutes();
    let seconds = alarmTime.getSeconds();
    let format = hours <12 ?"A.M" :'P.M';
    //create newLi tag to append to the alarms List
    let newLi = document.createElement('li');
    newLi.className = "alarms-li";
    newLi.id=  time;
    newLi.innerHTML = `
    <span class="fa-li"><i class="fas fa-bell fa-2x"></i></span>
    ${months[alarmTime.getMonth()]}
    ${alarmTime.getDate()}
    @
    ${hours % 12 < 10 ? ("0" + (hours % 12)): (hours % 12)}:
    ${minutes<10 ? "0"+ minutes : minutes }:
    ${seconds<10 ? "0"+ seconds : seconds }:
    ${format}

    <button  type="submit" onClick=snoozeAlarm() class='snoozeAlarm button'>Snooze</button>

    <button  type="submit" onClick={deleteAlarm(${i})} class='deleteAlarm button'>Delete</button>
    `;
    alarms_ul.appendChild(newLi);
}

//Delete Alarm function
let deleteAlarm = (index)=> {

    clearInterval(timer[index]);

}
function snooze() {
    setInterval(5*60000);
    alert("Snoozed for 5 minutes");
}
function snoozeAlarm(el){
    // console.log(el);
    if(el.classList.contains('snoozeAlarm')){
      el.parentElement.snooze();
    }

}

function removeAlarm(el){
    // console.log(el);
    if(el.classList.contains('deleteAlarm')){
      el.parentElement.remove();
    }

}
        //  Handle Events //

//Handle DisplayClock
document.addEventListener('DOMContentLoaded ',displayClock());

//handle Add Alarm
document.querySelector('#submit_alarm_time').addEventListener('click',(e)=>{
    e.preventDefault();
    //Call setAlarm function
    setAlarm();
});
document.getElementById('alarms_ul').addEventListener('click',(e)=>{

    snoozeAlarm(e.target);
})

//handle delete alarm event for removing the li from the list
document.getElementById('alarms_ul').addEventListener('click',(e)=>{

    removeAlarm(e.target);
})

</code>```

`I'm trying to add a snooze button functionality and I can't seem to get it working no matter what I try.

Any tips and tricks are greatly appreciated! Sorry if the code is messy, like I said, I just started with JS.`

Body:
I've been working on an alarm clock 'app' project to practice JavaScript. I'm fairly new to it so maybe I'm just not understanding clearInterval() correctly, and I was hoping someone could help.

JavaScript:

// Global variables and objects //

const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var timer =[];
var i = 0;

var alarms_ul = document.getElementById('alarms_ul');

// Display clock function //
let displayClock = () => {
    let today = new Date();
    let hours = today.getHours();
    let minutes = today.getMinutes();
    let seconds = today.getSeconds();
    let format = hours < 12 ?"A.M" :'P.M';
    let clock = document.getElementById('clock');
    let currentHour = hours < 10 ? '0' + hours : hours ;
    //Insert current time to the clock div as innerHTML
    clock.innerHTML = `
    ${hours > 12 ? hours - 12 : currentHour }
    : ${minutes < 10 ? '0' + minutes : minutes}
    : ${seconds < 10 ? '0' + seconds : seconds}
    : ${format}
    `;
    //create a setTimeout to call displayClock function for Working Clock Display
    setTimeout(displayClock,1000);
}

let setAlarm = () => {
    let alarmsInput = document.getElementById('alarm_input');
    let alarm = alarmsInput.value;
    alarmsInput.value="";
    if(alarm!==""){
        let curr_time = new Date();
        //create alarm_time object
        let alarm_time = new Date(alarm);
        let duration = alarm_time - curr_time ;
        if(duration < 0){
            alert('Time has already passed');
        }else{
            displayAlarms(alarm_time);
            // console.log("remaining time in seconds",duration/1000);
            timer[i++] = setTimeout(() => {
            alert('Times up');
            //console.log("Alarm Deleted");
             // remove the alarm from dom
            // document.getElementById(alarm_time).remove();
             i--;

            },duration);

        }
    }else{
        alert('Select Alarm Time !!!')
    }

}

// Display Alarm List //
let displayAlarms = (time) => {

    //clear alarms_ul innerHTml to avoid already append duplicated lists every time a new alarm is added
    // create necessary variables for every alarm_time object in the array ...
    let alarmTime = time;
    let hours = alarmTime.getHours();
    let minutes = alarmTime.getMinutes();
    let seconds = alarmTime.getSeconds();
    let format = hours <12 ?"A.M" :'P.M';
    //create newLi tag to append to the alarms List
    let newLi = document.createElement('li');
    newLi.className = "alarms-li";
    newLi.id=  time;
    newLi.innerHTML = `

    ${months[alarmTime.getMonth()]}
    ${alarmTime.getDate()}
    @
    ${hours % 12 < 10 ? ("0" + (hours % 12)): (hours % 12)}:
    ${minutes<10 ? "0"+ minutes : minutes }:
    ${seconds<10 ? "0"+ seconds : seconds }:
    ${format}

    <button  type="submit" onClick=snoozeAlarm() class='snoozeAlarm button'>Snooze</button>

    <button  type="submit" onClick={deleteAlarm(${i})} class='deleteAlarm button'>Delete</button>
    `;
    alarms_ul.appendChild(newLi);
}

//Delete Alarm function
let deleteAlarm = (index)=> {

    clearInterval(timer[index]);

}
function snooze() {
    setInterval(5*60000);
    alert("Snoozed for 5 minutes");
}
function snoozeAlarm(el){
    // console.log(el);
    if(el.classList.contains('snoozeAlarm')){
      el.parentElement.snooze();
    }

}

function removeAlarm(el){
    // console.log(el);
    if(el.classList.contains('deleteAlarm')){
      el.parentElement.remove();
    }

}
        //  Handle Events //

//Handle DisplayClock
document.addEventListener('DOMContentLoaded ',displayClock());

//handle Add Alarm
document.querySelector('#submit_alarm_time').addEventListener('click',(e)=>{
    e.preventDefault();
    //Call setAlarm function
    setAlarm();
});
document.getElementById('alarms_ul').addEventListener('click',(e)=>{

    snoozeAlarm(e.target);
})

//handle delete alarm event for removing the li from the list
document.getElementById('alarms_ul').addEventListener('click',(e)=>{

    removeAlarm(e.target);
})

`I'm trying to add a snooze button functionality and I can't seem to get it working no matter what I try.

Any tips and tricks are greatly appreciated! Sorry if the code is messy, like I said, I just started with JS.`


问:
My React native app crashes in android device after installing, Iam building using eas build
Iam using eas build -p android, but when I install an app on android device it crashes after splash screenApp crash on physical device

Iam expecting to get solution on that please...


问:
Struscture of MongoDB with too many collections
I'm realy new in MongoDB and have a qustion.
I'm planing to build a base with too many collections (few hundreds). Each collection consist of documents with different strusture. For example collections have documents like this:

```<code>First Collection:
{ "name": "Tom", "surname": "Smith", "age": "37", "phone": "123"}

Second Collection:
{"company": "Example LTD", "phone":"456"}

Third Collection:
{"phone": "123", "email": "tom@example.com"}
</code>```

I want to implement a search for a specific phone number across all collections. Does it make sense in terms of performance to create a metacollection that would contain all phone numbers from all collections? Like this:

```<code>Metacollection with phones:
{"123": ["First Collection", "Third Collection"]}
{"456": "Second Collection"}
</code>```

I believe that searching the metacollection and then specific collections should be faster than searching hundreds of collections for a specific phone number. Is my guess correct?

Body:
I'm realy new in MongoDB and have a qustion.
I'm planing to build a base with too many collections (few hundreds). Each collection consist of documents with different strusture. For example collections have documents like this:

First Collection:
{ "name": "Tom", "surname": "Smith", "age": "37", "phone": "123"}

Second Collection:
{"company": "Example LTD", "phone":"456"}

Third Collection:
{"phone": "123", "email": "tom@example.com"}

I want to implement a search for a specific phone number across all collections. Does it make sense in terms of performance to create a metacollection that would contain all phone numbers from all collections? Like this:

Metacollection with phones:
{"123": ["First Collection", "Third Collection"]}
{"456": "Second Collection"}

I believe that searching the metacollection and then specific collections should be faster than searching hundreds of collections for a specific phone number. Is my guess correct?


问:
Integrating google ads outbound requests configuration react-native
I am trying to integrate React Native Google Mobile Ads into my project and I am not sure where the  European user consent should and outbound request configuration should go. For example, how should I integrate this outbound code to my app.js
Full documation
Outbound

import mobileAds, { MaxAdContentRating } from 'react-native-google-mobile-ads';

mobileAds()
  .setRequestConfiguration({
    // Update all future requests suitable for parental guidance
    maxAdContentRating: MaxAdContentRating.PG,

    // Indicates that you want your content treated as child-directed for purposes of COPPA.
    tagForChildDirectedTreatment: true,

    // Indicates that you want the ad request to be handled in a
    // manner suitable for users under the age of consent.
    tagForUnderAgeOfConsent: true,

    // An array of test device IDs to allow.
    testDeviceIdentifiers: ['EMULATOR'],
  })
  .then(() => {
    // Request config successfully set!
  });```
</div>
</div>
</p>
```app.js
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, {useState, useEffect} from 'react';
import {
  SafeAreaView,
  Text, Button
} from 'react-native';
import { BannerAd, BannerAdSize,InterstitialAd, AdEventType, TestIds } from 'react-native-google-mobile-ads';

export default function App() {

  return(
    <SafeAreaView>
      <BannerAd
      unitId={adUnitId}
      size={BannerAdSize.FULL_BANNER}
      requestOptions={{
        requestNonPersonalizedAdsOnly: true,
      }}
    />
     <Text>Hello World</Text>
    />
    </SafeAreaView>
  )
}</code>```

Body:
I am trying to integrate React Native Google Mobile Ads into my project and I am not sure where the  European user consent should and outbound request configuration should go. For example, how should I integrate this outbound code to my app.js
Full documation
Outbound

import mobileAds, { MaxAdContentRating } from 'react-native-google-mobile-ads';

mobileAds()
  .setRequestConfiguration({
    // Update all future requests suitable for parental guidance
    maxAdContentRating: MaxAdContentRating.PG,

    // Indicates that you want your content treated as child-directed for purposes of COPPA.
    tagForChildDirectedTreatment: true,

    // Indicates that you want the ad request to be handled in a
    // manner suitable for users under the age of consent.
    tagForUnderAgeOfConsent: true,

    // An array of test device IDs to allow.
    testDeviceIdentifiers: ['EMULATOR'],
  })
  .then(() => {
    // Request config successfully set!
  });

app.js

import React, {useState, useEffect} from 'react';
import {
  SafeAreaView,
  Text, Button
} from 'react-native';
import { BannerAd, BannerAdSize,InterstitialAd, AdEventType, TestIds } from 'react-native-google-mobile-ads';

export default function App() {

  return(
    <SafeAreaView>
      <BannerAd
      unitId={adUnitId}
      size={BannerAdSize.FULL_BANNER}
      requestOptions={{
        requestNonPersonalizedAdsOnly: true,
      }}
    />
     <Text>Hello World</Text>
    />
    </SafeAreaView>
  )
}


问:
NestJS not getting file data from angular
So, when i make a request to the api to upload a file, then the file is undefined, but in angular its not undefined

Heres my code:

Angular HTML

```<code>          <label *ngIf="newPfpPreviewSRC == ''" for="newpfpinput">{{'selectpic'|translate}}</label>
          <input #newPFP (change)="getPfpPreview($event)" type="file" id="newpfpinput" hidden /><br />
<button (click)="pfpYES()" mat-raised-button>{{'yes'|translate}}</button>
</code>```

Angular component.ts

```<code>  newPfpPreviewSRC: any = '';
  pfpData: any = '';
  getPfpPreview(event: any) {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];

      this.pfpData = event.target.files[0];

      const reader = new FileReader();
      reader.onload = (e) => (this.newPfpPreviewSRC = reader.result);

      reader.readAsDataURL(file);
    }
  }
  async pfpYES() {
    console.log(this.pfpData)
    this.http
      .post(`http://localhost:3000/api/user/newpfp`, {
        userid: this.userid,
        pfp: await this.pfpData
      })
      .subscribe((response) => {
        console.log(response);
      });
  }
</code>```

NestJS

```<code>    @Post("newpfp")
    @UseInterceptors(FileInterceptor('file'))
    newPfp(@Body() uploadpfpdto: UploadPFPDto){
        console.log(uploadpfpdto)
    }
</code>```

Can you help me? Thanks!

Body:
So, when i make a request to the api to upload a file, then the file is undefined, but in angular its not undefined

Heres my code:

Angular HTML

          {{'selectpic'|translate}}
          <input #newPFP (change)="getPfpPreview($event)" type="file" id="newpfpinput" hidden />

<button (click)="pfpYES()" mat-raised-button>{{'yes'|translate}}</button>

Angular component.ts

  newPfpPreviewSRC: any = '';
  pfpData: any = '';
  getPfpPreview(event: any) {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];

      this.pfpData = event.target.files[0];

      const reader = new FileReader();
      reader.onload = (e) => (this.newPfpPreviewSRC = reader.result);

      reader.readAsDataURL(file);
    }
  }
  async pfpYES() {
    console.log(this.pfpData)
    this.http
      .post(`http://localhost:3000/api/user/newpfp`, {
        userid: this.userid,
        pfp: await this.pfpData
      })
      .subscribe((response) => {
        console.log(response);
      });
  }

NestJS

    @Post("newpfp")
    @UseInterceptors(FileInterceptor('file'))
    newPfp(@Body() uploadpfpdto: UploadPFPDto){
        console.log(uploadpfpdto)
    }

Can you help me? Thanks!


问:
Trimmed values while parsing XML file
I need your help to sort my problem out, coding with Swift on XCode 14.1 :

When trying to parse an XML file, I noticed that most of values are not trimmed and appears in the XML file with some trailing spaces such as name="ABC     " and number of spaces is not always the same. It's randomely from 3 to 6 or 7 spaces.

For example, when I execute the following code :

```<code>let subIndexer = xml["Objects"]["Points"]["Point"]
.filterAll { elem, _ in elem.attribute(by: "name")!.text  == "ABC" }
</code>```

...it doesn't find my element of course as it's "ABC           " in the XML.
How can I do ?

I thank you in advance !

Title: Trimmed values while parsing XML file

Body:
I need your help to sort my problem out, coding with Swift on XCode 14.1 :

When trying to parse an XML file, I noticed that most of values are not trimmed and appears in the XML file with some trailing spaces such as name="ABC     " and number of spaces is not always the same. It's randomely from 3 to 6 or 7 spaces.

For example, when I execute the following code :

let subIndexer = xml["Objects"]["Points"]["Point"]
.filterAll { elem, _ in elem.attribute(by: "name")!.text  == "ABC" }

...it doesn't find my element of course as it's "ABC           " in the XML.
How can I do ?

I thank you in advance !


问:
Is 'signingConfig' ignored when generating app-bundles?
I am still relatively new to Android development using Android Studio.

I understand there are three common scenarios when designing an Android application:

everyday debugging (using 'Debug' variant): no special configuration is needed in the build.gradle file. The application can be debugged right away, out of the box. No signingConfig declaration is required, the default gradle file can be used. Somehow, Android Studio takes care of everything by signing the app under the hood.

testing the 'Release' variant: the application MUST be signed explicitly to run on the device.

The following can be specified in build.gradle to assign the debug-variant signing file to the release variant:

```<code>buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.debug // this line
    }
}
</code>```

Once this is done, the Release variant can be run (and tested) on the device.

App-bundle (.aab) deployment to the Google Play Store (in my case).

Although I am obviously using the release variant for deployment, I noticed that the signingConfig line highlighted above does not need to be present in the gradle.file when doing Build > Generate Signed Bundle / APK... and then typing my keystore's passwords. The AAB file generation works with or without this line.

My questions are:

is this line really ignored during AAB generation? I don't want to have my AAB generated with a debug signature! Can I safely keep it uncommented in my gradle file? So as to be able to test my Release variant on a regular basis on the device before deploying.

is it useful to sign my Release variant in my build.gradle file with any other certificate than signingConfigs.debug, such as something derived from my upload-keystores.jks file, that I already created?

Body:
I am still relatively new to Android development using Android Studio.

I understand there are three common scenarios when designing an Android application:

everyday debugging (using 'Debug' variant): no special configuration is needed in the build.gradle file. The application can be debugged right away, out of the box. No signingConfig declaration is required, the default gradle file can be used. Somehow, Android Studio takes care of everything by signing the app under the hood.

testing the 'Release' variant: the application MUST be signed explicitly to run on the device.

The following can be specified in build.gradle to assign the debug-variant signing file to the release variant:

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.debug // this line
    }
}

Once this is done, the Release variant can be run (and tested) on the device.

App-bundle (.aab) deployment to the Google Play Store (in my case).

Although I am obviously using the release variant for deployment, I noticed that the signingConfig line highlighted above does not need to be present in the gradle.file when doing Build > Generate Signed Bundle / APK... and then typing my keystore's passwords. The AAB file generation works with or without this line.

My questions are:

is this line really ignored during AAB generation? I don't want to have my AAB generated with a debug signature! Can I safely keep it uncommented in my gradle file? So as to be able to test my Release variant on a regular basis on the device before deploying.

is it useful to sign my Release variant in my build.gradle file with any other certificate than signingConfigs.debug, such as something derived from my upload-keystores.jks file, that I already created?


问:
Evaluate Casbin policies real-time
I use Casbin as authorization library for my REST API, written in Go.

To load the policy from my Mongo database, I use MongoDB Adapter.

A single policy Mongo document looks like this:

{
  "_id": {
    "$oid": "639491f73e4c9bec05a1d1ec"
  },
  "ptype": "p",
  "v0": "admin",
  "v1": "laptops",
  "v2": "read",
  "v3": "",
  "v4": "",
  "v5": ""
}
```
<p>In my business logic, I validate if the user can access (read) laptops:</p>
<pre class="lang-golang prettyprint-override"><code>// Resolves to true
if can, _ := e.Enforce(user, "laptops", "read"); can {
    ...
</code>```

This works fine.

The problem now is when I delete the policy document, I would expect that I'm not allowed to access laptops anymore. This is only the case when I restart my application.

Thus, it appears that the Enforce checks are not being evaluated real-time.

As a workaround, I could call the LoadPolicy method as soon as the request comes in but this looks like a dirty hack to me.

I would really appreciate some help / suggestions.

Title: Evaluate Casbin policies real-time

Body:
I use Casbin as authorization library for my REST API, written in Go.

To load the policy from my Mongo database, I use MongoDB Adapter.

A single policy Mongo document looks like this:

{
  "_id": {
    "$oid": "639491f73e4c9bec05a1d1ec"
  },
  "ptype": "p",
  "v0": "admin",
  "v1": "laptops",
  "v2": "read",
  "v3": "",
  "v4": "",
  "v5": ""
}

In my business logic, I validate if the user can access (read) laptops:

// Resolves to true
if can, _ := e.Enforce(user, "laptops", "read"); can {
    ...

This works fine.

The problem now is when I delete the policy document, I would expect that I'm not allowed to access laptops anymore. This is only the case when I restart my application.

Thus, it appears that the Enforce checks are not being evaluated real-time.

As a workaround, I could call the LoadPolicy method as soon as the request comes in but this looks like a dirty hack to me.

I would really appreciate some help / suggestions.


问:
I can't access search parameter values that start with '#'
I'm trying to access my search parameters. I can access the value of my name key but I can't seem to access the value of my value key. I think it has something to do with the hash # at the begining.

Here is my URL

http://localhost:3000/all/?name=Color&value=#03FFF7

```<code>const queryString = window.location.search
      if (queryString) {
        const urlParams = new URLSearchParams(queryString)
        const name = urlParams.get('name')
        const value = urlParams.get('value')
        console.log(`This is the ${value}`)
        this.setState({ name, nameValue: value })
      }
</code>```

Body:
I'm trying to access my search parameters. I can access the value of my name key but I can't seem to access the value of my value key. I think it has something to do with the hash # at the begining.

Here is my URL

http://localhost:3000/all/?name=Color&value=#03FFF7

const queryString = window.location.search
      if (queryString) {
        const urlParams = new URLSearchParams(queryString)
        const name = urlParams.get('name')
        const value = urlParams.get('value')
        console.log(`This is the ${value}`)
        this.setState({ name, nameValue: value })
      }


问:
why console.dir(add); not showing scope variable? Windows 7
```<code>const add = (function () {let counter = 0; return function () {counter += 1; return counter}}) ();
</code>```

In windows 7 chrome console when i console.dir variable 'add' it does not show scope in it but in windows 10 it shows. why?

Body:
const add = (function () {let counter = 0; return function () {counter += 1; return counter}}) ();

In windows 7 chrome console when i console.dir variable 'add' it does not show scope in it but in windows 10 it shows. why?


问:
How to change a specific div using the same class without altering other elements related?
I'm pretty new to web development and I'm trying to learn css. I'm actually facing a layout issue. I would like to change the size of specific buttons on my page which is using the same div class. This class is related to variations for my products. Here I have two variations "size" and "color" I would like my label "size" to have a minimum width of 100% but I want to keep the actual size for "color" buttons.

After inspecting, I managed to change the size of a specific label but if I copy this element and change the css code into wordpress, this will affect every variation.

This is very basic knowledge but I really don't know what could be the right syntax to add.

Thanks a lot for your help.

```<code>.cfvsw-swatches-option cfvsw-label-option, .collector, .COLLECTOR - 42 x 30 cm - 149 €,
{
    min-width: 100%;
}
</code>```

Body:
I'm pretty new to web development and I'm trying to learn css. I'm actually facing a layout issue. I would like to change the size of specific buttons on my page which is using the same div class. This class is related to variations for my products. Here I have two variations "size" and "color" I would like my label "size" to have a minimum width of 100% but I want to keep the actual size for "color" buttons.

After inspecting, I managed to change the size of a specific label but if I copy this element and change the css code into wordpress, this will affect every variation.

This is very basic knowledge but I really don't know what could be the right syntax to add.

Thanks a lot for your help.

.cfvsw-swatches-option cfvsw-label-option, .collector, .COLLECTOR - 42 x 30 cm - 149 €,
{
    min-width: 100%;
}


问:
How to convert List<List<List<Int>>> into Bitmap object in Android Kotlin?
I have a data class (generated using JSON to Kotlin Data Class plugin) below that is used to parse json data from an object detection server. The server returns the "images" in multidimensional array. I am wondering how can I convert this JSON data in format that can be displayed in my ImageView in Kotlin.

Data Class

JSON Response

Your answers will be highly appreciated. Thankss!

Currently, I have this code that transform the images array into a bitmap. However, no image was being displayed in my ImageView.

Current Code


问:
How to pass a variable number of arguments with different types to ASP.NET Core Web API
Let's say we have two entities both of which have keys with different number of properties and types (mapped to a database using EF Core)

```<code>class Order
{
    [Key] int ProductId
    [Key] datetime OrderTime
}

class Product
{
    [Key] int Id
    string Name
}
</code>```

Is it possible to make a controller action method that takes a variable number of arguments with different types like the "params" c# keyword

```<code>[HttpDelete]
public Task<ActionResult> DeleteItem(params object?[] key)
{
    _repository.DeleteItem(key);
    return NoContent();
}
</code>```

If so, how do I send the arguments using an HttpClient, something like

```<code>var query = "?productid=0&ordertime=2022-12-10 10:15"
_httpClient.DeleteAsync(query);

var query = "?id=0"
_httpClient.DeleteAsync(query);
</code>```

Thank you.

Body:
Let's say we have two entities both of which have keys with different number of properties and types (mapped to a database using EF Core)

class Order
{
    [Key] int ProductId
    [Key] datetime OrderTime
}

class Product
{
    [Key] int Id
    string Name
}

Is it possible to make a controller action method that takes a variable number of arguments with different types like the "params" c# keyword

[HttpDelete]
public Task<ActionResult> DeleteItem(params object?[] key)
{
    _repository.DeleteItem(key);
    return NoContent();
}

If so, how do I send the arguments using an HttpClient, something like

var query = "?productid=0&ordertime=2022-12-10 10:15"
_httpClient.DeleteAsync(query);

var query = "?id=0"
_httpClient.DeleteAsync(query);

Thank you.


问:
How to track Mux Live Stream Data in Flutter
I'm struggling to make my video player track data inside Mux. I'm currently using FlutterFlow (no-code Flutter app builder) and have successfully implemented the live streaming feature, but would love to be able to track video and user data. I have also integrated this player https://pub.dev/packages/mux_player but since it's html, it uses core html features in mobile where it goes fullscreen when playing and doesn't autoplay (building a social app like TikTok/Instagram where you scroll). I'd like it to simply play when loaded and not go fullscreen.

Any advice is very much appreciated!

```<code>import '../../backend/backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import '../widgets/index.dart'; // Imports other custom widgets
import '../actions/index.dart'; // Imports custom actions
import '../../flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';

import 'package:webviewx/webviewx.dart';

class MuxPlayer extends StatefulWidget {
  const MuxPlayer(
      {Key? key, this.width, this.height, required this.playbackId})
      : super(key: key);

  final double? width;
  final double? height;
  final String playbackId;

  @override
  _MuxPlayerState createState() => _MuxPlayerState();
}

class _MuxPlayerState extends State<MuxPlayer> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.cyan,
      ),
      home: VideoScreen(pbId: widget.playbackId),
    );
  }
}

class VideoScreen extends StatelessWidget {
  final String pbId;

  const VideoScreen({Key? key, required this.pbId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Html5Player(
        playbackId: pbId,
      ),
    );
  }
}

//

class Html5Player extends StatefulWidget {
  const Html5Player({
    this.height = double.maxFinite,
    this.width = double.maxFinite,
    required this.playbackId,
    this.streamType,
    this.videoTitle,
    this.viewerUserId,
    this.primaryColor = 'burlywood',
    this.secondaryColor = '#383838',
    this.muted = false,
    this.crossOrigin = 'anonymous',
    this.startTime,
    Key? key,
  }) : super(key: key);

  ///
  /// `playbackId` is  video play back id from mux.
  ///
  final String playbackId;

  ///
  ///
  ///
  final String? streamType;

  ///
  ///
  final String? videoTitle;

  ///
  ///
  ///
  final String? viewerUserId;

  ///
  ///
  final String? primaryColor;

  ///
  final String? secondaryColor;

  ///
  final bool? muted;

  ///
  final String? crossOrigin;

  ///
  final double? startTime;

  ///
  final double height;

  ///
  final double width;

  @override
  State<Html5Player> createState() => _Html5PlayerState();
}

class _Html5PlayerState extends State<Html5Player> {
  late WebViewXController webviewController;

  late Widget body;

  @override
  void initState() {
    String initialHtmlSource = '''
  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Testing Mux Player</title>

  </head>
  <body style="overflow:hidden; margin:0">
    <script src="https://unpkg.com/@mux/mux-player"></script>

    <mux-player
      style="height: 100vh;width: 100vw;--bottom-controls: none;--top-controls:none;--seek-backward-button: none;--seek-forward-button: none;"
      stream-type= ${widget.streamType}
      playback-id= ${widget.playbackId}
      metadata-video-title=${widget.videoTitle}
      metadata-viewer-user-id= ${widget.viewerUserId}
      primary-color= ${widget.primaryColor}
      secondary-color=${widget.secondaryColor}
      muted=${widget.muted}
      crossOrigin=${widget.crossOrigin}
      forward-seek-offset="15"
      backward-seek-offset="15"
      start-time=${widget.startTime}
      autoplay="any"
      nohotkeys
      loop
      placeholder='#000000'
    ></mux-player>

  </body>
</html>
  ''';
    body = WebViewX(
      height: widget.height,
      width: widget.width,
      initialContent: initialHtmlSource,
      initialSourceType: SourceType.html,
      onWebViewCreated: (controller) => webviewController = controller,
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return body;
  }
}
</code>```

I've tried meddling with the http.dart pub.dev with no avail. I'm a total newb with Flutter or coding in general, any help is greatly appreciated.

Body:
I'm struggling to make my video player track data inside Mux. I'm currently using FlutterFlow (no-code Flutter app builder) and have successfully implemented the live streaming feature, but would love to be able to track video and user data. I have also integrated this player https://pub.dev/packages/mux_player but since it's html, it uses core html features in mobile where it goes fullscreen when playing and doesn't autoplay (building a social app like TikTok/Instagram where you scroll). I'd like it to simply play when loaded and not go fullscreen.

Any advice is very much appreciated!

import '../../backend/backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import '../widgets/index.dart'; // Imports other custom widgets
import '../actions/index.dart'; // Imports custom actions
import '../../flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';

import 'package:webviewx/webviewx.dart';

class MuxPlayer extends StatefulWidget {
  const MuxPlayer(
      {Key? key, this.width, this.height, required this.playbackId})
      : super(key: key);

  final double? width;
  final double? height;
  final String playbackId;

  @override
  _MuxPlayerState createState() => _MuxPlayerState();
}

class _MuxPlayerState extends State<MuxPlayer> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.cyan,
      ),
      home: VideoScreen(pbId: widget.playbackId),
    );
  }
}

class VideoScreen extends StatelessWidget {
  final String pbId;

  const VideoScreen({Key? key, required this.pbId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Html5Player(
        playbackId: pbId,
      ),
    );
  }
}

//

class Html5Player extends StatefulWidget {
  const Html5Player({
    this.height = double.maxFinite,
    this.width = double.maxFinite,
    required this.playbackId,
    this.streamType,
    this.videoTitle,
    this.viewerUserId,
    this.primaryColor = 'burlywood',
    this.secondaryColor = '#383838',
    this.muted = false,
    this.crossOrigin = 'anonymous',
    this.startTime,
    Key? key,
  }) : super(key: key);

  ///
  /// `playbackId` is  video play back id from mux.
  ///
  final String playbackId;

  ///
  ///
  ///
  final String? streamType;

  ///
  ///
  final String? videoTitle;

  ///
  ///
  ///
  final String? viewerUserId;

  ///
  ///
  final String? primaryColor;

  ///
  final String? secondaryColor;

  ///
  final bool? muted;

  ///
  final String? crossOrigin;

  ///
  final double? startTime;

  ///
  final double height;

  ///
  final double width;

  @override
  State<Html5Player> createState() => _Html5PlayerState();
}

class _Html5PlayerState extends State<Html5Player> {
  late WebViewXController webviewController;

  late Widget body;

  @override
  void initState() {
    String initialHtmlSource = '''
  <!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Testing Mux Player</title>

    <mux-player
      style="height: 100vh;width: 100vw;--bottom-controls: none;--top-controls:none;--seek-backward-button: none;--seek-forward-button: none;"
      stream-type= ${widget.streamType}
      playback-id= ${widget.playbackId}
      metadata-video-title=${widget.videoTitle}
      metadata-viewer-user-id= ${widget.viewerUserId}
      primary-color= ${widget.primaryColor}
      secondary-color=${widget.secondaryColor}
      muted=${widget.muted}
      crossOrigin=${widget.crossOrigin}
      forward-seek-offset="15"
      backward-seek-offset="15"
      start-time=${widget.startTime}
      autoplay="any"
      nohotkeys
      loop
      placeholder='#000000'
    ></mux-player>

  ''';
    body = WebViewX(
      height: widget.height,
      width: widget.width,
      initialContent: initialHtmlSource,
      initialSourceType: SourceType.html,
      onWebViewCreated: (controller) => webviewController = controller,
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return body;
  }
}

I've tried meddling with the http.dart pub.dev with no avail. I'm a total newb with Flutter or coding in general, any help is greatly appreciated.


问:
Qty_percent in strategy.close
what is "Error on bar 1403:invalid percent value. Expected from (0,100], passed 500.00?

I have this error when I setup percent in strategy.close (50%).

This is the string:

strategy.close("Short1", qty.percent= 50 , comment = "Close for 50%")

I have no problem if I setup 50%, but the algo close more early the position, so I would close it at bigger percent.

I try to setup in this method:

0.1*100

But Tradinview notify me the problem 1403.

Title: Qty_percent in strategy.close


问:
Custom cursor always behind elements. How to solve this?
I have created a custom cursor in my NextJS application like this:

```<code>import { useEffect, useState } from "react";
import { motion } from "framer-motion";

export default function Cursor(props: any) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const mouseMove = (e: any) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };
    window.addEventListener("mousemove", mouseMove);

    return () => {
      window.removeEventListener("mousemove", mouseMove);
    };
  }, []);

  const variants = {
    default: {
      x: position.x - 16,
      y: position.y - 16,
      backgroundColor: "#fff",
    },
    text: {
      height: 150,
      width: 150,
      x: position.x - 75,
      y: position.y - 75,
      backgroundColor: "#fff",
    },
  };

  return (
    <motion.div
      variants={variants}
      animate={props.cursorVariant}
      className="h-[32px] w-[32px] rounded-full fixed top-0 left-0"
    />
  );
}
</code>```

and added it to my index.tsx file as follows:

```<code>import HeadTag from "../components/HeadTag";
import Navbar from "../components/Navbar";
import Landing from "../components/Landing";
import AboutMe from "../components/AboutMe";
import Divider from "../components/Divider";
import Projects from "../components/Projects";
import Footer from "../components/Footer";
import ParticleComponent from "../components/Particles";
import Cursor from "../components/Cursor";
import { useState } from "react";

export default function Home() {
  const [cursorVariant, setCursorVariant] = useState("default");
  return (
    <>
      <HeadTag />
      <div
        style={{ scrollBehavior: "smooth" }}
        className="select-none bg-slate-900 w-full overflow-x-hidden flex flex-col items-center"
      >
        <Cursor cursorVariant={cursorVariant}/>
        <ParticleComponent />
        <Navbar />
        <Landing setCursorVariant={setCursorVariant}/>
        <AboutMe />
        <Divider />
        <Projects />
        <Divider />
        <Footer />
      </div>
    </>
  );
}
</code>```

Everything works fine regarding the styling and functions of the cursor but when I hover over elements like e.g. my Navbar Toggle, the cursor in in the background of that element and isn't visible anymore.
I have already tried giving the Div element of the cursor a higher z-index than the elements I want to hover over but this in not changing anything...

My global.css looks like this to prevent the default cursor from showing up:

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;

* { cursor: none;}
</code>```

Anyone has a tip for me how to solve this problem? :)
Thanks a lot!

Body:
I have created a custom cursor in my NextJS application like this:

import { useEffect, useState } from "react";
import { motion } from "framer-motion";

export default function Cursor(props: any) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const mouseMove = (e: any) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };
    window.addEventListener("mousemove", mouseMove);

    return () => {
      window.removeEventListener("mousemove", mouseMove);
    };
  }, []);

  const variants = {
    default: {
      x: position.x - 16,
      y: position.y - 16,
      backgroundColor: "#fff",
    },
    text: {
      height: 150,
      width: 150,
      x: position.x - 75,
      y: position.y - 75,
      backgroundColor: "#fff",
    },
  };

  return (
    <motion.div
      variants={variants}
      animate={props.cursorVariant}
      className="h-[32px] w-[32px] rounded-full fixed top-0 left-0"
    />
  );
}

and added it to my index.tsx file as follows:

import HeadTag from "../components/HeadTag";
import Navbar from "../components/Navbar";
import Landing from "../components/Landing";
import AboutMe from "../components/AboutMe";
import Divider from "../components/Divider";
import Projects from "../components/Projects";
import Footer from "../components/Footer";
import ParticleComponent from "../components/Particles";
import Cursor from "../components/Cursor";
import { useState } from "react";

export default function Home() {
  const [cursorVariant, setCursorVariant] = useState("default");
  return (
    <>
      <HeadTag />

        <Cursor cursorVariant={cursorVariant}/>
        <ParticleComponent />
        <Navbar />
        <Landing setCursorVariant={setCursorVariant}/>
        <AboutMe />
        <Divider />
        <Projects />
        <Divider />

    </>
  );
}

Everything works fine regarding the styling and functions of the cursor but when I hover over elements like e.g. my Navbar Toggle, the cursor in in the background of that element and isn't visible anymore.
I have already tried giving the Div element of the cursor a higher z-index than the elements I want to hover over but this in not changing anything...

My global.css looks like this to prevent the default cursor from showing up:

@tailwind base;
@tailwind components;
@tailwind utilities;

* { cursor: none;}

Anyone has a tip for me how to solve this problem? :)
Thanks a lot!


问:
Part of the data was lost when the data was processed in the way provided by huggingface(pytorch)
I'm reproducing a project at https://github.com/xplip/pixel.
It is based on huggingface's datasets and Trainer to implement.
I loaded sst2under gluewithout any problems:

```<code>raw_datasets = load_dataset("glue", data_args.task_name, cache_dir=model_args.cache_dir)
</code>```

Printing the information in the dataset is also normal:

```<code>train_dataset = raw_datasets["train"]

...

if training_args.do_train:
    for index in random.sample(range(len(train_dataset)), 3):
        logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")

>>> examples: {'sentence': ["although german cooking does not come readily to mind when considering the world 's best cuisine , mostly martha could make deutchland a popular destination for hungry tourists . "], 'label': [1], 'idx': [558]}

...
</code>```

However, during the training phase of the model, an error is reported.

```<code>trainer = PIXELTrainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset if training_args.do_train else None,
        eval_dataset=eval_dataset if training_args.do_eval else None,
        compute_metrics=compute_metrics,
        tokenizer=processor,
        data_collator=get_collator(training_args, processor, modality, is_regression=is_regression),
        callbacks=[EarlyStoppingCallback(early_stopping_patience=training_args.early_stopping_patience)]
        if training_args.early_stopping
        else None,
    )
# PIXELTrainer is a subclass of Trainer
...

train_result = trainer.train(resume_from_checkpoint=checkpoint)
</code>```

The following is my error message:

```<code>Traceback (most recent call last):
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\dataloader.py", line 517, in __next__
    data = self._next_data()
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\dataloader.py", line 557, in _next_data
    data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\arrow_dataset.py", line 2125, in __getitem__
    key,
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\arrow_dataset.py", line 2110, in _getitem
    pa_subtable, key, formatter=formatter, format_columns=format_columns, output_all_columns=output_all_columns
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 533, in format_table
    return formatter(pa_table, query_type=query_type)
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 281, in __call__
    return self.format_row(pa_table)
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 387, in format_row
    formatted_batch = self.format_batch(pa_table)
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 419, in format_batch
    return self.transform(batch)
  File "E:/Github_Pro/pixel/scripts/training/run_glue.py", line 358, in image_preprocess_fn
    encodings = [processor(text=format_fn(a)) for a in examples[sentence1_key]]
KeyError: 'sentence'
</code>```

According to the error message, I located this part:

```<code>def image_preprocess_fn(examples):
    # I print the information about examples
    print("examples:", examples)
    if sentence2_key:
        encodings = [
            processor(text=(format_fn(a), format_fn(b)))
            for a, b in zip(examples[sentence1_key], examples[sentence2_key])
        ]
    else:

        encodings = [processor(text=format_fn(a)) for a in examples[sentence1_key]]

    examples["pixel_values"] = [transforms(Image.fromarray(e.pixel_values)) for e in encodings]
    examples["attention_mask"] = [
        get_attention_mask(e.num_text_patches, seq_length=data_args.max_seq_length) for e in encodings
    ]

    return examples
</code>```

Then I print examples:

```<code>>>> examples: {'label': [1]}
</code>```

There is indeed no 'sentence'.
But there is 'sentence' in my original data, and since I am not familiar with datasets and Trainer, I don't know how to deal with this error anymore.

I would like someone to tell me why this is and show me how to modify the code to make it work.

Body:
I'm reproducing a project at https://github.com/xplip/pixel.
It is based on huggingface's datasets and Trainer to implement.
I loaded sst2under gluewithout any problems:

raw_datasets = load_dataset("glue", data_args.task_name, cache_dir=model_args.cache_dir)

Printing the information in the dataset is also normal:

train_dataset = raw_datasets["train"]

...

if training_args.do_train:
    for index in random.sample(range(len(train_dataset)), 3):
        logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")

>>> examples: {'sentence': ["although german cooking does not come readily to mind when considering the world 's best cuisine , mostly martha could make deutchland a popular destination for hungry tourists . "], 'label': [1], 'idx': [558]}

...

However, during the training phase of the model, an error is reported.

trainer = PIXELTrainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset if training_args.do_train else None,
        eval_dataset=eval_dataset if training_args.do_eval else None,
        compute_metrics=compute_metrics,
        tokenizer=processor,
        data_collator=get_collator(training_args, processor, modality, is_regression=is_regression),
        callbacks=[EarlyStoppingCallback(early_stopping_patience=training_args.early_stopping_patience)]
        if training_args.early_stopping
        else None,
    )
# PIXELTrainer is a subclass of Trainer
...

train_result = trainer.train(resume_from_checkpoint=checkpoint)

The following is my error message:

Traceback (most recent call last):
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\dataloader.py", line 517, in __next__
    data = self._next_data()
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\dataloader.py", line 557, in _next_data
    data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\arrow_dataset.py", line 2125, in __getitem__
    key,
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\arrow_dataset.py", line 2110, in _getitem
    pa_subtable, key, formatter=formatter, format_columns=format_columns, output_all_columns=output_all_columns
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 533, in format_table
    return formatter(pa_table, query_type=query_type)
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 281, in __call__
    return self.format_row(pa_table)
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 387, in format_row
    formatted_batch = self.format_batch(pa_table)
  File "C:\Development\Anaconda3\envs\pixels\lib\site-packages\datasets\formatting\formatting.py", line 419, in format_batch
    return self.transform(batch)
  File "E:/Github_Pro/pixel/scripts/training/run_glue.py", line 358, in image_preprocess_fn
    encodings = [processor(text=format_fn(a)) for a in examples[sentence1_key]]
KeyError: 'sentence'

According to the error message, I located this part:

def image_preprocess_fn(examples):
    # I print the information about examples
    print("examples:", examples)
    if sentence2_key:
        encodings = [
            processor(text=(format_fn(a), format_fn(b)))
            for a, b in zip(examples[sentence1_key], examples[sentence2_key])
        ]
    else:

        encodings = [processor(text=format_fn(a)) for a in examples[sentence1_key]]

    examples["pixel_values"] = [transforms(Image.fromarray(e.pixel_values)) for e in encodings]
    examples["attention_mask"] = [
        get_attention_mask(e.num_text_patches, seq_length=data_args.max_seq_length) for e in encodings
    ]

    return examples

Then I print examples:

>>> examples: {'label': [1]}

There is indeed no 'sentence'.
But there is 'sentence' in my original data, and since I am not familiar with datasets and Trainer, I don't know how to deal with this error anymore.

I would like someone to tell me why this is and show me how to modify the code to make it work.


问:
WooCommerce function add custom field to meta data orders
This function add custom field for variants "Csku" to meta data in orders:

```<code>add_action( 'woocommerce_checkout_create_order_line_item', 'add_csku_on_orders_and_emails', 10, 4 );
function add_csku_on_orders_and_emails( $item, $cart_item_key, $values, $order ) {
    $csku = $values['data']->get_meta('csku'); // Get product "csku"

    if ( ! empty($csku) ) {
        $item->add_meta_data( 'csku', $csku ); // add it as custom order item meta data
    }
}
</code>```

response API orders WooCommerce:

```<code>"meta_data": [
                    {
                        "id": 133,
                        "key": "size",
                        "value": "S",
                        "display_key": "Size",
                        "display_value": "S"
                    },
                    {
                        "id": 134,
                        "key": "csku",
                        "value": "skuvariant",
                        "display_key": "csku",
                        "display_value": "skuvariant"
                    }
                ],
</code>```

Database:
https://prnt.sc/pRl53abMPxBr

The problem is I need display in meta data API always first  csku and next rests meta data like sizes etc.

I checked in database and first is inserted variants example size S:

```<code>meta_id 133
order_item_id 13
meta_key size
meta_value S
</code>```

and then my custom field:

```<code>meta_id 134
order_item_id 13
meta_key csku
meta_value skuvariant
</code>```

How to change and first insert my custom field and then  others meta data or how to change directly on API to display always first  my custom field as first meta data?

Body:
This function add custom field for variants "Csku" to meta data in orders:

add_action( 'woocommerce_checkout_create_order_line_item', 'add_csku_on_orders_and_emails', 10, 4 );
function add_csku_on_orders_and_emails( $item, $cart_item_key, $values, $order ) {
    $csku = $values['data']->get_meta('csku'); // Get product "csku"

    if ( ! empty($csku) ) {
        $item->add_meta_data( 'csku', $csku ); // add it as custom order item meta data
    }
}

response API orders WooCommerce:

"meta_data": [
                    {
                        "id": 133,
                        "key": "size",
                        "value": "S",
                        "display_key": "Size",
                        "display_value": "S"
                    },
                    {
                        "id": 134,
                        "key": "csku",
                        "value": "skuvariant",
                        "display_key": "csku",
                        "display_value": "skuvariant"
                    }
                ],

Database:
https://prnt.sc/pRl53abMPxBr

The problem is I need display in meta data API always first  csku and next rests meta data like sizes etc.

I checked in database and first is inserted variants example size S:

meta_id 133
order_item_id 13
meta_key size
meta_value S

and then my custom field:

meta_id 134
order_item_id 13
meta_key csku
meta_value skuvariant

How to change and first insert my custom field and then  others meta data or how to change directly on API to display always first  my custom field as first meta data?


问:
Cached or not thread safe HttpContextAccessor?
I was running into strange user access issues which currently stands resolved. I have this scoped service as below.

```<code>services.AddScoped<IJwtService, JwtService>();
</code>```

The following custom middleware, which has the above service DI through constructor.

```<code> app.UseMiddleware<AccessCheckToRoutesMiddleware>();
</code>```

The following was the original code for the JwtService

```<code>        public JwtService(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
            //Later removed this section of code below to make it work consistently
            try
            {
                _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
            }
            catch { }

        }
        private void _getIdentity()
        {
            if (_identity==null) _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
           //Later changed the above section of code as below to make it work consistently
           _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
        }

        public bool IsPrivilegedUser()
        {
            _getIdentity();
            var val = _identity.FindFirst("IsPrivilegedUser")?.Value;
            return val.Equals("True", StringComparison.OrdinalIgnoreCase);
        }
</code>```

As explained in the code above, if I don't store the httpContextAccessor.HttpContext.User.Identity into a variable and get it every time straight, it gives strange results (basically the claims gets mixed up between various users accessing the app at that time. Can somebody exlain what is going on here? Is this a thread safety issue or is it some type of caching issue?

Body:
I was running into strange user access issues which currently stands resolved. I have this scoped service as below.

services.AddScoped<IJwtService, JwtService>();

The following custom middleware, which has the above service DI through constructor.

 app.UseMiddleware<AccessCheckToRoutesMiddleware>();

The following was the original code for the JwtService

        public JwtService(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
            //Later removed this section of code below to make it work consistently
            try
            {
                _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
            }
            catch { }

        }
        private void _getIdentity()
        {
            if (_identity==null) _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
           //Later changed the above section of code as below to make it work consistently
           _identity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
        }

        public bool IsPrivilegedUser()
        {
            _getIdentity();
            var val = _identity.FindFirst("IsPrivilegedUser")?.Value;
            return val.Equals("True", StringComparison.OrdinalIgnoreCase);
        }

As explained in the code above, if I don't store the httpContextAccessor.HttpContext.User.Identity into a variable and get it every time straight, it gives strange results (basically the claims gets mixed up between various users accessing the app at that time. Can somebody exlain what is going on here? Is this a thread safety issue or is it some type of caching issue?


问:
how to change some of audio default
I have wav file and I want to change some of the options from dic variable

```<code>optimization = {
    'amplify': '2.2 dB',
    'bass': '9.0 dB',
    'treble': '-1.0 dB',
    'volume': '1.0 dB',
    'speed': '0.98',
    'high-pass': {
        'frequency': '1000 Hz',
        'roll-off': '6dB per octave',
    },
    'low-pass': {
        'frequency': '1000 Hz',
        'roll-off': '6dB per octave',
    },
    'snap-to': 'nearest',
    'quality': 'insane-320 kbps',
    'variable-speed': 'standard',
    'chanel-mode': 'joint-stereo',
    'rate': '16000 HZ',
}
</code>```

and save that for my sppech-to-text model

Title: how to change some of audio default

Body:
I have wav file and I want to change some of the options from dic variable

optimization = {
    'amplify': '2.2 dB',
    'bass': '9.0 dB',
    'treble': '-1.0 dB',
    'volume': '1.0 dB',
    'speed': '0.98',
    'high-pass': {
        'frequency': '1000 Hz',
        'roll-off': '6dB per octave',
    },
    'low-pass': {
        'frequency': '1000 Hz',
        'roll-off': '6dB per octave',
    },
    'snap-to': 'nearest',
    'quality': 'insane-320 kbps',
    'variable-speed': 'standard',
    'chanel-mode': 'joint-stereo',
    'rate': '16000 HZ',
}

and save that for my sppech-to-text model


问:
I ruined the admin page, how do I fix it? ( Django 4.1 )
I have followed the steps from the django tutorial ( https://docs.djangoproject.com/en/4.1/intro/tutorial01/ ) and once I'd finished all the steps I stopped developing the project for 2 weeks at least without giving it much thought.

Once I've decided to check how the pages were looking like that's when I found this:

The admin page

And I don't know how I did it.

Here's how the documentation looks like:

```<code>meuSite/
    __init__.py
    settings.py
    urls.py
    asgi.py
    wsgi.py
polls/
    migrations/
    static/
    templates/
        admin/
            base.html
        polls/
            detail.html
            index.html
            results.html

    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    urls.py
    views.py
db.sqlite3
manage.py
</code>```

SETTINGS:

```<code>meuSite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]
</code>```

URLS:

```<code># meuSite/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("polls/", include('polls.urls')),
]

</code>```
```<code># polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:question_id>/', views.DetailView.as_view(), name='detail'),
    path('<int:question_id>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote')
]
</code>```

If there's something else that I didn't show that may have the root of the problem, please tell me

I tried solving it by deleting the templates/admin directory, but it didn't change how the page looks

Body:
I have followed the steps from the django tutorial ( https://docs.djangoproject.com/en/4.1/intro/tutorial01/ ) and once I'd finished all the steps I stopped developing the project for 2 weeks at least without giving it much thought.

Once I've decided to check how the pages were looking like that's when I found this:

The admin page

And I don't know how I did it.

Here's how the documentation looks like:

meuSite/
    __init__.py
    settings.py
    urls.py
    asgi.py
    wsgi.py
polls/
    migrations/
    static/
    templates/
        admin/
            base.html
        polls/
            detail.html
            index.html
            results.html

    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    urls.py
    views.py
db.sqlite3
manage.py

SETTINGS:

meuSite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

URLS:

# meuSite/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("polls/", include('polls.urls')),
]

# polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:question_id>/', views.DetailView.as_view(), name='detail'),
    path('<int:question_id>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote')
]

If there's something else that I didn't show that may have the root of the problem, please tell me

I tried solving it by deleting the templates/admin directory, but it didn't change how the page looks


问:
I have a question about css in symfony 5.4
But when I put my css cards they don't come out well on mobile
It turns out that when you use the code that I have left below, the cards overlap over the footer and the footer does not go down at all

base.html.twig with header and footer

```<code><!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        <link rel="icon" href="/public/svg/logoPlanesSinFondo.svg">
        {# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
        {% if form is defined and form %}
            {% form_theme form 'bootstrap_5_layout.html.twig' %}
        {% endif %}

        {% block stylesheets %}
            <link href="/css/base.css" rel="stylesheet" type="text/css">
            <link href="/css/main.css" rel="stylesheet" type="text/css">
            <link href="/css/cards.css" rel="stylesheet" type="text/css">
            <link href="/css/family.css" rel="stylesheet" type="text/css">
            <link href="/css/login.css" rel="stylesheet" type="text/css">
            <link href="/css/calendar.css" rel="stylesheet" type="text/css">
            <link href="/css/calendario.css" rel="stylesheet" type="text/css">
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css" integrity="sha256-5veQuRbWaECuYxwap/IOE/DAwNxgm4ikX7nrgsqYp88=" crossorigin="anonymous">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
            <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        {% endblock %}
    </head>
    <body>
        {% block menu %}
            <nav class="navbar navbar-dark navbar-expand">
                <div class="container-fluid">
                    <a href="https://www.iesjoseplanes.es/" target="_blank">
                        <img id="icon" src="/svg/logoPlanesSinFondo.svg">
                    </a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                        <div class="navbar-nav ms-auto">
                            {% if is_granted("IS_AUTHENTICATED_REMEMBERED") %}
                                <a class="nav-link" href="{{ path('app_logout') }}">
                                    Cerrar sesión
                                </a>
                            {% else %}
                                <a class="nav-link" href="{{ path('app_login') }}">Iniciar sesión</a>
                                <a class="nav-link" href="{{ path('app_register') }}">Registrar</a>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </nav>
        {% endblock %}

        {% block body %}
        {% endblock %}

        {% block footer %}
            <footer class="footer-distributed">
                <div class="footer-left">
                    <p class="footer-links">
                        <a href="/">Home</a>
                    </p>

                    <p class="footer-company-name">© 2022 Eduonix Learning Solutions Pvt. Ltd.</p>
                </div>
                <div class="footer-center">
                    <div>
                        <i class="fa fa-phone"></i>
                        <p>+91 22-27782183</p>
                    </div>
                    <div>
                        <i class="fa fa-envelope"></i>
                        <p><a href="mailto:support@eduonix.com">support@eduonix.com</a></p>
                    </div>
                </div>
                <div class="footer-right">
                    <div class="footer-icons">
                        <a href="https://www.facebook.com/IesJosePlanes"><i class="fa fa-facebook"></i></a>
                        <a href="https://twitter.com/iesjoseplanes"><i class="fa fa-twitter"></i></a>
                        <a href="https://www.instagram.com/ies.joseplanes_oficial"><i class="fa fa-instagram"></i></a>
                    </div>
                </div>
            </footer>
        {% endblock %}

        {% block javascripts %}
            <script src="/public/javascripts/navbar.js"></script>
            <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
            <script src="/javascripts/sweetalert2.all.min.js"></script>
        {% endblock %}
    </body>
</html>
</code>```

My familia.html.twig when adapted for mobile the footer is placed behind the body

```<code>{% extends 'base.html.twig' %}

{% block title %}Familia{% endblock %}

{% block body %}

<div id="familyBody">
    <div id="containerCards" class="container">
        <div id="cardfamily1" class="card">
            <div class="slide slide1">
                <div class="content">
                    <a href="{{path('showTutores')}}" class="icon">
                        <img aria-hidden="true" style="width:300px;"></img>
                    </a>
                </div>
            </div>
            <div class="slide slide2">
                <a href="{{path('showTutores')}}" class="content">
                    <h3>Tutoría</h3>
                </a>
            </div>
        </div>
        <div id="cardfamily2" class="card">
            <div class="slide slide1">
                <div class="content">
                    <a href="{{path('showSecretaria')}}" class="icon">
                        <img aria-hidden="true" style="width:300px;"></img>
                    </a>
                </div>
            </div>
            <div class="slide slide2">
                <a href="{{path('showSecretaria')}}" class="content">
                    <h3>Secretaría</h3>
                </a>
            </div>
        </div>
        <div id="cardfamily3" class="card">
            <div class="slide slide1">
                <div class="content">
                    <a href="{{path('showOrientacion')}}" class="icon">
                        <img aria-hidden="true" style="width:300px;"></img>
                    </a>
                </div>
            </div>
            <div class="slide slide2">
                <a href="{{path('showOrientacion')}}" class="content">
                    <h3>Orientación</h3>
                </a>
            </div>
        </div>
    </div>
    <a href="/"><lottie-player id="buttonReturn" class="btn btn-primary" src="https://assets9.lottiefiles.com/packages/lf20_tuwojxyr.json"  background="transparent" speed="1" style="width: 70px; height: 40px;"  loop  autoplay></lottie-player></a>
</div>
{% endblock %}
</code>```

This is the css

```<code>body{
    width: 100%;
    height: 100%;
}

/* .row{
    display: flex;
}

#container{
    display: flex;
    flex-direction: column;
    height: calc(100vh - 24.045407636738908vh);
} */

#familyBody{
    display: flex;
    flex-direction: column;
    height: calc(100vh - 24.045407636738908vh);
    width: 100vw;
    flex-wrap: wrap;
}

#containerCards{
    display: flex;
    height: calc(100vh - 28.99587203302374vh);
    justify-content:space-around;
    align-items: center;
    flex-wrap: wrap;
}

#buttonReturn{
    width: 70px;
    margin-left: 20px;
}
</code>```

Can anybody help me?

Body:
But when I put my css cards they don't come out well on mobile
It turns out that when you use the code that I have left below, the cards overlap over the footer and the footer does not go down at all

base.html.twig with header and footer

<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        <link rel="icon" href="/public/svg/logoPlanesSinFondo.svg">
        {# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
        {% if form is defined and form %}
            {% form_theme form 'bootstrap_5_layout.html.twig' %}
        {% endif %}

        {% block stylesheets %}
            <link href="/css/base.css" rel="stylesheet" type="text/css">
            <link href="/css/main.css" rel="stylesheet" type="text/css">
            <link href="/css/cards.css" rel="stylesheet" type="text/css">
            <link href="/css/family.css" rel="stylesheet" type="text/css">
            <link href="/css/login.css" rel="stylesheet" type="text/css">
            <link href="/css/calendar.css" rel="stylesheet" type="text/css">
            <link href="/css/calendario.css" rel="stylesheet" type="text/css">
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css" integrity="sha256-5veQuRbWaECuYxwap/IOE/DAwNxgm4ikX7nrgsqYp88=" crossorigin="anonymous">
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
            <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        {% endblock %}

        {% block menu %}

                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

                    </button>

                            {% if is_granted("IS_AUTHENTICATED_REMEMBERED") %}

                                    Cerrar sesión

                            {% else %}
                                Iniciar sesión
                                Registrar
                            {% endif %}

        {% endblock %}

        {% block body %}
        {% endblock %}

        {% block footer %}

                        Home

© 2022 Eduonix Learning Solutions Pvt. Ltd.

+91 22-27782183

support@eduonix.com

        {% endblock %}

        {% block javascripts %}

        {% endblock %}

My familia.html.twig when adapted for mobile the footer is placed behind the body

{% extends 'base.html.twig' %}

{% block title %}Familia{% endblock %}

{% block body %}

Tutoría

Secretaría

Orientación

    <lottie-player id="buttonReturn" class="btn btn-primary" src="https://assets9.lottiefiles.com/packages/lf20_tuwojxyr.json"  background="transparent" speed="1" style="width: 70px; height: 40px;"  loop  autoplay></lottie-player>

{% endblock %}

This is the css

body{
    width: 100%;
    height: 100%;
}

/* .row{
    display: flex;
}

#container{
    display: flex;
    flex-direction: column;
    height: calc(100vh - 24.045407636738908vh);
} */

#familyBody{
    display: flex;
    flex-direction: column;
    height: calc(100vh - 24.045407636738908vh);
    width: 100vw;
    flex-wrap: wrap;
}

#containerCards{
    display: flex;
    height: calc(100vh - 28.99587203302374vh);
    justify-content:space-around;
    align-items: center;
    flex-wrap: wrap;
}

#buttonReturn{
    width: 70px;
    margin-left: 20px;
}

Can anybody help me?


问:
How to make responsive UI if UIScreen is deprecated in SwiftUI?
My view contains an area on the bottom. I want to make it fill the 0.3 times of the screen height. However, if the UIScreen is deprecated, I cannot get the screen size on newer versions of iOS. Additionally, if I use GeometryReader, my screen breaks. I am new to SwiftUI and I believe there is another way to work with these type of situations rather than hardcoding the size. Any help is appreciated.

For example:

```<code>Button {
    onButtonPressed()
} {
    Text("Press Me")
}
.frame(
    maxWidth: .infinity,
    maxHeight: UIScreen.main.bounds.height * 0.3 // Can not do that anymore
)
</code>```

Body:
My view contains an area on the bottom. I want to make it fill the 0.3 times of the screen height. However, if the UIScreen is deprecated, I cannot get the screen size on newer versions of iOS. Additionally, if I use GeometryReader, my screen breaks. I am new to SwiftUI and I believe there is another way to work with these type of situations rather than hardcoding the size. Any help is appreciated.

For example:

Button {
    onButtonPressed()
} {
    Text("Press Me")
}
.frame(
    maxWidth: .infinity,
    maxHeight: UIScreen.main.bounds.height * 0.3 // Can not do that anymore
)


问:
How to save the terminal output in columns?
How can I save terminal output to a single column in pandas?

```<code>btn = driver.find_element(By. XPATH,
"/html[1]/body[1]/div[1]/div[1]/div[1]/div[4]/div[1]/header[1]/div[2]/div[2]")
btn.get_attribute("title")
sleep(2)
print(btn.text)
</code>```

I need to use .text in btn, to get the desired result.

I'm using selenium to extract the information

terminal exit

The element that separates the information is the comma.

Body:
How can I save terminal output to a single column in pandas?

btn = driver.find_element(By. XPATH,
"/html[1]/body[1]/div[1]/div[1]/div[1]/div[4]/div[1]/header[1]/div[2]/div[2]")
btn.get_attribute("title")
sleep(2)
print(btn.text)

I need to use .text in btn, to get the desired result.

I'm using selenium to extract the information

terminal exit

The element that separates the information is the comma.


问:
SSIS low on virtual memory in debug mode
I run packages in debug mode in Visual Studio, but often get 'low on virtual memory' warnings,

I also often run multiple instances of Visual Studio to enable multiple packages to run for different purposes simultaneously.

The machine has 64 gig of memory, and more than 30 gig is free at the time I start getting the following in the output window. Any ideas? (I've tried it with larger values for DefaultBufferMaxRows and corresponding increases in DefaultBufferSize)

Information: 0x4004800C at Data Flow Task, SSIS.Pipeline: The buffer manager detected that the system was low on virtual memory, but was unable to swap out any buffers. 32 buffers were considered and 32 were locked. Either not enough memory is available to the pipeline because not enough is installed, other processes are using it, or too many buffers are locked.

Information: 0x4004800F at Data Flow Task: Buffer manager allocated 40 megabyte(s) in 4 physical buffer(s).