问:
Unable to assign NULL to a pointer
I've got weird problem i can't explain with NULL assigment to a pointer. This is my test struct:

```<code>typedef struct
{
    uint8_t *buffer_pntr;
    uint8_t size;
    uint8_t some_other_stuff;
}my_struct_t;

void my_function (my_struct_t *handler)
{
    memset(&handler,0,sizeof(handler);
    handler->buffer_pntr=NULL;
}

void main(void)
{
   my_struct_t test;
   my_function(&test);
}
</code>```

I want to call my_function to set my struct to a known state because i'm declaring my struct inside main so it becomes local and local variable state is unknown. Problem is that assigning NULL causes system crash(Hardfault on cortex-m4) and i'm also not sure if using memset on struct with pointer is a good practise. Removing NULL assigment from my_function and using test.buffer_pntr=NULL outside my_function solves the problem.

答:
```<code>memset(&handler,0,sizeof(handler));
</code>```

should be

```<code>memset(handler,0,sizeof(*handler));
</code>```

As handler is already pointer, regarding sizeof(handler) is size of pointer you need to pass size of object where handler is pointing.

Title: Unable to assign NULL to a pointer

Body:
I've got weird problem i can't explain with NULL assigment to a pointer. This is my test struct:

typedef struct
{
    uint8_t *buffer_pntr;
    uint8_t size;
    uint8_t some_other_stuff;
}my_struct_t;

void my_function (my_struct_t *handler)
{
    memset(&handler,0,sizeof(handler);
    handler->buffer_pntr=NULL;
}

void main(void)
{
   my_struct_t test;
   my_function(&test);
}

I want to call my_function to set my struct to a known state because i'm declaring my struct inside main so it becomes local and local variable state is unknown. Problem is that assigning NULL causes system crash(Hardfault on cortex-m4) and i'm also not sure if using memset on struct with pointer is a good practise. Removing NULL assigment from my_function and using test.buffer_pntr=NULL outside my_function solves the problem.

Body:
memset(&handler,0,sizeof(handler));

should be

memset(handler,0,sizeof(*handler));

As handler is already pointer, regarding sizeof(handler) is size of pointer you need to pass size of object where handler is pointing.


来源: stackexchange

问:
Why does .MSI file open read-only?
I am attempting to open a .MSI installer package file to modify it. Whenever I try to open it, it opens in read-only mode. I see this with Orca, with InstEd, or when opening the file directly via code:

```<code> `MsiOpenDatabase()` (ERROR_OPEN_FAILED with MSIDBOPEN_DIRECT or
                      MSIDBOPEN_TRANSACT persistence modes).
</code>```

The file itself does not have the read-only attribute set (in fact, has no attributes set)

I am using an account with Administrators group access

As far as I can tell, no other process has the file open

No installs are in progress or suspended

I can copy the file to another location, and open it read/write there. But the original, I cannot touch

Thanks in advance for your help.

答:
Try to close/kill processes that might interfere, for example:

Other running Install shield instances

Installshield updater

Installshield licensing service

Antivirus

ContentLicense: CC BY-SA 3.0

Title: Why does .MSI file open read-only?

Body:
I am attempting to open a .MSI installer package file to modify it. Whenever I try to open it, it opens in read-only mode. I see this with Orca, with InstEd, or when opening the file directly via code:

 `MsiOpenDatabase()` (ERROR_OPEN_FAILED with MSIDBOPEN_DIRECT or
                      MSIDBOPEN_TRANSACT persistence modes).

The file itself does not have the read-only attribute set (in fact, has no attributes set)

I am using an account with Administrators group access

As far as I can tell, no other process has the file open

No installs are in progress or suspended

I can copy the file to another location, and open it read/write there. But the original, I cannot touch

Thanks in advance for your help.

ContentLicense: CC BY-SA 4.0


问:
In Django, disable @login_required for search engine spiders
I'm looking for a clean way to let search engine spiders bypass @login_required, viewing pages which typically require a logged-in user.  I could write middleware that would automatically log search engines into a dummy account, but that's not exactly what I'd call clean.  Any suggestions for a better solution?  Thanks.</p>

答:
I don't get it. in "@login_required" you have an important word: "required". if it's "required", it's for a good reason. It means that, in order to see the webpage, your credentials are mandatory. Because the content is private, secret, etc.

If you want to make your pages to be available via search engines, you have to make them public, and thus, login is not required anymore. And so, your view should not be protected by the @login_required decorator.

Maybe your problem lies beyond the availabilty of your pages. Maybe your content is actually made to be public, and your views should not be protected by this decorator. Maybe the only thing you need is to load the public part for every user (logged or anonymous) and eventually load the private bits if your user is identified.

Otherwise, leaving a backdoor for spiders is definitely a bad idea, because your private content won't be private anymore.


问:
How to add multiple columns in already made table in Laravel?
I want to add multiple number of columns in the already made table in Laravel . How can i add multiple columns ?

I don't know how to do add columns in my table. I can only add single column one at a time.

Below given is my migration table up function.

```<code>public function up()
{
    Schema::create('matches', function (Blueprint $table) {
        $table->increments('id');
        $table->string('sports');
        $table->string('match');
        $table->string('date');
        $table->string('time');
        $table->string('teamA');
        $table->longtext('teamA_flag');
        $table->string('teamB');
        $table->longtext('teamB_flag');
        $table->string('venue');
        $table->string('status');
        $table->timestamps();
    });
}
</code>```

This is my table whose name is matches. I want to add two columns using Laravel. The name of columns are: email and qualification.

I am expecting to add multiple number of columns on the table (matches).
I want to add multiple number of columns in the already made table in Laravel . How can i add multiple columns ?

I don't know how to do add columns in my table. I can only add single column one at a time.

答:
Create migration first by php artisan make:migration alter_table_matches,
open migration that is created by the command.

```<code>public function up()
{
    Schema::table('matches', function (Blueprint $table) {
        $table->string('email')->nullable()->default(null);
        $table->string('qualification')->nullable()->default(null);
    });
}
</code>```

then in down function

```<code>public function down()
{
    Schema::table('matches', function (Blueprint $table) {
        $table->dropColumn('email');
        $table->dropColumn('qualification');
    });
}
</code>```

Body:
I want to add multiple number of columns in the already made table in Laravel . How can i add multiple columns ?

I don't know how to do add columns in my table. I can only add single column one at a time.

Below given is my migration table up function.

public function up()
{
    Schema::create('matches', function (Blueprint $table) {
        $table->increments('id');
        $table->string('sports');
        $table->string('match');
        $table->string('date');
        $table->string('time');
        $table->string('teamA');
        $table->longtext('teamA_flag');
        $table->string('teamB');
        $table->longtext('teamB_flag');
        $table->string('venue');
        $table->string('status');
        $table->timestamps();
    });
}

This is my table whose name is matches. I want to add two columns using Laravel. The name of columns are: email and qualification.

I am expecting to add multiple number of columns on the table (matches).
I want to add multiple number of columns in the already made table in Laravel . How can i add multiple columns ?

I don't know how to do add columns in my table. I can only add single column one at a time.

Body:
Create migration first by php artisan make:migration alter_table_matches,
open migration that is created by the command.

public function up()
{
    Schema::table('matches', function (Blueprint $table) {
        $table->string('email')->nullable()->default(null);
        $table->string('qualification')->nullable()->default(null);
    });
}

then in down function

public function down()
{
    Schema::table('matches', function (Blueprint $table) {
        $table->dropColumn('email');
        $table->dropColumn('qualification');
    });
}


问:
To git checkout without overwriting data
How can you git-checkout without overwriting the data?

I run

```<code> git checkout master
</code>```

I get

```<code>error: Entry 'forms/answer.php' would be overwritten by merge. Cannot merge.
</code>```

This is surprising, since I did not know that Git merges when I git-checkout.
I have always run after the command separately git merge new-feature.
This seems to be apparently unnecessary if Git merges at checkout.

答:
You can do a git reset --soft to make your HEAD point to the new branch, but leave all the files as they are (including the ones that were changed in the new branch). Then you can use git checkout to checkout just the files that you really want from the new branch.

```<code>       git reset [<mode>] [<commit>]
           This form resets the current branch head to <commit> and possibly updates the index (resetting it to the
           tree of <commit>) and the working tree depending on <mode>. If <mode> is omitted, defaults to --mixed.
           The <mode> must be one of the following:

           --soft
               Does not touch the index file or the working tree at all (but resets the head to <commit>, just like
               all modes do). This leaves all your changed files "Changes to be committed", as git status would put
               it.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can you git-checkout without overwriting the data?

I run

 git checkout master

I get

error: Entry 'forms/answer.php' would be overwritten by merge. Cannot merge.

This is surprising, since I did not know that Git merges when I git-checkout.
I have always run after the command separately git merge new-feature.
This seems to be apparently unnecessary if Git merges at checkout.

Body:
You can do a git reset --soft to make your HEAD point to the new branch, but leave all the files as they are (including the ones that were changed in the new branch). Then you can use git checkout to checkout just the files that you really want from the new branch.

       git reset [<mode>] [<commit>]
           This form resets the current branch head to <commit> and possibly updates the index (resetting it to the
           tree of <commit>) and the working tree depending on <mode>. If <mode> is omitted, defaults to --mixed.
           The <mode> must be one of the following:

           --soft
               Does not touch the index file or the working tree at all (but resets the head to <commit>, just like
               all modes do). This leaves all your changed files "Changes to be committed", as git status would put
               it.


问:
Create function/procedure to return table to get the last rows
I have several tables, each with a different key.

For example: the key for the Customer could be 2 or more columns.

Input - dbo.customer:

```<code>Customer e_Date    Value
------------------------
1000     2019-05-26  200
1000     2019-05-25  100
2000     2019-04-23   50
2000     2019-04-21   20
</code>```

Output :

```<code>Customer  e_date       value
----------------------------
1000      2019-05-26    200
2000      2019-04-23     50
</code>```

The max dates and the values for them was return for each customer (key).

I want to build a function or procedure in SQL where I will enter the name of table and the key and will return me the output. A return table function.

```<code>exec procedure get_Last_Row_By_Key (@Table_Name, @Key)
</code>```

and it will show me the output.

In this example :

```<code>exec procedure get_Last_Row_By_Key ('dbo.customer', Customer)
</code>```

I guess that when the @key will be multiple value I can do concat of the other columns to make them a one column key.

答:
put below query in your function using row_number() window function

```<code> select customer,e_date,value from
           (select *,row_number()over(partition by customer order by e_date desc) rn
 from table ) a where a.rn=1
</code>```

Body:
I have several tables, each with a different key.

For example: the key for the Customer could be 2 or more columns.

Input - dbo.customer:

Customer e_Date    Value
------------------------
1000     2019-05-26  200
1000     2019-05-25  100
2000     2019-04-23   50
2000     2019-04-21   20

Output :

Customer  e_date       value
----------------------------
1000      2019-05-26    200
2000      2019-04-23     50

The max dates and the values for them was return for each customer (key).

I want to build a function or procedure in SQL where I will enter the name of table and the key and will return me the output. A return table function.

exec procedure get_Last_Row_By_Key (@Table_Name, @Key)

and it will show me the output.

In this example :

exec procedure get_Last_Row_By_Key ('dbo.customer', Customer)

I guess that when the @key will be multiple value I can do concat of the other columns to make them a one column key.

Body:
put below query in your function using row_number() window function

 select customer,e_date,value from
           (select *,row_number()over(partition by customer order by e_date desc) rn
 from table ) a where a.rn=1


答:
The problem is here:

```<code>memset(&handler,0,sizeof(handler));
</code>```

I assume you want to zero the struct, but handler is a pointer, so when you say &handler you’re taking a pointer to the pointer and zeroing it. So effectively you’re doing

```<code>handler = NULL;
</code>```

And then dereferencing the pointer is causing the problem. If you want to zero the structure you need to do

```<code>memset(handler,0,sizeof(*handler));
</code>```

Then, of course, you don’t need to set the pointer inside to NULL separately.

Title: Unable to assign NULL to a pointer

Body:
The problem is here:

memset(&handler,0,sizeof(handler));

I assume you want to zero the struct, but handler is a pointer, so when you say &handler you’re taking a pointer to the pointer and zeroing it. So effectively you’re doing

handler = NULL;

And then dereferencing the pointer is causing the problem. If you want to zero the structure you need to do

memset(handler,0,sizeof(*handler));

Then, of course, you don’t need to set the pointer inside to NULL separately.


问:
How to store data in database using redbeans php
I am trying to store data from my web form to database using redbeans but I cannot make it work. I have already make sure that database is connected. I am using apache xampp server for web and sql.
This is my code

Form

<?php
    require "validatecar.php";
?>

<form method="POST">
    Model <input type="text" name="Model">
    Manufacturing Company <input type="text" name="Company">
    Pessenger Capacity <input type="number" name="Pessenger">
    Luggage Capacty <input type="number" name="Luggage">
    Doors <input type="number" name="Doors">
    Transmission <input type="text" name="Transmission">
    Stereo <input type="text" name="Stereo">
    Air Conditioning <input type="text" name="AC">
    Image <input type="file" name="Image">
    <input type="submit" name="Submit">
</form>

```

<p><strong>Validate</strong></p>

<pre class="lang-php prettyprint-override"><code><?php
    include "dbconnection.php";
?>

<?php
    if(isset($_POST['Submit']))
    {

        $model = $_POST['Model'];
        $company = $_POST['Company'];
        $pessenger = $_POST['Pessenger'];
        $luggage = $_POST['Luggage'];
        $doors = $_POST['Doors'];
        $transmission = $_POST['Transmission'];
        $stereo = $_POST['Stereo'];
        $ac = $_POST['AC'];
        $image = $_POST['Image'];

        $cars = R::dispense('cars');
        $cars->model = $model;
        $cars->company = $company;
        $cars->pessenger = $pessenger;
        $cars->luggage = $luggage;
        $cars->doors = $doors;
        $cars->transmission = $transmission;
        $cars->stereo = $stereo;
        $cars->ac = $ac;
        $cars->image = $image;
        R::store($cars);

        R::close();
    }
?>
</code>```

If you could tell me what am I doing wrong and how to solve it, that would be very helpful. Thanks in advance.

答:
You've gone for naming using first letter capital. But for some reason your name for your submit fails your naming convention.

You are looking for $_POST['Submit'] when you have named it all lower case 'submit' instead of Submit so your code for storing in your Database will never run.

If you were to perform a var_dump() or print_r() on $_POST.

I.E. in your validate.php for instance, prior to your if test, you will see what is being "Posted".

```<code><?php
    var_dump($_POST);  // Added for Debug - View what is being posted.
    if(isset($_POST['Submit']))
    {
    //... Rest of code here
</code>```

So in your form, your submit input has a wee typo for your "name" value.

```<code><input type="submit" name="submit">
</code>```

should be...

```<code><input type="submit" name="Submit">
</code>```

Body:
I am trying to store data from my web form to database using redbeans but I cannot make it work. I have already make sure that database is connected. I am using apache xampp server for web and sql.
This is my code

Form

<?php
    require "validatecar.php";
?>

<form method="POST">
    Model <input type="text" name="Model">
    Manufacturing Company <input type="text" name="Company">
    Pessenger Capacity <input type="number" name="Pessenger">
    Luggage Capacty <input type="number" name="Luggage">
    Doors <input type="number" name="Doors">
    Transmission <input type="text" name="Transmission">
    Stereo <input type="text" name="Stereo">
    Air Conditioning <input type="text" name="AC">
    Image <input type="file" name="Image">
    <input type="submit" name="Submit">
</form>

Validate

<?php
    include "dbconnection.php";
?>

<?php
    if(isset($_POST['Submit']))
    {

        $model = $_POST['Model'];
        $company = $_POST['Company'];
        $pessenger = $_POST['Pessenger'];
        $luggage = $_POST['Luggage'];
        $doors = $_POST['Doors'];
        $transmission = $_POST['Transmission'];
        $stereo = $_POST['Stereo'];
        $ac = $_POST['AC'];
        $image = $_POST['Image'];

        $cars = R::dispense('cars');
        $cars->model = $model;
        $cars->company = $company;
        $cars->pessenger = $pessenger;
        $cars->luggage = $luggage;
        $cars->doors = $doors;
        $cars->transmission = $transmission;
        $cars->stereo = $stereo;
        $cars->ac = $ac;
        $cars->image = $image;
        R::store($cars);

        R::close();
    }
?>

If you could tell me what am I doing wrong and how to solve it, that would be very helpful. Thanks in advance.

Body:
You've gone for naming using first letter capital. But for some reason your name for your submit fails your naming convention.

You are looking for $_POST['Submit'] when you have named it all lower case 'submit' instead of Submit so your code for storing in your Database will never run.

If you were to perform a var_dump() or print_r() on $_POST.

I.E. in your validate.php for instance, prior to your if test, you will see what is being "Posted".

<?php
    var_dump($_POST);  // Added for Debug - View what is being posted.
    if(isset($_POST['Submit']))
    {
    //... Rest of code here

So in your form, your submit input has a wee typo for your "name" value.

<input type="submit" name="submit">

should be...

<input type="submit" name="Submit">


问:
How to use jQuery WYSIWYG HTML editor in ASP.net page
I am working in a blog application , i want to integrate the HTML editor of jQuery in ASP.net application.Although i have much easier option of using ASP.net AJAX toolkit editor , but it is not lightweight, so i want to go with jQuery HTML editor.

Can you suggest some tutorial which helps to do so.

Thanks in advance.

答:
I'm using this one http://premiumsoftware.net/cleditor/

A very good one :-bd


问:
Webpack: Inline processed font file in index.html
I'm using html-webpack-plugin and I would like to insert my hashed font file to my custom index.html template.

index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
     <style>
        @font-face {
          font-family: Inter;
          src: url("<%= ?????? %>") format("woff2");
        }
     </style>
</code>```

And I import the font in my entry file app.js like import "./fonts/inter.woff2"

I can't figure out how to get the reference of the processed font asset.

答:
This question was part of my effort to inline some critical CSS which contains my font-face too.

First, follow this mini-css-extract-plugin guide to extract CSS based on entry. Though one thing I did differently was I directly provide the SCSS file that contains my critical CSS index.scss as a separate entry chunk named critical:

```<code>// webpack.config.js
module.exports = {
  entry: {
    app: 'index.js',
    critical: path.resolve(__dirname, "../src/index.scss")
  },
</code>```

Then in my index.html we will utilize the webpack's compilation and html-webpack-plugin's htmlWebpackPlugin object:

```<code>// index.html
<style>
   <%= compilation.assets[htmlWebpackPlugin.files.chunks.critical.css[0]].source() %>
</style>
</code>```

And there you have it- The content of your critical index.scss being inlined in your index.html!

Body:
I'm using html-webpack-plugin and I would like to insert my hashed font file to my custom index.html template.

index.html

<!DOCTYPE html>

And I import the font in my entry file app.js like import "./fonts/inter.woff2"

I can't figure out how to get the reference of the processed font asset.

Body:
This question was part of my effort to inline some critical CSS which contains my font-face too.

First, follow this mini-css-extract-plugin guide to extract CSS based on entry. Though one thing I did differently was I directly provide the SCSS file that contains my critical CSS index.scss as a separate entry chunk named critical:

// webpack.config.js
module.exports = {
  entry: {
    app: 'index.js',
    critical: path.resolve(__dirname, "../src/index.scss")
  },

Then in my index.html we will utilize the webpack's compilation and html-webpack-plugin's htmlWebpackPlugin object:

// index.html
<style>
   <%= compilation.assets[htmlWebpackPlugin.files.chunks.critical.css[0]].source() %>
</style>

And there you have it- The content of your critical index.scss being inlined in your index.html!


问:
Configuring Elasticsearch 7 cluster
I have three server and I have installed elasticsearch on all of them.

In the elasticsearch.yml I have the following config:

first server: 172.31.1.1

```<code># /etc/elasticsearch/elasticsearch.yml
cluster.name: es-cluster
node.name: es-1
network.host: 172.31.1.1
http.port: 9200
network.host:
discovery.seed_hosts: ["172.31.1.1", "172.31.1.2", "172.31.1.3"]
cluster.initial_master_nodes:["es-1", "es-2", "es-3"]

gateway.recover_after_nodes: 2
gateway.expected_nodes: 3
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
# some more default values
</code>```

second server: 172.31.1.2

```<code>node.name: es-2
network.host: 172.31.1.2
# everything else same as first server
</code>```

second server: 172.31.1.3

```<code>node.name: es-3
network.host: 172.31.1.3
# everything else same as first server
</code>```

Now when I run: curl http://es-1:9200/_cluster/stats

I notice that the cluster size is 1. if I run the same curl command on a different server, again the cluster size is 1 and the cluster_name is the same, but cluster_uuid is different...

It seems that nodes are not able to connect to each other...

I am using Ubuntu server, for node name I edited /etc/hostname and changed the host name to
es-1 and used the same name in elasticsearch.yml... but it seems that cluster nodes are not able to communicate with one another...

Update 1

```<code>curl http://es-1:9200/_cat/health
prod-es-cluster red 1 1 0 0 0 0 0 0 - NaN%

curl http://es-1/:9200/_cat/nodes
172.31.1.1 8 38 1 0.03 0.03 0.00 mdi * ip-172-31-1-1
</code>```

I just check the log and it's strange...

```<code>sudo cat /var/log/elasticsearch/elasticsearch.log
[INFO ][o.e.n.Node               ] [es-1] stopping ...
[INFO ][o.e.x.w.WatcherService   ] [es-1] stopping watch service, reason [shutdown initiated]
[INFO ][o.e.x.m.p.l.CppLogMessageHandler] [es-1] [controller/19159] [Main.cc@148] Ml controller exiting
[INFO ][o.e.x.m.p.NativeController] [es-1] Native controller process has stopped - no new native processes can be started
[INFO ][o.e.n.Node               ] [es-1] stopped
[INFO ][o.e.n.Node               ] [es-1] closing ...
[INFO ][o.e.n.Node               ] [es-1] closed
</code>```

That is all written to the log file... after restarting Elasticsearch nothing new gets added to the log file... it feels like I am either reading the wrong log file or I have put the configuration in the wrong .yml file

Update 2

This is how I start the service:

```<code>sudo /bin/systemctl enable elasticsearch.service
</code>```

Update 3

As pointed out by @hamidbayat, I think there is permission issues. Only super user have permission to /var/lib/elasticsearch

If I try to run elastic search as my ubuntu user I will get this error:

```<code>ubuntu@my-ip:~$ /usr/share/elasticsearch/bin/elasticsearch
/usr/share/elasticsearch/bin/elasticsearch-env: line 73:
/etc/default/elasticsearch: Permission denied
</code>```

If I try to run it as root, I will get this error:

```<code>ubuntu@myip:~$ sudo /usr/share/elasticsearch/bin/elasticsearch
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
[data][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [es-1] uncaught exception in thread [main]
org.elasticsearch.bootstrap.StartupException: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:163) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:150) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:124) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:115) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:92) ~[elasticsearch-7.1.0.jar:7.1.0]
Caused by: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:102) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:169) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:325) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:159) ~[elasticsearch-7.1.0.jar:7.1.0]
        ... 6 more
</code>```

答:
This is how I solved the issue:

I was reading elasticsearch.log and thought I am not getting anything in the log file, but realized that the logs are being written to cluster-name.log (es-cluster.log in my case)

I commented out http.port: 9200 in elasticsearch.yml I believe elasticsearch uses 9300 by default.

I removed the node's own IP from discovery.seed_hosts:, so only other nodes are added to this list, e.g. for first server I have:

discovery.seed_hosts: ["172.31.1.2", "172.31.1.3"]

I realized each node has formed it's own cluster and that's why they were not joining the same cluster. So I had to merge the clusters. Since I had no data in the cluster, I had the option of deleting the data path. So I left node 1 running and stopped elasticsearch on node 2 & 3. Then deleted the data path on nodes 2 & 3 (in my case data path was /var/lib/elasticsearch/). Then started nodes 2 and 3 and they joined the cluster.

Title: Configuring Elasticsearch 7 cluster

Body:
I have three server and I have installed elasticsearch on all of them.

In the elasticsearch.yml I have the following config:

first server: 172.31.1.1

# /etc/elasticsearch/elasticsearch.yml
cluster.name: es-cluster
node.name: es-1
network.host: 172.31.1.1
http.port: 9200
network.host:
discovery.seed_hosts: ["172.31.1.1", "172.31.1.2", "172.31.1.3"]
cluster.initial_master_nodes:["es-1", "es-2", "es-3"]

gateway.recover_after_nodes: 2
gateway.expected_nodes: 3
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
# some more default values

second server: 172.31.1.2

node.name: es-2
network.host: 172.31.1.2
# everything else same as first server

second server: 172.31.1.3

node.name: es-3
network.host: 172.31.1.3
# everything else same as first server

Now when I run: curl http://es-1:9200/_cluster/stats

I notice that the cluster size is 1. if I run the same curl command on a different server, again the cluster size is 1 and the cluster_name is the same, but cluster_uuid is different...

It seems that nodes are not able to connect to each other...

I am using Ubuntu server, for node name I edited /etc/hostname and changed the host name to
es-1 and used the same name in elasticsearch.yml... but it seems that cluster nodes are not able to communicate with one another...

Update 1

curl http://es-1:9200/_cat/health
prod-es-cluster red 1 1 0 0 0 0 0 0 - NaN%

curl http://es-1/:9200/_cat/nodes
172.31.1.1 8 38 1 0.03 0.03 0.00 mdi * ip-172-31-1-1

I just check the log and it's strange...

sudo cat /var/log/elasticsearch/elasticsearch.log
[INFO ][o.e.n.Node               ] [es-1] stopping ...
[INFO ][o.e.x.w.WatcherService   ] [es-1] stopping watch service, reason [shutdown initiated]
[INFO ][o.e.x.m.p.l.CppLogMessageHandler] [es-1] [controller/19159] [Main.cc@148] Ml controller exiting
[INFO ][o.e.x.m.p.NativeController] [es-1] Native controller process has stopped - no new native processes can be started
[INFO ][o.e.n.Node               ] [es-1] stopped
[INFO ][o.e.n.Node               ] [es-1] closing ...
[INFO ][o.e.n.Node               ] [es-1] closed

That is all written to the log file... after restarting Elasticsearch nothing new gets added to the log file... it feels like I am either reading the wrong log file or I have put the configuration in the wrong .yml file

Update 2

This is how I start the service:

sudo /bin/systemctl enable elasticsearch.service

Update 3

As pointed out by @hamidbayat, I think there is permission issues. Only super user have permission to /var/lib/elasticsearch

If I try to run elastic search as my ubuntu user I will get this error:

ubuntu@my-ip:~$ /usr/share/elasticsearch/bin/elasticsearch
/usr/share/elasticsearch/bin/elasticsearch-env: line 73:
/etc/default/elasticsearch: Permission denied

If I try to run it as root, I will get this error:

ubuntu@myip:~$ sudo /usr/share/elasticsearch/bin/elasticsearch
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
[data][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [es-1] uncaught exception in thread [main]
org.elasticsearch.bootstrap.StartupException: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:163) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:150) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:124) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:115) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:92) ~[elasticsearch-7.1.0.jar:7.1.0]
Caused by: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:102) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:169) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:325) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:159) ~[elasticsearch-7.1.0.jar:7.1.0]
        ... 6 more


问:
Type mismatch in Geocoder Address
I am implementing a code in kotlin to show an address in google map. I have the address stored in Firebase. I am extracting the data and converting the address into a string and then trying to find the latitude and longitude from the same. Here is my code for getting the latitude and longitude:

```<code>   private fun getLocationFromAddress(context: Context, addkey: String?): LatLng? {

    val coder = Geocoder(context)
    val address: List<Address>
    var p1: LatLng? = null
    var strAddress = ""

    try {

        val user = FirebaseAuth.getInstance().currentUser
        val userid = user?.uid
        mRef = FirebaseDatabase.getInstance().reference.child("users").child(userid.toString()).child("users")

        mRef.child(addkey.toString()).addValueEventListener(object: ValueEventListener{
            override fun onCancelled(p0: DatabaseError) {
            }

            override fun onDataChange(p0: DataSnapshot) {
                strAddress = p0.child("****").child(addkey.toString()).child("***").getValue(String::class.java)

            }

        })
        address = coder.getFromLocationName(strAddress, 5)
        if (address == null) {
            return null
        }

        val location = address[0]
        p1 = LatLng(location.latitude, location.longitude)

    } catch (ex: IOException) {

        ex.printStackTrace()
    }

    return p1

}
</code>```

However, I am getting Type mismatch error at address = coder.getFromLocationName(strAddress, 5).

It says: "Type Mismatch.
          Required: List "My Project Name.com".Address
          Found: (Mutable)List android.location.Address!>!

答:
change the declaration of address

```<code>val address: MutableList<Address>
</code>```

List is unmutable, but you get a mutable list back.

Title: Type mismatch in Geocoder Address

Body:
I am implementing a code in kotlin to show an address in google map. I have the address stored in Firebase. I am extracting the data and converting the address into a string and then trying to find the latitude and longitude from the same. Here is my code for getting the latitude and longitude:

   private fun getLocationFromAddress(context: Context, addkey: String?): LatLng? {

    val coder = Geocoder(context)
    val address: List<Address>
    var p1: LatLng? = null
    var strAddress = ""

    try {

        val user = FirebaseAuth.getInstance().currentUser
        val userid = user?.uid
        mRef = FirebaseDatabase.getInstance().reference.child("users").child(userid.toString()).child("users")

        mRef.child(addkey.toString()).addValueEventListener(object: ValueEventListener{
            override fun onCancelled(p0: DatabaseError) {
            }

            override fun onDataChange(p0: DataSnapshot) {
                strAddress = p0.child("****").child(addkey.toString()).child("***").getValue(String::class.java)

            }

        })
        address = coder.getFromLocationName(strAddress, 5)
        if (address == null) {
            return null
        }

        val location = address[0]
        p1 = LatLng(location.latitude, location.longitude)

    } catch (ex: IOException) {

        ex.printStackTrace()
    }

    return p1

}

However, I am getting Type mismatch error at address = coder.getFromLocationName(strAddress, 5).

It says: "Type Mismatch.
          Required: List "My Project Name.com".Address
          Found: (Mutable)List android.location.Address!>!

Body:
change the declaration of address

val address: MutableList<Address>

List is unmutable, but you get a mutable list back.


问:
Sorting 2D array by two numeric items
I want to sort a 2D array first by column 5, then by column 4.  They represent the PTS and GD on a football league table.

```<code>var table = [
  ["teamA", 6, 2, 0, 2, 7],
  ["teamB", 6, 1, 1, 6, 7],
  ["teamC", 6, 2, 1, 8, 7]
];
</code>```

I've adapted the great advice I received on the forum:
Sorting 2D Array by numeric item

I replicated the function so that it first sorts by PTS and then by GD.

```<code>console.log(table.sort(comparePTS));

console.log(table.sort(compareGD));

function comparePTS(a, b) {
  return b[5] - a[5]

}
function compareGD(a, b) {
  return b[4] - a[4]
}
</code>```

Although this works, it displays the table twice:

Sorted by PTS

```<code>[ [ "teamA", 6, 2, 0, 2, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamC", 6, 2, 1, 8, 7 ] ]
</code>```

Sorted by PTS and GD

```<code>[ [ "teamC", 6, 2, 1, 8, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamA", 6, 2, 0, 2, 7 ] ]
</code>```

And this seems the most clunky solution.  What's the best way to achieve this within a single function?  Thanks in advance.

答:
You could chain the order functions until you have a difference for returning this value to the sorting function.

const
    PTS = a => a[5],
    GD = a => a[4],
    ASC = fn => (a, b) => fn(a) - fn(b),
    DESC = fn => (a, b) => fn(b) - fn(a),
    sortBy = fns => (a, b) => {
        var value;
        fns.some(fn => value = fn(a, b));
        return value;
    };

var table = [["teamA", 6, 2, 0, 2, 7], ["teamB", 6, 1, 1, 6, 7], ["teamC", 6, 2, 1, 8, 7]];

table.sort(sortBy([DESC(PTS), DESC(GD)]));

console.log(table);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Sorting 2D array by two numeric items

Body:
I want to sort a 2D array first by column 5, then by column 4.  They represent the PTS and GD on a football league table.

var table = [
  ["teamA", 6, 2, 0, 2, 7],
  ["teamB", 6, 1, 1, 6, 7],
  ["teamC", 6, 2, 1, 8, 7]
];

I've adapted the great advice I received on the forum:
Sorting 2D Array by numeric item

I replicated the function so that it first sorts by PTS and then by GD.

console.log(table.sort(comparePTS));

console.log(table.sort(compareGD));

function comparePTS(a, b) {
  return b[5] - a[5]

}
function compareGD(a, b) {
  return b[4] - a[4]
}

Although this works, it displays the table twice:

Sorted by PTS

[ [ "teamA", 6, 2, 0, 2, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamC", 6, 2, 1, 8, 7 ] ]

Sorted by PTS and GD

[ [ "teamC", 6, 2, 1, 8, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamA", 6, 2, 0, 2, 7 ] ]

And this seems the most clunky solution.  What's the best way to achieve this within a single function?  Thanks in advance.

Body:
You could chain the order functions until you have a difference for returning this value to the sorting function.

const
    PTS = a => a[5],
    GD = a => a[4],
    ASC = fn => (a, b) => fn(a) - fn(b),
    DESC = fn => (a, b) => fn(b) - fn(a),
    sortBy = fns => (a, b) => {
        var value;
        fns.some(fn => value = fn(a, b));
        return value;
    };

var table = [["teamA", 6, 2, 0, 2, 7], ["teamB", 6, 1, 1, 6, 7], ["teamC", 6, 2, 1, 8, 7]];

table.sort(sortBy([DESC(PTS), DESC(GD)]));

console.log(table);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
heroku rake db:migrate rake aborted! unable to open database
I am currently making my way through the Ruby on Rails tutorial over at http://ruby.railstutorial.org/ and I am trying to migrate the demo_app database to heroku.

```<code>heroku rake db:migrate
    rake aborted!
    unable to open database file
</code>```

I have read on other stackoverflow posts that some people fixed this by entering

```<code>group :production, :staging do
  gem "pg"
end

group :development, :test do
  gem "sqlite3-ruby", "~> 1.3.0", :require => "sqlite3"
end
</code>```

in the gemfile. I also entered it into my gemfile and then deleted my old gemfile.lock and redid my bundle install AND rake db:migrate command. I am still receiving the same error.

I am obviously brand new to ruby, rails and heroku but I understand that the problem seems to be that I am using sqlite locally and postgresql in production (on heroku). Do I now have to install this postgresql onto my machine and then RE-migrate the DB? I am afraid I will not be able to get much more out of the tutorials (or ruby on rails itself) if I cannot use heroku.

答:
or if it's working ok locally do a heroku db:push to magically put your local sqlite DB into Heroku's postgresql db.

I always work with the same DB platform locally just so I don't run into any differences (usually only when you start doing DB specific SQL) so I run Postgresql locally too.

Body:
I am currently making my way through the Ruby on Rails tutorial over at http://ruby.railstutorial.org/ and I am trying to migrate the demo_app database to heroku.

heroku rake db:migrate
    rake aborted!
    unable to open database file

I have read on other stackoverflow posts that some people fixed this by entering

group :production, :staging do
  gem "pg"
end

group :development, :test do
  gem "sqlite3-ruby", "~> 1.3.0", :require => "sqlite3"
end

in the gemfile. I also entered it into my gemfile and then deleted my old gemfile.lock and redid my bundle install AND rake db:migrate command. I am still receiving the same error.

I am obviously brand new to ruby, rails and heroku but I understand that the problem seems to be that I am using sqlite locally and postgresql in production (on heroku). Do I now have to install this postgresql onto my machine and then RE-migrate the DB? I am afraid I will not be able to get much more out of the tutorials (or ruby on rails itself) if I cannot use heroku.


问:
What does mean if (\false) (yes, with backslash) in PHP?
This morning, I've been notified that a new Twig_Extensions release is available! Yay!

Before integrating it to twigfiddle, I wanted to see changes. This is mainly adding support to namespaces using class_alias function, and then add PSR-4 correspoding classes that just include the legacy one.

But each new (namespaced) classes are implemented like this:

```<code><?php

namespace Twig\Extensions;

require __DIR__.'/../lib/Twig/Extensions/Extension/Text.php';

if (\false) {
    class TextExtension extends \Twig_Extensions_Extension_Text
    {
    }
}
</code>```

What does this notation mean?

答:
```<code>if (\false) {
    class TextExtension extends \Twig_Extensions_Extension_Text
    {
    }
}
</code>```

The code is still reachable by code sniffers and IDEs. However I think it should have deprecation note there. So that developers would be notified about using deprecated classes.

Here is an example from main Twig repository.
https://github.com/twigphp/Twig/blob/v2.10.0/lib/Twig/Token.php

Body:
This morning, I've been notified that a new Twig_Extensions release is available! Yay!

Before integrating it to twigfiddle, I wanted to see changes. This is mainly adding support to namespaces using class_alias function, and then add PSR-4 correspoding classes that just include the legacy one.

But each new (namespaced) classes are implemented like this:

<?php

namespace Twig\Extensions;

require __DIR__.'/../lib/Twig/Extensions/Extension/Text.php';

if (\false) {
    class TextExtension extends \Twig_Extensions_Extension_Text
    {
    }
}

What does this notation mean?

Body:
if (\false) {
    class TextExtension extends \Twig_Extensions_Extension_Text
    {
    }
}

The code is still reachable by code sniffers and IDEs. However I think it should have deprecation note there. So that developers would be notified about using deprecated classes.

Here is an example from main Twig repository.
https://github.com/twigphp/Twig/blob/v2.10.0/lib/Twig/Token.php


问:
Is it possible to print a specific position value from each arrays in php?
I've some array in php. I want to print a specific value from a specific position of each array. For example, If i want to print the second value from each array, so that what's the function for that in php ?</p>

```<code>$firstArray = array("Saif", "Website Development", "Senior");

$secondArray = array("Rifat", 25, "Mentor");

$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");
</code>```

答:
You can approach this by using a custom function OR array_column

```<code>$firstArray = array("Saif", "Website Development", "Senior");
$secondArray = array("Rifat", 25, "Mentor");
$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");
function getValuesByPosition($position, ...$arr){ //Splat operator
    $res=[];
    foreach($arr as $key => $value){
      $res[] = $value[$position];
    }
    return $res;
}
$result = getValuesByPosition(1,$firstArray,$secondArray,$thirdArray);
</code>```

OR

Using array_column as @andreas solution.

Body:
I've some array in php. I want to print a specific value from a specific position of each array. For example, If i want to print the second value from each array, so that what's the function for that in php ?

$firstArray = array("Saif", "Website Development", "Senior");

$secondArray = array("Rifat", 25, "Mentor");

$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");

Body:
You can approach this by using a custom function OR array_column

$firstArray = array("Saif", "Website Development", "Senior");
$secondArray = array("Rifat", 25, "Mentor");
$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");
function getValuesByPosition($position, ...$arr){ //Splat operator
    $res=[];
    foreach($arr as $key => $value){
      $res[] = $value[$position];
    }
    return $res;
}
$result = getValuesByPosition(1,$firstArray,$secondArray,$thirdArray);

OR

Using array_column as @andreas solution.


问:
React build issue, ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js):
I am trying to build react application from scratch using Webpack 4

I am getting following error when I try to build. Whereas babel-core is already installed, I also tried installing @babel/core but it didn't work

```<code>ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
    at Function.Module._resolveFilename (module.js:538:15)
    at Function.Module._load (module.js:468:25)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/digvijay.upadhyay/digvijayu/react_webpack_4_from_scratch/node_modules/babel-loader/lib/index.js:5:15)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src main[1]
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = ./index.html
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 500 bytes {0} [built]
    [./node_modules/lodash/lodash.js] 527 KiB {0} [built]
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 489 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
ℹ ｢wdm｣: Failed to compile.
</code>```

webpack.config.js

```<code>const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [htmlPlugin]
};
</code>```

edit: Added the package json file to the question
package.json

```<code>  "devDependencies": {
        "babel-core": "^6.26.3",
        "babel-loader": "^8.0.0",
        "babel-preset-env": "^1.7.0",
        "babel-preset-react": "^6.24.1",
        "html-webpack-plugin": "^3.2.0",
        "webpack": "^4.17.1",
        "webpack-cli": "^3.1.0",
        "webpack-dev-server": "^3.1.6"
      },
      "dependencies": {
        "@babel/core": "^7.0.0",
        "path": "^0.12.7",
        "react": "^16.4.2",
        "react-dom": "^16.4.2"
      }

{
  "name": "boiler-plate-react-webpack-4",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open --display-error-details",
    "build-dev": "webpack --mode development",
    "build-prod": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.6"
  },
  "dependencies": {
    "@babel/core": "^7.0.0",
    "path": "^0.12.7",
    "react": "^16.4.2",
    "react-dom": "^16.4.2"
  }
}
</code>```

答:
Try to install latest loader.</p>

```<code>   npm install -D babel-loader @babel/core @babel/preset-env OR
   npm install -D babel-loader@latest @babel/core@latest @babel/preset-env@latest
</code>```

Body:
I am trying to build react application from scratch using Webpack 4

I am getting following error when I try to build. Whereas babel-core is already installed, I also tried installing @babel/core but it didn't work

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
    at Function.Module._resolveFilename (module.js:538:15)
    at Function.Module._load (module.js:468:25)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/digvijay.upadhyay/digvijayu/react_webpack_4_from_scratch/node_modules/babel-loader/lib/index.js:5:15)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src main[1]
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = ./index.html
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 500 bytes {0} [built]
    [./node_modules/lodash/lodash.js] 527 KiB {0} [built]
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 489 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
ℹ ｢wdm｣: Failed to compile.

webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [htmlPlugin]
};

edit: Added the package json file to the question
package.json

  "devDependencies": {
        "babel-core": "^6.26.3",
        "babel-loader": "^8.0.0",
        "babel-preset-env": "^1.7.0",
        "babel-preset-react": "^6.24.1",
        "html-webpack-plugin": "^3.2.0",
        "webpack": "^4.17.1",
        "webpack-cli": "^3.1.0",
        "webpack-dev-server": "^3.1.6"
      },
      "dependencies": {
        "@babel/core": "^7.0.0",
        "path": "^0.12.7",
        "react": "^16.4.2",
        "react-dom": "^16.4.2"
      }

{
  "name": "boiler-plate-react-webpack-4",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open --display-error-details",
    "build-dev": "webpack --mode development",
    "build-prod": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.6"
  },
  "dependencies": {
    "@babel/core": "^7.0.0",
    "path": "^0.12.7",
    "react": "^16.4.2",
    "react-dom": "^16.4.2"
  }
}

Body:
Try to install latest loader.

   npm install -D babel-loader @babel/core @babel/preset-env OR
   npm install -D babel-loader@latest @babel/core@latest @babel/preset-env@latest


问:
JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)
```<code>could not read JSON: Can not construct instance of java.util.Date from String
value '2012-07-21 12:11:12': not a valid representation("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
</code>```

passing json request to REST controller method in a POJO class.user should enter only in below datetime format other wise it should throw message.why DateSerializer is not calling?

```<code>add(@Valid @RequestBody User user)
{
}
</code>```

json:

```<code>{
   "name":"ssss",
   "created_date": "2012-07-21 12:11:12"
}
</code>```

pojo class variable

```<code>@JsonSerialize(using=DateSerializer.class)
@Column
@NotNull(message="Please enter a date")
@Temporal(value=TemporalType.TIMESTAMP)
private Date created_date;

public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    logger.info("serialize:"+value);
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    logger.info("DateSerializer formatter:"+formatter.format(value));
    jgen.writeString(formatter.format(value));
}
</code>```

答:
I solved this by using the below steps.

1.In entity class annote it using @JsonDeserialize

```<code>@Entity
@Table(name="table")
public class Table implements Serializable {
// Some code
@JsonDeserialize(using= CustomerDateAndTimeDeserialize.class)
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_ts")
private Date createdTs
}
</code>```

Write CustomDateAndTimeDeserialize.java Sample Code

Body:
could not read JSON: Can not construct instance of java.util.Date from String
value '2012-07-21 12:11:12': not a valid representation("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

passing json request to REST controller method in a POJO class.user should enter only in below datetime format other wise it should throw message.why DateSerializer is not calling?

add(@Valid @RequestBody User user)
{
}

json:

{
   "name":"ssss",
   "created_date": "2012-07-21 12:11:12"
}

pojo class variable

@JsonSerialize(using=DateSerializer.class)
@Column
@NotNull(message="Please enter a date")
@Temporal(value=TemporalType.TIMESTAMP)
private Date created_date;

public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    logger.info("serialize:"+value);
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    logger.info("DateSerializer formatter:"+formatter.format(value));
    jgen.writeString(formatter.format(value));
}

Body:
I solved this by using the below steps.

1.In entity class annote it using @JsonDeserialize

@Entity
@Table(name="table")
public class Table implements Serializable {
// Some code
@JsonDeserialize(using= CustomerDateAndTimeDeserialize.class)
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_ts")
private Date createdTs
}

Write CustomDateAndTimeDeserialize.java Sample Code


问:
How to convert EventCallback<T> to EventCallback<bool>
Blazor has a generic class named EventCallback

How can I cast a

```<code>protected EventCallback<T> ValueChanged { get; set; }
</code>```

to

```<code>EventCallback<bool> BoolChanged
   {
     get
     {
       if (typeof(T) == typeof(bool))
         return ValueChanged; //<== Error needs cast some how?
     }
   }
</code>```

答:
Have you ever try

```<code>(EventCallback<bool>)ValueChanged;
</code>```

Ensure that type of ValueChanged in that case is EventCallback<bool>.

Body:
Blazor has a generic class named EventCallback

How can I cast a

protected EventCallback<T> ValueChanged { get; set; }

to

EventCallback<bool> BoolChanged
   {
     get
     {
       if (typeof(T) == typeof(bool))
         return ValueChanged; //<== Error needs cast some how?
     }
   }

Body:
Have you ever try

(EventCallback<bool>)ValueChanged;

Ensure that type of ValueChanged in that case is EventCallback<bool>.


问:
Unexplained "no such file or directory" in compiled code
The following copied and modified code reads the space bar to activate data capture from attached test equipment.  Without the intervening code summarized below, it runs fine.  I have avoided "using namespace std" by creating a kbrd namespace and using only the standard commands I need. The code compiles without difficulty, but when I run it with the necessary code to capture keyboard data and initialize the test gear, it runs to "Check point Alpha" and waits.  When I hit space bar (or any other key!), it prints:

```<code>Check Point Beta
No such file or directory.
</code>```

Very similar code using the left mouse button to collect data runs as expected.  I am constructing a small computer, using a "paper" display for portable use outdoors, and would like to have code that does not need a mouse...

I have run out of things to try to fix this.  Your help is requested and will be much appreciated.

```<code>    #include <stdlib.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <linux/input.h>
    #include <string.h>
    #include <stdio.h>
    #include <iostream>
    #include <fstream>
    #include <signal.h>
    #include <float.h>
    #include <sa_api.h>
    #pragma comment(lib,"sa_api.lib")
    #undef max
    #undef min

   namespace kbrd{
     const char *dev = "/dev/input/event3";
     struct input_event ev;
     ssize_t n;
     int fd;}

   using std::cin;
   using std::cout;
   using std::__cxx11::string;
   using std::endl;
   using std::ofstream;
   using std::ios;

   int main(void)
   {
    [[Code which
      Initiates equipment API, prompts screen & reads keyboard to
      gather details to be stored with data from attached test
      equipment...]]`

    while (N_az <Num_Samples) {

      kbrd::fd = open(kbrd::dev, O_RDONLY);
      if (kbrd::fd == -1) {
        fprintf(stderr, "Cannot open %s: %s.\n", kbrd::dev,
        strerror(errno));
        return EXIT_FAILURE;
      }
      //and then read keyboard events from the device:
      cout << "Check Point Alpha" << endl;
      while (1) {
        kbrd::n = read(kbrd::fd, &kbrd::ev, sizeof kbrd::ev);
        if (kbrd::n == (ssize_t)-1) {
          if (errno == EINTR)
            continue;
          else
            break;
        } else
        if (kbrd::n != sizeof kbrd::ev) {
          errno = EIO;
          break;
        }
        cout << "Check Point Beta" << endl;

        if (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&&
            kbrd::ev.value <= 2 */&& kbrd::ev.code == 57){
          cout << "Check Point Charlie" << endl;

          continue;

          [[ Code to read attached test gear & store data, one point at a
             time...]]

          N_az = N_az + 1;
        }
        else {
          fflush(stdout);
          fprintf(stderr, "%s.\n", strerror(errno));
          return EXIT_FAILURE;
        }
      }
    }

   return EXIT_SUCCESS;
 }
</code>```

答:
When I hit space bar (or any other key!), it prints:

```<code>Check Point Beta
No such file or directory.
</code>```

because your code is

```<code>   cout << "Check Point Beta" << endl;

   if (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&&
       kbrd::ev.value <= 2 */&& kbrd::ev.code == 57){
     cout << "Check Point Charlie" << endl;
     ...
   }
   else {
     fflush(stdout);
     fprintf(stderr, "%s.\n", strerror(errno));
     return EXIT_FAILURE;
   }
</code>```

that means (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&& kbrd::ev.value <= 2 */&& kbrd::ev.code == 57) is false, No such file or directory is coming from strerror so you have an error somewhere before and probably not in the read, reset errno to 0 before the read. Warning when there is no error errno is not reset to 0, it is only set in case of an error, so it is your responsibility to reset it to 0.

Just temporarily write the values of kbrd::ev.type / kbrd::ev.value / kbrd::ev.code before the test and run your program to know what are the values when you press the space bar allowing you to modify your code in consequence

Body:
The following copied and modified code reads the space bar to activate data capture from attached test equipment.  Without the intervening code summarized below, it runs fine.  I have avoided "using namespace std" by creating a kbrd namespace and using only the standard commands I need. The code compiles without difficulty, but when I run it with the necessary code to capture keyboard data and initialize the test gear, it runs to "Check point Alpha" and waits.  When I hit space bar (or any other key!), it prints:

Check Point Beta
No such file or directory.

Very similar code using the left mouse button to collect data runs as expected.  I am constructing a small computer, using a "paper" display for portable use outdoors, and would like to have code that does not need a mouse...

I have run out of things to try to fix this.  Your help is requested and will be much appreciated.

    #include <stdlib.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <linux/input.h>
    #include <string.h>
    #include <stdio.h>
    #include <iostream>
    #include <fstream>
    #include <signal.h>
    #include <float.h>
    #include <sa_api.h>
    #pragma comment(lib,"sa_api.lib")
    #undef max
    #undef min

   namespace kbrd{
     const char *dev = "/dev/input/event3";
     struct input_event ev;
     ssize_t n;
     int fd;}

   using std::cin;
   using std::cout;
   using std::__cxx11::string;
   using std::endl;
   using std::ofstream;
   using std::ios;

   int main(void)
   {
    [[Code which
      Initiates equipment API, prompts screen & reads keyboard to
      gather details to be stored with data from attached test
      equipment...]]`

    while (N_az <Num_Samples) {

      kbrd::fd = open(kbrd::dev, O_RDONLY);
      if (kbrd::fd == -1) {
        fprintf(stderr, "Cannot open %s: %s.\n", kbrd::dev,
        strerror(errno));
        return EXIT_FAILURE;
      }
      //and then read keyboard events from the device:
      cout << "Check Point Alpha" << endl;
      while (1) {
        kbrd::n = read(kbrd::fd, &kbrd::ev, sizeof kbrd::ev);
        if (kbrd::n == (ssize_t)-1) {
          if (errno == EINTR)
            continue;
          else
            break;
        } else
        if (kbrd::n != sizeof kbrd::ev) {
          errno = EIO;
          break;
        }
        cout << "Check Point Beta" << endl;

        if (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&&
            kbrd::ev.value <= 2 */&& kbrd::ev.code == 57){
          cout << "Check Point Charlie" << endl;

          continue;

          [[ Code to read attached test gear & store data, one point at a
             time...]]

          N_az = N_az + 1;
        }
        else {
          fflush(stdout);
          fprintf(stderr, "%s.\n", strerror(errno));
          return EXIT_FAILURE;
        }
      }
    }

   return EXIT_SUCCESS;
 }

Body:
When I hit space bar (or any other key!), it prints:

Check Point Beta
No such file or directory.

because your code is

   cout << "Check Point Beta" << endl;

   if (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&&
       kbrd::ev.value <= 2 */&& kbrd::ev.code == 57){
     cout << "Check Point Charlie" << endl;
     ...
   }
   else {
     fflush(stdout);
     fprintf(stderr, "%s.\n", strerror(errno));
     return EXIT_FAILURE;
   }

that means (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&& kbrd::ev.value <= 2 */&& kbrd::ev.code == 57) is false, No such file or directory is coming from strerror so you have an error somewhere before and probably not in the read, reset errno to 0 before the read. Warning when there is no error errno is not reset to 0, it is only set in case of an error, so it is your responsibility to reset it to 0.

Just temporarily write the values of kbrd::ev.type / kbrd::ev.value / kbrd::ev.code before the test and run your program to know what are the values when you press the space bar allowing you to modify your code in consequence


问:
Paging UICollectionView by cells, not screen
I have UICollectionView with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining of a cell. With paging enabled, the collection view scrolls the whole page, which is 2 cells at once, and then it stops.

I need to enable scrolling by a single cell, or scrolling by multiple cells with stopping at the edge of the cell.

I tried to subclass UICollectionViewFlowLayout and to implement the method targetContentOffsetForProposedContentOffset, but so far I was only able to break my collection view and it stopped scrolling. Is there any easier way to achieve this and how, or do I really need to implement all methods of UICollectionViewFlowLayout subclass? Thanks.

答:
This is my solution, in Swift 4.2, I wish it could help you.

class SomeViewController: UIViewController {

  private lazy var flowLayout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: /* width */, height: /* height */)
    layout.minimumLineSpacing = // margin
    layout.minimumInteritemSpacing = 0.0
    layout.sectionInset = UIEdgeInsets(top: 0.0, left: /* margin */, bottom: 0.0, right: /* margin */)
    layout.scrollDirection = .horizontal
    return layout
  }()

  private lazy var collectionView: UICollectionView = {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.dataSource = self
    collectionView.delegate = self
    // collectionView.register(SomeCell.self)
    return collectionView
  }()

  private var currentIndex: Int = 0
}

// MARK: - UIScrollViewDelegate

extension SomeViewController {
  func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    guard scrollView == collectionView else { return }

    let pageWidth = flowLayout.itemSize.width + flowLayout.minimumLineSpacing
    currentIndex = Int(scrollView.contentOffset.x / pageWidth)
  }

  func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    guard scrollView == collectionView else { return }

    let pageWidth = flowLayout.itemSize.width + flowLayout.minimumLineSpacing
    var targetIndex = Int(roundf(Float(targetContentOffset.pointee.x / pageWidth)))
    if targetIndex > currentIndex {
      targetIndex = currentIndex + 1
    } else if targetIndex < currentIndex {
      targetIndex = currentIndex - 1
    }
    let count = collectionView.numberOfItems(inSection: 0)
    targetIndex = max(min(targetIndex, count - 1), 0)
    print("targetIndex: \(targetIndex)")

    targetContentOffset.pointee = scrollView.contentOffset
    var offsetX: CGFloat = 0.0
    if targetIndex < count - 1 {
      offsetX = pageWidth * CGFloat(targetIndex)
    } else {
      offsetX = scrollView.contentSize.width - scrollView.width
    }
    collectionView.setContentOffset(CGPoint(x: offsetX, y: 0.0), animated: true)
  }
}
```


问:
Well designed Registration form
I am developing .net application.I need some good looking registraion form using jquery.
please help me.</p>

答:
To build good looking form you need to know:
HTML, CSS, ASP.NET ( in your case ), Javascript (jQuery), Usability and Accessibility. You cannot learn all those in one question.

If you want jQuery Validation which will be hard to make work with ASP.NET so better use ASP.NER build-in validation which validate on client and server side per control

Title: Well designed Registration form


问:
KafkaStreams adding more than 1 processor in Topology not working
I have added multiple processors in my topology. Only 1 processor is working. I am able to receive messages from topic1,topic2 and process them using Processor1 and prod output to topic3-sink. Processor2 is not being called in my code.</p>

```<code>@Component
public class CustomTopology {
    @PostConstruct
    public void createTopology() {
        Topology topology = new Topology();
        topology.addSource("source", new KeyDeserializer(), new ValueDeserializer(), "topic1", "topic2");
        topology.addProcessor("processor1", new CustomProcessorSupplier1(), "source");
        topology.addProcessor("processor2", new CustomProcessorSupplier2(), "processor1");
        topology.addSink("sink", "topic3-sink", "source", "processor2");
        Properties p = new Properties();
        p.put(APPLICATION_ID_CONFIG, "stream1");
        p.put(BOOTSTRAP_SERVERS_CONFIG, KafkaUtil.getBootStrapServers());
        p.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, KeySerde.class);
        p.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, ValueSerde.class);
        KafkaStreams streams = new KafkaStreams(topology, p);
        streams.start();
    }
}

class CustomProcessorSupplier1 implements ProcessorSupplier<Integer, Message> {

    @Override
    public Processor<Integer, Message> get() {
        Processor<Integer, Message> processor = new Processor<Integer, Message>() {
            ...

            @Override
            public void process(Integer key, Message value) {
                value.setName(value.getName() + "ProcessB");
            }

            ...
        };
        return processor;
    }
}

class CustomProcessorSupplier2 implements ProcessorSupplier<Integer, Message> {

    @Override
    public Processor<Integer, Message> get() {
        Processor<Integer, Message> processor = new Processor<Integer, Message>() {
           ...

            @Override
            public void process(Integer key, Message value) {
                value.setName(value.getName() + "ansalProcess");
            }

            ...
        };
        return processor;
    }
}
</code>```

答:
To pass record forward in Processor you have to call ProcessorContext::forward.
This method is overloaded. You can forward all message to all following nodes, but you can also choose subset of nodes to which message will be forwarded.

You have to add to your Processors impementation (CustomProcessorSupplier1 and CustomProcessorSupplier1) context().forward(someKey, someValue);

Your processors doesn't produce message to topic3-sink. Messages appears there because one of parent's nodes is SourceNode (input topics):

```<code>topology.addSink("sink", "topic3-sink", "source", "processor2");
</code>```

Body:
I have added multiple processors in my topology. Only 1 processor is working. I am able to receive messages from topic1,topic2 and process them using Processor1 and prod output to topic3-sink. Processor2 is not being called in my code.

@Component
public class CustomTopology {
    @PostConstruct
    public void createTopology() {
        Topology topology = new Topology();
        topology.addSource("source", new KeyDeserializer(), new ValueDeserializer(), "topic1", "topic2");
        topology.addProcessor("processor1", new CustomProcessorSupplier1(), "source");
        topology.addProcessor("processor2", new CustomProcessorSupplier2(), "processor1");
        topology.addSink("sink", "topic3-sink", "source", "processor2");
        Properties p = new Properties();
        p.put(APPLICATION_ID_CONFIG, "stream1");
        p.put(BOOTSTRAP_SERVERS_CONFIG, KafkaUtil.getBootStrapServers());
        p.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, KeySerde.class);
        p.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, ValueSerde.class);
        KafkaStreams streams = new KafkaStreams(topology, p);
        streams.start();
    }
}

class CustomProcessorSupplier1 implements ProcessorSupplier<Integer, Message> {

    @Override
    public Processor<Integer, Message> get() {
        Processor<Integer, Message> processor = new Processor<Integer, Message>() {
            ...

            @Override
            public void process(Integer key, Message value) {
                value.setName(value.getName() + "ProcessB");
            }

            ...
        };
        return processor;
    }
}

class CustomProcessorSupplier2 implements ProcessorSupplier<Integer, Message> {

    @Override
    public Processor<Integer, Message> get() {
        Processor<Integer, Message> processor = new Processor<Integer, Message>() {
           ...

            @Override
            public void process(Integer key, Message value) {
                value.setName(value.getName() + "ansalProcess");
            }

            ...
        };
        return processor;
    }
}

Body:
To pass record forward in Processor you have to call ProcessorContext::forward.
This method is overloaded. You can forward all message to all following nodes, but you can also choose subset of nodes to which message will be forwarded.

You have to add to your Processors impementation (CustomProcessorSupplier1 and CustomProcessorSupplier1) context().forward(someKey, someValue);

Your processors doesn't produce message to topic3-sink. Messages appears there because one of parent's nodes is SourceNode (input topics):

topology.addSink("sink", "topic3-sink", "source", "processor2");


问:
Cannot change theme dynamically
I'm trying to change the theme of an app dynamically. But I can change it only when the app is alive. Means, when I kill the app and open it again, the default theme is applied.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
        public ArrayList<FTPFile> listfile=null;
        Intent men;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
            String choice=preferences.getString("CurrentTheme",null);

                Toast.makeText(getApplicationContext(),"Its"+ choice,Toast.LENGTH_SHORT).show();
           if(choice=="Light")
               this.setTheme(R.style.AppThemeLight);
           else
               this.setTheme(R.style.AppTheme);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
}
</code>```

AndroidManifest.xml

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity"  android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".file_explorer"  android:theme="@style/AppTheme" />
    <activity android:name=".settings"  android:theme="@style/AppTheme" />
</application>
</code>```

Code that changes value to shared preferences

```<code>SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
Editor editor=preferences.edit();
 RadioGroup rg=findViewById(R.id.radgrp);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.light:
                        Log.d("MRR","Light");
                        editor.putString("CurrentTheme","Light");
                        editor.apply();
                        break;
                    case R.id.dark:
                        Log.d("MRR","Dark");
                        editor.putString("CurrentTheme","Dark");
                        editor.apply();
                }
            }
        });
</code>```

答:
To implementing a dark/night theme, it's better to use the darktheme feature.

The following code is a sample of its implementation:

```<code> boolean isNight = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES

                viewModel.setThemeStatus(isNight) //save the last state of theme
                //to switch between light/dark
                AppCompatDelegate
               .setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES)
</code>```

And in your launcher activity:

```<code>boolean isNight = viewModel.getThemeStatus()

AppCompatDelegate.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES)
</code>```

Title: Cannot change theme dynamically

Body:
I'm trying to change the theme of an app dynamically. But I can change it only when the app is alive. Means, when I kill the app and open it again, the default theme is applied.

MainActivity.java

public class MainActivity extends AppCompatActivity {
        public ArrayList<FTPFile> listfile=null;
        Intent men;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
            String choice=preferences.getString("CurrentTheme",null);

                Toast.makeText(getApplicationContext(),"Its"+ choice,Toast.LENGTH_SHORT).show();
           if(choice=="Light")
               this.setTheme(R.style.AppThemeLight);
           else
               this.setTheme(R.style.AppTheme);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
}

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity"  android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".file_explorer"  android:theme="@style/AppTheme" />
    <activity android:name=".settings"  android:theme="@style/AppTheme" />
</application>

Code that changes value to shared preferences

SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
Editor editor=preferences.edit();
 RadioGroup rg=findViewById(R.id.radgrp);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.light:
                        Log.d("MRR","Light");
                        editor.putString("CurrentTheme","Light");
                        editor.apply();
                        break;
                    case R.id.dark:
                        Log.d("MRR","Dark");
                        editor.putString("CurrentTheme","Dark");
                        editor.apply();
                }
            }
        });

Body:
To implementing a dark/night theme, it's better to use the darktheme feature.

The following code is a sample of its implementation:

 boolean isNight = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES

                viewModel.setThemeStatus(isNight) //save the last state of theme
                //to switch between light/dark
                AppCompatDelegate
               .setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES)

And in your launcher activity:

boolean isNight = viewModel.getThemeStatus()

AppCompatDelegate.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES)


问:
How to upgrade existing Micronaut application to new Micronaut version 1.1.2?
I have been upgrading like this..

```<code>plugins {
    id "io.spring.dependency-management" version "1.0.6.RELEASE"
    id "com.github.johnrengelman.shadow" version "4.0.2"
}

apply plugin:"application"
apply plugin:"groovy"

version "0.1"
group "com.shanky"

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "https://jcenter.bintray.com" }
}

dependencyManagement {
    imports {
        mavenBom 'io.micronaut:micronaut-bom:1.1.2'
    }
}

dependencies {
    compile "io.micronaut:micronaut-runtime-groovy"
    compile "io.micronaut:micronaut-validation"
    compile "io.micronaut:micronaut-http-client"
    compile "io.micronaut:micronaut-http-server-netty"
    compileOnly "io.micronaut:micronaut-inject-groovy"
    runtime "ch.qos.logback:logback-classic:1.2.3"
    testCompile "io.micronaut:micronaut-inject-groovy"
    testCompile("org.spockframework:spock-core") {
        exclude group: "org.codehaus.groovy", module: "groovy-all"
    }
    compile 'io.micronaut:micronaut-views'
    runtime 'org.thymeleaf:thymeleaf:3.0.11.RELEASE'
    compile "io.micronaut.configuration:micronaut-hibernate-validator"
    compile "io.micronaut.configuration:micronaut-hibernate-gorm"
    runtime 'org.postgresql:postgresql:42.2.5'
    annotationProcessor "io.micronaut:micronaut-security"
    compile "io.micronaut:micronaut-security"
    compile "io.micronaut:micronaut-security-session"
    runtime "org.hibernate:hibernate-ehcache:5.1.9.Final"
}

shadowJar {
    mergeServiceFiles()
}

run.jvmArgs('-noverify', '-XX:TieredStopAtLevel=1')

mainClassName = "com.shanky.Application"

tasks.withType(GroovyCompile) {
    groovyOptions.forkOptions.jvmArgs.add('-Dgroovy.parameters=true')
}
</code>```

So far this is my build.gradle file. I have updated mavenBom to upgrade Micronaut version. I've create a dummy project with Micronaut version 1.1.2 just to differentiate build.gradle file. I don't see any major difference in between them.
Any help would be appreciated

答:
But it is not upgrading.

That is unlikely to be correct.  It may be that you aren't seeing the effect of that change in your IDE if the IDE is out of sync with your Gradle build but changing that version number in build.gradle does in fact upgrade the project.

Body:
I have been upgrading like this..

plugins {
    id "io.spring.dependency-management" version "1.0.6.RELEASE"
    id "com.github.johnrengelman.shadow" version "4.0.2"
}

apply plugin:"application"
apply plugin:"groovy"

version "0.1"
group "com.shanky"

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "https://jcenter.bintray.com" }
}

dependencyManagement {
    imports {
        mavenBom 'io.micronaut:micronaut-bom:1.1.2'
    }
}

dependencies {
    compile "io.micronaut:micronaut-runtime-groovy"
    compile "io.micronaut:micronaut-validation"
    compile "io.micronaut:micronaut-http-client"
    compile "io.micronaut:micronaut-http-server-netty"
    compileOnly "io.micronaut:micronaut-inject-groovy"
    runtime "ch.qos.logback:logback-classic:1.2.3"
    testCompile "io.micronaut:micronaut-inject-groovy"
    testCompile("org.spockframework:spock-core") {
        exclude group: "org.codehaus.groovy", module: "groovy-all"
    }
    compile 'io.micronaut:micronaut-views'
    runtime 'org.thymeleaf:thymeleaf:3.0.11.RELEASE'
    compile "io.micronaut.configuration:micronaut-hibernate-validator"
    compile "io.micronaut.configuration:micronaut-hibernate-gorm"
    runtime 'org.postgresql:postgresql:42.2.5'
    annotationProcessor "io.micronaut:micronaut-security"
    compile "io.micronaut:micronaut-security"
    compile "io.micronaut:micronaut-security-session"
    runtime "org.hibernate:hibernate-ehcache:5.1.9.Final"
}

shadowJar {
    mergeServiceFiles()
}

run.jvmArgs('-noverify', '-XX:TieredStopAtLevel=1')

mainClassName = "com.shanky.Application"

tasks.withType(GroovyCompile) {
    groovyOptions.forkOptions.jvmArgs.add('-Dgroovy.parameters=true')
}

So far this is my build.gradle file. I have updated mavenBom to upgrade Micronaut version. I've create a dummy project with Micronaut version 1.1.2 just to differentiate build.gradle file. I don't see any major difference in between them.
Any help would be appreciated


问:
Reverse factorial fun won't go beyond 170
I am a beginner at pyhon and I'm trying to reverse the factorial function.
The factorial of 5 is 120
And I want my code to take input 120 and be able to return 5
Here's my present code:

```<code>`from math import factorial
    def rf(f):
        d=2
        while f/factorial(d) != 1:
            if f/factorial(d) <= 1:
                 print("Entered number is not a factorial")
                 return
            d += 1
        return int(d)`
</code>```

It can reverse the factorial upto 170.But when I enter the factorial of 171 the code gets into OverFlowError.
Is there a solution to my code?
or, a more reliable code to reverse factorial.

答:
The immediate problem is that you're using floating-point math, and floating-point math has limited range:

```<code>>>> sys.float_info.max
1.7976931348623157e+308
</code>```

(170! is smaller than this, but 171! is larger.)

If you stick to integer math, you'll sidestep that problem since Python integers are only limited by the amount of available memory and so can grow much larger.

It's also worth noting that repeatedly calling factorial() is expensive.

If it were me, I'd do something like this:

```<code>def rf(f):
  n = 2
  while True:
    f, r = divmod(f, n)
    if r != 0:
      return None  # input isn't a factorial
    if f == 1:
      return n
    n += 1

print(rf(6))
print(rf(42))
print(rf(200896062499134299656951336898466838917540340798867777940435335160044860953395980941180138112097309735631594101037399609671032132186331495273609598531966730972945653558819806475064353856858157445040809209560358463319644664891114256430017824141796753818192338642302693327818731986039603200000000000000000000000000000000000000000000))
</code>```

This divides the input by 2 then 3 then 4 etc until the result is 1, while making sure that the remainder stays zero throughout.

I've used divmod to simultaneously compute the quotient and the remainder of each division step.

Body:
I am a beginner at pyhon and I'm trying to reverse the factorial function.
The factorial of 5 is 120
And I want my code to take input 120 and be able to return 5
Here's my present code:

`from math import factorial
    def rf(f):
        d=2
        while f/factorial(d) != 1:
            if f/factorial(d) <= 1:
                 print("Entered number is not a factorial")
                 return
            d += 1
        return int(d)`

It can reverse the factorial upto 170.But when I enter the factorial of 171 the code gets into OverFlowError.
Is there a solution to my code?
or, a more reliable code to reverse factorial.

Body:
The immediate problem is that you're using floating-point math, and floating-point math has limited range:

>>> sys.float_info.max
1.7976931348623157e+308

(170! is smaller than this, but 171! is larger.)

If you stick to integer math, you'll sidestep that problem since Python integers are only limited by the amount of available memory and so can grow much larger.

It's also worth noting that repeatedly calling factorial() is expensive.

If it were me, I'd do something like this:

def rf(f):
  n = 2
  while True:
    f, r = divmod(f, n)
    if r != 0:
      return None  # input isn't a factorial
    if f == 1:
      return n
    n += 1

print(rf(6))
print(rf(42))
print(rf(200896062499134299656951336898466838917540340798867777940435335160044860953395980941180138112097309735631594101037399609671032132186331495273609598531966730972945653558819806475064353856858157445040809209560358463319644664891114256430017824141796753818192338642302693327818731986039603200000000000000000000000000000000000000000000))

This divides the input by 2 then 3 then 4 etc until the result is 1, while making sure that the remainder stays zero throughout.

I've used divmod to simultaneously compute the quotient and the remainder of each division step.


问:
How to make pagination in the REST service?
I have to write some REST service which should handle a million entries and return a response to the user in JSON format. I'm writing some REST-controller using Spring and make pagination.

```<code>public List<ContactDto> getAllContacts() {

        double countItems = contactRepo.count();
        int pages = (int) Math.ceil(countItems / totalItemsPerPage);

        List<Contact> contacts = new ArrayList<>();
        for (int i = 0; i < pages; i++) {
            Page<Contact> page = contactRepo.findAll(PageRequest.of(i, totalItemsPerPage));
            contacts.addAll(page.stream().collect(Collectors.toList()));
        }

        return contacts.stream()
                .map(entity -> new ContactDto(entity.getId(), entity.getName()))
                .collect(Collectors.toList());
    }
</code>```

I'm new in spring and pagination.

In this approach is have a sense or I'm doing something wrong?

I mean I want to know I'm using pagination write or wrong?

Thanks for the help!

答:
It seems that you are collecting all the Contacts from all the pages and that does not make sense as you are storing all the data in memory negating all the lazy loading benefints.

I would suggest the following:

1.Rest controller should be able to accept pageNumber and pageSize arguments:

```<code>@GetMapping(value="/uri/{pageNumber}/{pageSize}")
public List<Contact> getContactsPage(@PathVariable("pageNumber") final Integer pageNumber, @PathVariable("pageSize") final Integer pageSize) {
//service or repository call
}
</code>```

2.Repository interface should extent PagingAndSortingRepository:

```<code>public interface ContactRepository extends PagingAndSortingRepository<Contact, Long> {
    Page<Contact> fingAll(Pageable pageable);
}
</code>```

3.In your service or in controller directly create a Pageable object and pass it as ContactRepository#fingAll() argument:

```<code>final Pageable contactsPageable = PageRequest.of(pageNumber, pageSize);
</code>```

4.Map Page to DTO if necessary.

Body:
I have to write some REST service which should handle a million entries and return a response to the user in JSON format. I'm writing some REST-controller using Spring and make pagination.

public List<ContactDto> getAllContacts() {

        double countItems = contactRepo.count();
        int pages = (int) Math.ceil(countItems / totalItemsPerPage);

        List<Contact> contacts = new ArrayList<>();
        for (int i = 0; i < pages; i++) {
            Page<Contact> page = contactRepo.findAll(PageRequest.of(i, totalItemsPerPage));
            contacts.addAll(page.stream().collect(Collectors.toList()));
        }

        return contacts.stream()
                .map(entity -> new ContactDto(entity.getId(), entity.getName()))
                .collect(Collectors.toList());
    }

I'm new in spring and pagination.

In this approach is have a sense or I'm doing something wrong?

I mean I want to know I'm using pagination write or wrong?

Thanks for the help!

Body:
It seems that you are collecting all the Contacts from all the pages and that does not make sense as you are storing all the data in memory negating all the lazy loading benefints.

I would suggest the following:

1.Rest controller should be able to accept pageNumber and pageSize arguments:

@GetMapping(value="/uri/{pageNumber}/{pageSize}")
public List<Contact> getContactsPage(@PathVariable("pageNumber") final Integer pageNumber, @PathVariable("pageSize") final Integer pageSize) {
//service or repository call
}

2.Repository interface should extent PagingAndSortingRepository:

public interface ContactRepository extends PagingAndSortingRepository<Contact, Long> {
    Page<Contact> fingAll(Pageable pageable);
}

3.In your service or in controller directly create a Pageable object and pass it as ContactRepository#fingAll() argument:

final Pageable contactsPageable = PageRequest.of(pageNumber, pageSize);

4.Map Page to DTO if necessary.