问:
How to access a collection of heterogenous functions randomly?
I am implementing an evolutionary algorithm where I have a numerical genetic encoding (0-n). Where each number from 0 to n represents a function. I have implemented a numpy version where it is possible to do the following. The actual implementation is a bit more complicated but this snippet captures the core functionality.

n = 3
max_ops = 10
# Generate randomly generated args and OPs
for i in range(number_of_iterations):
    args = np.random.randint(min_val_arg, max_val_arg, size=(arg_count, arg_shape[0], arg_shape[1])
    gene_of_operations = np.random.randint(0,n,size=(max_ops))

    # A collection of OP encodings and operations. Doesn't need to be a dict.
    dict_of_n_OPs = {
    0:np.add,
    1:np.multiply,
    2:np.diff
    }

    @njit
    def execute_genome(gene_of_operations, args, dict_of_n_OPs):
        result = 0
        for op, arg in zip(gene_of_operations,args)
            result+= op(arg)
        return result

     ## executing the gene
     execute_genome(gene_of_operations, args, dict_of_n_OPs)
     print(results)
```

Now when adding the njit decorator expects a statically typed function. Where heterogenously typed collections such as my dict_of_n_OPs are not supported, I have tried rendering it as a numpy array, numba.typed.Dict, numba.typed.List. But discovered none supports heteregoenous types.

What would be a numba compliant approach that allows for executing different functions based on a numerical encoding such as '00201'. Where number 0 would execute function 0?

Is the only way an n line if else statement for n unique operations/functions?

Body:
I am implementing an evolutionary algorithm where I have a numerical genetic encoding (0-n). Where each number from 0 to n represents a function. I have implemented a numpy version where it is possible to do the following. The actual implementation is a bit more complicated but this snippet captures the core functionality.

n = 3
max_ops = 10
# Generate randomly generated args and OPs
for i in range(number_of_iterations):
    args = np.random.randint(min_val_arg, max_val_arg, size=(arg_count, arg_shape[0], arg_shape[1])
    gene_of_operations = np.random.randint(0,n,size=(max_ops))

    # A collection of OP encodings and operations. Doesn't need to be a dict.
    dict_of_n_OPs = {
    0:np.add,
    1:np.multiply,
    2:np.diff
    }

    @njit
    def execute_genome(gene_of_operations, args, dict_of_n_OPs):
        result = 0
        for op, arg in zip(gene_of_operations,args)
            result+= op(arg)
        return result

     ## executing the gene
     execute_genome(gene_of_operations, args, dict_of_n_OPs)
     print(results)

Now when adding the njit decorator expects a statically typed function. Where heterogenously typed collections such as my dict_of_n_OPs are not supported, I have tried rendering it as a numpy array, numba.typed.Dict, numba.typed.List. But discovered none supports heteregoenous types.

What would be a numba compliant approach that allows for executing different functions based on a numerical encoding such as '00201'. Where number 0 would execute function 0?

Is the only way an n line if else statement for n unique operations/functions?


来源: stackexchange

问:
Postman multiple responses on a single request
I want to run unit tests in my program whenever the api receives a request. the api returns a response once when it has received a valid request, but then later it will send once it's done with the unit tests. The first response is shown in Postman, but not the second repsonse. I can see that it getting send using wireshark though.

These are two separate responses and since this api is what it is, I don't have the power to change it. How can i use Postman to receive the second response as well?

Edit additional information is requested so:
I have in my collection a POST request and when I trigger it I get a response back with a body with:

```<code>{
    "messageType" : "Response"
    "options" : "async"
}
</code>```

Then the code can see that another response is incoming later, because of the async token.

A bit later another response is received:

```<code>{
    "messageType" : "Response"
    "Tests" : "11 ok tests"
}
</code>```

But in postman I can't seem to receive the second response, as the transaction is finished after the first one. How can I make postman also receive the second response?

ContentLicense: CC BY-SA 4.0

Body:
I want to run unit tests in my program whenever the api receives a request. the api returns a response once when it has received a valid request, but then later it will send once it's done with the unit tests. The first response is shown in Postman, but not the second repsonse. I can see that it getting send using wireshark though.

These are two separate responses and since this api is what it is, I don't have the power to change it. How can i use Postman to receive the second response as well?

Edit additional information is requested so:
I have in my collection a POST request and when I trigger it I get a response back with a body with:

{
    "messageType" : "Response"
    "options" : "async"
}

Then the code can see that another response is incoming later, because of the async token.

A bit later another response is received:

{
    "messageType" : "Response"
    "Tests" : "11 ok tests"
}

But in postman I can't seem to receive the second response, as the transaction is finished after the first one. How can I make postman also receive the second response?


问:
Validation error working wit ASP.NET MVC .NET FRAMEWORK
your text
I added validation to my ASP.NET MVC .NET FRAMEOWRK project and get this error:
your text
Unable to cast object of type 'System.Int32' to type 'System.String'.
My project connect to data base with one table.

my code:
Customer.cs:

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ConnectToDB
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    public partial class Customers : IValidatableObject
    {
        [StringLength(1000, ErrorMessage = "Queue number must be no more than 1000 digits")]
        [Required(ErrorMessage = "Queue number is required")]
        [DataType(DataType.Text)]
        [DisplayName("Queue number")]
        public int queueNumber { get; set; }

        [StringLength(30, ErrorMessage = "First name must be no more tha 1000 letters")]
        [RegularExpression("^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")] // RegEx: Used to validate a person name
        [Required(ErrorMessage = "First name is required")]
        [DisplayName("First name")]
        [DataType(DataType.Text)]
        public string firstName { get; set; }

        [StringLength(30, ErrorMessage = "Last name must be no more tha 1000 letters")]
        [RegularExpression("^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")] // RegEx: Used to validate a person name
        [Required(ErrorMessage = "Last name is required")]
        [DisplayName("Last name")]
        [DataType(DataType.Text)]
        public string lastName { get; set; }

        [Required(ErrorMessage = "Time customer enter is required")]
        [DisplayName("Time customer enter")]
        [DataType(DataType.Time)]
        public Nullable<System.TimeSpan> timeCusEnter { get; set; }

        // Validation for queue number using IValidatableObject interface:
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> errors = new List<ValidationResult>();

            if (queueNumber < 0)
            {
                errors.Add(new ValidationResult("Queue number can not be negative.", new List<string> { "queueNumber" }));
            }

            return errors;
        }
    }
}
</code>```

addCustomer.cshtml:

```<code>@model ConnectToDB.Customers

@{
    ViewBag.Title = "addCustomer";
}

<link rel="stylesheet" href="~/CSS/addCusDesign.css" />
<link rel="stylesheet" href="~/CSS/Local.css" />
<body>
    @*Menu:*@
    <div class="navBar">
        <span class="navItem">
            @Html.ActionLink("Dequeue to the queue", "addCustomer")
        </span>
        <span class="navItem">
            @Html.ActionLink("Customers list", "customersList")
        </span>
    </div>
    <h2>Enqueue</h2>
    <span id="secondTitle">Fill in the following details, then press the button and enter the queue.<br>Have a good day :)</span>
    <br />
    <br />

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Customers</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.queueNumber, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.queueNumber, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.queueNumber)
                </div>
            </div>
            <br />

            <div class="form-group">
                @Html.LabelFor(model => model.firstName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.firstName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.firstName)
                </div>
            </div>
            <br />

            <div class="form-group">
                @Html.LabelFor(model => model.lastName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.lastName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.lastName)
                </div>
            </div>
            <br />

            <div class="form-group">
                @Html.LabelFor(model => model.timeCusEnter, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.timeCusEnter, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.timeCusEnter)
                </div>
            </div>
            <br />
            <br />
            @Html.ValidationSummary(true, "Add customer was unsuccessful. Please coorect the following errors: ")
            @*Dequeue customer to the queue input: *@
            <div class="form-group">
                <div class="GetInTheQueue">
                    <input type="submit" value="GET IN THE QUEUE" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    <br />
    <br />

    @*Carusel in boostrap: *@
    <!-- #region Carusel -->
    <div id="carouselExampleFade" class="carousel slide carousel-fade" data-bs-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="~/Images/image1.jpeg" class="d-block w-100" alt="...">
            </div>
            <div class="carousel-item">
                <img src="~/Images/image2.png" class="d-block w-100" alt="...">
            </div>
            <div class="carousel-item">
                <img src="~/Images/Image3.jpeg" class="d-block w-100" alt="...">
            </div>
            <div class="carousel-item">
                <img src="~/Images/Image4.jpeg" class="d-block w-100" alt="...">
            </div>
            <div class="carousel-item">
                <img src="~/Images/Image5.jpeg" class="d-block w-100" alt="...">
            </div>
        </div>
        <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="visually-hidden">Previous</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="visually-hidden">Next</span>
        </button>
    </div>
    <!-- #endregion -->
    <br />
    <br />
    @*Images: *@
    <!-- #region Images -->

    <div class="images">
        <img width="200" height="200" src="~/Images/image1.jpeg" alt="Queue image1" />
        <img width="200" height="200" src="~/Images/image2.png" alt="Queue image2" />
        <img width="200" height="200" src="~/Images/Image3.jpeg" alt="Queue image3" />
        <img width="200" height="200" src="~/Images/Image4.jpeg" alt="Queue image4" />
        <img width="200" height="200" src="~/Images/Image5.jpeg" alt="Queue image5" />
    </div>
    <!-- #endregion -->
</body>
</code>```

Would appreciate help

The validation work for me yesterday, but today not working.

Body:
your text
I added validation to my ASP.NET MVC .NET FRAMEOWRK project and get this error:
your text
Unable to cast object of type 'System.Int32' to type 'System.String'.
My project connect to data base with one table.

my code:
Customer.cs:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ConnectToDB
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    public partial class Customers : IValidatableObject
    {
        [StringLength(1000, ErrorMessage = "Queue number must be no more than 1000 digits")]
        [Required(ErrorMessage = "Queue number is required")]
        [DataType(DataType.Text)]
        [DisplayName("Queue number")]
        public int queueNumber { get; set; }

        [StringLength(30, ErrorMessage = "First name must be no more tha 1000 letters")]
        [RegularExpression("^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")] // RegEx: Used to validate a person name
        [Required(ErrorMessage = "First name is required")]
        [DisplayName("First name")]
        [DataType(DataType.Text)]
        public string firstName { get; set; }

        [StringLength(30, ErrorMessage = "Last name must be no more tha 1000 letters")]
        [RegularExpression("^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")] // RegEx: Used to validate a person name
        [Required(ErrorMessage = "Last name is required")]
        [DisplayName("Last name")]
        [DataType(DataType.Text)]
        public string lastName { get; set; }

        [Required(ErrorMessage = "Time customer enter is required")]
        [DisplayName("Time customer enter")]
        [DataType(DataType.Time)]
        public Nullable<System.TimeSpan> timeCusEnter { get; set; }

        // Validation for queue number using IValidatableObject interface:
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> errors = new List<ValidationResult>();

            if (queueNumber < 0)
            {
                errors.Add(new ValidationResult("Queue number can not be negative.", new List<string> { "queueNumber" }));
            }

            return errors;
        }
    }
}

addCustomer.cshtml:

@model ConnectToDB.Customers

@{
    ViewBag.Title = "addCustomer";
}

<link rel="stylesheet" href="~/CSS/addCusDesign.css" />
<link rel="stylesheet" href="~/CSS/Local.css" />

    @*Menu:*@

            @Html.ActionLink("Dequeue to the queue", "addCustomer")

            @Html.ActionLink("Customers list", "customersList")

Enqueue

    Fill in the following details, then press the button and enter the queue.
Have a good day :)

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

Customers

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.queueNumber, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.queueNumber, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.queueNumber)

                @Html.LabelFor(model => model.firstName, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.firstName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.firstName)

                @Html.LabelFor(model => model.lastName, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.lastName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.lastName)

                @Html.LabelFor(model => model.timeCusEnter, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.timeCusEnter, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.timeCusEnter)

            @Html.ValidationSummary(true, "Add customer was unsuccessful. Please coorect the following errors: ")
            @*Dequeue customer to the queue input: *@

                    <input type="submit" value="GET IN THE QUEUE" class="btn btn-default" />

    }

    @*Carusel in boostrap: *@

        <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev">

            Previous
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next">

            Next
        </button>

    @*Images: *@

Would appreciate help

The validation work for me yesterday, but today not working.


问:
how to know the reason of error System.NullReferenceException: 'Object reference not set to an instance of an object.'
I have the following subroutine to get data from table:

```<code>'GetData
    Public Sub GetData(ByVal SqlStr As String, ByVal xDt As DataTable, ByVal xPar() As MySqlParameter)
        Using xCmd As New MySqlCommand() With {
                    .CommandType = CommandType.Text,
                    .CommandText = SqlStr,
                    .Connection = _ServerConnStr
                    }

            If xPar IsNot Nothing Then
                For i As Integer = 0 To xPar.Length - 1
                    xCmd.Parameters.Add(xPar(i))
                Next
            End If

            Using xDa As New MySqlDataAdapter(xCmd)
                xDa.Fill(xDt)
            End Using
            xDt.Dispose()
        End Using
    End Sub
</code>```

and I use that sub to get data from tblfatora1:

```<code>Public Sub MySql_GetFhMain()
        xDtMain = New DataTable()

        Dim xPar(2) As MySqlParameter
        xPar(0) = New MySqlParameter("@Date1", MySqlDbType.Date) With {
                                    .Value = Date1}
        xPar(1) = New MySqlParameter("@Date2", MySqlDbType.Date) With {
                                    .Value = Date2}
        xPar(2) = New MySqlParameter("@FhReso", DbType.Int32) With {
                                    .Value = FhReso}

            xSqlStr = "SELECT
                FhID, FhRef, FhCode, FhDate, FhQuan, FhPurPrice,
                FhPurTotal, FhCarNo, FhResoDetails, FhPalletQuan,
                FhPalletPrice, accreso.AccName AS ResoName,
                accdriv.AccName AS DriverName, CONCAT(CategoryName,'-',ProductName) AS ProductName,

                (SELECT GROUP_CONCAT(AccName) FROM tblaccounts
                    INNER JOIN tblfatora2 ON
                        tblfatora2.FbCus = tblaccounts.AccID
                                where FIND_IN_SET(AccID, FbCus) AND tblfatora2.FhRef = tblfatora1.FhRef)AS TheCustomers,

                (SELECT GROUP_CONCAT(PlaceName) FROM tblplaces
                    INNER JOIN tblfatora2 ON
                        tblfatora2.FbCusPlace = tblplaces.PlaceID
                                where FIND_IN_SET(PlaceID, FbCusPlace) AND tblfatora2.FhRef = tblfatora1.FhRef)AS ThePlaces ,

                (FhQuan -  (SELECT IFNULL(SUM(FbQuan), 0) FROM tblfatora2 WHERE FhRef = tblfatora1.FhRef)) AS TheRemain,
ProductPallet, PlaceName, FhDriver, FhProduct, FhReso, FhResoPlace

                                            FROM tblfatora1
                                        INNER JOIN tblproducts ON tblproducts.ProductID = tblfatora1.FhProduct
                                        INNER JOIN tblaccounts accreso ON accreso.AccID = tblfatora1.FhReso
                                        INNER JOIN tblaccounts accdriv ON accdriv.AccID = tblfatora1.FhDriver
                                        INNER JOIN tblcategories cat ON cat.CategoryID = tblproducts.ProductCategory
                                        INNER JOIN tblcurrencies curr ON accdriv.AccCurrID = curr.CurrencyID
                                        INNER JOIN tblplaces plc ON plc.PlaceID = tblfatora1.FhResoPlace
                                        WHERE (FhDate Between @Date1 And @Date2)"

        xClsMySql.GetData(xSqlStr, xDtMain, xPar)

    End Sub
</code>```

but sometimes when I run it I get the following error:

although when I check the rows count I see that there are many rows so the DtMain has rows:

as I said that error sometimes happens, not always, I tried to see the reason of the error but I couldn't

Body:
I have the following subroutine to get data from table:

'GetData
    Public Sub GetData(ByVal SqlStr As String, ByVal xDt As DataTable, ByVal xPar() As MySqlParameter)
        Using xCmd As New MySqlCommand() With {
                    .CommandType = CommandType.Text,
                    .CommandText = SqlStr,
                    .Connection = _ServerConnStr
                    }

            If xPar IsNot Nothing Then
                For i As Integer = 0 To xPar.Length - 1
                    xCmd.Parameters.Add(xPar(i))
                Next
            End If

            Using xDa As New MySqlDataAdapter(xCmd)
                xDa.Fill(xDt)
            End Using
            xDt.Dispose()
        End Using
    End Sub

and I use that sub to get data from tblfatora1:

Public Sub MySql_GetFhMain()
        xDtMain = New DataTable()

        Dim xPar(2) As MySqlParameter
        xPar(0) = New MySqlParameter("@Date1", MySqlDbType.Date) With {
                                    .Value = Date1}
        xPar(1) = New MySqlParameter("@Date2", MySqlDbType.Date) With {
                                    .Value = Date2}
        xPar(2) = New MySqlParameter("@FhReso", DbType.Int32) With {
                                    .Value = FhReso}

            xSqlStr = "SELECT
                FhID, FhRef, FhCode, FhDate, FhQuan, FhPurPrice,
                FhPurTotal, FhCarNo, FhResoDetails, FhPalletQuan,
                FhPalletPrice, accreso.AccName AS ResoName,
                accdriv.AccName AS DriverName, CONCAT(CategoryName,'-',ProductName) AS ProductName,

                (SELECT GROUP_CONCAT(AccName) FROM tblaccounts
                    INNER JOIN tblfatora2 ON
                        tblfatora2.FbCus = tblaccounts.AccID
                                where FIND_IN_SET(AccID, FbCus) AND tblfatora2.FhRef = tblfatora1.FhRef)AS TheCustomers,

                (SELECT GROUP_CONCAT(PlaceName) FROM tblplaces
                    INNER JOIN tblfatora2 ON
                        tblfatora2.FbCusPlace = tblplaces.PlaceID
                                where FIND_IN_SET(PlaceID, FbCusPlace) AND tblfatora2.FhRef = tblfatora1.FhRef)AS ThePlaces ,

                (FhQuan -  (SELECT IFNULL(SUM(FbQuan), 0) FROM tblfatora2 WHERE FhRef = tblfatora1.FhRef)) AS TheRemain,
ProductPallet, PlaceName, FhDriver, FhProduct, FhReso, FhResoPlace

                                            FROM tblfatora1
                                        INNER JOIN tblproducts ON tblproducts.ProductID = tblfatora1.FhProduct
                                        INNER JOIN tblaccounts accreso ON accreso.AccID = tblfatora1.FhReso
                                        INNER JOIN tblaccounts accdriv ON accdriv.AccID = tblfatora1.FhDriver
                                        INNER JOIN tblcategories cat ON cat.CategoryID = tblproducts.ProductCategory
                                        INNER JOIN tblcurrencies curr ON accdriv.AccCurrID = curr.CurrencyID
                                        INNER JOIN tblplaces plc ON plc.PlaceID = tblfatora1.FhResoPlace
                                        WHERE (FhDate Between @Date1 And @Date2)"

        xClsMySql.GetData(xSqlStr, xDtMain, xPar)

    End Sub

but sometimes when I run it I get the following error:

although when I check the rows count I see that there are many rows so the DtMain has rows:

as I said that error sometimes happens, not always, I tried to see the reason of the error but I couldn't


问:
unzip encrypted file with AES-256 node.js
I'm trying to decrypt zip file using crypto provided file is in s3 storage and I have password for the file and no info for IV.
I'm using cryptoDecipher but getting error cryptoDecipher is deprecated. I saw some post saying use createDecipheriv but I don't have any IV that I can use.

below is a sample code -

```<code>function demo(entry){
    password = 'mypassword';
    algorithm = 'aes-256-cbc';
    let decrypt = crypto.createDecipher(algorithm,password)
    let res = entry.stream().pipe(decrypt);
    const uploadParams = {
        Body:res,
        Bucket:myS3bucket,
        key:myfilename,
    }
    uploadfile(uploadParams)
}
</code>```

I'm using unzipper to unzip file and getting 'entry as object for file so just using that object in demo function'

help me out as I'm new to streams and crypto lib.

Body:
I'm trying to decrypt zip file using crypto provided file is in s3 storage and I have password for the file and no info for IV.
I'm using cryptoDecipher but getting error cryptoDecipher is deprecated. I saw some post saying use createDecipheriv but I don't have any IV that I can use.

below is a sample code -

function demo(entry){
    password = 'mypassword';
    algorithm = 'aes-256-cbc';
    let decrypt = crypto.createDecipher(algorithm,password)
    let res = entry.stream().pipe(decrypt);
    const uploadParams = {
        Body:res,
        Bucket:myS3bucket,
        key:myfilename,
    }
    uploadfile(uploadParams)
}

I'm using unzipper to unzip file and getting 'entry as object for file so just using that object in demo function'

help me out as I'm new to streams and crypto lib.


问:
error while trying to read a single cell genomic dataset
My code is
multiome <- load_object(file.path(dataset, "C:/Users/s/Desktop/Shahid/MOJITOO DATASETS/PBMC_Multiome.Rds"))

I get the following error:

```<code>Error in open.connection(3L, "rb") : cannot open the connection
In addition: Warning message:
In open.connection(3L, "rb") :
  cannot open file 'kidney/C:/Users/s/Desktop/Shahid/MOJITOO DATASETS/PBMC_Multiome.Rds': Invalid argument
Called from: open.connection(3L, "rb")
</code>```

I want to implement the MOJITOO single cell integration model. I get the error shown above.

Body:
My code is
multiome <- load_object(file.path(dataset, "C:/Users/s/Desktop/Shahid/MOJITOO DATASETS/PBMC_Multiome.Rds"))

I get the following error:

Error in open.connection(3L, "rb") : cannot open the connection
In addition: Warning message:
In open.connection(3L, "rb") :
  cannot open file 'kidney/C:/Users/s/Desktop/Shahid/MOJITOO DATASETS/PBMC_Multiome.Rds': Invalid argument
Called from: open.connection(3L, "rb")

I want to implement the MOJITOO single cell integration model. I get the error shown above.


问:
Are my assumptions about streams correct, and if so, how can I check for the case of 'input1'?
I am writing a program that receives a series of double values from the user and does stuff with them, in the form of 1.2 .2 -3 -> white-space de-limited values

At this point, it's already been validated that the string input contains only digits, '.', ' ', and '-'.

The program below is an outline of what I would like to use for additional input validation.

It seems like the while(buffer >> test) loop can be used for this, checking if EOF was reached for validation. However, there are a couple cases I am unhappy about.

Why is the bad() bit not setting for input1 and how can I check for an input of that type? I had thought bad() would be set due to the read/write error.

What is the role of whitespaces in the stream? Are they generally ignored? To me, it seems like the stream simply begins at its current position and attempts to read the type it is designated, ignoring white space. It can do without whitespaces if a negative follows a positive, see input2.

Does it always hold true that a double or int value that is being read to will be set to 0 when the stream fails to convert?

```<code>#include<iostream>
#include <sstream>
using namespace std;
int main(){

    string input0 = "1 2 3";    // Failed, EOF, 'test' retains correct value -> standard what I want

    string input1 = "1 2 3-";   // Failed, EOF, 'test' set to 0 b/c conversion failed -> why is bad not set?, not what I want -> how do I check for this?

    string input2 = "1 2-3";    // Failed, EOF, 'test', correct values -> weird behavior (would prefer this didn't occur)
    string input3 = "1 2 -3 "; // Failed, EOF, correct values -> does what I want it to
    string input4 = ".1 2---3  ";   // Failed, buffer position 4, 'test' set to 0   -> does what I want it to
    string input5 = ".1        2       3     "; // Failed, EOF, correct values      -> does what I want
    string input6 = ".1 2 --3 ";    // Failed, buffer position 4, 'test' set to 0 -> does what I want
    string input7 = ".1 - 2 3";     // Failed, buffer position 2, 'test set to 0 -> does what I want

    istringstream buffer(input7);
    double test = 0;
    while (buffer >> test){
        cout << "In loop" << endl;
        cout << "Value of test: " << test << endl;
        cout << "Buffer position: " << buffer.tellg() << endl;
    }
    cout << "Out of loop" << endl;
    cout << test << endl;

    if (buffer.good())          // no error flags set
        cout << "Good" << endl;
    if (buffer.bad())           // read/write error on i/o (integrity of stream lost) -> never set?
        cout << "Bad" << endl;
    if (buffer.fail())          // logical error on i/o (failure to convert) -> set on EOF
        cout << "Failed" << endl;
    if (buffer.eof())           // EOF reached on input op
        cout << "EOF" << endl;

    // .clear() would clear stream

}
</code>```

Is there any way to check explicitly for inputs of type input1 (most important), input2, input7 and input5 using stream functionality (and not another form of validation), in order to attempt to disallow them?

Body:
I am writing a program that receives a series of double values from the user and does stuff with them, in the form of 1.2 .2 -3 -> white-space de-limited values

At this point, it's already been validated that the string input contains only digits, '.', ' ', and '-'.

The program below is an outline of what I would like to use for additional input validation.

It seems like the while(buffer >> test) loop can be used for this, checking if EOF was reached for validation. However, there are a couple cases I am unhappy about.

Why is the bad() bit not setting for input1 and how can I check for an input of that type? I had thought bad() would be set due to the read/write error.

What is the role of whitespaces in the stream? Are they generally ignored? To me, it seems like the stream simply begins at its current position and attempts to read the type it is designated, ignoring white space. It can do without whitespaces if a negative follows a positive, see input2.

Does it always hold true that a double or int value that is being read to will be set to 0 when the stream fails to convert?

#include<iostream>
#include <sstream>
using namespace std;
int main(){

    string input0 = "1 2 3";    // Failed, EOF, 'test' retains correct value -> standard what I want

    string input1 = "1 2 3-";   // Failed, EOF, 'test' set to 0 b/c conversion failed -> why is bad not set?, not what I want -> how do I check for this?

    string input2 = "1 2-3";    // Failed, EOF, 'test', correct values -> weird behavior (would prefer this didn't occur)
    string input3 = "1 2 -3 "; // Failed, EOF, correct values -> does what I want it to
    string input4 = ".1 2---3  ";   // Failed, buffer position 4, 'test' set to 0   -> does what I want it to
    string input5 = ".1        2       3     "; // Failed, EOF, correct values      -> does what I want
    string input6 = ".1 2 --3 ";    // Failed, buffer position 4, 'test' set to 0 -> does what I want
    string input7 = ".1 - 2 3";     // Failed, buffer position 2, 'test set to 0 -> does what I want

    istringstream buffer(input7);
    double test = 0;
    while (buffer >> test){
        cout << "In loop" << endl;
        cout << "Value of test: " << test << endl;
        cout << "Buffer position: " << buffer.tellg() << endl;
    }
    cout << "Out of loop" << endl;
    cout << test << endl;

    if (buffer.good())          // no error flags set
        cout << "Good" << endl;
    if (buffer.bad())           // read/write error on i/o (integrity of stream lost) -> never set?
        cout << "Bad" << endl;
    if (buffer.fail())          // logical error on i/o (failure to convert) -> set on EOF
        cout << "Failed" << endl;
    if (buffer.eof())           // EOF reached on input op
        cout << "EOF" << endl;

    // .clear() would clear stream

}

Is there any way to check explicitly for inputs of type input1 (most important), input2, input7 and input5 using stream functionality (and not another form of validation), in order to attempt to disallow them?


问:
how to change keycloak template theme [the actual keycloak administration console theme]
I want to know how to change keycloak template theme,

I have to change the actual keycloak administration console theme not the login/admin/account/email theme :

keycloak theme

In the admin console, I can select the theme of the login/admin/account/email pages, but what i want is to change the actual theme for this admin console

i hope i was clear enough this is my first time posting a question.


问:
Error: error validating monitor from https://api.datadoghq.com/api/v1/monitor/validate: 400 Bad Request: {"errors"
As of today I get the follow error when trying to run Terraform:

│ Error: error validating monitor from https://api.datadoghq.com/api/v1/monitor/validate: 400 Bad Request: {"errors":["The value provided for parameter 'query' is invalid: invalid operator specified: "]}
│
│ with module.log_metrics.datadog_monitor.log_monitor[0],
│ on modules\logmonitor\main.tf line 36, in resource "datadog_monitor" "log_monitor":
│ 36: resource "datadog_monitor" "log_monitor" {

The Terraform Resources I am working with :

```<code>resource "datadog_monitor" "log_monitor" {
count = var.enabled ? 1 : 0
name = join(" - ", compact([
var.name_prefix,
local.service_display_name,
var.name,
var.name_suffix
]))
type = "log alert"
query = <<EOQ
log("(cardinality:@activity.session_id[@service:force.africa.cloud @log_ngixi.file_suffix:matchinfo domain:production-pa10-xxxxxxx.xxxxxx.net @matcherror:true] / cardinality:@activity.session_id[@service:force.africa.cloud @log_ngixi.file_prefix:orderinfo domain:production-pa04-xxxxxx.xxxxxx.net]) * 100").last("10m") > 40
EOQ
</code>```

I had search through stackoverflow documentations but cant resolve the issue.

Body:
As of today I get the follow error when trying to run Terraform:

│ Error: error validating monitor from https://api.datadoghq.com/api/v1/monitor/validate: 400 Bad Request: {"errors":["The value provided for parameter 'query' is invalid: invalid operator specified: "]}
│
│ with module.log_metrics.datadog_monitor.log_monitor[0],
│ on modules\logmonitor\main.tf line 36, in resource "datadog_monitor" "log_monitor":
│ 36: resource "datadog_monitor" "log_monitor" {

The Terraform Resources I am working with :

resource "datadog_monitor" "log_monitor" {
count = var.enabled ? 1 : 0
name = join(" - ", compact([
var.name_prefix,
local.service_display_name,
var.name,
var.name_suffix
]))
type = "log alert"
query = <<EOQ
log("(cardinality:@activity.session_id[@service:force.africa.cloud @log_ngixi.file_suffix:matchinfo domain:production-pa10-xxxxxxx.xxxxxx.net @matcherror:true] / cardinality:@activity.session_id[@service:force.africa.cloud @log_ngixi.file_prefix:orderinfo domain:production-pa04-xxxxxx.xxxxxx.net]) * 100").last("10m") > 40
EOQ

I had search through stackoverflow documentations but cant resolve the issue.


问:
How can i add items to shopping cart using JavaScript
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:

```<code></code>```
```<code>const listProducts = [
    {
        id: 1,
        name: 'Short Pant',
        price: '300.000 VND',
        imageUrl: 'img/1.jpg',
        button: 'Add to Cart'
    },
    {
        id: 2,
        name: 'Long Pant',
        price: '500.000 VND',
        imageUrl: 'img/2.jpg',
        button: 'Add to Cart'
    },
    {
        id: 3,
        name: 'Long Shirt',
        price: '400.000 VND',
        imageUrl: 'img/3.jpg',
        button: 'Add to Cart'
    },
    {
        id: 4,
        name: 'T-Shirt',
        price: '200.000 VND',
        imageUrl: 'img/4.jpg',
        button: 'Add to Cart'

    }
];

const product = document.getElementsByClassName("product");

let item = "";
let listItem = item  => {
    for (i = 0; i < listProducts.length; i++) {
    item += `
    <div class="product-item">
      <img src="${listProducts[i].imageUrl}" alt="ảnh" />
      <h2>${listProducts[i].name}</h2>
      <div><span>${listProducts[i].price}</span></div>
      <button class="btn">${listProducts[i].button}</button></div>`
    }
    return item
}

product[0].innerHTML = listItem();

let btnCart = document.getElementsByClassName('btn')
for (j = 0; j < listProducts.length; j++) {
    addEventListener('click', function() {
        this.document.querySelector('.listCart').append(item)

    })
</code>```

And this is my HTML Code

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        max-width: 350px;
        height: 350px;
        object-fit: contain;
      }
      .product {
        display: flex;
        justify-content: space-around;
      }
      .product-item {
        border: 1px solid;
        text-align: center;
      }
      h2 {
        border-top: 1px solid black;
        text-align: center;
        margin-top: 50px;
        padding-top: 20px;
      }
    </style>
  </head>
  <body>
    <div class="product"></div>
    <div class="cart">
      <div class="listCart">
        <h2>Cart</h2>
      </div>
    </div>
    <script src="bai10.js"></script>
  </body>
</html>

</code>```
```<code></code>```

I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:

I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:

Body:
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:

const listProducts = [
    {
        id: 1,
        name: 'Short Pant',
        price: '300.000 VND',
        imageUrl: 'img/1.jpg',
        button: 'Add to Cart'
    },
    {
        id: 2,
        name: 'Long Pant',
        price: '500.000 VND',
        imageUrl: 'img/2.jpg',
        button: 'Add to Cart'
    },
    {
        id: 3,
        name: 'Long Shirt',
        price: '400.000 VND',
        imageUrl: 'img/3.jpg',
        button: 'Add to Cart'
    },
    {
        id: 4,
        name: 'T-Shirt',
        price: '200.000 VND',
        imageUrl: 'img/4.jpg',
        button: 'Add to Cart'

    }
];

const product = document.getElementsByClassName("product");

let item = "";
let listItem = item  => {
    for (i = 0; i < listProducts.length; i++) {
    item += `

${listProducts[i].name}

${listProducts[i].price}

      <button class="btn">${listProducts[i].button}</button>
`
    }
    return item
}

product[0].innerHTML = listItem();

let btnCart = document.getElementsByClassName('btn')
for (j = 0; j < listProducts.length; j++) {
    addEventListener('click', function() {
        this.document.querySelector('.listCart').append(item)

    })

And this is my HTML Code

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

Cart

I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:

I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:


问:
DataCloneError: Failed to execute 'structuredClone' on 'Window': Symbol(react.element) could not be cloned
I want to make use of the structuredClone() function inside my react app.
its working in ubuntu but not in windows.</p>
```<code>flightnewDatas.push(structuredClone({ ...reslgs, traveller: travellerData, seatData: travandSeat, seatArray: reslgs?.seatArray ? reslgs?.seatArray : [], noOfSeatsSelected: 0 }))

</code>```
```<code>JSON.parse(JSON.stringify(flightnewDatas))
</code>```
```<code>const data = structuredClone(toRaw(flightnewDatas));
</code>```

Body:
I want to make use of the structuredClone() function inside my react app.
its working in ubuntu but not in windows.

flightnewDatas.push(structuredClone({ ...reslgs, traveller: travellerData, seatData: travandSeat, seatArray: reslgs?.seatArray ? reslgs?.seatArray : [], noOfSeatsSelected: 0 }))

JSON.parse(JSON.stringify(flightnewDatas))

const data = structuredClone(toRaw(flightnewDatas));


问:
How to get the Carrier Gateway ID with boto3?
As mentioned in the title, I need to get all carrier gateway ids in a specific VPC (I have the VPC ID). What can I do?

I have tried the describe_vpc function, but that one didn't work.


问:
Error build ipa from android studio, but work well on xcode
i need to build .ipa fila from flutter project on my Macbook.
I always get error when run build .ipa from android studio, but when i try on xcode it can success build and export .ipa file.

This is error log for that :

```<code>rahmad@Rahmads-MacBook-Air ios % flutter build ipa --flavor dev -t lib/main_dev.dart
Changing current working directory to: /Users/rahmad/work/mantra-flutter-enterprise

 Building with sound null safety

Archiving com.cdn.mantra.dev...
Automatically signing iOS for device deployment using specified development team in Xcode project: J8FAKZW
Running pod install...                                           2,147ms
Running Xcode build...
Xcode archive done.                                         37.3s
Failed to build iOS app
Error output from Xcode build:
↳
    ** ARCHIVE FAILED **

Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/flutter_tools.xjy4ef/flutter_ios_build_temp_dirpFWZuS/temporary_xcresult_bundle

    /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/SchemeScriptAction-GQ6JxC.sh: line 3: /.envfile: Read-only file system
    /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/SchemeScriptAction-GQ6JxC.sh: line 4: /.symlinks/plugins/flutter_config/ios/Classes/BuildXCConfig.rb: No such file or directory
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/TOCropViewController/Objective-C/TOCropViewController/TOCropViewController.m:87:14: warning: 'automaticallyAdjustsScrollViewInsets' is deprecated: first deprecated in iOS 11.0 - Use UIScrollView's contentInsetAdjustmentBehavior instead
    [-Wdeprecated-declarations]
            self.automaticallyAdjustsScrollViewInsets = NO;
                 ^
    In module 'UIKit' imported from /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/Target Support Files/TOCropViewController/TOCropViewController-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIViewController.h:260:34: note: 'automaticallyAdjustsScrollViewInsets' has been explicitly marked deprecated here
    @property(nonatomic,assign) BOOL automaticallyAdjustsScrollViewInsets API_DEPRECATED("Use UIScrollView's contentInsetAdjustmentBehavior instead", ios(7.0,11.0),tvos(7.0,11.0)); // Defaults to YES
                                     ^
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/TOCropViewController/Objective-C/TOCropViewController/TOCropViewController.m:1299:36: warning: 'topLayoutGuide' is deprecated: first deprecated in iOS 11.0 - Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor
    [-Wdeprecated-declarations]
                statusBarHeight = self.topLayoutGuide.length;
                                       ^
    In module 'UIKit' imported from /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/Target Support Files/TOCropViewController/TOCropViewController-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIViewController.h:505:58: note: 'topLayoutGuide' has been explicitly marked deprecated here
    @property(nonatomic,readonly,strong) id<UILayoutSupport> topLayoutGuide API_DEPRECATED("Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor", ios(7.0,11.0), tvos(7.0,11.0));
                                                             ^
    2 warnings generated.
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKPhotoGallery/DKPhotoGallery/DKPhotoGalleryContentVC.swift:39:52: warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    internal protocol DKPhotoGalleryContentDataSource: class {
                                                       ^~~~~
                                                       AnyObject
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKPhotoGallery/DKPhotoGallery/DKPhotoGalleryContentVC.swift:55:50: warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    internal protocol DKPhotoGalleryContentDelegate: class {
                                                     ^~~~~
                                                     AnyObject
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKPhotoGallery/DKPhotoGallery/DKPhotoGalleryContentVC.swift:107:14: warning: 'automaticallyAdjustsScrollViewInsets' was deprecated in iOS 11.0: Use UIScrollView's contentInsetAdjustmentBehavior instead
            self.automaticallyAdjustsScrollViewInsets = false
                 ^
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKImagePickerController/Sources/DKImagePickerController/View/DKAssetGroupDetailVC.swift:344:14: warning: 'frameInterval' was deprecated in iOS 10.0: preferredFramesPerSecond
            link.frameInterval = 1
                 ^
    /Users/rahmad/work/master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/file_picker-4.6.1/ios/Classes/FilePickerPlugin.m:357:1: warning: implementing deprecated method [-Wdeprecated-implementations]
    - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
    ^
    In module 'UIKit' imported from /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/Target Support Files/file_picker/file_picker-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIDocumentPickerViewController.h:27:1: note: method 'documentPicker:didPickDocumentAtURL:' declared here
    - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url API_DEPRECATED_WITH_REPLACEMENT("documentPicker:didPickDocumentsAtURLs:", ios(8.0, 11.0));
    ^
    1 warning generated.
    /Users/rahmad/work/master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/file_picker-4.6.1/ios/Classes/FileUtils.m:133:30: warning: unused variable 'exportError' [-Wunused-variable]
                        NSError *exportError = exporter.error;
                                 ^
    1 warning generated.
    ../master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core-2.4.0/lib/src/firebase_app.dart:18:25: Error: Member not found: 'FirebaseAppPlatform.verifyExtends'.
        FirebaseAppPlatform.verifyExtends(_delegate);
                            ^^^^^^^^^^^^^
    ../master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-14.2.0/lib/src/messaging.dart:128:22: Error: A value of type 'Future<bool>' can't be returned from a function with return type 'bool'.
     - 'Future' is from 'dart:async'.
        return _delegate.isSupported();
                         ^
    Failed to package /Users/rahmad/work/mantra-flutter-enterprise.
    Command PhaseScriptExecution failed with a nonzero exit code
    note: Building targets in dependency order
    warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target
    'Runner' from project 'Runner')
    warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in
    target 'Runner' from project 'Runner')
    warning: Run script build phase 'Copy GoogleInfoPlist' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase.
    (in target 'Runner' from project 'Runner')

    Result bundle written to path:
        /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/flutter_tools.xjy4ef/flutter_ios_build_temp_dirpFWZuS/temporary_xcresult_bundle

Uncategorized (Xcode): Exited with status code 127

Encountered error while archiving for device.
</code>```

I have 2 weeks for try solving this, but still not have solution.

I hope you can help me to build .ipa from android studio successfully.

Body:
i need to build .ipa fila from flutter project on my Macbook.
I always get error when run build .ipa from android studio, but when i try on xcode it can success build and export .ipa file.

This is error log for that :

rahmad@Rahmads-MacBook-Air ios % flutter build ipa --flavor dev -t lib/main_dev.dart
Changing current working directory to: /Users/rahmad/work/mantra-flutter-enterprise

 Building with sound null safety

Archiving com.cdn.mantra.dev...
Automatically signing iOS for device deployment using specified development team in Xcode project: J8FAKZW
Running pod install...                                           2,147ms
Running Xcode build...
Xcode archive done.                                         37.3s
Failed to build iOS app
Error output from Xcode build:
↳
    ** ARCHIVE FAILED **

Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/flutter_tools.xjy4ef/flutter_ios_build_temp_dirpFWZuS/temporary_xcresult_bundle

    /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/SchemeScriptAction-GQ6JxC.sh: line 3: /.envfile: Read-only file system
    /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/SchemeScriptAction-GQ6JxC.sh: line 4: /.symlinks/plugins/flutter_config/ios/Classes/BuildXCConfig.rb: No such file or directory
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/TOCropViewController/Objective-C/TOCropViewController/TOCropViewController.m:87:14: warning: 'automaticallyAdjustsScrollViewInsets' is deprecated: first deprecated in iOS 11.0 - Use UIScrollView's contentInsetAdjustmentBehavior instead
    [-Wdeprecated-declarations]
            self.automaticallyAdjustsScrollViewInsets = NO;
                 ^
    In module 'UIKit' imported from /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/Target Support Files/TOCropViewController/TOCropViewController-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIViewController.h:260:34: note: 'automaticallyAdjustsScrollViewInsets' has been explicitly marked deprecated here
    @property(nonatomic,assign) BOOL automaticallyAdjustsScrollViewInsets API_DEPRECATED("Use UIScrollView's contentInsetAdjustmentBehavior instead", ios(7.0,11.0),tvos(7.0,11.0)); // Defaults to YES
                                     ^
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/TOCropViewController/Objective-C/TOCropViewController/TOCropViewController.m:1299:36: warning: 'topLayoutGuide' is deprecated: first deprecated in iOS 11.0 - Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor
    [-Wdeprecated-declarations]
                statusBarHeight = self.topLayoutGuide.length;
                                       ^
    In module 'UIKit' imported from /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/Target Support Files/TOCropViewController/TOCropViewController-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIViewController.h:505:58: note: 'topLayoutGuide' has been explicitly marked deprecated here
    @property(nonatomic,readonly,strong) id<UILayoutSupport> topLayoutGuide API_DEPRECATED("Use view.safeAreaLayoutGuide.topAnchor instead of topLayoutGuide.bottomAnchor", ios(7.0,11.0), tvos(7.0,11.0));
                                                             ^
    2 warnings generated.
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKPhotoGallery/DKPhotoGallery/DKPhotoGalleryContentVC.swift:39:52: warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    internal protocol DKPhotoGalleryContentDataSource: class {
                                                       ^~~~~
                                                       AnyObject
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKPhotoGallery/DKPhotoGallery/DKPhotoGalleryContentVC.swift:55:50: warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
    internal protocol DKPhotoGalleryContentDelegate: class {
                                                     ^~~~~
                                                     AnyObject
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKPhotoGallery/DKPhotoGallery/DKPhotoGalleryContentVC.swift:107:14: warning: 'automaticallyAdjustsScrollViewInsets' was deprecated in iOS 11.0: Use UIScrollView's contentInsetAdjustmentBehavior instead
            self.automaticallyAdjustsScrollViewInsets = false
                 ^
    /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/DKImagePickerController/Sources/DKImagePickerController/View/DKAssetGroupDetailVC.swift:344:14: warning: 'frameInterval' was deprecated in iOS 10.0: preferredFramesPerSecond
            link.frameInterval = 1
                 ^
    /Users/rahmad/work/master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/file_picker-4.6.1/ios/Classes/FilePickerPlugin.m:357:1: warning: implementing deprecated method [-Wdeprecated-implementations]
    - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
    ^
    In module 'UIKit' imported from /Users/rahmad/work/mantra-flutter-enterprise/ios/Pods/Target Support Files/file_picker/file_picker-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIDocumentPickerViewController.h:27:1: note: method 'documentPicker:didPickDocumentAtURL:' declared here
    - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url API_DEPRECATED_WITH_REPLACEMENT("documentPicker:didPickDocumentsAtURLs:", ios(8.0, 11.0));
    ^
    1 warning generated.
    /Users/rahmad/work/master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/file_picker-4.6.1/ios/Classes/FileUtils.m:133:30: warning: unused variable 'exportError' [-Wunused-variable]
                        NSError *exportError = exporter.error;
                                 ^
    1 warning generated.
    ../master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core-2.4.0/lib/src/firebase_app.dart:18:25: Error: Member not found: 'FirebaseAppPlatform.verifyExtends'.
        FirebaseAppPlatform.verifyExtends(_delegate);
                            ^^^^^^^^^^^^^
    ../master/flutter3_0_0/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-14.2.0/lib/src/messaging.dart:128:22: Error: A value of type 'Future<bool>' can't be returned from a function with return type 'bool'.
     - 'Future' is from 'dart:async'.
        return _delegate.isSupported();
                         ^
    Failed to package /Users/rahmad/work/mantra-flutter-enterprise.
    Command PhaseScriptExecution failed with a nonzero exit code
    note: Building targets in dependency order
    warning: Run script build phase 'Run Script' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target
    'Runner' from project 'Runner')
    warning: Run script build phase 'Thin Binary' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in
    target 'Runner' from project 'Runner')
    warning: Run script build phase 'Copy GoogleInfoPlist' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase.
    (in target 'Runner' from project 'Runner')

    Result bundle written to path:
        /var/folders/kp/vm23k0rx5r7cwwn73dmdcs640000gn/T/flutter_tools.xjy4ef/flutter_ios_build_temp_dirpFWZuS/temporary_xcresult_bundle

Uncategorized (Xcode): Exited with status code 127

Encountered error while archiving for device.

I have 2 weeks for try solving this, but still not have solution.

I hope you can help me to build .ipa from android studio successfully.


问:
SonarQube - java custom rule - class not found
So little introduction.

I have been using this for learning -> https://github.com/SonarSource/sonar-java/blob/master/docs/CUSTOM_RULES_101.md

I created sonar docker instance from docker compose -> https://github.com/SonarSource/docker-sonarqube/blob/master/example-compose-files/sq-with-postgres/docker-compose.yml

I have created a very very simple rule. Here is a full source code (this rule is checking only for interfaces commenets):

```<code>@Rule(key = "PublicInterfaceWithJavaDocComments")
public class PublicInterfaceWithJavaDocComments extends BaseTreeVisitor implements JavaFileScanner {

    private JavaFileScannerContext context;

    @Override
    public void scanFile(JavaFileScannerContext context) {
        this.context = context;
        scan(context.getTree());
    }

    @Override
    public void visitClass(ClassTree tree) {
        if (tree.is(Tree.Kind.INTERFACE) && tree.symbol().isPublic()) {
            final Javadoc javadoc = new Javadoc(tree);
            if (tree.is(Tree.Kind.INTERFACE) && isDescriptionEmpty(javadoc)) {
                this.context.reportIssue(this, tree, "JavaDoc missing on public interface declaration.");
            }
            super.visitClass(tree);
        }

    }

    @Override
    public void visitMethod(MethodTree tree) {
        Javadoc javadoc = new Javadoc(tree);
        if (tree.is(Tree.Kind.METHOD) && javadoc.noMainDescription()) {
            this.context.reportIssue(this, tree, "JavaDoc missing on public interfaces methods declaration.");
        }
        super.visitMethod(tree);

    }

    public boolean isDescriptionEmpty(Javadoc javadoc) {
        return javadoc.noMainDescription(); // check if it returns true when description exists
    }

}
</code>```

So till this moment nothing ordinary - tests are passing its time to deploy this to sonar. So I run mvn package I have my jar file (which is pretty small 384 kb) I put it on $SONAR_HOME/extensions/plugins everything is perfect. I can see rule in sonar I activate it and now its time to test it.

I have sample gradle project so its not a big deal (Im on windows machine) - so I use command:

./gradlew sonar --stacktrace -D"sonar.projectKey=Test" -D"sonar.host.url=http://localhost:9000" -D"sonar.login=sqp_9b1a09f402459589aa3eeea6105e
9a3d86400c6d"

And here I have a issue:

Caused by: java.lang.ClassNotFoundException: org.sonar.java.checks.helpers.Javadoc

Looks like Sonar dont have this class ? What I have done wrong ?

Body:
So little introduction.

I have been using this for learning -> https://github.com/SonarSource/sonar-java/blob/master/docs/CUSTOM_RULES_101.md

I created sonar docker instance from docker compose -> https://github.com/SonarSource/docker-sonarqube/blob/master/example-compose-files/sq-with-postgres/docker-compose.yml

I have created a very very simple rule. Here is a full source code (this rule is checking only for interfaces commenets):

@Rule(key = "PublicInterfaceWithJavaDocComments")
public class PublicInterfaceWithJavaDocComments extends BaseTreeVisitor implements JavaFileScanner {

    private JavaFileScannerContext context;

    @Override
    public void scanFile(JavaFileScannerContext context) {
        this.context = context;
        scan(context.getTree());
    }

    @Override
    public void visitClass(ClassTree tree) {
        if (tree.is(Tree.Kind.INTERFACE) && tree.symbol().isPublic()) {
            final Javadoc javadoc = new Javadoc(tree);
            if (tree.is(Tree.Kind.INTERFACE) && isDescriptionEmpty(javadoc)) {
                this.context.reportIssue(this, tree, "JavaDoc missing on public interface declaration.");
            }
            super.visitClass(tree);
        }

    }

    @Override
    public void visitMethod(MethodTree tree) {
        Javadoc javadoc = new Javadoc(tree);
        if (tree.is(Tree.Kind.METHOD) && javadoc.noMainDescription()) {
            this.context.reportIssue(this, tree, "JavaDoc missing on public interfaces methods declaration.");
        }
        super.visitMethod(tree);

    }

    public boolean isDescriptionEmpty(Javadoc javadoc) {
        return javadoc.noMainDescription(); // check if it returns true when description exists
    }

}

So till this moment nothing ordinary - tests are passing its time to deploy this to sonar. So I run mvn package I have my jar file (which is pretty small 384 kb) I put it on $SONAR_HOME/extensions/plugins everything is perfect. I can see rule in sonar I activate it and now its time to test it.

I have sample gradle project so its not a big deal (Im on windows machine) - so I use command:

./gradlew sonar --stacktrace -D"sonar.projectKey=Test" -D"sonar.host.url=http://localhost:9000" -D"sonar.login=sqp_9b1a09f402459589aa3eeea6105e
9a3d86400c6d"

And here I have a issue:

Caused by: java.lang.ClassNotFoundException: org.sonar.java.checks.helpers.Javadoc

Looks like Sonar dont have this class ? What I have done wrong ?


问:
React Native - Recurrence rule UI for custom calendar
I'm trying to build a custom calendar that supports creating recurrent events. I need help with 2 things.

How to parse a recurrence rule and display UI

Generate a recurrence rule from the UI.

The web version of the mobile app is using Sync Fusion calendar which does the heavy lifting but unfortunately, there is no support for react native.

I tried searching for a library that generates UI from the recurrence rule and the recurrence rule itself from the UI(based on user actions). For the recurrence rule, I came across this JS library https://www.npmjs.com/package/rrule but I don't know how to achieve the above 2 using this.

Attached are the screens for defining recurrence.


问:
How to enqueue scripts properly in admin widgets wordpress?
I have made custom widgets, I am enqueuing woocommerce scripts like selectWoo, wc-enhance, select2, its enqueuing in DOM, but not working, probably scripts loading before DOM. Can Anybody help me out?</p>
```<code>if ( in_array( $screen_id, array( 'widgets' ) ) ) {
wp_enqueue_script( 'select2' );
wp_enqueue_script( 'selectWoo' );
wp_enqueue_script( 'wc-enhanced-select' );

}
</code>```

Body:
I have made custom widgets, I am enqueuing woocommerce scripts like selectWoo, wc-enhance, select2, its enqueuing in DOM, but not working, probably scripts loading before DOM. Can Anybody help me out?

if ( in_array( $screen_id, array( 'widgets' ) ) ) {
wp_enqueue_script( 'select2' );
wp_enqueue_script( 'selectWoo' );
wp_enqueue_script( 'wc-enhanced-select' );

}


问:
How to create sticky table header and Freeze first two Columns in HTML Table Using CSS3
I am facing the issue on MUI data table.
scroll should be use of browser for vertical and horizontal scroll we can use table. when i am using the browser scroll with freez two column and sticky header so header does not sticky with browser scroll if anybody have any solution please give me.

sticky header with freez column.


问:
Python Script executed from VBA not writting on excel
I'm using a Macro on Excel to run a python script. This Script reads some data from excel, makes some calculus and inserts the result in the same Excel.
When I run the python Script in cmd from windows, there is no problem.
However, when running the script from VBA it makes nothing.

This is the Python Script that I'm using:

```<code>from openpyxl import Workbook
from openpyxl import load_workbook

filesheet = input("ingrese nombre del archivo (extensión excel): ")
wb=Workbook()

wb = load_workbook(filesheet, data_only = True, keep_vba= True)
ws = wb["ESTADOS"]
ww = wb["SEÑALES"]

binario = str(ws["D27"].value)
print(binario)
hexa = hex(int(binario,2))
print(hexa)

filas = int(ww.max_row)

for x in range(2,filas+1):
    celda = str(ww.cell(row = x, column = 2).value)
    if celda == str("None") and hexa != 0:
        print(hexa)
        ww.cell(row = x, column=2).value = hexa
        hexa=0

</code>```

And this is the VBA code that I'm using:

```<code>Sub link_python()

Dim objShell As Object
Dim PythonExe As String
Dim PythonScript As Variant

Set objShell = VBA.CreateObject("Wscript.shell")

    'Provide the file path to the Python Exe
    PythonExe = """C:\Users\z004nxje\python.exe"""

    'Provide the file path to the Python script
    PythonScript = "C:\Users\z004nxje\SITRA\Script.py"

    'Run the Python script
    objShell.Run PythonExe & " " & PythonScript
    Application.Goto Reference:="link_python"

End Sub

</code>```

Anyone knows why it isn't writing on the Excel cells?
Thanks

Body:
I'm using a Macro on Excel to run a python script. This Script reads some data from excel, makes some calculus and inserts the result in the same Excel.
When I run the python Script in cmd from windows, there is no problem.
However, when running the script from VBA it makes nothing.

This is the Python Script that I'm using:

from openpyxl import Workbook
from openpyxl import load_workbook

filesheet = input("ingrese nombre del archivo (extensión excel): ")
wb=Workbook()

wb = load_workbook(filesheet, data_only = True, keep_vba= True)
ws = wb["ESTADOS"]
ww = wb["SEÑALES"]

binario = str(ws["D27"].value)
print(binario)
hexa = hex(int(binario,2))
print(hexa)

filas = int(ww.max_row)

for x in range(2,filas+1):
    celda = str(ww.cell(row = x, column = 2).value)
    if celda == str("None") and hexa != 0:
        print(hexa)
        ww.cell(row = x, column=2).value = hexa
        hexa=0

And this is the VBA code that I'm using:

Sub link_python()

Dim objShell As Object
Dim PythonExe As String
Dim PythonScript As Variant

Set objShell = VBA.CreateObject("Wscript.shell")

    'Provide the file path to the Python Exe
    PythonExe = """C:\Users\z004nxje\python.exe"""

    'Provide the file path to the Python script
    PythonScript = "C:\Users\z004nxje\SITRA\Script.py"

    'Run the Python script
    objShell.Run PythonExe & " " & PythonScript
    Application.Goto Reference:="link_python"

End Sub

Anyone knows why it isn't writing on the Excel cells?
Thanks


问:
trigger a function only once per user
I have an application where each user who has previously authenticated can access the index.html page with a button to trigger a time.sleep(t) function.
What I would like is that the same user cannot retrigger the function.

urls.py

```<code>from . import views
from django.contrib.auth.decorators import login_required
urlpatterns = [
    path('page1',  login_required(function=views.page1, login_url="login"), name="page1"),
]
</code>```

views.py

```<code>def page1(request):
    if(request.GET.get("arg")=="nap" and request.session.get("nap") == None):
            request.session["nap"] = True
            sleep(1, 5)
            request.session["nap"] = None
    return render(request, 'page1.html')

def sleep(t, n):
    for i in range(0,n):
        time.sleep(t)
        print(f"nap n°{i}")
</code>```

index.html

```<code><button type="button">
    <a href="{% url 'page1' %}?arg=nap"> NAP </a>
</button>
</code>```

Title: trigger a function only once per user

Body:
I have an application where each user who has previously authenticated can access the index.html page with a button to trigger a time.sleep(t) function.
What I would like is that the same user cannot retrigger the function.

urls.py

from . import views
from django.contrib.auth.decorators import login_required
urlpatterns = [
    path('page1',  login_required(function=views.page1, login_url="login"), name="page1"),
]

views.py

def page1(request):
    if(request.GET.get("arg")=="nap" and request.session.get("nap") == None):
            request.session["nap"] = True
            sleep(1, 5)
            request.session["nap"] = None
    return render(request, 'page1.html')

def sleep(t, n):
    for i in range(0,n):
        time.sleep(t)
        print(f"nap n°{i}")

index.html

<button type="button">
     NAP
</button>


问:
Android 11 : ANR Happening due to AudioPolicyService server died!. During VoIP call, while Audio routing from Bluetooth to Earpiece/Speaker
beginning of crash

TimeCheck  TimeCheck timeout for IAudioPolicyService command 6

Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 2268 (TimeCheckThread), pid 841 (audioserver)

A  pid: 841, tid: 2268, name: TimeCheckThread  >>> /system/bin/audioserver <<<

signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr --------

Abort message: 'TimeCheck timeout for IAudioPolicyService command 6'
x0  0000000000000000  x1  00000000000008dc  x2  0000000000000006  x3  0000006df5169530

MESSAGE_HANDLE_DISABLE_DELAYED: disabling:false

AudioFlinger server died!

AudioPolicyService server died!

Command failed for android_media_AudioSystem_error_callback: -32

Waiting for service 'media.audio_flinger' on '/dev/binder'...

TimeCheck timeout for IAudioPolicyService command 6
AudioPolicyService server died!
AudioFlinger server died!


问:
error: (-215:Assertion failed) sources.size() == modalities.size() in function 'cv::linemod::Detector::match'
```<code>import cv2
import matplotlib.pyplot as plt

template = cv2.imread('./light_t.jpg')
template = cv2.resize(template, (200, 200))
print(template.shape)
lineModDetector = cv2.linemod.getDefaultLINE()
print(len(lineModDetector.getModalities()))

mask = cv2.bitwise_not(template)[:,:,1]

ret, boundingBox = lineModDetector.addTemplate([template], "circle", mask)
print(ret)
print(boundingBox)

target = cv2.imread('../image/materias/light.jpg',)
target = cv2.resize( target, (200, 200))

results = lineModDetector.match(target, threshold=80)
</code>```

I got the following error when running this code:

```<code>error: (-215:Assertion failed) sources.size() == modalities.size() in function 'cv::linemod::Detector::match'
</code>```

I try to implement linemod using python

Body:
import cv2
import matplotlib.pyplot as plt

template = cv2.imread('./light_t.jpg')
template = cv2.resize(template, (200, 200))
print(template.shape)
lineModDetector = cv2.linemod.getDefaultLINE()
print(len(lineModDetector.getModalities()))

mask = cv2.bitwise_not(template)[:,:,1]

ret, boundingBox = lineModDetector.addTemplate([template], "circle", mask)
print(ret)
print(boundingBox)

target = cv2.imread('../image/materias/light.jpg',)
target = cv2.resize( target, (200, 200))

results = lineModDetector.match(target, threshold=80)

I got the following error when running this code:

error: (-215:Assertion failed) sources.size() == modalities.size() in function 'cv::linemod::Detector::match'

I try to implement linemod using python


问:
Multiple BottomSheet in one Screen in Jetpack Compose
As from ModalBottomSheetLayout doc we have to provide content. If i want to add multiple BottomSheet to a Screen i can't use multiple ModalBottomSheetLayout as same content have to pass multiple times and it will not work.

After searching i have found many are using multiple sheetContent in a single ModalBottomSheetLayout. Just like below way:

```<code>    sheetContent = {
        when (sheetContentState.value) {
            0 -> {
                BottomSheetFirstScreen()
            }
            1 -> {
                BottomSheetSecondScreen()
            }
        }
    }
</code>```

For me it become complex as different Sheet configuration using same code. I want to know is there any other better way to load multiple BottomSheet in a Screen.

How about using ModalBottomSheetLayout and BottomSheetScaffold in a single Screen. How to do that.

Thanks in advance.

Body:
As from ModalBottomSheetLayout doc we have to provide content. If i want to add multiple BottomSheet to a Screen i can't use multiple ModalBottomSheetLayout as same content have to pass multiple times and it will not work.

After searching i have found many are using multiple sheetContent in a single ModalBottomSheetLayout. Just like below way:

    sheetContent = {
        when (sheetContentState.value) {
            0 -> {
                BottomSheetFirstScreen()
            }
            1 -> {
                BottomSheetSecondScreen()
            }
        }
    }

For me it become complex as different Sheet configuration using same code. I want to know is there any other better way to load multiple BottomSheet in a Screen.

How about using ModalBottomSheetLayout and <a href="https://developer.android.com/reference/kotlin/androidx/compose/material/package-summary#BottomSheetScaffold(kotlin.Function1,androidx.compose.ui.Modifier,androidx.compose.material.BottomSheetScaffoldState,kotlin.Function0,kotlin.Function1,kotlin.Function0,androidx.compose.material.FabPosition,kotlin.Boolean,androidx.compose.ui.graphics.Shape,androidx.compose.ui.unit.Dp,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.unit.Dp,kotlin.Function1,kotlin.Boolean,androidx.compose.ui.graphics.Shape,androidx.compose.ui.unit.Dp,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,kotlin.Function1)" rel="nofollow noreferrer">BottomSheetScaffold in a single Screen. How to do that.

Thanks in advance.


问:
Mongodb : can't find a table mapping for namespace database.collection
I am trying to develop an android application withAndroid Studio in java and to insert data from a text entered in the application into the mongodb database, however, although the connection is carried out without problem the logs return me "Error:FUNCTION_EXECUTION_ERROR(realm::app::ServiceError:14): can't find a table mapping for namespace db.collec". I do however have a collection named collec in a db database.

Here is my code in java, do you know what is causing this

```<code>public void onClick(View v) {
    User user = app.currentUser();
    mongoClient = user.getMongoClient("mongodb-atlas");
    mongoDatabase = mongoClient.getDatabase("db");
    MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collec");

    mongoCollection.insertOne(new Document("userid",user.getId()).append("data",dataEditText.getText().toString())).getAsync(result -> {
        if(result.isSuccess())
        {
            Log.v("Data","Data Inserted Successfully");
        }
        else
        {
            Log.v("Data","Error:"+result.getError().toString());
        }
    });

</code>```

The error seems to be the same as here but I don't understand the resolution.

MongoDB Realm Functions on React Native

Body:
I am trying to develop an android application withAndroid Studio in java and to insert data from a text entered in the application into the mongodb database, however, although the connection is carried out without problem the logs return me "Error:FUNCTION_EXECUTION_ERROR(realm::app::ServiceError:14): can't find a table mapping for namespace db.collec". I do however have a collection named collec in a db database.

Here is my code in java, do you know what is causing this

public void onClick(View v) {
    User user = app.currentUser();
    mongoClient = user.getMongoClient("mongodb-atlas");
    mongoDatabase = mongoClient.getDatabase("db");
    MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collec");

    mongoCollection.insertOne(new Document("userid",user.getId()).append("data",dataEditText.getText().toString())).getAsync(result -> {
        if(result.isSuccess())
        {
            Log.v("Data","Data Inserted Successfully");
        }
        else
        {
            Log.v("Data","Error:"+result.getError().toString());
        }
    });

The error seems to be the same as here but I don't understand the resolution.

MongoDB Realm Functions on React Native


问:
Problems with characters remaining when unchecked
This is a builder-type site where invitations are completed when a customer enters a form.
There is a part where the customer put a typography, and even if I uncheck it, the text(typography) remains on the result screen.
Which part should I modify?</p>
```<code><div>
            <input
                id="typography-enable"
                type="checkbox"
                bind:checked={enableTypography}
                on:change={() => {
                    payload.typography = enableTypography ? {} : undefined;
                }}
            />
            <label for="typography-enable">메인 사진에 문구를 추가합니다.</label>
        </div>
        {#if enableTypography && typeof payload.typography !== "undefined"}
            <FlexTableLayout class="my-3" name="문구">
                <div>
                    <div class="mb-1">
                        <input
                            id="typography-content"
                            type="text"
                            maxlength={30}
                            bind:value={payload.typography.content}
                        />
                    </div>
</code>```

Body:
This is a builder-type site where invitations are completed when a customer enters a form.
There is a part where the customer put a typography, and even if I uncheck it, the text(typography) remains on the result screen.
Which part should I modify?

            <input
                id="typography-enable"
                type="checkbox"
                bind:checked={enableTypography}
                on:change={() => {
                    payload.typography = enableTypography ? {} : undefined;
                }}
            />
            메인 사진에 문구를 추가합니다.

        {#if enableTypography && typeof payload.typography !== "undefined"}
            <FlexTableLayout class="my-3" name="문구">

                        <input
                            id="typography-content"
                            type="text"
                            maxlength={30}
                            bind:value={payload.typography.content}
                        />


问:
EF Core expression tree FORMAT equivalent
I'm trying to build dynamic SQL queries using expression trees. I'm having issues implementing SQL Function FORMAT on datetime datatype. I would like to generate expression that would translate to the following SQL statement:

```<code>SELECT *
FROM ComputerUpdate
WHERE FORMAT(UpdatePerformed, 'dd/MM/yyyy, hh-mm-ss') LIKE '%15/12/%'
</code>```

I was able to dynamically generate LIKE part of SQL query, but I cannot find FORMAT equivalent.

I tried the following code:

```<code>var format_method = typeof(DateTime).GetMethod("ToString", new[] { typeof(string) });

return Expression.Call(
    Expression.PropertyOrField(parameter, prop.Name),
    format_method,
    Expression.Constant("dd/MM/yyyy, hh-mm-ss", typeof(string))
);
</code>```

However, this approach throws the following exception:

The LINQ expression 'DbSet().Where(o => o.UpdatePerformed.ToString("dd/MM/yyyy, hh-mm-ss").Contains("15/12/")' could not be translated. Additional information: Translation of method 'System.DateTime.ToString' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Another downside of this approach is that it does not work on nullable DateTime properties - in that case, the following exception was thrown:

Method 'System.String ToString(System.String)' declared on type 'System.DateTime' cannot be called with instance of type 'System.Nullable`1[System.DateTime]'

I am using EF Core 7.0

Body:
I'm trying to build dynamic SQL queries using expression trees. I'm having issues implementing SQL Function FORMAT on datetime datatype. I would like to generate expression that would translate to the following SQL statement:

SELECT *
FROM ComputerUpdate
WHERE FORMAT(UpdatePerformed, 'dd/MM/yyyy, hh-mm-ss') LIKE '%15/12/%'

I was able to dynamically generate LIKE part of SQL query, but I cannot find FORMAT equivalent.

I tried the following code:

var format_method = typeof(DateTime).GetMethod("ToString", new[] { typeof(string) });

return Expression.Call(
    Expression.PropertyOrField(parameter, prop.Name),
    format_method,
    Expression.Constant("dd/MM/yyyy, hh-mm-ss", typeof(string))
);

However, this approach throws the following exception:

The LINQ expression 'DbSet().Where(o => o.UpdatePerformed.ToString("dd/MM/yyyy, hh-mm-ss").Contains("15/12/")' could not be translated. Additional information: Translation of method 'System.DateTime.ToString' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Another downside of this approach is that it does not work on nullable DateTime properties - in that case, the following exception was thrown:

Method 'System.String ToString(System.String)' declared on type 'System.DateTime' cannot be called with instance of type 'System.Nullable`1[System.DateTime]'

I am using EF Core 7.0


问:
Store data from BroadcastChannel.onmessage in a variable
I need to fetch data from a dedicated worker, and store it inside other threads.

I'm trying to do it using the BroacastChannel API,but while I managed to get the data and console.log it in other threads, I can't store it in a variable.

I tried something like

```<code>var x = ""
channel.onmessage = function(event)=>{x = event.data}

</code>```

but while the x gets redefined inside the brackets, the x in the outer scope stays unchanged. (I purposefully tried var instead of let, to see if I could circumvent the scoping).

All of the examples I found either use the response to console.log, or store it in local storage or into an html element. Neither of these options are good for me: I need the data in a variable.

Body:
I need to fetch data from a dedicated worker, and store it inside other threads.

I'm trying to do it using the BroacastChannel API,but while I managed to get the data and console.log it in other threads, I can't store it in a variable.

I tried something like

var x = ""
channel.onmessage = function(event)=>{x = event.data}

but while the x gets redefined inside the brackets, the x in the outer scope stays unchanged. (I purposefully tried var instead of let, to see if I could circumvent the scoping).

All of the examples I found either use the response to console.log, or store it in local storage or into an html element. Neither of these options are good for me: I need the data in a variable.


问:
GraphQL Subscription with Async returns AttributeError: __aexit__
I'm trying to connect to a GraphQL subscription using Python + Asyncio + GQL Client

But whenever I try to subscribe in the background it fails out.

Whenever I use

       async with session.subscribe(

I get the error

    async with session.subscribe( AttributeError: __aexit__

Here's a sample of the code:

```<code>`async def main():
    transport = WebsocketsTransport(
        url='wss://myapi',
        headers={
            'Authorization':
            'Bearer '
        })
    async with Client(transport=transport,
                      fetch_schema_from_transport=True) as session:

        todays_matches = [1099628]

        goal_assists_params = {"matches_id": todays_matches}

        Match_Events_Subscription = gql(
            """my-graph-ql-query""")

        final_df_list = []

        # Start the subscription in a background task
        async with session.subscribe(
            Match_Events_Subscription,
            variable_values=goal_assists_params) as stats_subscription:
            subscription_task asyncio.create_task(stats_subscription)
            while True:
                # Wait for new data from the subscription
                stats = await stats_subscription.next()
                events = stats.get('live_match_event')
                df = pd.DataFrame(events)
                final_df_list.append(df)
                print(df)

                # Check the current time and exit the loop if the desired time has been reached
                current_time = datetime.datetime.now(datetime.timezone.utc)
                stop_time = datetime.datetime(
                    2022, 12, 25, 12, 0, 0, tzinfo=datetime.timezone.utc
                )  # Change this to the desired stop time
                if current_time >= stop_time:
                    break

        print(final_df_list)

asyncio.run(main())`
</code>```

Body:
I'm trying to connect to a GraphQL subscription using Python + Asyncio + GQL Client

But whenever I try to subscribe in the background it fails out.

Whenever I use

       async with session.subscribe(

I get the error

    async with session.subscribe( AttributeError: __aexit__

Here's a sample of the code:

`async def main():
    transport = WebsocketsTransport(
        url='wss://myapi',
        headers={
            'Authorization':
            'Bearer '
        })
    async with Client(transport=transport,
                      fetch_schema_from_transport=True) as session:

        todays_matches = [1099628]

        goal_assists_params = {"matches_id": todays_matches}

        Match_Events_Subscription = gql(
            """my-graph-ql-query""")

        final_df_list = []

        # Start the subscription in a background task
        async with session.subscribe(
            Match_Events_Subscription,
            variable_values=goal_assists_params) as stats_subscription:
            subscription_task asyncio.create_task(stats_subscription)
            while True:
                # Wait for new data from the subscription
                stats = await stats_subscription.next()
                events = stats.get('live_match_event')
                df = pd.DataFrame(events)
                final_df_list.append(df)
                print(df)

                # Check the current time and exit the loop if the desired time has been reached
                current_time = datetime.datetime.now(datetime.timezone.utc)
                stop_time = datetime.datetime(
                    2022, 12, 25, 12, 0, 0, tzinfo=datetime.timezone.utc
                )  # Change this to the desired stop time
                if current_time >= stop_time:
                    break

        print(final_df_list)

asyncio.run(main())`


问:
JSON in request payload is malformed Error
I am trying to use post curl command to insert json in db. But facing the issue as JSON in request payload is malformed. Can anyone please help me on this

Curl Command:

```<code>curl --location --request POST "https://localhost:1234/service" --header "Content-Type: application/json" --data-raw "{ \"modelId\": 9, \"languageCode\": \"no\", \"purpose\": \"NO_RECORD\", \"details\": [ { \"buttons\": [ { \"label\": \"ÅÅÅÅ\", \"value\": \"submit\", \"view\": \"NO_RECORDS\" } ] } ]}"
</code>```

Body:
I am trying to use post curl command to insert json in db. But facing the issue as JSON in request payload is malformed. Can anyone please help me on this

Curl Command:

curl --location --request POST "https://localhost:1234/service" --header "Content-Type: application/json" --data-raw "{ \"modelId\": 9, \"languageCode\": \"no\", \"purpose\": \"NO_RECORD\", \"details\": [ { \"buttons\": [ { \"label\": \"ÅÅÅÅ\", \"value\": \"submit\", \"view\": \"NO_RECORDS\" } ] } ]}"


问:
Securing quarkus application : how to prevent client redirection to auth form on unauthorized access to REST api endpoints
I have a Quarkus 2.15.1.Final application serving both static pages and REST endpoints (under /api path).

To secure this app, i have configured policies and roles and restricted access to both those resources.

When an unauthorized access is made against a protected static page, my quarkus app redirects the client to a authentication form (/login.html).

Also, when i manually send a request against one of my protected REST endpoint, Quarkus returns me this same redirection to the login form (302). In such case, i would expect Quarkus to just return me a 401 (Unauthorized), not a 200 along the login form (which by the way is not json but html content).

application.properties excerpt :

```<code># =============================================================================
# Http
# =============================================================================
quarkus.http.port=8089
quarkus.http.root-path=/
#quarkus.http.non-application-root-path=/

# =============================================================================
# Resteasy reactive jackson
# =============================================================================
quarkus.resteasy-reactive.path=/api
quarkus.jackson.serialization-inclusion=non-empty

# =============================================================================
# Security
# =============================================================================
quarkus.http.auth.form.enabled=true
quarkus.http.auth.form.login-page=/login.html
quarkus.http.auth.form.landing-page=/welcome.html
quarkus.http.auth.form.error-page=/login.html

quarkus.http.auth.policy.policy1.roles-allowed=user

quarkus.http.auth.permission.roles1.policy=policy1
quarkus.http.auth.permission.roles1.paths=/welcome.html,/assets/main*.js

quarkus.security.jaxrs.deny-unannotated-endpoints=true
</code>```

A protected (see the @Authenticated at class level) REST resource :

```<code>@Path("principal")
@Tag(name = "principal", description = "Internal API dedicated to currently authenticated principal infos retrieval")
@Authenticated
public class PrincipalController {

    public static final Logger LOGGER = LoggerFactory.getLogger(PrincipalController.class);

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Operation(summary = "Retrieve currently authenticated principal infos")
    @APIResponses(value = {
            @APIResponse(responseCode = "200", description = "Currently authenticated principal public infos") })
    public RestResponse<PrincipalInfosDTO> retrievePrincipalInfos(@Context SecurityContext securityContext) {
        return RestResponse.ok(PrincipalInfosDTO.builder().name(securityContext.getUserPrincipal().getName()).build());
    }
}
</code>```

If i naively try to specify a Accept : application/json header in the request towards the REST API endpoint, it has no effect and the redirection to the login form occurs.

I wonder if there is some way to specify that redirection to login form should not occur on certain circumstances, and that a simple 401 is then returned.

Body:
I have a Quarkus 2.15.1.Final application serving both static pages and REST endpoints (under /api path).

To secure this app, i have configured policies and roles and restricted access to both those resources.

When an unauthorized access is made against a protected static page, my quarkus app redirects the client to a authentication form (/login.html).

Also, when i manually send a request against one of my protected REST endpoint, Quarkus returns me this same redirection to the login form (302). In such case, i would expect Quarkus to just return me a 401 (Unauthorized), not a 200 along the login form (which by the way is not json but html content).

application.properties excerpt :

# =============================================================================
# Http
# =============================================================================
quarkus.http.port=8089
quarkus.http.root-path=/
#quarkus.http.non-application-root-path=/

# =============================================================================
# Resteasy reactive jackson
# =============================================================================
quarkus.resteasy-reactive.path=/api
quarkus.jackson.serialization-inclusion=non-empty

# =============================================================================
# Security
# =============================================================================
quarkus.http.auth.form.enabled=true
quarkus.http.auth.form.login-page=/login.html
quarkus.http.auth.form.landing-page=/welcome.html
quarkus.http.auth.form.error-page=/login.html

quarkus.http.auth.policy.policy1.roles-allowed=user

quarkus.http.auth.permission.roles1.policy=policy1
quarkus.http.auth.permission.roles1.paths=/welcome.html,/assets/main*.js

quarkus.security.jaxrs.deny-unannotated-endpoints=true

A protected (see the @Authenticated at class level) REST resource :

@Path("principal")
@Tag(name = "principal", description = "Internal API dedicated to currently authenticated principal infos retrieval")
@Authenticated
public class PrincipalController {

    public static final Logger LOGGER = LoggerFactory.getLogger(PrincipalController.class);

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Operation(summary = "Retrieve currently authenticated principal infos")
    @APIResponses(value = {
            @APIResponse(responseCode = "200", description = "Currently authenticated principal public infos") })
    public RestResponse<PrincipalInfosDTO> retrievePrincipalInfos(@Context SecurityContext securityContext) {
        return RestResponse.ok(PrincipalInfosDTO.builder().name(securityContext.getUserPrincipal().getName()).build());
    }
}

If i naively try to specify a Accept : application/json header in the request towards the REST API endpoint, it has no effect and the redirection to the login form occurs.

I wonder if there is some way to specify that redirection to login form should not occur on certain circumstances, and that a simple 401 is then returned.