问:
The model item passed into the ViewDataDictionary is of type '...', but this ViewDataDictionary instance requires a model item of type '...'
What am I doing?

I am trying using two modal in one view.

What's the problem?

When run give this error:

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ProgramaEstagio.Models.Person', but this ViewDataDictionary instance requires a model item of type 'ProgramaEstagio.Models.RegisterViewModel'.

Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)
</code>```

Part of "PersonController.cs":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ProgramaEstagio.Data;
using ProgramaEstagio.Models;

namespace ProgramaEstagio.Controllers
{
    public class PersonController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PersonController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Person
        public async Task<IActionResult> Index()
        {
            return View(await _context.Person.ToListAsync());
        }
        // GET: Person/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Person.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FullName,BirthDate,sex")] Person person)
        {
            if (id != person.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(person.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }
```
<p><strong>RegisterViewModel.cs:</strong></p>
<pre class="lang-cs prettyprint-override"><code>namespace ProgramaEstagio.Models
{
    public class RegisterViewModel
    {
        public Person Person { get; set; }
        public Address Address { get; set; }
    }
}
</code>```

Edit.cshtml:

@model ProgramaEstagio.Models.RegisterViewModel

@{
    ViewData["Title"] = "Edit";
}

Edit

Person

        <form asp-action="Edit">

            <input type="hidden" asp-for="Person.ID" />

                <input asp-for="Person.FullName" class="form-control" />

                <input asp-for="Person.BirthDate" class="form-control" />

                <input asp-for="Person.sex" class="form-control" />

Address

            <input type="hidden" asp-for="Address.ID" />

                <input asp-for="Address.Country" class="form-control" />

                <input asp-for="Address.Complement" class="form-control" />

                <input asp-for="Address.Distric" class="form-control" />

                <input asp-for="Address.City" class="form-control" />

                <input asp-for="Address.State" class="form-control" />

                <select asp-for="Address.PersonID" class="form-control" asp-items="ViewBag.PersonID"></select>

                <input type="submit" value="Save" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
```
<p>What I have to do? please help me. If need more information, ask please. And sorry for any error orthography and grammar I am studing English.
Project Link: https://github.com/vitorhugo1207/Sys-Vacina/tree/EditPagePersonAdress</p>
<p>Edit:
<strong>AddressController.cs:</strong></p>
<pre class="lang-cs prettyprint-override"><code>        // GET: Addresse/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            RegisterViewModel register = new RegisterViewModel();
            if (id == null)
            {
                return NotFound();
            }

            var address = await _context.Address.FindAsync(id);
            if (address == null)
            {
                return NotFound();
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            register.Address = address;
            return View(register);
        }

        // POST: Addresse/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Country,Complement,Distric,City,State,PersonID")] Address address)
        {
            if (id != address.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(address);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AddressExists(address.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            return View(address);
        }
</code>```

答:
It is happening on this line: return View(person);. You are sending a Model of type Person but you need to send a Model of RegisterViewModel. You need to send the correct Model to your View:

```<code>    public async Task<IActionResult> Edit(int? id)
    {
        RegisterViewModel register = new RegisterViewModel();
        if (id == null)
        {
            return NotFound();
        }

        var person = await _context.Person.FindAsync(id);
        if (person == null)
        {
            return NotFound();
        }
        register.Person = person;
        var address = await _context.Address.FindAsync(id);
        if (address == null)
        {
            return NotFound();
        }
        register.Address = address;
        return View(register);
    }
</code>```

Body:
What am I doing?

I am trying using two modal in one view.

What's the problem?

When run give this error:

An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ProgramaEstagio.Models.Person', but this ViewDataDictionary instance requires a model item of type 'ProgramaEstagio.Models.RegisterViewModel'.

Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)

Part of "PersonController.cs":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ProgramaEstagio.Data;
using ProgramaEstagio.Models;

namespace ProgramaEstagio.Controllers
{
    public class PersonController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PersonController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Person
        public async Task<IActionResult> Index()
        {
            return View(await _context.Person.ToListAsync());
        }
        // GET: Person/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Person.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FullName,BirthDate,sex")] Person person)
        {
            if (id != person.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(person.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }

RegisterViewModel.cs:

namespace ProgramaEstagio.Models
{
    public class RegisterViewModel
    {
        public Person Person { get; set; }
        public Address Address { get; set; }
    }
}

Edit.cshtml:

@model ProgramaEstagio.Models.RegisterViewModel

@{
    ViewData["Title"] = "Edit";
}

Edit

Person

        <form asp-action="Edit">

            <input type="hidden" asp-for="Person.ID" />

                <input asp-for="Person.FullName" class="form-control" />

                <input asp-for="Person.BirthDate" class="form-control" />

                <input asp-for="Person.sex" class="form-control" />

Address

            <input type="hidden" asp-for="Address.ID" />

                <input asp-for="Address.Country" class="form-control" />

                <input asp-for="Address.Complement" class="form-control" />

                <input asp-for="Address.Distric" class="form-control" />

                <input asp-for="Address.City" class="form-control" />

                <input asp-for="Address.State" class="form-control" />

                <select asp-for="Address.PersonID" class="form-control" asp-items="ViewBag.PersonID"></select>

                <input type="submit" value="Save" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

What I have to do? please help me. If need more information, ask please. And sorry for any error orthography and grammar I am studing English.
Project Link: https://github.com/vitorhugo1207/Sys-Vacina/tree/EditPagePersonAdress

Edit:
AddressController.cs:

        // GET: Addresse/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            RegisterViewModel register = new RegisterViewModel();
            if (id == null)
            {
                return NotFound();
            }

            var address = await _context.Address.FindAsync(id);
            if (address == null)
            {
                return NotFound();
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            register.Address = address;
            return View(register);
        }

        // POST: Addresse/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Country,Complement,Distric,City,State,PersonID")] Address address)
        {
            if (id != address.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(address);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AddressExists(address.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            return View(address);
        }

Body:
It is happening on this line: return View(person);. You are sending a Model of type Person but you need to send a Model of RegisterViewModel. You need to send the correct Model to your View:

    public async Task<IActionResult> Edit(int? id)
    {
        RegisterViewModel register = new RegisterViewModel();
        if (id == null)
        {
            return NotFound();
        }

        var person = await _context.Person.FindAsync(id);
        if (person == null)
        {
            return NotFound();
        }
        register.Person = person;
        var address = await _context.Address.FindAsync(id);
        if (address == null)
        {
            return NotFound();
        }
        register.Address = address;
        return View(register);
    }


来源: stackexchange

问:
Issue with .NET 4.8 framework installation on WiX bootstrapper project
I am working on a WiX bootstrapper application with Custom UI that installs a .msi and some .exe files. I have a prerequisite that .NET 4.8 must be installed on the system. If it is not installed then first install the .NET 4.8 framework then install all the other items.

I am using WiX v3.14.0.5722 for the installer application.
Going through the documentation to install .NET 4.8 I follow this article.
Link: How To: Install the .NET Framework Using Burn

```<code><Chain>
    <PackageGroupRef Id="NetFx48Redist"/>
    .....
    .....
</Chain>
</code>```

I have also tried to check and place conditions on the .msi project as below.

```<code><PropertyRef Id="WIX_IS_NETFRAMEWORK_48_OR_LATER_INSTALLED"/>

.......
.......

<Condition Message="This application requires .NET Framework 4.8. Please install the .NET Framework then run this installer again.">
    <![CDATA[Installed OR WIX_IS_NETFRAMEWORK_48_OR_LATER_INSTALLED]]>
</Condition>
</code>```

But no solution is working for me. and I am getting this error as below.

```<code>Bundle.wxs(67,0): error LGHT0094: Unresolved reference to symbol 'ChainPackageGroup:NetFx48Redist'

</code>```

Then I found some implementations about .NET 4.8 installation and import the NetFx48.wxs file from wixtoolset/wix3 and then the  ChainPackageGroup:NetFx48Redist error was gone but another problem I found as below:

```<code>Acquiring package NetFx48Redist, payload NetFx48Redist, download from httpsgo.microsoft.comfwlinkLinkId=2088631
Error 0x80070490 Failed to find expected public key in certificate chain.
Error 0x80070490 Failed to verify expected payload against actual certificate chain.
Error 0x80070490 Failed to verify signature of payload NetFx48Redist

</code>```

I also follow the link .NET 4.8 redistributable downloads have changed its hash and file size and could not solve my problem.

Can anyone help me to solve the .NET 4.8 installation issue? Thank you in advance. Happy coding.

答:
I have solved my problem and I want to share my thought about it as lots of developers can be benefited from this.

As the implementation of .NET 4.8 framework installation in WixNetFxExtension extension was included or not in WiX v3.14.0.5722 WiX version. In my case, it was not working.

So I included the NetFx48.wxs file in my project in both bootstrapper and .msi projects but I have to update the remotePayload.

So how to update remotePayload of NetFx48.wxs

```<code><RemotePayload
          CertificatePublicKey="D17AFCE951979605250FAEBAFA7AE974899AED22"
          CertificateThumbprint="C82273A065EC470FB1EBDE846A91E6FFB29E9C12"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="5A84A8E612E270E27D0061D58DB6B470153BE1F9"
          ProductName="Microsoft .NET Framework 4.8"
          Size="1479400"
          Version="4.8.3928.0" />
<RemotePayload
          CertificatePublicKey="D17AFCE951979605250FAEBAFA7AE974899AED22"
          CertificateThumbprint="C82273A065EC470FB1EBDE846A91E6FFB29E9C12"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="8DD233698D5EB4609B86C2AC917279FE39E0EF4C"
          ProductName="Microsoft .NET Framework 4.8"
          Size="117380440"
          Version="4.8.3928.0" />
</code>```

First, you have to download the ndp48-web.exe and ndp48-x86-x64-allos-enu.exe files then go to wix installation folder. Then run the following command

heat.exe payload [ndp48-web.exe file directory] -out [file_name.wxs]

do it for the second file also.

heat.exe payload [ndp48-x86-x64-allos-enu.exe file directory] -out [file_name.wxs]

Then we can get the updated remotePayload files as shown bellow

```<code> <RemotePayload
          CertificatePublicKey="F49F9B33E25E33CCA0BFB15A62B7C29FFAB3880B"
          CertificateThumbprint="ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="4181398AA1FD5190155AC3A388434E5F7EA0B667"
          ProductName="Microsoft .NET Framework 4.8"
          Size="1439328"
          Version="4.8.4115.0" />

<RemotePayload
          CertificatePublicKey="F49F9B33E25E33CCA0BFB15A62B7C29FFAB3880B"
          CertificateThumbprint="ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="E322E2E0FB4C86172C38A97DC6C71982134F0570"
          ProductName="Microsoft .NET Framework 4.8"
          Size="117380440"
          Version="4.8.4115.0" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a WiX bootstrapper application with Custom UI that installs a .msi and some .exe files. I have a prerequisite that .NET 4.8 must be installed on the system. If it is not installed then first install the .NET 4.8 framework then install all the other items.

I am using WiX v3.14.0.5722 for the installer application.
Going through the documentation to install .NET 4.8 I follow this article.
Link: How To: Install the .NET Framework Using Burn

<Chain>
    <PackageGroupRef Id="NetFx48Redist"/>
    .....
    .....
</Chain>

I have also tried to check and place conditions on the .msi project as below.

<PropertyRef Id="WIX_IS_NETFRAMEWORK_48_OR_LATER_INSTALLED"/>

.......
.......

<Condition Message="This application requires .NET Framework 4.8. Please install the .NET Framework then run this installer again.">
    <![CDATA[Installed OR WIX_IS_NETFRAMEWORK_48_OR_LATER_INSTALLED]]>
</Condition>

But no solution is working for me. and I am getting this error as below.

Bundle.wxs(67,0): error LGHT0094: Unresolved reference to symbol 'ChainPackageGroup:NetFx48Redist'

Then I found some implementations about .NET 4.8 installation and import the NetFx48.wxs file from wixtoolset/wix3 and then the  ChainPackageGroup:NetFx48Redist error was gone but another problem I found as below:

Acquiring package NetFx48Redist, payload NetFx48Redist, download from httpsgo.microsoft.comfwlinkLinkId=2088631
Error 0x80070490 Failed to find expected public key in certificate chain.
Error 0x80070490 Failed to verify expected payload against actual certificate chain.
Error 0x80070490 Failed to verify signature of payload NetFx48Redist

I also follow the link .NET 4.8 redistributable downloads have changed its hash and file size and could not solve my problem.

Can anyone help me to solve the .NET 4.8 installation issue? Thank you in advance. Happy coding.

Body:
I have solved my problem and I want to share my thought about it as lots of developers can be benefited from this.

As the implementation of .NET 4.8 framework installation in WixNetFxExtension extension was included or not in WiX v3.14.0.5722 WiX version. In my case, it was not working.

So I included the NetFx48.wxs file in my project in both bootstrapper and .msi projects but I have to update the remotePayload.

So how to update remotePayload of NetFx48.wxs

<RemotePayload
          CertificatePublicKey="D17AFCE951979605250FAEBAFA7AE974899AED22"
          CertificateThumbprint="C82273A065EC470FB1EBDE846A91E6FFB29E9C12"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="5A84A8E612E270E27D0061D58DB6B470153BE1F9"
          ProductName="Microsoft .NET Framework 4.8"
          Size="1479400"
          Version="4.8.3928.0" />
<RemotePayload
          CertificatePublicKey="D17AFCE951979605250FAEBAFA7AE974899AED22"
          CertificateThumbprint="C82273A065EC470FB1EBDE846A91E6FFB29E9C12"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="8DD233698D5EB4609B86C2AC917279FE39E0EF4C"
          ProductName="Microsoft .NET Framework 4.8"
          Size="117380440"
          Version="4.8.3928.0" />

First, you have to download the ndp48-web.exe and ndp48-x86-x64-allos-enu.exe files then go to wix installation folder. Then run the following command

heat.exe payload [ndp48-web.exe file directory] -out [file_name.wxs]

do it for the second file also.

heat.exe payload [ndp48-x86-x64-allos-enu.exe file directory] -out [file_name.wxs]

Then we can get the updated remotePayload files as shown bellow

 <RemotePayload
          CertificatePublicKey="F49F9B33E25E33CCA0BFB15A62B7C29FFAB3880B"
          CertificateThumbprint="ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="4181398AA1FD5190155AC3A388434E5F7EA0B667"
          ProductName="Microsoft .NET Framework 4.8"
          Size="1439328"
          Version="4.8.4115.0" />

<RemotePayload
          CertificatePublicKey="F49F9B33E25E33CCA0BFB15A62B7C29FFAB3880B"
          CertificateThumbprint="ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B"
          Description="Microsoft .NET Framework 4.8 Setup"
          Hash="E322E2E0FB4C86172C38A97DC6C71982134F0570"
          ProductName="Microsoft .NET Framework 4.8"
          Size="117380440"
          Version="4.8.4115.0" />


问:
how to check null value of Integer type field in ASP.NET MVC view?
I have integer type field in database which is having property "Not Null".

when i create a view & do a validation, if i left that field blank, it will consider it as 0 so i can not compare it with 0 because if someone insert a value 0 then it will be considered as error!

one another problem is that i am using Model error as described in the book "ASP.NET MVC 1.0" @ Scott Gu blog.  And I am checking the value in partial class of object (created by LINQ-To-SQL). i.e

```<code>public partial class Person
{
    public bool IsValid
    {
        get { return (GetRuleViolations().Count() == 0); }
    }
    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name))
            yield return new RuleViolation("Name is Required", "Name");
        if (Age == 0)
            yield return new RuleViolation("Age is Required", "Age");
        yield break;
    }
    partial void OnValidate(ChangeAction action)
    {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }
}
</code>```

There is also problem with range.

Like in database if i declared as smallint i.e. short in c#, now if i exceed that range then it gives error as "A Value is reguired".

so finally is there any best way for validation in ASP.NET MVC?

答:
I would validate the form on the client first. If the age is 0 then let the user know that it's not a valid age. On the server change the message, it's misleading:

```<code>if (Age == 0)
    yield return new RuleViolation("0 years is not a valid age", "Age");
</code>```

I know that because you bind to a model property from your Person entity it gets 0 as the default value - why don't you change that in the database then? Set a default in the database to a value that you consider reasonable for the user age, so that it no longer displays as 0 for new entities.

If you don't want to change the db values, use jQuery to set the textbox values to empty strings on your Create page when it loads. If the user tries to submit such a form you can check on the client to disallow it and on the server you don't have to do anything, the user will get a "A value is required" message back.

By the way, you wrote:

i can not compare it with 0 because if
  someone insert a value 0 then it will
  be considered as error

I don't see a problem in this particular domain model. Do you think that age of 0 is a good value or not? Ask yourself.

OwnerDisplayName: Vikas

ContentLicense: CC BY-SA 2.5

Body:
I have integer type field in database which is having property "Not Null".

when i create a view & do a validation, if i left that field blank, it will consider it as 0 so i can not compare it with 0 because if someone insert a value 0 then it will be considered as error!

one another problem is that i am using Model error as described in the book "ASP.NET MVC 1.0" @ Scott Gu blog.  And I am checking the value in partial class of object (created by LINQ-To-SQL). i.e

public partial class Person
{
    public bool IsValid
    {
        get { return (GetRuleViolations().Count() == 0); }
    }
    public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name))
            yield return new RuleViolation("Name is Required", "Name");
        if (Age == 0)
            yield return new RuleViolation("Age is Required", "Age");
        yield break;
    }
    partial void OnValidate(ChangeAction action)
    {
        if (!IsValid)
            throw new ApplicationException("Rule violations prevent saving");
    }
}

There is also problem with range.

Like in database if i declared as smallint i.e. short in c#, now if i exceed that range then it gives error as "A Value is reguired".

so finally is there any best way for validation in ASP.NET MVC?

Body:
I would validate the form on the client first. If the age is 0 then let the user know that it's not a valid age. On the server change the message, it's misleading:

if (Age == 0)
    yield return new RuleViolation("0 years is not a valid age", "Age");

I know that because you bind to a model property from your Person entity it gets 0 as the default value - why don't you change that in the database then? Set a default in the database to a value that you consider reasonable for the user age, so that it no longer displays as 0 for new entities.

If you don't want to change the db values, use jQuery to set the textbox values to empty strings on your Create page when it loads. If the user tries to submit such a form you can check on the client to disallow it and on the server you don't have to do anything, the user will get a "A value is required" message back.

By the way, you wrote:

i can not compare it with 0 because if
  someone insert a value 0 then it will
  be considered as error

I don't see a problem in this particular domain model. Do you think that age of 0 is a good value or not? Ask yourself.

OwnerDisplayName: Pawel Krakowiak


问:
What's most performant way in iOS to check if a string is one of a list of strings?
I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?

Since my comparison list is rather small, I'm currently trying this:

```<code>- (BOOL) isStringInList:(NSString *)testString{

if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
   return YES;

return NO;
}
</code>```

This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.

Any thoughts on how to improve performance would be appreciated.

答:
```<code>- (BOOL)isString:(NSString*)testString inList:(NSString*)listString
{
    BOOL result = NO;
    if (testString != nil)
    {
        NSRange range = [listString rangeOfString:testString];
        result = (range.location != NSNotFound);
    }
    return result;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?

Since my comparison list is rather small, I'm currently trying this:

- (BOOL) isStringInList:(NSString *)testString{

if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
   return YES;

return NO;
}

This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.

Any thoughts on how to improve performance would be appreciated.


问:
pass props with Lazy loading in react-router-dom v6
I need to pass props to the lazy components.

```<code>const A = React.lazy(() => import("./A"));

function App() {
return (
      <Suspense fallback={<GlobalLoader />}>
        <Routes>
          <Route path="/s/:name" element={<ValidateName />} />
          <Route path="/s" element={<Page fullsize={true}><A name='default'/></Page>} />
          <Route path="*" element={<Navigate replace to='/s' />} />
        </Routes>
      </Suspense>
)
}
const Validatename = () => {
    const {name} = useParams();
    let allowedValues =[{'name':a, ... },{'name':b, ... },{'name':c, ... }]
    let validValue = allowedValues.filter((i)=>i.name === name);
    let isValid = (validValue > 0);

    if(!isValid) return <Navigate replace to =='/s'>
    return <Page fullSize={true}><A name={name}/></Page>
}
</code>```

Edit:

Desired outcome: Lazy Loading for Component A.

Component A is initialised with either 'default' value or value passed in URL i.e. 'name'

Which value to pass is decided by ValidateName Component and default route /s.

Problem: How to pass prop 'name' in A so that it can be loaded lazily.

答:
It is not possible in this outer context

Instead, you can use useParams() to get the path in the lazy loaded component A

if you want you can create a wrapper around A and call useParams() here like following however basically it is the same thing.

```<code>const AWrapper= () => {
  const { path } = useParams();
  if(path.id){
      return <A prop={path.id} />
  } else{
      return <A props="default" />
  }
};
</code>```

PS: you should change A to AWrapper in Route too

Body:
I need to pass props to the lazy components.

const A = React.lazy(() => import("./A"));

function App() {
return (
      <Suspense fallback={<GlobalLoader />}>
        <Routes>
          <Route path="/s/:name" element={<ValidateName />} />
          <Route path="/s" element={<Page fullsize={true}></Page>} />
          <Route path="*" element={<Navigate replace to='/s' />} />
        </Routes>
      </Suspense>
)
}
const Validatename = () => {
    const {name} = useParams();
    let allowedValues =[{'name':a, ... },{'name':b, ... },{'name':c, ... }]
    let validValue = allowedValues.filter((i)=>i.name === name);
    let isValid = (validValue > 0);

    if(!isValid) return <Navigate replace to =='/s'>
    return <Page fullSize={true}></Page>
}

Edit:

Desired outcome: Lazy Loading for Component A.

Component A is initialised with either 'default' value or value passed in URL i.e. 'name'

Which value to pass is decided by ValidateName Component and default route /s.

Problem: How to pass prop 'name' in A so that it can be loaded lazily.

Body:
It is not possible in this outer context

Instead, you can use useParams() to get the path in the lazy loaded component A

if you want you can create a wrapper around A and call useParams() here like following however basically it is the same thing.

const AWrapper= () => {
  const { path } = useParams();
  if(path.id){
      return <A prop={path.id} />
  } else{
      return <A props="default" />
  }
};

PS: you should change A to AWrapper in Route too


问:
How overwrite docs with scripts in google?
I make one script to auto fill a Google Doc from a Google Form Submissiom. Now I need another script to overwrite the document when there is a change in some spreadsheet value . (the user cannot edit the form's response but can change values in the spreadsheet).

enter image description here

答:
As long as you know what paragraph it is that needs to be edited you can try this.

Before:

```<code>function myFunction() {
  try {
    var doc = DocumentApp.getActiveDocument();
    var body = doc.getBody();
    var paras = body.getParagraphs();
    var i = 0;
    for( i=0; i<paras.length; i+=2 ) {
      paras[i].setText("Line "+(100+i));
    }
  }
  catch(err) {
    console.log(err);
  }
}
</code>```

After:

Body:
As long as you know what paragraph it is that needs to be edited you can try this.

Before:

function myFunction() {
  try {
    var doc = DocumentApp.getActiveDocument();
    var body = doc.getBody();
    var paras = body.getParagraphs();
    var i = 0;
    for( i=0; i<paras.length; i+=2 ) {
      paras[i].setText("Line "+(100+i));
    }
  }
  catch(err) {
    console.log(err);
  }
}

After:


问:
Apply a function to two columns of dataframe and create a new column
I want to apply this function on the following columns but I could not.</p>
```<code>def damage(a,b):
  l=5
  if (a==b+0.3) or ((a>=1.5* b) and (a<=1.9 * b)):
    l=1
  elif  (a>=2* b) and (a<=2.9 * b) :
    l=2
  elif   (a>=4) or (a>= 3* b):
    l=3
  elif (a==b) or (a<=b+0.3)  or (a<= 1.5 *b):
    l=0
  return l

df['1st_day_damage'] =df[df['Cr-1'],df['Cr']].apply(damage)
</code>```

答:
It's better to use vectorized code. apply is slow.

Coding in the blind since you didn't provide any example:

a = df['Cr-1']
b = df['Cr']

df['1st_day_damage'] = np.select(
    [
        (a == b + 0.3) | ((1.5 * b <= a) & (a <= 1.9 * b)),
        (2 * b <= a) & (a <= 2.9 * b),
        (a >= 4) | (a >= 3 * b),
        (a == b) | (a <= b + 0.3) | (a <= 1.5 * b)
    ],
    [
        1,
        2,
        3,
        0
    ],
    default=5
)

```

Body:
I want to apply this function on the following columns but I could not.

def damage(a,b):
  l=5
  if (a==b+0.3) or ((a>=1.5* b) and (a<=1.9 * b)):
    l=1
  elif  (a>=2* b) and (a<=2.9 * b) :
    l=2
  elif   (a>=4) or (a>= 3* b):
    l=3
  elif (a==b) or (a<=b+0.3)  or (a<= 1.5 *b):
    l=0
  return l

df['1st_day_damage'] =df[df['Cr-1'],df['Cr']].apply(damage)


问:
Mongoose - How to change the TTL based on another field?
How would I set the TTL based on another field in the schema? I want to set the the expireAt field to whatever value accountType is (the value can be a month /  a week / a day).However, this code doesn't expire the document or change the expiry date. I've tried many variations of the TTL field but it doesn't seem to work.

import mongoose from 'mongoose'
import { generateKey } from '../lib/generateKey'

const KeySchema = new mongoose.Schema({
  key: {
    type: String,
    default: generateKey,
    required: true,
  },
  accountType: { /* The value can be a month, a week or a day*/
    type: String,
    required: true,
  },
  dailyLimit: {
    type: Number,
    default: 0,
    required: true,
  },
  expireAt: {
    type: Date,
    default: Date.now,
    index: {
      expireAfterSeconds: 60
    }
  },
})

KeySchema.pre('save', function (next) {
  switch (this.accountType) {
    case 'month':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 30
      }
      break
    case 'week':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 7
      }
      break
    case 'day':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 1
      }
      break
  }

  next()
})

export default mongoose.models.Key || mongoose.model('Key', KeySchema)
```

I've tried
createdAt: { type: Date, expires: 600 },
KeySchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 })
expireAt: { type: Date, default: Date.now, index: { expires: '5s' }}

答:
MongoDB handles TTL using an index

Mongoose creates the TTL index at the same time it create all of the other indexes, based on the schema, and the same index is used for all documents.

While it is possible to have partial indexes based on field values, MongoDB does not permit creating multiple indexes that contain the same keys but different options, like expiry.

Instead of trying to vary the index option expireAfterSeconds for each document, you might add another field to the scheme named deleteAt with expireAfterSeconds set to 0, then in the pre-save function set deletedAt based on the values of the expireAt and accountType fields.

Body:
How would I set the TTL based on another field in the schema? I want to set the the expireAt field to whatever value accountType is (the value can be a month /  a week / a day).However, this code doesn't expire the document or change the expiry date. I've tried many variations of the TTL field but it doesn't seem to work.

import mongoose from 'mongoose'
import { generateKey } from '../lib/generateKey'

const KeySchema = new mongoose.Schema({
  key: {
    type: String,
    default: generateKey,
    required: true,
  },
  accountType: { /* The value can be a month, a week or a day*/
    type: String,
    required: true,
  },
  dailyLimit: {
    type: Number,
    default: 0,
    required: true,
  },
  expireAt: {
    type: Date,
    default: Date.now,
    index: {
      expireAfterSeconds: 60
    }
  },
})

KeySchema.pre('save', function (next) {
  switch (this.accountType) {
    case 'month':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 30
      }
      break
    case 'week':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 7
      }
      break
    case 'day':
      this.expireAt.index = {
        expires: 60 * 60 * 24 * 1
      }
      break
  }

  next()
})

export default mongoose.models.Key || mongoose.model('Key', KeySchema)

I've tried
createdAt: { type: Date, expires: 600 },
KeySchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 })
expireAt: { type: Date, default: Date.now, index: { expires: '5s' }}


问:
How can I make the lines to enter on a new line on auto as I write across on Vscode?
The code in Vscode is not entering a new line on auto as I write across. It just keeps going sideways making it hard to see all the code.

答: Go to View then enable Word wrap.

Body: Go to View then enable Word wrap.


问:
Device build number hidden?
I just got a new phone (HTC Desire) running android 4.4 and I am trying to set it up for development but I can't find the build number in order to tap it 7 times in order to reveal the development options, I've already been able to and had much luck with other phones but this one leaves me confused.</p>

答:
Not sure if it's the different Android versions or the phone versions, but on different phones, it may be at different locations. Instead of "Build number" it might be "Software version" on some phones.

Most Android phones:

“Settings”>”About”>Tap ”Build Number” 7 times quickly or more.

Other android phones:

"Settings">"System Management">"About Phone">Tap "Software version" 7
times quickly or more.

Just tap anything in "About" that has "build number" or "software info" or "software version" in it, as different phones seem to have different locations.

Title: Device build number hidden?


问:
How to slide-in an element in a row and animate siblings with relative width in VueJS
I want to slide-in an element in a row and make the other elements width shrink accordingly but still maintain their relative widths:

```<code>    <div style="width: 100%; display: flex">
      <div id="firstColumn" style="flex-grow: 1"></div>
      <div id="secondColumn" style="flex-grow: 2"></div>
      <div id="thirdColumn" style="flex-grow: 1" v-if="showColumn"></div>
    </div>
</code>```

I have tried vue transition on the third column (see CodePen) but the animation does not work as expected  and the two other columns just snaps in place. I am guessing that there is a simple/elegant way to do this?

答:
note that in the code-pen you've used .slide-enter which in vue3 should be .slide-enter-from

How elements in the flex get their size

You're using a transform: translate(100%,0) rule on the third element to move it across the screen.

when the flexbox calculates their size for each child, it won't take into account any transforms. It will calculate as if the element is already there in place.

Thus the 'snap' when you click the button.

The size of the children is calculated by looking at the flex-grow, flex-shrink, width, min-width and max-width css properties.

Have size of the column be part of the animation

You can make the size of the new column be part of the animation.

By animating the flex-grow property from 0 to the actual size.

this will cause the siblings to also re-size when the new column is animating.

```<code>.slide-enter-active,
.slide-leave-active {
  transition: all 1s;
}

slide-enter-from,
.slide-leave-to {
  transform: translate(100%, 0);
  flex-grow:0 !important;
}
</code>```

Example

Code pen example

I think you can drop the translate from the animation; but I don't know what you want your animation to look like.

Body:
I want to slide-in an element in a row and make the other elements width shrink accordingly but still maintain their relative widths:

I have tried vue transition on the third column (see CodePen) but the animation does not work as expected  and the two other columns just snaps in place. I am guessing that there is a simple/elegant way to do this?

Body:
note that in the code-pen you've used .slide-enter which in vue3 should be .slide-enter-from

How elements in the flex get their size

You're using a transform: translate(100%,0) rule on the third element to move it across the screen.

when the flexbox calculates their size for each child, it won't take into account any transforms. It will calculate as if the element is already there in place.

Thus the 'snap' when you click the button.

The size of the children is calculated by looking at the flex-grow, flex-shrink, width, min-width and max-width css properties.

Have size of the column be part of the animation

You can make the size of the new column be part of the animation.

By animating the flex-grow property from 0 to the actual size.

this will cause the siblings to also re-size when the new column is animating.

.slide-enter-active,
.slide-leave-active {
  transition: all 1s;
}

slide-enter-from,
.slide-leave-to {
  transform: translate(100%, 0);
  flex-grow:0 !important;
}

Example

Code pen example

I think you can drop the translate from the animation; but I don't know what you want your animation to look like.


问:
ValueError: Expected object or value - read_json method pandas
I am trying to read in a large .json file into a pandas dataframe on google colab. I have read similar problems on here as well as the api for read_json method to no avail. I feel that the orient='records' arg should work for my json. Any help would be appreciated.

My code:

```<code>import pandas as pd

df = pd.read_json('/content/data/events_World_Cup.json', orient='records')
</code>```

The error:

```<code>/usr/local/lib/python3.7/dist-packages/pandas/io/json/_json.py in _parse_no_numpy(self)
   1157         else:
   1158             self.obj = DataFrame(
-> 1159                 loads(json, precise_float=self.precise_float), dtype=None
   1160             )
   1161

ValueError: Expected object or value
</code>```

An element of my json file:

```<code>[
    {"eventId": 8,
     "subEventName": "Simple pass",
     "tags": [{"id": 1801}],
     "playerId": 122671,
     "positions": [{"y": 50, "x": 50}, {"y": 53, "x": 35}],
     "matchId": 2057954,
     "eventName": "Pass",
     "teamId": 16521,
     "matchPeriod": "1H",
     "eventSec": 1.6562140000000003,
     "subEventId": 85,
     "id": 258612104
     }
.
.
.
]
</code>```

The entire json file can be found here:
https://figshare.com/articles/dataset/Events/7770599?backTo=/collections/Soccer_match_event_dataset/4415000

I am using the events_World_Cup.json to start off given its size.

Thank you

答:
This worked for me;

```<code>pd.read_json('events_World_Cup.json', orient='records')
</code>```

Pandas version: 1.3.4

Python version: 3.10.0

Can you please check your pandas version?

Body:
I am trying to read in a large .json file into a pandas dataframe on google colab. I have read similar problems on here as well as the api for read_json method to no avail. I feel that the orient='records' arg should work for my json. Any help would be appreciated.

My code:

import pandas as pd

df = pd.read_json('/content/data/events_World_Cup.json', orient='records')

The error:

/usr/local/lib/python3.7/dist-packages/pandas/io/json/_json.py in _parse_no_numpy(self)
   1157         else:
   1158             self.obj = DataFrame(
-> 1159                 loads(json, precise_float=self.precise_float), dtype=None
   1160             )
   1161

ValueError: Expected object or value

An element of my json file:

[
    {"eventId": 8,
     "subEventName": "Simple pass",
     "tags": [{"id": 1801}],
     "playerId": 122671,
     "positions": [{"y": 50, "x": 50}, {"y": 53, "x": 35}],
     "matchId": 2057954,
     "eventName": "Pass",
     "teamId": 16521,
     "matchPeriod": "1H",
     "eventSec": 1.6562140000000003,
     "subEventId": 85,
     "id": 258612104
     }
.
.
.
]

The entire json file can be found here:
https://figshare.com/articles/dataset/Events/7770599?backTo=/collections/Soccer_match_event_dataset/4415000

I am using the events_World_Cup.json to start off given its size.

Thank you

Body:
This worked for me;

pd.read_json('events_World_Cup.json', orient='records')

Pandas version: 1.3.4

Python version: 3.10.0

Can you please check your pandas version?


问:
Nodemon: Error: listen EADDRINUSE: address already in use :::5000
I'm creating a project and using nodejs, express for the backend.
Everything works fine but as I make any change in the file, nodemon is unable to restart the server due to following error:

Error: listen EADDRINUSE: address already in use :::5000

index.js:

```<code>const express = require("express");
const morgan = require("morgan");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const dotenv = require("dotenv");
var passport = require("passport");

dotenv.config();

const PORT = process.env.PORT || 5000;

const app = express();

.....

app.listen(PORT, () => console.log(`Server listening on port ${PORT}!`));
</code>```

package.json

{
  "name": "chat-app-backend",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon --ignore 'sessions/' index.js"
  },
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^8.2.0",
    "express": "~4.16.0",
    "express-session": "^1.17.0",
    "http-errors": "~1.6.2",
    "jade": "~1.11.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.9.4",
    "morgan": "~1.9.0",
    "passport": "^0.4.1",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^6.0.1",
    "session-file-store": "^1.4.0",
    "uuid": "^7.0.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.2"
  }
}
```

I've to explicitly kill the server from the terminal every time, which is not the optimal solution.
I tried several things, but none are working. Even found some issue in nodemon GitHub issue page, but there also I couldn't find anything.

I'm also adding the output of lsof -i:5000, even if server I'm closing the server - *node    31625 rishav   20u  IPv6 5300049      0t0  TCP :5000 (LISTEN)

答:
I came across this recently in vscode working on node.js project using port 3000.
At the terminal simply type:

npx kill-port 3000
```

Body:
I'm creating a project and using nodejs, express for the backend.
Everything works fine but as I make any change in the file, nodemon is unable to restart the server due to following error:

Error: listen EADDRINUSE: address already in use :::5000

index.js:

const express = require("express");
const morgan = require("morgan");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const dotenv = require("dotenv");
var passport = require("passport");

dotenv.config();

const PORT = process.env.PORT || 5000;

const app = express();

.....

app.listen(PORT, () => console.log(`Server listening on port ${PORT}!`));

package.json

{
  "name": "chat-app-backend",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon --ignore 'sessions/' index.js"
  },
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^8.2.0",
    "express": "~4.16.0",
    "express-session": "^1.17.0",
    "http-errors": "~1.6.2",
    "jade": "~1.11.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.9.4",
    "morgan": "~1.9.0",
    "passport": "^0.4.1",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^6.0.1",
    "session-file-store": "^1.4.0",
    "uuid": "^7.0.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.2"
  }
}

I've to explicitly kill the server from the terminal every time, which is not the optimal solution.
I tried several things, but none are working. Even found some issue in nodemon GitHub issue page, but there also I couldn't find anything.

I'm also adding the output of lsof -i:5000, even if server I'm closing the server - *node    31625 rishav   20u  IPv6 5300049      0t0  TCP :5000 (LISTEN)


问:
Scroll only scrollable div and not page in Blazor Server
I've seen quite a few old posts with similar issues but haven't been able to quite find a solution that works for me.  In my blazor server project I have a script that should scroll a div inside a component on pages.  (timeline of events).  This div should scroll on load (to bottom of items).  Now if the timelone is not in view when it loads (lower down on page, this is by design) it would also bring the div into view (scroll the page down), where I only want the div to scroll to the bottom.  This is what I currently use.  What's the easiest way to only make the div scroll, and not the page even if the div isn't visible?

The reason I also specify an item in my script is that if events happen higher up (event status changes, etc) then it requires view, so it would scroll up to get to the item of focus. On page load, I would just specify the index of the last item.

```<code> <script>
        function ListViewScroll(args) {
            let div = document.getElementById('lstTimeLine');
            div.querySelector('[data-uid="' + args.id + '"]').scrollIntoView({ behavior: 'smooth' });
        }
</script>
</code>```

Thanks so much for help in advance.

答:
To Mister Magoo's point, This is what worked for me:

```<code>function ScrollTimelineToBottom() {
             let div = document.getElementById('lstTimeLine');
             div.scrollTop = div.scrollHeight;
        } ;
</code>```

Sorry for the dup post.

Body:
I've seen quite a few old posts with similar issues but haven't been able to quite find a solution that works for me.  In my blazor server project I have a script that should scroll a div inside a component on pages.  (timeline of events).  This div should scroll on load (to bottom of items).  Now if the timelone is not in view when it loads (lower down on page, this is by design) it would also bring the div into view (scroll the page down), where I only want the div to scroll to the bottom.  This is what I currently use.  What's the easiest way to only make the div scroll, and not the page even if the div isn't visible?

The reason I also specify an item in my script is that if events happen higher up (event status changes, etc) then it requires view, so it would scroll up to get to the item of focus. On page load, I would just specify the index of the last item.

Thanks so much for help in advance.

Body:
To Mister Magoo's point, This is what worked for me:

function ScrollTimelineToBottom() {
             let div = document.getElementById('lstTimeLine');
             div.scrollTop = div.scrollHeight;
        } ;

Sorry for the dup post.


问:
How to run/connect to Entrypoint process via socket/port (executable)
TL;DR
"Reading/writing to stdin/stdout of Entrypoint executable process on running container (ex. Docker, podman) via socket/http"

My question is in regards to executable containers and how to spin/wrap them up as servers, and connect to them remotely (socket/curl/http).

I have an executable container that is not a server, just a standalone executable ENTRYPOINT command. (Example: wkhtmltopdf). I would love to use an image like that as a container, but not make it a part of my own container/Dockerfile (i.e. not to modify/maintain it).

As I understand if I run this image as a container, it will immediately die as there is no input/ on this process and it does not act as a server/listening for connections.

A lot of tutorials state that you can run containers via docker run ... command.

If I am on Windows inside WSL2 distro I am not necessarily going to have docker installed locally. But I believe that we can connect to other containers that are on the same network (default bridge network).

But how would one spin-up/expose executable container as a server and connect to it's stdin/stdout?

I want for container to listen on port (direct to executable stdin), process the request with said executable, and obtain the results from stdout/curl.

What I think can work:

Spinning process as a server (Golang example)

Do I need to wrap every executable that I want to expose BUT not make it as a part of my own Dockerfile or is there a common pattern/tool I can use for such a scenario.

P.S. wkhtmltopdf executable example I gave also comes with python and node included. (I am thinking about some sort of one-liner solution akin to docker run --rm -v ... X ... python -m SimpleHTTPServer ... )

答:
This answer just describes the situation on Linux.

I haven't tested this but I think you could combine systemd socket activation

```<code>[Socket]
ListenStream=127.0.0.1:9999
Accept=yes
</code>```

(see example https://unix.stackexchange.com/questions/551000/systemd-socket-activation-stdin)

with netcat (see example
https://unix.stackexchange.com/questions/332163/netcat-send-text-to-echo-service-read-reply-then-exit)

Use the -i flag, i.e., podman run -i ... or docker run -i to pass stdin in to the container.

Body:
This answer just describes the situation on Linux.

I haven't tested this but I think you could combine systemd socket activation

[Socket]
ListenStream=127.0.0.1:9999
Accept=yes

(see example https://unix.stackexchange.com/questions/551000/systemd-socket-activation-stdin)

with netcat (see example
https://unix.stackexchange.com/questions/332163/netcat-send-text-to-echo-service-read-reply-then-exit)

Use the -i flag, i.e., podman run -i ... or docker run -i to pass stdin in to the container.


问:
Show image name inside the image field in Django forms
I have this edit or update form in which I want to display only the image name in the form for a better user experience so that the user could know which image he has uploaded while creating the data.
I am storing the image name in the model as well,but i want to display the image name inside the image field.
forms.py

```<code>class MenuCategoryForm(forms.ModelForm):
    image = forms.ImageField(allow_empty_file=True, required=False)

    class Meta:
        model = MenuCategory
        fields = ['name', 'description', 'menu_options']
</code>```

view

```<code>def menu_category_update(request, id):
    item = MenuCategory.objects.get(id=id)

    if request.method == 'POST':
        form = MenuCategoryForm(request.POST, request.FILES, instance=item)

        if form.is_valid():
            if request.FILES['image']:
                image = request.FILES['image']
                image_url = upload_image(image, 'menu_category', image.name)
                obj = form.save(commit=False)
                obj.image_url = image_url
                form.save()

            else:
                form.save()
            return redirect('menu-category')

    else:
        form = MenuCategoryForm(instance=item)

    context = {
        'form': form,
        'item': item
    }
    return render(request, 'menu/menu_category_update.html', context)
</code>```

Template

```<code>{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
  <div class="row Edit-form-box">
    <div class="form-inner-box bg-white">
      <div class="heading-editing">
        <h3>Edit menu category</h3>
      </div>

      <form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
        {% csrf_token %} {{ form|crispy }}

        <div class="update-buttons-container">
          <button class="btn btn-info1" type="submit" value="Update">
            Update
          </button>
          <a class="btn btn-secondary" href="{% url 'menu-category' %}"
            >Cancel</a
          >
        </div>
      </form>
    </div>
  </div>
</div>

{% endblock %}
</code>```

答:
Well in other to get the name of the image in your form you will be better off in using a form initial like so:

```<code>def menu_category_update(request,id):
    item = MenuCategory.objects.get(id=id)
    if request.method == 'POST':
        form = MenuCategoryForm(request.POST, request.FILES, instance=item)
        if form.is_valid:
            obj = form.save(commit=False)
           # obj.username = request.user
            form.save()
            return redirect('menu-category')
        else:
            form = MenuCategoryForm(
                initial={'image':item.image,
                                'name':item.name,
                                  'description':iteem.description,
})# this are the fields that we want to show in the form
    context = {
        'form': form,
        'item': item
    }
    return render(request, 'menu/menu_category_update.html', context)

</code>```

In your form html you will apply the form initial to the field that you want to show in your form, by doing something like this: form.initial.name As i have illustrated below :

```<code>{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
  <div class="row Edit-form-box">
    <div class="form-inner-box bg-white">
      <div class="heading-editing">
        <h3>Edit menu category</h3>
      </div>

      <form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
        {% csrf_token %}
     <label> Image name </label>
       {{form.initial.name}}
    <label> Description </label>
        {{ form.initial.description }}
        <label> Image </label>
       {{ form.initial.image }}
        <div class="update-buttons-container">
          <button class="btn btn-info1" type="submit" value="Update">
            Update
          </button>
          <a class="btn btn-secondary" href="{% url 'menu-category' %}"
            >Cancel</a
          >
        </div>
      </form>
    </div>
  </div>
</div>

{% endblock %}
</code>```

Body:
I have this edit or update form in which I want to display only the image name in the form for a better user experience so that the user could know which image he has uploaded while creating the data.
I am storing the image name in the model as well,but i want to display the image name inside the image field.
forms.py

class MenuCategoryForm(forms.ModelForm):
    image = forms.ImageField(allow_empty_file=True, required=False)

    class Meta:
        model = MenuCategory
        fields = ['name', 'description', 'menu_options']

view

def menu_category_update(request, id):
    item = MenuCategory.objects.get(id=id)

    if request.method == 'POST':
        form = MenuCategoryForm(request.POST, request.FILES, instance=item)

        if form.is_valid():
            if request.FILES['image']:
                image = request.FILES['image']
                image_url = upload_image(image, 'menu_category', image.name)
                obj = form.save(commit=False)
                obj.image_url = image_url
                form.save()

            else:
                form.save()
            return redirect('menu-category')

    else:
        form = MenuCategoryForm(instance=item)

    context = {
        'form': form,
        'item': item
    }
    return render(request, 'menu/menu_category_update.html', context)

Template

{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}

{% block content %}

Edit menu category

      <form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
        {% csrf_token %} {{ form|crispy }}

          <button class="btn btn-info1" type="submit" value="Update">
            Update
          </button>
          Cancel

      </form>

{% endblock %}

Body:
Well in other to get the name of the image in your form you will be better off in using a form initial like so:

def menu_category_update(request,id):
    item = MenuCategory.objects.get(id=id)
    if request.method == 'POST':
        form = MenuCategoryForm(request.POST, request.FILES, instance=item)
        if form.is_valid:
            obj = form.save(commit=False)
           # obj.username = request.user
            form.save()
            return redirect('menu-category')
        else:
            form = MenuCategoryForm(
                initial={'image':item.image,
                                'name':item.name,
                                  'description':iteem.description,
})# this are the fields that we want to show in the form
    context = {
        'form': form,
        'item': item
    }
    return render(request, 'menu/menu_category_update.html', context)

In your form html you will apply the form initial to the field that you want to show in your form, by doing something like this: form.initial.name As i have illustrated below :

{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
  <div class="row Edit-form-box">
    <div class="form-inner-box bg-white">
      <div class="heading-editing">
        <h3>Edit menu category</h3>
      </div>

      <form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
        {% csrf_token %}
     <label> Image name </label>
       {{form.initial.name}}
    <label> Description </label>
        {{ form.initial.description }}
        <label> Image </label>
       {{ form.initial.image }}
        <div class="update-buttons-container">
          <button class="btn btn-info1" type="submit" value="Update">
            Update
          </button>
          <a class="btn btn-secondary" href="{% url 'menu-category' %}"
            >Cancel</a
          >
        </div>
      </form>
    </div>
  </div>
</div>

{% endblock %}


问:
Closing the div tag making form unusable
I am creating a form using HTML with the NodeJs backend.
The form is not submitting if I close one of the div tag. This is really weird and if I keep it open then it is submitting fine.

I have spend a lot of time in this and I am unable to see where I am doing wrong. I have counted all the div multiple times but the count is coming to be fine.
Below is my HTML form -

```<code><% layout('layouts/boilerPlate') %>
<h1 class="text-center mb-3">Experiment Detail</h1>
<div class="col-6 offset-3">
    <form action="/plannerHome" method="POST" class="classification" enctype="multipart/form-data" >
        <div class="classifications">
            <label class="form-label" for="taskName">Experiment name: </label>
            <input type="text" name="taskName" id="taskName" required>
        </div>
    <!-- The closing tag of this div is causing problem -->
        <div class="classifications">
            <label class="form-label" for="taskType">Experiment Type: </label>
            <select name="taskType" id = "taskType">
                <option value="None">Please Select a Experiment type</option>
                <option value="classify">Classification</option>
                <option value="instance-segmentation">Instance Segmentation</option>
                <option value="semantic-segmentation">Semantic Segmentation</option>
                <option value="localisation">Localisation</option>
            </select>
        <!--</div> This is causing problem -->
    <!-- For the Supplementary material to revise -->
        <div class="classifications">
            <label class="form-label" for="dataManual">Supplementary material: </label>
            <input class="form-control" type="file" id="dataManual" name="dataManual">
        </div>
    <!-- For the input file -->
        <div class="classifications">
            <label class="form-label" for="labelFile">Label file: </label>
            <input class="form-control" type="file" id="labelFile" name="labelFile" >
        </div>
    <!-- Upload file folder : https://stackoverflow.com/questions/43958335/select-folder-instead-of-single-file-input-->

        <div class="classifications">
            <label class="form-label" for="data">Data: </label>
            <input class="form-control mb-3 " type="file" id="data" name="data">
        </div>

    </form>
    <div class="mb-3">
        <button>Create Experiment</button>
    </div>
</div>
</code>```

答:
There are 2 issues I see here.

You are not closing the input tags which are self-closing tags.

THE PROBLEM: The button is not within the form and you are not attaching the click event in the button to your form - or at least not in the included form.

Here is a revised and working version of your code

<% layout('layouts/boilerPlate') %>

Experiment Detail

    <form action="/plannerHome" method="POST" class="classification" enctype="multipart/form-data" >

            Experiment name:
            <input type="text" name="taskName" id="taskName" required />

            Experiment Type:
            <select name="taskType" id="taskType">
                <option value="None">Please Select a Experiment type</option>
                <option value="classify">Classification</option>
                <option value="instance-segmentation">Instance Segmentation</option>
                <option value="semantic-segmentation">Semantic Segmentation</option>
                <option value="localisation">Localisation</option>
            </select>

            Supplementary material:
            <input class="form-control" type="file" id="dataManual" name="dataManual" />

            Label file:
            <input class="form-control" type="file" id="labelFile" name="labelFile" />

            Data:
            <input class="form-control mb-3 " type="file" id="data" name="data" />

            <button type="submit">Create Experiment</button>

    </form>

    ```

Body:
I am creating a form using HTML with the NodeJs backend.
The form is not submitting if I close one of the div tag. This is really weird and if I keep it open then it is submitting fine.

I have spend a lot of time in this and I am unable to see where I am doing wrong. I have counted all the div multiple times but the count is coming to be fine.
Below is my HTML form -

<% layout('layouts/boilerPlate') %>

Experiment Detail

    <form action="/plannerHome" method="POST" class="classification" enctype="multipart/form-data" >

            Experiment name:
            <input type="text" name="taskName" id="taskName" required>

            Experiment Type:
            <select name="taskType" id = "taskType">
                <option value="None">Please Select a Experiment type</option>
                <option value="classify">Classification</option>
                <option value="instance-segmentation">Instance Segmentation</option>
                <option value="semantic-segmentation">Semantic Segmentation</option>
                <option value="localisation">Localisation</option>
            </select>

            Supplementary material:
            <input class="form-control" type="file" id="dataManual" name="dataManual">

            Label file:
            <input class="form-control" type="file" id="labelFile" name="labelFile" >

            Data:
            <input class="form-control mb-3 " type="file" id="data" name="data">

    </form>

        <button>Create Experiment</button>

Body:
There are 2 issues I see here.

You are not closing the input tags which are self-closing tags.

THE PROBLEM: The button is not within the form and you are not attaching the click event in the button to your form - or at least not in the included form.

Here is a revised and working version of your code

<% layout('layouts/boilerPlate') %>
<h1 class="text-center mb-3">Experiment Detail</h1>
<div class="col-6 offset-3">
    <form action="/plannerHome" method="POST" class="classification" enctype="multipart/form-data" >
        <div class="classifications">
            <label class="form-label" for="taskName">Experiment name: </label>
            <input type="text" name="taskName" id="taskName" required />
        </div>
    <!-- The closing tag of this div is causing problem -->
        <div class="classifications">
            <label class="form-label" for="taskType">Experiment Type: </label>
            <select name="taskType" id="taskType">
                <option value="None">Please Select a Experiment type</option>
                <option value="classify">Classification</option>
                <option value="instance-segmentation">Instance Segmentation</option>
                <option value="semantic-segmentation">Semantic Segmentation</option>
                <option value="localisation">Localisation</option>
            </select>
        </div><!-- This is causing problem -->
    <!-- For the Supplementary material to revise -->
        <div class="classifications">
            <label class="form-label" for="dataManual">Supplementary material: </label>
            <input class="form-control" type="file" id="dataManual" name="dataManual" />
        </div>
    <!-- For the input file -->
        <div class="classifications">
            <label class="form-label" for="labelFile">Label file: </label>
            <input class="form-control" type="file" id="labelFile" name="labelFile" />
        </div>
    <!-- Upload file folder : https://stackoverflow.com/questions/43958335/select-folder-instead-of-single-file-input-->

        <div class="classifications">
            <label class="form-label" for="data">Data: </label>
            <input class="form-control mb-3 " type="file" id="data" name="data" />
        </div>
        <div class="mb-3">
            <button type="submit">Create Experiment</button>
        </div>
    </form>
</div>


问:
SQL: return all rows that contain more than two identical absolute values in a column grouped by another column
I have a table with the following content:

Batch
Amount

1
250

1
-250

1
250

1
100

2
50

3
100

3
100

There may be a different number of rows for each batch, the values of 'Amount' are random and may contain positive or negative numbers.

I need to return Batches for which there are more than two identical absolute values of Amount (in the example above that would be batch 1)

答:
Looks like a group by & having:

Sample data:

```<code>SQL> with test (batch, amount) as
  2    (select 1,  250 from dual union all
  3     select 1, -250 from dual union all
  4     select 1,  250 from dual union all
  5     select 1,  100 from dual union all
  6     select 2,   50 from dual union all
  7     select 3,  100 from dual union all
  8     select 3,  100 from dual
  9    )
</code>```

Query:

```<code> 10  select batch
 11  from test
 12  group by batch, abs(amount)
 13  having count(*) > 2;

     BATCH
----------
         1

SQL>
</code>```

Body:
Looks like a group by & having:

Sample data:

SQL> with test (batch, amount) as
  2    (select 1,  250 from dual union all
  3     select 1, -250 from dual union all
  4     select 1,  250 from dual union all
  5     select 1,  100 from dual union all
  6     select 2,   50 from dual union all
  7     select 3,  100 from dual union all
  8     select 3,  100 from dual
  9    )

Query:

 10  select batch
 11  from test
 12  group by batch, abs(amount)
 13  having count(*) > 2;

     BATCH
----------
         1

SQL>