问:
Kubectl Java client returns exit code 3 when using exec
I am writing a little backup programm for an application. This will run as a CronJob within my k8s cluster. At one point, it should trigger an mysql dump on the database inside another pod.

My code:

```<code>Exec exec = new Exec();
Process process = exec.exec(
    "default",
    "database-pod",
    new String[]{"sh", "-c", ""mysqldump -u {{user}} --p={{password}} schema > dbdump.sql",
    false,
    tty
);
process.waitFor();
process.destroy();
int exitValue = process.exitValue();
</code>```

process.exitValue() always contains 3 + the mysql dump file is created, but does not contain any sql statements.
Does somebody have a clue what I am doing wrong?

The base image of my backup programm is gcr.io/distroless/java:11 if that helps and was built using Jib

答:
When kubectl exec (or oc exec command) returns non-zero exit code, you should manually connect to the pod, and execute the same command directly, to inspect what's wrong:

```<code>[my-host]$ kubectl exec ${pod-id} -n ${namespace} bash -ti
[root@my-pod]# command...
# print command exit code (should be the same as before)
[root@my-pod]# echo $?
</code>```

Body:
I am writing a little backup programm for an application. This will run as a CronJob within my k8s cluster. At one point, it should trigger an mysql dump on the database inside another pod.

My code:

Exec exec = new Exec();
Process process = exec.exec(
    "default",
    "database-pod",
    new String[]{"sh", "-c", ""mysqldump -u {{user}} --p={{password}} schema > dbdump.sql",
    false,
    tty
);
process.waitFor();
process.destroy();
int exitValue = process.exitValue();

process.exitValue() always contains 3 + the mysql dump file is created, but does not contain any sql statements.
Does somebody have a clue what I am doing wrong?

The base image of my backup programm is gcr.io/distroless/java:11 if that helps and was built using Jib

Body:
When kubectl exec (or oc exec command) returns non-zero exit code, you should manually connect to the pod, and execute the same command directly, to inspect what's wrong:

[my-host]$ kubectl exec ${pod-id} -n ${namespace} bash -ti
[root@my-pod]# command...
# print command exit code (should be the same as before)
[root@my-pod]# echo $?


来源: stackexchange

问:
Bootstrap 4 navigation active link state
I use bootstrapv4 navigation, but when I click on an item, the active state doesn't switch.
I tried some js but none of them are working.
I'm using kirby cms, but i don't this is causing any problems..
Could using <?php snippet('header')?> cause the trouble?
Or am I setting it up wrong?

This ist my header.php

                url() ?>"><?php if($image = $site->image('logo.png')): ?>
                        <img class="logo-image mr-5" src="<?= $image->url() ?>" alt="logo"><?php endif ?>

            <button class="navbar-toggler pt-0" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation" onclick="toggleFunction(this)">

            </button>

                    <?php $menuCounter=0;
                    foreach ($site->children()->listed() as $subpage):
                        $menuCounter++;
                        $class = ($menuCounter == 1) ? "active" : "inactive";
                        $span = ($menuCounter == 1) ? "(current)" : "";
                        ?>
                        <li class="<?php echo $class ?> nav-item">
                            url() ?>"><?= $subpage->title() ?><?= $span ?>

                    <?php endforeach ?>

    ```
</div>
</div>
</p>

<p>This is my js-file</p>

```$(".nav-item").on("click", function(){
        $(".nav-item").find(".active").removeClass("active");
        $(this).addClass("active");
    });
```

答:
You dont need Javacript for that in Kirby. You can use a helper like this within you foreach loop:

```<code><li class="menu-item<?= r($subpage->isOpen(), ' active') ?>">
</code>```

More Infos about the helpers and the isOpen-object:
https://getkirby.com/docs/reference/templates/helpers
https://getkirby.com/docs/reference/objects/page/is-open

ContentLicense: CC BY-SA 4.0

Body:
I use bootstrapv4 navigation, but when I click on an item, the active state doesn't switch.
I tried some js but none of them are working.
I'm using kirby cms, but i don't this is causing any problems..
Could using <?php snippet('header')?> cause the trouble?
Or am I setting it up wrong?

This ist my header.php

                <a class="logo-link" href="<?= $site->url() ?>"><?php if($image = $site->image('logo.png')): ?>
                        <img class="logo-image mr-5" src="<?= $image->url() ?>" alt="logo"><?php endif ?>

            <button class="navbar-toggler pt-0" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation" onclick="toggleFunction(this)">

            </button>

                    <?php $menuCounter=0;
                    foreach ($site->children()->listed() as $subpage):
                        $menuCounter++;
                        $class = ($menuCounter == 1) ? "active" : "inactive";
                        $span = ($menuCounter == 1) ? "(current)" : "";
                        ?>
                        <li class="<?php echo $class ?> nav-item">
                            <a class="menu-point nav-link" href="<?= $subpage->url() ?>"><?= $subpage->title() ?><?= $span ?>

                    <?php endforeach ?>

This is my js-file

$(".nav-item").on("click", function(){
        $(".nav-item").find(".active").removeClass("active");
        $(this).addClass("active");
    });

Body:
You dont need Javacript for that in Kirby. You can use a helper like this within you foreach loop:

<li class="menu-item<?= r($subpage->isOpen(), ' active') ?>">

More Infos about the helpers and the isOpen-object:
https://getkirby.com/docs/reference/templates/helpers
https://getkirby.com/docs/reference/objects/page/is-open


问:
Does anyone really use .Net CAS in their apps?
I am thinking about taking the 70-536 exam, and there is all this stuff about CAS and caspol and stuff.

Has anyone out there actually taken the time to use CAS either Decoratively or Imperatively?

I can see where it would be useful to have a basic understanding of CAS Codegroups, permission sets and what not, but i can't fathom a real scenario where I would ever actually want to use it?

I understand what the SecurityAction Demand and LinkDemand do, i just can't imagine actually using them. The only scenario that comes to mind would if i had a strongly named assembly that would run from the internet with elevated privileges and for some reason i wanted to make sure that anybody calling my assemblies also had appropriate permissions... but when does that really happen?

I only do Winforms development, perhaps in web apps this a greater concern that people often need to address?

Perhaps I am not security minded enough, lol.

Again, i'm not looking for links to microsoft documentation :) i'm  looking for realworld examples where people use this stuff.

thanks

答:
Read this: http://blogs.msdn.com/b/shawnfa/archive/2010/02/24/so-is-cas-dead-in-net-4-or-what.aspx

.NET 4 provides completely new security model, so you would better invest your knowledge in it: http://weblogs.asp.net/hernandl/archive/2009/05/22/new-net-4-0-security-changes.aspx

ContentLicense: CC BY-SA 3.0


问:
Kubernates cluster instance
I have created a Kubernetes cluster and one of instance in the cluster is inactive
I want to review the configured Kubernetes Engine cluster of an inactive configuration by which command should I check?
Should I use this "kubectl config get-contexts"?
or
kubectl config use-context and kubectl config view?

Am beginner to cloud please anyone explains?

答:
You can run below command to check status of all the nodes of a kubernetes cluster. Pleases note if you are using GKE managed service you will not be able to see status of master nodes, you will only see status of worker nodes.

```<code>kubectl get nodes -o wide
kubectl describe node nodename
</code>```

You can also run below command to check status of control plane components.

```<code>kubectl get componentstatus
</code>```

Title: Kubernates cluster instance

Body:
You can run below command to check status of all the nodes of a kubernetes cluster. Pleases note if you are using GKE managed service you will not be able to see status of master nodes, you will only see status of worker nodes.

kubectl get nodes -o wide
kubectl describe node nodename

You can also run below command to check status of control plane components.

kubectl get componentstatus


问:
Docker cannot start on Windows
Executing docker version command on Windows returns the following results:

```<code>C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
</code>```

Running the diagnostics produces the following:

```<code>C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at <ScriptBlock>, <No file>: line 27
 [+] Service is running 127ms
 [+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
 [+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
 [-] Do not have DisableVSmbOplock set to 1 53ms
   Expected: {0}
   But was:  {1}
   66:              $regvalue.VSmbDisableOplocks | Should Be 0
   at <ScriptBlock>, <No file>: line 66
 [+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
 [-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
   ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   at <ScriptBlock>, <No file>: line 90
Describing Container network is created
 [-] Error occurred in Describe block 1.08s
   RuntimeException: Cannot index into a null array.
   at <ScriptBlock>, <No file>: line 119
Showing output from: docker info

Showing output from: docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64

Showing output from: docker network ls

Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
</code>```

答:
Solved for me by running a docker desktop app, check-in notification. Setup if necessary.

```<code>$ net start com.docker.service
</code>```

The Docker for Windows Service service is starting.
The Docker for Windows Service service was started successfully.

```<code>$ docker version

$ net start com.docker.service
</code>```

The requested service has already been started.

Title: Docker cannot start on Windows

Body:
Executing docker version command on Windows returns the following results:

C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Running the diagnostics produces the following:

C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at

Body:
Solved for me by running a docker desktop app, check-in notification. Setup if necessary.

$ net start com.docker.service

The Docker for Windows Service service is starting.
The Docker for Windows Service service was started successfully.

$ docker version

$ net start com.docker.service

The requested service has already been started.


问:
Bootstrap is messing with my table layout when i use repeater
I have a repeater with a couple nested repeaters. Everythink works fine, except for the layout when I try to use bootstrap. In the first picture

I try to make it work inside a div with class=row. Everything is crazy. Even when i try to have it alone second picture

same mistakes. When i remove all divs, the render is perfect. Here is my code for the first one

```<code> <div class="container-fluid">
    <div class="row">
        <div class="col-sm-2 col-md-2 col-lg-2" style="border-bottom:double;">
            <ul class="nav flex-column" style="margin-left: -15px;">
                (navigate menu)
            </ul>
            </div>
 <div  class="col-sm-10 col-md-10 col-lg-10"  style="border-bottom:double">
                <div class="row">
                    <div class="col-3">
    ... an invisibe panel...
</div>
             <div class="col-12">
    ... panel with search option for populating repeater ...
</div>
                    <div class="col-12">

                <asp:Panel ID="panel_endiaferomenwn_provoli" runat="server">
                <div class="table-responsive table-bordered">
                        <table  style="min-width:950px; width:100%">
                            <tr>
                                <td style="width: 8%; min-width:100px; text-wrap:none" id="last_change"><b>a</b></td>
                                <td style="width: 30%;"><b>b</b></td>
                                <td style="width: 15%;"><b>c</b></td>
                                <td style="width: 10%;"><b>d</b></td>
                                <td style="width: 14%;"><b>e / αγόρασε</b></td>
                                <td style="width: 10%; min-width:100px;"><b>f</b></td>
                                <td style="width: 8%; min-width:100px;"><b>g</b></td>
                                <td style="width: 5%; min-width:80px;"><b>h</b></td>
                            </tr>
                        </table>
                    </div>

                <asp:Repeater ID="rep_all" runat="server" DataSourceID="data_rep" OnPreRender="rep_all_PreRender">
                    <ItemTemplate>
                        <div class="table-responsive table-bordered">
                        <table style="min-width:950px; width:100%;">
                            <tbody>
                            <tr>
                                <td style="width:8%; min-width:100px;"><asp:Label ID="lbl_rep_last_change" runat="server" Text='<%# Convert.ToDateTime(Eval("date_of_last_change")).ToString("dd/MM/yyyy") %>'></asp:Label></td>
                                <td style="width:30%;">
                                 <asp:Repeater ID="rep_details" runat="server">
                                    <ItemTemplate>
                                        <div class="table-responsive">
                                            <table style="width:100%">
                                                <thead>
                                                </thead>
                                                <tbody>
                                                   <tr data-toggle="collapse" class="xeraki" style="width:30%;" data-target="#collapse<%# Eval("id") %>">
                                                        <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                            <asp:Label ID="lbl_det_name_title" Text="Επωνυμία" runat="server" Font-Bold="true"></asp:Label></td>
                                                        <td style="border: none; padding: 1px;">
                                                            <asp:Label ID="lbl_det_name" runat="server" Font-Underline="true" ForeColor="Blue" Text='<%# Eval("name") %>'></asp:Label></td>
                                                       <td style="border: none; padding: 1px;"></td>
                                                    </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <div class="collapse" id="collapse<%# Eval("id") %>">
                                            <div class="table-responsive">
                                        <table style="width:100%">
                                            <tbody>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_til1_title" Text="Τηλ1 " runat="server" Font-Bold="true"></asp:Label>
                                                    </td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_til1" runat="server" Text='<%# Eval("phone1") %>'></asp:Label></td>
                                                </tr>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_til2_title" Text="Τηλ2 " runat="server" Font-Bold="true"></asp:Label></td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_til2" runat="server" Text='<%# Eval("phone2") %>'></asp:Label></td>
                                                </tr>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_manager_title" Text="Υπεύθυνος " runat="server" Font-Bold="true"></asp:Label></td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_manager" runat="server" Text='<%# Eval("manager") %>'></asp:Label></td>
                                                </tr>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_perioxi_title" Text="Περιοχή " runat="server" Font-Bold="true"></asp:Label></td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_perioxi" runat="server" Text='<%# Eval("area") %>'></asp:Label></td>
                                                </tr>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_address_title" Text="Διεύθυνση " runat="server" Font-Bold="true"></asp:Label></td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_address" runat="server" Text='<%# Eval("address") %>'></asp:Label></td>
                                                </tr>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_afm_title" Text="ΑΦΜ " runat="server" Font-Bold="true"></asp:Label></td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_afm" runat="server" Text='<%# Eval("afm") %>'></asp:Label></td>
                                                </tr>
                                                <tr>
                                                    <td style="border: none; padding: 1px; width: 40%; text-wrap: none;">
                                                        <asp:Label ID="lbl_det_salesman_title" Text="Πωλητής " runat="server" Font-Bold="true"></asp:Label></td>
                                                    <td style="border: none; padding: 1px;">
                                                        <asp:Label ID="lbl_det_salesman" runat="server" Text='<%# Eval("salesman") %>'></asp:Label></td>
                                                </tr>

                                            </tbody>
                                            </table>
                                            </div>
                                            </div>

                                    </ItemTemplate>
                                    </asp:Repeater>

                                </td>
                                <td style="width:15%;"><asp:Label ID="lbl_rep_show" runat="server" Text='<%# Eval("show") %>'></asp:Label> <asp:Label ID="lbl_rep_id" runat="server" Text='<%# Eval("id") %>' Visible="false"></asp:Label> </td>
                                <td style="width:10%;"><asp:Label ID="lbl_rep_perioxi" runat="server" Text='<%# Eval("area") %>'></asp:Label></td>
                                <td style="width:14%;">
                                    <asp:Repeater ID="rep_rep_inter" runat="server">
                                    <ItemTemplate>
                                        <div class="table-responsive">
                                            <table>
                                                <thead>
                                                </thead>
                                                <tbody>
                                                <tr>
                                                    <td style="border:none;padding:1px;width:55%;"><asp:Label ID="lbl2_name" runat="server" Text='<%# Eval("name") %>'></asp:Label><asp:Label ID="lbl_rep2_id" runat="server" Text='<%# Eval("id") %>' Visible="false"></asp:Label></td>
                                                    <td style="border:none;padding:1px;width:45%;"><asp:CheckBox CssClass="d-flex text-right" ID="check_buy" runat="server" Text="" Enabled="false" /></td>
                                                </tr>
                                                    </tbody>
                                            </table>
                                        </div>
                                    </ItemTemplate>
                                    </asp:Repeater>
                                </td>
                                <td style="width:10%;min-width:100px;"><asp:Label ID="lbl_rep_katastasi" runat="server" Text='<%# Eval("katastasi") %>'></asp:Label> </td>
                                <td style="width:8%;min-width:100px;"><asp:Label ID="lbl_rep_prothesmia" runat="server" Text='<%# Convert.ToDateTime(Eval("date_of_next_step")).ToString("dd/MM/yyyy") %>'></asp:Label></td>
                                <td style="width: 5%; min-width:80px;">
                                    <div class="d-flex justify-content-center"">
                                    <asp:ImageButton ID="btn_expand" runat="server" OnClick="btn_expand_Click" ImageUrl="../webimages/expand-arrow.png" Width="48" />
                                    <asp:ImageButton ID="btn_collapse" runat="server" OnClick="btn_collapse_Click" ImageUrl="../webimages/collapse-arrow.png" Width="48" Visible="false"/>
                                        </div>
                                </td>
                            </tr>

                                <tr>

                                    <div class="table-responsive table-bordered">
                                        <table style="min-width: 950px; width: 100%;">
                                            <tbody>
                                                <tr>

                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>

                                        <div id="expand_epafes" runat="server" class="colapse">
                                            <header>
                                                <div class="table-responsive table-bordered">
                                                <table style="min-width: 950px; width: 100%;">

                                                 <tr>
                                                    <td style="width: 10%; min-width:175px;" id="date_epafes2"><b>Ημερομηνία Επαφής</b></td>
                                                    <td style="width: 45%; text-align:center;"><b>Παρατηρήσεις</b></td>
                                                     <td style="width:15%;"><b>Κατάσταση</b></td>
                                                     <td style="width:10%;"><b>Προθεσμία</b></td>
                                                     <td style="width: 15%;"><b>Προσφορά</b></td>
                                                    <td style="width: 5%; min-width:80px;"><b></b></td>
                                                </tr>

                                                  </table>
                                                    </div>
                                            </header>
                                    <asp:Repeater ID="rep_epafes" runat="server">
                                        <ItemTemplate>
                                            <div class="table-responsive table-bordered">

                                                <table style="min-width: 950px; width: 100%;">

                                                    <tbody>
                                                        <tr>
                                                           <td style="width: 10%; min-width:175px;" id="date_epafes">
                                                               <asp:Label ID="epafes_lbl_imerominia" runat="server" Text='<%# Convert.ToDateTime(Eval("date_made")).ToString("dd/MM/yyyy") %>'></asp:Label>
                                                               <asp:TextBox ID="epafes_edit_imerominia" runat="server" Visible="false" TextMode="Date" Text='<%# Convert.ToDateTime(Eval("date_made")).ToString("yyyy-MM-dd") %>'></asp:TextBox>
                                                           </td>
                                                            <td style="width: 45%;">
                                                               <asp:Label ID="epafes_lbl_remarks" runat="server" Text='<%# Eval("remarks") %>' ></asp:Label>
                                                                <asp:Label ID="lbl_epafes_id_endiaferontos" runat="server" Visible="false" Text='<%# Eval("id_endeiaferontos") %>'></asp:Label>
                                                                <asp:Label ID="lbl_epafes_id_epafis" runat="server" Visible="false" Text='<%# Eval("id") %>' ></asp:Label>
                                                                <asp:TextBox ID="epafes_edit_remarks" runat="server" CssClass="w-100" Visible="false" Text='<%# Eval("remarks") %>'></asp:TextBox>
                                                            </td>
                                                            <td style="width: 15%;">

                                                            </td>
                                                            <td style="width: 10%;">

                                                            </td>
                                                            <td style="width: 15%;">
                                                                <asp:Button ID="btn_test" runat="server" Text="test" OnClick="btn_test_Click"  />
                                                            </td>
                                                            <td style="width: 5%; min-width:80px;" class="d-flex justify-content-center">
                                                                <asp:ImageButton ImageUrl="../webimages/edit.png" ID="btn_edit_edit" runat="server" OnClick="btn_edit_edit_Click" />
                                                                <asp:ImageButton ImageUrl="../webimages/ok.png" ID="btn_edit_save" runat="server" Visible="false" OnClick="btn_edit_save_Click" />
                                                                <asp:ImageButton ImageUrl="../webimages/cancel.png" ID="btn_edit_cancel" runat="server" Visible="false" OnClick="btn_edit_cancel_Click" />
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <div class="table-responsive table-bordered">
                                                <table style="min-width: 950px; width: 100%;">
                                                    <tbody>
                                                        <tr>
                                                            <td style="width: 10%; min-width: 175px;">
                                                                <asp:TextBox ID="txt_epafes_date_add" runat="server" TextMode="Date" Text='<%# DateTime.Now.ToString("yyyy-MM-dd") %>'></asp:TextBox>
                                                            </td>
                                                            <td style="width: 50%;">
                                                                <asp:TextBox ID="txt_epafes_remarks_add" runat="server" Placeholder="Παρατηρήσεις" CssClass="w-100" ></asp:TextBox>
                                                            </td>
                                                            <td style="width:20%;">
                                                            </td>
                                                            <td style="width: 15%;">

                                                            </td>
                                                            <td style="width: 5%; min-width: 80px;" class="d-flex justify-content-center">
                                                                <asp:ImageButton ImageUrl="../webimages/save.png" ID="btn_epafi_add" runat="server" OnClick="btn_epafi_add_Click" />
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </FooterTemplate>
                                    </asp:Repeater>
                                       </div>
                                </tr>
                                </tbody>
                        </table>
                            </div>
                    </ItemTemplate>
                </asp:Repeater>

                <asp:SqlDataSource ID="data_rep" runat="server" (connectio details) ></asp:SqlDataSource>
                    </asp:Panel>

                </div>

                </div>
 </div>

        </div>

</div>
</code>```

I am sorry for the long code, tried to make it shorter. I also include a picture with code collapsed, to help you see it easier.

答: If you want to maintain the layout. Make use of style="display-flex". Put it in a columns parent division along with subdivisions. col-6 or whatever append it to that div(Parent you can give col-12). Your formatting will be maintained. Happy coding :)</p>

Body:
I have a repeater with a couple nested repeaters. Everythink works fine, except for the layout when I try to use bootstrap. In the first picture

I try to make it work inside a div with class=row. Everything is crazy. Even when i try to have it alone second picture

same mistakes. When i remove all divs, the render is perfect. Here is my code for the first one

                (navigate menu)

    ... an invisibe panel...

    ... panel with search option for populating repeater ...

                <asp:Panel ID="panel_endiaferomenwn_provoli" runat="server">

                                a
                                b
                                c
                                d
                                e / αγόρασε
                                f
                                g
                                h

                <asp:Repeater ID="rep_all" runat="server" DataSourceID="data_rep" OnPreRender="rep_all_PreRender">
                    <ItemTemplate>

                                <asp:Label ID="lbl_rep_last_change" runat="server" Text='<%# Convert.ToDateTime(Eval("date_of_last_change")).ToString("dd/MM/yyyy") %>'></asp:Label>

                                 <asp:Repeater ID="rep_details" runat="server">
                                    <ItemTemplate>

                                                   <tr data-toggle="collapse" class="xeraki" style="width:30%;" data-target="#collapse<%# Eval("id") %>">

                                                            <asp:Label ID="lbl_det_name_title" Text="Επωνυμία" runat="server" Font-Bold="true"></asp:Label>

                                                            <asp:Label ID="lbl_det_name" runat="server" Font-Underline="true" ForeColor="Blue" Text='<%# Eval("name") %>'></asp:Label>

                                        <div class="collapse" id="collapse<%# Eval("id") %>">

                                                        <asp:Label ID="lbl_det_til1_title" Text="Τηλ1 " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_til1" runat="server" Text='<%# Eval("phone1") %>'></asp:Label>

                                                        <asp:Label ID="lbl_det_til2_title" Text="Τηλ2 " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_til2" runat="server" Text='<%# Eval("phone2") %>'></asp:Label>

                                                        <asp:Label ID="lbl_det_manager_title" Text="Υπεύθυνος " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_manager" runat="server" Text='<%# Eval("manager") %>'></asp:Label>

                                                        <asp:Label ID="lbl_det_perioxi_title" Text="Περιοχή " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_perioxi" runat="server" Text='<%# Eval("area") %>'></asp:Label>

                                                        <asp:Label ID="lbl_det_address_title" Text="Διεύθυνση " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_address" runat="server" Text='<%# Eval("address") %>'></asp:Label>

                                                        <asp:Label ID="lbl_det_afm_title" Text="ΑΦΜ " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_afm" runat="server" Text='<%# Eval("afm") %>'></asp:Label>

                                                        <asp:Label ID="lbl_det_salesman_title" Text="Πωλητής " runat="server" Font-Bold="true"></asp:Label>

                                                        <asp:Label ID="lbl_det_salesman" runat="server" Text='<%# Eval("salesman") %>'></asp:Label>

                                    </ItemTemplate>
                                    </asp:Repeater>

                                <asp:Label ID="lbl_rep_show" runat="server" Text='<%# Eval("show") %>'></asp:Label> <asp:Label ID="lbl_rep_id" runat="server" Text='<%# Eval("id") %>' Visible="false"></asp:Label>
                                <asp:Label ID="lbl_rep_perioxi" runat="server" Text='<%# Eval("area") %>'></asp:Label>

                                    <asp:Repeater ID="rep_rep_inter" runat="server">
                                    <ItemTemplate>

                                                    <asp:Label ID="lbl2_name" runat="server" Text='<%# Eval("name") %>'></asp:Label><asp:Label ID="lbl_rep2_id" runat="server" Text='<%# Eval("id") %>' Visible="false"></asp:Label>
                                                    <asp:CheckBox CssClass="d-flex text-right" ID="check_buy" runat="server" Text="" Enabled="false" />

                                    </ItemTemplate>
                                    </asp:Repeater>

                                <asp:Label ID="lbl_rep_katastasi" runat="server" Text='<%# Eval("katastasi") %>'></asp:Label>
                                <asp:Label ID="lbl_rep_prothesmia" runat="server" Text='<%# Convert.ToDateTime(Eval("date_of_next_step")).ToString("dd/MM/yyyy") %>'></asp:Label>

                                    <asp:ImageButton ID="btn_expand" runat="server" OnClick="btn_expand_Click" ImageUrl="../webimages/expand-arrow.png" Width="48" />
                                    <asp:ImageButton ID="btn_collapse" runat="server" OnClick="btn_collapse_Click" ImageUrl="../webimages/collapse-arrow.png" Width="48" Visible="false"/>

                                                    Ημερομηνία Επαφής
                                                    Παρατηρήσεις
                                                     Κατάσταση
                                                     Προθεσμία
                                                     Προσφορά

                                    <asp:Repeater ID="rep_epafes" runat="server">
                                        <ItemTemplate>

                                                               <asp:Label ID="epafes_lbl_imerominia" runat="server" Text='<%# Convert.ToDateTime(Eval("date_made")).ToString("dd/MM/yyyy") %>'></asp:Label>
                                                               <asp:TextBox ID="epafes_edit_imerominia" runat="server" Visible="false" TextMode="Date" Text='<%# Convert.ToDateTime(Eval("date_made")).ToString("yyyy-MM-dd") %>'></asp:TextBox>

                                                               <asp:Label ID="epafes_lbl_remarks" runat="server" Text='<%# Eval("remarks") %>' ></asp:Label>
                                                                <asp:Label ID="lbl_epafes_id_endiaferontos" runat="server" Visible="false" Text='<%# Eval("id_endeiaferontos") %>'></asp:Label>
                                                                <asp:Label ID="lbl_epafes_id_epafis" runat="server" Visible="false" Text='<%# Eval("id") %>' ></asp:Label>
                                                                <asp:TextBox ID="epafes_edit_remarks" runat="server" CssClass="w-100" Visible="false" Text='<%# Eval("remarks") %>'></asp:TextBox>

                                                                <asp:Button ID="btn_test" runat="server" Text="test" OnClick="btn_test_Click"  />

                                                                <asp:ImageButton ImageUrl="../webimages/edit.png" ID="btn_edit_edit" runat="server" OnClick="btn_edit_edit_Click" />
                                                                <asp:ImageButton ImageUrl="../webimages/ok.png" ID="btn_edit_save" runat="server" Visible="false" OnClick="btn_edit_save_Click" />
                                                                <asp:ImageButton ImageUrl="../webimages/cancel.png" ID="btn_edit_cancel" runat="server" Visible="false" OnClick="btn_edit_cancel_Click" />

                                        </ItemTemplate>
                                        <FooterTemplate>

                                                                <asp:TextBox ID="txt_epafes_date_add" runat="server" TextMode="Date" Text='<%# DateTime.Now.ToString("yyyy-MM-dd") %>'></asp:TextBox>

                                                                <asp:TextBox ID="txt_epafes_remarks_add" runat="server" Placeholder="Παρατηρήσεις" CssClass="w-100" ></asp:TextBox>

                                                                <asp:ImageButton ImageUrl="../webimages/save.png" ID="btn_epafi_add" runat="server" OnClick="btn_epafi_add_Click" />

                                        </FooterTemplate>
                                    </asp:Repeater>

                    </ItemTemplate>
                </asp:Repeater>

                <asp:SqlDataSource ID="data_rep" runat="server" (connectio details) ></asp:SqlDataSource>
                    </asp:Panel>

I am sorry for the long code, tried to make it shorter. I also include a picture with code collapsed, to help you see it easier.


问:
Laravel firstOrNew by a specific table column
I have an array of objects coming from the frontend. I only want to create a new record of what's coming in if not already present in the database but only by the primaryKey ('The_ID').

When I use firstOrNew, it creates duplicate entry.

Model:

 protected $primaryKey = 'The_ID'; // Fake name.

 public $incrementing = true;

 public $timestamps = false;

 protected $fillable = [
   // all fields except the $primaryKey
 ];
```

<p>Controller:</p>

<pre class="lang-php prettyprint-override"><code> $array = $request->lists;

 foreach ($array as $list) {
   ( new Model )->firstOrNew([
     'sue' => 'young',
     'foo' => 'bar',

     'datetimeadded' => \Carbon::now() // previous dev used this name :(
   ])->save();
 }
</code>```

What I'd like is that, if The_ID is in the database, do not save. The_ID comes in the request so I can access it with $list['The_ID'] in the loop.

If this was already answered, please close. Thanks.

答:
firstOrNew accepts 2 arrays. 1 is your where clause basically and the second is what you want to insert. By using only 1 array you basically have a where clause in everything. Modify you code to:

```<code>foreach ($array as $list) {
   ( new Model )->firstOrNew(
   ['id' => $request->id],
   [
     'sue' => 'young',
     'foo' => 'bar',

     'datetimeadded' => \Carbon::now() // previous dev used this name :(
   ])->save();
 }
</code>```

The first array i used basically is something like:

```<code>where('id' ,'=',$request->id);
</code>```

id: the PK of your table,

$request->id : id of an element coming from the front-end matching
your PK.

You can also use updateOrCreate for that so you will update the current fields of an existing record or create a new record.

Body:
I have an array of objects coming from the frontend. I only want to create a new record of what's coming in if not already present in the database but only by the primaryKey ('The_ID').

When I use firstOrNew, it creates duplicate entry.

Model:

 protected $primaryKey = 'The_ID'; // Fake name.

 public $incrementing = true;

 public $timestamps = false;

 protected $fillable = [
   // all fields except the $primaryKey
 ];

Controller:

 $array = $request->lists;

 foreach ($array as $list) {
   ( new Model )->firstOrNew([
     'sue' => 'young',
     'foo' => 'bar',

     'datetimeadded' => \Carbon::now() // previous dev used this name :(
   ])->save();
 }

What I'd like is that, if The_ID is in the database, do not save. The_ID comes in the request so I can access it with $list['The_ID'] in the loop.

If this was already answered, please close. Thanks.

Body:
firstOrNew accepts 2 arrays. 1 is your where clause basically and the second is what you want to insert. By using only 1 array you basically have a where clause in everything. Modify you code to:

foreach ($array as $list) {
   ( new Model )->firstOrNew(
   ['id' => $request->id],
   [
     'sue' => 'young',
     'foo' => 'bar',

     'datetimeadded' => \Carbon::now() // previous dev used this name :(
   ])->save();
 }

The first array i used basically is something like:

where('id' ,'=',$request->id);

id: the PK of your table,

$request->id : id of an element coming from the front-end matching
your PK.

You can also use updateOrCreate for that so you will update the current fields of an existing record or create a new record.


问:
How to add and delete item from array in Angular
I am doing a project that need to display an array and user can add in new data or delete existing data from the array.

I am stuck with how to add and delete item from array.

I tried to use push function to add and pop function to delete but failed.

HTML

Student Details

 Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" value={{selectedStudent.name}}>

 Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"
                value={{selectedStudent.age}}>

College:<input type="text" [(ngModel)]="college" placeholder="Please enter College"
                value={{selectedStudent.college}}>

        <button class="btnA" onclick="addStudent()">Add</button>
        <button class="btnE" onclick="editStudent()">Edit</button>
        <button class="btnD" onclick="deleteStudent()">Delete</button>

        {{student.name}} {{student.age}} {{student.college}}

```
</div>
</div>
</p>

<p><strong>.ts</strong></p>

```export class WriteComponent implements OnInit {

    name: string;
    age: number;
    college: string;
    student = STUDENTS;
    selectedStudent: Student;

    constructor() {}
    ngOnInit(): void {}

    onSelect(student: Student): void {
        this.selectedStudent = student;
    }

}
```

<p><strong>mock-student.ts</strong> (where I store my array)</p>

```import { Student } from './student';

export const STUDENTS : Student[]=[
  {name:'Johnny',age:24,college:'Harvard'},
  {name:'Samantha',age:20,college:'INTI'},
  {name:'Aditya',age:21,college:'Sunway'},
  {name:'Troy',age:25,college:'TARUC'},
]
```

答:
Hope this helps.....

Result:

app.component.html

```<code><div class="container">
<h2>Add User</h2>
<form class="form-inline" autocomplete="off" (submit)="addStudent()">
    <div class="form-group">
      <label for="email">Name:</label>
      <input type="text" class="form-control" id="name" name="name" [(ngModel)]="user.name">
    </div>
    <div class="form-group">
      <label for="pwd">Age:</label>
      <input type="number" class="form-control" id="age" name="age" [(ngModel)]="user.age">
    </div>
    <div class="form-group">
        <label for="pwd">College:</label>
        <input type="text" class="form-control" id="college" name="college" [(ngModel)]="user.college">
      </div>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

<div class="user-list" *ngIf="usersList && usersList.length">
    <h2>List of Users</h2>
    <table class="table table-condensed">
        <thead>
        <tr>
            <th>SL.No</th>
            <th>Name</th>
            <th>Age</th>
            <th>College</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
            <tr *ngFor="let user of usersList; let i = index">
                <th>{{i}}</th>
                <td>{{user.name}}</td>
                <td>{{user.age}}</td>
                <td>{{user.college}}</td>
                <td>
                    <button style="margin-right: 5px;" class="btn btn-warning" (click)="editStudent(i)">Edit</button>
                    <button class="btn btn-danger" (click)="deleteStudent(i)">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

app.component.ts

```<code>export class AppComponent implements OnInit{
  user: User;
  usersList: User[] = []

  ngOnInit(): void {
   this.resetForm();
  }

  addStudent() {
   this.usersList.push(this.user);
   this.resetForm();
  }

  editStudent(index: number) {
    this.user = this.usersList[index];
    this.deleteStudent(index);
  }

  deleteStudent(index: number) {
    this.usersList.splice(index, 1);
  }

  resetForm() {
   this.user = {age: null, name: '', college: ''};
  }
}

interface User {
 name: string;
 age: string;
 college: string;
}
</code>```

Body:
I am doing a project that need to display an array and user can add in new data or delete existing data from the array.

I am stuck with how to add and delete item from array.

I tried to use push function to add and pop function to delete but failed.

HTML

Student Details

 Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" value={{selectedStudent.name}}>

 Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"
                value={{selectedStudent.age}}>

College:<input type="text" [(ngModel)]="college" placeholder="Please enter College"
                value={{selectedStudent.college}}>

        <button class="btnA" onclick="addStudent()">Add</button>
        <button class="btnE" onclick="editStudent()">Edit</button>
        <button class="btnD" onclick="deleteStudent()">Delete</button>

        {{student.name}} {{student.age}} {{student.college}}

.ts

export class WriteComponent implements OnInit {

    name: string;
    age: number;
    college: string;
    student = STUDENTS;
    selectedStudent: Student;

    constructor() {}
    ngOnInit(): void {}

    onSelect(student: Student): void {
        this.selectedStudent = student;
    }

}

mock-student.ts (where I store my array)

import { Student } from './student';

export const STUDENTS : Student[]=[
  {name:'Johnny',age:24,college:'Harvard'},
  {name:'Samantha',age:20,college:'INTI'},
  {name:'Aditya',age:21,college:'Sunway'},
  {name:'Troy',age:25,college:'TARUC'},
]

Body:
Hope this helps.....

Result:

app.component.html

<div class="container">
<h2>Add User</h2>
<form class="form-inline" autocomplete="off" (submit)="addStudent()">
    <div class="form-group">
      <label for="email">Name:</label>
      <input type="text" class="form-control" id="name" name="name" [(ngModel)]="user.name">
    </div>
    <div class="form-group">
      <label for="pwd">Age:</label>
      <input type="number" class="form-control" id="age" name="age" [(ngModel)]="user.age">
    </div>
    <div class="form-group">
        <label for="pwd">College:</label>
        <input type="text" class="form-control" id="college" name="college" [(ngModel)]="user.college">
      </div>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

<div class="user-list" *ngIf="usersList && usersList.length">
    <h2>List of Users</h2>
    <table class="table table-condensed">
        <thead>
        <tr>
            <th>SL.No</th>
            <th>Name</th>
            <th>Age</th>
            <th>College</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
            <tr *ngFor="let user of usersList; let i = index">
                <th>{{i}}</th>
                <td>{{user.name}}</td>
                <td>{{user.age}}</td>
                <td>{{user.college}}</td>
                <td>
                    <button style="margin-right: 5px;" class="btn btn-warning" (click)="editStudent(i)">Edit</button>
                    <button class="btn btn-danger" (click)="deleteStudent(i)">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

app.component.ts

export class AppComponent implements OnInit{
  user: User;
  usersList: User[] = []

  ngOnInit(): void {
   this.resetForm();
  }

  addStudent() {
   this.usersList.push(this.user);
   this.resetForm();
  }

  editStudent(index: number) {
    this.user = this.usersList[index];
    this.deleteStudent(index);
  }

  deleteStudent(index: number) {
    this.usersList.splice(index, 1);
  }

  resetForm() {
   this.user = {age: null, name: '', college: ''};
  }
}

interface User {
 name: string;
 age: string;
 college: string;
}


问:
Is there a way to DeserializeObject without empty constructor?
I am currently in the progress of enabling non-nullable reference types for my .net core api.

The problem is that the integrationtest fails when trying to deserializeObject because it has no empty constructor. I can't have an empty constructor because that will make property: possible null.

The problem:

JsonConvert.DeserializeObject<ViewModel>(result); calls the constructor which has a constructor with an object argument ViewModel(Model model). In the test this is null.

I have made a simple sample:

The api:

```<code>public class Dog
    {
        public string Name { get; set; } = null!;
    }

    public class DogViewModel
    {

        public DogViewModel(Dog dog)
        {
            Name = dog.Name;
        }

        public string Name { get; set; }
    }

    [HttpGet]
    [Route("dog")]
    public DogViewModel GetDog()
    {
        var dog = new Dog
        {
            Name = "Fido"
        };
        return new DogViewModel(dog);
    }
</code>```

This works when I use a client to call the api, but it fails from the tests:

Test

```<code>    [Fact]
    public async Task GetDog()
    {

        var response = await Client.GetAsync("dog");

        var result = response.Content.ReadAsStringAsync().Result;
        Assert.True(response.IsSuccessStatusCode, result);
        var responeseAsObject = JsonConvert.DeserializeObject<DogViewModel>(result); <----- this is where it breaks
        Assert.IsType<string>(responeseAsObject.Name);
        Assert.NotNull(responeseAsObject);
    }
</code>```

JsonConvert.DeserializeObject calls the constructor of DogViewModel;  DogViewModel(Dog dog), but dog is null.

答:
That's correct behavior JsonConvert.DeserializeObject uses constructor to just create an object. It won't pass any parameter to it and that's why you are getting an error.

What's happening is, dog is null and hence your assignment of Name = dog.Name; throws NullreferenceException.

You should ideally check dog for null before using it in your constructor.

```<code>    public DogViewModel(Dog dog)
    {
        Name = dog?.Name;
    }
</code>```

Body:
I am currently in the progress of enabling non-nullable reference types for my .net core api.

The problem is that the integrationtest fails when trying to deserializeObject because it has no empty constructor. I can't have an empty constructor because that will make property: possible null.

The problem:

JsonConvert.DeserializeObject<ViewModel>(result); calls the constructor which has a constructor with an object argument ViewModel(Model model). In the test this is null.

I have made a simple sample:

The api:

public class Dog
    {
        public string Name { get; set; } = null!;
    }

    public class DogViewModel
    {

        public DogViewModel(Dog dog)
        {
            Name = dog.Name;
        }

        public string Name { get; set; }
    }

    [HttpGet]
    [Route("dog")]
    public DogViewModel GetDog()
    {
        var dog = new Dog
        {
            Name = "Fido"
        };
        return new DogViewModel(dog);
    }

This works when I use a client to call the api, but it fails from the tests:

Test

    [Fact]
    public async Task GetDog()
    {

        var response = await Client.GetAsync("dog");

        var result = response.Content.ReadAsStringAsync().Result;
        Assert.True(response.IsSuccessStatusCode, result);
        var responeseAsObject = JsonConvert.DeserializeObject<DogViewModel>(result); <----- this is where it breaks
        Assert.IsType<string>(responeseAsObject.Name);
        Assert.NotNull(responeseAsObject);
    }

JsonConvert.DeserializeObject calls the constructor of DogViewModel;  DogViewModel(Dog dog), but dog is null.

Body:
That's correct behavior JsonConvert.DeserializeObject uses constructor to just create an object. It won't pass any parameter to it and that's why you are getting an error.

What's happening is, dog is null and hence your assignment of Name = dog.Name; throws NullreferenceException.

You should ideally check dog for null before using it in your constructor.

    public DogViewModel(Dog dog)
    {
        Name = dog?.Name;
    }


问:
Serialize JavaScript objects in ClojureScript
How do I make a writer for JS error object to send thru the wire? When I do (pr-str (js/Error. "OOPS")) it gives me "#object[Error Error: OOPS]". And (js->clj (js/Error. "Oops!")) gives something like #object[Error Error: Oops!].
I want to make a writer for JS errors so I can send them thru the wire (maybe EDN) and deserialize at the other end.

答:
ClojureScript does not attempt to serialize JS objects with a constructor, apart from some exceptions, like js/Date.
In the case of js/Error, it makes sense to first ask: how would this be solved in the JS world?
One answer is available here: https://stackoverflow.com/a/26199752/564509

```<code>(.stringify js/JSON (.getOwnPropertyNames js/Object err))
</code>```

If you need the error to be serialized not as JSON but as EDN, you just have to iterate over the error's own property names yourself and fill in the data structure. Something like

```<code>(defn err->edn [e]
  (into {}
        (map (fn [k]
               [(keyword k) (js->clj (gobject/get e k))]))
        (.getOwnPropertyNames js/Object e)))
</code>```

where gobject is required as [goog.object :as gobject].

Body:
ClojureScript does not attempt to serialize JS objects with a constructor, apart from some exceptions, like js/Date.
In the case of js/Error, it makes sense to first ask: how would this be solved in the JS world?
One answer is available here: https://stackoverflow.com/a/26199752/564509

(.stringify js/JSON (.getOwnPropertyNames js/Object err))

If you need the error to be serialized not as JSON but as EDN, you just have to iterate over the error's own property names yourself and fill in the data structure. Something like

(defn err->edn [e]
  (into {}
        (map (fn [k]
               [(keyword k) (js->clj (gobject/get e k))]))
        (.getOwnPropertyNames js/Object e)))

where gobject is required as [goog.object :as gobject].


问:
Angular material table dynamic rows
I am creating a project using angular and material. In my project i want to add customised footer row in material table on click of button and delete that row on click of delete button.

Here is my code:

https://stackblitz.com/edit/angular-dshjiz-beqnrj?file=src/app/table-basic-example.html

答:
You need to push data as mentioned by Armen. You also need to call renderRows() method of the table as per suggestion https://material.angular.io/components/table/overview#1-write-your-mat-table-and-provide-data

Please check your updated stackblitz example

Same method can be implemented to delete the row. Just make sure the renderRows method calls everytime the table updates.

Title: Angular material table dynamic rows


问:
Is it necessary to use “start_activity” with Appium?
I am using Python 3.7 with appium. After I defined my desired capabilities, I noticed the application is open when I call:

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

and then y automation test start without issues.

So I was wondering why to use:

```<code>driver.start_activity("com.app.android", "com.app.mainactivity.MainActivity")
</code>```

?

Because when I write the 2 lines:

```<code>driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.start_activity("com.instagram.android", "com.instagram.mainactivity.MainActivity")
</code>```

I can see Appium launching 2 times the app. So I make the conclusion that it is useless to write a line of code with "start_activity".

Can someone explain me the difference and in which scenario I should use "start_activity" as the declaration of driver with the line:

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

is enough to start the application and run the test.

Thanks for helping me to understand better appium.

答:
There is no need to use driver.start_activity unless you want to switch from the default one you gave in capabilities.

When you start the new session you already providing enough information (package, starting activity) for Appium to launch your application.

If you wonder about the use case for start_activity:

between the tests to reset the app state

quickly starting the test with custom App state rather than navigating through the app.

Body:
I am using Python 3.7 with appium. After I defined my desired capabilities, I noticed the application is open when I call:

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

and then y automation test start without issues.

So I was wondering why to use:

driver.start_activity("com.app.android", "com.app.mainactivity.MainActivity")

?

Because when I write the 2 lines:

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.start_activity("com.instagram.android", "com.instagram.mainactivity.MainActivity")

I can see Appium launching 2 times the app. So I make the conclusion that it is useless to write a line of code with "start_activity".

Can someone explain me the difference and in which scenario I should use "start_activity" as the declaration of driver with the line:

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

is enough to start the application and run the test.

Thanks for helping me to understand better appium.


问:
Switch to specific tab in Vim like in Firefox?
How do I make Vim switch to a certain tab when I hit Alt+# ?  For example, to get to the third tab, I'd hit Alt+3 (like the behavior in Firefox).

Edit: also, how can I make Control + tab == gt, Control + shift + tab == gT

答:
Getting this to work in urxvt proved difficult. Eventually I settled on using the folowing bindings:

```<code>:nnoremap <Esc>1 gt1
:nnoremap <Esc>2 gt2
:nnoremap <Esc>3 gt3
:nnoremap <Esc>4 gt4
:nnoremap <Esc>5 gt5
:nnoremap <Esc>6 gt6
:nnoremap <Esc>7 gt7
:nnoremap <Esc>8 gt8
:nnoremap <Esc>9 gt9
:nnoremap <Esc>0 gt0
</code>```

The problem was that Alt number combinations get bound to escape prefixed numbers by default in rxvt. Originally I managed by having the following in my ~/.vimrc file:

```<code>:nnoremap <M-1> gt1
:nnoremap <M-2> gt2
...
</code>```

This was made to work by using the following to '~/.Xdefaults':

```<code>URxvt*meta8: true
</code>```

This forces rxvt to use the 8th character bit when Alt is pressed, which is what Vim uses to detect the Alt state. Setting this in your .Xdefaults file enables the 8th bit to be set. However, this causes problems in other programs, such as irssi running over screen, hence my suggested solution.

ContentLicense: CC BY-SA 2.5

Body:
Getting this to work in urxvt proved difficult. Eventually I settled on using the folowing bindings:

:nnoremap <Esc>1 gt1
:nnoremap <Esc>2 gt2
:nnoremap <Esc>3 gt3
:nnoremap <Esc>4 gt4
:nnoremap <Esc>5 gt5
:nnoremap <Esc>6 gt6
:nnoremap <Esc>7 gt7
:nnoremap <Esc>8 gt8
:nnoremap <Esc>9 gt9
:nnoremap <Esc>0 gt0

The problem was that Alt number combinations get bound to escape prefixed numbers by default in rxvt. Originally I managed by having the following in my ~/.vimrc file:

:nnoremap <M-1> gt1
:nnoremap <M-2> gt2
...

This was made to work by using the following to '~/.Xdefaults':

URxvt*meta8: true

This forces rxvt to use the 8th character bit when Alt is pressed, which is what Vim uses to detect the Alt state. Setting this in your .Xdefaults file enables the 8th bit to be set. However, this causes problems in other programs, such as irssi running over screen, hence my suggested solution.


问:
Sql query to get output on the basis of 3 columns in oracle SQL
I have a scenario where i have 3 coloumns i.e liqn_days , liq_months and liqn_years .
So if liqn_days have value and others are 0 then print Monthly .
or liq_months  is 3 others are 0 then get output as quartely.
or liq_months  is 6 and others coloumns are 0 then output will be half yearly
or liqn_years  is having value or others are 0 then output will be  yearly.

```<code>liqn_days  liq_months  liqn_years

0          0            1

12        0             0

0         3             0

ouput for 1st row - Yearly
ouput for 2st row  - Monthly
output for 3rd row - quarterly
</code>```

Please assist me in this .

答:
You can use case expression :

```<code>select t.*, (case when liqn_days > 0 and liq_months = 0 and liqn_yearsand = 0
                  then 'Monthly'
                  when liq_months = 3 and liqn_days = 0 and liqn_yearsand = 0
                  then 'quarterly'
                  when liq_months =  6 and liqn_days = 0 and liqn_yearsand = 0
                  then 'half yearly'
                  when liq_months =  0 and liqn_days = 0 and liqn_yearsand > 0
                  then ' yearly'
                  else 'other'
             end)
from table t;
</code>```

Body:
I have a scenario where i have 3 coloumns i.e liqn_days , liq_months and liqn_years .
So if liqn_days have value and others are 0 then print Monthly .
or liq_months  is 3 others are 0 then get output as quartely.
or liq_months  is 6 and others coloumns are 0 then output will be half yearly
or liqn_years  is having value or others are 0 then output will be  yearly.

liqn_days  liq_months  liqn_years

0          0            1

12        0             0

0         3             0

ouput for 1st row - Yearly
ouput for 2st row  - Monthly
output for 3rd row - quarterly

Please assist me in this .

Body:
You can use case expression :

select t.*, (case when liqn_days > 0 and liq_months = 0 and liqn_yearsand = 0
                  then 'Monthly'
                  when liq_months = 3 and liqn_days = 0 and liqn_yearsand = 0
                  then 'quarterly'
                  when liq_months =  6 and liqn_days = 0 and liqn_yearsand = 0
                  then 'half yearly'
                  when liq_months =  0 and liqn_days = 0 and liqn_yearsand > 0
                  then ' yearly'
                  else 'other'
             end)
from table t;


问:
When can a comparison operator ever return anything else than 0 or 1?
Comparison operators in C, they return either 0 for false, and non-zero for true. Is this correct?

Are there any examples where a comparison operator can return anything else than 0 or 1?

I cannot think of any so why is it possible that C can return anything else but 0 or 1? I mean (2 > 0) will always be 1. (2 == 2) will always be 1. In which cases can that ever return anything else but 1?

Hope it makes sense

答:
No, these operators are specified by the standard to explicitly return 1 or 0. From chapter 6.5 of the standard:

Relational operators

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >=
  (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is
  false. The result has type int.

Equality operators

The == (equal to) and != (not equal to) operators are analogous to the relational
  operators except for their lower precedence. Each of the operators yields 1 if the
  specified relation is true and 0 if it is false. The result has type int.


问:
Get most upper descendant descendant(s) in jQuery
From page=$("#page") I want to get all the specified SVGs but not the subsequent inner ones.

```<code><div id="page">
    <div ...>
        <svg> /* THIS ONE */
            <rect ...>
            <circle ...>
            <svg> /* NOT THIS ONE */
                <foo> ... </foo>
            </svg>
        </svg>
    </div>
    <div ...>
        <div ...>
            <svg> /* THIS ONE */
                <rect ...>
                <circle ...>
                <svg> /* NOT THIS ONE */
                    <foo> ... </foo>
                </svg>
            </svg>
        </div>
   </div>
</div>
</code>```

EDIT I've updated the markup to clearly specify what I mean.

One solution is to use :not(svg svg) which i find ugly and performance heavy.

答:
You could use the following:

```<code>$(page).children(svg).first()
</code>```

Which will get you the first svg, in this case the outer most one, but might also still be performance heavy if that is part of your concern.

Body:
From page=$("#page") I want to get all the specified SVGs but not the subsequent inner ones.

        <svg> /* THIS ONE */
            <rect ...>
            <circle ...>
            <svg> /* NOT THIS ONE */
                <foo> ... </foo>
            </svg>
        </svg>

            <svg> /* THIS ONE */
                <rect ...>
                <circle ...>
                <svg> /* NOT THIS ONE */
                    <foo> ... </foo>
                </svg>
            </svg>

EDIT I've updated the markup to clearly specify what I mean.

One solution is to use :not(svg svg) which i find ugly and performance heavy.

Body:
You could use the following:

$(page).children(svg).first()

Which will get you the first svg, in this case the outer most one, but might also still be performance heavy if that is part of your concern.


问:
how to add RecyclerView in one of the inflated layout of viewpager2

I'm trying to create a RecyclerView in each layout of viewpager2

for viewpager2 I'm using RecyclerView adapter to inflate layouts

1. main layout

```<code><androidx.viewpager2.widget.ViewPager2
        android:id="@+id/id_view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/id_settings_package_tab_layout" />
</code>```

2. I'm calling an adapter

```<code>id_view_pager.adapter = MultiViewAdapter(this, list)
</code>```

3. MultiViewAdapter

```<code>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            R.layout.fragment_pkg_set_type -> {
                var view: View = layoutInflater.inflate(R.layout.fragment_layout, parent, false)
                Log.d("log", "onCreateViewHolder : Layout inflating is called")
                return ViewHolder1(view)
            }
            else -> {
                var view: View =
                    layoutInflater.inflate(R.layout.fragment_layout_others, parent, false)
                return ViewHolder2(view)
            }
        }
    }
</code>```

4. fragment_layout

```<code><androidx.recyclerview.widget.RecyclerView
        android:id="@+id/id_pkg_set_type_list_rv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/fragment_pkg_type_list_ui"/>

    <EditText
        android:id="@+id/id_pkg_type_value"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:hint="Add Type"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/id_pkg_type_add"
        app:layout_constraintStart_toStartOf="parent" />
</code>```

now I'm getting the all the inflated layouts and EditText was visible

now in order to load RecyclerView I wrote one more file corresponds to fragment_layout file

5. LayoutFragment.kt

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        var myDataset = arrayOf("one", "two", "three", "four", "five")
        var viewManager = LinearLayoutManager(context)
        var viewAdapter = PackageTypeAdapter(context, myDataset)

        viewManager.orientation = LinearLayoutManager.VERTICAL
        id_pkg_set_type_list_rv.setHasFixedSize(true)
        id_pkg_set_type_list_rv.layoutManager = viewManager
        id_pkg_set_type_list_rv.adapter = viewAdapter

        viewAdapter.notifyDataSetChanged()
    }

    class PackageTypeAdapter(context: Context?, data: Array<String>) :
        RecyclerView.Adapter<PackageTypeAdapter.MyViewHolder>() {

        var mData: Array<String>

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): PackageTypeAdapter.MyViewHolder {
            var layoutInflater = LayoutInflater.from(parent.context)
            var view = layoutInflater.inflate(R.layout.fragment_pkg_type_list_ui, parent, false)
            return MyViewHolder(view)
        }

        override fun getItemCount(): Int {
            return mData.size
        }

        override fun onBindViewHolder(holder: PackageTypeAdapter.MyViewHolder, position: Int) {
            holder.text_value.text = mData[position]
        }

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var text_value: TextView

            init {
                text_value = itemView.findViewById(R.id.id_text_value)
            }
        }

        init {
            mData = data
        }

    }
</code>```

unfortunately it is not reading this file

So, I'm not getting RecyclerView list

How to load nested RecyclerView to Viewpager2 which uses a RecyclerView to inflate layouts into viewpager2 ?

答:
I think you confused a lot. and That's why you are creating LayoutFragment.kt

You have to delete that file and add

```<code>is ViewHolder1 -> {
                var myDataset = arrayOf("one", "two", "three", "four", "five")
                var viewManager = LinearLayoutManager(ctx)
                var viewAdapter = PkgSetTypeFragment.PackageTypeAdapter(ctx, myDataset)

                viewManager.orientation = LinearLayoutManager.VERTICAL
                holder.id_pkg_set_type_list_rv.setHasFixedSize(true)
                holder.id_pkg_set_type_list_rv.layoutManager = viewManager
                holder.id_pkg_set_type_list_rv.adapter = viewAdapter

                viewAdapter.notifyDataSetChanged()

                holder.imageButton.setOnClickListener(View.OnClickListener {

                })
            }
            is ViewHolder2 -> holder.myTextView.text = mData[position]
</code>```

inside on view bind holder file.

Body:
I'm trying to create a RecyclerView in each layout of viewpager2

for viewpager2 I'm using RecyclerView adapter to inflate layouts

1. main layout

<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/id_view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/id_settings_package_tab_layout" />

2. I'm calling an adapter

id_view_pager.adapter = MultiViewAdapter(this, list)

3. MultiViewAdapter

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            R.layout.fragment_pkg_set_type -> {
                var view: View = layoutInflater.inflate(R.layout.fragment_layout, parent, false)
                Log.d("log", "onCreateViewHolder : Layout inflating is called")
                return ViewHolder1(view)
            }
            else -> {
                var view: View =
                    layoutInflater.inflate(R.layout.fragment_layout_others, parent, false)
                return ViewHolder2(view)
            }
        }
    }

4. fragment_layout

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/id_pkg_set_type_list_rv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/fragment_pkg_type_list_ui"/>

    <EditText
        android:id="@+id/id_pkg_type_value"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:hint="Add Type"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/id_pkg_type_add"
        app:layout_constraintStart_toStartOf="parent" />

now I'm getting the all the inflated layouts and EditText was visible

now in order to load RecyclerView I wrote one more file corresponds to fragment_layout file

5. LayoutFragment.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        var myDataset = arrayOf("one", "two", "three", "four", "five")
        var viewManager = LinearLayoutManager(context)
        var viewAdapter = PackageTypeAdapter(context, myDataset)

        viewManager.orientation = LinearLayoutManager.VERTICAL
        id_pkg_set_type_list_rv.setHasFixedSize(true)
        id_pkg_set_type_list_rv.layoutManager = viewManager
        id_pkg_set_type_list_rv.adapter = viewAdapter

        viewAdapter.notifyDataSetChanged()
    }

    class PackageTypeAdapter(context: Context?, data: Array<String>) :
        RecyclerView.Adapter<PackageTypeAdapter.MyViewHolder>() {

        var mData: Array<String>

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): PackageTypeAdapter.MyViewHolder {
            var layoutInflater = LayoutInflater.from(parent.context)
            var view = layoutInflater.inflate(R.layout.fragment_pkg_type_list_ui, parent, false)
            return MyViewHolder(view)
        }

        override fun getItemCount(): Int {
            return mData.size
        }

        override fun onBindViewHolder(holder: PackageTypeAdapter.MyViewHolder, position: Int) {
            holder.text_value.text = mData[position]
        }

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var text_value: TextView

            init {
                text_value = itemView.findViewById(R.id.id_text_value)
            }
        }

        init {
            mData = data
        }

    }

unfortunately it is not reading this file

So, I'm not getting RecyclerView list

How to load nested RecyclerView to Viewpager2 which uses a RecyclerView to inflate layouts into viewpager2 ?

Body:
I think you confused a lot. and That's why you are creating LayoutFragment.kt

You have to delete that file and add

is ViewHolder1 -> {
                var myDataset = arrayOf("one", "two", "three", "four", "five")
                var viewManager = LinearLayoutManager(ctx)
                var viewAdapter = PkgSetTypeFragment.PackageTypeAdapter(ctx, myDataset)

                viewManager.orientation = LinearLayoutManager.VERTICAL
                holder.id_pkg_set_type_list_rv.setHasFixedSize(true)
                holder.id_pkg_set_type_list_rv.layoutManager = viewManager
                holder.id_pkg_set_type_list_rv.adapter = viewAdapter

                viewAdapter.notifyDataSetChanged()

                holder.imageButton.setOnClickListener(View.OnClickListener {

                })
            }
            is ViewHolder2 -> holder.myTextView.text = mData[position]

inside on view bind holder file.


问:
How to get the full dates between two dates using javascript / react?
My requirement is to get the number of days between two dates.

For example, the start date is 02/20/2020 to 01/03/2020 I would like to display the results like

Feb 20 Thursday, Feb 21 Friday,....01 Mar Monday.

I went through this scenario in StackOverflow but I didn't get the expected solution for the same.

Could anyone please guide in achieving this scenario using javascript or react?

答:
You can start by first creating two date objects, one for the start date and another for the end date. Then, find out how many days are in between these dates. Finally, you can loop through this number and get the current date plus the current index in the loop and print that.

As a React component:

const App = () => {
  const [dates, setDates] = React.useState([]);

  React.useEffect(() => {
    const start = new Date('02/20/2020');
    const end = new Date('03/01/2020');

    const daysBetween = (end.getTime() - start.getTime()) / (1000 * 3600 * 24);
    const arr = [];

    for (let i = 0; i <= daysBetween; i++) {
      const temp = new Date();
      temp.setDate(start.getDate() + i)
      arr.push(temp);
    }

    setDates(arr);
  }, []);

  return (

      {dates.map(date => (

          {date.toLocaleDateString(
            "en-US",
            {month: "short", day: "2-digit", weekday: "long"}
          )}

      ))}

  );
}

ReactDOM.render(<App />, document.getElementById("app"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

Body:
You can start by first creating two date objects, one for the start date and another for the end date. Then, find out how many days are in between these dates. Finally, you can loop through this number and get the current date plus the current index in the loop and print that.

As a React component:

const App = () => {
  const [dates, setDates] = React.useState([]);

  React.useEffect(() => {
    const start = new Date('02/20/2020');
    const end = new Date('03/01/2020');

    const daysBetween = (end.getTime() - start.getTime()) / (1000 * 3600 * 24);
    const arr = [];

    for (let i = 0; i <= daysBetween; i++) {
      const temp = new Date();
      temp.setDate(start.getDate() + i)
      arr.push(temp);
    }

    setDates(arr);
  }, []);

  return (
    <ul>
      {dates.map(date => (
        <li key={date}>
          {date.toLocaleDateString(
            "en-US",
            {month: "short", day: "2-digit", weekday: "long"}
          )}
        </li>
      ))}
    </ul>
  );
}

ReactDOM.render(<App />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>


问:
getting exception "desired type = NSOrderedSet; given type = __NSArrayM " in swift while mapping collection
[1 I have ticked sorted]I am using swift verison pod 'FastEasyMapping', '~> 1.2'

I am getting the below error:

desired type = NSOrderedSet; given type = __NSArrayM

while mapping using method

```<code>FEMDeserializer.collection(fromRepresentation:mapping:context)
</code>```

Getting exception in line ::

```<code>mapping.addToManyRelationshipMapping(ABC.defaultmapping(), forProperty: "cde", keyPath: "CDE")
</code>```

property of cde is in  ABC is

```<code>@NSManaged var cde : NSOrderedSet!
</code>```

答:
I Got the Reason it was silly mistake  that I wrote wrong key I write this ::

mapping.addToManyRelationshipMapping(ABC.defaultmapping(), forProperty: "CDE", keyPath: "cde")

that should be actually ::
 mapping.addToManyRelationshipMapping(ABC.defaultmapping(), forProperty: "cde", keyPath: "CDE")

Thanks All

Body:
[1 I have ticked sorted]I am using swift verison pod 'FastEasyMapping', '~> 1.2'

I am getting the below error:

desired type = NSOrderedSet; given type = __NSArrayM

while mapping using method

FEMDeserializer.collection(fromRepresentation:mapping:context)

Getting exception in line ::

mapping.addToManyRelationshipMapping(ABC.defaultmapping(), forProperty: "cde", keyPath: "CDE")

property of cde is in  ABC is

@NSManaged var cde : NSOrderedSet!


问:
How do I update an object state in react via hooks
This is a simple question. How do I successfully update state object via react hooks?

I just started using hooks, and I like how it allows to use the simple and pure JavaScript function to create and manage state with the useState() function, and also, make changes that affect components using the useEffect() function, but I can't seem to make update to the state work!

After making a request to an API, it return the data needed, but when I try to update the state for an error in request and for a successful request, it does not update the state. I logged it to the browser console, but no change was made to the state, it returns undefined.

I know that I'm not doing something right in the code.
Here is my App component, Its a single component for fetching and updating:

```<code>import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading'
    });

    // Fetch and update date
    useEffect(() => {

        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                SetData({placeholder: 'Something went wrong'});
            }
            response.json()
        })
        .then(result => {
           console.log(data);
           setData({data: result});
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}

ReactDOM.render(<App />, document.getElementById('app'));
</code>```

答:
There are a few things you can improve:

the react-hook useState does not behave like the class counterpart. It does not automatically merge the provided object with the state, you have to do that yourself.

I would recommend if you can work without an object as your state to do so as this can reduce the amount of re-renders by a significant amount and makes it easier to change the shape of the state afterwards as you can just add or remove variables and see all the usages immediately.

With a state object

```<code>export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading'
    });

    // Fetch and update date
    useEffect(() => {
        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                throw new Error(response.statusText); // Goto catch block
            }
            return response.json(); // <<- Return the JSON Object
        })
        .then(result => {
           console.log(data);
           setData(oldState => ({ ...oldState, data: result})); // <<- Merge previous state with new data
        })
        .catch(error => { // Use .catch() to catch exceptions. Either in the request or any of your .then() blocks
            console.error(error); // Log the error object in the console.
            const errorMessage = 'Something went wrong';
            setData(oldState=> ({ ...oldState, placeholder: errorMessage }));
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}
</code>```

Without a state object

```<code>export default function App() {
    const [data, setData] = useState([]);
    const [loaded, setLoaded] = useState(false);
    const [placeholder, setPlaceholder] = useState('Loading');

    // Fetch and update date
    useEffect(() => {
        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                throw new Error(response.statusText); // Goto catch block
            }
            return response.json(); // <<- Return the JSON Object
        })
        .then(result => {
           console.log(data);
           setData(data);
        })
        .catch(error => { // Use .catch() to catch exceptions. Either in the request or any of your .then() blocks
            console.error(error); // Log the error object in the console.
            const errorMessage = 'Something went wrong';
            setPlaceholder(errorMessage);
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}
</code>```

Body:
This is a simple question. How do I successfully update state object via react hooks?

I just started using hooks, and I like how it allows to use the simple and pure JavaScript function to create and manage state with the useState() function, and also, make changes that affect components using the useEffect() function, but I can't seem to make update to the state work!

After making a request to an API, it return the data needed, but when I try to update the state for an error in request and for a successful request, it does not update the state. I logged it to the browser console, but no change was made to the state, it returns undefined.

I know that I'm not doing something right in the code.
Here is my App component, Its a single component for fetching and updating:

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading'
    });

    // Fetch and update date
    useEffect(() => {

        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                SetData({placeholder: 'Something went wrong'});
            }
            response.json()
        })
        .then(result => {
           console.log(data);
           setData({data: result});
        });

    },[]);

    return (

{console.log(data)}

    );
}

ReactDOM.render(<App />, document.getElementById('app'));

Body:
There are a few things you can improve:

the react-hook useState does not behave like the class counterpart. It does not automatically merge the provided object with the state, you have to do that yourself.

I would recommend if you can work without an object as your state to do so as this can reduce the amount of re-renders by a significant amount and makes it easier to change the shape of the state afterwards as you can just add or remove variables and see all the usages immediately.

With a state object

export default function App() {

    // Set date state
    const [data,setData]  = useState({
       data: [],
       loaded: false,
       placeholder: 'Loading'
    });

    // Fetch and update date
    useEffect(() => {
        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                throw new Error(response.statusText); // Goto catch block
            }
            return response.json(); // <<- Return the JSON Object
        })
        .then(result => {
           console.log(data);
           setData(oldState => ({ ...oldState, data: result})); // <<- Merge previous state with new data
        })
        .catch(error => { // Use .catch() to catch exceptions. Either in the request or any of your .then() blocks
            console.error(error); // Log the error object in the console.
            const errorMessage = 'Something went wrong';
            setData(oldState=> ({ ...oldState, placeholder: errorMessage }));
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}

Without a state object

export default function App() {
    const [data, setData] = useState([]);
    const [loaded, setLoaded] = useState(false);
    const [placeholder, setPlaceholder] = useState('Loading');

    // Fetch and update date
    useEffect(() => {
        fetch('http://localhost:8000/api/lead/')
        .then(response => {
            if (response.status !== 200) {
                throw new Error(response.statusText); // Goto catch block
            }
            return response.json(); // <<- Return the JSON Object
        })
        .then(result => {
           console.log(data);
           setData(data);
        })
        .catch(error => { // Use .catch() to catch exceptions. Either in the request or any of your .then() blocks
            console.error(error); // Log the error object in the console.
            const errorMessage = 'Something went wrong';
            setPlaceholder(errorMessage);
        });

    },[]);

    return (
      <h1>{console.log(data)}</h1>
    );
}


问:
How can I make this macro work on selected text only? And can it be made to run faster?
I need to check certain documents to determine whether the number of insertions is < or >= 50% of the original text.
The macro I've cobbled together from various online sources does this quite well, and gives one of two message box messages depending on the text in question.

However, there are two issues:

the macro appears to run on the entire text, and I would like it to run only on the text the user manually selects prior to running the macro.

on certain files it hangs for a long time and sometimes crashes my PC.

How can I adjust the macro to ensure that it will run only on selected text? And can it be tweaked to make it run faster/be more robust/not crash my PC?

```<code>Sub RevMacro2()
  Dim lInsertsWords As Long
  Dim oRevision As Revision

    lInsertsWords = 0
    For Each oRevision In ActiveDocument.Revisions
        Select Case oRevision.Type
            Case wdRevisionInsert
                lInsertsWords = lInsertsWords + oRevision.Range.Words.Count
        End Select
    Next oRevision

n = ActiveDocument.Range.ComputeStatistics(wdStatisticWords)
o = lInsertsWords
p = n / 2

Dim message As String
 If o < p Then
    message = "Blocks:" & vbTab & "60% Copy fee" & vbCr & _
    "Other:" & vbTab & "75% Copy fee"
 End If
 If o >= p Then
    message = "Blocks: 75% Copy fee" & vbCr & _
    "Other: 100% Copy fee" & vbCr
 End If
 MsgBox message

End Sub
</code>```

答:
For an additional criterion, you might use something like:</p>

```<code>Sub RevMacro()
Dim i As Long, j As Long, n As Long, r As Long
With Selection.Range
  n = .ComputeStatistics(wdStatisticWords): r = .Revisions.Count
  For i = 1 To r
    With .Revisions(i)
      If .Type = wdRevisionInsert Then j = j + .Range.ComputeStatistics(wdStatisticWords)
    End With
  Next
End With
If j / n < 0.5 Then 'less than 50%
  MsgBox "Blocks:" & vbTab & "60% Copy fee" & vbCr & _
  "Other:" & vbTab & "75% Copy fee"
ElseIf j / n < 0.75 Then  '50%+ but less than 75%
  MsgBox "Blocks: 75% Copy fee" & vbCr & _
    "Other: 90% Copy fee" & vbCr
Else '75%+
  MsgBox "Blocks: 90% Copy fee" & vbCr & _
    "Other: 100% Copy fee" & vbCr
End If
End Sub
</code>```

Body:
I need to check certain documents to determine whether the number of insertions is < or >= 50% of the original text.
The macro I've cobbled together from various online sources does this quite well, and gives one of two message box messages depending on the text in question.

However, there are two issues:

the macro appears to run on the entire text, and I would like it to run only on the text the user manually selects prior to running the macro.

on certain files it hangs for a long time and sometimes crashes my PC.

How can I adjust the macro to ensure that it will run only on selected text? And can it be tweaked to make it run faster/be more robust/not crash my PC?

Sub RevMacro2()
  Dim lInsertsWords As Long
  Dim oRevision As Revision

    lInsertsWords = 0
    For Each oRevision In ActiveDocument.Revisions
        Select Case oRevision.Type
            Case wdRevisionInsert
                lInsertsWords = lInsertsWords + oRevision.Range.Words.Count
        End Select
    Next oRevision

n = ActiveDocument.Range.ComputeStatistics(wdStatisticWords)
o = lInsertsWords
p = n / 2

Dim message As String
 If o
= p Then
    message = "Blocks: 75% Copy fee" & vbCr & _
    "Other: 100% Copy fee" & vbCr
 End If
 MsgBox message

End Sub

Body:
For an additional criterion, you might use something like:

Sub RevMacro()
Dim i As Long, j As Long, n As Long, r As Long
With Selection.Range
  n = .ComputeStatistics(wdStatisticWords): r = .Revisions.Count
  For i = 1 To r
    With .Revisions(i)
      If .Type = wdRevisionInsert Then j = j + .Range.ComputeStatistics(wdStatisticWords)
    End With
  Next
End With
If j / n < 0.5 Then 'less than 50%
  MsgBox "Blocks:" & vbTab & "60% Copy fee" & vbCr & _
  "Other:" & vbTab & "75% Copy fee"
ElseIf j / n < 0.75 Then  '50%+ but less than 75%
  MsgBox "Blocks: 75% Copy fee" & vbCr & _
    "Other: 90% Copy fee" & vbCr
Else '75%+
  MsgBox "Blocks: 90% Copy fee" & vbCr & _
    "Other: 100% Copy fee" & vbCr
End If
End Sub