问:
InvalidOperationException : Asp.Net Core Model object usage in .cshtml
I have Upsert.cshtml assosciated with BooksController when I am trying to add book when loading the view it is getting the exception as mentioned below.

I am learning Asp.Net core as per my understanding Model means we can access the book object of controller and access the properties.Please help with this why I am not able to access Id using Model?

Upsert.cshtml

```<code>@{
    ViewData["Title"] = "Upsert";
}
@model BookListMVC.Models.Book

<br />
<h2 class="text-info">@(Model.Id != 0 ? "Edit" : "Create") Book</h2>
<br />
<div class="Border container" style="padding:30px;">
    <form method="post">
        @if (Model.Id != 0)
        {
            <input type="hidden" asp-for="Id" />
        }
        <div class="text-danger" asp-validation-summary="ModelOnly"></div>
        <div class="form-group row">
            <div class="form-group row">
                <div class="col-3">
                    <label asp-for="Name"></label>
                </div>
                <div class="col-7">
                    <input asp-for="Name" class="form-control" />
                </div>
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <div class="form-group row">
                <div class="col-3">
                    <label asp-for="Author"></label>
                </div>
                <div class="col-7">
                    <input asp-for="Author" class="form-control" />
                </div>
                <span asp-validation-for="Author" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <div class="form-group row">
                <div class="col-3">
                    <label asp-for="ISBN"></label>
                </div>
                <div class="col-7">
                    <input asp-for="ISBN" class="form-control" />
                </div>
                <span asp-validation-for="ISBN" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-3 offset-3">
                <button type="submit" value="Create" class="btn btn-primary form-control">
                    @(Model.Id != 0 ? "Update" : "Create")
                </button>
            </div>
            <div class="col-3">
                <a asp-page="Index" class="btn btn-success form-control">Back to List</a>
            </div>
        </div>
    </form>
</div>

@section Scripts{
    <partial name="_ValidationScriptsPartial" />
}

InvalidOperationException: The relative page path 'Index' can only be used while executing a Razor Page. Specify a root relative path with a leading '/' to generate a URL outside of a Razor Page. If you are using LinkGenerator then you must provide the current HttpContext to use relative pages.
Microsoft.AspNetCore.Mvc.Routing.UrlHelperBase.CalculatePageName(ActionContext context, RouteValueDictionary ambientValues, string pageName)
Microsoft.AspNetCore.Mvc.Routing.UrlHelperBase.NormalizeRouteValuesForPage(ActionContext context, string page, string handler, RouteValueDictionary values, RouteValueDictionary ambientValues)
Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Page(IUrlHelper urlHelper, string pageName, string pageHandler, object values, string protocol, string host, string fragment)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GeneratePageLink(ViewContext viewContext, string linkText, string pageName, string pageHandler, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Books_Upsert.<ExecuteAsync>b__21_0() in Upsert.cshtml
+
                    @(Model.Id != 0 ? "Update" : "Create")
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
AspNetCore.Views_Books_Upsert.ExecuteAsync() in Upsert.cshtml
+
<h2 class="text-info">@(Model.Id != 0 ? "Edit" : "Create") Book</h2>
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)

Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

答:
The error message means you use the wrong tag helper asp-page,change like below:

```<code><a asp-action="Index" class="btn btn-success form-control">Back to List</a>
</code>```

The whole demo like below:

Model:

```<code>public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

Index.cshtml:

```<code>@model IEnumerable<Book>

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

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>
</code>```

Create.cshtml:

```<code>@{
    ViewData["Title"] = "Upsert";
}
@model Book

<br />
<h2 class="text-info">@(Model.Id != 0 ? "Edit" : "Create") Book</h2>
<br />
<div class="Border container" style="padding:30px;">
    <form method="post">
        @if (Model.Id != 0)
        {
            <input type="hidden" asp-for="Id" />
        }
        <div class="text-danger" asp-validation-summary="ModelOnly"></div>
        <div class="form-group row">
            <div class="form-group row">
                <div class="col-3">
                    <label asp-for="Name"></label>
                </div>
                <div class="col-7">
                    <input asp-for="Name" class="form-control" />
                </div>
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group row">
            <div class="col-3 offset-3">
                <button type="submit" value="Create" class="btn btn-primary form-control">
                    @(Model.Id != 0 ? "Update" : "Create")
                </button>
            </div>
            <div class="col-3">
                <a asp-action="Index" class="btn btn-success form-control">Back to List</a>
            </div>
        </div>
    </form>
</div>

@section Scripts{
    <partial name="_ValidationScriptsPartial" />
}
</code>```

Controller:

```<code>public class BooksController : Controller
{
    private readonly MyDbContext _context;

    public BooksController(MyDbContext context)
    {
        _context = context;
    }
    // GET: Books
    public async Task<IActionResult> Index()
    {
        return View(await _context.Book.ToListAsync());
    }

    // GET: Books/Create
    public IActionResult Create()
    {
        var model = new Book() { Id = 0 };
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Name")] Book book)
    {
        if (ModelState.IsValid)
        {
            _context.Add(book);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(book);
    }

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

        var book = await _context.Book.FindAsync(id);
        if (book == null)
        {
            return NotFound();
        }
        return View("Create",book);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Book book)
    {
        if (id != book.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            _context.Update(book);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View("Create",book);
    }
}
</code>```

Body:
I have Upsert.cshtml assosciated with BooksController when I am trying to add book when loading the view it is getting the exception as mentioned below.

I am learning Asp.Net core as per my understanding Model means we can access the book object of controller and access the properties.Please help with this why I am not able to access Id using Model?

Upsert.cshtml

@{
    ViewData["Title"] = "Upsert";
}
@model BookListMVC.Models.Book

@(Model.Id != 0 ? "Edit" : "Create") Book

    <form method="post">
        @if (Model.Id != 0)
        {
            <input type="hidden" asp-for="Id" />
        }

                    <input asp-for="Name" class="form-control" />

                    <input asp-for="Author" class="form-control" />

                    <input asp-for="ISBN" class="form-control" />

                <button type="submit" value="Create" class="btn btn-primary form-control">
                    @(Model.Id != 0 ? "Update" : "Create")
                </button>

                Back to List

    </form>

@section Scripts{
    <partial name="_ValidationScriptsPartial" />
}

InvalidOperationException: The relative page path 'Index' can only be used while executing a Razor Page. Specify a root relative path with a leading '/' to generate a URL outside of a Razor Page. If you are using LinkGenerator then you must provide the current HttpContext to use relative pages.
Microsoft.AspNetCore.Mvc.Routing.UrlHelperBase.CalculatePageName(ActionContext context, RouteValueDictionary ambientValues, string pageName)
Microsoft.AspNetCore.Mvc.Routing.UrlHelperBase.NormalizeRouteValuesForPage(ActionContext context, string page, string handler, RouteValueDictionary values, RouteValueDictionary ambientValues)
Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Page(IUrlHelper urlHelper, string pageName, string pageHandler, object values, string protocol, string host, string fragment)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GeneratePageLink(ViewContext viewContext, string linkText, string pageName, string pageHandler, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Books_Upsert.<ExecuteAsync>b__21_0() in Upsert.cshtml
+
                    @(Model.Id != 0 ? "Update" : "Create")
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
AspNetCore.Views_Books_Upsert.ExecuteAsync() in Upsert.cshtml
+

@(Model.Id != 0 ? "Edit" : "Create") Book

Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)

Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Body:
The error message means you use the wrong tag helper asp-page,change like below:

<a asp-action="Index" class="btn btn-success form-control">Back to List</a>

The whole demo like below:

Model:

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Index.cshtml:

@model IEnumerable<Book>

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

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Create.cshtml:

@{
    ViewData["Title"] = "Upsert";
}
@model Book

<br />
<h2 class="text-info">@(Model.Id != 0 ? "Edit" : "Create") Book</h2>
<br />
<div class="Border container" style="padding:30px;">
    <form method="post">
        @if (Model.Id != 0)
        {
            <input type="hidden" asp-for="Id" />
        }
        <div class="text-danger" asp-validation-summary="ModelOnly"></div>
        <div class="form-group row">
            <div class="form-group row">
                <div class="col-3">
                    <label asp-for="Name"></label>
                </div>
                <div class="col-7">
                    <input asp-for="Name" class="form-control" />
                </div>
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group row">
            <div class="col-3 offset-3">
                <button type="submit" value="Create" class="btn btn-primary form-control">
                    @(Model.Id != 0 ? "Update" : "Create")
                </button>
            </div>
            <div class="col-3">
                <a asp-action="Index" class="btn btn-success form-control">Back to List</a>
            </div>
        </div>
    </form>
</div>

@section Scripts{
    <partial name="_ValidationScriptsPartial" />
}

Controller:

public class BooksController : Controller
{
    private readonly MyDbContext _context;

    public BooksController(MyDbContext context)
    {
        _context = context;
    }
    // GET: Books
    public async Task<IActionResult> Index()
    {
        return View(await _context.Book.ToListAsync());
    }

    // GET: Books/Create
    public IActionResult Create()
    {
        var model = new Book() { Id = 0 };
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Name")] Book book)
    {
        if (ModelState.IsValid)
        {
            _context.Add(book);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(book);
    }

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

        var book = await _context.Book.FindAsync(id);
        if (book == null)
        {
            return NotFound();
        }
        return View("Create",book);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Book book)
    {
        if (id != book.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            _context.Update(book);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View("Create",book);
    }
}


来源: stackexchange

问:
What does "Unable to inject Capacitor" mean and how can I fix it?
I tried migrating a Cordova test app to Capacitor according to 1 and encountered the following error in logcat on Android:

```<code>E/Capacitor( 3537): Unable to inject Capacitor, Plugins won't work
</code>```

and the deviceready event seems to be missing.

Here is www/index.html:

demo-app

```

<p>Here is <code>www/app.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>document
  .getElementById('status')
  .appendChild(document.createElement('b'))
  .appendChild(document.createTextNode('status:'))

document.addEventListener('deviceready', function () {
  document
    .getElementById('status')
    .appendChild(document.createElement('i'))
    .appendChild(document.createTextNode('ready'))
})
</code>```

FYI the Cordova test app was generated by generate-cordova-package and modified to remove the extremely simple HEADER and CSS.

[1] https://capacitor.ionicframework.com/docs/cordova/migrating-from-cordova-to-capacitor/

答:
After a bit of research, I discovered the following gem from this comment on ionic-team/capacitor issue 1572:

Capacitor injects itself into html files searching for the head tag

So just inserting  into the HTML resolves this issue and causes the Cordova-compatible deviceready event to be sent.

I really hope to see this documented in 1 and 2 the near future.

[1] https://capacitor.ionicframework.com/docs/cordova/migrating-from-cordova-to-capacitor/

[2] https://capacitor.ionicframework.com/docs/getting-started/

P.S. This subject is also discussed here: https://forum.ionicframework.com/t/unable-to-inject-capacitor/178713

I raised this PR to get this documented: https://github.com/ionic-team/capacitor/pull/3024

ContentLicense: CC BY-SA 4.0

Body:
I tried migrating a Cordova test app to Capacitor according to 1 and encountered the following error in logcat on Android:

E/Capacitor( 3537): Unable to inject Capacitor, Plugins won't work

and the deviceready event seems to be missing.

Here is www/index.html:

demo-app

Here is www/app.js:

document
  .getElementById('status')
  .appendChild(document.createElement('b'))
  .appendChild(document.createTextNode('status:'))

document.addEventListener('deviceready', function () {
  document
    .getElementById('status')
    .appendChild(document.createElement('i'))
    .appendChild(document.createTextNode('ready'))
})

FYI the Cordova test app was generated by generate-cordova-package and modified to remove the extremely simple HEADER and CSS.

[1] https://capacitor.ionicframework.com/docs/cordova/migrating-from-cordova-to-capacitor/

Body:
After a bit of research, I discovered the following gem from this comment on ionic-team/capacitor issue 1572:

Capacitor injects itself into html files searching for the head tag

So just inserting <head></head> into the HTML resolves this issue and causes the Cordova-compatible deviceready event to be sent.

I really hope to see this documented in 1 and 2 the near future.

[1] https://capacitor.ionicframework.com/docs/cordova/migrating-from-cordova-to-capacitor/

[2] https://capacitor.ionicframework.com/docs/getting-started/

P.S. This subject is also discussed here: https://forum.ionicframework.com/t/unable-to-inject-capacitor/178713

I raised this PR to get this documented: https://github.com/ionic-team/capacitor/pull/3024


问:
Adding List Data to Another List Based on Their Value
I have a List:

```<code>    List<MenuItem> makanan = [
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/mie goreng.jpeg'),
    namaMenu: 'Mie Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Mie Kuah',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Campur',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Bakso Komplit',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
];
</code>```

also have Model that I want to make list from my previous list like this:

```<code>class TableOrder {
  String namaMakanan;
  int qtyMakanan;
  String noteMakanan;

  TableOrder({this.namaMakanan, this.qtyMakanan, this.noteMakanan});
}
</code>```

How can I get data from previous list into new list based on their qty value, if the qty is more than 0 that data will be added into new list.

答:
use the where method of list

List<MenuItem> newMakanan = makanan.where((item) => item.qty > 0).toList();
```

docs here

Body:
I have a List:

    List<MenuItem> makanan = [
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/mie goreng.jpeg'),
    namaMenu: 'Mie Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Mie Kuah',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Campur',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Bakso Komplit',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
];

also have Model that I want to make list from my previous list like this:

class TableOrder {
  String namaMakanan;
  int qtyMakanan;
  String noteMakanan;

  TableOrder({this.namaMakanan, this.qtyMakanan, this.noteMakanan});
}

How can I get data from previous list into new list based on their qty value, if the qty is more than 0 that data will be added into new list.

Body:
use the where method of list

List<MenuItem> newMakanan = makanan.where((item) => item.qty > 0).toList();

docs here


问:
Custom Library component is not a known element, but app compiles and runs

The Problem

My html files warn that my custom components/pipes 'are not a known element'. However building and running the application works as intended, and the custom components/pipes are functional. The dichotomy of the components working but showing as errors is annoying and can be difficult to work with. I know this is a small thing, but I really want to not see errors in my html files when there are no errors.

Summary

I have two distinct angular projects; an angular library which I consume with my angular application. The library exports several custom components, pipes and services which the application uses. I do not have this library published via npm, instead I use npm-link to give the application access to the library. This seems to work as any service/component defined in my applications components work and doesn't complain. Though the moment I put anything in my template file from my library, that selector is underlined and a warning appears.

The files

```<code>/*Library Module*/
@NgModule({
  declarations: [
    ThemeToggleComponent,
    // Other custom components/pipes
  ],
  exports: [
    ThemeToggleComponent,
    // Other components needed in templates files
  ]
})
export class MyCommonModule {}

</code>```
```<code>/*
 * Public API Surface of my-common library
 */

export * from './lib/my-common.module';
/*
 * Many other components, services, pipes, etc etc
 */
export * from './lib/theme-toggle/theme-toggle.component';

</code>```
```<code>/* Consuming Application module */
import { MyCommonModule } from 'my-common';

@NgModule({
  imports: [
    MyCommonModule,
  ],
  declarations: [
    MyComponent,
  ],
})
export class MyModule {}
</code>```
```<code>/* Template of MyComponent, my.component.html */
<div>
  <my-theme-toggle (darkThemeSelected)="toggleTheme($event)"></my-theme-toggle>
</div>
</code>```

The file above will have all lines which reference my custom components underlined in red with the error message 'my-theme-toggle' is not a known element: ...if it is, verify it is apart of the module.

Attempts to fix

I've tried a things, but to no avail

Not using NPM link and just copying the library created by ng-packagr into the node modules of my application

Rebuilding and relinking/restarting everything

Searching for other S.O questions: most questions are about build failures because the import/export was actually incorrect.

My hunches

I think this is an issue with the paths compiler option in tsconfig.json in the consuming application. Throughout all of my research this is the one thing that pops up more than anything else. I currently do not have a path set, because everything is working. My common library looks and acts like any other node_module library, other than this issue.

My other thought is that because everything works and runs, then the issue may be with vs-code not understanding the import, or something of that nature. Though I think this is unlikely.

The background

Both angular projects are on version 9, rc7. I use ng-packagr to build my library. I use visual studio code, and at the time of writing I am on the latest release.

EDIT
This problem went away upon upgrading to angular 11, I think several of the other issues might solve it, but this feels like the best option.

答:
I have exactly the same problem. Here is a fix,

Adding

```<code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
</code>```

and

```<code>schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],
</code>```

to your module

A complete app.module.ts for your reference

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgNiceSelectModule } from 'ng-nice-select';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgNiceSelectModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})
export class AppModule { }
</code>```

Body:
The Problem

My html files warn that my custom components/pipes 'are not a known element'. However building and running the application works as intended, and the custom components/pipes are functional. The dichotomy of the components working but showing as errors is annoying and can be difficult to work with. I know this is a small thing, but I really want to not see errors in my html files when there are no errors.

Summary

I have two distinct angular projects; an angular library which I consume with my angular application. The library exports several custom components, pipes and services which the application uses. I do not have this library published via npm, instead I use npm-link to give the application access to the library. This seems to work as any service/component defined in my applications components work and doesn't complain. Though the moment I put anything in my template file from my library, that selector is underlined and a warning appears.

The files

/*Library Module*/
@NgModule({
  declarations: [
    ThemeToggleComponent,
    // Other custom components/pipes
  ],
  exports: [
    ThemeToggleComponent,
    // Other components needed in templates files
  ]
})
export class MyCommonModule {}

/*
 * Public API Surface of my-common library
 */

export * from './lib/my-common.module';
/*
 * Many other components, services, pipes, etc etc
 */
export * from './lib/theme-toggle/theme-toggle.component';

/* Consuming Application module */
import { MyCommonModule } from 'my-common';

@NgModule({
  imports: [
    MyCommonModule,
  ],
  declarations: [
    MyComponent,
  ],
})
export class MyModule {}

/* Template of MyComponent, my.component.html */

  <my-theme-toggle (darkThemeSelected)="toggleTheme($event)"></my-theme-toggle>

The file above will have all lines which reference my custom components underlined in red with the error message 'my-theme-toggle' is not a known element: ...if it is, verify it is apart of the module.

Attempts to fix

I've tried a things, but to no avail

Not using NPM link and just copying the library created by ng-packagr into the node modules of my application

Rebuilding and relinking/restarting everything

Searching for other S.O questions: most questions are about build failures because the import/export was actually incorrect.

My hunches

I think this is an issue with the paths compiler option in tsconfig.json in the consuming application. Throughout all of my research this is the one thing that pops up more than anything else. I currently do not have a path set, because everything is working. My common library looks and acts like any other node_module library, other than this issue.

My other thought is that because everything works and runs, then the issue may be with vs-code not understanding the import, or something of that nature. Though I think this is unlikely.

The background

Both angular projects are on version 9, rc7. I use ng-packagr to build my library. I use visual studio code, and at the time of writing I am on the latest release.

EDIT
This problem went away upon upgrading to angular 11, I think several of the other issues might solve it, but this feels like the best option.

Body:
I have exactly the same problem. Here is a fix,

Adding

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

and

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

to your module

A complete app.module.ts for your reference

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgNiceSelectModule } from 'ng-nice-select';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgNiceSelectModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ]
})
export class AppModule { }


问:
Gridview wrap content flutter
I have a json, I want to display it in gridview, the json has many content, in gridview I just want to show only 9 items.

The problem was I want to wrap the content of the gridview but I dont know how.
I tried wrap widget. If its not possible then I guess I'll reconsider using columns and row for this one.

Please check the code below.

```<code>class ServicesWidget extends StatefulWidget {
  @override
  _ServicesState createState() => _ServicesState();
}

class _ServicesState extends State<ServicesWidget> {
  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: GridView.count(
        crossAxisCount: 3,
        childAspectRatio: 1,
        children: <Widget>[
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
        ],
      ),
    );
  }
}

</code>```

```<code>class HomeScreen extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<HomeScreen> {

  @override
  Widget build(BuildContext context) {
    return DirectSelectContainer(
      child: Scaffold(
          appBar: AppBar(
            title: Row(
              children: <Widget>[
                // cityDirectSelect(),
                // areaDirectSelect(),
                Spacer(flex: 1),
                IconButton(
                  padding: EdgeInsets.all(0),
                  icon: Icon(Icons.person),
                  color: Colors.grey,
                  onPressed: () {
                    Get.off(LoginScreen());
                  },
                )
              ],
            ),
          ),
          body: Center(
            child: Container(
              child: Column(
                children: <Widget>[
                  ServicesWidget(),
                  Container(
                    width: double.infinity,
                    child: Text('qweqwe'),
                    color: Colors.red,
                  )
                ],
              ),
            ),
          )),
    );
  }
}
</code>```

答: I solve it using shrinkWrap. Now the gridview height is wrapped according to its children.shrinkwrap gridview</p>

Title: Gridview wrap content flutter

Body:
I have a json, I want to display it in gridview, the json has many content, in gridview I just want to show only 9 items.

The problem was I want to wrap the content of the gridview but I dont know how.
I tried wrap widget. If its not possible then I guess I'll reconsider using columns and row for this one.

Please check the code below.

class ServicesWidget extends StatefulWidget {
  @override
  _ServicesState createState() => _ServicesState();
}

class _ServicesState extends State<ServicesWidget> {
  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: GridView.count(
        crossAxisCount: 3,
        childAspectRatio: 1,
        children: <Widget>[
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
          Center(child: Text('qwe')),
        ],
      ),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<HomeScreen> {

  @override
  Widget build(BuildContext context) {
    return DirectSelectContainer(
      child: Scaffold(
          appBar: AppBar(
            title: Row(
              children: <Widget>[
                // cityDirectSelect(),
                // areaDirectSelect(),
                Spacer(flex: 1),
                IconButton(
                  padding: EdgeInsets.all(0),
                  icon: Icon(Icons.person),
                  color: Colors.grey,
                  onPressed: () {
                    Get.off(LoginScreen());
                  },
                )
              ],
            ),
          ),
          body: Center(
            child: Container(
              child: Column(
                children: <Widget>[
                  ServicesWidget(),
                  Container(
                    width: double.infinity,
                    child: Text('qweqwe'),
                    color: Colors.red,
                  )
                ],
              ),
            ),
          )),
    );
  }
}


问:
How to load multiple controls in a view
I am still clueless how to start preparing a form like this on MVC 3.

I am a beginner and all I have learned till now is to bind data from controller to the strongly typed view. But as I know that we can return only one varibale from the return statment

public ActionResult(int id)
{
   // Do some logic
   return View(role);
}

Now the above code return the role list to the view. But how would I pass other details also like Licence state, organization.. etc *

Another complex example:

Let say my form need to display details like Country [drop down], State [Drop down], Department [ComboBox list], Organization [radio button list], List of all employee [table/Grid]

How would I display all the controls value with single RETURN?

Note: * I assume that all the detials like role, Licence state, Organization etc I am fetching from database.

I hope I am clear with my explanation, please let me know if I need to explain it bit further.

Also, I am sorry for this stupid question, this is because I am in my very first learning stage of MVC

答:
You would write a view model:

```<code>public class MyViewModel
{
    public SomeModel1 Section1 { get; set; }
    public SomeModel2 Section2 { get; set; }
    public SomeModel3 Section3 { get; set; }
}
</code>```

and in your controller action you will return this view model to the view:

```<code>public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Section1 = ...,
            Section2 = ...,
            Section3 = ...,
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        ... process the model when the form is submitted
    }
}
</code>```

and in the view:

```<code>@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Section1)
    @Html.EditorFor(x => x.Section2)
    @Html.EditorFor(x => x.Section3)
    ...
}
</code>```

and of course you will have strongly typed editor templates for each section:

~/Views/Shared/EditorTemplates/SomeModel1.cshtml

~/Views/Shared/EditorTemplates/SomeModel2.cshtml

~/Views/Shared/EditorTemplates/SomeModel3.cshtml

...

which will represent the partial contents of each section

ContentLicense: CC BY-SA 3.0

Title: How to load multiple controls in a view

Body:
You would write a view model:

public class MyViewModel
{
    public SomeModel1 Section1 { get; set; }
    public SomeModel2 Section2 { get; set; }
    public SomeModel3 Section3 { get; set; }
}

and in your controller action you will return this view model to the view:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Section1 = ...,
            Section2 = ...,
            Section3 = ...,
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        ... process the model when the form is submitted
    }
}

and in the view:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Section1)
    @Html.EditorFor(x => x.Section2)
    @Html.EditorFor(x => x.Section3)
    ...
}

and of course you will have strongly typed editor templates for each section:

~/Views/Shared/EditorTemplates/SomeModel1.cshtml

~/Views/Shared/EditorTemplates/SomeModel2.cshtml

~/Views/Shared/EditorTemplates/SomeModel3.cshtml

...

which will represent the partial contents of each section


问:
Can I use the userSub in AWS Cognito as primary key?
I am looking to use the data that comes with Cognito as secondary key to connect to other database.Potentially, I could use username or email. However, according to the project requirement, there will be lots of concerns of using sensitive data as primary key for other database. I am looking for an alternative way to set the unique key. Wonder whether userSub can be used as unique key for each users? Or there's any other values that I can use?</p>

答:
Im my opinion I would not use an email address as a key.

How would this affect the system if the user decided to change the email address in the future or for some reason the email address simply becomes obsolete.

The sub I think would be a decent choice to use as a key. However, whenever I am thinking about primary keys I'm always thinking a million years in the future.

Ultimately I would choose a key that will forever be unique throughout the org eliminating the possibility of any future conflicts or in your case, confidentiality issues.


问:
WPF: Textbox and Binding to Double not able to type . on it
I have a text box like

```<code><TextBox Text="{Binding TransactionDetails.TransactionAmount, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="5"
x:Name="TextBoxAmount"/>
</code>```

And I have taken "TransactionAmount" as Double. Its working well on integer value but when I am typing some Floating point value like 100.456 I am not able to type '.'

答:
you can replace the default converter with this class when binding to double type source data. This is more convient to use. below is the code:</p>

```<code>public class double2txtConverter : IValueConverter
    {
        string _strCache;
        double _dCache;
        //Convert double to string of textbox.
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (_dCache == (double)value)
                return _strCache;
            else
                return value.ToString();
        }
        //convert string to double;
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            _strCache = (string)value;
            _dCache = double.Parse(_strCache);
            return _dCache;
        }
    }
//below is codebehind usage:
        Binding bd = new Binding(path);
        bd.Converter = new double2txtConverter();
        bd.Source = source;
        bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        txtTarget.SetBinding(TextBox.TextProperty, bd);
</code>```

Body:
I have a text box like

<TextBox Text="{Binding TransactionDetails.TransactionAmount, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.ColumnSpan="2" Grid.Row="5"
x:Name="TextBoxAmount"/>

And I have taken "TransactionAmount" as Double. Its working well on integer value but when I am typing some Floating point value like 100.456 I am not able to type '.'

Body:
you can replace the default converter with this class when binding to double type source data. This is more convient to use. below is the code:

public class double2txtConverter : IValueConverter
    {
        string _strCache;
        double _dCache;
        //Convert double to string of textbox.
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (_dCache == (double)value)
                return _strCache;
            else
                return value.ToString();
        }
        //convert string to double;
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            _strCache = (string)value;
            _dCache = double.Parse(_strCache);
            return _dCache;
        }
    }
//below is codebehind usage:
        Binding bd = new Binding(path);
        bd.Converter = new double2txtConverter();
        bd.Source = source;
        bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        txtTarget.SetBinding(TextBox.TextProperty, bd);


问:
How to import python file from different folder in Visual Studio Code?
I can't import a python file from different folder in visual studio code. I also tried to save a init.py file in my module but got the same error.
I don't wanna use pythonPATH.

```<code>import my_module.shopping_cart
</code>```

the error I get:

```<code>/python/sample codes/notebook.py", line 4, in <module>
import my_module.shopping_cart
</code>```

ModuleNotFoundError: No module named 'my_module'

答:
Give me an example.
I just test in my machine with tree folder

```<code>C:.
├───child
├───---- child.py
├───parent
├───---- parent.py
</code>```

In child.py

```<code>aaa = 1234
print aaa
</code>```

In parent.py

```<code>import sys
sys.path.insert(1, '../child')
from child import aaa

print aaa
</code>```

And result:

```<code>1234 # result from child.py
1234 # result from parent.py
</code>```

Body:
I can't import a python file from different folder in visual studio code. I also tried to save a init.py file in my module but got the same error.
I don't wanna use pythonPATH.

import my_module.shopping_cart

the error I get:

/python/sample codes/notebook.py", line 4, in <module>
import my_module.shopping_cart

ModuleNotFoundError: No module named 'my_module'

Body:
Give me an example.
I just test in my machine with tree folder

C:.
├───child
├───---- child.py
├───parent
├───---- parent.py

In child.py

aaa = 1234
print aaa

In parent.py

import sys
sys.path.insert(1, '../child')
from child import aaa

print aaa

And result:

1234 # result from child.py
1234 # result from parent.py


问:
stop character been inserted into input react
I want to detect which character base on user keyboard hence I use onKeyDown, but how do I stop ',' been inserted into the input element?</p>

```<code>const [inputValue, setInputValue] = useState("");

  const handleKeyDown = (e: any) => {
    if (['188'].includes(e.keyCode)) {
      console.log("do something");
    }
  };

  const handleChange = (e: any) => {
    setInputValue(e.target.value)
  }

  return (
      <input
        type="text"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
  );
</code>```

答:
```<code>const handleKeyDown = (e: any) => {
  if (['188'].includes(e.keyCode)) {
      return;
  }
};
</code>```

Body:
I want to detect which character base on user keyboard hence I use onKeyDown, but how do I stop ',' been inserted into the input element?

const [inputValue, setInputValue] = useState("");

  const handleKeyDown = (e: any) => {
    if (['188'].includes(e.keyCode)) {
      console.log("do something");
    }
  };

  const handleChange = (e: any) => {
    setInputValue(e.target.value)
  }

  return (
      <input
        type="text"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
  );


问:
Jupyterlab can't map shortcuts: [additional property error]
I am using Jupyterlab, 1.2.4. I tried the configuration below, but it gives an error. Any idea why?

Jupyter lab shortcuts

{
  "notebook:collapse-selected-outputs": {
    "command": "notebook:hide-cell-outputs",
    "keys": [
      "O"
    ],
    "selector": ".jp-Notebook:focus"
  },

  "notebook:expand-selected-outputs": {
    "command": "notebook:show-cell-outputs",
    "keys": [
      "O",
      "O"
    ],
    "selector": ".jp-Notebook:focus"
  },

  "notebook:clear-all-outputs": {
    "command": "notebook:hide-all-cell-outputs",
    "keys": [
      "Ctrl L"
    ],
    "selector": ".jp-Notebook:focus"
  },

  "notebook:collapse-all-code": {
    "command": "notebook:hide-all-cell-code",
    "keys": [
      "Shift O"
    ],
    "selector": ".jp-Notebook:focus"
  }
}
```

答:
I just copied the same JSON format that's used in the System Defaults section and everything works. Copy this to the User Preferences section.

{
  "shortcuts": [
    {
      "command": "notebook:hide-cell-outputs",
      "keys": ["O"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:show-cell-outputs",
      "keys": ["O", "O"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:hide-all-cell-outputs",
      "keys": ["Ctrl L"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:hide-all-cell-code",
      "keys": ["Shift O"],
      "selector": ".jp-Notebook:focus"
    }
  ]
}
```

Tested on JupyterLab 1.2.6.

Body:
I just copied the same JSON format that's used in the System Defaults section and everything works. Copy this to the User Preferences section.

{
  "shortcuts": [
    {
      "command": "notebook:hide-cell-outputs",
      "keys": ["O"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:show-cell-outputs",
      "keys": ["O", "O"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:hide-all-cell-outputs",
      "keys": ["Ctrl L"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:hide-all-cell-code",
      "keys": ["Shift O"],
      "selector": ".jp-Notebook:focus"
    }
  ]
}

Tested on JupyterLab 1.2.6.


问:
Generic collection support in WCF
Does WCF support generic collections?
I looked at the proxy object, and it seems to generate object array from a generic list collection.

Thanks

答:
When you add/edit the service client, if you click on the "Advanced ..." button you will see an option allowing you to choose the collection type your service client will create. The default is System.Array, but you can change it to System.Collections.Generic.List (along with many other choices).

http://msdn.microsoft.com/en-us/library/bb514724.aspx

OwnerDisplayName: Jeremy Thomson

ContentLicense: CC BY-SA 2.5

Title: Generic collection support in WCF

LastEditorDisplayName: Daniel Auger

OwnerDisplayName: eking


问:
Can a function parameter have more than one default value?
```<code>import tkinter
root = tkinter.Tk()
for i in range(5):
    def func(text=i):
        print(text)
    tkinter.Button(root, command=func).pack()
root.mainloop()
</code>```

The code defines a new function every time the loop runs. But after the loop ends, shouldn't func only refer to the last function defined with text having the default value of 4. All the command options for all the buttons point to the same functions but still the defaults are different. Why?

答:
Can a function parameter have more than one default value?

Yes, it can have as many as you want.

But after the loop ends, shouldn't func only refer to the last function defined with text having the default value of 4.

No, because you create a new function in each iteration of the loop. Each time def func is called inside the loop, a new function is called.

Body:
import tkinter
root = tkinter.Tk()
for i in range(5):
    def func(text=i):
        print(text)
    tkinter.Button(root, command=func).pack()
root.mainloop()

The code defines a new function every time the loop runs. But after the loop ends, shouldn't func only refer to the last function defined with text having the default value of 4. All the command options for all the buttons point to the same functions but still the defaults are different. Why?


问:
Convert varbinary value to string to get the same value
I need to convert the VarBinary value to a String value and I want to get the same value as VarBinary. Please see the below:

```<code>DECLARE @RFID INT
SET @RFID = 1292202724
SELECT CONVERT(VARBINARY(8), @RFID) AS 'VARBINARY_VALUE'
SELECT CAST((CONVERT(VARBINARY(8), @RFID)) AS NVARCHAR) AS 'STRING_VALUE' --Using Cast
SELECT CONVERT(NVARCHAR(15),(CONVERT(VARBINARY(8), @RFID))) AS 'STRING_VALUE' --Using Convert
</code>```

Below is the result:

What I want is the string value should get the same value "0x4D0572E4" as VarBinary value. But as you can see, I cannot convert to string.

If you have the solution, please let me know.

答:
When you look at the official docs for convert you find that for binary data there is a style option of 0, 1, 2. Style option 1 gives the value in hex format.

```<code>DECLARE @RFID INT = 1292202724;

SELECT CONVERT(VARBINARY(8), @RFID) AS 'VARBINARY_VALUE';

SELECT CONVERT(NVARCHAR(15), CONVERT(VARBINARY(8), @RFID), 1 /* style 1 */) AS 'STRING_VALUE'; --Using Convert
</code>```

Body:
I need to convert the VarBinary value to a String value and I want to get the same value as VarBinary. Please see the below:

DECLARE @RFID INT
SET @RFID = 1292202724
SELECT CONVERT(VARBINARY(8), @RFID) AS 'VARBINARY_VALUE'
SELECT CAST((CONVERT(VARBINARY(8), @RFID)) AS NVARCHAR) AS 'STRING_VALUE' --Using Cast
SELECT CONVERT(NVARCHAR(15),(CONVERT(VARBINARY(8), @RFID))) AS 'STRING_VALUE' --Using Convert

Below is the result:

What I want is the string value should get the same value "0x4D0572E4" as VarBinary value. But as you can see, I cannot convert to string.

If you have the solution, please let me know.

Body:
When you look at the official docs for convert you find that for binary data there is a style option of 0, 1, 2. Style option 1 gives the value in hex format.

DECLARE @RFID INT = 1292202724;

SELECT CONVERT(VARBINARY(8), @RFID) AS 'VARBINARY_VALUE';

SELECT CONVERT(NVARCHAR(15), CONVERT(VARBINARY(8), @RFID), 1 /* style 1 */) AS 'STRING_VALUE'; --Using Convert


问:
UnicodeDecodeError is showing on the window ........... how to solve it?

i am simply reading from one file but why this is showing error? how to get rid of it?

答:
Hi docx is a special extension that has been built by Microsoft normal python with open only supports RAW data files such as .csv .txt etc. Use docx library to read a docx file example as below.

```<code>import docx

# open connection to Word Document
doc = docx.Document("zen_of_python.docx")

# read in each paragraph in file
result = [p.text for p in doc.paragraphs]
</code>```

Body:
Hi docx is a special extension that has been built by Microsoft normal python with open only supports RAW data files such as .csv .txt etc. Use docx library to read a docx file example as below.

import docx

# open connection to Word Document
doc = docx.Document("zen_of_python.docx")

# read in each paragraph in file
result = [p.text for p in doc.paragraphs]


问:
Why this handler (runnable) is slowing down my app if it is launched on a service?
i am using a background service that it is retrieving data and inserting data on a remote server. OK, i puted it on a background service because i wanted to get that done in background without slowing down my app, but it is slowing down my app !

as you will see in the code, it haves a sleep of 60 seconds, and my app is getting frozen 2/3 seconds each 60 seconds, it is this code, i am sure, but i dont know how to solve it

```<code>public class MyService extends Service implements Runnable{
    boolean serviceStopped;
    RemoteConnection con; //conexion remota
    List <Position> positions;
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
    private Handler mHandler;
    private Runnable updateRunnable = new Runnable() {
        @Override public void run() {
            //contenido
            if (serviceStopped==false)
            {
                positions=con.RetrievePositions(settings.getString("login","")); //traigo todas las posiciones
                if (positions.size()>=10) //si hay 10 borro la mas vieja
                    con.deletePosition(positions.get(0).getIdposition());
                if (settings.getString("mylatitude", null)!=null && settings.getString("mylongitude", null)!=null)
                    con.insertPosition(settings.getString("mylatitude", null),settings.getString("mylongitude", null), formatDate(new Date()), settings.getString("login",""));
            }
            queueRunnable();//duerme
        }
    };
    private void queueRunnable() {
        //mHandler.postDelayed(updateRunnable, 60000); //envia una posicion al servidor cada minuto (60.000 milisegundos es un minuto)
        mHandler.postDelayed(updateRunnable, 60000);
    }

    public void onCreate() {
        serviceStopped=false;
settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
        configEditor = settings.edit();
        positions=new ArrayList<Position>();
        con = new RemoteConnection();
            mHandler = new Handler();
            queueRunnable();
        }
</code>```

答:
Even if you created a service it doesn't mean it will run on a separate thread. Take a look http://developer.android.com/reference/android/app/Service.html

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

Please take some time to read how services actually work in Android http://developer.android.com/guide/topics/fundamentals/services.html

So, IntentService and scheduled alert can be a solution here.

Body:
i am using a background service that it is retrieving data and inserting data on a remote server. OK, i puted it on a background service because i wanted to get that done in background without slowing down my app, but it is slowing down my app !

as you will see in the code, it haves a sleep of 60 seconds, and my app is getting frozen 2/3 seconds each 60 seconds, it is this code, i am sure, but i dont know how to solve it

public class MyService extends Service implements Runnable{
    boolean serviceStopped;
    RemoteConnection con; //conexion remota
    List <Position> positions;
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
    private Handler mHandler;
    private Runnable updateRunnable = new Runnable() {
        @Override public void run() {
            //contenido
            if (serviceStopped==false)
            {
                positions=con.RetrievePositions(settings.getString("login","")); //traigo todas las posiciones
                if (positions.size()>=10) //si hay 10 borro la mas vieja
                    con.deletePosition(positions.get(0).getIdposition());
                if (settings.getString("mylatitude", null)!=null && settings.getString("mylongitude", null)!=null)
                    con.insertPosition(settings.getString("mylatitude", null),settings.getString("mylongitude", null), formatDate(new Date()), settings.getString("login",""));
            }
            queueRunnable();//duerme
        }
    };
    private void queueRunnable() {
        //mHandler.postDelayed(updateRunnable, 60000); //envia una posicion al servidor cada minuto (60.000 milisegundos es un minuto)
        mHandler.postDelayed(updateRunnable, 60000);
    }

    public void onCreate() {
        serviceStopped=false;
settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
        configEditor = settings.edit();
        positions=new ArrayList<Position>();
        con = new RemoteConnection();
            mHandler = new Handler();
            queueRunnable();
        }


问:
How do I integrate exe publishing with the VS2019 build of the console .net core 2.2 application?
I saw a couple of similar questions but so far I found no single answer to the problem of integrating the publishing step with my build process. Unfortunately the dotnet publish command rebuilds the project again meaning that if I put the "dotnet publish" command in the project's Post-Build steps I get an infinite loop of building retries.

What I want to achieve is to get an exe built for my .NET Core 2.2 Console App for a few selected environments eg. osx and windows-10, possibly linux too, each in its own folder. Obvious condition is that it has to be integrated with the build, so no extra manuals steps (commands) are required. This has to work from within VS2019 Pro as well in CI (like AzureDevOps).

Is this basic step achievable or .Net core was a major step-back in the progress of software development?
I hope I just miss something and I am just grossly exaggerating. :)

Thanks, Radek

答:
How do I integrate exe publishing with the VS2019 build of the console
  .net core 2.2 application?

Actually, I think you do not need to worry about this.

dotnet publish already contains the build process. Publish process will first execute Build and then run publish. In a word, Build is  a part of Publish process.

So when you input dotnet publish under Build, you will get an infinite loop of building retries.

Solution

----- Just delete post-build event in xxx.csproj file and just dotnet publish directly and it will run the build process first.

You can test in the local VS and when you right-click on your project-->Publish, it will show the step in the output windwow.

In addition, as far as I know, Azure DevOps has a task called dotnet publish which contains Build.

And if you want to do some msbuild custom target only for publish step, you can add a condition like Condition="'$(DeployOnBuild)'=='true'", it will execute for Publish process rather than the normal build step(right-click on your project-->Build).

```<code><Target Name="testone" Condition="'$(DeployOnBuild)'=='true'" AfterTargets="Build">

    xxxxxxxxxxxxxx

</Target>
</code>```

---------------Update 1----------------

First question

Actually, the build of the publish is the pure process and then publish will copy the content of the build output into publish folder. So the execute program is just from the build output folder.

See the publish log:

So you should not specify a publish target under the build process. This is superfluous.

Second question

To generate this program for Window-10, linux or osx, you can try these command line to publish your project:(Release is the standard release build configuration)

For Win-10:

dotnet publish -r win10-x64 -c Release --self-contained

Linux:

dotnet publish -r linux-x64 -c Release --self-contained

For osx:

dotnet publish -r osx.10.12-x64 -c Release --self-contained

In this way, the project is first built according to the specified runtime and then published.

More info about .NET Core RID Catalog, you can refer to this document.

Update 2

I think you should change the configuration in this package UI:

Then click Save.

Also, when you publish this web project, please try to delete bin and obj folder and then publish it.

Debug: bin\Debug\netcoreapp2.1\publish

Release: bin\Release\netcoreapp2.1\publish

Or you should use dotnet command as I described to publish the project. The path is under Debug or Release folder.

Body:
How do I integrate exe publishing with the VS2019 build of the console
  .net core 2.2 application?

Actually, I think you do not need to worry about this.

dotnet publish already contains the build process. Publish process will first execute Build and then run publish. In a word, Build is  a part of Publish process.

So when you input dotnet publish under Build, you will get an infinite loop of building retries.

Solution

----- Just delete post-build event in xxx.csproj file and just dotnet publish directly and it will run the build process first.

You can test in the local VS and when you right-click on your project-->Publish, it will show the step in the output windwow.

In addition, as far as I know, Azure DevOps has a task called dotnet publish which contains Build.

And if you want to do some msbuild custom target only for publish step, you can add a condition like Condition="'$(DeployOnBuild)'=='true'", it will execute for Publish process rather than the normal build step(right-click on your project-->Build).

<Target Name="testone" Condition="'$(DeployOnBuild)'=='true'" AfterTargets="Build">

    xxxxxxxxxxxxxx

</Target>

---------------Update 1----------------

First question

Actually, the build of the publish is the pure process and then publish will copy the content of the build output into publish folder. So the execute program is just from the build output folder.

See the publish log:

So you should not specify a publish target under the build process. This is superfluous.

Second question

To generate this program for Window-10, linux or osx, you can try these command line to publish your project:(Release is the standard release build configuration)

For Win-10:

dotnet publish -r win10-x64 -c Release --self-contained

Linux:

dotnet publish -r linux-x64 -c Release --self-contained

For osx:

dotnet publish -r osx.10.12-x64 -c Release --self-contained

In this way, the project is first built according to the specified runtime and then published.

More info about .NET Core RID Catalog, you can refer to this document.

Update 2

I think you should change the configuration in this package UI:

Then click Save.

Also, when you publish this web project, please try to delete bin and obj folder and then publish it.

Debug: bin\Debug\netcoreapp2.1\publish

Release: bin\Release\netcoreapp2.1\publish

Or you should use dotnet command as I described to publish the project. The path is under Debug or Release folder.


问:
CrossCurrentActivity is null in dependency even though it is initialized and not null in app
In my Xamarin.Forms project, I am using Plugin.FirebaseAuth to log in by phone number.

It works fine for the iOS project, but for Android, the VerifyPhoneNumberAsync() call

```<code>await CrossFirebaseAuth.Current.PhoneAuthProvider.VerifyPhoneNumberAsync(CrossFirebaseAuth.Current.Instance, user.PhoneNumber);
</code>```

is throwing "current activity is null" from the CrossCurrentActivity.Current.Activity ?? check in https://github.com/f-miyu/Plugin.FirebaseAuth/blob/master/Plugin.FirebaseAuth.Android/PhoneAuthProviderWrapper.cs

Plugin.CurrentActivity is initialized (formerly in MainActivity.cs but now in MainApplication.cs as recommended) with no errors as per instructions in https://github.com/jamesmontemagno/CurrentActivityPlugin:

MainActivity.cs OnCreate():

```<code>Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, bundle);
</code>```

MainApplication.cs OnCreate():

```<code>Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this);
</code>```

I get the same null error when I call VerifyPhoneNumberAsync() regardless of where I initialize CurrentActivity.

Adding the

```<code>var activity = CrossCurrentActivity.Current.Activity ?? throw new NullReferenceException("current activity is null");
</code>```

line in my MainActivity.cs directly throws no error.

Is there anything else I could be overlooking?

Dependency Versions

Plugin.FirebaseAuth 1.1.2

Xamarin.Forms 4.4.0.991265

答:
Unfortunately, neither of the previously suggested solutions worked in my scenario.  However, the issue resolved itself after upgrading multiple dependencies, including:

Plugin.FirebaseAuth 3.1.0

Xamarin.Forms 4.6.0.800

Body:
In my Xamarin.Forms project, I am using Plugin.FirebaseAuth to log in by phone number.

It works fine for the iOS project, but for Android, the VerifyPhoneNumberAsync() call

await CrossFirebaseAuth.Current.PhoneAuthProvider.VerifyPhoneNumberAsync(CrossFirebaseAuth.Current.Instance, user.PhoneNumber);

is throwing "current activity is null" from the CrossCurrentActivity.Current.Activity ?? check in https://github.com/f-miyu/Plugin.FirebaseAuth/blob/master/Plugin.FirebaseAuth.Android/PhoneAuthProviderWrapper.cs

Plugin.CurrentActivity is initialized (formerly in MainActivity.cs but now in MainApplication.cs as recommended) with no errors as per instructions in https://github.com/jamesmontemagno/CurrentActivityPlugin:

MainActivity.cs OnCreate():

Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, bundle);

MainApplication.cs OnCreate():

Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this);

I get the same null error when I call VerifyPhoneNumberAsync() regardless of where I initialize CurrentActivity.

Adding the

var activity = CrossCurrentActivity.Current.Activity ?? throw new NullReferenceException("current activity is null");

line in my MainActivity.cs directly throws no error.

Is there anything else I could be overlooking?

Dependency Versions

Plugin.FirebaseAuth 1.1.2

Xamarin.Forms 4.4.0.991265


问:
How can I use getSystemService in a non-activity class (LocationManager)?
I'm having trouble offloading tasks from the main Activities OnCreate method onto another class to do the heavy lifting.

When I try to call getSystemService from the non-Activity class an exception is thrown.

lmt.java:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fyl lfyl = new fyl();
        Location location = lfyl.getLocation();
        String latLongString = lfyl.updateWithNewLocation(location);

        TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
        myLocationText.setText("Your current position is:\n" + latLongString);
    }
}
```
<p>fyl.java</p>
<pre class="lang-java prettyprint-override"><code>    package com.atClass.lmt;

    import android.app.Activity;
    import android.os.Bundle;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.content.Context;

    public class fyl {
        public Location getLocation(){
            LocationManager locationManager;
            String context = Context.LOCATION_SERVICE;
            locationManager = (LocationManager)getSystemService(context);

            String provider = LocationManager.GPS_PROVIDER;
            Location location = locationManager.getLastKnownLocation(provider);

            return location;
        }

        public String updateWithNewLocation(Location location) {
            String latLongString;

            if (location != null){
                double lat = location.getLatitude();
                double lng = location.getLongitude();
                latLongString = "Lat:" + lat + "\nLong:" + lng;
            }else{
                latLongString = "No Location";
            }

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

答:
For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

```<code>Worker(Context context, WorkerParameters workerParams)
</code>```

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

```<code>mContext.getSystenService(Context.ACTIVITY_SERVICE)
</code>```

Body:
I'm having trouble offloading tasks from the main Activities OnCreate method onto another class to do the heavy lifting.

When I try to call getSystemService from the non-Activity class an exception is thrown.

lmt.java:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fyl lfyl = new fyl();
        Location location = lfyl.getLocation();
        String latLongString = lfyl.updateWithNewLocation(location);

        TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
        myLocationText.setText("Your current position is:\n" + latLongString);
    }
}

fyl.java

    package com.atClass.lmt;

    import android.app.Activity;
    import android.os.Bundle;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.content.Context;

    public class fyl {
        public Location getLocation(){
            LocationManager locationManager;
            String context = Context.LOCATION_SERVICE;
            locationManager = (LocationManager)getSystemService(context);

            String provider = LocationManager.GPS_PROVIDER;
            Location location = locationManager.getLastKnownLocation(provider);

            return location;
        }

        public String updateWithNewLocation(Location location) {
            String latLongString;

            if (location != null){
                double lat = location.getLatitude();
                double lng = location.getLongitude();
                latLongString = "Lat:" + lat + "\nLong:" + lng;
            }else{
                latLongString = "No Location";
            }

            return latLongString;
        }
    }

Body:
For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

Worker(Context context, WorkerParameters workerParams)

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

mContext.getSystenService(Context.ACTIVITY_SERVICE)


问:
onKeyDown get value from e.target.value?
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

```<code>const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />
    </div>   ); };
</code>```

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js

答:
When you update the value of input, you should use onChange().

But, If you want to catch some character and treat about that, you should use onKeyDown().

So, in your case, you should use both.

this is an example code about backspace.

```<code>const Input = (props) =>{
  const [value, setValue] = React.useState('');

  function handleChange(e){
    setValue(e.target.value);
  }
  function handleBackSpace(e){
    if(e.keyCode === 8){
      //Do something.
    }
  }
  return (
    <div>
      <input onChange={handleChange} onKeyDown={handleBackSpace} value={value} type="text" />
    </div>
  )
}

```

```

Body:
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (

      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />

   ); };

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js

Body:
When you update the value of input, you should use onChange().

But, If you want to catch some character and treat about that, you should use onKeyDown().

So, in your case, you should use both.

this is an example code about backspace.

const Input = (props) =>{
  const [value, setValue] = React.useState('');

  function handleChange(e){
    setValue(e.target.value);
  }
  function handleBackSpace(e){
    if(e.keyCode === 8){
      //Do something.
    }
  }
  return (
    <div>
      <input onChange={handleChange} onKeyDown={handleBackSpace} value={value} type="text" />
    </div>
  )
}

```


问:
Asynchronous vs synchronoous socket
I have a situation that there will be 500 concurrent connection to server. In term of response time which method is faster? (asynchronous or synchronous) And what are the reasons behind?

I know asynchronous socket is like a list of connection, then it will ask each of the connection, do you have anything to send or receive. If the list is very long, then response time may take longer as well. Is this correct?

答:
Asynchronous sockets will work better. They use IOCP internally which is a very effective way to handle pending IO operations.

If you have a few sockets, use threads since it's easier. Stick with asynchronous sockets otherwise.

Title: Asynchronous vs synchronoous socket


问:
How to use single groupId with multiple artifactId in maven?
First dependency is to validate xml file.

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <version>2.4.0</version>
</dependency>
</code>```

Second dependency is to write POI object to file.

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>
</code>```

Now, I need a solution like this below :

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>
</code>```

Is it possible to achieve this ?

答:
It's not at all possible to keep multiple artifactId tags in a single dependency tag.

XML schema definition for Maven will not validate it. It will produce an error like this :

```<code>Project build error: Non-parseable POM project/pom.xml: Duplicated tag: 'artifactId' (position: START_TAG seen ...</artifactId>\n
</code>```

For example :

This is right.

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>
</code>```

This is wrong.

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>
</code>```

You can simply use like this as artifactId are different (without any issue) :

```<code>    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xerces</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.12.0</version>
    </dependency>
</code>```

You can refer to this : Multiple versions of the same dependency in Maven

Note : JDK 8 already gives you SAX parser to validate XML. Please use that. You don't need third party jar to validate XML.

Read here about Java SAX Parser.

Body:
First dependency is to validate xml file.

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <version>2.4.0</version>
</dependency>

Second dependency is to write POI object to file.

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>

Now, I need a solution like this below :

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>

Is it possible to achieve this ?

Body:
It's not at all possible to keep multiple artifactId tags in a single dependency tag.

XML schema definition for Maven will not validate it. It will produce an error like this :

Project build error: Non-parseable POM project/pom.xml: Duplicated tag: 'artifactId' (position: START_TAG seen ...</artifactId>\n

For example :

This is right.

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>

This is wrong.

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>

You can simply use like this as artifactId are different (without any issue) :

    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xerces</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.12.0</version>
    </dependency>

You can refer to this : Multiple versions of the same dependency in Maven

Note : JDK 8 already gives you SAX parser to validate XML. Please use that. You don't need third party jar to validate XML.

Read here about Java SAX Parser.


问:
Adding List Data to Another List Based on Their Value
I have a List:

```<code>    List<MenuItem> makanan = [
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/mie goreng.jpeg'),
    namaMenu: 'Mie Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Mie Kuah',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Campur',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Bakso Komplit',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
];
</code>```

also have Model that I want to make list from my previous list like this:

```<code>class TableOrder {
  String namaMakanan;
  int qtyMakanan;
  String noteMakanan;

  TableOrder({this.namaMakanan, this.qtyMakanan, this.noteMakanan});
}
</code>```

How can I get data from previous list into new list based on their qty value, if the qty is more than 0 that data will be added into new list.

答:
You can use List.where and List.map like this:

final List<TableOrder> newList = makanan
  .where((item) => item.qty > 0)
  .map((item) => TableOrder(namaMakanan: item.namaMenu, ...))
  .toList();
```

Body:
I have a List:

    List<MenuItem> makanan = [
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/mie goreng.jpeg'),
    namaMenu: 'Mie Goreng',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Mie Kuah',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Nasi Campur',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
  MenuItem(
    gambarMenu: Image.asset('images/nasigoreng.jpeg'),
    namaMenu: 'Bakso Komplit',
    priceMenu: 'Rp. 15.000',
    qty: 0,
    note: 'Catatan',
  ),
];

also have Model that I want to make list from my previous list like this:

class TableOrder {
  String namaMakanan;
  int qtyMakanan;
  String noteMakanan;

  TableOrder({this.namaMakanan, this.qtyMakanan, this.noteMakanan});
}

How can I get data from previous list into new list based on their qty value, if the qty is more than 0 that data will be added into new list.


问:
Wordpress: Selecting only one post type for WP_list_categories
Similar to this.

I've created two custom post types, and now they are happily sharing two taxonomies, but unfortunately wp_list_categories doesn't allow me to list a taxonomy by only one post type.
The code of wp_list_categories relies on get_categories, resulting in an array of categories.
So I produced a wp_query thus:

```<code>$query = new WP_Query( 'taxonomy=123&term=9&post_type=type' )
</code>```

so I could do something like:

```<code>if (!$query) {
unset $categories[categories]
}
</code>```

but I keep getting a $query even if there are no such posts.

答:
I did this by cloning the wp_list_categories function, giving it a different name and putting in this code after the line: $categories=get_categories($r):

foreach ($categories as $key => $category){
        $temp = array ( 'post_type'=>$r['type'], 'tax_query' => array(
            array (
                'taxonomy' => $category->taxonomy,
                'field' => 'slug',
                'terms' => $category->slug
            )

```<code>    )
        );
    $pauli = new wp_query($temp);
    if($pauli->post_count==0){
        unset($categories[$key]);
    }
}
</code>```

As you can see, it removes categories that do not have any of the post type you need, and then continues the process as wp_list_categories does normally. You may have to add a filter to ensure the category page/taxonomy page called only displays the post type you want, but this depends on what type of permalink you have.

Body:
Similar to this.

I've created two custom post types, and now they are happily sharing two taxonomies, but unfortunately wp_list_categories doesn't allow me to list a taxonomy by only one post type.
The code of wp_list_categories relies on get_categories, resulting in an array of categories.
So I produced a wp_query thus:

$query = new WP_Query( 'taxonomy=123&term=9&post_type=type' )

so I could do something like:

if (!$query) {
unset $categories[categories]
}

but I keep getting a $query even if there are no such posts.

Body:
I did this by cloning the wp_list_categories function, giving it a different name and putting in this code after the line: $categories=get_categories($r):

foreach ($categories as $key => $category){
        $temp = array ( 'post_type'=>$r['type'], 'tax_query' => array(
            array (
                'taxonomy' => $category->taxonomy,
                'field' => 'slug',
                'terms' => $category->slug
            )

    )
        );
    $pauli = new wp_query($temp);
    if($pauli->post_count==0){
        unset($categories[$key]);
    }
}

As you can see, it removes categories that do not have any of the post type you need, and then continues the process as wp_list_categories does normally. You may have to add a filter to ensure the category page/taxonomy page called only displays the post type you want, but this depends on what type of permalink you have.