问:
Too many open files on a project using spring-cloud stream and kafka after upgrade to 2.1
After upgrade to spring cloud stream 2.1 on a project using multi binder kafka(2 brokers) and rabbit(1 broker) we are facing too many open files problem.

The number of files opened keeps growing to the limit defined by the os(redhat 7.3).

I use the actuator endpoint to monitor:
/actuator/metrics/process.files.open

```<code>{
"name": "process.files.open",
"description": "The open file descriptor count",
"baseUnit": "files",
"measurements": [
{
"statistic": "VALUE",
"value": 1686
}

]
}
</code>```

Using the version 2.0 of spring cloud stream the problem is not observed, the number of open files is stable aroun 80 files.
Using the exact following versions:

```<code> +- org.springframework.cloud:spring-cloud-stream-binder-kafka-core:jar:2.0.0.RELEASE:compile
[INFO] |  |  \- org.springframework.integration:spring-integration-kafka:jar:3.0.3.RELEASE:compile
[INFO] |  +- org.apache.kafka:kafka-clients:jar:1.0.2:compile
[INFO] |  |  +- org.lz4:lz4-java:jar:1.4:compile
[INFO] |  |  \- org.xerial.snappy:snappy-java:jar:1.1.4:compile
[INFO] |  \- org.springframework.kafka:spring-kafka:jar:2.1.10.RELEASE:compile
</code>```

I'm suspecting that the upgrade to kafka-client 2.0.0 is the potential issue.

In a first attempt I wanted to try the spring cloud stream 2.1 with kafka-clients 1.0.2, according to docs it's possible but I'm facing an issue.
Here's my maven configuration with exclusion:

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-binder-kafka</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-kafka</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>1.0.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-kafka</artifactId>
    <version>3.1.0.RELEASE</version>
</dependency>
</code>```

I'm having the following error:

```<code>java.lang.NoSuchMethodError: org.apache.kafka.clients.consumer.Consumer.poll(Ljava/time/Duration;)Lorg/apache/kafka/clients/consumer/ConsumerRecords;
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:741)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:698)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

Any idea about too many open files and how to diagnose?
How can I test with downgraded kafka clients?

Thanks for you help.

答:
java.lang.NoSuchMethodError: org.apache.kafka.clients.consumer.Consumer.poll(Ljava/time/Duration;)Lorg/apache/kafka/clients/consumer/ConsumerRecords;

spring-kafka 2.2.x needs 2.0.1 kafka-clients or later.

Body:
After upgrade to spring cloud stream 2.1 on a project using multi binder kafka(2 brokers) and rabbit(1 broker) we are facing too many open files problem.

The number of files opened keeps growing to the limit defined by the os(redhat 7.3).

I use the actuator endpoint to monitor:
/actuator/metrics/process.files.open

{
"name": "process.files.open",
"description": "The open file descriptor count",
"baseUnit": "files",
"measurements": [
{
"statistic": "VALUE",
"value": 1686
}

]
}

Using the version 2.0 of spring cloud stream the problem is not observed, the number of open files is stable aroun 80 files.
Using the exact following versions:

 +- org.springframework.cloud:spring-cloud-stream-binder-kafka-core:jar:2.0.0.RELEASE:compile
[INFO] |  |  \- org.springframework.integration:spring-integration-kafka:jar:3.0.3.RELEASE:compile
[INFO] |  +- org.apache.kafka:kafka-clients:jar:1.0.2:compile
[INFO] |  |  +- org.lz4:lz4-java:jar:1.4:compile
[INFO] |  |  \- org.xerial.snappy:snappy-java:jar:1.1.4:compile
[INFO] |  \- org.springframework.kafka:spring-kafka:jar:2.1.10.RELEASE:compile

I'm suspecting that the upgrade to kafka-client 2.0.0 is the potential issue.

In a first attempt I wanted to try the spring cloud stream 2.1 with kafka-clients 1.0.2, according to docs it's possible but I'm facing an issue.
Here's my maven configuration with exclusion:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-binder-kafka</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-kafka</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>1.0.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-kafka</artifactId>
    <version>3.1.0.RELEASE</version>
</dependency>

I'm having the following error:

java.lang.NoSuchMethodError: org.apache.kafka.clients.consumer.Consumer.poll(Ljava/time/Duration;)Lorg/apache/kafka/clients/consumer/ConsumerRecords;
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:741)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:698)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.lang.Thread.run(Thread.java:834)

Any idea about too many open files and how to diagnose?
How can I test with downgraded kafka clients?

Thanks for you help.


来源: stackexchange

问:
Using Awk to find Unique chars bought by a customer
I have log files like this (it's only space between them but for readibility i changed that) :

```<code>Customer  Car             Bought
François  Nissan Pajero   28/05/2016
Matthew   Mercedes S      10/01/2019
Andrew    Peugeot 508     05/0/2000
Matthew   Toyota Hilux    02/10/2012
</code>```

I need to make an awk script which display for each customer what car he has bought like this :

```<code>Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
Francois, car bought: Nissan Pjero, number of cars: 1
</code>```

I'm not able to know how to do it.

I think i should create an array for Customer and one for the car and indexed it with the number of line

```<code>awk ' { Customer[NR]=$1; Car[NR]=$2} END {}'
</code>```

What should i add in the END, i'm little perplexed

I thought doing this also:

```<code>awk ' { Customer[$1]=$2} END { for (i in Customer) print i,Customer[i]}'
</code>```

The problem with this array, it will destroy the previous value of the car in the Customer indexed array.

答:
Assuming that each customer really does have a 1-word name as shown in your example and implied by your code (if not then we'd use fixed-width field parsing to identify the fields - see https://stackoverflow.com/a/31947741/1745001):

```<code>$ cat tst.awk
NR>1 {
    gsub(/^[[:space:]]+|[[:space:]]+$/,"")
    cust = $1
    gsub(/^[^[:space:]]+[[:space:]]+|[[:space:]]+[^[:space:]]+$/,"")
    cars[cust,++numCars[cust]] = $0
    custs[cust]
}
END {
    for (cust in custs) {
        printf "%s, car bought: ", cust
        for (carNr=1; carNr<=numCars[cust]; carNr++) {
            printf "%s,", cars[cust,carNr]
        }
        printf " number of cars: %d\n", numCars[cust]
    }
}

$ awk -f tst.awk file
Andrew, car bought: Peugeot 508, number of cars: 1
Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
François, car bought: Nissan Pajero, number of cars: 1
</code>```

With the above if a given customer buys the same type of car (e.g. Peugeot 508) on multiple dates they will all be listed/counted in the output.

ContentLicense: CC BY-SA 4.0

Body:
I have log files like this (it's only space between them but for readibility i changed that) :

Customer  Car             Bought
François  Nissan Pajero   28/05/2016
Matthew   Mercedes S      10/01/2019
Andrew    Peugeot 508     05/0/2000
Matthew   Toyota Hilux    02/10/2012

I need to make an awk script which display for each customer what car he has bought like this :

Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
Francois, car bought: Nissan Pjero, number of cars: 1

I'm not able to know how to do it.

I think i should create an array for Customer and one for the car and indexed it with the number of line

awk ' { Customer[NR]=$1; Car[NR]=$2} END {}'

What should i add in the END, i'm little perplexed

I thought doing this also:

awk ' { Customer[$1]=$2} END { for (i in Customer) print i,Customer[i]}'

The problem with this array, it will destroy the previous value of the car in the Customer indexed array.

Body:
Assuming that each customer really does have a 1-word name as shown in your example and implied by your code (if not then we'd use fixed-width field parsing to identify the fields - see https://stackoverflow.com/a/31947741/1745001):

$ cat tst.awk
NR>1 {
    gsub(/^[[:space:]]+|[[:space:]]+$/,"")
    cust = $1
    gsub(/^[^[:space:]]+[[:space:]]+|[[:space:]]+[^[:space:]]+$/,"")
    cars[cust,++numCars[cust]] = $0
    custs[cust]
}
END {
    for (cust in custs) {
        printf "%s, car bought: ", cust
        for (carNr=1; carNr<=numCars[cust]; carNr++) {
            printf "%s,", cars[cust,carNr]
        }
        printf " number of cars: %d\n", numCars[cust]
    }
}

$ awk -f tst.awk file
Andrew, car bought: Peugeot 508, number of cars: 1
Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
François, car bought: Nissan Pajero, number of cars: 1

With the above if a given customer buys the same type of car (e.g. Peugeot 508) on multiple dates they will all be listed/counted in the output.


问:
Error while unit test - TypeError: Cannot read property 'cityWeather' of undefined
In Component.ts,

```<code>this.dataService.currentCity.subscribe(info => {
  this.cities = info;
});

this.dataService.currentSelectedCity.subscribe(index => {
  this.selectedCityIndex = index;
});

this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
</code>```

I am trying to test this piece of code in ngOnInit(). But I am unsure how to test this code. Here, my other component is sending me an array of objects and also the index of the selected item using Behavior subject to which I am subscribing in this component's `ngOnInit(). And trying to access cityWeather property in the selected object.

In Spec.ts I am tried something like this which I am sure is not a correct way of testing this.

```<code>it("should handle ngOnInit", async(() => {
        let response;
        const dataService = fixture.debugElement.injector.get(DataService);
        spyOn(dataService, 'currentCity').and.returnValue(of(response));
        component.ngOnInit();
        expect(component.cities).toEqual(response);
    }));
</code>```

When I run the application, I am getting the output but when I test ngoninit function then I am not getting the response from subscribe. I am getting the below error. Failed: Cannot read property 'cityWeather' of undefined TypeError: Cannot read property 'cityWeather' of undefined

In data.service.ts

```<code>private citySubject = new BehaviorSubject<any>('');
currentCity = this.citySubject.asObservable();
private selectedCity = new BehaviorSubject<any>('');
currentSelectedCity= this.selectedCitySubject.asObservable();

sendCityWeatherInfo(info,index) {
  this.citySubject.next(info);
  this.selectedCitySubject.next(index);
}
</code>```

I am calling this in a component like this (passing an array of objects and index)

```<code>this.dataService.sendCityWeatherInfo(this.cities, index);
</code>```

答:
Since you are dealing with observable streams which are asynchronous in nature,
this.cities and this.selectedCityIndex can get updated in unknown order or at unknown time.

Therefore, the following synchronous code falls pray to chance of dealing with undefined values.

```<code>this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
</code>```

For example, when you try to assign this.selectedCityInfo, this.cities or this.selectedCityIndex could be undefined and the assignment would fail.
What is more, in your service you initialise both of your behaviour subjects with empty strings.. which is of different data type.

This sort of design is inviting various problems and unexpected behaviours.
I would suggest to steer clear of architecting your dataflow in this way.

Instead, I'd suggest to either combine both observables in one subscription by using combineLatest function, or refactoring bits the following way:

Since in your service updateSelectedCity method you emit from both observables at the same time, perhaps (if it fits your application) it would be easier to emit both values in a single observable? Then we would know that both values definitely arrive and we can do this.selectedCityInfo and this.selectedCityWeatherList assignments in subscribe callback function.

In service:

```<code>/* you can keep private property and recast it to Observable,
but you can also subscribe to Subjects and BehaviorSubjects directly
since they extend Observable class.
So that's what I'm doing here */

cityWeatherInfo$ =  = new BehaviorSubject<any>({ info: null, index: null });

sendCityWeatherInfo(info,index) {
  this.cityWeatherInfo$.next({ info, index });

}
</code>```

In component:

```<code>this.dataService.cityWeatherInfo$
  .subscribe(({ info, index }) => {
    if (info !== null && index !== null) {
      this.cities = info;
      this.selectedCityIndex = index;
      this.selectedCityInfo = this.cities[this.selectedCityIndex];
      this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
    }
  });

</code>```

P.S. I don't know all your app's requirements, but perhaps you can use simple Subject instead of BehaviorSubject in your service. That way it wouldn't emit initial null values and if (info !== null && index !== null) check would not be necessary.

Body:
In Component.ts,

this.dataService.currentCity.subscribe(info => {
  this.cities = info;
});

this.dataService.currentSelectedCity.subscribe(index => {
  this.selectedCityIndex = index;
});

this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;

I am trying to test this piece of code in ngOnInit(). But I am unsure how to test this code. Here, my other component is sending me an array of objects and also the index of the selected item using Behavior subject to which I am subscribing in this component's `ngOnInit(). And trying to access cityWeather property in the selected object.

In Spec.ts I am tried something like this which I am sure is not a correct way of testing this.

it("should handle ngOnInit", async(() => {
        let response;
        const dataService = fixture.debugElement.injector.get(DataService);
        spyOn(dataService, 'currentCity').and.returnValue(of(response));
        component.ngOnInit();
        expect(component.cities).toEqual(response);
    }));

When I run the application, I am getting the output but when I test ngoninit function then I am not getting the response from subscribe. I am getting the below error. Failed: Cannot read property 'cityWeather' of undefined TypeError: Cannot read property 'cityWeather' of undefined

In data.service.ts

private citySubject = new BehaviorSubject<any>('');
currentCity = this.citySubject.asObservable();
private selectedCity = new BehaviorSubject<any>('');
currentSelectedCity= this.selectedCitySubject.asObservable();

sendCityWeatherInfo(info,index) {
  this.citySubject.next(info);
  this.selectedCitySubject.next(index);
}

I am calling this in a component like this (passing an array of objects and index)

this.dataService.sendCityWeatherInfo(this.cities, index);

Body:
Since you are dealing with observable streams which are asynchronous in nature,
this.cities and this.selectedCityIndex can get updated in unknown order or at unknown time.

Therefore, the following synchronous code falls pray to chance of dealing with undefined values.

this.selectedCityInfo = this.cities[this.selectedCityIndex];
this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;

For example, when you try to assign this.selectedCityInfo, this.cities or this.selectedCityIndex could be undefined and the assignment would fail.
What is more, in your service you initialise both of your behaviour subjects with empty strings.. which is of different data type.

This sort of design is inviting various problems and unexpected behaviours.
I would suggest to steer clear of architecting your dataflow in this way.

Instead, I'd suggest to either combine both observables in one subscription by using combineLatest function, or refactoring bits the following way:

Since in your service updateSelectedCity method you emit from both observables at the same time, perhaps (if it fits your application) it would be easier to emit both values in a single observable? Then we would know that both values definitely arrive and we can do this.selectedCityInfo and this.selectedCityWeatherList assignments in subscribe callback function.

In service:

/* you can keep private property and recast it to Observable,
but you can also subscribe to Subjects and BehaviorSubjects directly
since they extend Observable class.
So that's what I'm doing here */

cityWeatherInfo$ =  = new BehaviorSubject<any>({ info: null, index: null });

sendCityWeatherInfo(info,index) {
  this.cityWeatherInfo$.next({ info, index });

}

In component:

this.dataService.cityWeatherInfo$
  .subscribe(({ info, index }) => {
    if (info !== null && index !== null) {
      this.cities = info;
      this.selectedCityIndex = index;
      this.selectedCityInfo = this.cities[this.selectedCityIndex];
      this.selectedCityWeatherList = this.selectedCityInfo.cityWeather.list;
    }
  });

P.S. I don't know all your app's requirements, but perhaps you can use simple Subject instead of BehaviorSubject in your service. That way it wouldn't emit initial null values and if (info !== null && index !== null) check would not be necessary.


问:
Color of status bar icons in Dialog's Window
This is the code which I use for changing color of status bar icon:

```<code>window.decorView.systemUiVisibility = if (light) {
    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
} else {
    View.SYSTEM_UI_FLAG_VISIBLE
}
</code>```

Unfortunately it does not work for Window object of a Dialog. Any idea why?

EDIT: It is not a duplicate of Android statusbar icons color - the link SO thread doesn't mention Dialogs

答: The problem was that I was executing this code from DialogFragment.onStart and I should call it from onResume

Body:
This is the code which I use for changing color of status bar icon:

window.decorView.systemUiVisibility = if (light) {
    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
} else {
    View.SYSTEM_UI_FLAG_VISIBLE
}

Unfortunately it does not work for Window object of a Dialog. Any idea why?

EDIT: It is not a duplicate of Android statusbar icons color - the link SO thread doesn't mention Dialogs


问:
how to save multiple ckeditor in php?
I have create a multiple ckeditor in php, it can display the panel of ckeditor correctly, but when I click update after adding something in it, it didn't save to the database.</p>

```<code><?php
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$id = $_POST['id'];

$content = $_POST['content'];

$query_update = "UPDATE `correspond` SET content='$content' WHERE id='$id'";

mysql_query($query_update);

header("Location: correspond.php");
}
?>

<table>
<?php while($row_correspond_result=mysql_fetch_assoc($correspond_result)){ ?>
<tr class="table table-bordered table-striped"><form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center"><div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?>        </div>
<script>
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}});
</script>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>

</form></tr><?php }?> </tbody></table>
</code>```

答:
To save multiple ckeditor, you have need to pass the name attribute in array format. when you click on submit save the content value using the serialize function.

PHP code.

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST["action"])&&($_POST["action"]=="update")){
    $content = $id = '';
    $form_data = $_POST['form_data'];
    for($i=0 ; $i<count($form_data['id']); $i++){
        $content = serialize($form_data['content'][$i]);
        $id = $form_data['id'][$i];
        $query_update = "UPDATE correspond SET content='$content' WHERE id= $id";
        mysqli_query($conn, $query_update);
    }
    //header("Location: correspond.php");
}
?>
</code>```

At the time of display unserialize content value and put in textarea field.

HTML Code.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.11.4/standard/ckeditor.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
     CKEDITOR.replace( elements[ i ]);
    //CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}
});
</script>

<table>
<tr class="table table-bordered table-striped">
<form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center">

<?php
$sql = "SELECT id, content FROM correspond";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
while($row = $result->fetch_assoc()) {
    //get the content form database and use unserialize method
    $content = unserialize($row["content"]);
?>

<!-- Change div to textarea and use the name attr as array format -->
<textarea contenteditable="true" class="myContent" name="form_data[content][]" id="content"><?php echo $content;?> </textarea>
<!-- add the corresponding id to update the content. -->
<input type="hidden" name = "form_data[id][]" value ="<?php echo $row["id"];?> ">
<?php
}
}
?>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>

</form></tr></tbody></table>
</code>```

Title: how to save multiple ckeditor in php?

Body:
I have create a multiple ckeditor in php, it can display the panel of ckeditor correctly, but when I click update after adding something in it, it didn't save to the database.

<?php
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$id = $_POST['id'];

$content = $_POST['content'];

$query_update = "UPDATE `correspond` SET content='$content' WHERE id='$id'";

mysql_query($query_update);

header("Location: correspond.php");
}
?>

<?php while($row_correspond_result=mysql_fetch_assoc($correspond_result)){ ?>

<form action="" method="POST" name="correspond_form" id="correspond_formJoin">

<?php echo $row_correspond_result["content"];?>

<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update">

</form>
<?php }?>

Body:
To save multiple ckeditor, you have need to pass the name attribute in array format. when you click on submit save the content value using the serialize function.

PHP code.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST["action"])&&($_POST["action"]=="update")){
    $content = $id = '';
    $form_data = $_POST['form_data'];
    for($i=0 ; $i<count($form_data['id']); $i++){
        $content = serialize($form_data['content'][$i]);
        $id = $form_data['id'][$i];
        $query_update = "UPDATE correspond SET content='$content' WHERE id= $id";
        mysqli_query($conn, $query_update);
    }
    //header("Location: correspond.php");
}
?>

At the time of display unserialize content value and put in textarea field.

HTML Code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.11.4/standard/ckeditor.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
     CKEDITOR.replace( elements[ i ]);
    //CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}
});
</script>

<table>
<tr class="table table-bordered table-striped">
<form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center">

<?php
$sql = "SELECT id, content FROM correspond";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
while($row = $result->fetch_assoc()) {
    //get the content form database and use unserialize method
    $content = unserialize($row["content"]);
?>

<!-- Change div to textarea and use the name attr as array format -->
<textarea contenteditable="true" class="myContent" name="form_data[content][]" id="content"><?php echo $content;?> </textarea>
<!-- add the corresponding id to update the content. -->
<input type="hidden" name = "form_data[id][]" value ="<?php echo $row["id"];?> ">
<?php
}
}
?>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>

</form></tr></tbody></table>


问:
Cordova InAppBrowser plugin broken for OSX platform
When compiling a cordova macos app with the InAppBrowser plugin installed under Mojave 10.14.2 and Xcode 10.1 I get the following error message:

ERROR: Plugin 'InAppBrowser' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml

I've checked the config.xml, and it contains the correct entry:

```<code><plugin name="cordova-plugin-inappbrowser" spec="^3.0.0" />
</code>```

I've looked in /plugins and the plugin and its xml file are there.

I've removed and added the plugin and the platform.

Taking a cue from this old (and marked fixed) bug, I manually inserted the following into the config.xml file in Xcode:

```<code>    <feature name="InAppBrowser">
    <param name="osx-package" value="CDVDevice" />
</feature>
</code>```

That changes the error message to this:

ERROR: Method 'open:' not defined in Plugin 'InAppBrowser'

Any ideas what's going on here?

答:
```<code><platform name="osx">
    ...
    <feature name="InAppBrowser">
        <param name="osx-package" value="CDVInAppBrowser" />
    </feature>
    ...
</platform>
</code>```

This works for me.

Body:
When compiling a cordova macos app with the InAppBrowser plugin installed under Mojave 10.14.2 and Xcode 10.1 I get the following error message:

ERROR: Plugin 'InAppBrowser' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml

I've checked the config.xml, and it contains the correct entry:

<plugin name="cordova-plugin-inappbrowser" spec="^3.0.0" />

I've looked in /plugins and the plugin and its xml file are there.

I've removed and added the plugin and the platform.

Taking a cue from this old (and marked fixed) bug, I manually inserted the following into the config.xml file in Xcode:

    <feature name="InAppBrowser">
    <param name="osx-package" value="CDVDevice" />
</feature>

That changes the error message to this:

ERROR: Method 'open:' not defined in Plugin 'InAppBrowser'

Any ideas what's going on here?

Body:
<platform name="osx">
    ...
    <feature name="InAppBrowser">
        <param name="osx-package" value="CDVInAppBrowser" />
    </feature>
    ...
</platform>

This works for me.


问:
Users dissapear when I sort a doubly-linked list using quicksort
I have a doubly-linked list and I want to sort the users by their ELO.

The problem is that when the function swap() is called, some users dissapear

This is what I get in my console:
https://imgur.com/a/pJSPSnW

As you can see, the first swap (between players 1 and 2) is done correctly.
But, when it swaps players 3 and 4, user1 dissapears.

I think that the problem is inside the function swap(), but I can't figure out where exactly

Code:
User/Node declaration

```<code>struct user {
public:
    string username;
    float ELO = NULL; //Score of the user
    user* next = nullptr;
    user* previous = nullptr;
};
</code>```

QuickSortRecursive function

```<code> void ELOManager::_quickSortRecursive(user* low, user* high) {
    if (high != nullptr && low != high && low != nullptr) {
        user* p = partition(low, high);
        _quickSortRecursive(low, p->previous);
        _quickSortRecursive(p->next, high);
    }
}
</code>```

QuickSort function

```<code>void ELOManager::quickSort(){
    _quickSortRecursive(first, last);
}
</code>```

Partition function

```<code>    user* ELOManager::partition(user* low, user* high) {
    float pivot = high->ELO;

    user* i = low->previous;

    for (user* j = low; j != high && j!=nullptr; j = j->next) {
        if (j->ELO <= pivot){
            i = (i == NULL) ? low : i->next;

            swap(i, j);
        }
    }
    //i = (i == NULL) ? low : i->next;
    swap(i->next, high);
    cout << endl << "Loop finished -----------------------" << endl;
    printUsers();
    return i;
}
</code>```

Swap function

```<code>    void ELOManager::swap(user* A, user* B) {
    user* tmp = new user();
    user* swapperVector[4];

    cout << endl << "swap1[" << A->username << "]" << endl;
    cout << "swap2[" << B->username << "]" << endl;

    if (A == B) {
        cout << "Same Users: Continue" << endl;
        return;
    }

    swapperVector[0] = A->previous;
    swapperVector[1] = B->previous;
    swapperVector[2] = A->next;
    swapperVector[3] = B->next;

    if (areTheyNeighbours(A, B)) {
        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;

        A->previous = B;
        B->previous = swapperVector[1];
        A->next = swapperVector[3];
        B->next = A;
        cout << endl << "Option 1" << endl;
    }
    else {
        A->previous = swapperVector[1];
        B->previous = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[2];

        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;
        cout << endl << "Option 2" << endl;
    }

    cout <<"Print list after swap" << endl << "-----" << endl;
    printUsers();
}
</code>```

Feel free to get into my project's github
https://github.com/pablogalve/ELO-System

I would appreciate your help :)

答:
Amanda's answer shows one way to deal with adjacent nodes, but there doesn't need to be a special case to handle adjacent versus non-adjacent nodes, if the swapping is done first by swapping what is pointing to the two target nodes, then swapping the pointers within the two target nodes.</p>

```<code>    AP = A->previous;
    BP = B->previous;
    AN = A->next;
    BN = B->next;
    std::swap(AN->previous, BN->previous);
    std::swap(AP->next, BP->next);
    std::swap(A->previous, B->previous);
    std::swap(A->next, B->next);
</code>```

Body:
I have a doubly-linked list and I want to sort the users by their ELO.

The problem is that when the function swap() is called, some users dissapear

This is what I get in my console:
https://imgur.com/a/pJSPSnW

As you can see, the first swap (between players 1 and 2) is done correctly.
But, when it swaps players 3 and 4, user1 dissapears.

I think that the problem is inside the function swap(), but I can't figure out where exactly

Code:
User/Node declaration

struct user {
public:
    string username;
    float ELO = NULL; //Score of the user
    user* next = nullptr;
    user* previous = nullptr;
};

QuickSortRecursive function

 void ELOManager::_quickSortRecursive(user* low, user* high) {
    if (high != nullptr && low != high && low != nullptr) {
        user* p = partition(low, high);
        _quickSortRecursive(low, p->previous);
        _quickSortRecursive(p->next, high);
    }
}

QuickSort function

void ELOManager::quickSort(){
    _quickSortRecursive(first, last);
}

Partition function

    user* ELOManager::partition(user* low, user* high) {
    float pivot = high->ELO;

    user* i = low->previous;

    for (user* j = low; j != high && j!=nullptr; j = j->next) {
        if (j->ELO <= pivot){
            i = (i == NULL) ? low : i->next;

            swap(i, j);
        }
    }
    //i = (i == NULL) ? low : i->next;
    swap(i->next, high);
    cout << endl << "Loop finished -----------------------" << endl;
    printUsers();
    return i;
}

Swap function

    void ELOManager::swap(user* A, user* B) {
    user* tmp = new user();
    user* swapperVector[4];

    cout << endl << "swap1[" <username << "]" << endl;
    cout << "swap2[" <username << "]" << endl;

    if (A == B) {
        cout << "Same Users: Continue" << endl;
        return;
    }

    swapperVector[0] = A->previous;
    swapperVector[1] = B->previous;
    swapperVector[2] = A->next;
    swapperVector[3] = B->next;

    if (areTheyNeighbours(A, B)) {
        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;

        A->previous = B;
        B->previous = swapperVector[1];
        A->next = swapperVector[3];
        B->next = A;
        cout << endl << "Option 1" << endl;
    }
    else {
        A->previous = swapperVector[1];
        B->previous = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[2];

        A->previous->next = B;
        A->next->previous = B;
        B->previous->next = A;
        B->next->previous = A;
        cout << endl << "Option 2" << endl;
    }

    cout <<"Print list after swap" << endl << "-----" << endl;
    printUsers();
}

Feel free to get into my project's github
https://github.com/pablogalve/ELO-System

I would appreciate your help :)

Body:
Amanda's answer shows one way to deal with adjacent nodes, but there doesn't need to be a special case to handle adjacent versus non-adjacent nodes, if the swapping is done first by swapping what is pointing to the two target nodes, then swapping the pointers within the two target nodes.

    AP = A->previous;
    BP = B->previous;
    AN = A->next;
    BN = B->next;
    std::swap(AN->previous, BN->previous);
    std::swap(AP->next, BP->next);
    std::swap(A->previous, B->previous);
    std::swap(A->next, B->next);


问:
Missing ";" before statement
I can't figure out where I made a mistake in the syntax, please help. The error is in the first line. I made everything else before I did the first line and the error wasn't there before I made it.</p>

```<code>    String msg.payload2 = msg.payload.toLowerCase();
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        msg.payload = "Heads";
    } else {
        msg.payload = "Tails";
    }
}
return msg.payload
</code>```

答:
JavaScript is loosely typed. When accessing a property on an object, using the syntax msg.payload2 you should receive the value contained in the property payload2 from the msg object. However, if the property doesn't exist, the payload2 property will return undefined. This is why your code worked before adding the first line in your example.

This line:

if (msg.payload2 == "-coinflip")

will always evaluate to false if the payload2 property is never defined.

The reason it didn't work when you added line 1 of your code snippet in; is that you're trying to give a type to an object property in JavaScript using syntax that the JS engine doesn't understand and will throw a SyntaxError.

EDIT:

let msg = { payload: '' }; // assuming this is an object defined higher up. I've placed this here for more context
let result;
msg.payload2 = msg.payload && msg.payload.toLowerCase(); // This line also protects against trying to lowercase an undefined payload
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        result = "Heads";
    } else {
        result = "Tails";
    }
}
return result;
```

I don't consider this production code but it will get your app running.

Title: Missing ";" before statement

Body:
I can't figure out where I made a mistake in the syntax, please help. The error is in the first line. I made everything else before I did the first line and the error wasn't there before I made it.

    String msg.payload2 = msg.payload.toLowerCase();
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        msg.payload = "Heads";
    } else {
        msg.payload = "Tails";
    }
}
return msg.payload

Body:
JavaScript is loosely typed. When accessing a property on an object, using the syntax msg.payload2 you should receive the value contained in the property payload2 from the msg object. However, if the property doesn't exist, the payload2 property will return undefined. This is why your code worked before adding the first line in your example.

This line:

if (msg.payload2 == "-coinflip")

will always evaluate to false if the payload2 property is never defined.

The reason it didn't work when you added line 1 of your code snippet in; is that you're trying to give a type to an object property in JavaScript using syntax that the JS engine doesn't understand and will throw a SyntaxError.

EDIT:

let msg = { payload: '' }; // assuming this is an object defined higher up. I've placed this here for more context
let result;
msg.payload2 = msg.payload && msg.payload.toLowerCase(); // This line also protects against trying to lowercase an undefined payload
if (msg.payload2 == "-coinflip") {
    rnd = Math.floor (Math.random() * (2-0));
    if (rnd == 1) {
        result = "Heads";
    } else {
        result = "Tails";
    }
}
return result;

I don't consider this production code but it will get your app running.


问:
How to Integrate react-native-swiper using flatlist
I was trying to integrate react-native-swiper, which loads videos in it.
I am looking for a way to integrate it with a flat list. but the data is not loading properly, is there any alternative way to load data using flat list (using array.map())

```<code>export default class HomeTab extends Component {
    render() {
     return (
       <FlatList
          data={Data}
          keyExtractor={(item, index) => item.id}
          renderItem={({item}) =>

            <Swiper style={styles.wrapper}
                showsButtons={false}
                horizontal={true}
                loop={false}
                index={item.id}
                activeDot={
                  <View></View>
                }
                dot={
                  <View></View>
                }
                >
                  <View style={styles.slide1}>
                            <Video
                                source={{uri: item.media}}   // Can be a URL or a local file.
                                ref={(ref) => {
                                  this.player = ref
                                }}
                                resizeMode={'contain'}
                                style={styles.backgroundVideo}
                        />

                      </View>
            </Swiper>

            }
          />
    )
  }
}
</code>```

using npm package: react-native-swiper https://www.npmjs.com/package/react-native-swiper

答:
try to use this lib, cause react-native-swiper-flatlist it has flatlist inside
Example below:</p>

```<code>  <SwiperFlatList
        autoplay
        autoplayDelay={3}
        index={3}
        autoplayLoop
        data={items}
        renderItem={({item}) => // Standard Image
                            <View style={[styles.child, { backgroundColor: '#000' }]}>
                                <Image
                                    source={{uri:item.key}}
                                    style={styles.checkoutSliderImage}
                                />
                                <Text>{item.key}</Text>
                            </View>
                        }
        showPagination
      />
</code>```

Body:
I was trying to integrate react-native-swiper, which loads videos in it.
I am looking for a way to integrate it with a flat list. but the data is not loading properly, is there any alternative way to load data using flat list (using array.map())

export default class HomeTab extends Component {
    render() {
     return (
       <FlatList
          data={Data}
          keyExtractor={(item, index) => item.id}
          renderItem={({item}) =>

            <Swiper style={styles.wrapper}
                showsButtons={false}
                horizontal={true}
                loop={false}
                index={item.id}
                activeDot={
                  <View></View>
                }
                dot={
                  <View></View>
                }
                >
                  <View style={styles.slide1}>
                            <Video
                                source={{uri: item.media}}   // Can be a URL or a local file.
                                ref={(ref) => {
                                  this.player = ref
                                }}
                                resizeMode={'contain'}
                                style={styles.backgroundVideo}
                        />

                      </View>
            </Swiper>

            }
          />
    )
  }
}

using npm package: react-native-swiper https://www.npmjs.com/package/react-native-swiper

Body:
try to use this lib, cause react-native-swiper-flatlist it has flatlist inside
Example below:

  <SwiperFlatList
        autoplay
        autoplayDelay={3}
        index={3}
        autoplayLoop
        data={items}
        renderItem={({item}) => // Standard Image
                            <View style={[styles.child, { backgroundColor: '#000' }]}>
                                <Image
                                    source={{uri:item.key}}
                                    style={styles.checkoutSliderImage}
                                />
                                <Text>{item.key}</Text>
                            </View>
                        }
        showPagination
      />


问:
Sequelize + Express TypeError: User.find is not a function
I am following an online tutorial on using PostgreSQL, Express and Passport and when I try to sign in, I get the following error stack trace:

```<code>at /path/to/server/routes/api.js:30:8
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at next (/path/to/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/path/to/server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at /path/to/server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)
at next (/path/to/server/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)
at router (/path/to/server/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)
at /path/to/server/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)
at next (/path/to/server/node_modules/express/lib/router/index.js:275:10)
at /path/to/server/node_modules/express/lib/router/index.js:635:15
at next (/path/to/server/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)
at router (/path/to/server/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)
at /path/to/server/node_modules/express/lib/router/index.js:284:7
</code>```

/path/to/server/models/index.js

```<code>'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
</code>```

/path/to/server/models/user.js

```<code>'use strict';

var bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});
  User.beforeSave((user, options) => {
    if (user.changed('password')) {
      user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
    }
  });
  User.prototype.comparePassword = function (passw, cb) {
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
  };
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};
</code>```

/path/to/server/api.js

```<code>const express = require('express');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const router = express.Router();
require('../config/passport')(passport);
const User = require('../models').User;

router.post('/signin', function(req, res) {
  User
      .find({
        where: {
          username: req.body.username
        }
      })
      .then((user) => {
        if (!user) {
          return res.status(401).send({
            message: 'Authentication failed. User not found.',
          });
        }
        user.comparePassword(req.body.password, (err, isMatch) => {
          if(isMatch && !err) {
            var token = jwt.sign(JSON.parse(JSON.stringify(user)), 'nodeauthsecret', {expiresIn: 86400 * 30});
            jwt.verify(token, 'nodeauthsecret', function(err, data){
              console.log(err, data);
            })
            res.json({success: true, token: 'JWT ' + token});
          } else {
            res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
          }
        })
      })
      .catch((error) => res.status(400).send(error));
});
</code>```

Why is User.find() not being recognised as a method? and how do I fix this issue?

答: I was looking for a find method on the sequelize doc and couldn't find the find method, just a findAll and findOne. Perhaps it was deprecated on newer versions docs.sequelizejs.com/manual/querying.html

Body:
I am following an online tutorial on using PostgreSQL, Express and Passport and when I try to sign in, I get the following error stack trace:

at /path/to/server/routes/api.js:30:8
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at next (/path/to/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/path/to/server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at /path/to/server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)
at next (/path/to/server/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)
at router (/path/to/server/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)
at /path/to/server/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/path/to/server/node_modules/express/lib/router/index.js:335:12)
at next (/path/to/server/node_modules/express/lib/router/index.js:275:10)
at /path/to/server/node_modules/express/lib/router/index.js:635:15
at next (/path/to/server/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/path/to/server/node_modules/express/lib/router/index.js:174:3)
at router (/path/to/server/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/path/to/server/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/path/to/server/node_modules/express/lib/router/index.js:317:13)
at /path/to/server/node_modules/express/lib/router/index.js:284:7

/path/to/server/models/index.js

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

/path/to/server/models/user.js

'use strict';

var bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});
  User.beforeSave((user, options) => {
    if (user.changed('password')) {
      user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
    }
  });
  User.prototype.comparePassword = function (passw, cb) {
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
  };
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

/path/to/server/api.js

const express = require('express');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const router = express.Router();
require('../config/passport')(passport);
const User = require('../models').User;

router.post('/signin', function(req, res) {
  User
      .find({
        where: {
          username: req.body.username
        }
      })
      .then((user) => {
        if (!user) {
          return res.status(401).send({
            message: 'Authentication failed. User not found.',
          });
        }
        user.comparePassword(req.body.password, (err, isMatch) => {
          if(isMatch && !err) {
            var token = jwt.sign(JSON.parse(JSON.stringify(user)), 'nodeauthsecret', {expiresIn: 86400 * 30});
            jwt.verify(token, 'nodeauthsecret', function(err, data){
              console.log(err, data);
            })
            res.json({success: true, token: 'JWT ' + token});
          } else {
            res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
          }
        })
      })
      .catch((error) => res.status(400).send(error));
});

Why is User.find() not being recognised as a method? and how do I fix this issue?


问:
Upgrade terraform to specific version
Use case

I have installed Terraform v0.11.13 via homebrew and as recommended by terraform I want to ugprade to version v0.11.14 before doing the major upgrade to v0.12.0.

The problem

When I run brew upgrade terraform or download the Mac package from the terraform website it would immediately update my terraform version to v0.12.0 I think.

So how can I upgrade to v0.11.14 instead?

答:
For anyone looking to do the same without using homebrew:

Get source

```<code>$ wget https://releases.hashicorp.com/terraform/0.11.14/terraform_0.11.14_linux_amd64.zip

$ unzip terraform_0.11.14_linux_amd64.zip
</code>```

Give binary executable permissions and install (will overwrite current version)

```<code>$ chmod +x terraform

$ sudo mv terraform /usr/local/bin/
</code>```

Confirm version

```<code>$ terraform --version
</code>```

Source: https://titosoft.github.io/kvm/terraform-and-kvm/#installing-terraform

Title: Upgrade terraform to specific version

Body:
For anyone looking to do the same without using homebrew:

Get source

$ wget https://releases.hashicorp.com/terraform/0.11.14/terraform_0.11.14_linux_amd64.zip

$ unzip terraform_0.11.14_linux_amd64.zip

Give binary executable permissions and install (will overwrite current version)

$ chmod +x terraform

$ sudo mv terraform /usr/local/bin/

Confirm version

$ terraform --version

Source: https://titosoft.github.io/kvm/terraform-and-kvm/#installing-terraform


问:
ASP.NET Core - How do I detect if my IHostedService crashes at runtime? Can I restart it?
I'm implementing a timed background service in my ASP.NET Core web site, using the code found at this blog post as a model. The bit that does the real work looks like the following...

```<code>protected async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        // Put your code here

        // Wait 30 minutes before running again.
        await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken);
    }
}
</code>```

This works fine until something causes the service to crash. Obviously, in a production application you'd hope that this wouldn't happen, but being practical, I need to account for the possibility.

As far as I can see, the framework creates and starts the task, and the rest of the app doesn't know anything about it. Can I detect if the IHostedService service crashes, and can I restart it? If not, what do I do? Having this run at regular intervals is crucial to the web site, so I need to know I can handle any problems.

答:
If not, what do I do? Having this run at regular intervals is crucial to the web site, so I need to know I can handle any problems.

You should be running critical background services in a separate, independent process. This can be Azure Functions or Docker or even a Win32 service with auto-restart enabled. This way, something else restarts your process as necessary.

Body:
I'm implementing a timed background service in my ASP.NET Core web site, using the code found at this blog post as a model. The bit that does the real work looks like the following...

protected async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        // Put your code here

        // Wait 30 minutes before running again.
        await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken);
    }
}

This works fine until something causes the service to crash. Obviously, in a production application you'd hope that this wouldn't happen, but being practical, I need to account for the possibility.

As far as I can see, the framework creates and starts the task, and the rest of the app doesn't know anything about it. Can I detect if the IHostedService service crashes, and can I restart it? If not, what do I do? Having this run at regular intervals is crucial to the web site, so I need to know I can handle any problems.


问:
Is there a way to display labels in a plot only when clicked on?
Imagine I have this dataset, data1 (post-scaling and PCA).

```<code>            F1    F2     F3  F4   F5 ... F21
1          0.28  2.29  5.64 1.04 3.92    1065
2          0.26  1.28  4.38 1.05 3.40    1050
3          0.30  2.81  5.68 1.03 3.17    1185
4          0.24  2.18  7.80 0.86 3.45    1480
5          0.39  1.82  4.32 1.04 2.93     735
.
.
.
1000       0.34  1.97  6.75 1.05 2.85    1450
</code>```

I did a k-means cluster analysis on the dataset using:

```<code>Clusters <- kmeans(data1, 5, nstart = 25)
data1 <- data.frame(data1)
data1 <- data1 %>% mutate(Cluster = Clusters$cluster)
</code>```

Then I inserted rownames of character type from another dataset:

```<code>rownames(data1) <- data2$Name
</code>```

Then, to avoid labels overlapping I used

```<code>p1 <- autoplot(Clusters, data = data1, frame = TRUE, label = F, x=1, y=2)
p2 <- p1 + geom_text_repel(aes(label = rownames(data1)))
</code>```

Since I have over 500 data points, the labels predictably overlapped and can't be read. I was wondering if there is a method of labeling when the label is only displayed when you click or hover over the data point. Or any other solution is welcome. Thanks

答:
You can do it with plotly. With add_trace() you can show a label only on hover.

```<code>library(ggplot2)
library(plotly)
library(dplyr)

data <- mtcars[, c("mpg", "wt")] # just two features

k_data <- kmeans(data, 3) # find clusters
</code>```

Now let's add the cluster info to data:

```<code>data <- cbind(data, cluster=k_data$cluster)
#                mpg    wt cluster
# Mazda RX4     21.0 2.620       1
# Mazda RX4 Wag 21.0 2.875       1
# Datsun 710    22.8 2.320       1
</code>```

Now we can plot everything:

```<code>plot_ly(data = data, x = ~mpg, y = ~wt, color = ~as.factor(cluster)) %>%
  add_trace(
    type = 'scatter',
    mode = 'markers',
    text = rownames(data), # when you hover on a point it will show it's rowname
    hoverinfo = 'text',
    showlegend = F
  )
</code>```

More guides here and here.

Body:
Imagine I have this dataset, data1 (post-scaling and PCA).

            F1    F2     F3  F4   F5 ... F21
1          0.28  2.29  5.64 1.04 3.92    1065
2          0.26  1.28  4.38 1.05 3.40    1050
3          0.30  2.81  5.68 1.03 3.17    1185
4          0.24  2.18  7.80 0.86 3.45    1480
5          0.39  1.82  4.32 1.04 2.93     735
.
.
.
1000       0.34  1.97  6.75 1.05 2.85    1450

I did a k-means cluster analysis on the dataset using:

Clusters <- kmeans(data1, 5, nstart = 25)
data1 <- data.frame(data1)
data1 <- data1 %>% mutate(Cluster = Clusters$cluster)

Then I inserted rownames of character type from another dataset:

rownames(data1) <- data2$Name

Then, to avoid labels overlapping I used

p1 <- autoplot(Clusters, data = data1, frame = TRUE, label = F, x=1, y=2)
p2 <- p1 + geom_text_repel(aes(label = rownames(data1)))

Since I have over 500 data points, the labels predictably overlapped and can't be read. I was wondering if there is a method of labeling when the label is only displayed when you click or hover over the data point. Or any other solution is welcome. Thanks

Body:
You can do it with plotly. With add_trace() you can show a label only on hover.

library(ggplot2)
library(plotly)
library(dplyr)

data <- mtcars[, c("mpg", "wt")] # just two features

k_data <- kmeans(data, 3) # find clusters

Now let's add the cluster info to data:

data <- cbind(data, cluster=k_data$cluster)
#                mpg    wt cluster
# Mazda RX4     21.0 2.620       1
# Mazda RX4 Wag 21.0 2.875       1
# Datsun 710    22.8 2.320       1

Now we can plot everything:

plot_ly(data = data, x = ~mpg, y = ~wt, color = ~as.factor(cluster)) %>%
  add_trace(
    type = 'scatter',
    mode = 'markers',
    text = rownames(data), # when you hover on a point it will show it's rowname
    hoverinfo = 'text',
    showlegend = F
  )

More guides here and here.


问:
Recoding specific column values using reference list
My dataframe looks like this

```<code>data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))
</code>```

And I have a reference list that looks like this -

```<code>ref=list(Male=1,Female=2)
</code>```

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

```<code>do.call(dplyr::recode, c(list(data), ref))
</code>```

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

答:
You can use factor, i.e.

```<code>factor(data$Gender, levels = names(ref), labels = ref)
#[1] 1 2 2 2 1 2 1 1 2 2
</code>```

Body:
My dataframe looks like this

data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))

And I have a reference list that looks like this -

ref=list(Male=1,Female=2)

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

do.call(dplyr::recode, c(list(data), ref))

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

Body:
You can use factor, i.e.

factor(data$Gender, levels = names(ref), labels = ref)
#[1] 1 2 2 2 1 2 1 1 2 2


问:
Remove duplicates from a List<T> in C#
Anyone have a quick method for de-duplicating a generic List in C#?</p>

答:
All answers copy lists, or create a new list, or use slow functions, or are just painfully slow.

To my understanding, this is the fastest and cheapest method I know (also, backed by a very experienced programmer specialized on real-time physics optimization).

```<code>// Duplicates will be noticed after a sort O(nLogn)
list.Sort();

// Store the current and last items. Current item declaration is not really needed, and probably optimized by the compiler, but in case it's not...
int lastItem = -1;
int currItem = -1;

int size = list.Count;

// Store the index pointing to the last item we want to keep in the list
int last = size - 1;

// Travel the items from last to first O(n)
for (int i = last; i >= 0; --i)
{
    currItem = list[i];

    // If this item was the same as the previous one, we don't want it
    if (currItem == lastItem)
    {
        // Overwrite last in current place. It is a swap but we don't need the last
       list[i] = list[last];

        // Reduce the last index, we don't want that one anymore
        last--;
    }

    // A new item, we store it and continue
    else
        lastItem = currItem;
}

// We now have an unsorted list with the duplicates at the end.

// Remove the last items just once
list.RemoveRange(last + 1, size - last - 1);

// Sort again O(n logn)
list.Sort();
</code>```

Final cost is:

nlogn + n + nlogn = n + 2nlogn = O(nlogn) which is pretty nice.

Note about RemoveRange:
Since we cannot set the count of the list and avoid using the Remove funcions, I don't know exactly the speed of this operation but I guess it is the fastest way.

OwnerDisplayName: JC Grubbs

ContentLicense: CC BY-SA 2.5

Title: Remove duplicates from a List<T> in C#

Body:
All answers copy lists, or create a new list, or use slow functions, or are just painfully slow.

To my understanding, this is the fastest and cheapest method I know (also, backed by a very experienced programmer specialized on real-time physics optimization).

// Duplicates will be noticed after a sort O(nLogn)
list.Sort();

// Store the current and last items. Current item declaration is not really needed, and probably optimized by the compiler, but in case it's not...
int lastItem = -1;
int currItem = -1;

int size = list.Count;

// Store the index pointing to the last item we want to keep in the list
int last = size - 1;

// Travel the items from last to first O(n)
for (int i = last; i >= 0; --i)
{
    currItem = list[i];

    // If this item was the same as the previous one, we don't want it
    if (currItem == lastItem)
    {
        // Overwrite last in current place. It is a swap but we don't need the last
       list[i] = list[last];

        // Reduce the last index, we don't want that one anymore
        last--;
    }

    // A new item, we store it and continue
    else
        lastItem = currItem;
}

// We now have an unsorted list with the duplicates at the end.

// Remove the last items just once
list.RemoveRange(last + 1, size - last - 1);

// Sort again O(n logn)
list.Sort();

Final cost is:

nlogn + n + nlogn = n + 2nlogn = O(nlogn) which is pretty nice.

Note about RemoveRange:
Since we cannot set the count of the list and avoid using the Remove funcions, I don't know exactly the speed of this operation but I guess it is the fastest way.


问:
Loading Module on Mac -Python3
Very New to Coding I am trying to use a package from GitHub which I installed with pip, and I keep getting an error when using the functions. I want to be able to access my food for the given day.

This is the code I am trying to run. It should print the given day's calorie information.

```<code>import myfitnesspal

client = myfitnesspal.Client('username')

day = client.get_date(2013, 3, 2)
print(day)
</code>```

This is the error I'm getting.

Traceback (most recent call last):
  File "/Users/user/Desktop/PythonWorkspace/myfitnesspal.py", line 1, in
    import myfitnesspal
  File "/Users/user/Desktop/PythonWorkspace/myfitnesspal.py", line 4, in
    client = myfitnesspal.Client('username')
AttributeError: module 'myfitnesspal' has no attribute 'Client'

Also, this is the link to the GitHub if that helps https://github.com/coddingtonbear/python-myfitnesspal

答:
This may be silly but can you check if you did import the package correctly using pip freeze or pip list

If not and you can't install the package use : sudo pip install myfitnesspal

If you did, maybe try importing Client :

```<code>from myfitnesspal import Client

client = Client('username')

day = client.get_date(2013, 3, 2)
print(day)
</code>```

Title: Loading Module on Mac -Python3

Body:
Very New to Coding I am trying to use a package from GitHub which I installed with pip, and I keep getting an error when using the functions. I want to be able to access my food for the given day.

This is the code I am trying to run. It should print the given day's calorie information.

import myfitnesspal

client = myfitnesspal.Client('username')

day = client.get_date(2013, 3, 2)
print(day)

This is the error I'm getting.

Traceback (most recent call last):
  File "/Users/user/Desktop/PythonWorkspace/myfitnesspal.py", line 1, in
    import myfitnesspal
  File "/Users/user/Desktop/PythonWorkspace/myfitnesspal.py", line 4, in
    client = myfitnesspal.Client('username')
AttributeError: module 'myfitnesspal' has no attribute 'Client'

Also, this is the link to the GitHub if that helps https://github.com/coddingtonbear/python-myfitnesspal

Body:
This may be silly but can you check if you did import the package correctly using pip freeze or pip list

If not and you can't install the package use : sudo pip install myfitnesspal

If you did, maybe try importing Client :

from myfitnesspal import Client

client = Client('username')

day = client.get_date(2013, 3, 2)
print(day)


问:
How to plot two lines in the same graph if the number of observations is uneqal?
I have two dataframes each containing a "Date" and a "Price" column.
I now want to produce a graph with two plots in it based on the observations of this two dataframes. The problem I have is that the dates are not equal. My data looks like this:

```<code>Date1 <- seq.Date(from = as.Date("2015-08-07"), to = as.Date("2015-08-16"), by = "days")
Price1 <- c(2.5,6.3,1.2,2.4,4.2,5.1,7.3,9.2,12.5,8.7)
df1 <- data.frame(Date1, Price1)

Date2 <- seq.Date(from=as.Date("2015-08-11"), to = as.Date ("2015-08-16"), by = "days")
Price2 <- c(24.3,21.2,18.4,16.2,17.1,15.6)
df2 <- data.frame(Date2, Price2)

df1
#         Date1 Price1
# 1  2015-08-07    2.5
# 2  2015-08-08    6.3
# 3  2015-08-09    1.2
# 4  2015-08-10    2.4
# 5  2015-08-11    4.2
# 6  2015-08-12    5.1
# 7  2015-08-13    7.3
# 8  2015-08-14    9.2
# 9  2015-08-15   12.5
# 10 2015-08-16    8.7

df2
#        Date2 Price2
# 1 2015-08-11   24.3
# 2 2015-08-12   21.2
# 3 2015-08-13   18.4
# 4 2015-08-14   16.2
# 5 2015-08-15   17.1
# 6 2015-08-16   15.6
</code>```

To create the two plots in one graph I use the following code:

```<code>par(mar = c(5, 5, 9, 5))
plot(df1[,1],df1[,2], log = "y", type ="l", col = "orange")
par(new = TRUE)
plot(df2[,2],log = "y", type = "l",col = "blue")
</code>```

What I would like to receive is a graph in which the plot from df1 starts from the beginning and the df2 starts at a later point in time.

Thanks!

答:
If you are interested in an approach from tidyverse:

```<code>df1 %>%
full_join(df2, by = c("Date1" = "Date2")) %>%
gather(key, value, -Date1) %>%
ggplot(aes(x = Date1, y = value, group = key, col = key)) +
geom_line()
</code>```

Here is the result:

Body:
I have two dataframes each containing a "Date" and a "Price" column.
I now want to produce a graph with two plots in it based on the observations of this two dataframes. The problem I have is that the dates are not equal. My data looks like this:

Date1 <- seq.Date(from = as.Date("2015-08-07"), to = as.Date("2015-08-16"), by = "days")
Price1 <- c(2.5,6.3,1.2,2.4,4.2,5.1,7.3,9.2,12.5,8.7)
df1 <- data.frame(Date1, Price1)

Date2 <- seq.Date(from=as.Date("2015-08-11"), to = as.Date ("2015-08-16"), by = "days")
Price2 <- c(24.3,21.2,18.4,16.2,17.1,15.6)
df2 <- data.frame(Date2, Price2)

df1
#         Date1 Price1
# 1  2015-08-07    2.5
# 2  2015-08-08    6.3
# 3  2015-08-09    1.2
# 4  2015-08-10    2.4
# 5  2015-08-11    4.2
# 6  2015-08-12    5.1
# 7  2015-08-13    7.3
# 8  2015-08-14    9.2
# 9  2015-08-15   12.5
# 10 2015-08-16    8.7

df2
#        Date2 Price2
# 1 2015-08-11   24.3
# 2 2015-08-12   21.2
# 3 2015-08-13   18.4
# 4 2015-08-14   16.2
# 5 2015-08-15   17.1
# 6 2015-08-16   15.6

To create the two plots in one graph I use the following code:

par(mar = c(5, 5, 9, 5))
plot(df1[,1],df1[,2], log = "y", type ="l", col = "orange")
par(new = TRUE)
plot(df2[,2],log = "y", type = "l",col = "blue")

What I would like to receive is a graph in which the plot from df1 starts from the beginning and the df2 starts at a later point in time.

Thanks!

Body:
If you are interested in an approach from tidyverse:

df1 %>%
full_join(df2, by = c("Date1" = "Date2")) %>%
gather(key, value, -Date1) %>%
ggplot(aes(x = Date1, y = value, group = key, col = key)) +
geom_line()

Here is the result:


问:
How can I schedule a cron job but not execute it?
I wanted to create a crontab file with schedule but do not want it to run.
How can I achieve this?

I created a crontab file using crontab -e, added the job. This has started running. I do not want this to run as the job should be scheduled ad hoc.

I wanted to prepare and keep and use the schedule on ad hoc.

答:
You could test for a file to be present and if it does it'll execute your task:

```<code>5 * * * * user test -f /var/lock/subsys/myfile && /home/user/backup.sh
</code>```

Thus when you are ready. You just

```<code>touch /var/lock/subsys/myfile
</code>```

and the script starts within the next five minutes.

But you have to make sure to remove the lock file afterwards.

Body:
You could test for a file to be present and if it does it'll execute your task:

5 * * * * user test -f /var/lock/subsys/myfile && /home/user/backup.sh

Thus when you are ready. You just

touch /var/lock/subsys/myfile

and the script starts within the next five minutes.

But you have to make sure to remove the lock file afterwards.