问:
How to sort by numbers that are part of a filename in bash?
I'm trying to assign a variable in bash to the file in this directory with the largest number before the '.tar.gz' and I'm drawing a complete blank on the best way to approach this:</p>

```<code>ls /dirname | sort
daily-500-12345.tar.gz
daily-500-12345678.tar.gz
daily-500-987654321.tar.gz
weekly-200-1111111.tar.gz
monthly-100-8675309.tar.gz
</code>```

答:
```<code>sort -Vrt - -k3,3
</code>```

-V Natural sort

-r Reverse, so you can use head -1 to get the first line only

-t - Use hyphen as field separator

-k3,3 Sort using only the third field

Output:

daily-500-987654321.tar.gz
daily-500-12345678.tar.gz
monthly-100-8675309.tar.gz
weekly-200-1111111.tar.gz
daily-500-12345.tar.gz
```

Body:
I'm trying to assign a variable in bash to the file in this directory with the largest number before the '.tar.gz' and I'm drawing a complete blank on the best way to approach this:

ls /dirname | sort
daily-500-12345.tar.gz
daily-500-12345678.tar.gz
daily-500-987654321.tar.gz
weekly-200-1111111.tar.gz
monthly-100-8675309.tar.gz

Body:
sort -Vrt - -k3,3

-V Natural sort

-r Reverse, so you can use head -1 to get the first line only

-t - Use hyphen as field separator

-k3,3 Sort using only the third field

Output:

daily-500-987654321.tar.gz
daily-500-12345678.tar.gz
monthly-100-8675309.tar.gz
weekly-200-1111111.tar.gz
daily-500-12345.tar.gz


来源: stackexchange

问:
Does including ncurses.h in C programming also include stdio.h?
I was studying up on ncurses.h because I am trying to learn a bit of design aspects for c, and stumbled across a statement saying that stdio.h is inside of ncurses

```<code>  #include <ncurses.h>        /*ncurses.h includes stdio.h*/
</code>```

Is this true? If so, can someone explain to me why, and if that means I don't have to ever include it again?

Also, does this cause any issues because I am not exactly defining it in a regular sense

答:
ncurses' curses.h includes <stdio.h> because a few of the (X/Open Curses) standard functions which curses.h declares use FILE.  The C standard refers to FILE as an "object type", which some might read literally as requiring a typedef.  However there have been implementations where FILE is a symbol defined with #define, e.g.,

```<code>#define   FILE    struct _iobuf
</code>```

(quoting from more than one BSD: 4.3BSD, SunOS 4, Ultrix).  Without delving into its history, I'd assume the change to make it a typedef came from the AT&T code since it shows up in the SVr4 implementations.

For that reason (as well as it being the simplest way to guarantee that FILE is declared properly), curses.h will include stdio.h.

Now... there are a few other header files which you might encounter which require another header file to be included, to make them useful.  One longstanding example is for the stat function, i.e.,

```<code>#include <sys/types.h>
#include <sys/stat.h>
</code>```

but in the relevant (system-specific) documentation, both headers are shown in the manual page summary.  The POSIX documentation for stat does not point that out, but uses it in the examples.   Some newer implementations include (or provide in some roundabout way) the definitions from <sys/types.h> needed in <sys/stat.h>, but in writing portable code, that has not been something to rely upon.

curses was never documented in that way, e.g., you're unlikely to find manual pages showing

```<code>#include <stdio.h>
#include <curses.h>
</code>```

because the original 4BSD curses included <stdio.h>.  Interestingly enough, 4.2BSD curses header did not use any definition from stdio.h.  It also included sgtty.h (analogous to termios.h), but used those definitions in the header file.  Perhaps the original developer thought that including stdio.h was a good idea.  In any case, in later versions of curses, it did use FILE, and since the precedent of including stdio.h. from curses.h was well established, no one considered splitting things up as done with <sys/types.h> and <sys/stat.h>.

ncurses' documentation has mentioned the header files which curses.h includes, in a NOTES section:

The header file <curses.h>  automatically  includes  the  header  files
  <stdio.h> and <unctrl.h>.

That note dates back to ncurses 1.8.7 in 1994, making it rather unlikely that you will encounter a version of ncurses for which the statement is untrue.

X/Open Curses has something similar to say:

The inclusion of <curses.h> may make visible all symbols from the headers <stdio.h>, <term.h>, <termios.h> and <wchar.h>.

HPUX curses, for instance, includes <term.h> from <curses.h> to declare setupterm in curses.h, but ncurses (and Solaris curses) do not.  AIX curses includes <term.h> and <termios.h>.  Again, ncurses (and Solaris curses) do not.  X/Open Curses says "may make visible" because including a header file  does not necessarily make all symbols in it visible (there are ifdef's to consider).

However, these functions in any X/Open Curses (i.e., anything more current than 1990) use FILE, making <stdio.h> needed for <curses.h>:

getwin (SVr4)

newterm (SVr2)

putwin (SVr4)

Now... including <stdio.h> before <curses.h> probably will not make any difference (aside from adding clutter to your program).  It's possible (but unlikely) that there could be some symbol redefined in <curses.h> which alters the behavior of the standard features in <stdio.h>.  Since any implementation of stdio.h which you are likely to encounter has include-guards (a feature from the 1990s—not seen in SunOS 4's 1994 headers) including <stdio.h> after <curses.h> would also be unlikely to change the behavior of your program (again, clutter being the only result).

Include-guards have been the preferred style for system headers since the 1990s.  I have a script (called Include) which I use for test-compiling headers which I wrote in 1998, to check that a given header includes the necessary headers (such as in this case) to provide all of the necessary typedefs and symbols used in the header file.

ContentLicense: CC BY-SA 4.0

Body:
I was studying up on ncurses.h because I am trying to learn a bit of design aspects for c, and stumbled across a statement saying that stdio.h is inside of ncurses

  #include <ncurses.h>        /*ncurses.h includes stdio.h*/

Is this true? If so, can someone explain to me why, and if that means I don't have to ever include it again?

Also, does this cause any issues because I am not exactly defining it in a regular sense

Body:
ncurses' curses.h includes <stdio.h> because a few of the (X/Open Curses) standard functions which curses.h declares use FILE.  The C standard refers to FILE as an "object type", which some might read literally as requiring a typedef.  However there have been implementations where FILE is a symbol defined with #define, e.g.,

#define   FILE    struct _iobuf

(quoting from more than one BSD: 4.3BSD, SunOS 4, Ultrix).  Without delving into its history, I'd assume the change to make it a typedef came from the AT&T code since it shows up in the SVr4 implementations.

For that reason (as well as it being the simplest way to guarantee that FILE is declared properly), curses.h will include stdio.h.

Now... there are a few other header files which you might encounter which require another header file to be included, to make them useful.  One longstanding example is for the stat function, i.e.,

#include <sys/types.h>
#include <sys/stat.h>

but in the relevant (system-specific) documentation, both headers are shown in the manual page summary.  The POSIX documentation for stat does not point that out, but uses it in the examples.   Some newer implementations include (or provide in some roundabout way) the definitions from <sys/types.h> needed in <sys/stat.h>, but in writing portable code, that has not been something to rely upon.

curses was never documented in that way, e.g., you're unlikely to find manual pages showing

#include <stdio.h>
#include <curses.h>

because the original 4BSD curses included <stdio.h>.  Interestingly enough, 4.2BSD curses header did not use any definition from stdio.h.  It also included sgtty.h (analogous to termios.h), but used those definitions in the header file.  Perhaps the original developer thought that including stdio.h was a good idea.  In any case, in later versions of curses, it did use FILE, and since the precedent of including stdio.h. from curses.h was well established, no one considered splitting things up as done with <sys/types.h> and <sys/stat.h>.

ncurses' documentation has mentioned the header files which curses.h includes, in a NOTES section:

The header file <curses.h>  automatically  includes  the  header  files
  <stdio.h> and <unctrl.h>.

That note dates back to ncurses 1.8.7 in 1994, making it rather unlikely that you will encounter a version of ncurses for which the statement is untrue.

X/Open Curses has something similar to say:

The inclusion of <curses.h> may make visible all symbols from the headers <stdio.h>, <term.h>, <termios.h> and <wchar.h>.

HPUX curses, for instance, includes <term.h> from <curses.h> to declare setupterm in curses.h, but ncurses (and Solaris curses) do not.  AIX curses includes <term.h> and <termios.h>.  Again, ncurses (and Solaris curses) do not.  X/Open Curses says "may make visible" because including a header file  does not necessarily make all symbols in it visible (there are ifdef's to consider).

However, these functions in any X/Open Curses (i.e., anything more current than 1990) use FILE, making <stdio.h> needed for <curses.h>:

getwin (SVr4)

newterm (SVr2)

putwin (SVr4)

Now... including <stdio.h> before <curses.h> probably will not make any difference (aside from adding clutter to your program).  It's possible (but unlikely) that there could be some symbol redefined in <curses.h> which alters the behavior of the standard features in <stdio.h>.  Since any implementation of stdio.h which you are likely to encounter has include-guards (a feature from the 1990s—not seen in SunOS 4's 1994 headers) including <stdio.h> after <curses.h> would also be unlikely to change the behavior of your program (again, clutter being the only result).

Include-guards have been the preferred style for system headers since the 1990s.  I have a script (called Include) which I use for test-compiling headers which I wrote in 1998, to check that a given header includes the necessary headers (such as in this case) to provide all of the necessary typedefs and symbols used in the header file.


问:
How to archive multiple isolated instances of a micro service app in kubernetes?
We developed an application which consist out of a few go/java services, a mongoDB and a reverse proxy which forwards REST-calls to the specific service. Each service runs in an own docker container.
The whole app is deployable with a single docker-compose file.

We successfully managed to deploy the app in a kubernetes cluster.

Now the "tricky" part: We want to deploy one isolated instance of the app for each customer. (remember one instance consists of approximately 10 containers)

In the past we reached this goal by deploying multiple instances of the docker-compose file.

What is the recommended way in Kubernetes to reach this?

Thank you very much.

答:
Applications can be separated via simple naming and labels or namespaces. Separation could go even further into restricting the nodes an instance may run on or even running separate clusters.

Network policies can be applied on top of deployment to improve network isolation. This would be needed to emulate the docker-compose "network bridge per instance" setup.

"Isolated" can mean a lot of things though as there are various layers where the term can be applied in various ways.

Naming

Many instances of a deployment can run intermingled on a cluster as long as the naming of each kubernetes resource doesn't clash. This includes the labels applied (and sometimes annotations) that are used to select or report on apps so you can uniquely identify a customers resources.

```<code>kubectl create -f deployment-customer1.yaml
kubectl create -f deployment-customer2.yaml
</code>```

This type of naming is easier to manage with a deployment mechanism like helm. Helm "charts" describe a release and are built with the base concept of a variable "release name", so yaml templates can rely on variables. The average helm release would be:

```<code>helm install -f customer1-values.yaml customer1-app me/my-app-chart
helm install -f customer2-values.yaml customer2-app me/my-app-chart
</code>```

Namespaces

A namespace is a logical grouping of resources in a cluster. By itself, a namespace only provides naming isolation but a lot of other k8s resources can then depend on a namespace to apply to:

Authorization/Role based access to k8s

Pod security policy

Resource quotas

A namespace per customer/instance may be useful, for example if you had a "premium" customer that get a bigger slice of resources quotas. It may also make labelling and selecting instances easier, which Network Policy will use.

Environments can be a good fit for a namespace, so a similar deployment can go to the dev/test/prod ns. If you are giving users access to manage or query Kubernetes resources themselves, namespaces make management much easier.

Managing namespaced resources might look like:

```<code>kubectl create ns customer1
kubectl create -f deployment.yaml -n customer1
kubectl create ns customer2
kubectl create -f deployment.yaml -n customer2
</code>```

Again, helm is equally applicable to namespaced deployments.

DNS is probably worth a mention too, containers will look up host names in their own namespace by default. In namespace customer1, looking up the host name service-name will resolve to service-name.customer1.svc.cluster.local

Similarly in the namespace customer2: A lookup for service-name is service-name.customer2.svc.cluster.local

Nodes

Customers could be pinned to a particular nodes (VM or physical) to provide security and/or resource isolation from other customers.

Clusters

Cluster separation can provide full security, resource and network isolation without relying on kubernetes to manage it.

Large apps can often end up using a complete cluster per "grouping". This has a huge overhead of management for each cluster but allow closer to complete independence between instances. Security can be a big driver for this, as you can provide a layer of isolation between clusters outside of the Kubernetes masters.

Network Policy

A network policy lets you restrict network access between Pods/Services via label selectors. Kubernetes will actively manage the firewall rules wherever the Pods are scheduled in the cluster. This would be required to provide similar network isolation to docker-compose creating a network per instance.

The cluster will need to use a network plugin (CNI) that supports network policies, like Calico.

Body:
Applications can be separated via simple naming and labels or namespaces. Separation could go even further into restricting the nodes an instance may run on or even running separate clusters.

Network policies can be applied on top of deployment to improve network isolation. This would be needed to emulate the docker-compose "network bridge per instance" setup.

"Isolated" can mean a lot of things though as there are various layers where the term can be applied in various ways.

Naming

Many instances of a deployment can run intermingled on a cluster as long as the naming of each kubernetes resource doesn't clash. This includes the labels applied (and sometimes annotations) that are used to select or report on apps so you can uniquely identify a customers resources.

kubectl create -f deployment-customer1.yaml
kubectl create -f deployment-customer2.yaml

This type of naming is easier to manage with a deployment mechanism like helm. Helm "charts" describe a release and are built with the base concept of a variable "release name", so yaml templates can rely on variables. The average helm release would be:

helm install -f customer1-values.yaml customer1-app me/my-app-chart
helm install -f customer2-values.yaml customer2-app me/my-app-chart

Namespaces

A namespace is a logical grouping of resources in a cluster. By itself, a namespace only provides naming isolation but a lot of other k8s resources can then depend on a namespace to apply to:

Authorization/Role based access to k8s

Pod security policy

Resource quotas

A namespace per customer/instance may be useful, for example if you had a "premium" customer that get a bigger slice of resources quotas. It may also make labelling and selecting instances easier, which Network Policy will use.

Environments can be a good fit for a namespace, so a similar deployment can go to the dev/test/prod ns. If you are giving users access to manage or query Kubernetes resources themselves, namespaces make management much easier.

Managing namespaced resources might look like:

kubectl create ns customer1
kubectl create -f deployment.yaml -n customer1
kubectl create ns customer2
kubectl create -f deployment.yaml -n customer2

Again, helm is equally applicable to namespaced deployments.

DNS is probably worth a mention too, containers will look up host names in their own namespace by default. In namespace customer1, looking up the host name service-name will resolve to service-name.customer1.svc.cluster.local

Similarly in the namespace customer2: A lookup for service-name is service-name.customer2.svc.cluster.local

Nodes

Customers could be pinned to a particular nodes (VM or physical) to provide security and/or resource isolation from other customers.

Clusters

Cluster separation can provide full security, resource and network isolation without relying on kubernetes to manage it.

Large apps can often end up using a complete cluster per "grouping". This has a huge overhead of management for each cluster but allow closer to complete independence between instances. Security can be a big driver for this, as you can provide a layer of isolation between clusters outside of the Kubernetes masters.

Network Policy

A network policy lets you restrict network access between Pods/Services via label selectors. Kubernetes will actively manage the firewall rules wherever the Pods are scheduled in the cluster. This would be required to provide similar network isolation to docker-compose creating a network per instance.

The cluster will need to use a network plugin (CNI) that supports network policies, like Calico.


问:
CORS header ‘Access-Control-Allow-Origin’ missing for json POST using API
Installed fruitcake/laravel-cors on Laravel 5.8

My testserver uses php artisan serve on 127.0.0.1:8000 using routes/api.php
client (nuxt) is running on 127.0.0.1:3000

I'm able to send data to the server using the POSTMAN tool

I've configured fruitcake/laravel-cors

```<code>protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];
</code>```

and config/cors.php

```<code><?php

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => [],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];
</code>```

Still getting:

Access to XMLHttpRequest at
  'http://127.0.0.1:8000/api/customerFeedbackStore' from origin
  'http://127.0.0.1:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

in browser.

答: 'paths' must not be empty. You should at least se it to [ '*' ], so it covers every request.</p>

Body:
Installed fruitcake/laravel-cors on Laravel 5.8

My testserver uses php artisan serve on 127.0.0.1:8000 using routes/api.php
client (nuxt) is running on 127.0.0.1:3000

I'm able to send data to the server using the POSTMAN tool

I've configured fruitcake/laravel-cors

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

and config/cors.php

<?php

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => [],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];

Still getting:

Access to XMLHttpRequest at
  'http://127.0.0.1:8000/api/customerFeedbackStore' from origin
  'http://127.0.0.1:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

in browser.


问:
How to fetch the complete statement using UNIX Commands
We are using Oracle Apps where we also develop programs using UNIX. In our Oracle Apps UNIX program, while running a program, we will pass parameters and the parameter values will be stored in $1 value. And this $1 will also contain other information like instance, what is program id, program ran user name and user id etc., as below

```<code>XX_VENDOR_ACH_HOST FCP_REQID=9946271 FCP_LOGIN="APPS/trn12fnd" FCP_USERID=127 FCP_USERNAME="USERNAME" FCP_PRINTER="noprint" FCP_SAVE_OUT=Y FCP_NUM_COPIES=0 "TEST Pay Batch 021120-c"
</code>```

here, TEST Pay Batch 021120-c is the only parameter value. Now, I need to fetch this parameter value. So, I wrote the command as below

echo $1 | cut -d" " -f9 | sed 's/"//g'

But, it is just printing the word TEST not the complete value. Can anyone please help me with the complete command to fetch TEST Pay Batch 021120-c

Regards,
Srivathsava

答:
Assuming;

The parameter value is enclosed with double-quotes

The parameter value is located at the end of $1

then how about;

```<code>echo "$1" | sed 's/.*"\([^"]\+\)"$/\1/'
</code>```

which outputs:

```<code>TEST Pay Batch 021120-c
</code>```

If my assumptions are incorrect and if the parameter value string has
some distinct characteristics (e.g. it starts with TEST Pay Batch),
please let me know. Then I'll tweak the regex to extract the parameter value.

Body:
We are using Oracle Apps where we also develop programs using UNIX. In our Oracle Apps UNIX program, while running a program, we will pass parameters and the parameter values will be stored in $1 value. And this $1 will also contain other information like instance, what is program id, program ran user name and user id etc., as below

XX_VENDOR_ACH_HOST FCP_REQID=9946271 FCP_LOGIN="APPS/trn12fnd" FCP_USERID=127 FCP_USERNAME="USERNAME" FCP_PRINTER="noprint" FCP_SAVE_OUT=Y FCP_NUM_COPIES=0 "TEST Pay Batch 021120-c"

here, TEST Pay Batch 021120-c is the only parameter value. Now, I need to fetch this parameter value. So, I wrote the command as below

echo $1 | cut -d" " -f9 | sed 's/"//g'

But, it is just printing the word TEST not the complete value. Can anyone please help me with the complete command to fetch TEST Pay Batch 021120-c

Regards,
Srivathsava

Body:
Assuming;

The parameter value is enclosed with double-quotes

The parameter value is located at the end of $1

then how about;

echo "$1" | sed 's/.*"\([^"]\+\)"$/\1/'

which outputs:

TEST Pay Batch 021120-c

If my assumptions are incorrect and if the parameter value string has
some distinct characteristics (e.g. it starts with TEST Pay Batch),
please let me know. Then I'll tweak the regex to extract the parameter value.


问:
oracle sql cursor update an email domain name using an email domain name
I want to give a domain name to change to a new domain name. the procedure will pass two string.
not using a Primary key but using the Email
execute procedure('gmail.com', 'hotmail.com');

all the emails with 'Gmail.com' in the database will change the new domain name with 'Hotmail.com'.
and here is my code.

I have an error with 'wrong number or type of arguments in call to PR_Q3'

```<code>create procedure PR_Q3
is P_NewEamil varchar2(50); P_OldEmail varchar2(50);
cursor E_info is select Email_Address from Broker where P_OldEmail = Email_Address
for update of Email_Address;
begin
open E_info;
fetch E_info into P_NewEamil;
while E_info%found loop
if(P_NewEamil like '%.com') then
update Broker set Email_Address = P_NewEamil where Email_Address= P_OldEmail;
else

 end if;
end loop;
close E_info;

 end PR_Q3;
</code>```

答:
Your procedure should look like this:

```<code>create procedure PR_Q3(p_oldemail in varchar2,
                       p_newemail in varchar2)
As
Begin

UPDATE BROKER
SET
    EMAIL_ADDRESS = REPLACE(EMAIL_ADDRESS, p_oldemail, p_newemail)
WHERE
    REGEXP_LIKE ( EMAIL_ADDRESS,'.*@'|| p_oldemail|| '$' );

Commit;

End;
/
</code>```

To call this procedure, you need to pass both the domain as following:

```<code>Begin
Pr_q3('gmail.com', 'hotmail.com');
End;
/
</code>```

Cheers!!

Body:
I want to give a domain name to change to a new domain name. the procedure will pass two string.
not using a Primary key but using the Email
execute procedure('gmail.com', 'hotmail.com');

all the emails with 'Gmail.com' in the database will change the new domain name with 'Hotmail.com'.
and here is my code.

I have an error with 'wrong number or type of arguments in call to PR_Q3'

create procedure PR_Q3
is P_NewEamil varchar2(50); P_OldEmail varchar2(50);
cursor E_info is select Email_Address from Broker where P_OldEmail = Email_Address
for update of Email_Address;
begin
open E_info;
fetch E_info into P_NewEamil;
while E_info%found loop
if(P_NewEamil like '%.com') then
update Broker set Email_Address = P_NewEamil where Email_Address= P_OldEmail;
else

 end if;
end loop;
close E_info;

 end PR_Q3;

Body:
Your procedure should look like this:

create procedure PR_Q3(p_oldemail in varchar2,
                       p_newemail in varchar2)
As
Begin

UPDATE BROKER
SET
    EMAIL_ADDRESS = REPLACE(EMAIL_ADDRESS, p_oldemail, p_newemail)
WHERE
    REGEXP_LIKE ( EMAIL_ADDRESS,'.*@'|| p_oldemail|| '$' );

Commit;

End;
/

To call this procedure, you need to pass both the domain as following:

Begin
Pr_q3('gmail.com', 'hotmail.com');
End;
/

Cheers!!


问:
CSS Card Flip Does Not Work On Apple Devices
I have a website where users can make flash cards and use them. Iv'e tested the cards on all devices and web browsers and apple devices seem to give me problems. The animation works and allows the card to flip, but the content on the back of the card disappears. I won't include it because it's long, but I also have a JS function that adds "flipped" to the class "gallery-cell". You will see this in my CSS.

    .gallery-cell.card {
      position: relative;

     -webkit-transition: 0.5s;
     -moz-transition: 0.6s;
     transition: transform .5s;

     -webkit-perspective: 1000;
     -moz-perspective: 1000;
     -o-perspective:1000;
     -ms-perspective: 1000;
     perspective: 1000;

     -ms-transform: perspective(1000px);
     -moz-transform: perspective(1000px);
     -moz-transform-style: preserve-3d;
     -ms-transform-style: preserve-3d;
     transform-style: preserve-3d;
     -webkit-transform-style: preserve-3d;
     word-break: break-word;
    }

    .card__face {
      position: absolute;
      height: 100%;
      width: 100%;
      padding: 25px;

      -webkit-backface-visibility: hidden;
      -moz-backface-visibility: hidden;
      -ms-backface-visibility: hidden;
      backface-visibility: hidden;

      display: flex;
      justify-content: center;
      text-align: center;
      cursor: pointer;
    }

    .card__face--back {
      -webkit-transform: rotateY(180deg);
      -moz-transform: rotateY(180deg);
      -o-transform: rotateY(180deg);
      -ms-transform: rotateY(180deg);
      transform: rotateY( 180deg );
    }

    .card__face--front {
        -moz-transform-style: preserve-3d;
        -ms-transform-style: preserve-3d;
        -webkit-transform-style: preserve-3d;
        transform-style: preserve-3d;

        -webkit-perspective: inherit;
        -moz-perspective: inherit;
        -o-perspective: inherit;
        -ms-perspective: inherit;
        perspective: inherit;

        z-index: 2;
        background-color: #fff;
    }

    .flipped {
      -webkit-transform: rotateY(180deg);
      -moz-transform: rotateY(180deg);
      -o-transform: rotateY(180deg);
      -ms-transform: rotateY(180deg);
       transform: rotateY(180deg);
    }

    .card_contents {
        overflow-y: auto;
        margin: 0;
        display: flex;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='gallery-cell card flippable'>
     <div class='card__face card__face--front'>
   <div class='card_contents'>
    <h3>
     $question
    </h3>
   </div>
     </div>
     <div class='card__face card__face--back'>
   <div class='card_contents'>
    <h3>
     $answer
    </h3>
   </div>
     </div>
    </div></code>```

答:
The reason why I reworked the CSS and HTML is b/c once adding your code to JSFiddle, it was immediately not displaying correctly.

First issue is that you need another wrapper element to hold the containers (card__face). Also perspective cannot be inherited. Unfortunately the animation would not work unless a height was supplied on the main wrapper element. min-height did not work either.

You could run some JS and determine the height on load. (see CSS3 Flip Card with Automatic Height)

```<code><div class="gallery-cell card flippable">
  <div class="wrapper">
    <div class='card__face card__face--front'>
      <div class='card_contents'>
        <h3>
          $question
        </h3>
      </div>
    </div>
    <div class='card__face card__face--back'>
      <div class='card_contents'>
        <h3>
          $answer
        </h3>
      </div>
    </div>
  </div>

</div>
</code>```

```<code>.gallery-cell {
  background-color: transparent;
  width: 100%;
  height: 100px;
  perspective: 1000px;
}

.wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.5s;
  transform-style: preserve-3d;
}

.gallery-cell:hover .wrapper,
.gallery-cell.flipped .wrapper {
  transform: rotateY(180deg);
}

.card__face {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.card__face--front {
  background-color: red;
}

.card__face--back {
  background-color: #000;
  color: white;
  transform: rotateY(180deg);
}

.card_contents {
    overflow-y: auto;
    margin: 0;
    display: flex;
}
</code>```

I added the hover in case you wanted to test it - here's https://jsfiddle.net/rzqkpva9/

Body:
I have a website where users can make flash cards and use them. Iv'e tested the cards on all devices and web browsers and apple devices seem to give me problems. The animation works and allows the card to flip, but the content on the back of the card disappears. I won't include it because it's long, but I also have a JS function that adds "flipped" to the class "gallery-cell". You will see this in my CSS.

    .gallery-cell.card {
      position: relative;

     -webkit-transition: 0.5s;
     -moz-transition: 0.6s;
     transition: transform .5s;

     -webkit-perspective: 1000;
     -moz-perspective: 1000;
     -o-perspective:1000;
     -ms-perspective: 1000;
     perspective: 1000;

     -ms-transform: perspective(1000px);
     -moz-transform: perspective(1000px);
     -moz-transform-style: preserve-3d;
     -ms-transform-style: preserve-3d;
     transform-style: preserve-3d;
     -webkit-transform-style: preserve-3d;
     word-break: break-word;
    }

    .card__face {
      position: absolute;
      height: 100%;
      width: 100%;
      padding: 25px;

      -webkit-backface-visibility: hidden;
      -moz-backface-visibility: hidden;
      -ms-backface-visibility: hidden;
      backface-visibility: hidden;

      display: flex;
      justify-content: center;
      text-align: center;
      cursor: pointer;
    }

    .card__face--back {
      -webkit-transform: rotateY(180deg);
      -moz-transform: rotateY(180deg);
      -o-transform: rotateY(180deg);
      -ms-transform: rotateY(180deg);
      transform: rotateY( 180deg );
    }

    .card__face--front {
        -moz-transform-style: preserve-3d;
        -ms-transform-style: preserve-3d;
        -webkit-transform-style: preserve-3d;
        transform-style: preserve-3d;

        -webkit-perspective: inherit;
        -moz-perspective: inherit;
        -o-perspective: inherit;
        -ms-perspective: inherit;
        perspective: inherit;

        z-index: 2;
        background-color: #fff;
    }

    .flipped {
      -webkit-transform: rotateY(180deg);
      -moz-transform: rotateY(180deg);
      -o-transform: rotateY(180deg);
      -ms-transform: rotateY(180deg);
       transform: rotateY(180deg);
    }

    .card_contents {
        overflow-y: auto;
        margin: 0;
        display: flex;
    }

     $question

     $answer

Body:
The reason why I reworked the CSS and HTML is b/c once adding your code to JSFiddle, it was immediately not displaying correctly.

First issue is that you need another wrapper element to hold the containers (card__face). Also perspective cannot be inherited. Unfortunately the animation would not work unless a height was supplied on the main wrapper element. min-height did not work either.

You could run some JS and determine the height on load. (see CSS3 Flip Card with Automatic Height)

<div class="gallery-cell card flippable">
  <div class="wrapper">
    <div class='card__face card__face--front'>
      <div class='card_contents'>
        <h3>
          $question
        </h3>
      </div>
    </div>
    <div class='card__face card__face--back'>
      <div class='card_contents'>
        <h3>
          $answer
        </h3>
      </div>
    </div>
  </div>

</div>

.gallery-cell {
  background-color: transparent;
  width: 100%;
  height: 100px;
  perspective: 1000px;
}

.wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.5s;
  transform-style: preserve-3d;
}

.gallery-cell:hover .wrapper,
.gallery-cell.flipped .wrapper {
  transform: rotateY(180deg);
}

.card__face {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.card__face--front {
  background-color: red;
}

.card__face--back {
  background-color: #000;
  color: white;
  transform: rotateY(180deg);
}

.card_contents {
    overflow-y: auto;
    margin: 0;
    display: flex;
}

I added the hover in case you wanted to test it - here's https://jsfiddle.net/rzqkpva9/


问:
Hibernate @SequenceGenerator not global
I have two entity classes which use generated values

```<code>@Entity
@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
public class Ent1 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}

@Entity
public class Ent2 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}
</code>```

The problem is that if don't put the line

```<code>@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
</code>```

on both entities I get an error:

```<code>Caused by: org.hibernate.AnnotationException: Unknown Id.generator: idgen
</code>```

But the JPA spec says that the scope of the @SequenceGenerator is 'global' and can be reused across entities.

What am I missing?

答:
copy

```<code>@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
</code>```

to Ent2 should work,

you can refer https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/seq-generator.html for more details

ContentLicense: CC BY-SA 3.0

Title: Hibernate @SequenceGenerator not global

Body:
I have two entity classes which use generated values

@Entity
@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
public class Ent1 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}

@Entity
public class Ent2 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}

The problem is that if don't put the line

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")

on both entities I get an error:

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: idgen

But the JPA spec says that the scope of the @SequenceGenerator is 'global' and can be reused across entities.

What am I missing?

Body:
copy

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")

to Ent2 should work,

you can refer https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/seq-generator.html for more details


问:
Excel filter out name
I have an excel row that i need to filter down. I want to filter out just the first name and last name, see example below. I cant seem to find a vlookup for this scenario.

Before:

After:

答:
To extract the first name, use:

```<code>=LEFT(A1,FIND(" ",A1)-1)
</code>```

And for the second name:

```<code>=MID(A1,FIND(" ",A1)+1,FIND(" ",A1,FIND(" ",A1)+1)-FIND(" ",A1))
</code>```

The breakdown:

=LEFT(A1,FIND(" ",A1)-1)

We use FIND to locate the first space (" ") in the data (A1).

Using LEFT, we extract everything from the leftmost character up to the location of the first space and -1 to account for the space character.

=MID(A1,FIND(" ",A1)+1,FIND(" ",A1,FIND(" ",A1)+1)-FIND(" ",A1))

We use FIND to locate the second space (" ") in the data (A1), adding the formula for locating the first space as a parameter to the next FIND (FIND(" ",A1)+1). Note that it is +1 now because we want to look past the location of space character.

We now have the location of the second space character. We subtract the second space character location from the first space character location which gives us the total length of the second word. (FIND(" ",A1,FIND(" ",A1)+1)-FIND(" ",A1))

Similar to LEFT, we use MID to extract data from the middle of the data string. We are simply saying MIDDLE(data, where to start, length of desired data).

Title: Excel filter out name

Body:
To extract the first name, use:

=LEFT(A1,FIND(" ",A1)-1)

And for the second name:

=MID(A1,FIND(" ",A1)+1,FIND(" ",A1,FIND(" ",A1)+1)-FIND(" ",A1))

The breakdown:

=LEFT(A1,FIND(" ",A1)-1)

We use FIND to locate the first space (" ") in the data (A1).

Using LEFT, we extract everything from the leftmost character up to the location of the first space and -1 to account for the space character.

=MID(A1,FIND(" ",A1)+1,FIND(" ",A1,FIND(" ",A1)+1)-FIND(" ",A1))

We use FIND to locate the second space (" ") in the data (A1), adding the formula for locating the first space as a parameter to the next FIND (FIND(" ",A1)+1). Note that it is +1 now because we want to look past the location of space character.

We now have the location of the second space character. We subtract the second space character location from the first space character location which gives us the total length of the second word. (FIND(" ",A1,FIND(" ",A1)+1)-FIND(" ",A1))

Similar to LEFT, we use MID to extract data from the middle of the data string. We are simply saying MIDDLE(data, where to start, length of desired data).


问:
OSError: [Errno 22] Invalid argument, opening a file in python
I want to open a file and although I have given its address correctly, an error appears when I run the program.

This is my code:

```<code>file1 = open('C:\pronouns.txt', 'r')
</code>```

This is the error:

```<code>OSError: [Errno 22] Invalid argument: '\u202a\u202aC:\\pronouns.txt\u202a'
</code>```

答:
```<code>file1 = open('C:\pronouns.txt', 'r').
</code>```

rename the first character your file with capital

```<code>file1 = open('C:\Pronouns.txt', 'r')
</code>```

Body:
I want to open a file and although I have given its address correctly, an error appears when I run the program.

This is my code:

file1 = open('C:\pronouns.txt', 'r')

This is the error:

OSError: [Errno 22] Invalid argument: '\u202a\u202aC:\\pronouns.txt\u202a'

Body:
file1 = open('C:\pronouns.txt', 'r').

rename the first character your file with capital

file1 = open('C:\Pronouns.txt', 'r')


问:
How to create Angular 9 project with IVY?
How to create Angular 9 project with IVY?

I tried the following:

```<code>ng new sample9prjivy --enable-ivy
</code>```

My environment:

Angular CLI: 9.0.2

Node: 12.16.0

OS: win32 x64

Angular:
...
Ivy Workspace:

Package and Version

@angular-devkit/architect    0.900.2

@angular-devkit/core         9.0.2

@angular-devkit/schematics   9.0.2

@schematics/angular          9.0.2

@schematics/update           0.900.2

rxjs                         6.5.3

C:\src\Angular\pilot\A9>ng new sample9prjivy --enable-ivy

Unknown option: '--enable-ivy'

What I missed?

答:
As an earlier poster tried to explain, there's no such "ng new" flag as --enable-ivy.

As  andrewjames explained above, the "ivy" tag is incorrect.  You want "angular-ivy".  I fixed it for you.

If you want to enable Ivy for older Angular builds, read this thread:  How do I enable Ivy for Angular 8 or 9?.  You'll need to edit tsconfig.json and angular.json.

It looks like Ivy is now the default for Angular 9:

https://angular.io/guide/ivy

Ivy is the code name for Angular's next-generation compilation and
  rendering
  pipeline.
  With the version 9 release of Angular, the new compiler and runtime
  instructions are used by default instead of the older compiler and
  runtime, known as View Engine.

As the documentation discusses, there IS a flag for enableIvy ... but it's set in tsconfig.app.json.   It is NOT a command line option for "ng new".

Update:

The answer to the OP's original question: you don't have to "create an Angular 9 project with Ivy": in Angular 9, Ivy should be enabled by default.

To answer the follow-on question about NG6002: look here (already cited below):

https://github.com/angular/angular/issues/35399

https://github.com/angular/angular/pull/35191

One final suggestion: it couldn't hurt to:

Update Angular: ng update @angular/cli @angular/core

Create a brand new project and copy the old source into the new project

Another Update

Original problem: ng new sample9prjivy --enable-ivy =>

Unknown option: '--enable-ivy'

Cause: --enable-ivy simply isn't a legal "ng" option with Angular 9.  Don't do it!

Next problem: I always got more error NG6002

This is a well-known issue upgrading existing projects to Angular 9.  Look here and here.  The basic issue is that "upgrading" the project can result in "inconsistencies".  Both links suggest workarounds; I've also suggested some workarounds.  I don't know if you've tried any of them yet :(

CURRENT SUGGESTION:

Since you don't seem to be making much progress, I'd suggest the following:

a) UNINSTALL Angular: get a "clean version":

```<code>npm uninstall -g @angular/cli
npm cache clean
npm cache verify
npm install -g @angular/cli
</code>```

b) Confirm your "clean install" of Angular 9:

```<code>ng --version
...
Angular CLI: 9.0.3
Node: 10.15.1
OS: win32 x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.900.3
@angular-devkit/core         9.0.3
@angular-devkit/schematics   9.0.3
@schematics/angular          9.0.3
@schematics/update           0.900.3
rxjs                         6.5.3
</code>```

c) Create a brand new project with your "known good" Angular install.

Do NOT change ANY configuration!  Do NOT try to explicitly "enable Ivy"!

d) Copy over your old source code (ONLY the project source code!) to your new project.

e) Verify that "everything works".

f) Post back what you find.

Body:
How to create Angular 9 project with IVY?

I tried the following:

ng new sample9prjivy --enable-ivy

My environment:

Angular CLI: 9.0.2

Node: 12.16.0

OS: win32 x64

Angular:
...
Ivy Workspace:

Package and Version

@angular-devkit/architect    0.900.2

@angular-devkit/core         9.0.2

@angular-devkit/schematics   9.0.2

@schematics/angular          9.0.2

@schematics/update           0.900.2

rxjs                         6.5.3

C:\src\Angular\pilot\A9>ng new sample9prjivy --enable-ivy

Unknown option: '--enable-ivy'

What I missed?

Body:
As an earlier poster tried to explain, there's no such "ng new" flag as --enable-ivy.

As  andrewjames explained above, the "ivy" tag is incorrect.  You want "angular-ivy".  I fixed it for you.

If you want to enable Ivy for older Angular builds, read this thread:  How do I enable Ivy for Angular 8 or 9?.  You'll need to edit tsconfig.json and angular.json.

It looks like Ivy is now the default for Angular 9:

https://angular.io/guide/ivy

Ivy is the code name for Angular's next-generation compilation and
  rendering
  pipeline.
  With the version 9 release of Angular, the new compiler and runtime
  instructions are used by default instead of the older compiler and
  runtime, known as View Engine.

As the documentation discusses, there IS a flag for enableIvy ... but it's set in tsconfig.app.json.   It is NOT a command line option for "ng new".

Update:

The answer to the OP's original question: you don't have to "create an Angular 9 project with Ivy": in Angular 9, Ivy should be enabled by default.

To answer the follow-on question about NG6002: look here (already cited below):

https://github.com/angular/angular/issues/35399

https://github.com/angular/angular/pull/35191

One final suggestion: it couldn't hurt to:

Update Angular: ng update @angular/cli @angular/core

Create a brand new project and copy the old source into the new project

Another Update

Original problem: ng new sample9prjivy --enable-ivy =>

Unknown option: '--enable-ivy'

Cause: --enable-ivy simply isn't a legal "ng" option with Angular 9.  Don't do it!

Next problem: I always got more error NG6002

This is a well-known issue upgrading existing projects to Angular 9.  Look here and here.  The basic issue is that "upgrading" the project can result in "inconsistencies".  Both links suggest workarounds; I've also suggested some workarounds.  I don't know if you've tried any of them yet :(

CURRENT SUGGESTION:

Since you don't seem to be making much progress, I'd suggest the following:

a) UNINSTALL Angular: get a "clean version":

npm uninstall -g @angular/cli
npm cache clean
npm cache verify
npm install -g @angular/cli

b) Confirm your "clean install" of Angular 9:

ng --version
...
Angular CLI: 9.0.3
Node: 10.15.1
OS: win32 x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.900.3
@angular-devkit/core         9.0.3
@angular-devkit/schematics   9.0.3
@schematics/angular          9.0.3
@schematics/update           0.900.3
rxjs                         6.5.3

c) Create a brand new project with your "known good" Angular install.

Do NOT change ANY configuration!  Do NOT try to explicitly "enable Ivy"!

d) Copy over your old source code (ONLY the project source code!) to your new project.

e) Verify that "everything works".

f) Post back what you find.


问:
Add git to existing project on server
I know maybe this question is answered somewhere but I didn't find a solution for it.  I have a project that is already in a live server  and I want to add a .git to be able to pull/push from my local machine.

I was thinking that I can do on the server :
git init
git remote add origin git@project.git
git add .
git commit -m "Initial commit"

But it seems not to be the right way so I tried  to do a git init --bare project.git and clone from my local, but the directory is empty.

Can someone tell me how I can do add git in this case.
Thank You.

答:
I think I know what you want to do and I have done the same thing before.  What I wanted was something like this, where both folders are Git repos

```<code>  laptop              server
~/website   <=>   /var/www/html
  .git/             .git/
  index.html        index.html
</code>```

However, that is not possible because from my laptop I can't push to the repo in /var/www/html because that is not a bare repo.  I also can't make it a bare repo because a bare repo doesn't have a worktree (which I need because that's the files that display my website).

So instead I needed a middle man:

```<code>  laptop            server              server
~/website   <=>   website.git   =>   /var/www/html
  .git/                                .git/
  index.html                           index.html
</code>```

where website.git is a bare repo.  Then I just add a post receive hook in the file website.git/hooks/post-receive that cds to /var/www/html and pulls from the bare repo that's on the same hard drive.  Here is my hook

#!/bin/bash

# unset environment set by git
unset $(git rev-parse --local-env-vars)

# go to website and assemble
cd /var/www/html
git fetch origin
git reset --hard origin/master

# Whatever other instruction you need to build the website
# ...
```

Title: Add git to existing project on server

Body:
I think I know what you want to do and I have done the same thing before.  What I wanted was something like this, where both folders are Git repos

  laptop              server
~/website   <=>   /var/www/html
  .git/             .git/
  index.html        index.html

However, that is not possible because from my laptop I can't push to the repo in /var/www/html because that is not a bare repo.  I also can't make it a bare repo because a bare repo doesn't have a worktree (which I need because that's the files that display my website).

So instead I needed a middle man:

  laptop            server              server
~/website   <=>   website.git   =>   /var/www/html
  .git/                                .git/
  index.html                           index.html

where website.git is a bare repo.  Then I just add a post receive hook in the file website.git/hooks/post-receive that cds to /var/www/html and pulls from the bare repo that's on the same hard drive.  Here is my hook

#!/bin/bash

# unset environment set by git
unset $(git rev-parse --local-env-vars)

# go to website and assemble
cd /var/www/html
git fetch origin
git reset --hard origin/master

# Whatever other instruction you need to build the website
# ...


问:
MongoDB database restoration takes too much time
I encountered with the following issue. I was tasked to restore Mongo DB from a backup and I am using mongorestore.exe (on Windows OS) for it. Restoration process takes about 1,5h, a backup file size is about 25G (contains 25M documents).

I tried to restore both on an AWS Document DB cluster (instance type: db.r5.large) and on locally installed MongoDB (EC2-instance, r5n.large). I got almost the same time of the process (about 1.5h)

My question: Is it reasonable time for this operation and how can I optimize/reduce time that needs for this?

All advice is very appreciated.

答: Agree with Ayoub@, parallelizing with --numParallelCollections has helped many folks speed up the restore process. Also, you can additionally speed up the restore by scaling up the Amazon DocumentDB instance to a larger size for the duration of the restore and scale it back down to an r5.large when the restore is complete. Amazon DocumentDB charges by the second for instance costs to help minimize costs for these scenarios.</p>


问:
Allow kubernetes storageclass resturl HTTPS with self-signed certificate
I'm currently trying to setup GlusterFS integration for a Kubernetes cluster. Volume provisioning is done with Heketi.

GlusterFS-cluster has a pool of 3 VMs
1st node has Heketi server and client configured. Heketi API is secured with a self-signed certificate OpenSSL and can be accessed.

e.g. curl https://heketinodeip:8080/hello -k
returns the expected response.

StorageClass definition sets the "resturl" to Heketi API https://heketinodeip:8080

When storageclass was created successfully and I try to create a PVC, this fails:

"x509: certificate signed by unknown authority"

This is expected, as ususally one has to allow this insecure HTTPS-connection or explicitly import the issuer CA (e.g. a file simply containing the pem-String)

But: How is this done for Kubernetes? How do I allow this insecure connection to Heketi from Kubernetes, allowing insecure self-signed cert HTTPS or where/how do I import a CA?

It is not an DNS/IP problem, this was resolved with correct subjectAltName settings.

(seems that everybody is using Heketi, and it seems to be still a standard usecase for GlusterFS integration, but always without SSL, if connected to Kubernetes)

Thank you!

答:
To skip verification of server cert, caller just need specify InsecureSkipVerify: true. Refer this github issue for more information (https://github.com/heketi/heketi/issues/1467)

In this page, they have specified a way to use self signed certificate. Not explained thoroughly but still can be useful (https://github.com/gluster/gluster-kubernetes/blob/master/docs/design/tls-security.md#self-signed-keys).


问:
Display Array List From Left To Right
I am trying to display an array list from left to right with a div scroll. But it become top to bottom. How should I do to solve it? This my demo code as you reference.

HTML

```<code><div>
  <h2 class="ylet-primary-500 alignleft">Sessions</h2>
</div>
<div style="clear: both;"></div>

<div *ngFor="let batch of batches">
  <div class="box">
    <div>
      <h3 class="classes">
        {{batch.month}}
        <span class="chips"> </span>
      </h3>
    </div>
    <div style="clear: both;">
      <p class="timings">
        <mat-icon matPrefix>access_time</mat-icon><span>{{batch.time}}</span>
        <span class="slots"> <mat-icon>list_alt</mat-icon>{{batch.slots}}</span>
      </p>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.box {
  border: 1px solid #ccc;
  padding: 4px;
  width: 70%;
  direction: rtl;
  display: inline-block;
}
</code>```

答:
Try to wrap loop div container with div container and add css flex style.

```<code><div class="container">
<div *ngFor="let batch of batches">
  <div class="box">
    <div>
      <h3 class="classes">
        {{batch.month}}
        <span class="chips"> </span>
      </h3>
    </div>
    <div style="clear: both;">
      <p class="timings">
        <mat-icon matPrefix>access_time</mat-icon><span>{{batch.time}}</span>
        <span class="slots"> <mat-icon>list_alt</mat-icon>{{batch.slots}}</span>
      </p>
    </div>
  </div>
</div>
</code>```

```<code>.container {
    display: flex;
    flex-wrap: wrap;
}
</code>```

Title: Display Array List From Left To Right

Body:
I am trying to display an array list from left to right with a div scroll. But it become top to bottom. How should I do to solve it? This my demo code as you reference.

HTML

Sessions

        {{batch.month}}

        <mat-icon matPrefix>access_time</mat-icon>{{batch.time}}
         <mat-icon>list_alt</mat-icon>{{batch.slots}}

CSS

.box {
  border: 1px solid #ccc;
  padding: 4px;
  width: 70%;
  direction: rtl;
  display: inline-block;
}

Body:
Try to wrap loop div container with div container and add css flex style.

<div class="container">
<div *ngFor="let batch of batches">
  <div class="box">
    <div>
      <h3 class="classes">
        {{batch.month}}
        <span class="chips"> </span>
      </h3>
    </div>
    <div style="clear: both;">
      <p class="timings">
        <mat-icon matPrefix>access_time</mat-icon><span>{{batch.time}}</span>
        <span class="slots"> <mat-icon>list_alt</mat-icon>{{batch.slots}}</span>
      </p>
    </div>
  </div>
</div>

.container {
    display: flex;
    flex-wrap: wrap;
}


问:
React form submission logic with lifted state and controlled dependence
I've dug myself into a deep rabbit hole with this component in an attempt to use React hooks.

The Parent component handles a dictionary state which is eventually distributed to multiple components.

My problem child component WordInput has a form with a single input. When submitting the form the component is fetching the word's definition from an API and passing on both the word and the definition to the parent which then sets the state in the form of dictionary. So far, so good IF it's the first word in dictionary. The part I'm having trouble with is to submit any subsequent words/definitions.

When the user submits a subsequent word, I want the component to check whether the word already exists in the dictionary that is passed to the child. If it doesn't exist, add it to the dictionary via the submit function.

I think the problem is that I'm trying to do too much with useEffect
I useEffect to:
  - set loading
  - check and process the dictionary for existing words
  - check that definition and word aren't empty and submit both to parent/dictionary
  - fetch a definition from an API

In the unprocessed code, I have multiple console.groups to help me keep track of what is happening. The more I add to the component, the more Subgroups and subgroups of subgroups accumulate. Clearly, the approach I'm taking isn't very dry and causes too many re-renders of the component/useEffect functions. For conciseness, I have taken out the console.log entries.

The imported fetchWordDefinition merely processes the fetched data and arranges it correctly into an array.

I don't know how to keep this dry and effective, and any help is appreciated with this rather simple task. My hunch is to keep all the logic to submit the word/definition in the submit handler, and only use useEffect to validate the data prior to that.

```<code>import React, { useState, useEffect } from "react";
import fetchWordDefinition from "./lib/utils";

const WordInput = ({ onSubmit, dictionary }) => {
    const [definition, setDefinition] = useState([]);
    const [cause, setCause] = useState({ function: "" });
    const [error, setError] = useState({});
    const [loading, setLoading] = useState(false);
    const [word, setWord] = useState("");
    const [wordExistsInDB, setWordExistsInDB] = useState(false);

    useEffect(() => {
        const dictionaryEmpty = dictionary.length === 0 ? true : false;

        if (dictionaryEmpty) {
            return;
        } else {
            for (let i = 0; i < dictionary.length; i += 1) {
                if (dictionary[i].word === word) {
                    setWordExistsInDB(true);
                    setError({ bool: true, msg: "Word already exists in DB" });
                    break;
                } else {
                    setWordExistsInDB(false);
                    setError({ bool: false, msg: "" });
                }
            }
        }
    }, [dictionary, word]);

    useEffect(() => {
        const definitionNotEmpty = definition.length !== 0 ? true : false;
        const wordNotEmpty = word !== "" ? true : false;

        if (wordNotEmpty && definitionNotEmpty && !wordExistsInDB) {
            onSubmit(word, definition);
            setWord("");
            setDefinition([]);
        }
    }, [definition, word, onSubmit, wordExistsInDB]);

    useEffect(() => {
        if (cause.function === "fetch") {
            async function fetchFunction() {
                const fetch = await fetchWordDefinition(word);
                return fetch;
            }

            fetchFunction().then(definitionArray => {
                setDefinition(definitionArray);
                setCause({ function: "" });
            });
        }
    }, [cause, word]);

    const handleSubmit = async e => {
        e.preventDefault();

        setLoading(true);
        setCause({ function: "fetch" });
    };

    return (
        <form onSubmit={handleSubmit}>
            {error.bool ? <span>{error.msg}</span> : null}
            <input
                name='word'
                placeholder='Enter Word'
                type='text'
                value={word}
                onChange={({ target: { value } }) => setWord(value)}
            />
            <input type='submit' />
        </form>
    );
};

export default WordInput;
</code>```

答:
I think you're missing out on some clarity and what useEffect is for

A functional component gets re-ran everytime either a prop or a state changes. useEffect runs when the component gets created, and we use it for things like doing a first-time fetch, or subscribing to an event handler. The second argument (array of variables) is used so that, if we have for example a blog post with with comments etc, we don't re-fetch everything unless the ID changes (meaning it's a new blog post)

Looking at your code, we have this flow:

User inputs something and hits Submit

Check if the word exists in a dictionary

a. If it exists, display an error message

b. If it doesn't exist, fetch from an API and call onSubmit

So really the only state we have here is the word. You can just compute an error based on if the word is in the dictionary, and the API call is done in a callback (useCallback). You have a lot of extra state that doesn't really matter in a state-way

A simplified version would look like this

```<code>const WordInput = ({ onSubmit, dictionary }) => {
  const [word, setWord] = useState("")
  const [loading, setLoading] = useState(false)

  // `find` will find the first entry in array that matches
  const wordExists = !!dictionary.find(entry => entry.word === word)

  // Ternary operator,
  const error = (wordExists) ? "Word already exists in DB" : null

  // When user hits submit
  const handleSubmit = useCallback(() => {
    if (wordExists || !word.length) return;

    setLoading(true)
    fetchFunction()
      .then(definitionArray => {
        onSubmit(word, definitionArray)
      })
  }, [])

  return (
      <form onSubmit={handleSubmit}>
          {error && <span>{error}</span>}

          <input
              name='word'
              placeholder='Enter Word'
              type='text'
              value={word}
              onChange={({ target: { value } }) => setWord(value)}
          />
          <input type='submit' onclick={handleSubmit} disabled={wordExists}/>
      </form>
  );
};
</code>```

Body:
I've dug myself into a deep rabbit hole with this component in an attempt to use React hooks.

The Parent component handles a dictionary state which is eventually distributed to multiple components.

My problem child component WordInput has a form with a single input. When submitting the form the component is fetching the word's definition from an API and passing on both the word and the definition to the parent which then sets the state in the form of dictionary. So far, so good IF it's the first word in dictionary. The part I'm having trouble with is to submit any subsequent words/definitions.

When the user submits a subsequent word, I want the component to check whether the word already exists in the dictionary that is passed to the child. If it doesn't exist, add it to the dictionary via the submit function.

I think the problem is that I'm trying to do too much with useEffect
I useEffect to:
  - set loading
  - check and process the dictionary for existing words
  - check that definition and word aren't empty and submit both to parent/dictionary
  - fetch a definition from an API

In the unprocessed code, I have multiple console.groups to help me keep track of what is happening. The more I add to the component, the more Subgroups and subgroups of subgroups accumulate. Clearly, the approach I'm taking isn't very dry and causes too many re-renders of the component/useEffect functions. For conciseness, I have taken out the console.log entries.

The imported fetchWordDefinition merely processes the fetched data and arranges it correctly into an array.

I don't know how to keep this dry and effective, and any help is appreciated with this rather simple task. My hunch is to keep all the logic to submit the word/definition in the submit handler, and only use useEffect to validate the data prior to that.

import React, { useState, useEffect } from "react";
import fetchWordDefinition from "./lib/utils";

const WordInput = ({ onSubmit, dictionary }) => {
    const [definition, setDefinition] = useState([]);
    const [cause, setCause] = useState({ function: "" });
    const [error, setError] = useState({});
    const [loading, setLoading] = useState(false);
    const [word, setWord] = useState("");
    const [wordExistsInDB, setWordExistsInDB] = useState(false);

    useEffect(() => {
        const dictionaryEmpty = dictionary.length === 0 ? true : false;

        if (dictionaryEmpty) {
            return;
        } else {
            for (let i = 0; i < dictionary.length; i += 1) {
                if (dictionary[i].word === word) {
                    setWordExistsInDB(true);
                    setError({ bool: true, msg: "Word already exists in DB" });
                    break;
                } else {
                    setWordExistsInDB(false);
                    setError({ bool: false, msg: "" });
                }
            }
        }
    }, [dictionary, word]);

    useEffect(() => {
        const definitionNotEmpty = definition.length !== 0 ? true : false;
        const wordNotEmpty = word !== "" ? true : false;

        if (wordNotEmpty && definitionNotEmpty && !wordExistsInDB) {
            onSubmit(word, definition);
            setWord("");
            setDefinition([]);
        }
    }, [definition, word, onSubmit, wordExistsInDB]);

    useEffect(() => {
        if (cause.function === "fetch") {
            async function fetchFunction() {
                const fetch = await fetchWordDefinition(word);
                return fetch;
            }

            fetchFunction().then(definitionArray => {
                setDefinition(definitionArray);
                setCause({ function: "" });
            });
        }
    }, [cause, word]);

    const handleSubmit = async e => {
        e.preventDefault();

        setLoading(true);
        setCause({ function: "fetch" });
    };

    return (
        <form onSubmit={handleSubmit}>
            {error.bool ? {error.msg} : null}
            <input
                name='word'
                placeholder='Enter Word'
                type='text'
                value={word}
                onChange={({ target: { value } }) => setWord(value)}
            />
            <input type='submit' />
        </form>
    );
};

export default WordInput;

Body:
I think you're missing out on some clarity and what useEffect is for

A functional component gets re-ran everytime either a prop or a state changes. useEffect runs when the component gets created, and we use it for things like doing a first-time fetch, or subscribing to an event handler. The second argument (array of variables) is used so that, if we have for example a blog post with with comments etc, we don't re-fetch everything unless the ID changes (meaning it's a new blog post)

Looking at your code, we have this flow:

User inputs something and hits Submit

Check if the word exists in a dictionary

a. If it exists, display an error message

b. If it doesn't exist, fetch from an API and call onSubmit

So really the only state we have here is the word. You can just compute an error based on if the word is in the dictionary, and the API call is done in a callback (useCallback). You have a lot of extra state that doesn't really matter in a state-way

A simplified version would look like this

const WordInput = ({ onSubmit, dictionary }) => {
  const [word, setWord] = useState("")
  const [loading, setLoading] = useState(false)

  // `find` will find the first entry in array that matches
  const wordExists = !!dictionary.find(entry => entry.word === word)

  // Ternary operator,
  const error = (wordExists) ? "Word already exists in DB" : null

  // When user hits submit
  const handleSubmit = useCallback(() => {
    if (wordExists || !word.length) return;

    setLoading(true)
    fetchFunction()
      .then(definitionArray => {
        onSubmit(word, definitionArray)
      })
  }, [])

  return (
      <form onSubmit={handleSubmit}>
          {error && <span>{error}</span>}

          <input
              name='word'
              placeholder='Enter Word'
              type='text'
              value={word}
              onChange={({ target: { value } }) => setWord(value)}
          />
          <input type='submit' onclick={handleSubmit} disabled={wordExists}/>
      </form>
  );
};


问:
Func syntax for async call
I try to create an AsyncCommand with a parameter.

I used this method but it's not working.

```<code> public static AsyncCommand<T> Create(Func<System.Threading.Tasks.Task<T>> func)
    {

        return new AsyncCommand<T>(new Command<T>(async (x) =>  await func(x)));
    }
</code>```

And when I call it with my viewmodel:

```<code> public ICommand OnRemoveTagCommand = AsyncCommand<ResultElementRatingDto>.Create(RemoveTag);

 private async Task<ResultElementRatingDto> RemoveTag(ResultElementRatingDto ratingDto)
    {

        return null;
    }
</code>```

The error is:

cannot convert from 'method group' to 'Func'

What's wrong in my code?

答:
Depending on the overloads of Create that are available, and depending on the language version you're using, the compiler sometimes cannot resolve a method group to an unambiguous overload when only considering return types. In that case, call the method with a lambda expression:

```<code>public ICommand OnRemoveTagCommand = AsyncCommand<ResultElementRatingDto>.Create(x => RemoveTag(x));
</code>```

Title: Func syntax for async call

Body:
I try to create an AsyncCommand with a parameter.

I used this method but it's not working.

 public static AsyncCommand<T> Create(Func<System.Threading.Tasks.Task<T>> func)
    {

        return new AsyncCommand<T>(new Command<T>(async (x) =>  await func(x)));
    }

And when I call it with my viewmodel:

 public ICommand OnRemoveTagCommand = AsyncCommand<ResultElementRatingDto>.Create(RemoveTag);

 private async Task<ResultElementRatingDto> RemoveTag(ResultElementRatingDto ratingDto)
    {

        return null;
    }

The error is:

cannot convert from 'method group' to 'Func'

What's wrong in my code?

Body:
Depending on the overloads of Create that are available, and depending on the language version you're using, the compiler sometimes cannot resolve a method group to an unambiguous overload when only considering return types. In that case, call the method with a lambda expression:

public ICommand OnRemoveTagCommand = AsyncCommand<ResultElementRatingDto>.Create(x => RemoveTag(x));


问:
Is there some sort of Laravel Controller cache?
Weird problem I'm having with Laravel 5.5

I can update and even delete a controller and yet it appears as if a cached / old version is still being called.

I've tried clearing cache, clearing route cache, clearing config cache -
 doesn't seem to have any effect.

On my local test environment if I delete the controller file then try to access it I immediately get a not found error. On my production server I do not.

Anyone have any ideas or advice?

答: In my case, I did as suggested by the other solutions contributed here but nothing happened. I had to refresh the Wamp Server I was using and that was it, it started working fine again.</p>


问:
invalid null pointer in xstring
So I'm almost done with this assignment but now I'm having difficulties again. When I try to draw text from a question class I get invalid null pointer from xstring.  I have about 2 hours, so any help would really be appreciated

Here's the question class:

```<code>class Question {

public:
    int col;
    int row;
    bool dailyDouble;
    char* question;
    char* answer;
    double value;
    Question();
    Question(int, int, bool, char*, char*);
    bool checkAnswer(string);
    Question& operator=(const Question&);
};

Question::Question() {}

Question::Question(int c, int r, bool d, char* q, char* a)
{
    col = c; row = r; dailyDouble = d; question = q, answer = a;
    if(d)
        value = r * 200 * 2;
    else
        value = r * 200;
}

bool Question::checkAnswer(string answer)
{
    if(answer.find("What is") && answer.find(answer))
        return true;
    return false;
}

Question& Question::operator=(const Question&)
{
    return *this;
}
</code>```

I have a draw text method (that works) but I'm running out of room, so this is the line that causes the error:

```<code> drawText((WinWidth/2)-200,(WinHeight/2) - 100, curQuestion.question);
</code>```

any help would really be appreciated!

答:
Your operator=(const Question&) is wrong, it does nothing but returning the current object. If that object was created with the default constructor, "question" and "answer" are not initialized, and your program may crash if this operator is used.

The operator "=" is supposed to copy each field. For string pointers like "question" and "answer", you need to allocate new memory for the string content, and copy the characters from the strings of the object passed as a parameter. But you probably should get rid of the  operator= anyway, and use std::string for "question" and "answer" instead of char* (see below).

Finally,

```<code>if(answer.find("What is") && answer.find(answer))
</code>```

Does not make sense. It should probably be something like:

```<code>bool Question::checkAnswer(string proposedAnswer)
{
    if(question.find("What is") && answer.find(proposedAnswer))
        return true;
    return false;
}
</code>```

... assuming you changed the type of question and answer from char* to string:

```<code>public:
    int col;
    int row;
    bool dailyDouble;
    string question;
    string answer;
    ...
</code>```

Title: invalid null pointer in xstring

Body:
So I'm almost done with this assignment but now I'm having difficulties again. When I try to draw text from a question class I get invalid null pointer from xstring.  I have about 2 hours, so any help would really be appreciated

Here's the question class:

class Question {

public:
    int col;
    int row;
    bool dailyDouble;
    char* question;
    char* answer;
    double value;
    Question();
    Question(int, int, bool, char*, char*);
    bool checkAnswer(string);
    Question& operator=(const Question&);
};

Question::Question() {}

Question::Question(int c, int r, bool d, char* q, char* a)
{
    col = c; row = r; dailyDouble = d; question = q, answer = a;
    if(d)
        value = r * 200 * 2;
    else
        value = r * 200;
}

bool Question::checkAnswer(string answer)
{
    if(answer.find("What is") && answer.find(answer))
        return true;
    return false;
}

Question& Question::operator=(const Question&)
{
    return *this;
}

I have a draw text method (that works) but I'm running out of room, so this is the line that causes the error:

 drawText((WinWidth/2)-200,(WinHeight/2) - 100, curQuestion.question);

any help would really be appreciated!

Body:
Your operator=(const Question&) is wrong, it does nothing but returning the current object. If that object was created with the default constructor, "question" and "answer" are not initialized, and your program may crash if this operator is used.

The operator "=" is supposed to copy each field. For string pointers like "question" and "answer", you need to allocate new memory for the string content, and copy the characters from the strings of the object passed as a parameter. But you probably should get rid of the  operator= anyway, and use std::string for "question" and "answer" instead of char* (see below).

Finally,

if(answer.find("What is") && answer.find(answer))

Does not make sense. It should probably be something like:

bool Question::checkAnswer(string proposedAnswer)
{
    if(question.find("What is") && answer.find(proposedAnswer))
        return true;
    return false;
}

... assuming you changed the type of question and answer from char* to string:

public:
    int col;
    int row;
    bool dailyDouble;
    string question;
    string answer;
    ...


问:
Unbalanced parenthesis and missing operator in batch file
The following code generates "Unbalanced parenthesis" on on the command prompt at the start and end of the for loop as well as "Missing Operator" at the end of the for loop. However, the code works fine. I found in other related question that it happens majorly due to nested brackets but even that is not present here.</p>

```<code>for /R .\sql_queries %%m in (*.sql) do (
Echo Querying: %%~nm
::Querying with GAT  - Refer "for /?" for help on %%x variables
java -Xms64m -Xmx512m -cp %mypath% com.app.GenericAxlTool -i %ip% -v 6.0 -a %axlVer% -d %DBVer% -u %userName% -p %password% -c sqlselect -f %%m >output.tmp
cd sql
ren *.tsv %%~nm.tsv >output.tmp
move %%~nm.tsv ..\Reports >output.tmp
cd..
)
</code>```

答:
CMD shell has been programmed to interpret the first close bracket ) to be associated with 1st open bracket ( in code blocks.

I got same errors when grouping codes in brackets.
Found a discussion here: https://ss64.com/nt/syntax-brackets.html

Might help someone with workarounds.

Body:
The following code generates "Unbalanced parenthesis" on on the command prompt at the start and end of the for loop as well as "Missing Operator" at the end of the for loop. However, the code works fine. I found in other related question that it happens majorly due to nested brackets but even that is not present here.

for /R .\sql_queries %%m in (*.sql) do (
Echo Querying: %%~nm
::Querying with GAT  - Refer "for /?" for help on %%x variables
java -Xms64m -Xmx512m -cp %mypath% com.app.GenericAxlTool -i %ip% -v 6.0 -a %axlVer% -d %DBVer% -u %userName% -p %password% -c sqlselect -f %%m >output.tmp
cd sql
ren *.tsv %%~nm.tsv >output.tmp
move %%~nm.tsv ..\Reports >output.tmp
cd..
)


问:
How to enable plain id query rather than using paths in api_platform graphql?
I have implemented api_platform in my symfony 4 project, the problem is that I have to use the paths provided by the Rest api to fetch data using graphql like this

```<code>{
  user(id:"api/users/1")
  {
    id
  }
}
</code>```

rather than

```<code>{
  user(id:1){
  id
  }
}
</code>```

Went through the documentation and didn't find a solution for this. Using plain api paths in graph api isn't really worth moving to graphql. Any help.

答:
You can handle that in the resolver function, so you will receive a string param in the PHP resolver function instead of int(id).
check this example: https://github.com/khaledalam/simple-system-with-graphql-react-php</p>

Body:
I have implemented api_platform in my symfony 4 project, the problem is that I have to use the paths provided by the Rest api to fetch data using graphql like this

{
  user(id:"api/users/1")
  {
    id
  }
}

rather than

{
  user(id:1){
  id
  }
}

Went through the documentation and didn't find a solution for this. Using plain api paths in graph api isn't really worth moving to graphql. Any help.


问:
Spring mvc thymeleaf. How to show whitelabel error page as modal or popup or toast
I have a problem with error displaying in my spring mvc app. So let me describe more detail about problem.

I already know what to do if i want to show custom error page instead of default whitelabel error page. I read about this here and watched some tutorials on youtube. It is simple, but the problem is that user will always redirected to new page, containing error description.

I want to display all my backend exceptions in specific format as a modal window, or alert message or toast as shown here but for thymeleaf. Best solution is modal pages, cause this give me more flexibility of content displaying. But modal can be invoked used JavaScript on frontend side, how to use controller exceptions as trigger for opening modal page (without using AJAX if possible)?

Here is what i want actually, when some method in controller, that can throw an exception is called and exception thrown

```<code>@GetMapping
public ModelAndView throwException() throws Exception {
    throw new Exception("Oops :( something went wrong");
}
</code>```

something like this shall be displayed
error window

Please help me to find a solution. Thanks a lot for your attention.

P.S. if this is complicated or impossible i want to know atleast how to show error message from controller + some buttons or input fields related to error on current(same) page, without redirecting to new one?

答:
TL;DR

No easy way out. If I were you I'd stick with generic error pages. You can customize them for diffent kind of errors.

Tooling inadequate to your problem.

IMO The problem you've described would be better suited for SPA (single page application) written
in any modern frontend framework with java backend exposing REST API. Normally enpoint would return
json containing actual, requested data. But in case of any error you could
simply return 4xx code with description of an error as a payload. Then
presentation logic in javascript could display it whatever you want without page reload.

Since you've decided to use thymeleaf which is templating engine you should accept its limitations. Most of calls to a controller
is a request for a view. Spring and Thymeleaf takes a template file, populates it with model's data and
send back the whole page to your browser. If this process fails while collecting data  the page couldn't be correctly rendered. Therefore the most reasonable
thing to do is to redirect to the error page instead.

Reasonable way out

If generic error pages scares you off, some extra effort can be made. Instead of generic error handling, you
could handle exceptions in each Controller's method.
On error you may provide different "errored" model that will be used to populate the template. It gives you
flexibility on how the error is displayed. It would depend on how you had prepared a template.

E.g.

view.html

<!DOCTYPE html>

    <meta charset="UTF-8">

Data:

Error occurred:

```

<p><strong>MyController.java</strong></p>

<pre class="lang-java prettyprint-override"><code>@Controller
class MyController {

    @GetMapping("/view")
    public String view(Model model) {
        try {
            model.addAttribute("actualData", mayThrowExceptionDataFetch());
        } catch(Exception e) {
            model.addAttribute("errorData", e.getMessage());
        }
        return "view";
    }

    private String mayThrowExceptionDataFetch() {
        // Either return a value or throw an exception
    }
}

</code>```

That way a view will always be returned. Even when error happens it is handled and displayed.

Unreasonable way out

Important note: this is demo only. For sure I wouldn't try it in production.

I found your requriements so unusual (controller exceptions as trigger for opening modal page) that I wanted to check
 if something alike is even possible. I've imagined a solution may be something like:

Frontend: subscribe to server send events endpoint (source of errors).

Backend: while catching an exception, abort the request so that server doesn't return anything.

Backend: send a message containing error description to appriopriate client.

Frontend: receive event, alert it somehow.

Then I come up with this working demo, that indeed doesn't cause page reload yet displays an error:

index.html

<!DOCTYPE HTML>

    <meta charset="UTF-8" />

    Click for exception

```

<p><strong>MyService.java</strong></p>

<pre class="lang-java prettyprint-override"><code>@Service
public class MyService {

    private final SseEmitter emitter = new SseEmitter();

    public SseEmitter getEmitter() {
        return emitter;
    }
}

</code>```

MyExceptionHandler.java

@ControllerAdvice
public class MyExceptionHandler {

    private final MyService service;

    @Autowired
    public MyExceptionHandler(MyService service) {
        this.service = service;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.CONTINUE) // I don't figure out how to abort request
    public ResponseEntity<Void> handle(Exception ex) {
        try {
            service.getEmitter().send(SseEmitter.event().data(ex.getMessage()));
        } catch (IOException e) {
            // TODO
        }
    }
}

```

<p><strong>MyController.java</strong></p>

<pre class="lang-java prettyprint-override"><code>@Controller
public class MyController {

    private final MyService service;

    @Autowired
    public MyCtrl(MyService service) {
        this.service = service;
    }

    @GetMapping("/sse")
    public SseEmitter sse() {
        return service.getEmitter();
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/exception")
    public String exception() {
        throw new RuntimeException("Oops :o");
    }
}
</code>```

Everyting above is spring-boot project with spring-boot-starter-thymeleaf and spring-boot-starter-web dependencies.
Run application, go to localhost:8080/index then click a link. An alert should appear without page reload.

Body:
I have a problem with error displaying in my spring mvc app. So let me describe more detail about problem.

I already know what to do if i want to show custom error page instead of default whitelabel error page. I read about this here and watched some tutorials on youtube. It is simple, but the problem is that user will always redirected to new page, containing error description.

I want to display all my backend exceptions in specific format as a modal window, or alert message or toast as shown here but for thymeleaf. Best solution is modal pages, cause this give me more flexibility of content displaying. But modal can be invoked used JavaScript on frontend side, how to use controller exceptions as trigger for opening modal page (without using AJAX if possible)?

Here is what i want actually, when some method in controller, that can throw an exception is called and exception thrown

@GetMapping
public ModelAndView throwException() throws Exception {
    throw new Exception("Oops :( something went wrong");
}

something like this shall be displayed
error window

Please help me to find a solution. Thanks a lot for your attention.

P.S. if this is complicated or impossible i want to know atleast how to show error message from controller + some buttons or input fields related to error on current(same) page, without redirecting to new one?

Body:
TL;DR

No easy way out. If I were you I'd stick with generic error pages. You can customize them for diffent kind of errors.

Tooling inadequate to your problem.

IMO The problem you've described would be better suited for SPA (single page application) written
in any modern frontend framework with java backend exposing REST API. Normally enpoint would return
json containing actual, requested data. But in case of any error you could
simply return 4xx code with description of an error as a payload. Then
presentation logic in javascript could display it whatever you want without page reload.

Since you've decided to use thymeleaf which is templating engine you should accept its limitations. Most of calls to a controller
is a request for a view. Spring and Thymeleaf takes a template file, populates it with model's data and
send back the whole page to your browser. If this process fails while collecting data  the page couldn't be correctly rendered. Therefore the most reasonable
thing to do is to redirect to the error page instead.

Reasonable way out

If generic error pages scares you off, some extra effort can be made. Instead of generic error handling, you
could handle exceptions in each Controller's method.
On error you may provide different "errored" model that will be used to populate the template. It gives you
flexibility on how the error is displayed. It would depend on how you had prepared a template.

E.g.

view.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h1>Data:</h1>
    <div th:if="${actualData}">
        <p th:text="${actualData}"></p>
    </div>
    <!-- Instead of div below, you could supply a modal and pice of javascript opening it -->
    <div th:if="${errorData}">
        <h3>Error occurred:</h3>
        <p th:text="${errorData}"></p>
    </div>
</body>
</html>

MyController.java

@Controller
class MyController {

    @GetMapping("/view")
    public String view(Model model) {
        try {
            model.addAttribute("actualData", mayThrowExceptionDataFetch());
        } catch(Exception e) {
            model.addAttribute("errorData", e.getMessage());
        }
        return "view";
    }

    private String mayThrowExceptionDataFetch() {
        // Either return a value or throw an exception
    }
}

That way a view will always be returned. Even when error happens it is handled and displayed.

Unreasonable way out

Important note: this is demo only. For sure I wouldn't try it in production.

I found your requriements so unusual (controller exceptions as trigger for opening modal page) that I wanted to check
 if something alike is even possible. I've imagined a solution may be something like:

Frontend: subscribe to server send events endpoint (source of errors).

Backend: while catching an exception, abort the request so that server doesn't return anything.

Backend: send a message containing error description to appriopriate client.

Frontend: receive event, alert it somehow.

Then I come up with this working demo, that indeed doesn't cause page reload yet displays an error:

index.html

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
</head>
<body>
    <a th:href="@{/exception}">Click for exception</a>
    <script>
        var sse = new EventSource('http://localhost:8080/sse');
        sse.onmessage = function (evt) {
            alert(evt.data);
        };
    </script>
</body>
</html>

MyService.java

@Service
public class MyService {

    private final SseEmitter emitter = new SseEmitter();

    public SseEmitter getEmitter() {
        return emitter;
    }
}

MyExceptionHandler.java

@ControllerAdvice
public class MyExceptionHandler {

    private final MyService service;

    @Autowired
    public MyExceptionHandler(MyService service) {
        this.service = service;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.CONTINUE) // I don't figure out how to abort request
    public ResponseEntity<Void> handle(Exception ex) {
        try {
            service.getEmitter().send(SseEmitter.event().data(ex.getMessage()));
        } catch (IOException e) {
            // TODO
        }
    }
}

MyController.java

@Controller
public class MyController {

    private final MyService service;

    @Autowired
    public MyCtrl(MyService service) {
        this.service = service;
    }

    @GetMapping("/sse")
    public SseEmitter sse() {
        return service.getEmitter();
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/exception")
    public String exception() {
        throw new RuntimeException("Oops :o");
    }
}

Everyting above is spring-boot project with spring-boot-starter-thymeleaf and spring-boot-starter-web dependencies.
Run application, go to localhost:8080/index then click a link. An alert should appear without page reload.


问:
AWS DMS "Load complete, replication ongoing" not working MongoDB to DocDB
I am trying to make a PoC for MongoDB to DocDB migration with DMS.
I've set up a MongoDB instance with some dummy data and an empty DocDB. Source and Target endpoints are also set in DMS and both of them are connecting successfully to my databases.

When I create a migration task in DMS everything seems to be working fine. All existing data is successfully replicated from the MongoDB instance to DocDB and the migration task state is at "Load complete, replication ongoing".
At this point I tried creating new entries in existing collections as well as creating new empty collections in MongoDB but nothing happens in DocDB. If I understand correctly the replication should be real time and anything I create should be replicated instantly?
Also there are no indication of errors or warnings whatsoever... I don't suppose its a connectivity issue to the databases since the initial data is being replicated.
Also the users I am using for the migration have admin privileges in both databases.

Does anyone have any suggestions?

答:
@PPetkov - could you check the following?
1. Check if right privileges were assigned to the user in the MongoDB endpoint according to https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MongoDB.html.
2. Check if replicate set to capture changes was appropriately configured in the MongoDB instance.
3. Once done, try to search for "]E:" or "]W:" in the CloudWatch logs to understand if there are any noticeable failures/warnings. </p>


问:
Python 2 Subprocess: Cannot get output from readline
I have the following C application

```<code>#include <stdio.h>

int main(void)
{
    printf("hello world\n");
    /* Go into an infinite loop here. */
    while(1);

    return 0;
}
</code>```

And I have the following python code.

```<code>import subprocess
import time
import pprint

def run():
    command = ["./myapplication"]
    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    try:
        while process.poll() is None:
            # HELP: This call blocks...
            for i in  process.stdout.readline():
                print(i)

    finally:
        if process.poll() is None:
            process.kill()

if __name__ == "__main__":
    run()
</code>```

When I run the python code, the stdout.readline or even stdout.read blocks.

If I run the application using subprocess.call(program) then I can see "hello world" in stdout.

How can I read input from stdout with the example I have provided?

Note: I would not want to modify my C program. I have tried this on both Python 2.7.17 and Python 3.7.5 under Ubuntu 19.10 and I get the same behaviour. Adding bufsize=0 did not help me.

答:
Applications built using the C Standard IO Library (built with #include <stdio.h>) buffer input and output (see here for why). The stdio library, like isatty, can tell that it is writing to a pipe not a TTY and so it chooses block buffering instead of line buffering. Data is flushed when the buffer is full, but "hello world\n" is not filling the buffer so it's not flushed.

One way around is shown in Timo Hartmann answer, using stdbuf utility. This uses an LD_PRELOAD trick to swap in its own libstdbuf.so. In many cases that is a fine solution, but LD_PRELOAD is kind of a hack and does not work in some cases, so it may not be a general solution.

Maybe you want to do this directly in Python, and there are stdlib options to help here, you can use a pseudo-tty (docs py2, docs py3) connected to stdout instead of a pipe.  The program myapplication should enable line buffering, meaning that any newline character flushes the buffer.

```<code>from __future__ import print_function
from subprocess import Popen, PIPE
import errno
import os
import pty
import sys

mfd, sfd = pty.openpty()
proc = Popen(["/tmp/myapplication"], stdout=sfd)
os.close(sfd)  # don't wait for input
while True:
    try:
        output = os.read(mfd, 1000)
    except OSError as e:
        if e.errno != errno.EIO:
            raise
    else:
        print(output)
</code>```

Note that we are reading bytes from the output now, so we can not necessarily decode them right away!

See Processing the output of a subprocess with Python in realtime for a blog post cleaning up this idea. There are also existing third-party libraries to do this stuff, see ptyprocess.

Body:
I have the following C application

#include <stdio.h>

int main(void)
{
    printf("hello world\n");
    /* Go into an infinite loop here. */
    while(1);

    return 0;
}

And I have the following python code.

import subprocess
import time
import pprint

def run():
    command = ["./myapplication"]
    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    try:
        while process.poll() is None:
            # HELP: This call blocks...
            for i in  process.stdout.readline():
                print(i)

    finally:
        if process.poll() is None:
            process.kill()

if __name__ == "__main__":
    run()

When I run the python code, the stdout.readline or even stdout.read blocks.

If I run the application using subprocess.call(program) then I can see "hello world" in stdout.

How can I read input from stdout with the example I have provided?

Note: I would not want to modify my C program. I have tried this on both Python 2.7.17 and Python 3.7.5 under Ubuntu 19.10 and I get the same behaviour. Adding bufsize=0 did not help me.

Body:
Applications built using the C Standard IO Library (built with #include <stdio.h>) buffer input and output (see here for why). The stdio library, like isatty, can tell that it is writing to a pipe not a TTY and so it chooses block buffering instead of line buffering. Data is flushed when the buffer is full, but "hello world\n" is not filling the buffer so it's not flushed.

One way around is shown in Timo Hartmann answer, using stdbuf utility. This uses an LD_PRELOAD trick to swap in its own libstdbuf.so. In many cases that is a fine solution, but LD_PRELOAD is kind of a hack and does not work in some cases, so it may not be a general solution.

Maybe you want to do this directly in Python, and there are stdlib options to help here, you can use a pseudo-tty (docs py2, docs py3) connected to stdout instead of a pipe.  The program myapplication should enable line buffering, meaning that any newline character flushes the buffer.

from __future__ import print_function
from subprocess import Popen, PIPE
import errno
import os
import pty
import sys

mfd, sfd = pty.openpty()
proc = Popen(["/tmp/myapplication"], stdout=sfd)
os.close(sfd)  # don't wait for input
while True:
    try:
        output = os.read(mfd, 1000)
    except OSError as e:
        if e.errno != errno.EIO:
            raise
    else:
        print(output)

Note that we are reading bytes from the output now, so we can not necessarily decode them right away!

See Processing the output of a subprocess with Python in realtime for a blog post cleaning up this idea. There are also existing third-party libraries to do this stuff, see ptyprocess.