问:
navigation property vs using left join
I have this linq statement where I want to convert into navigation property. The linq statement has a left join so I am not sure how to do that with the navigation property. I am using EF 6.0.0.0. I am trying to get all the MeetingPollingResponseTexts if there is values or nulls.</p>
```<code>MeetingPollingParticipantsAnswers = (from p in db.MeetingPollingParticipants
                                    join mp in db.MeetingPollings on p.MeetingPollingId equals mp.MeetingPollingId
                                    join pq in db.MeetingPollingQuestions on mp.MeetingPollingId equals pq.MeetingPollingId
                                    join pp in db.MeetingPollingParts on pq.MeetingPollingQuestionId equals pp.MeetingPollingQuestionId
                                    join pv in db.MeetingPollingPartsValues on pp.MeetingPollingPartsId equals pv.MeetingPollingPartsId
                                    join rt in db.MeetingPollingResponseTexts on pv.MeetingPollingPartsValuesId equals rt.MeetingPollingPartsValuesId into lj_rt
                                    from rt in lj_rt.DefaultIfEmpty()
                                    where p.MeetingPollingId == MeetingPollingId && p.CustomerId == CustomerId
                                    select new Model.MeetingPollingParticipantsAnswers
                                    {
                                        QuestionValue = pv.QuestionValue,
                                        MeetingPollingQuestionResponseText = rt.MeetingPollingQuestionResponseText,
                                    }).ToList();

   var meetingParticipantsAnswers = db.MeetingPollingParticipants
                            .Include(x => x.MeetingPolling)
                                    .Include(x => x.MeetingPollingQuestions
                                            .Select(q => q.MeetingPollingParts
                                            .Select(i => i.MeetingPollingPartsValues)))
                              .Where(p => p.CustomerId == CustomerId && p.MeetingPollingId == MeetingPollingId).ToList();
</code>```

Title: navigation property vs using left join

Body:
I have this linq statement where I want to convert into navigation property. The linq statement has a left join so I am not sure how to do that with the navigation property. I am using EF 6.0.0.0. I am trying to get all the MeetingPollingResponseTexts if there is values or nulls.

MeetingPollingParticipantsAnswers = (from p in db.MeetingPollingParticipants
                                    join mp in db.MeetingPollings on p.MeetingPollingId equals mp.MeetingPollingId
                                    join pq in db.MeetingPollingQuestions on mp.MeetingPollingId equals pq.MeetingPollingId
                                    join pp in db.MeetingPollingParts on pq.MeetingPollingQuestionId equals pp.MeetingPollingQuestionId
                                    join pv in db.MeetingPollingPartsValues on pp.MeetingPollingPartsId equals pv.MeetingPollingPartsId
                                    join rt in db.MeetingPollingResponseTexts on pv.MeetingPollingPartsValuesId equals rt.MeetingPollingPartsValuesId into lj_rt
                                    from rt in lj_rt.DefaultIfEmpty()
                                    where p.MeetingPollingId == MeetingPollingId && p.CustomerId == CustomerId
                                    select new Model.MeetingPollingParticipantsAnswers
                                    {
                                        QuestionValue = pv.QuestionValue,
                                        MeetingPollingQuestionResponseText = rt.MeetingPollingQuestionResponseText,
                                    }).ToList();

   var meetingParticipantsAnswers = db.MeetingPollingParticipants
                            .Include(x => x.MeetingPolling)
                                    .Include(x => x.MeetingPollingQuestions
                                            .Select(q => q.MeetingPollingParts
                                            .Select(i => i.MeetingPollingPartsValues)))
                              .Where(p => p.CustomerId == CustomerId && p.MeetingPollingId == MeetingPollingId).ToList();


来源: stackexchange

问:
What is the difference between rendering Vulkan graphics using GTK and rendering Vulkan graphics using Qt?
I am trying to choose between GTK+3 GdkVulkanContext and Qt QVulkanWindowRenderer for a project that requires the use of Vulkan for rendering graphics. What are the key differences between the two frameworks in terms of their support for and integration with Vulkan (GTK+3 will be manually translated in c++)? Are there any significant advantages or disadvantages to using one over the other in this context?</p>

ContentLicense: CC BY-SA 4.0


问:
Blazor: System.InvalidOperationException: Unable to resolve service for type 'DbContext' while attempting to activate FluentValidator
I'm trying to implement validation for Forms in Blazor WebAssembly. I've decided to use FluentValidation with Blazored.FluentValidation package, but I encountered a problem with validators that use DbContext, for example, to check if there is no other person in db with the given email, phoneNr, or personal ID.

Full Exception message

EmployeeValidator.cs

public class EmployeeValidator : AbstractValidator<EmployeeDto>
    {
        public EmployeeValidator(GymDbContext dbContext)
        {
            RuleFor(x => x.FirstName)
                .NotEmpty().WithMessage("Imię jest wymagane")
                .Length(2, 20).WithMessage("Imię musi zawierać od 2 do 20 znaków");

            RuleFor(x => x.LastName)
                .NotEmpty().WithMessage("Nazwisko jest wymagane")
                .Length(2, 20).WithMessage("Nazwisko musi zawierać od 2 do 20 znaków");

            RuleFor(x => x.PhoneNr)
                .NotEmpty().WithMessage("Numer telefonu jest wymagany")
                .Length(9, 9).WithMessage("Numer telefonu musi zawierać 9 cyfr")
                .Matches("^[0-9]*$").WithMessage("Numer telefonu może zawierać tylko cyfry")
                .Custom((value, context) =>
                {
                    var phoneNrInUse = dbContext.Person.Any(s => s.PhoneNr == value);
                    if (phoneNrInUse)
                    {
                        context.AddFailure("PhoneNr", "Podany Numer Telefonu jest w użyciu");
                    }
                });

            RuleFor(x => x.Email)
                .NotEmpty().WithMessage("Email jest wymagany")
                .EmailAddress().WithMessage("Email ma niepoprawny format")
                .Custom((value, context) =>
                {
                    var emailInUse = dbContext.Person.Any(s => s.Email == value);
                    if (emailInUse)
                    {
                        context.AddFailure("Email", "Podany Email jest w użyciu");
                    }
                });

            RuleFor(x => x.Pesel)
                .NotEmpty().WithMessage("Pesel jest wymagany")
                .Length(11, 11).WithMessage("Pesel musi zawierać 11 cyfr")
                .Matches("^[0-9]*$").WithMessage("Pesel może zawierać tylko cyfry")
                .Custom((value, context) =>
                {
                    var peselInDb = dbContext.Person.Any(s => s.Pesel == value);
                    if (peselInDb)
                    {
                        context.AddFailure("Pesel", "Podany pesel jest w użyciu");
                    }
                });

            RuleFor(x => x.Password)
                .NotEmpty().WithMessage("Hasło jest wymagane");

            RuleFor(x => x.ConfirmPassword)
                .Equal(x => x.Password).WithMessage("Hasło i potwierdzenie hasła są różne");

            RuleFor(x => x.Salary)
                .NotEmpty().WithMessage("Wynagrodzenie jest wymagane")
                .GreaterThan(0).WithMessage("Wynagrodzenie musi być liczbą dodatnią");
        }
    }
```
<p>EmployeeForm.razor</p>
```@page "/employeeAdd"
@page "/employeeForm/{FormMode}/{CurrentID}"
@using Projekt_Inzynierski.Core.DTOs;
@inject NavigationManager NavigationManager
@inject HttpClient _httpClient

Dane Pracownika

<EditForm Model="@employeeDto" OnValidSubmit=@OnValidSubmit>
    <FluentValidationValidator />

        <input for="Id" class="form-control" @bind="@employeeDto.Id" />

        Email:
        <InputText @bind-Value="@employeeDto.Email" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.Email)" />

        Hasło:
        <InputText @bind-Value="@employeeDto.Password" class="form-control" type="password" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.Password)" />

        Potwierdzenie hasła:
        <InputText @bind-Value="@employeeDto.ConfirmPassword" class="form-control" type="password" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.ConfirmPassword)" />

        Imię:
        <InputText @bind-Value="@employeeDto.FirstName" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.FirstName)" />

        Nazwisko:
        <InputText @bind-Value="@employeeDto.LastName" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.LastName)" />

        Numer tel.:
        <InputText @bind-Value="@employeeDto.PhoneNr" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.PhoneNr)" />

        Pesel:
        <InputText @bind-Value="@employeeDto.Pesel" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.Pesel)" />

        Wynagrodzenie:
        <InputNumber @bind-Value="@employeeDto.Salary" class="form-control" disabled="@isDisabled"></InputNumber>
        <ValidationMessage For="@(() => employeeDto.Salary)" />

        <input type="submit" class="btn btn-primary" value=@(FormMode != "edit" ? "Zapisz" : "Aktualizuj") />
        <input type="button" class="btn btn-primary" @onclick=@Cancel value="Anuluj" />

</EditForm>
@code {
    [Parameter]
    public string CurrentID { get; set; }
    [Parameter]
    public string FormMode { get; set; }

    EmployeeDto employeeDto = new EmployeeDto();
    bool isDisabled;

    protected override async Task OnInitializedAsync()
    {
        if (FormMode == "details")
        {
            isDisabled = true;
        }
        if (FormMode == "edit" || FormMode == "details")
        {
            var fetchedEmployee = await _httpClient.GetFromJsonAsync<EmployeeDto>($"api/employee/{CurrentID}");
            if (fetchedEmployee != null)
            {
                employeeDto = fetchedEmployee;
            }
        }

    }

    protected void OnValidSubmit()
    {
        if (FormMode != "edit")
        {
            CreateEmployee();
        }
        else
        {
            UpdateEmployee();
        }
    }

    protected async void CreateEmployee()
    {
        await _httpClient.PostAsJsonAsync("api/employee", employeeDto);
        NavigationManager.NavigateTo("employeeList");
    }

    protected async void UpdateEmployee()
    {
        await _httpClient.PutAsJsonAsync($"api/employee/{CurrentID}", employeeDto);
        NavigationManager.NavigateTo("employeeList");
    }

    void Cancel()
    {
        NavigationManager.NavigateTo("employeeList");
    }
}
```
<p>Program.cs - registering validators</p>
<pre class="lang-cs prettyprint-override"><code>
//Validation
builder.Services.AddFluentValidationAutoValidation(config =>
{
    config.DisableDataAnnotationsValidation = true;
})
    .AddValidatorsFromAssemblyContaining<EmployeeValidator>();
</code>```

If I remove the Custom Rules from the EmployeeValidator.cs file everything works fine but I need them
I searched the internet for a solution but did not find one. Is there other way to do this?

Body:
I'm trying to implement validation for Forms in Blazor WebAssembly. I've decided to use FluentValidation with Blazored.FluentValidation package, but I encountered a problem with validators that use DbContext, for example, to check if there is no other person in db with the given email, phoneNr, or personal ID.

Full Exception message

EmployeeValidator.cs

public class EmployeeValidator : AbstractValidator<EmployeeDto>
    {
        public EmployeeValidator(GymDbContext dbContext)
        {
            RuleFor(x => x.FirstName)
                .NotEmpty().WithMessage("Imię jest wymagane")
                .Length(2, 20).WithMessage("Imię musi zawierać od 2 do 20 znaków");

            RuleFor(x => x.LastName)
                .NotEmpty().WithMessage("Nazwisko jest wymagane")
                .Length(2, 20).WithMessage("Nazwisko musi zawierać od 2 do 20 znaków");

            RuleFor(x => x.PhoneNr)
                .NotEmpty().WithMessage("Numer telefonu jest wymagany")
                .Length(9, 9).WithMessage("Numer telefonu musi zawierać 9 cyfr")
                .Matches("^[0-9]*$").WithMessage("Numer telefonu może zawierać tylko cyfry")
                .Custom((value, context) =>
                {
                    var phoneNrInUse = dbContext.Person.Any(s => s.PhoneNr == value);
                    if (phoneNrInUse)
                    {
                        context.AddFailure("PhoneNr", "Podany Numer Telefonu jest w użyciu");
                    }
                });

            RuleFor(x => x.Email)
                .NotEmpty().WithMessage("Email jest wymagany")
                .EmailAddress().WithMessage("Email ma niepoprawny format")
                .Custom((value, context) =>
                {
                    var emailInUse = dbContext.Person.Any(s => s.Email == value);
                    if (emailInUse)
                    {
                        context.AddFailure("Email", "Podany Email jest w użyciu");
                    }
                });

            RuleFor(x => x.Pesel)
                .NotEmpty().WithMessage("Pesel jest wymagany")
                .Length(11, 11).WithMessage("Pesel musi zawierać 11 cyfr")
                .Matches("^[0-9]*$").WithMessage("Pesel może zawierać tylko cyfry")
                .Custom((value, context) =>
                {
                    var peselInDb = dbContext.Person.Any(s => s.Pesel == value);
                    if (peselInDb)
                    {
                        context.AddFailure("Pesel", "Podany pesel jest w użyciu");
                    }
                });

            RuleFor(x => x.Password)
                .NotEmpty().WithMessage("Hasło jest wymagane");

            RuleFor(x => x.ConfirmPassword)
                .Equal(x => x.Password).WithMessage("Hasło i potwierdzenie hasła są różne");

            RuleFor(x => x.Salary)
                .NotEmpty().WithMessage("Wynagrodzenie jest wymagane")
                .GreaterThan(0).WithMessage("Wynagrodzenie musi być liczbą dodatnią");
        }
    }

EmployeeForm.razor

@page "/employeeAdd"
@page "/employeeForm/{FormMode}/{CurrentID}"
@using Projekt_Inzynierski.Core.DTOs;
@inject NavigationManager NavigationManager
@inject HttpClient _httpClient

Dane Pracownika

<EditForm Model="@employeeDto" OnValidSubmit=@OnValidSubmit>
    <FluentValidationValidator />

        <input for="Id" class="form-control" @bind="@employeeDto.Id" />

        Email:
        <InputText @bind-Value="@employeeDto.Email" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.Email)" />

        Hasło:
        <InputText @bind-Value="@employeeDto.Password" class="form-control" type="password" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.Password)" />

        Potwierdzenie hasła:
        <InputText @bind-Value="@employeeDto.ConfirmPassword" class="form-control" type="password" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.ConfirmPassword)" />

        Imię:
        <InputText @bind-Value="@employeeDto.FirstName" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.FirstName)" />

        Nazwisko:
        <InputText @bind-Value="@employeeDto.LastName" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.LastName)" />

        Numer tel.:
        <InputText @bind-Value="@employeeDto.PhoneNr" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.PhoneNr)" />

        Pesel:
        <InputText @bind-Value="@employeeDto.Pesel" class="form-control" disabled="@isDisabled"></InputText>
        <ValidationMessage For="@(() => employeeDto.Pesel)" />

        Wynagrodzenie:
        <InputNumber @bind-Value="@employeeDto.Salary" class="form-control" disabled="@isDisabled"></InputNumber>
        <ValidationMessage For="@(() => employeeDto.Salary)" />

        <input type="submit" class="btn btn-primary" value=@(FormMode != "edit" ? "Zapisz" : "Aktualizuj") />
        <input type="button" class="btn btn-primary" @onclick=@Cancel value="Anuluj" />

</EditForm>
@code {
    [Parameter]
    public string CurrentID { get; set; }
    [Parameter]
    public string FormMode { get; set; }

    EmployeeDto employeeDto = new EmployeeDto();
    bool isDisabled;

    protected override async Task OnInitializedAsync()
    {
        if (FormMode == "details")
        {
            isDisabled = true;
        }
        if (FormMode == "edit" || FormMode == "details")
        {
            var fetchedEmployee = await _httpClient.GetFromJsonAsync<EmployeeDto>($"api/employee/{CurrentID}");
            if (fetchedEmployee != null)
            {
                employeeDto = fetchedEmployee;
            }
        }

    }

    protected void OnValidSubmit()
    {
        if (FormMode != "edit")
        {
            CreateEmployee();
        }
        else
        {
            UpdateEmployee();
        }
    }

    protected async void CreateEmployee()
    {
        await _httpClient.PostAsJsonAsync("api/employee", employeeDto);
        NavigationManager.NavigateTo("employeeList");
    }

    protected async void UpdateEmployee()
    {
        await _httpClient.PutAsJsonAsync($"api/employee/{CurrentID}", employeeDto);
        NavigationManager.NavigateTo("employeeList");
    }

    void Cancel()
    {
        NavigationManager.NavigateTo("employeeList");
    }
}

Program.cs - registering validators

//Validation
builder.Services.AddFluentValidationAutoValidation(config =>
{
    config.DisableDataAnnotationsValidation = true;
})
    .AddValidatorsFromAssemblyContaining<EmployeeValidator>();

If I remove the Custom Rules from the EmployeeValidator.cs file everything works fine but I need them
I searched the internet for a solution but did not find one. Is there other way to do this?


问:
Multiple of values from different divs with the same class
I am loading dynamically divs that have a some class. At the end, I would like to multiple of the values from all of the class.

there is a code

```<code>$(document).ready(function(){
   $('.show-tip').click(function(e) {
    $(this.parentElement.parentElement.querySelector(".tip-kurz")).appendTo( "#betbuilder" );
    var multiple = 0;
$('#betbuilder .tip-kurz').each(function()
{
    multiple += Number($(this).text());
});
document.querySelector(".course").innerHTML = multiple;
});
</code>```

i tried everything, but nothing works

Body:
I am loading dynamically divs that have a some class. At the end, I would like to multiple of the values from all of the class.

there is a code

$(document).ready(function(){
   $('.show-tip').click(function(e) {
    $(this.parentElement.parentElement.querySelector(".tip-kurz")).appendTo( "#betbuilder" );
    var multiple = 0;
$('#betbuilder .tip-kurz').each(function()
{
    multiple += Number($(this).text());
});
document.querySelector(".course").innerHTML = multiple;
});

i tried everything, but nothing works


问:
Generating a Python datetime from String
I have a date formated like this: "Thu Jan 05 17:42:26 MST 2023" and need to change it to be formated like this: "2023-01-06T04:58:00Z".

I thought this would be really easy. Parse the date with datetime.datetime.strptime(), adjust the timezone with datetime.datetime.astimezone(pytz.utc) and output it with datetime.datetime.strftime().

On my machine running Python 3.10 it is that simple. Even though strptime discards timezone, astimezone(pytz.utc) still works for some reason and outputs the correct time format.

On the server, running Python 2.7 it throws "ValueError: astimezone() requires an aware datetime". So I slice the timezone out of the initial string and localize the datetime. Works great except pytz.timezone() cannot parse daylight savings timezones like MDT. I know there is a parameter for DST but then I have to manually parse the timezone string to figure out DST.

The only way I have gotten this work work properly is by making a dictionary of every timezone and their offsets, parsing the intial string into a epoch timestamp, applying the offset, then formatting back into my desired string.

What am I doing wrong? Why is this so insanely difficult?

```<code># Works fine on Python 3.10 but returns error on Python 2.7
def _formatTimestamp1(timestamp):
    local_dt = datetime.strptime(str(timestamp), '%a %b %d %H:%M:%S %Z %Y')
    utc_dt = local_dt.astimezone(pytz.utc)
    fmt_dt = utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return str(fmt_dt)

# Works good but pytz.timezone() cannot handle paring DST times like 'MDT'
def _formatTimestamp2(timestamp):
    local_dt = datetime.strptime(str(timestamp), '%a %b %d %H:%M:%S %Z %Y')
    timezone = pytz.timezone(timestamp[20:-5])
    aware = timezone.localize(local_dt)
    utc_dt = aware.astimezone(pytz.utc)
    fmt_dt = utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return str(fmt_dt)

# So far this is the best method, but requires building a timezone database
def _formatTimestamp3(timestamp):
    tz_dict = {"MST":-7,"MDT":-6}
    local_dt = datetime.strptime(str(timestamp), '%a %b %d %H:%M:%S %Z %Y')
    utc_dt = datetime.fromtimestamp(local_dt.timestamp() - tz_dict[timestamp[20:-5]] * 60 * 60)
    fmt_dt = utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return str(fmt_dt)
</code>```

Body:
I have a date formated like this: "Thu Jan 05 17:42:26 MST 2023" and need to change it to be formated like this: "2023-01-06T04:58:00Z".

I thought this would be really easy. Parse the date with datetime.datetime.strptime(), adjust the timezone with datetime.datetime.astimezone(pytz.utc) and output it with datetime.datetime.strftime().

On my machine running Python 3.10 it is that simple. Even though strptime discards timezone, astimezone(pytz.utc) still works for some reason and outputs the correct time format.

On the server, running Python 2.7 it throws "ValueError: astimezone() requires an aware datetime". So I slice the timezone out of the initial string and localize the datetime. Works great except pytz.timezone() cannot parse daylight savings timezones like MDT. I know there is a parameter for DST but then I have to manually parse the timezone string to figure out DST.

The only way I have gotten this work work properly is by making a dictionary of every timezone and their offsets, parsing the intial string into a epoch timestamp, applying the offset, then formatting back into my desired string.

What am I doing wrong? Why is this so insanely difficult?

# Works fine on Python 3.10 but returns error on Python 2.7
def _formatTimestamp1(timestamp):
    local_dt = datetime.strptime(str(timestamp), '%a %b %d %H:%M:%S %Z %Y')
    utc_dt = local_dt.astimezone(pytz.utc)
    fmt_dt = utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return str(fmt_dt)

# Works good but pytz.timezone() cannot handle paring DST times like 'MDT'
def _formatTimestamp2(timestamp):
    local_dt = datetime.strptime(str(timestamp), '%a %b %d %H:%M:%S %Z %Y')
    timezone = pytz.timezone(timestamp[20:-5])
    aware = timezone.localize(local_dt)
    utc_dt = aware.astimezone(pytz.utc)
    fmt_dt = utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return str(fmt_dt)

# So far this is the best method, but requires building a timezone database
def _formatTimestamp3(timestamp):
    tz_dict = {"MST":-7,"MDT":-6}
    local_dt = datetime.strptime(str(timestamp), '%a %b %d %H:%M:%S %Z %Y')
    utc_dt = datetime.fromtimestamp(local_dt.timestamp() - tz_dict[timestamp[20:-5]] * 60 * 60)
    fmt_dt = utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return str(fmt_dt)


问:
How do I hide/remove year from datetime query
I want to return month - day from my date column. It is set to Datetime format.

I have tried DATENAME, DATEPART, month, day, and year and all of them give me a singular response. I'd like to keep the month and day in the same column. If not I'll find a workaround.

2022-01-09

01-09

```<code>Select Cast(created_date as date)Date,
    [Name],
    count(Name)Total,
    Cast(Sum([Total_Tax_Exclusive_Price])as Decimal(18,2))Revenue
From DBO.Receipts
Where [name] Like 'Smartfruit Smoothie%'
and [Created_Date] between '2022-09-15' and '2022-12-20'
Group by Cast(created_date as date),Name
</code>```

This query returns

```<code>Date      |        Name     | Count|Revenue
2022-09-15  Smartfruit Smoothie 10  46.75
2022-09-16  Smartfruit Smoothie 3   14.00
2022-09-17  Smartfruit Smoothie 14  64.75
2022-09-19  Smartfruit Smoothie 10  49.00
2022-09-20  Smartfruit Smoothie 6   29.50
2022-09-21  Smartfruit Smoothie 14  69.75
</code>```

Body:
I want to return month - day from my date column. It is set to Datetime format.

I have tried DATENAME, DATEPART, month, day, and year and all of them give me a singular response. I'd like to keep the month and day in the same column. If not I'll find a workaround.

2022-01-09

01-09

Select Cast(created_date as date)Date,
    [Name],
    count(Name)Total,
    Cast(Sum([Total_Tax_Exclusive_Price])as Decimal(18,2))Revenue
From DBO.Receipts
Where [name] Like 'Smartfruit Smoothie%'
and [Created_Date] between '2022-09-15' and '2022-12-20'
Group by Cast(created_date as date),Name

This query returns

Date      |        Name     | Count|Revenue
2022-09-15  Smartfruit Smoothie 10  46.75
2022-09-16  Smartfruit Smoothie 3   14.00
2022-09-17  Smartfruit Smoothie 14  64.75
2022-09-19  Smartfruit Smoothie 10  49.00
2022-09-20  Smartfruit Smoothie 6   29.50
2022-09-21  Smartfruit Smoothie 14  69.75


问:
Create HTML file of a generated PDF file (fpdf2) using Python
I am trying to create an HTML file of a PDF output generated by fpdf2 using Python packages. My code for creating the PDF is the following, which saves the PDF in my local disk:

```<code>from fpdf import FPDF
pdf = FPDF()
####my code for putting content (text, image, table) in the pdf
pdf.output(file_savingpath, "F")
</code>```

Does anyone have a minimal working solution to create an automated HTML file creation solution using Python 3.x?

Best,

Debayan

Body:
I am trying to create an HTML file of a PDF output generated by fpdf2 using Python packages. My code for creating the PDF is the following, which saves the PDF in my local disk:

from fpdf import FPDF
pdf = FPDF()
####my code for putting content (text, image, table) in the pdf
pdf.output(file_savingpath, "F")

Does anyone have a minimal working solution to create an automated HTML file creation solution using Python 3.x?

Best,

Debayan


问:
Using loadFont() function to load *.ttf from directory
I am having the following folder structure:

I am using the following p5js library:

```<code>    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>
</code>```

I am trying to load my font using the following:

```<code>let myFont;
function preload() {
  // var myFont = loadFont('Abel-Regular.ttf');
  myFont = loadFont("fonts/NotoSerifArmenian-Thin.ttf");
}
</code>```

However I get as error:

```<code>Font could not be loaded fonts/NotoSerifArmenian-Thin.ttf
cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js:11
</code>```

Any suggestions what I am doing wrong?

I appreciate your replies!

Body:
I am having the following folder structure:

I am using the following p5js library:

I am trying to load my font using the following:

let myFont;
function preload() {
  // var myFont = loadFont('Abel-Regular.ttf');
  myFont = loadFont("fonts/NotoSerifArmenian-Thin.ttf");
}

However I get as error:

Font could not be loaded fonts/NotoSerifArmenian-Thin.ttf
cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js:11

Any suggestions what I am doing wrong?

I appreciate your replies!


问:
Resuming merge conflict resolution in a remote repository
Following on from GitHub subtree merge requests, I've been pondering whether a merge conflict that arises during a(n automated) git subtree pull could easily be "stored" somewhere in order that it can later be "resumed" on a different (manual) copy of the repo.

From git stash during a merge conflict, I gather that a merge conflict can (with a little tweaking) be stashed and resumed in the same repo; and from How can I share a git stash?, I gather that a stash can be shared with a remote repo as a regular commit... but the former requires git stash pop's --index flag in order to restore an index state that differs from that of the working set, whereas the latter would entail a git checkout of the remote stash's ref that results in an index that is aligned with the working set.  I'm not even sure whether pushing a stash as a regular ref would retain such distinct information for the two data structures?

Is there any way that merge conflict resolution can be resumed in another/remote copy of the repo?


问:
Why Does URL Redirect Add Parameters to Root Directory of Destination DomainURL?
[Edit] is there anything I can add to my question so that I can get assistance?

Please help me work this out.

I am trying to use a web.config redirect from a dynamic page on one domain to a static page on a new domain.  Here is the code I'm trying  (I've tried many other variations too without success):

```<code>    <rule name="69" stopProcessing="true">
    <match url="^product-details.php?aaaaa=B086RX7LW1&bbbbb=Moleskine%20Cover%20XL" />
   <action type="Redirect" url="https://www.leatherjournals.com/collections/notebook-leather-covers/products/leather-refillable-journal-cover-for-moleskine-cahier?
   variant=42204410183930" redirectType="Permanent" />
   </rule>
</code>```

So the page should redirect to:

https://www.leatherjournals.com/collections/notebook-leather-covers/products/leather-refillable-journal-cover-for-moleskine-cahier?variant=42204410183930

But it actually redirects to

https://www.leatherjournals.com?aaaaa=B086RX7LW1&bbbbb=Moleskine%20Cover%20XL

That page shouldn't have parameters.  The root page is shown instead with the parameters added to the url (it is a full url, the 'bbbbb=' doesn't show properly in my question).

Any advice please?  Thanks in advance.

Body:
[Edit] is there anything I can add to my question so that I can get assistance?

Please help me work this out.

I am trying to use a web.config redirect from a dynamic page on one domain to a static page on a new domain.  Here is the code I'm trying  (I've tried many other variations too without success):

    <rule name="69" stopProcessing="true">
    <match url="^product-details.php?aaaaa=B086RX7LW1&bbbbb=Moleskine%20Cover%20XL" />
   <action type="Redirect" url="https://www.leatherjournals.com/collections/notebook-leather-covers/products/leather-refillable-journal-cover-for-moleskine-cahier?
   variant=42204410183930" redirectType="Permanent" />
   </rule>

So the page should redirect to:

https://www.leatherjournals.com/collections/notebook-leather-covers/products/leather-refillable-journal-cover-for-moleskine-cahier?variant=42204410183930

But it actually redirects to

https://www.leatherjournals.com?aaaaa=B086RX7LW1&bbbbb=Moleskine%20Cover%20XL

That page shouldn't have parameters.  The root page is shown instead with the parameters added to the url (it is a full url, the 'bbbbb=' doesn't show properly in my question).

Any advice please?  Thanks in advance.


问:
Mail Session fails in Tomee Server
I can send an email via a simple Java programme but if I use exactly the same settings to create Java Mail Session resource in Tomee's conf/tomee.xml file, the code fails:

Here is the simple Java code that WORKS:

```<code>public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable","true");
        // smtp.gmail.com supports TLSv1.2 and TLSv1.3
        // smtp.office365.com supports only TLSv1.2
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        props.put("mail.smtp.host", "smtp.privateemail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("<valid email>", "<valid password>");
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(<valid email>));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(<valid recipient email>));
            message.setSubject("You got mail");
            message.setText("This email was sent with JavaMail.");
            Transport.send(message);
            System.out.println("Email sent.");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
</code>```

However, if I try to configure the same properties in Tomee's conf/tomee.xml file, nothing works and the application throws an error:

```<code>Send failure (javax.mail.AuthenticationFailedException: null)
</code>```

Here is the configuration in conf/tomee.xml

```<code><Resource id="mail/bjm" type="javax.mail.Session">
        mail.smtp.host=smtp.privateemail.com
        mail.smtp.port=587
        mail.transport.protocol=smtp
        mail.smtp.auth=true
        ail.smtp.starttls.enable=true
        mail.smtp.ssl.protocols=TLSv1.2
        mail.smtp.user=<valid email>
        password=<valid password>
</Resource>
</code>```

The configuration settings were copied from the Tomee docs that DOES NOT WORK.

And finally here is my Java/EE code that uses this resource in vain:

```<code>@Resource(name = "mail/bjm")
Session session;
...
...
MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(<valid email>));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(<valid recipient email>));

</code>```

Would be grateful if someone can shed some light on the issue.

Many Thanks

Title: Mail Session fails in Tomee Server

Body:
I can send an email via a simple Java programme but if I use exactly the same settings to create Java Mail Session resource in Tomee's conf/tomee.xml file, the code fails:

Here is the simple Java code that WORKS:

public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable","true");
        // smtp.gmail.com supports TLSv1.2 and TLSv1.3
        // smtp.office365.com supports only TLSv1.2
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        props.put("mail.smtp.host", "smtp.privateemail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("<valid email>", "<valid password>");
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(<valid email>));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(<valid recipient email>));
            message.setSubject("You got mail");
            message.setText("This email was sent with JavaMail.");
            Transport.send(message);
            System.out.println("Email sent.");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

However, if I try to configure the same properties in Tomee's conf/tomee.xml file, nothing works and the application throws an error:

Send failure (javax.mail.AuthenticationFailedException: null)

Here is the configuration in conf/tomee.xml

<Resource id="mail/bjm" type="javax.mail.Session">
        mail.smtp.host=smtp.privateemail.com
        mail.smtp.port=587
        mail.transport.protocol=smtp
        mail.smtp.auth=true
        ail.smtp.starttls.enable=true
        mail.smtp.ssl.protocols=TLSv1.2
        mail.smtp.user=<valid email>
        password=<valid password>
</Resource>

The configuration settings were copied from the Tomee docs that DOES NOT WORK.

And finally here is my Java/EE code that uses this resource in vain:

@Resource(name = "mail/bjm")
Session session;
...
...
MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(<valid email>));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(<valid recipient email>));

Would be grateful if someone can shed some light on the issue.

Many Thanks


问:
text field length taking complete screen width
I have a text field (mui) inside a div and the text field opens up on clicking an edit icon. Div has some content and has a display: flex. I want the text field to take the complete screen width in mobile view irrespective of div length.

How to do this. Please help.

I have tried width:100% in div and tried overriding mui width. Cannot use VW.

Tried adding a new class with a width of 100%. Cannot add width in px.


问:
How to write the excel logic to power bi
How to add the measure value to the next row measure .

Excel logic

```<code>IF ( Forecast - ABS(Pervoiusmonth measure value) - sdoue , Forecast - ABS(Pervoiusmonth measure value) - sodue , 0 )
</code>```

(Pervoiusmonth measure value) - how to write in the power bi

What the above excel logic to power bi

Body:
How to add the measure value to the next row measure .

Excel logic

IF ( Forecast - ABS(Pervoiusmonth measure value) - sdoue , Forecast - ABS(Pervoiusmonth measure value) - sodue , 0 )

(Pervoiusmonth measure value) - how to write in the power bi

What the above excel logic to power bi


问:
How to use Import Report API in Power BI
https://learn.microsoft.com/en-us/rest/api/power-bi/imports/post-import-in-group is what I am trying to implement in PowerShell to publish a local report to Power BI Service. When I try this API it shows 400 Bad Request error.</p>
```<code>$accessToken = Get-AccessToken -ClientId "{client_id}" -ClientSecret "{client_secret}"

$headers = @{
    "Authorization" = "Bearer $accessToken"
}

$boundary = [System.Guid]::NewGuid().ToString()
$headers.Add("Content-Type", "multipart/form-data; boundary=$boundary")

$body = @"
--$boundary
Content-Disposition: form-data; name=`"file`"; filename=`"report.pbix`"
Content-Type: application/octet-stream
--$boundary--
"@

$response = Invoke-RestMethod -Method Post -Uri "https://api.powerbi.com/v1.0/myorg/imports" -Headers $headers -Body $body

</code>```

Body:
https://learn.microsoft.com/en-us/rest/api/power-bi/imports/post-import-in-group is what I am trying to implement in PowerShell to publish a local report to Power BI Service. When I try this API it shows 400 Bad Request error.

$accessToken = Get-AccessToken -ClientId "{client_id}" -ClientSecret "{client_secret}"

$headers = @{
    "Authorization" = "Bearer $accessToken"
}

$boundary = [System.Guid]::NewGuid().ToString()
$headers.Add("Content-Type", "multipart/form-data; boundary=$boundary")

$body = @"
--$boundary
Content-Disposition: form-data; name=`"file`"; filename=`"report.pbix`"
Content-Type: application/octet-stream
--$boundary--
"@

$response = Invoke-RestMethod -Method Post -Uri "https://api.powerbi.com/v1.0/myorg/imports" -Headers $headers -Body $body


问:
Vue 3 basic website not work on webOS LG TV
I have basic vue3 website, that works on every platform, except webOS LG TV, the page cannot loaded. Loaded only favicon and meta title.

Dont know where is problem. Thank you for advice

I tried this -  https://cli.vuejs.org/guide/browser-compatibility.html.


问:
Unable to call ModelBinders in Program.cs file
why ModelBinders.Binders.Add(typeof(string), new TrimModelBinder()); is not getting run? my input value still have extra space. I just want to trim some input field when OnPost() / OnGet() gets called

Program.cs

```<code>var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
...
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

    ModelBinders.Binders.Add(typeof(string), new TrimModelBinder());

    app.UseHsts();
 }

 app.UseHttpsRedirection();
</code>```

TrimModelBinder class

```<code>public class TrimModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled;
        var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;

        var value = unvalidatedValueProvider == null ?
          bindingContext.ValueProvider.GetValue(bindingContext.ModelName) :
          unvalidatedValueProvider.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation);

        var attemptedValue = value?.AttemptedValue;

        return string.IsNullOrWhiteSpace(attemptedValue) ? attemptedValue : attemptedValue.Trim();
    }
}
</code>```

Body:
why ModelBinders.Binders.Add(typeof(string), new TrimModelBinder()); is not getting run? my input value still have extra space. I just want to trim some input field when OnPost() / OnGet() gets called

Program.cs

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
...
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

    ModelBinders.Binders.Add(typeof(string), new TrimModelBinder());

    app.UseHsts();
 }

 app.UseHttpsRedirection();

TrimModelBinder class

public class TrimModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled;
        var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;

        var value = unvalidatedValueProvider == null ?
          bindingContext.ValueProvider.GetValue(bindingContext.ModelName) :
          unvalidatedValueProvider.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation);

        var attemptedValue = value?.AttemptedValue;

        return string.IsNullOrWhiteSpace(attemptedValue) ? attemptedValue : attemptedValue.Trim();
    }
}


问:
Transform RGB color space to LMS color space
So I have been trying to convert an RGB color space to LMS space, apply certain color filters and then back to RGB space. Works fine with OpenCV and on images.

Now, I need to apply such color filters on a Qt application or the elements in the application. I found the QColorSpace and QColorTransform in Qt Graphical Effects module but these have no examples as such.

So my question is, if I have a Qt application that displays a rectangle with a few colors in it, then how can I apply a color filter on this application which would make the rectangle with the same colors look different because of the color filter?

If the color filter cannot be applied on the whole application, then is it possible to apply it on only the rectangle?

I understand that such a filter needs to be programmed in the shader somehow. But I am not sure how to do this.

Any examples explaining this in Qt would be great.


问:
How to request access to files in a webview app?
I found an example of a webview app opening a link inside itself, everything works. My problem is that on this site you need to upload images, and for this you need access. When you try to click on the select images button, nothing happens, I think because the application does not have access to the device files.

How do I do this on (the first?) when launching the application, was access to the gallery or files of the smartphone requested so that the selection button in the webview worked? This is only for the Android system.

My "home_page" files (the link opens the website to resize the image)

```<code>import 'package:flutter/material.dart';
import 'my_webview.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home Page"),
      ),
      body: Center(
        child: FlatButton(
          child: Text("Open Webpage"),
          onPressed: () {
             Navigator.of(context).push(MaterialPageRoute(
              builder: (BuildContext context) => MyWebView(
                title: "resize-image",
                selectedUrl: "https://www.iloveimg.com/resize-image",
              )
            ));
          },
        ),
      ),
    );
  }
}
</code>```

My "main" files

```<code>import 'package:flutter/material.dart';
import 'home_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}
</code>```

My "my_webview" files

```<code>import 'dart:async';

    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';

    class MyWebView extends StatelessWidget {
      final String title;
      final String selectedUrl;

      final Completer<WebViewController> _controller = Completer<WebViewController>();

      MyWebView({
        required this.title,
        required this.selectedUrl,
      });

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(title),
          ),
          body: WebView(
            initialUrl: selectedUrl,
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _controller.complete(webViewController);
            },
          ));
      }
    }
</code>```

and dependencies in pubspec.yaml

```<code>  dependencies:
      flutter:
        sdk: flutter
      webview_flutter: ^3.0.4
      permission_handler: ^10.2.0
</code>```

Body:
I found an example of a webview app opening a link inside itself, everything works. My problem is that on this site you need to upload images, and for this you need access. When you try to click on the select images button, nothing happens, I think because the application does not have access to the device files.

How do I do this on (the first?) when launching the application, was access to the gallery or files of the smartphone requested so that the selection button in the webview worked? This is only for the Android system.

My "home_page" files (the link opens the website to resize the image)

import 'package:flutter/material.dart';
import 'my_webview.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home Page"),
      ),
      body: Center(
        child: FlatButton(
          child: Text("Open Webpage"),
          onPressed: () {
             Navigator.of(context).push(MaterialPageRoute(
              builder: (BuildContext context) => MyWebView(
                title: "resize-image",
                selectedUrl: "https://www.iloveimg.com/resize-image",
              )
            ));
          },
        ),
      ),
    );
  }
}

My "main" files

import 'package:flutter/material.dart';
import 'home_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}

My "my_webview" files

import 'dart:async';

    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';

    class MyWebView extends StatelessWidget {
      final String title;
      final String selectedUrl;

      final Completer<WebViewController> _controller = Completer<WebViewController>();

      MyWebView({
        required this.title,
        required this.selectedUrl,
      });

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(title),
          ),
          body: WebView(
            initialUrl: selectedUrl,
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _controller.complete(webViewController);
            },
          ));
      }
    }

and dependencies in pubspec.yaml

  dependencies:
      flutter:
        sdk: flutter
      webview_flutter: ^3.0.4
      permission_handler: ^10.2.0


问:
Vertex AI project on Android Studio
I am developing an app on Android Studio using the Cloud Vision APIs from Google, and I have already made the label detection from a picture taken with the smartphone, but I would like to make a second version with a pre-trained model by me with the API Vertex AI since the general label detection is not pretty specific for what I want.

I already know how to train the model in the web, but I have been looking for an example of how to implement the Vertex API on Android Studio (Java), does anybody have an example? or could help me? the documentation is not full since it is a "new" API.

Thanks.

Title: Vertex AI project on Android Studio


问:
Selenium, can’t access child window / alert /?
I am using selenium, java app to navigate a web page. I get to a point where if I hover over an area, I see a + magnifying glass. When I click here, it brings up a new window. This window contains the information I am after. On MacOS, this window only contains the information and a close X in upper right corner see attached.

I’ve tried  to treat this window as an “alert” (ie driver.switchTo().alert(); and get “Exception in thread "main" org.openqa.selenium.NoAlertPresentException: no such alert.”

I’ve tried treating as a window (ie  boolean isChildWindowOpen = wait.until(ExpectedConditions.
NumberOfWindowsToBe(2)); and get “Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for number of open windows to be 2 (tried for 10 second(s) with 500 milliseconds interval). I only get 1 window.

The HTML code I am clicking on is  == $0. I’m guessing this is related to JS doing something?

Attached is the parent window with the child overlayed and inspect data for the parent window.


问:
Sphinx autosummary is ignoring all custom text I try to add to my custom template
I'm trying to create a custom template for autosummary, but I can't figure out how to add any custom modifications.

I'm using autosummary in an rst like this:

```<code>API
===

.. autosummary::
   :toctree: _autosummary
   :template: custom_test.rst.j2
   :recursive:

   myapp
</code>```

I copied the default custom template and have just been trying to modify it to understand how this works: https://github.com/sphinx-doc/sphinx/blob/29e12ec4dbe96130bbd733aaba9d89fd68c2d5a0/sphinx/ext/autosummary/templates/autosummary/module.rst

The below snippets are that template with just these specific changes made to them.

First I confirmed it's picking up the template because this throws an error:

```<code>{# At the very top of the template file #}
{{ fullname | escape | underline}}

.. automodule:: "derpderpderp"
</code>```

WARNING: don't know which module to import for autodocumenting '"derpderpderp"'

I've been trying to add arbitrary text and directives, but all of that is ignored and I can't see why.

First I tried just adding a heading at the top:

```<code>{{ fullname | escape | underline}}
    Some Heading
    ============

.. automodule:: {{ fullname }}
</code>```

No error is thrown, but when I look at the rsts in _autosummary that were generated none of them have this heading added.

I also tried adding a sidebar, this throws no errors, but no rsts have this sidebar text I added to the template:

```<code>{{ fullname | escape | underline}}
.. sidebar:: Sidebar Title
    :subtitle: Optional Sidebar Subtitle

    Subsequent indented lines comprise
    the body of the sidebar, and are
    interpreted as body elements.
</code>```

Again I can confirm it's reading and processing the template because using it with no content throws an error showing it's at least processing it:

```<code>{{ fullname | escape | underline}}
.. sidebar::
</code>```

ERROR: Content block expected for the "sidebar" directive; none found.

Also in the modules section I tried removing .. rubric:: Modules, but after rendering it adds it to the rst files anyway:

```<code>{% block modules %}
{% if modules %}
{# .. rubric:: Modules #}
</code>```

I was able to add a :template: setting to the autosummary section under the modules block though:

```<code>{% block modules %}
{% if modules %}
.. rubric:: Modules

.. autosummary::
   :toctree:
   :recursive:
   {# I can see this template setting added to all the auto generated rst files as expected #}
   :template: custom_test.rst.j2
</code>```

I'm not sure what I am allowed to modify. I was assuming this was just a regular Jinja template used to generate the rst files. Is there something special about how it's processed that makes it impossible to just add arbitrary text and settings?

Body:
I'm trying to create a custom template for autosummary, but I can't figure out how to add any custom modifications.

I'm using autosummary in an rst like this:

API
===

.. autosummary::
   :toctree: _autosummary
   :template: custom_test.rst.j2
   :recursive:

   myapp

I copied the default custom template and have just been trying to modify it to understand how this works: https://github.com/sphinx-doc/sphinx/blob/29e12ec4dbe96130bbd733aaba9d89fd68c2d5a0/sphinx/ext/autosummary/templates/autosummary/module.rst

The below snippets are that template with just these specific changes made to them.

First I confirmed it's picking up the template because this throws an error:

{# At the very top of the template file #}
{{ fullname | escape | underline}}

.. automodule:: "derpderpderp"

WARNING: don't know which module to import for autodocumenting '"derpderpderp"'

I've been trying to add arbitrary text and directives, but all of that is ignored and I can't see why.

First I tried just adding a heading at the top:

{{ fullname | escape | underline}}
    Some Heading
    ============

.. automodule:: {{ fullname }}

No error is thrown, but when I look at the rsts in _autosummary that were generated none of them have this heading added.

I also tried adding a sidebar, this throws no errors, but no rsts have this sidebar text I added to the template:

{{ fullname | escape | underline}}
.. sidebar:: Sidebar Title
    :subtitle: Optional Sidebar Subtitle

    Subsequent indented lines comprise
    the body of the sidebar, and are
    interpreted as body elements.

Again I can confirm it's reading and processing the template because using it with no content throws an error showing it's at least processing it:

{{ fullname | escape | underline}}
.. sidebar::

ERROR: Content block expected for the "sidebar" directive; none found.

Also in the modules section I tried removing .. rubric:: Modules, but after rendering it adds it to the rst files anyway:

{% block modules %}
{% if modules %}
{# .. rubric:: Modules #}

I was able to add a :template: setting to the autosummary section under the modules block though:

{% block modules %}
{% if modules %}
.. rubric:: Modules

.. autosummary::
   :toctree:
   :recursive:
   {# I can see this template setting added to all the auto generated rst files as expected #}
   :template: custom_test.rst.j2

I'm not sure what I am allowed to modify. I was assuming this was just a regular Jinja template used to generate the rst files. Is there something special about how it's processed that makes it impossible to just add arbitrary text and settings?


问:
Spring Boot @Cachable ( Default Implementation ) List<Object>
I have a scenario where I have two external APIs

List of Users (/users)

User based on ID ( /users/{id} )

The APIs are expensive operations as it's been called from a 3rd Party Service.

I want to build a cache using Spring Boot Cache

@Cachable("users")
public List<Users> getUsers(){}

@Cachable("users", key="#id")
public User getUser(){}
```
<p>I want to build a cache such that when we call <code>getUsers()</code> the first time it will build a cache for subsequent <code>getUser(1)</code> methods.</p>
<p>How can I achieve this using Spring Boot ( Default implementation of Cache )?</p>
<p>I already tried to do the below:</p>
<pre class="lang-java prettyprint-override"><code>@Cachable("users")
public List<Users> getUsers(){}

@Cachable("users", key="#id")
public User getUser(){}
</code>```

It creates different keys in the cache so even though I have called getUsers() the getUser() method calls the API.

Body:
I have a scenario where I have two external APIs

List of Users (/users)

User based on ID ( /users/{id} )

The APIs are expensive operations as it's been called from a 3rd Party Service.

I want to build a cache using Spring Boot Cache

@Cachable("users")
public List<Users> getUsers(){}

@Cachable("users", key="#id")
public User getUser(){}

I want to build a cache such that when we call getUsers() the first time it will build a cache for subsequent getUser(1) methods.

How can I achieve this using Spring Boot ( Default implementation of Cache )?

I already tried to do the below:

@Cachable("users")
public List<Users> getUsers(){}

@Cachable("users", key="#id")
public User getUser(){}

It creates different keys in the cache so even though I have called getUsers() the getUser() method calls the API.


问:
Ionic assets doesn't work when deployed on angular
I made an ionic app with

@ionic/angular ^6.1.9
@capacitor/android 4.3.0
@angular/core ^14.0.0

when served in browser everything works but when deployed on android, i've got no translations, no icons and a lot of errors for polyfill.js

Here are these errors

E/Capacitor/Plugin: MalformedURLException java.net.MalformedURLException: no protocol: ./assets/i18n/fr.json

E/Capacitor/Plugin: MalformedURLException java.net.MalformedURLException: no protocol: /svg/add.svg

E/Capacitor/Console: File: http://localhost/polyfills.js - Line 1 - Msg: Unhandled Promise rejection: MalformedURLException

Does somebody have an idea on what's the problem, i compared angular.json and TranslateLoader with another project but it's the same, i don't know why i works with a project and not with another

Here is my angular.json build assets options

```<code>

    "assets": [
        {
            "glob": "**/*",
            "input": "src/assets",
            "output": "assets"
        },
        {
            "glob": "**/*.svg",
            "input": "node_modules/ionicons/dist/ionicons/svg",
            "output": "./svg"
        }
    ],

</code>```

my package.json dependencies

```<code>

    "dependencies": {
        "@angular/common": "^14.0.0",
        "@angular/core": "^14.0.0",
        "@angular/forms": "^14.0.0",
        "@angular/platform-browser": "^14.0.0",
        "@angular/platform-browser-dynamic": "^14.0.0",
        "@angular/router": "^14.0.0",
        "@awesome-cordova-plugins/splash-screen": "^5.44.0",
        "@awesome-cordova-plugins/status-bar": "^5.44.0",
        "@capacitor-community/barcode-scanner": "^3.0.0",
        "@capacitor-community/electron": "^4.1.0",
        "@capacitor-community/sqlite": "^4.1.0",
        "@capacitor/android": "4.3.0",
        "@capacitor/app": "^4.0.0",
        "@capacitor/camera": "^4.1.2",
        "@capacitor/core": "^4.0.0",
        "@capacitor/dialog": "^4.0.0",
        "@capacitor/filesystem": "^4.0.0",
        "@capacitor/haptics": "^4.0.0",
        "@capacitor/ios": "4.3.0",
        "@capacitor/keyboard": "^4.0.0",
        "@capacitor/network": "^4.0.1",
        "@capacitor/preferences": "^4.0.1",
        "@capacitor/status-bar": "^4.0.0",
        "@capacitor/toast": "^4.0.0",
        "@ionic-native/file": "^5.36.0",
        "@ionic-native/splash-screen": "^5.36.0",
        "@ionic/angular": "^6.1.9",
        "@ionic/pwa-elements": "^3.1.1",
        "@ngx-translate/core": "^14.0.0",
        "@ngx-translate/http-loader": "^7.0.0",
        "cordova-plugin-statusbar": "^3.0.0",
        "jeep-sqlite": "^1.6.2",
        "json-concat": "^0.0.1",
        "moment": "^2.29.4",
        "moment-timezone": "^0.5.37",
        "replace": "^1.2.1",
        "rxjs": "~6.6.0",
        "tslib": "^2.2.0",
        "typeorm": "^0.3.10",
        "zone.js": "~0.11.4"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^14.0.0",
        "@angular-eslint/builder": "~13.0.1",
        "@angular-eslint/eslint-plugin": "~13.0.1",
        "@angular-eslint/eslint-plugin-template": "~13.0.1",
        "@angular-eslint/template-parser": "~13.0.1",
        "@angular/cli": "^14.0.0",
        "@angular/compiler": "^14.0.0",
        "@angular/compiler-cli": "^14.0.0",
        "@angular/language-service": "^14.0.0",
        "@capacitor/cli": "^4.0.0",
        "@ionic/angular-toolkit": "^6.0.0",
        "@ionic/lab": "3.2.13",
        "@types/jasmine": "^3.6.0",
        "@types/jasminewd2": "^2.0.3",
        "@types/node": "^12.20.55",
        "@typescript-eslint/eslint-plugin": "5.3.0",
        "@typescript-eslint/parser": "5.3.0",
        "copyfiles": "^2.4.1",
        "eslint": "^7.6.0",
        "eslint-plugin-import": "2.22.1",
        "eslint-plugin-jsdoc": "30.7.6",
        "eslint-plugin-prefer-arrow": "1.2.2",
        "jasmine-core": "~3.8.0",
        "jasmine-spec-reporter": "~5.0.0",
        "karma": "~6.3.14",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage": "~2.0.3",
        "karma-coverage-istanbul-reporter": "~3.0.2",
        "karma-jasmine": "~4.0.0",
        "karma-jasmine-html-reporter": "^1.5.0",
        "protractor": "~7.0.0",
        "ts-node": "^10.7.0",
        "typescript": "~4.7.3"
    },

</code>```

My translateLoader

```<code>

    export function createTranslateLoader(http: HttpClient) {
        let suffix = `.json`;

        if (environment.buildVersion) {
            suffix += '?v=' + environment.buildVersion;
        }

        return new TranslateHttpLoader(http, './assets/i18n/', suffix);
    }

    @NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        TranslateModule.forRoot({
            defaultLanguage: environment.defaultLocale,
            loader: {provide: TranslateLoader, useFactory: createTranslateLoader, deps: [HttpClient]}
        }),
    ],
    ...

</code>```

Thank you for your help

Body:
I made an ionic app with

@ionic/angular ^6.1.9
@capacitor/android 4.3.0
@angular/core ^14.0.0

when served in browser everything works but when deployed on android, i've got no translations, no icons and a lot of errors for polyfill.js

Here are these errors

E/Capacitor/Plugin: MalformedURLException java.net.MalformedURLException: no protocol: ./assets/i18n/fr.json

E/Capacitor/Plugin: MalformedURLException java.net.MalformedURLException: no protocol: /svg/add.svg

E/Capacitor/Console: File: http://localhost/polyfills.js - Line 1 - Msg: Unhandled Promise rejection: MalformedURLException

Does somebody have an idea on what's the problem, i compared angular.json and TranslateLoader with another project but it's the same, i don't know why i works with a project and not with another

Here is my angular.json build assets options

    "assets": [
        {
            "glob": "**/*",
            "input": "src/assets",
            "output": "assets"
        },
        {
            "glob": "**/*.svg",
            "input": "node_modules/ionicons/dist/ionicons/svg",
            "output": "./svg"
        }
    ],

my package.json dependencies

    "dependencies": {
        "@angular/common": "^14.0.0",
        "@angular/core": "^14.0.0",
        "@angular/forms": "^14.0.0",
        "@angular/platform-browser": "^14.0.0",
        "@angular/platform-browser-dynamic": "^14.0.0",
        "@angular/router": "^14.0.0",
        "@awesome-cordova-plugins/splash-screen": "^5.44.0",
        "@awesome-cordova-plugins/status-bar": "^5.44.0",
        "@capacitor-community/barcode-scanner": "^3.0.0",
        "@capacitor-community/electron": "^4.1.0",
        "@capacitor-community/sqlite": "^4.1.0",
        "@capacitor/android": "4.3.0",
        "@capacitor/app": "^4.0.0",
        "@capacitor/camera": "^4.1.2",
        "@capacitor/core": "^4.0.0",
        "@capacitor/dialog": "^4.0.0",
        "@capacitor/filesystem": "^4.0.0",
        "@capacitor/haptics": "^4.0.0",
        "@capacitor/ios": "4.3.0",
        "@capacitor/keyboard": "^4.0.0",
        "@capacitor/network": "^4.0.1",
        "@capacitor/preferences": "^4.0.1",
        "@capacitor/status-bar": "^4.0.0",
        "@capacitor/toast": "^4.0.0",
        "@ionic-native/file": "^5.36.0",
        "@ionic-native/splash-screen": "^5.36.0",
        "@ionic/angular": "^6.1.9",
        "@ionic/pwa-elements": "^3.1.1",
        "@ngx-translate/core": "^14.0.0",
        "@ngx-translate/http-loader": "^7.0.0",
        "cordova-plugin-statusbar": "^3.0.0",
        "jeep-sqlite": "^1.6.2",
        "json-concat": "^0.0.1",
        "moment": "^2.29.4",
        "moment-timezone": "^0.5.37",
        "replace": "^1.2.1",
        "rxjs": "~6.6.0",
        "tslib": "^2.2.0",
        "typeorm": "^0.3.10",
        "zone.js": "~0.11.4"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^14.0.0",
        "@angular-eslint/builder": "~13.0.1",
        "@angular-eslint/eslint-plugin": "~13.0.1",
        "@angular-eslint/eslint-plugin-template": "~13.0.1",
        "@angular-eslint/template-parser": "~13.0.1",
        "@angular/cli": "^14.0.0",
        "@angular/compiler": "^14.0.0",
        "@angular/compiler-cli": "^14.0.0",
        "@angular/language-service": "^14.0.0",
        "@capacitor/cli": "^4.0.0",
        "@ionic/angular-toolkit": "^6.0.0",
        "@ionic/lab": "3.2.13",
        "@types/jasmine": "^3.6.0",
        "@types/jasminewd2": "^2.0.3",
        "@types/node": "^12.20.55",
        "@typescript-eslint/eslint-plugin": "5.3.0",
        "@typescript-eslint/parser": "5.3.0",
        "copyfiles": "^2.4.1",
        "eslint": "^7.6.0",
        "eslint-plugin-import": "2.22.1",
        "eslint-plugin-jsdoc": "30.7.6",
        "eslint-plugin-prefer-arrow": "1.2.2",
        "jasmine-core": "~3.8.0",
        "jasmine-spec-reporter": "~5.0.0",
        "karma": "~6.3.14",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage": "~2.0.3",
        "karma-coverage-istanbul-reporter": "~3.0.2",
        "karma-jasmine": "~4.0.0",
        "karma-jasmine-html-reporter": "^1.5.0",
        "protractor": "~7.0.0",
        "ts-node": "^10.7.0",
        "typescript": "~4.7.3"
    },

My translateLoader

    export function createTranslateLoader(http: HttpClient) {
        let suffix = `.json`;

        if (environment.buildVersion) {
            suffix += '?v=' + environment.buildVersion;
        }

        return new TranslateHttpLoader(http, './assets/i18n/', suffix);
    }

    @NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        TranslateModule.forRoot({
            defaultLanguage: environment.defaultLocale,
            loader: {provide: TranslateLoader, useFactory: createTranslateLoader, deps: [HttpClient]}
        }),
    ],
    ...

Thank you for your help


问:
PowerBI Dynamic totals counting in calculated column
I need help vith creating a dinamic total calculations in my calendar table.
So I have a table called Dataset consisted of  folowing columns: ArchDate, Type, Status.

And of caurse I can use slicers to filter it by Status or Type.

Ive created a Calendar table using DAX

```<code>MyCalendar = CALENDAR(DATE(2020,01,01),TODAY())
</code>```

Then I've added calculated column "Totals" which counts a number of occurances of each date in Dataset[ArchDate]

```<code>Totals =
var total_Calc=CALCULATE(COUNTA('Dataset'[ArchDate]),FILTER('Dataset','Dataset'[ArchDate]=MyCalendar[Date]))
return if(total_Calc=BLANK(),0,total_Calc)
</code>```

And now my calendar looks like this

But my problem is that I cant use slicers to filter values of Dataset. For example I need to count just First Stage but if I select the value of the "Type" slider values of MyCalendar[Totals] remains the same. Mean slicer does not work.

Please advise how to resolve it. Is it possible? This is my sample pbix

My pbix

Body:
I need help vith creating a dinamic total calculations in my calendar table.
So I have a table called Dataset consisted of  folowing columns: ArchDate, Type, Status.

And of caurse I can use slicers to filter it by Status or Type.

Ive created a Calendar table using DAX

MyCalendar = CALENDAR(DATE(2020,01,01),TODAY())

Then I've added calculated column "Totals" which counts a number of occurances of each date in Dataset[ArchDate]

Totals =
var total_Calc=CALCULATE(COUNTA('Dataset'[ArchDate]),FILTER('Dataset','Dataset'[ArchDate]=MyCalendar[Date]))
return if(total_Calc=BLANK(),0,total_Calc)

And now my calendar looks like this

But my problem is that I cant use slicers to filter values of Dataset. For example I need to count just First Stage but if I select the value of the "Type" slider values of MyCalendar[Totals] remains the same. Mean slicer does not work.

Please advise how to resolve it. Is it possible? This is my sample pbix

My pbix


问:
SSH connection failure
I have a desktop program that has to download some files from multiple vm(s) on different servers under 2 different vpns.  The program also accesses the databases on the vm(s) to download data from each vm.  The servers are both UBANTU servers I suspect that one may be older than the other.  I have no problems with the older server, I access the databases and I can download the files from the server.  I use ssh2_scp_recv to download the files.  I have no problems with downloading the data from the vm databases on the newer server.  BUT, I cannot download the files, I get the following:

Warning: ssh2_connect(): Error starting up SSH connection(-5): Unable to exchange encryption keys in ...(the program name and line #)

Warning: ssh2_connect(): Unable to connect to (server ip ) in (program name and line number)

I have the latest version of Libssh2 installed and it appears to be working correctly with the older server..  Any suggestion would be appreciated.

Title: SSH connection failure


问:
Scorecardpy woebin_adj does not show all plots to adjust binning
I am struggling with woebin_adj from scorecardpy package.
My dataset consists of 10 variable Y columns and 1 variable X column.

First, I use woebin_plot to plot and it shows 10 plots correctly.
Then, I would like to adjust binning for some variable using woebin_adj. The result showed only 4 plots for me to adjust.

```<code>breaks_adj = sc.woebin_adj(df, "y", bins)
</code>```

I checked the length of dataframe that is generated from woebin and is used as an input parameter. It showed that the length is 10 correctly.

```<code>print(len(bins))
>>10
</code>```

Body:
I am struggling with woebin_adj from scorecardpy package.
My dataset consists of 10 variable Y columns and 1 variable X column.

First, I use woebin_plot to plot and it shows 10 plots correctly.
Then, I would like to adjust binning for some variable using woebin_adj. The result showed only 4 plots for me to adjust.

breaks_adj = sc.woebin_adj(df, "y", bins)

I checked the length of dataframe that is generated from woebin and is used as an input parameter. It showed that the length is 10 correctly.

print(len(bins))
>>10


问:
How to update cookie when refreshing the access token in Blazor server-side?
In my app, I use OpenIdConnect to connect to the authorization server and is set up in Startup.cs as follows:

```<code>services.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Authority = authority;
    options.ClientId = clientId;
    options.ClientSecret = clientSecret;
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.ResponseMode = OpenIdConnectResponseMode.FormPost;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.SaveTokens = true;
    options.UseTokenLifetime = true
    options.Scope.Add(OpenIdConnectScope.OpenIdProfile);
    options.Scope.Add(OpenIdConnectScope.Email);
    options.Scope.Add(OpenIdConnectScope.OfflineAccess);
    options.SecurityTokenValidator = new JwtSecurityTokenHandler
    {
        InboundClaimTypeMap = new Dictionary<string, string>()
    };
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name"
    };
});
</code>```

Everything works fine. I now need to add refreshing tokens. As this is a Blazor server-side app I can't use the same method as for normal MVC projects by using cookie events:

```<code>.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => {
    options.Events = new CookieAuthenticationEvents {
        OnValidatePrincipal = async context => {}};
};
</code>```

Howver, I use Refit and I have a DelegatingHandler and at this stage I can check for the access token lifetime and use the refresh token to exchange for new access and refresh tokens.

Once I get the new tokens, and as I set UseTokenlifetime = true, how do I update the cookie at this stage?

Body:
In my app, I use OpenIdConnect to connect to the authorization server and is set up in Startup.cs as follows:

services.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Authority = authority;
    options.ClientId = clientId;
    options.ClientSecret = clientSecret;
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.ResponseMode = OpenIdConnectResponseMode.FormPost;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.SaveTokens = true;
    options.UseTokenLifetime = true
    options.Scope.Add(OpenIdConnectScope.OpenIdProfile);
    options.Scope.Add(OpenIdConnectScope.Email);
    options.Scope.Add(OpenIdConnectScope.OfflineAccess);
    options.SecurityTokenValidator = new JwtSecurityTokenHandler
    {
        InboundClaimTypeMap = new Dictionary<string, string>()
    };
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name"
    };
});

Everything works fine. I now need to add refreshing tokens. As this is a Blazor server-side app I can't use the same method as for normal MVC projects by using cookie events:

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => {
    options.Events = new CookieAuthenticationEvents {
        OnValidatePrincipal = async context => {}};
};

Howver, I use Refit and I have a DelegatingHandler and at this stage I can check for the access token lifetime and use the refresh token to exchange for new access and refresh tokens.

Once I get the new tokens, and as I set UseTokenlifetime = true, how do I update the cookie at this stage?


问:
Removing an image in SwiftUI
I am working on a chess game in SwiftUI and I need a way to remove images (pieces) from board. Each pieces is created with the following code.
GeometryReader { geo in
Image(name)
.resizable()
.frame(width: CGFloat(cellSize), height: CGFloat(cellSize))
.scaledToFit()
.position(location)
.gesture(DragGesture()
.onChanged { value in
withAnimation(.spring()) {
location = value.location
}
}
.onEnded { value in
withAnimation(.spring()) {
print("Location: ", location)
print("name: ", name)
print("startlocation: ", value.startLocation)
(location, placement.pieces) = placement.checkSpot(loc: value.location, size: cellSize, start: value.startLocation, name: name, pieces: placement.pieces)                        }
}
)
}

I looked through the documentation and YouTube videos and could not find a .remove/.delete command or any help on this. I found a lot of help on adding/resizing/moving the image but nothing on deleting one.

Title: Removing an image in SwiftUI


问:
Fetch URL get 404 but URL exists
I'm trying to fetch the LastFM API to get a user image when an input is changed.

The fetched URL is 'http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=tom_pla&api_key=MY_API_KEY&format=json'

/**
 * useEffect hook.
 * This hook is called when the component is mounted.
 * It fetches the Last.fm API to get the user image when the username is changed and longer than 3 characters.
 */
useEffect(() => {
  let cancelToken = axios.CancelToken;
  let source = cancelToken.source();

  if (username.length >= 3) {
    setTimeout(() => {
      axios({
        method: "GET",
        url: `${baseURL}?method=user.getinfo&user=${username}${endURL}`,
        cancelToken: source.token,
        headers: {
          Accept: 'application/json',
        }
      })
        .then(res => {
          // Check if the fetch is successful.
          if (res.data && res.data.user && res.data.user.image) {
            setUsernameImage(res.data.user.image[2]["#text"]);
          }
        })
        .catch((error) => {
          if (axios.isCancel(error) || error.response.status === 404) {
            console.log("Request canceled", error.message);
          } else {
            console.log(error);
          }
          setUsernameImage(null);
        })
    }, 250);
  }

 return () => {
    source.cancel(); // Cancel the request
  }
}, [username]);
```

When fetching some username (for example tom_pla) I have a GET adress 404 (Not Found) but when I manually type the URL in a browser, it works...

It doesn't crash my code but logs the GET 404 error with my api key shown.

How to solve this please.

Thanks,
Tom.

Title: Fetch URL get 404 but URL exists

Body:
I'm trying to fetch the LastFM API to get a user image when an input is changed.

The fetched URL is 'http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=tom_pla&api_key=MY_API_KEY&format=json'

/**
 * useEffect hook.
 * This hook is called when the component is mounted.
 * It fetches the Last.fm API to get the user image when the username is changed and longer than 3 characters.
 */
useEffect(() => {
  let cancelToken = axios.CancelToken;
  let source = cancelToken.source();

  if (username.length >= 3) {
    setTimeout(() => {
      axios({
        method: "GET",
        url: `${baseURL}?method=user.getinfo&user=${username}${endURL}`,
        cancelToken: source.token,
        headers: {
          Accept: 'application/json',
        }
      })
        .then(res => {
          // Check if the fetch is successful.
          if (res.data && res.data.user && res.data.user.image) {
            setUsernameImage(res.data.user.image[2]["#text"]);
          }
        })
        .catch((error) => {
          if (axios.isCancel(error) || error.response.status === 404) {
            console.log("Request canceled", error.message);
          } else {
            console.log(error);
          }
          setUsernameImage(null);
        })
    }, 250);
  }

 return () => {
    source.cancel(); // Cancel the request
  }
}, [username]);

When fetching some username (for example tom_pla) I have a GET adress 404 (Not Found) but when I manually type the URL in a browser, it works...

It doesn't crash my code but logs the GET 404 error with my api key shown.

How to solve this please.

Thanks,
Tom.


问:
How to loop until the program was stopped
I'm trying to make a program that is similar to a stopwatch, but not exactly. I am programming on https://www.online-python.com on a Chromebook. I want the program to just count up by 0.02 until the process or terminal is stopped.

Code

Whenever I try running the code, it does not carriage return correctly. My desired output is for the program to count up on a single line until the program is stopped, and then it stops counting. I also want it to go to 1.00 when the counter reaches 0.60.

```<code>import time

def mindseCOUNTING():
    mindse = 0
    while mindse > -1:
        time.sleep(0.02)
        format_float = "{:.2f}".format(mindse)
        print(f"{format_float}", end = "\r")
        mindse += 0.02

mindseCOUNTING()
</code>```

Current output:

```<code>>>> 0.02
>>> 0.04
>>> 0.06
>>> 0.08
>>> 0.10
>>> 0.12
</code>```

Is there a pattern or module to make a while loop that keeps looping until the program is stopped?

Body:
I'm trying to make a program that is similar to a stopwatch, but not exactly. I am programming on https://www.online-python.com on a Chromebook. I want the program to just count up by 0.02 until the process or terminal is stopped.

Code

Whenever I try running the code, it does not carriage return correctly. My desired output is for the program to count up on a single line until the program is stopped, and then it stops counting. I also want it to go to 1.00 when the counter reaches 0.60.

import time

def mindseCOUNTING():
    mindse = 0
    while mindse > -1:
        time.sleep(0.02)
        format_float = "{:.2f}".format(mindse)
        print(f"{format_float}", end = "\r")
        mindse += 0.02

mindseCOUNTING()

Current output:

>>> 0.02
>>> 0.04
>>> 0.06
>>> 0.08
>>> 0.10
>>> 0.12

Is there a pattern or module to make a while loop that keeps looping until the program is stopped?


问:
How to write a correct sql query which do not return duplicated result?
I have multiple tables and I joined them incorrectly or I am missing something.

Table joins looks this:

```<code>SELECT Item.*, Category.*, SubCategory.*, Location.*, Brand.*, ItmCondition.*, User.*, Image.*
FROM Item
JOIN Category ON Item.Category_Id = Category.Category_Id
JOIN SubCategory ON Item.SubCategory_Id = SubCategory.SubCategory_Id
JOIN Location ON Item.Location_Id = Location.Location_Id
JOIN Brand ON Item.Brand_Id = Brand.Brand_Id
JOIN ItmCondition ON Item.Condition_Id = ItmCondition.Condition_Id
JOIN User ON Item.User_Id = User.User_Id
JOIN Image ON Item.Item_Id = Image.Item_Id
WHERE Item.Category_Id =".$_GET['ctgId'];
</code>```

Each item in Item table has one or more related image/s in Image table. I want to fetch the first image as a thumbnail for each Item even tho each Item can have one or multiple images in Image table. with the above query I get duplicated Items for each Images related to it. I’m pretty new to this and I hope you understand what I’m trying to say!

Body:
I have multiple tables and I joined them incorrectly or I am missing something.

Table joins looks this:

SELECT Item.*, Category.*, SubCategory.*, Location.*, Brand.*, ItmCondition.*, User.*, Image.*
FROM Item
JOIN Category ON Item.Category_Id = Category.Category_Id
JOIN SubCategory ON Item.SubCategory_Id = SubCategory.SubCategory_Id
JOIN Location ON Item.Location_Id = Location.Location_Id
JOIN Brand ON Item.Brand_Id = Brand.Brand_Id
JOIN ItmCondition ON Item.Condition_Id = ItmCondition.Condition_Id
JOIN User ON Item.User_Id = User.User_Id
JOIN Image ON Item.Item_Id = Image.Item_Id
WHERE Item.Category_Id =".$_GET['ctgId'];

Each item in Item table has one or more related image/s in Image table. I want to fetch the first image as a thumbnail for each Item even tho each Item can have one or multiple images in Image table. with the above query I get duplicated Items for each Images related to it. I’m pretty new to this and I hope you understand what I’m trying to say!


问:
Fill pattern for Bar graph or StackedBar in Jasper Report
How to use fill parttern for the Bar or Stacked Bar graph in Jasper Report?
Can anyone give some instructions or a easy example?
Many thanks.

My expecting is somethink like the graph beblow,and I want to use diagonal stroke to fill the bar.


问:
Blazor - How do I binding a deeply nested child component to a variable on my page?
I'm using a 3rd party autocomplete component in my app, and because I'm using autocomplete in several instances all with the same appearance and behaviour, I wanted to wrap it in my own component so I can do most of the plumbing once.

I'm trying to bind a property of the autocomplete component to a property of my wrapping component, which is then bound to a property of my page.

So 99% of the setup is done in the wrapper, all I need to do is create a function on my page to execute a search and set a propert which the wrapper is then bound to. My problem is (shown below) in the ReadData function (AutocompleteSearch).  If I set items to a static list the dropdown displays fine. If I invoke a function on my page, specified by the OnSearch property of my wrapper, the autocomplete does not appear. I think this must have something to do with binding in Blazor that I do not understand...

Here is my component wrapper:

```<code>@typeparam TKey

<Blazorise.Components.Autocomplete
        TItem="AutocompleteItem<TKey>"
        TValue=TKey
        Data="@Items"
        ReadData="@AutocompleteSearch"
        TextField="@((item) => item.Display)"
        ValueField="@(( item ) => item.ID)"
        Placeholder="@Placeholder"
        Debounce="true"
        DebounceInterval="100"
        FreeTyping="false"
        @bind-SelectedValue="SelectedID"
        @bind-SelectedText="SelectedText">
        <ItemContent>
            @if (context.Item.FrequentlyUsed)
            {
                <span class="@FrequentlyUsedClass"> </span>
            }
            @context.Text
        </ItemContent>
</Blazorise.Components.Autocomplete>

@code {
    [Inject]
    public ILogger<Blazorise.Components.Autocomplete<TKey, AutocompleteItem<TKey>>> Logger { get; set; }

    [Parameter]
    public string Placeholder { get; set; } = "Search...";

    [Parameter]
    public string FrequentlyUsedClass { get; set; } = "text-warning icon-dashboard-star-full";

    [Parameter]
    public IEnumerable<AutocompleteItem<TKey>>? Items { get; set; }

    [Parameter]
    public EventCallback<AutocompleteReadDataEventArgs> OnSearch { get; set; }

    [Parameter]
    public TKey SelectedID { get; set; }

    [Parameter]
    public string SelectedText { get; set; }

    private async Task AutocompleteSearch(AutocompleteReadDataEventArgs args)
    {
        Logger.LogTrace("Search start.");

        //does not work
        await OnSearch.InvokeAsync(args);
        StateHasChanged();

        //works
        //Items = new List<AutocompleteItem<TKey>>()
        //{
        //    new AutocompleteItem<TKey>()
        //    {
        //        Display = "test"
        //    }
        //};

        Logger.LogTrace($"Items found: {Items.Count()}");
        Logger.LogTrace("Search complete.");
    }

}
</code>```

Here is the relevant parts on my page:

```<code>@code {
    [Inject]
    private IDAL DB { get; set; }

    //Autocomplete
    private IEnumerable<AutocompleteItem<int>>? AutocompleteItems { get; set; }
    private int AutoCompleteSelectedID { get; set; }
    private string? AutocompleteSelectedText { get; set; }

    private /*async Task*/ void AutocompleteSearch(AutocompleteReadDataEventArgs args)
    {
        if (!args.CancellationToken.IsCancellationRequested)
        {
            AutocompleteItems = DB.SearchSampleItems(args.SearchValue);
        }
    }
}
</code>```

EDIT
I also tried another approach.  Instead of trying to bind the AutocompleteItems property of my wrapper to a property on my page, then bind
the Data property of the Autocomplete control to the AutocompleteItems property of my wrapper, I tried returning the items in the search arguments.  I think it ends up being cleaner, but still has the same result.

```<code>private async Task AutocompleteSearch(AutocompleteReadDataEventArgs args)
{
    Logger.LogTrace($"Search start: {args.SearchValue}");

    //does not work
    var searchArgs = new AutocompleteSearchEventArgs(args.SearchValue, args.CancellationToken);
    await OnSearch.InvokeAsync(searchArgs);
    Items = searchArgs.ItemsFound.ToArray();
    StateHasChanged();

    //works
    //Items = new List<AutocompleteItem<TKey>>()
    //{
    //    new AutocompleteItem<TKey>()
    //    {
    //        Display = "test"
    //    }
    //};

    Logger.LogTrace($"Items found: {Items.Count()}");
    Logger.LogTrace("Search complete.");
}

public class AutocompleteSearchEventArgs
{
    public string SearchValue { get; private set; }

    public CancellationToken CancellationToken { get; private set; }

    public IEnumerable<AutocompleteItem<TKey>> ItemsFound { get; set; }

    public AutocompleteSearchEventArgs(string searchValue, CancellationToken cancellationToken = default(CancellationToken))
    {
        CancellationToken = cancellationToken;
        earchValue = searchValue;
    }
}
</code>```

Body:
I'm using a 3rd party autocomplete component in my app, and because I'm using autocomplete in several instances all with the same appearance and behaviour, I wanted to wrap it in my own component so I can do most of the plumbing once.

I'm trying to bind a property of the autocomplete component to a property of my wrapping component, which is then bound to a property of my page.

So 99% of the setup is done in the wrapper, all I need to do is create a function on my page to execute a search and set a propert which the wrapper is then bound to. My problem is (shown below) in the ReadData function (AutocompleteSearch).  If I set items to a static list the dropdown displays fine. If I invoke a function on my page, specified by the OnSearch property of my wrapper, the autocomplete does not appear. I think this must have something to do with binding in Blazor that I do not understand...

Here is my component wrapper:

@typeparam TKey

<Blazorise.Components.Autocomplete
        TItem="AutocompleteItem<TKey>"
        TValue=TKey
        Data="@Items"
        ReadData="@AutocompleteSearch"
        TextField="@((item) => item.Display)"
        ValueField="@(( item ) => item.ID)"
        Placeholder="@Placeholder"
        Debounce="true"
        DebounceInterval="100"
        FreeTyping="false"
        @bind-SelectedValue="SelectedID"
        @bind-SelectedText="SelectedText">
        <ItemContent>
            @if (context.Item.FrequentlyUsed)
            {

            }
            @context.Text
        </ItemContent>
</Blazorise.Components.Autocomplete>

@code {
    [Inject]
    public ILogger<Blazorise.Components.Autocomplete<TKey, AutocompleteItem<TKey>>> Logger { get; set; }

    [Parameter]
    public string Placeholder { get; set; } = "Search...";

    [Parameter]
    public string FrequentlyUsedClass { get; set; } = "text-warning icon-dashboard-star-full";

    [Parameter]
    public IEnumerable<AutocompleteItem<TKey>>? Items { get; set; }

    [Parameter]
    public EventCallback<AutocompleteReadDataEventArgs> OnSearch { get; set; }

    [Parameter]
    public TKey SelectedID { get; set; }

    [Parameter]
    public string SelectedText { get; set; }

    private async Task AutocompleteSearch(AutocompleteReadDataEventArgs args)
    {
        Logger.LogTrace("Search start.");

        //does not work
        await OnSearch.InvokeAsync(args);
        StateHasChanged();

        //works
        //Items = new List<AutocompleteItem<TKey>>()
        //{
        //    new AutocompleteItem<TKey>()
        //    {
        //        Display = "test"
        //    }
        //};

        Logger.LogTrace($"Items found: {Items.Count()}");
        Logger.LogTrace("Search complete.");
    }

}

Here is the relevant parts on my page:

@code {
    [Inject]
    private IDAL DB { get; set; }

    //Autocomplete
    private IEnumerable<AutocompleteItem<int>>? AutocompleteItems { get; set; }
    private int AutoCompleteSelectedID { get; set; }
    private string? AutocompleteSelectedText { get; set; }

    private /*async Task*/ void AutocompleteSearch(AutocompleteReadDataEventArgs args)
    {
        if (!args.CancellationToken.IsCancellationRequested)
        {
            AutocompleteItems = DB.SearchSampleItems(args.SearchValue);
        }
    }
}

EDIT
I also tried another approach.  Instead of trying to bind the AutocompleteItems property of my wrapper to a property on my page, then bind
the Data property of the Autocomplete control to the AutocompleteItems property of my wrapper, I tried returning the items in the search arguments.  I think it ends up being cleaner, but still has the same result.

private async Task AutocompleteSearch(AutocompleteReadDataEventArgs args)
{
    Logger.LogTrace($"Search start: {args.SearchValue}");

    //does not work
    var searchArgs = new AutocompleteSearchEventArgs(args.SearchValue, args.CancellationToken);
    await OnSearch.InvokeAsync(searchArgs);
    Items = searchArgs.ItemsFound.ToArray();
    StateHasChanged();

    //works
    //Items = new List<AutocompleteItem<TKey>>()
    //{
    //    new AutocompleteItem<TKey>()
    //    {
    //        Display = "test"
    //    }
    //};

    Logger.LogTrace($"Items found: {Items.Count()}");
    Logger.LogTrace("Search complete.");
}

public class AutocompleteSearchEventArgs
{
    public string SearchValue { get; private set; }

    public CancellationToken CancellationToken { get; private set; }

    public IEnumerable<AutocompleteItem<TKey>> ItemsFound { get; set; }

    public AutocompleteSearchEventArgs(string searchValue, CancellationToken cancellationToken = default(CancellationToken))
    {
        CancellationToken = cancellationToken;
        earchValue = searchValue;
    }
}


问:
TypeError: _jsxDEV is not a function when running User Journey exercise in Cypress tutorial
I'm running in to an issue when trying to complete this section of the Cypress Real World Testing course.

TypeError

TypeError: _jsxDEV is not a function

This error happened while generating the page. Any console logs will be displayed in the terminal window.

Call Stack

_createMdxContent
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/next-mdx-remote/dist/index.js (55:35)

MDXContent
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/next-mdx-remote/dist/index.js (55:35)

processChild
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3353:14)

resolve
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3270:5)

ReactDOMServerRenderer.render
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3753:22)

ReactDOMServerRenderer.read
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3690:29)

Object.renderToString
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (4298:27)

renderDocument
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/next/dist/server/render.js (736:47)

Object.renderToHTML
file:///Users/kylerchavez/Documents/GitHub/cypress-realworld-testing-course-app/node_modules/next/dist/server/render.js (819:34)

process.processTicksAndRejections
node:internal/process/task_queues (95:5)

I've tried deleting node-modules and running npm install again and I've poked around trying to figure out where that function is getting called and can't seem to find it.  Any advice?


问:
codeigniter 4 I run this command 'php spark migrate' and get these errors
[enter image description here](https://i.stack.imgur.com/iUlo0.png)

Microsoft Windows [Version 10.0.21996.1]
(c) Microsoft Corporation. All rights reserved.

C:\xampp\htdocs\ci-4-crud-ajax>php spark migrate

CodeIgniter v4.2.11 Command Line Tool - Server Time: 2023-01-06 12:34:35 UTC-06:00

Running all new migrations...

[CodeIgniter\Database\Exceptions\DatabaseException]

Unable to connect to the database.
Main connection [MySQLi]: No connection could be made because the target machine actively refused it

at SYSTEMPATH\Database\BaseConnection.php:418

C:\xampp\htdocs\ci-4-crud-ajax>

Microsoft Windows [Version 10.0.21996.1]
(c) Microsoft Corporation. All rights reserved.

C:\xampp\htdocs\ci-4-crud-ajax>php spark migrate

CodeIgniter v4.2.11 Command Line Tool - Server Time: 2023-01-06 12:34:35 UTC-06:00

Running all new migrations...

[CodeIgniter\Database\Exceptions\DatabaseException]

Unable to connect to the database.
Main connection [MySQLi]: No connection could be made because the target machine actively refused it

at SYSTEMPATH\Database\BaseConnection.php:418

C:\xampp\htdocs\ci-4-crud-ajax>