问:
ios speech recognition Error Domain=kAFAssistantErrorDomain Code=216 "(null)"
Basically I am learning ios speech recognition module following this tutorial:
https://medium.com/ios-os-x-development/speech-recognition-with-swift-in-ios-10-50d5f4e59c48

But when I test it on my iphone6, I always got this error:
Error Domain=kAFAssistantErrorDomain Code=216 "(null)"

I searched it on the internet, but find very rare info about this.

Here is my code:

```<code>//
//  ViewController.swift
//  speech_sample
//
//  Created by Peizheng Ma on 6/22/17.
//  Copyright © 2017 Peizheng Ma. All rights reserved.
//

import UIKit
import AVFoundation
import Speech

class ViewController: UIViewController, SFSpeechRecognizerDelegate {

//MARK: speech recognize variables
let audioEngine = AVAudioEngine()
let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
var request = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask: SFSpeechRecognitionTask?
var isRecording = false

override func viewDidLoad() {
    // super.viewDidLoad()
    // get Authorization
    self.requestSpeechAuthorization()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: properties
@IBOutlet weak var detectText: UILabel!
@IBOutlet weak var startButton: UIButton!

//MARK: actions
@IBAction func startButtonTapped(_ sender: UIButton) {
    if isRecording == true {

        audioEngine.stop()
//            if let node = audioEngine.inputNode {
//                node.removeTap(onBus: 0)
//            }
        audioEngine.inputNode?.removeTap(onBus: 0)
        // Indicate that the audio source is finished and no more audio will be appended
        self.request.endAudio()

        // Cancel the previous task if it's running
        if let recognitionTask = recognitionTask {
            recognitionTask.cancel()
            self.recognitionTask = nil
        }

        //recognitionTask?.cancel()
        //self.recognitionTask = nil
        isRecording = false
        startButton.backgroundColor = UIColor.gray
    } else {
        self.recordAndRecognizeSpeech()
        isRecording = true
        startButton.backgroundColor = UIColor.red
    }
}

//MARK: show alert
func showAlert(title: String, message: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) {
    DispatchQueue.main.async { [unowned self] in
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: handler))
        self.present(alertController, animated: true, completion: nil)
    }
}

//MARK: Recognize Speech
func recordAndRecognizeSpeech() {
    // Setup Audio Session
    guard let node = audioEngine.inputNode else { return }
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        self.request.append(buffer)
    }
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        self.showAlert(title: "SpeechNote", message: "There has been an audio engine error.", handler: nil)
        return print(error)
    }
    guard let myRecognizer = SFSpeechRecognizer() else {
        self.showAlert(title: "SpeechNote", message: "Speech recognition is not supported for your current locale.", handler: nil)
        return
    }
    if !myRecognizer.isAvailable {
        self.showAlert(title: "SpeechNote", message: "Speech recognition is not currently available. Check back at a later time.", handler: nil)
        // Recognizer is not available right now
        return
    }
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {

            let bestString = result.bestTranscription.formattedString
            self.detectText.text = bestString

//                var lastString: String = ""
//                for segment in result.bestTranscription.segments {
//                    let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
//                    lastString = bestString.substring(from: indexTo)
//                }
//                self.checkForColorsSaid(resultString: lastString)
        } else if let error = error {
            self.showAlert(title: "SpeechNote", message: "There has been a speech recognition error.", handler: nil)
            print(error)
        }
    })
}

//MARK: - Check Authorization Status
func requestSpeechAuthorization() {
    SFSpeechRecognizer.requestAuthorization { authStatus in
        OperationQueue.main.addOperation {
            switch authStatus {
            case .authorized:
                self.startButton.isEnabled = true
            case .denied:
                self.startButton.isEnabled = false
                self.detectText.text = "User denied access to speech recognition"
            case .restricted:
                self.startButton.isEnabled = false
                self.detectText.text = "Speech recognition restricted on this device"
            case .notDetermined:
                self.startButton.isEnabled = false
                self.detectText.text = "Speech recognition not yet authorized"
            }
        }
    }
}

}
</code>```

Thank you very much.

答: I had this error because I was running the app on the Simulator. Running on a regular device solves the issue.</p>

Body:
Basically I am learning ios speech recognition module following this tutorial:
https://medium.com/ios-os-x-development/speech-recognition-with-swift-in-ios-10-50d5f4e59c48

But when I test it on my iphone6, I always got this error:
Error Domain=kAFAssistantErrorDomain Code=216 "(null)"

I searched it on the internet, but find very rare info about this.

Here is my code:

//
//  ViewController.swift
//  speech_sample
//
//  Created by Peizheng Ma on 6/22/17.
//  Copyright © 2017 Peizheng Ma. All rights reserved.
//

import UIKit
import AVFoundation
import Speech

class ViewController: UIViewController, SFSpeechRecognizerDelegate {

//MARK: speech recognize variables
let audioEngine = AVAudioEngine()
let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
var request = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask: SFSpeechRecognitionTask?
var isRecording = false

override func viewDidLoad() {
    // super.viewDidLoad()
    // get Authorization
    self.requestSpeechAuthorization()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: properties
@IBOutlet weak var detectText: UILabel!
@IBOutlet weak var startButton: UIButton!

//MARK: actions
@IBAction func startButtonTapped(_ sender: UIButton) {
    if isRecording == true {

        audioEngine.stop()
//            if let node = audioEngine.inputNode {
//                node.removeTap(onBus: 0)
//            }
        audioEngine.inputNode?.removeTap(onBus: 0)
        // Indicate that the audio source is finished and no more audio will be appended
        self.request.endAudio()

        // Cancel the previous task if it's running
        if let recognitionTask = recognitionTask {
            recognitionTask.cancel()
            self.recognitionTask = nil
        }

        //recognitionTask?.cancel()
        //self.recognitionTask = nil
        isRecording = false
        startButton.backgroundColor = UIColor.gray
    } else {
        self.recordAndRecognizeSpeech()
        isRecording = true
        startButton.backgroundColor = UIColor.red
    }
}

//MARK: show alert
func showAlert(title: String, message: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) {
    DispatchQueue.main.async { [unowned self] in
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: handler))
        self.present(alertController, animated: true, completion: nil)
    }
}

//MARK: Recognize Speech
func recordAndRecognizeSpeech() {
    // Setup Audio Session
    guard let node = audioEngine.inputNode else { return }
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        self.request.append(buffer)
    }
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        self.showAlert(title: "SpeechNote", message: "There has been an audio engine error.", handler: nil)
        return print(error)
    }
    guard let myRecognizer = SFSpeechRecognizer() else {
        self.showAlert(title: "SpeechNote", message: "Speech recognition is not supported for your current locale.", handler: nil)
        return
    }
    if !myRecognizer.isAvailable {
        self.showAlert(title: "SpeechNote", message: "Speech recognition is not currently available. Check back at a later time.", handler: nil)
        // Recognizer is not available right now
        return
    }
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {

            let bestString = result.bestTranscription.formattedString
            self.detectText.text = bestString

//                var lastString: String = ""
//                for segment in result.bestTranscription.segments {
//                    let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
//                    lastString = bestString.substring(from: indexTo)
//                }
//                self.checkForColorsSaid(resultString: lastString)
        } else if let error = error {
            self.showAlert(title: "SpeechNote", message: "There has been a speech recognition error.", handler: nil)
            print(error)
        }
    })
}

//MARK: - Check Authorization Status
func requestSpeechAuthorization() {
    SFSpeechRecognizer.requestAuthorization { authStatus in
        OperationQueue.main.addOperation {
            switch authStatus {
            case .authorized:
                self.startButton.isEnabled = true
            case .denied:
                self.startButton.isEnabled = false
                self.detectText.text = "User denied access to speech recognition"
            case .restricted:
                self.startButton.isEnabled = false
                self.detectText.text = "Speech recognition restricted on this device"
            case .notDetermined:
                self.startButton.isEnabled = false
                self.detectText.text = "Speech recognition not yet authorized"
            }
        }
    }
}

}

Thank you very much.


来源: stackexchange

问:
Minimum difference based on group-index on two data frame
I have two data frame

```<code>A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1
</code>```

and B

```<code> Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914
</code>```

I would like to calculate the minimum difference between each value of A$X1 and all values of B$Longitude, based on group-index Year_month, and report in a new column of A the value of B$CHL

Let's say when A$X1, minus each value of B$longitude, values for values, for the same Year_month group is the minimum difference, I put in a column A$res the values of B$CHL
Example, for the first row of df A:

```<code>A[1,1]-B[1,1]
A[1,1]-B[2,1]
A[1,1]-B[3,1] ---> this is the minimum difference
</code>```

in the column A$res I put the result 12.58 (value of B[3,3]), and so on for each row of A$X1

```<code>I tried this code:
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))
</code>```

But I have the error:

```<code>Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used
</code>```

Any idea???

P.S:

```<code>sapply(A,class)
        X1 Year_month
  "factor"   "factor"

sapply(B,class)
 Longitude Year_month        CHL
  "factor"   "factor"  "numeric"
</code>```

答:
Avoid any looping as your needs are essentially set-based computation of data frames (aggregate level joined to unit level). Specifically, consider a merge and aggregate and then merge again:

```<code># MERGE THEN CALCULATE ROW-WISE DIFFERENCE
mdf <- within(merge(dfA, dfB, by="Year_month"), {
        Res <- X1 - Longitude
})

# AGGREGATE TO FIND MINIMUM RES
aggdf <- aggregate(Res ~ Year_month + X1, mdf, min)

# MERGE AGGREGATION BACK TO UNIT LEVEL BY SAME COLUMNS
final_df <- merge(aggdf, mdf, by=c("Year_month", "Res", "X1"))  #by ARG IS REDUNDANT
final_df
#   Year_month    Res      X1 Longitude      CHL
# 1     1999_1 6.7698 19.2073   12.4375 12.58700
# 2     1999_1 6.9415 19.3790   12.4375 12.58700
# 3     1999_1 6.9570 19.3945   12.4375 12.58700
# 4     2000_1 6.1350 18.7600   12.6250 13.06914
# 5     2000_1 6.6420 19.2670   12.6250 13.06914
# 6     2000_1 6.7255 19.3505   12.6250 13.06914
</code>```

Rextester demo

ContentLicense: CC BY-SA 4.0

Body:
I have two data frame

A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1

and B

 Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914

I would like to calculate the minimum difference between each value of A$X1 and all values of B$Longitude, based on group-index Year_month, and report in a new column of A the value of B$CHL

Let's say when A$X1, minus each value of B$longitude, values for values, for the same Year_month group is the minimum difference, I put in a column A$res the values of B$CHL
Example, for the first row of df A:

A[1,1]-B[1,1]
A[1,1]-B[2,1]
A[1,1]-B[3,1] ---> this is the minimum difference

in the column A$res I put the result 12.58 (value of B[3,3]), and so on for each row of A$X1

I tried this code:
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))

But I have the error:

Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used

Any idea???

P.S:

sapply(A,class)
        X1 Year_month
  "factor"   "factor"

sapply(B,class)
 Longitude Year_month        CHL
  "factor"   "factor"  "numeric"

Body:
Avoid any looping as your needs are essentially set-based computation of data frames (aggregate level joined to unit level). Specifically, consider a merge and aggregate and then merge again:

# MERGE THEN CALCULATE ROW-WISE DIFFERENCE
mdf <- within(merge(dfA, dfB, by="Year_month"), {
        Res <- X1 - Longitude
})

# AGGREGATE TO FIND MINIMUM RES
aggdf <- aggregate(Res ~ Year_month + X1, mdf, min)

# MERGE AGGREGATION BACK TO UNIT LEVEL BY SAME COLUMNS
final_df <- merge(aggdf, mdf, by=c("Year_month", "Res", "X1"))  #by ARG IS REDUNDANT
final_df
#   Year_month    Res      X1 Longitude      CHL
# 1     1999_1 6.7698 19.2073   12.4375 12.58700
# 2     1999_1 6.9415 19.3790   12.4375 12.58700
# 3     1999_1 6.9570 19.3945   12.4375 12.58700
# 4     2000_1 6.1350 18.7600   12.6250 13.06914
# 5     2000_1 6.6420 19.2670   12.6250 13.06914
# 6     2000_1 6.7255 19.3505   12.6250 13.06914

Rextester demo


问:
Count with group by on Postgresql
I have a postgresql type and a table

CREATE TYPE mem_status AS ENUM('waiting', 'active', 'expired');

CREATE TABLE mems (
  id BIGSERIAL PRIMARY KEY,
  status mem_status NOT NULL
);
```

<p>dataset</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO mems(id, status) VALUES
  (1, 'active'), (2, 'active'), (3, 'expired');
</code>```

I want to query counts that grouped by statuses. So I treid the query below.

WITH mem_statuses AS (
  SELECT unnest(enum_range(NULL::mem_status)) AS status
)
SELECT m.status, count(1)
  FROM mems m
  RIGHT JOIN mem_statuses ms ON ms.status = m.status
  GROUP BY m.status;
```

<p>But if there is no <code>waiting</code> mems, the result looks like below.</p>

```status     |  count
================
NULL       |  1      <- problem
'active'   |  2
'expired'  |  1
```

<p>I want to get result like this.</p>

```status     |  count
================
'waiting'  |  0
'active'   |  2
'expired'  |  1
```

How can I do that?

答:
Use count(id):

```<code>WITH mem_statuses AS (
  SELECT unnest(enum_range(NULL::mem_status)) AS status
)
SELECT ms.status, count(id)
  FROM mems m
  RIGHT JOIN mem_statuses ms ON ms.status = m.status
  GROUP BY ms.status;
</code>```

or:

```<code>select status, count(id)
from unnest(enum_range(null::mem_status)) as status
left join mems using(status)
group by status

 status  | count
---------+-------
 waiting |     0
 active  |     2
 expired |     1
(3 rows)
</code>```

Per the documentation count(expression) gives

number of input rows for which the value of expression is not null

Title: Count with group by on Postgresql

Body:
I have a postgresql type and a table

CREATE TYPE mem_status AS ENUM('waiting', 'active', 'expired');

CREATE TABLE mems (
  id BIGSERIAL PRIMARY KEY,
  status mem_status NOT NULL
);

dataset

INSERT INTO mems(id, status) VALUES
  (1, 'active'), (2, 'active'), (3, 'expired');

I want to query counts that grouped by statuses. So I treid the query below.

WITH mem_statuses AS (
  SELECT unnest(enum_range(NULL::mem_status)) AS status
)
SELECT m.status, count(1)
  FROM mems m
  RIGHT JOIN mem_statuses ms ON ms.status = m.status
  GROUP BY m.status;

But if there is no waiting mems, the result looks like below.

status     |  count
================
NULL       |  1      <- problem
'active'   |  2
'expired'  |  1

I want to get result like this.

status     |  count
================
'waiting'  |  0
'active'   |  2
'expired'  |  1

How can I do that?

Body:
Use count(id):

WITH mem_statuses AS (
  SELECT unnest(enum_range(NULL::mem_status)) AS status
)
SELECT ms.status, count(id)
  FROM mems m
  RIGHT JOIN mem_statuses ms ON ms.status = m.status
  GROUP BY ms.status;

or:

select status, count(id)
from unnest(enum_range(null::mem_status)) as status
left join mems using(status)
group by status

 status  | count
---------+-------
 waiting |     0
 active  |     2
 expired |     1
(3 rows)

Per the documentation count(expression) gives

number of input rows for which the value of expression is not null


问:
Send Image and table of string
When creating a post, the user can also upload a image. All data are sent to the DB via a REST API built using the Django REST Framework.

I got this error inr Image
the submitted data was not a file. check the encoding type on the form.

Service

```<code>addPosts(title: string, content: string, image: File, category: string, tags: string[]){
   let url = 'api/posts/post/';
   const formData = new FormData();

   formData.append("title", title);
   formData.append("content", content);
   formData.append("category", category);
   formData.append("tags", tags);
   formData.append("image", image);

   const post: Post = {title:title, content:content, image: image, category:category, tags:tags};

   let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
   let options = new RequestOptions({ headers: headers });

   this.http.post(url, post, options)
   .subscribe(responseData => {
     this.posts.push(post);
     this.postsUpdate.next([...this.posts]);
   });
 }
</code>```

when i use FormData i can't sent tags because i think FormData didn't support it and when i sent directly post i got
the submitted data was not a file. check the encoding type on the form.

答:
```<code>addPosts(title: string, content: string, image: File, category: string, tags: string[]){
   let url = 'api/posts/post/';
   const formData = new FormData();

   formData.append("title", title);
   formData.append("content", content);
   formData.append("category", category);
   formData.append("tags", tags);
   formData.append("image", image);

   const post: Post = {title:title, content:content, image: image, category:category, tags:tags};<------you set This

   let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
   let options = new RequestOptions({ headers: headers });
</code>```

Set formData

```<code>  this.http.post(url, post, options)<-----set Form Data instead of ` const post: Post`
   .subscribe(responseData => {
     this.posts.push(post);
     this.postsUpdate.next([...this.posts]);
   });
 }
</code>```

Title: Send Image and table of string

Body:
When creating a post, the user can also upload a image. All data are sent to the DB via a REST API built using the Django REST Framework.

I got this error inr Image
the submitted data was not a file. check the encoding type on the form.

Service

addPosts(title: string, content: string, image: File, category: string, tags: string[]){
   let url = 'api/posts/post/';
   const formData = new FormData();

   formData.append("title", title);
   formData.append("content", content);
   formData.append("category", category);
   formData.append("tags", tags);
   formData.append("image", image);

   const post: Post = {title:title, content:content, image: image, category:category, tags:tags};

   let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
   let options = new RequestOptions({ headers: headers });

   this.http.post(url, post, options)
   .subscribe(responseData => {
     this.posts.push(post);
     this.postsUpdate.next([...this.posts]);
   });
 }

when i use FormData i can't sent tags because i think FormData didn't support it and when i sent directly post i got
the submitted data was not a file. check the encoding type on the form.

Body:
addPosts(title: string, content: string, image: File, category: string, tags: string[]){
   let url = 'api/posts/post/';
   const formData = new FormData();

   formData.append("title", title);
   formData.append("content", content);
   formData.append("category", category);
   formData.append("tags", tags);
   formData.append("image", image);

   const post: Post = {title:title, content:content, image: image, category:category, tags:tags};<------you set This

   let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
   let options = new RequestOptions({ headers: headers });

Set formData

  this.http.post(url, post, options)<-----set Form Data instead of ` const post: Post`
   .subscribe(responseData => {
     this.posts.push(post);
     this.postsUpdate.next([...this.posts]);
   });
 }


问:
All declarations of 'stream' must have identical modifiers api-ai-javascript - Dialogflow
I am trying to integrate Dialogflow in Angular 7. I am getting this error.</p>

```<code>  ** Angular Live Development Server is listening on localhost:4200,
open your browser on http://localhost:4200/ **

Date: 2018-11-22T13:47:11.748Z
Hash: 4075ca64830b90f82558
Time: 4597ms
chunk {main} main.js, main.js.map (main) 1.85 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 92.4 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 16.2 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 318 kB [initial] [rendered]

ERROR in node_modules/api-ai-javascript/declarations.d.ts(39,5): error TS2687: All declarations of 'stream' must have identical modifiers.

ℹ ｢wdm｣: Failed to compile.
</code>```

答:
I had the same error and only with below changing in import line, it fixed.</p>

```<code>import {ApiAiClient} from 'api-ai-javascript/es6/ApiAiClient';
</code>```

Body:
I am trying to integrate Dialogflow in Angular 7. I am getting this error.

  ** Angular Live Development Server is listening on localhost:4200,
open your browser on http://localhost:4200/ **

Date: 2018-11-22T13:47:11.748Z
Hash: 4075ca64830b90f82558
Time: 4597ms
chunk {main} main.js, main.js.map (main) 1.85 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 92.4 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 16.2 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 318 kB [initial] [rendered]

ERROR in node_modules/api-ai-javascript/declarations.d.ts(39,5): error TS2687: All declarations of 'stream' must have identical modifiers.

ℹ ｢wdm｣: Failed to compile.

Body:
I had the same error and only with below changing in import line, it fixed.

import {ApiAiClient} from 'api-ai-javascript/es6/ApiAiClient';


问:
Is it Ok to use a <fragment> tag inside a layout of a RecyclerView's ViewHolder?
May question is whether a RecyclerView's ViewHolder's layout can have a <fragment> tag such as this:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:name="com.some.FragmentOne"
        android:id="@+id/somefragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>
</code>```

答:
This is not a good idea.

you'd be better to use  a ScrollView around a LinearLayout that the fragments are loaded into. The fragments will be loaded slightly sooner than with a RecyclerView, but you won't have to fight all the recycling infrastructure that you're not taking advantage of.

The fragments are going to be loaded on top of each other because when you commit the transaction, you're not actually changing the view. You're telling the fragment manager, "Hey, when you get a chance can you hook up this fragment to this ViewGroup ID?" The fragment manager goes with the first instance of that view ID that it finds, and so they get loaded on top of each other.

You might be able to get around that by having different IDs for the different positions, but I wouldn't recommend it.

Body:
May question is whether a RecyclerView's ViewHolder's layout can have a <fragment> tag such as this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:name="com.some.FragmentOne"
        android:id="@+id/somefragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>


问:
How to concatenate multiple data frames with long index without error?
I have a directory ".../dados" in which have multiple subdirectories whose names are a serial number plus some useless information - e.g. "17448_2017_Jul_2017_Oct", where the first number on it is the serial number. Inside each subdirectory, I have four ".txt" files whose lines/rows have the information of date and time, and an attribute of a certain type, say humidity, all named the same way in each subdirectory - e.g. "2019-01-29 03:11:26 54.7".

I want to concatenate all of them in order to generate a dataset with date index.

```<code>path = "/.../dados/"

df = pd.DataFrame()

for fld in os.listdir(path):
    subfld = path + fld
    if os.path.isdir(subfld):
        aux = pd.DataFrame()
        sn = fld.split('_')[0]
        for file in os.listdir(subfld):
            filepath = os.path.join(subfld, file)
            if os.path.isfile(filepath):
                new_col = pd.read_fwf(filepath, colspecs=[(0, 19), (20, -1)], skiprows=8, names=[file.split('_')[2][:-4]], parse_dates=[0], nrows=9999999)
                aux = pd.concat([aux, new_col], axis=1,  sort=False)
        aux['Machine'] = sn
        df = df.append(aux)
</code>```

This is a print of df.head(10):

```<code>HumTechRoom  TempTechRoom  TempExamRoom  HumExamRoom Machine
2018-03-04 00:45:11         82.6           NaN           NaN          NaN   22162
2018-03-04 00:45:47         80.0           NaN           NaN          NaN   22162
2018-03-04 00:45:53         78.0           NaN           NaN          NaN   22162
2018-03-04 00:46:04         75.9           NaN           NaN          NaN   22162
2018-03-04 00:46:20         73.7           NaN           NaN         51.3   22162
2018-03-04 00:46:58         71.7           NaN           NaN          NaN   22162
2018-03-04 00:47:40          NaN           NaN           NaN         53.4   22162
2018-03-04 00:47:41          NaN          14.5           NaN          NaN   22162
2018-03-04 00:47:54         74.3           NaN           NaN          NaN   22162
2018-03-04 00:47:59         76.6           NaN           NaN          NaN   22162
</code>```

THis is the error message that I get:

```<code>...
line 31, in <module>
    aux = pd.concat([aux, new_col], axis=1,  sort=False)

  File ".../concat.py", line 226, in concat
    return op.get_result()

  File ".../concat.py", line 423, in get_result
    copy=self.copy)

  File ".../internals.py", line 5425, in concatenate_block_managers
    return BlockManager(blocks, axes)

  File ".../internals.py", line 3282, in __init__
    self._verify_integrity()

  File ".../internals.py", line 3493, in _verify_integrity
    construction_error(tot_items, block.shape[1:], self.axes)

  File ".../internals.py", line 4843, in construction_error
    passed, implied))

ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)
</code>```

答:
Your DataFrames are of incompatible shape:

```<code>ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)
</code>```

In other words, the problem is that 19687 != 19685. Whatever answer you come across is going to come out of the specifics of your data, which is probably not practical to share, given its size. You need to, at least, add or delete 2 rows somewhere. You'll need to investigate to determine what and where.

Body:
I have a directory ".../dados" in which have multiple subdirectories whose names are a serial number plus some useless information - e.g. "17448_2017_Jul_2017_Oct", where the first number on it is the serial number. Inside each subdirectory, I have four ".txt" files whose lines/rows have the information of date and time, and an attribute of a certain type, say humidity, all named the same way in each subdirectory - e.g. "2019-01-29 03:11:26 54.7".

I want to concatenate all of them in order to generate a dataset with date index.

path = "/.../dados/"

df = pd.DataFrame()

for fld in os.listdir(path):
    subfld = path + fld
    if os.path.isdir(subfld):
        aux = pd.DataFrame()
        sn = fld.split('_')[0]
        for file in os.listdir(subfld):
            filepath = os.path.join(subfld, file)
            if os.path.isfile(filepath):
                new_col = pd.read_fwf(filepath, colspecs=[(0, 19), (20, -1)], skiprows=8, names=[file.split('_')[2][:-4]], parse_dates=[0], nrows=9999999)
                aux = pd.concat([aux, new_col], axis=1,  sort=False)
        aux['Machine'] = sn
        df = df.append(aux)

This is a print of df.head(10):

HumTechRoom  TempTechRoom  TempExamRoom  HumExamRoom Machine
2018-03-04 00:45:11         82.6           NaN           NaN          NaN   22162
2018-03-04 00:45:47         80.0           NaN           NaN          NaN   22162
2018-03-04 00:45:53         78.0           NaN           NaN          NaN   22162
2018-03-04 00:46:04         75.9           NaN           NaN          NaN   22162
2018-03-04 00:46:20         73.7           NaN           NaN         51.3   22162
2018-03-04 00:46:58         71.7           NaN           NaN          NaN   22162
2018-03-04 00:47:40          NaN           NaN           NaN         53.4   22162
2018-03-04 00:47:41          NaN          14.5           NaN          NaN   22162
2018-03-04 00:47:54         74.3           NaN           NaN          NaN   22162
2018-03-04 00:47:59         76.6           NaN           NaN          NaN   22162

THis is the error message that I get:

...
line 31, in <module>
    aux = pd.concat([aux, new_col], axis=1,  sort=False)

  File ".../concat.py", line 226, in concat
    return op.get_result()

  File ".../concat.py", line 423, in get_result
    copy=self.copy)

  File ".../internals.py", line 5425, in concatenate_block_managers
    return BlockManager(blocks, axes)

  File ".../internals.py", line 3282, in __init__
    self._verify_integrity()

  File ".../internals.py", line 3493, in _verify_integrity
    construction_error(tot_items, block.shape[1:], self.axes)

  File ".../internals.py", line 4843, in construction_error
    passed, implied))

ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)

Body:
Your DataFrames are of incompatible shape:

ValueError: Shape of passed values is (2, 19687), indices imply (2, 19685)

In other words, the problem is that 19687 != 19685. Whatever answer you come across is going to come out of the specifics of your data, which is probably not practical to share, given its size. You need to, at least, add or delete 2 rows somewhere. You'll need to investigate to determine what and where.


问:
Leaflet event: how to propagate to overlapping layers
Let's say I have some overlapping layers and each layer has a click event. When I click on the map, I'd like to know which layers are clicked on, though the click event stops after the first layer and does not propagate to its underlying layers. How can I achieve this?

Here's a sample fiddle and its code: https://jsfiddle.net/r0r0xLoc/

```<code><div id="mapid" style="width: 600px; height: 400px;"></div>

<script>
  var mymap = L.map('mapid').setView([51.505, -0.09], 13);

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
      '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
      'Imagery © <a href="http://mapbox.com">Mapbox</a>',
    id: 'mapbox.streets'
  }).addTo(mymap);

  L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
  ]).addTo(mymap).on('click', function() {
    console.log('clicked on 1st polygon')
  });

  L.polygon([
    [51.609, -0.1],
    [51.503, -0.06],
    [51.51, -0.047]
  ]).addTo(mymap).on('click', function() {
    console.log('clicked on 2nd polygon')
  });

</script>
</code>```

If you click on each polygon, you see its related message. If you click on the overlapping part, you only see the message for the second polygon.

答:
There is a leaflet plugin for propagating events to the underlying layers: https://github.com/danwild/leaflet-event-forwarder

You can use it in your javascript to enable event-forwarding, e.g.:

```<code>const myEventForwarder = new L.eventForwarder({
  map: map,
  events: {click: true, mousemove: false}
});
</code>```

Body:
Let's say I have some overlapping layers and each layer has a click event. When I click on the map, I'd like to know which layers are clicked on, though the click event stops after the first layer and does not propagate to its underlying layers. How can I achieve this?

Here's a sample fiddle and its code: https://jsfiddle.net/r0r0xLoc/

If you click on each polygon, you see its related message. If you click on the overlapping part, you only see the message for the second polygon.

Body:
There is a leaflet plugin for propagating events to the underlying layers: https://github.com/danwild/leaflet-event-forwarder

You can use it in your javascript to enable event-forwarding, e.g.:

const myEventForwarder = new L.eventForwarder({
  map: map,
  events: {click: true, mousemove: false}
});


问:
2D array on CUDA
I want to dynamically allocate global 2D array in CUDA. How can I achieve this?

In my main I am calling my Kernel in a loop. But before I call the kernel I need to allocate some memory on the GPU. After the kernel call a single integer is send from GPU to CPU to inform whether the problem is solved or not.

If the problem is not solved, I will not free the old memory , since there is a further need of it, and I should allocate new memory to the GPU and call the kernel again.

a sudocode is shown:

```<code>int n=0,i=0;
while(n==0)
{
    //allocate 2d memory for MEM[i++]
    //call kernel(MEM,i)
    // get n from kernel
}

__global__ void kernerl(Mem,int i)
{
    Mem[0][5]=1;
    Mem[1][0]=Mem[0][5]+23;//can use this when MEM[1] is allocated before kernel call
}
</code>```

Any suggestions? Thank you.

答:
Well, you can do it just as it would be done on CPU.

```<code>unsigned xSize = 666, ySize = 666;
int **h_ptr = (int**)malloc(sizeof(int*) * xSize);
int **d_ptr = NULL;
cudaMalloc( &d_ptr, xSize );
for(unsigned i = 0; i < xSize; ++i)
{
    cudaMalloc( &h_ptr[i], ySize );
}
cudaMemcpy( &d_ptr, &h_ptr, sizeof(int*) * xSize, cudaMemcpyHostToDevice );
free( h_ptr );
</code>```

...and free similiarly

```<code>int **h_ptr = (int**)malloc(sizeof(int*) * xSize);
cudaMemcpy( &h_ptr, &d_ptr, sizeof(int*) * xSize, cudaMemcpyDeviceToHost );
for(unsigned i = 0; i < xSize; ++i )
{
    cudaFree( h_ptr[i] );
}
cudaFree( d_ptr );
free( h_ptr );
</code>```

But you should keep in mind, that every access to a cell of this array will involve accesing GPU global memory twice. Due to that, memory access will be two times slower than with 1d array.

ContentLicense: CC BY-SA 3.0

Title: 2D array on CUDA

Body:
I want to dynamically allocate global 2D array in CUDA. How can I achieve this?

In my main I am calling my Kernel in a loop. But before I call the kernel I need to allocate some memory on the GPU. After the kernel call a single integer is send from GPU to CPU to inform whether the problem is solved or not.

If the problem is not solved, I will not free the old memory , since there is a further need of it, and I should allocate new memory to the GPU and call the kernel again.

a sudocode is shown:

int n=0,i=0;
while(n==0)
{
    //allocate 2d memory for MEM[i++]
    //call kernel(MEM,i)
    // get n from kernel
}

__global__ void kernerl(Mem,int i)
{
    Mem[0][5]=1;
    Mem[1][0]=Mem[0][5]+23;//can use this when MEM[1] is allocated before kernel call
}

Any suggestions? Thank you.

Body:
Well, you can do it just as it would be done on CPU.

unsigned xSize = 666, ySize = 666;
int **h_ptr = (int**)malloc(sizeof(int*) * xSize);
int **d_ptr = NULL;
cudaMalloc( &d_ptr, xSize );
for(unsigned i = 0; i < xSize; ++i)
{
    cudaMalloc( &h_ptr[i], ySize );
}
cudaMemcpy( &d_ptr, &h_ptr, sizeof(int*) * xSize, cudaMemcpyHostToDevice );
free( h_ptr );

...and free similiarly

int **h_ptr = (int**)malloc(sizeof(int*) * xSize);
cudaMemcpy( &h_ptr, &d_ptr, sizeof(int*) * xSize, cudaMemcpyDeviceToHost );
for(unsigned i = 0; i < xSize; ++i )
{
    cudaFree( h_ptr[i] );
}
cudaFree( d_ptr );
free( h_ptr );

But you should keep in mind, that every access to a cell of this array will involve accesing GPU global memory twice. Due to that, memory access will be two times slower than with 1d array.


问:
Importxml into Google Sheets automatically
I want to know how to import data using the Importxml function in Google spreadsheets.

https://www.tigeretf.com/front/products/product.do?ksdFund=KR7305080004&fundTypeCode=01000800

Above

```<code><기준가격(원)>
</code>```

I want to import data.

importxml(I2,I3)

I2 = https://www.tigeretf.com/front/products/product.do?ksdFund=KR7305080004&fundTypeCode=01000800

I3 = //*[@id="container"]/div[2]/div[2]/div[1]/div/table/tbody/tr/td[2]/strong/text()

Data is being loaded and cannot be refreshed.

I want the <기준가격(원)> data to be loaded automatically every time the sheet is refreshed.

答:
perhaps try like this:

```<code>=QUERY(IMPORTXML(
 "https://www.tigeretf.com/front/products/product.do?ksdFund=KR7305080004&fundTypeCode=01000800",
 "//strong[@class='price']"), "offset 1")
</code>```

Body:
I want to know how to import data using the Importxml function in Google spreadsheets.

https://www.tigeretf.com/front/products/product.do?ksdFund=KR7305080004&fundTypeCode=01000800

Above

<기준가격(원)>

I want to import data.

importxml(I2,I3)

I2 = https://www.tigeretf.com/front/products/product.do?ksdFund=KR7305080004&fundTypeCode=01000800

I3 = //*[@id="container"]/div[2]/div[2]/div[1]/div/table/tbody/tr/td[2]/strong/text()

Data is being loaded and cannot be refreshed.

I want the <기준가격(원)> data to be loaded automatically every time the sheet is refreshed.

Body:
perhaps try like this:

=QUERY(IMPORTXML(
 "https://www.tigeretf.com/front/products/product.do?ksdFund=KR7305080004&fundTypeCode=01000800",
 "//strong[@class='price']"), "offset 1")


问:
What does letter D represent in floating-point data
I have attached two pictures below in which I am stuck on one thing which is letter  D. In floating-point why letter D is used? Letter E represents exponent but what letter D represents?

Please tell me the use of D
Thanks

答:
Since single is 4-bytes and double is 8-bytes, the precision of each is such:

```<code>SINGLE  2.802597E-45 to 3.402823E+38
DOUBLE  4.490656458412465D-324 to 1.797693134862310D+308
</code>```

QB64 also has a 32-byte variable which is:

```<code>_FLOAT  1.18E-4932 to 1.18E+4932
</code>```

Body:
Since single is 4-bytes and double is 8-bytes, the precision of each is such:

SINGLE  2.802597E-45 to 3.402823E+38
DOUBLE  4.490656458412465D-324 to 1.797693134862310D+308

QB64 also has a 32-byte variable which is:

_FLOAT  1.18E-4932 to 1.18E+4932


问:
How to store weight values and converting to standard/metric weights?
I'm working on a Vue application, and one of the features deals with weight values. I'm currently storing them in my database as grams, and then converting them to pounds. Eventually I'd like to be able to have the user choose between metric and standard computations. I've created a function that returns four calculations, however they don't seem to add up correctly.

```<code>export const convertToPounds = weight => {
  return (Math.round((weight / 453.592) * 10) / 10).toFixed(2);
};
</code>```

This function is run four times. Once for the total, and three times based on which category the items filter into.

```<code>Total - 4170 grams converts to 9.20 lbs
ValueA - 2700 grams converts to 6.00 lbs
ValueB - 1400 grams converts to 3.10 lbs
ValueC - 70 grams converts to 0.20 lbs
</code>```

Looking at the final conversions though, the three values add up to 9.30 rather than the 9.20 that should be returned.

My question is whether the conversion method is too inaccurate to handle these types of conversions? Or is storing weights in grams not the best way to handle this scenario?

答:
I think your issue is that you are first Rounding it and then doing toFixed(2) which further rounds it. I checked briefly on google and it appears correct calculation: https://www.google.com/search?q=4170+grams+to+pounds

const convertToPounds = weight => {
  return (weight / 453.592).toFixed(2);
};

// Total - 4170 grams converts to 9.20 lbs
console.log(convertToPounds(4170));
// ValueA - 2700 grams converts to 6.00 lbs
console.log(convertToPounds(2700));
// ValueB - 1400 grams converts to 3.10 lbs
console.log(convertToPounds(1400));
// ValueC - 70 grams converts to 0.20 lbs
console.log(convertToPounds(70));```

Body:
I'm working on a Vue application, and one of the features deals with weight values. I'm currently storing them in my database as grams, and then converting them to pounds. Eventually I'd like to be able to have the user choose between metric and standard computations. I've created a function that returns four calculations, however they don't seem to add up correctly.

export const convertToPounds = weight => {
  return (Math.round((weight / 453.592) * 10) / 10).toFixed(2);
};

This function is run four times. Once for the total, and three times based on which category the items filter into.

Total - 4170 grams converts to 9.20 lbs
ValueA - 2700 grams converts to 6.00 lbs
ValueB - 1400 grams converts to 3.10 lbs
ValueC - 70 grams converts to 0.20 lbs

Looking at the final conversions though, the three values add up to 9.30 rather than the 9.20 that should be returned.

My question is whether the conversion method is too inaccurate to handle these types of conversions? Or is storing weights in grams not the best way to handle this scenario?


问:
Add comma from print json_encode
How to add commas to a json print?

```<code>$result = curl($url);
$result = json_decode($result , true);

$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}
</code>```

this is the response from my code

```<code>{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
}
{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
}
{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}
</code>```

I want to have a comma for each json result

```<code>{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
},{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
},{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}
</code>```

答:
I don't get the point of having ',' but I'm guessing you want a valid json output. If so I guess that your result data is an array:

```<code><?php
$result = [ 'data' => [
            [
                "id" => "17996292388215089",
                "username" => "hanikfadhilah",
                "text" => "Loh kapan ini huuu pengen"
            ],
            [
                "id" => "17877856039348099",
                "username" => "titan_kdk",
                "text" => "Mntb"
            ],
            [
                "id" => "17860767967398064",
                "username" => "explorecentraljava",
                "text" => "Terbaik fotonya lur"
            ]
        ]
    ];
</code>```

so all what you need to do in order to get it as a valid json is:

```<code>print json_encode($result['data'], JSON_PRETTY_PRINT);
</code>```

that produces output:

```<code>[
    {
        "id": "17996292388215089",
        "username": "hanikfadhilah",
        "text": "Loh kapan ini huuu pengen"
    },
    {
        "id": "17877856039348099",
        "username": "titan_kdk",
        "text": "Mntb"
    },
    {
        "id": "17860767967398064",
        "username": "explorecentraljava",
        "text": "Terbaik fotonya lur"
    }
]
</code>```

no need for any foreach loop.

json_encode()

Title: Add comma from print json_encode

Body:
How to add commas to a json print?

$result = curl($url);
$result = json_decode($result , true);

$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}

this is the response from my code

{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
}
{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
}
{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}

I want to have a comma for each json result

{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
},{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
},{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}

Body:
I don't get the point of having ',' but I'm guessing you want a valid json output. If so I guess that your result data is an array:

<?php
$result = [ 'data' => [
            [
                "id" => "17996292388215089",
                "username" => "hanikfadhilah",
                "text" => "Loh kapan ini huuu pengen"
            ],
            [
                "id" => "17877856039348099",
                "username" => "titan_kdk",
                "text" => "Mntb"
            ],
            [
                "id" => "17860767967398064",
                "username" => "explorecentraljava",
                "text" => "Terbaik fotonya lur"
            ]
        ]
    ];

so all what you need to do in order to get it as a valid json is:

print json_encode($result['data'], JSON_PRETTY_PRINT);

that produces output:

[
    {
        "id": "17996292388215089",
        "username": "hanikfadhilah",
        "text": "Loh kapan ini huuu pengen"
    },
    {
        "id": "17877856039348099",
        "username": "titan_kdk",
        "text": "Mntb"
    },
    {
        "id": "17860767967398064",
        "username": "explorecentraljava",
        "text": "Terbaik fotonya lur"
    }
]

no need for any foreach loop.

json_encode()


问:
rails not picking session data
I am implementing a payment gateway in my app.
Its like this:
The user fills the form with necessary details, along with a field containing return_url(say http://myapp.com/ebs_payment/ebs_response?dr={somedata}) and submit the form to a secure payment site. After the transaction is complete, the secure site puts some encrypted data into my param {dr} and the user is redirected back to the return url. The problem here is, when the user returns to the app with the return_url, the application fails to pick up the session data and returns a nil value.

Before submitting the form, I put the object @fdPaymentDets in to session.

Here is my controller:

```<code>class EbsPaymentController < ApplicationController
  #before_filter :login_required,:check_user_authenticate
  #access_control [:ebs_response] => ('user')

  def ebs_response
    @fdPaymentDets = session["fd_payment_details"]

    @deal = Deal.find(@fdPaymentDets.deal_id)

    @categories = find_all_categories
  end

  private
  def find_all_categories
     @sp = SitePreference.find(:first)
     Category.find(:all,:limit => @sp.categories_display_limit,:order => 'position')
  end

end
</code>```

When the user is redirected to the return url (http://myapp.com/ebs_payment/ebs_response?dr={encrypted_data}) from the secure site, rails is not picking the @fdPaymentDets object from session and making it nil thus resulting in an error when accessing data from the nil object.

The surprising thing is that, when I put the same return_url in my browser by hand, the session data is neatly picked and everything goes well.

Am missing any thing here? What could be the obvious reason?
Any help appreciated.

答:
Cookies and redirects are messy and bug prone (from a browser's implementation perspective).
Take a look at

Safari doesn't set Cookie but IE / FF does

Suggestion would be to change the implementation to set the session first in the show action, and then update the value before the redirect

Title: rails not picking session data

Body:
I am implementing a payment gateway in my app.
Its like this:
The user fills the form with necessary details, along with a field containing return_url(say http://myapp.com/ebs_payment/ebs_response?dr={somedata}) and submit the form to a secure payment site. After the transaction is complete, the secure site puts some encrypted data into my param {dr} and the user is redirected back to the return url. The problem here is, when the user returns to the app with the return_url, the application fails to pick up the session data and returns a nil value.

Before submitting the form, I put the object @fdPaymentDets in to session.

Here is my controller:

class EbsPaymentController < ApplicationController
  #before_filter :login_required,:check_user_authenticate
  #access_control [:ebs_response] => ('user')

  def ebs_response
    @fdPaymentDets = session["fd_payment_details"]

    @deal = Deal.find(@fdPaymentDets.deal_id)

    @categories = find_all_categories
  end

  private
  def find_all_categories
     @sp = SitePreference.find(:first)
     Category.find(:all,:limit => @sp.categories_display_limit,:order => 'position')
  end

end

When the user is redirected to the return url (http://myapp.com/ebs_payment/ebs_response?dr={encrypted_data}) from the secure site, rails is not picking the @fdPaymentDets object from session and making it nil thus resulting in an error when accessing data from the nil object.

The surprising thing is that, when I put the same return_url in my browser by hand, the session data is neatly picked and everything goes well.

Am missing any thing here? What could be the obvious reason?
Any help appreciated.


问:
how to make for-loop order to rbind all excel files in the same directory
i want to rbind all excel files (regardless the total amount of files) in a directory and make a new column that is filled with the name of files, so then i could identify where the data came from. For example, i have template of file like this

```<code>promo  stock
  a     200
  b     200
  c     200
</code>```

to be like this

```<code>store  promo  stock
file1    a     200
file1    b     200
file1    c     200
file2    a     200
file2    b     200
file2    c     200
file3    a     200
file3    b     200
file3    c     200
</code>```

how to make a for-loop order for this case? thanx in advance

答:
This should do it although Reduce(rbind) might be slow depending on how many files you have. Also you may need to modify the code to read your file based on the extension. Let me know -

```<code># set working directory to where the files are using setwd()

result <- lapply(dir(), function(x) {
  cbind(store = x, read.csv(paste0(x, ".csv"), header = T, stringsAsFactors = F))
}) %>%
  {Reduce(rbind, .)}
</code>```

Body:
i want to rbind all excel files (regardless the total amount of files) in a directory and make a new column that is filled with the name of files, so then i could identify where the data came from. For example, i have template of file like this

promo  stock
  a     200
  b     200
  c     200

to be like this

store  promo  stock
file1    a     200
file1    b     200
file1    c     200
file2    a     200
file2    b     200
file2    c     200
file3    a     200
file3    b     200
file3    c     200

how to make a for-loop order for this case? thanx in advance

Body:
This should do it although Reduce(rbind) might be slow depending on how many files you have. Also you may need to modify the code to read your file based on the extension. Let me know -

# set working directory to where the files are using setwd()

result <- lapply(dir(), function(x) {
  cbind(store = x, read.csv(paste0(x, ".csv"), header = T, stringsAsFactors = F))
}) %>%
  {Reduce(rbind, .)}


问:
Laravel Queue Cache not updating
I have used Laravel queues in my application and when i try to run

```<code> php artisan queue:restart
</code>```

it gives me following exception:

```<code> ErrorException  : file_put_contents(/storage/framework/cache/data/ee/2f/ee2f842aa7bb1f53edf3a2ed2c09a1807ffa6c90): failed to open stream: No such file or directory

  at /var/www/html/asd/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122
    118|      * @return int
    119|      */
    120|     public function put($path, $contents, $lock = false)
    121|     {
  > 122|         return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
    123|     }
    124|
    125|     /**
    126|      * Prepend to a file.

  Exception trace:

  1   file_put_contents("/var/www/html/asd/storage/framework/cache/data/ee/2f/ee2f842aa7bb1f53edf3a2ed2c09a1807ffa6c90", "9999999999i:1558912298;")
      /var/www/html/asd/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122

  2   Illuminate\Filesystem\Filesystem::put("/var/www/html/asd/storage/framework/cache/data/ee/2f/ee2f842aa7bb1f53edf3a2ed2c09a1807ffa6c90", "9999999999i:1558912298;")
      /var/www/html/asd/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php:65

  Please use the argument -v to see more details.
</code>```

I have tried running following commands but to no avail:

```<code>composer dump-autoload
php artisan optimize
php artisan clear-compiled
php artisan cache:clear
php artisan view:clear
php artisan route:cache
</code>```

I am not able to reflect changes made to my application logic that is in queue handlers, any help in this regard is much appreciated.

答: You forgot to run php artisan config:cache with the other commands

Title: Laravel Queue Cache not updating

Body:
I have used Laravel queues in my application and when i try to run

 php artisan queue:restart

it gives me following exception:

 ErrorException  : file_put_contents(/storage/framework/cache/data/ee/2f/ee2f842aa7bb1f53edf3a2ed2c09a1807ffa6c90): failed to open stream: No such file or directory

  at /var/www/html/asd/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122
    118|      * @return int
    119|      */
    120|     public function put($path, $contents, $lock = false)
    121|     {
  > 122|         return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
    123|     }
    124|
    125|     /**
    126|      * Prepend to a file.

  Exception trace:

  1   file_put_contents("/var/www/html/asd/storage/framework/cache/data/ee/2f/ee2f842aa7bb1f53edf3a2ed2c09a1807ffa6c90", "9999999999i:1558912298;")
      /var/www/html/asd/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122

  2   Illuminate\Filesystem\Filesystem::put("/var/www/html/asd/storage/framework/cache/data/ee/2f/ee2f842aa7bb1f53edf3a2ed2c09a1807ffa6c90", "9999999999i:1558912298;")
      /var/www/html/asd/vendor/laravel/framework/src/Illuminate/Cache/FileStore.php:65

  Please use the argument -v to see more details.

I have tried running following commands but to no avail:

composer dump-autoload
php artisan optimize
php artisan clear-compiled
php artisan cache:clear
php artisan view:clear
php artisan route:cache

I am not able to reflect changes made to my application logic that is in queue handlers, any help in this regard is much appreciated.


问:
Using ILOC without chained-indexing
So I wanted to select the first 10 rows of a dataframe but by a specific column name (e.g 'Price'). Obviously I could do this:

df.iloc[0:10]['Price']

But I want to avoid chained indexing. Is there a way to accomplish this? I can't use LOC because there are no index that are numbered 0,1,2,etc.

答:
a few other ways using iloc with named column:

```<code>df.iloc[:10, df.columns.get_loc('Price')]
</code>```

or

```<code>df.iloc[:10, (df.columns=='Price').nonzero()[0]]
</code>```

Title: Using ILOC without chained-indexing

Body:
a few other ways using iloc with named column:

df.iloc[:10, df.columns.get_loc('Price')]

or

df.iloc[:10, (df.columns=='Price').nonzero()[0]]


问:
Volley request JSONArray should be recognized if it was empty
I am using Volley to get JSON from remote PHP script.
Sometimes, the JSON array is empty.

This my code:

```<code>StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                    for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                );
                        list_data.add(listData);
                        spinner.setVisibility(View.GONE);
                    }
                    rv.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);
                Toast.makeText(getActivity(),
                        "No tienes notificaciones.", Toast.LENGTH_LONG)
                        .show();
                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
</code>```

If the JSON array is empty, then I am getting the response listener message saying that data[] is empty, but the Toast is not showing and also the spinner visibility is not gone as expected.

How should I change in my code to launch a Toast and to set the spinner visibility to GONE when the received JSON array is empty?

答:
public void onResponse(String response) means you request get response successfully and parse successfully, but this callback did not means the data value is not empty!

public void onErrorResponse(VolleyError error) means the request failed to get response, maybe error http code, or request successfully but parse failed.

So as you wish you want to do something when the request is success but data array is empty, you should add a logic both in the public void onResponse(String response) method to check the successfully response but data is empty situation

```<code>@Override
public void onResponse(String response) {
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray array = jsonObject.getJSONArray("data");

        if (array == null || array.length() == 0) {

            //data array is empty

            // add the logic you want

        } else {

            //data array not empty
            for (int i = 0; i < array.length(); i++) {
                JSONObject ob = array.getJSONObject(i);
                Notificacion listData = new Notificacion(ob.getString("id_notificacion")
                        , ob.getString("texto"),
                        ob.getString("fecha"),
                        ob.getString("nombre"),
                        ob.getString("nombre") + " " + ob.getString("apellidos"),
                        ob.getString("profesor"),
                        ob.getString("tutor"),
                        ob.getString("estado"),
                        ob.getString("envia_tutor"),
                        ob.getString("envia_profesor")

                );
                list_data.add(listData);
                spinner.setVisibility(View.GONE);
            }
            rv.setAdapter(adapter);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

Body:
I am using Volley to get JSON from remote PHP script.
Sometimes, the JSON array is empty.

This my code:

StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                    for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                );
                        list_data.add(listData);
                        spinner.setVisibility(View.GONE);
                    }
                    rv.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);
                Toast.makeText(getActivity(),
                        "No tienes notificaciones.", Toast.LENGTH_LONG)
                        .show();
                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);

If the JSON array is empty, then I am getting the response listener message saying that data[] is empty, but the Toast is not showing and also the spinner visibility is not gone as expected.

How should I change in my code to launch a Toast and to set the spinner visibility to GONE when the received JSON array is empty?

Body:
public void onResponse(String response) means you request get response successfully and parse successfully, but this callback did not means the data value is not empty!

public void onErrorResponse(VolleyError error) means the request failed to get response, maybe error http code, or request successfully but parse failed.

So as you wish you want to do something when the request is success but data array is empty, you should add a logic both in the public void onResponse(String response) method to check the successfully response but data is empty situation

@Override
public void onResponse(String response) {
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray array = jsonObject.getJSONArray("data");

        if (array == null || array.length() == 0) {

            //data array is empty

            // add the logic you want

        } else {

            //data array not empty
            for (int i = 0; i < array.length(); i++) {
                JSONObject ob = array.getJSONObject(i);
                Notificacion listData = new Notificacion(ob.getString("id_notificacion")
                        , ob.getString("texto"),
                        ob.getString("fecha"),
                        ob.getString("nombre"),
                        ob.getString("nombre") + " " + ob.getString("apellidos"),
                        ob.getString("profesor"),
                        ob.getString("tutor"),
                        ob.getString("estado"),
                        ob.getString("envia_tutor"),
                        ob.getString("envia_profesor")

                );
                list_data.add(listData);
                spinner.setVisibility(View.GONE);
            }
            rv.setAdapter(adapter);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}


问:
Why can't we record an incoming call in an android application?
is there any way to record an incoming call through android code?

If this feature doesn't exist, then how can some third party applications record calls?

答:
The ability to record a call is hardware or firmware dependent. Most Android phones don't have their internal "wiring" of audio path set up such that voice call audio reaches the application processor at all.

The apps that enable you to record a call on the market either:

Work only on those specific phones where the above is not true (very few models)

Or use a hack where they ask you to use a speakerphone and record the call audio actually from the phone microphone catching what the phone speakers send out...


问:
Determine if an object exists in a S3 bucket based on wildcard
Can someone please show me how to determine if a certain file/object exists in a S3 bucket and display a message if it exists or if it does not exist.

Basically I want it to:

1) Check a bucket on my S3 account such as testbucket

2) Inside of that bucket, look to see if there is a file with the prefix test_ (test_file.txt or test_data.txt).

3) If that file exists, then display a MessageBox (or Console message) that the file exists, or that the file does not exist.

Can someone please show me how to do this?

答:
Not sure if this applies to .NET Framework, but the .NET Core version of AWS SDK (v3) only supports async requests, so I had to use a slightly different solution:

```<code>/// <summary>
/// Determines whether a file exists within the specified bucket
/// </summary>
/// <param name="bucket">The name of the bucket to search</param>
/// <param name="filePrefix">Match files that begin with this prefix</param>
/// <returns>True if the file exists</returns>
public async Task<bool> FileExists(string bucket, string filePrefix)
{
    // Set this to your S3 region (of course)
    var region = Amazon.RegionEndpoint.USEast1;

    using (var client = new AmazonS3Client(region))
    {
        var request = new ListObjectsRequest {
            BucketName = bucket,
            Prefix = filePrefix,
            MaxKeys = 1
        };

        var response = await client.ListObjectsAsync(request, CancellationToken.None);

        return response.S3Objects.Any();
    }
}
</code>```

And, if you want to search a folder:

```<code>/// <summary>
/// Determines whether a file exists within the specified folder
/// </summary>
/// <param name="bucket">The name of the bucket to search</param>
/// <param name="folder">The name of the folder to search</param>
/// <param name="filePrefix">Match files that begin with this prefix</param>
/// <returns>True if the file exists</returns>
public async Task<bool> FileExists(string bucket, string folder, string filePrefix)
{
    return await FileExists(bucket, $"{folder}/{filePrefix}");
}
</code>```

Usage:

```<code>var testExists = await FileExists("testBucket", "test_");
// or...
var testExistsInFolder = await FileExists("testBucket", "testFolder/testSubFolder", "test_");
</code>```

Body:
Not sure if this applies to .NET Framework, but the .NET Core version of AWS SDK (v3) only supports async requests, so I had to use a slightly different solution:

/// <summary>
/// Determines whether a file exists within the specified bucket
/// </summary>
/// <param name="bucket">The name of the bucket to search</param>
/// <param name="filePrefix">Match files that begin with this prefix</param>
/// <returns>True if the file exists</returns>
public async Task<bool> FileExists(string bucket, string filePrefix)
{
    // Set this to your S3 region (of course)
    var region = Amazon.RegionEndpoint.USEast1;

    using (var client = new AmazonS3Client(region))
    {
        var request = new ListObjectsRequest {
            BucketName = bucket,
            Prefix = filePrefix,
            MaxKeys = 1
        };

        var response = await client.ListObjectsAsync(request, CancellationToken.None);

        return response.S3Objects.Any();
    }
}

And, if you want to search a folder:

/// <summary>
/// Determines whether a file exists within the specified folder
/// </summary>
/// <param name="bucket">The name of the bucket to search</param>
/// <param name="folder">The name of the folder to search</param>
/// <param name="filePrefix">Match files that begin with this prefix</param>
/// <returns>True if the file exists</returns>
public async Task<bool> FileExists(string bucket, string folder, string filePrefix)
{
    return await FileExists(bucket, $"{folder}/{filePrefix}");
}

Usage:

var testExists = await FileExists("testBucket", "test_");
// or...
var testExistsInFolder = await FileExists("testBucket", "testFolder/testSubFolder", "test_");


问:
Filtering ID's based on specified difference in values
I am trying to filter IDs based on a specified conditions. For instance, I want to filter IDs which have a particular difference in questionnaire score from pre to post treatment. The idea is to get IDs that have improved in score, have stayed the same or have worsened. Here is a mock data set of what I'm trying to achieve:-

```<code>    ID<-c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
    Condition<-c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
    Score<-c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11)
    df<-cbind(ID,Condition,Score)
    df<-as.data.frame(df)
    df$Condition<-as.factor(df$Condition)
</code>```

The main issue here is that there are ID's who appear in the data, for both pre and post, twice.

I have tried using a dplyr solution to select the appropriate columns from the main data frame, and then use tidyverse, and the spread function to convert to wide format, because from there I can work out the differences easily enough. However, there is a particular problem that I've experienced. It wouldn't work because there are duplicate instances where an ID has appeared in the data again (for example, IDs aaa, bbb & ccc).

```<code>     df2<-df%>%
     group_by(ID)%>%
     spread(Condition, Score)
</code>```

This gets me the following error message:-

Error: Each row of output must be identified by a unique combination of keys.
  Keys are shared for 12 rows:
  * 10, 22
  * 11, 23
  * 12, 24
  * 1, 19
  * 2, 20
  * 3, 21
  Do you need to create unique ID with tibble::rowid_to_column()?

Ideally, the kind of result I would be looking for is like so:-

```<code>    #improved
    ID      Pre       Post     Difference
    aaa      23        17           -6
    bbb      20        17           -3
    ggg      20        14           -6
    hhh      19        15           -4
    iii      18        10           -8
    aaa      23        20           -3
    bbb      23        18           -5
    ccc      21        11           -10

    #no improvement
    ID      Pre       Post      Difference
    ccc      19         19          0
    eee      22         22          0
    fff      22         22          0

    #worsened
    ID      Pre       Post      Difference
    ddd      15         20          +5
</code>```

Or something to this effect. As long as it allows me to include the repeated IDs. Ideally, I would like to be able to conditionally filter further based on the magnitude of difference. So for instance, if I want to subset/filter IDs with an improved score of more than 5, or a worsened score of more than 5. Bare in mind, my actual data set will have far more IDs to work with than the example that I just made up and provided. Any help would be greatly appreciated, as always.

Thank you in advance :)

答:
The other answers address Score being a factor due to the cbind() call. Here are solutions for Base R, data.table, and dplyr.

All of the solutions address the duplicate ID by adding an additional Group variable. This allows the spread to be successful.

```<code># Base R ------------------------------------------------------------------

df <- data.frame(ID, Condition, Score)
df$Group <- ave(seq_len(nrow(df)), df$Condition, FUN = seq_along)

df_wide <- reshape(df, timevar = 'Condition', idvar = c('ID', 'Group'), direction = 'wide')
df_wide$Difference <- df_wide$Score.Post - df_wide$Score.Pre
df_wide[order(df_wide$Difference),]

# data.table --------------------------------------------------------------
library(data.table)

dt <- data.table(ID, Condition, Score)
dt[, Group := seq_len(.N), by = Condition]

dt_wide <- dcast(dt, ID + Group ~ Condition, value.var = 'Score')
dt_wide[, Difference := Post - Pre]
dt_wide[order(Difference),]

# dplyr -------------------------------------------------------------------
library(tidyverse)

tib <- tibble(ID, Condition, Score)

tib%>%
  group_by(Condition)%>%
  mutate(Group = row_number())%>%
  ungroup()%>%
  spread(key = 'Condition', value = 'Score')%>%
  mutate(Difference = Post - Pre)%>%
  arrange(Difference)
</code>```

For this very small dataset, base R is fastest and data.table is slowest.

```<code>Unit: milliseconds
           expr    min      lq     mean  median      uq     max neval
     base_r_way 2.7562 2.98075 3.103155 3.05140 3.12810  6.0653   100
 data.table_way 6.6137 7.09705 8.216043 7.44250 8.01885 47.9138   100
      dplyr_way 4.7334 5.15005 5.350857 5.25085 5.40395  9.5594   100
</code>```

And data:

```<code>ID <- c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
Condition <- c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
Score <- as.integer(c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11))
</code>```

Body:
I am trying to filter IDs based on a specified conditions. For instance, I want to filter IDs which have a particular difference in questionnaire score from pre to post treatment. The idea is to get IDs that have improved in score, have stayed the same or have worsened. Here is a mock data set of what I'm trying to achieve:-

    ID<-c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
    Condition<-c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
    Score<-c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11)
    df<-cbind(ID,Condition,Score)
    df<-as.data.frame(df)
    df$Condition<-as.factor(df$Condition)

The main issue here is that there are ID's who appear in the data, for both pre and post, twice.

I have tried using a dplyr solution to select the appropriate columns from the main data frame, and then use tidyverse, and the spread function to convert to wide format, because from there I can work out the differences easily enough. However, there is a particular problem that I've experienced. It wouldn't work because there are duplicate instances where an ID has appeared in the data again (for example, IDs aaa, bbb & ccc).

     df2<-df%>%
     group_by(ID)%>%
     spread(Condition, Score)

This gets me the following error message:-

Error: Each row of output must be identified by a unique combination of keys.
  Keys are shared for 12 rows:
  * 10, 22
  * 11, 23
  * 12, 24
  * 1, 19
  * 2, 20
  * 3, 21
  Do you need to create unique ID with tibble::rowid_to_column()?

Ideally, the kind of result I would be looking for is like so:-

    #improved
    ID      Pre       Post     Difference
    aaa      23        17           -6
    bbb      20        17           -3
    ggg      20        14           -6
    hhh      19        15           -4
    iii      18        10           -8
    aaa      23        20           -3
    bbb      23        18           -5
    ccc      21        11           -10

    #no improvement
    ID      Pre       Post      Difference
    ccc      19         19          0
    eee      22         22          0
    fff      22         22          0

    #worsened
    ID      Pre       Post      Difference
    ddd      15         20          +5

Or something to this effect. As long as it allows me to include the repeated IDs. Ideally, I would like to be able to conditionally filter further based on the magnitude of difference. So for instance, if I want to subset/filter IDs with an improved score of more than 5, or a worsened score of more than 5. Bare in mind, my actual data set will have far more IDs to work with than the example that I just made up and provided. Any help would be greatly appreciated, as always.

Thank you in advance :)

Body:
The other answers address Score being a factor due to the cbind() call. Here are solutions for Base R, data.table, and dplyr.

All of the solutions address the duplicate ID by adding an additional Group variable. This allows the spread to be successful.

# Base R ------------------------------------------------------------------

df <- data.frame(ID, Condition, Score)
df$Group <- ave(seq_len(nrow(df)), df$Condition, FUN = seq_along)

df_wide <- reshape(df, timevar = 'Condition', idvar = c('ID', 'Group'), direction = 'wide')
df_wide$Difference <- df_wide$Score.Post - df_wide$Score.Pre
df_wide[order(df_wide$Difference),]

# data.table --------------------------------------------------------------
library(data.table)

dt <- data.table(ID, Condition, Score)
dt[, Group := seq_len(.N), by = Condition]

dt_wide <- dcast(dt, ID + Group ~ Condition, value.var = 'Score')
dt_wide[, Difference := Post - Pre]
dt_wide[order(Difference),]

# dplyr -------------------------------------------------------------------
library(tidyverse)

tib <- tibble(ID, Condition, Score)

tib%>%
  group_by(Condition)%>%
  mutate(Group = row_number())%>%
  ungroup()%>%
  spread(key = 'Condition', value = 'Score')%>%
  mutate(Difference = Post - Pre)%>%
  arrange(Difference)

For this very small dataset, base R is fastest and data.table is slowest.

Unit: milliseconds
           expr    min      lq     mean  median      uq     max neval
     base_r_way 2.7562 2.98075 3.103155 3.05140 3.12810  6.0653   100
 data.table_way 6.6137 7.09705 8.216043 7.44250 8.01885 47.9138   100
      dplyr_way 4.7334 5.15005 5.350857 5.25085 5.40395  9.5594   100

And data:

ID <- c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
Condition <- c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
Score <- as.integer(c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11))


问:
Compare 7 input numbers with 7 Random Numbers
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..</p>

```<code>List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}
</code>```

答:
This is my interpretation. </p>

```<code>    class Program
{
    private static Random rnd = new Random();
    static void Main(string[] args)
    {
        do
        {
            uint[] myRandoms = GetRandoms();
            uint[] userInput = GetUserInput();
            List<uint> matches = GetMatches(userInput, myRandoms);
            Console.WriteLine("Your Numbers");
            PrintEnumerable(userInput);
            Console.WriteLine("The Lottery Winners");
            PrintEnumerable(myRandoms);
            Console.WriteLine("Numbers You Matched");
            PrintEnumerable(matches);
            int NumOfMatches = matches.Count;
            if (matches.Count >= 4)
                Console.WriteLine($"You win! You matched {NumOfMatches} numbers.");
            else
                Console.WriteLine($"Sorry, you only matched {NumOfMatches} numbers.");
            Console.WriteLine("Play again? Enter Y for yes and N for no.");
        } while (Console.ReadLine().ToUpper() == "Y");
    }
   private static uint[] GetRandoms()
    {
        uint[] newRandoms = new uint[7];
        int index = 0;
        while (index < 7)
        {
            //.Next(int, int) limits the return to a non-negative random integer
            //that is equal to or greater than the first int and less than the second the int.
            //Said another way, it is inclusive of the first int and
            //exclusive of the second int.
            uint r = (uint)rnd.Next(1, 40);
            if (!newRandoms.Contains(r)) //prevent duplicates
            {
                newRandoms[index] = r;
                index++;
            }
        }
        return newRandoms.OrderBy(x => x).ToArray();
    }
    private static uint[] GetUserInput()
    {
        uint[] inputs = new uint[7];
        int i = 0;
        while (i < 7)
        {
            Console.WriteLine("Enter a whole number between 1 and 39 inclusive. No duplicates, please.");
            //Note: input <= 39 would cause an error if the first part of the
            // if failed and we used & instead of && (And instead of AndAlso in vb.net).
            //The second part of the if never executes if the first part fails
            //when && is used.                                                             //prevents duplicates
            if (uint.TryParse(Console.ReadLine(), out uint input) && input <= 39 && input >0 && !inputs.Contains(input))
            {
                inputs[i] = input;
                i++; //Note: i is not incremented unless we have a successful entry
            }
            else
                Console.WriteLine("Try again.");
        }
        return inputs.OrderBy(x => x).ToArray();
    }
    //I used a List<T> here because we don't know how many elements we will have.
    private static List<uint> GetMatches(uint[] input, uint[] rands)
    {
        List<uint> matches = new List<uint>();
        int i;
        for (i=0; i<7; i++)
        {
            if(rands.Contains(input[i]))
                matches.Add(input[i]);
        }
        //Or skip the for loop and do as Sunny Pelletier answered
        //matches = input.Intersect(rands).ToList();
        return matches.OrderBy(x=>x).ToList();
    }
    //You are able to send both List<T> and arrays to this method because they both implement IEnumerable
    private static void PrintEnumerable(IEnumerable<uint> ToPrint)
    {
        foreach (uint item in ToPrint)
            Console.WriteLine(item);
    }
}
</code>```

Body:
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..

List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}

Body:
This is my interpretation.

    class Program
{
    private static Random rnd = new Random();
    static void Main(string[] args)
    {
        do
        {
            uint[] myRandoms = GetRandoms();
            uint[] userInput = GetUserInput();
            List<uint> matches = GetMatches(userInput, myRandoms);
            Console.WriteLine("Your Numbers");
            PrintEnumerable(userInput);
            Console.WriteLine("The Lottery Winners");
            PrintEnumerable(myRandoms);
            Console.WriteLine("Numbers You Matched");
            PrintEnumerable(matches);
            int NumOfMatches = matches.Count;
            if (matches.Count >= 4)
                Console.WriteLine($"You win! You matched {NumOfMatches} numbers.");
            else
                Console.WriteLine($"Sorry, you only matched {NumOfMatches} numbers.");
            Console.WriteLine("Play again? Enter Y for yes and N for no.");
        } while (Console.ReadLine().ToUpper() == "Y");
    }
   private static uint[] GetRandoms()
    {
        uint[] newRandoms = new uint[7];
        int index = 0;
        while (index < 7)
        {
            //.Next(int, int) limits the return to a non-negative random integer
            //that is equal to or greater than the first int and less than the second the int.
            //Said another way, it is inclusive of the first int and
            //exclusive of the second int.
            uint r = (uint)rnd.Next(1, 40);
            if (!newRandoms.Contains(r)) //prevent duplicates
            {
                newRandoms[index] = r;
                index++;
            }
        }
        return newRandoms.OrderBy(x => x).ToArray();
    }
    private static uint[] GetUserInput()
    {
        uint[] inputs = new uint[7];
        int i = 0;
        while (i < 7)
        {
            Console.WriteLine("Enter a whole number between 1 and 39 inclusive. No duplicates, please.");
            //Note: input <= 39 would cause an error if the first part of the
            // if failed and we used & instead of && (And instead of AndAlso in vb.net).
            //The second part of the if never executes if the first part fails
            //when && is used.                                                             //prevents duplicates
            if (uint.TryParse(Console.ReadLine(), out uint input) && input <= 39 && input >0 && !inputs.Contains(input))
            {
                inputs[i] = input;
                i++; //Note: i is not incremented unless we have a successful entry
            }
            else
                Console.WriteLine("Try again.");
        }
        return inputs.OrderBy(x => x).ToArray();
    }
    //I used a List<T> here because we don't know how many elements we will have.
    private static List<uint> GetMatches(uint[] input, uint[] rands)
    {
        List<uint> matches = new List<uint>();
        int i;
        for (i=0; i<7; i++)
        {
            if(rands.Contains(input[i]))
                matches.Add(input[i]);
        }
        //Or skip the for loop and do as Sunny Pelletier answered
        //matches = input.Intersect(rands).ToList();
        return matches.OrderBy(x=>x).ToList();
    }
    //You are able to send both List<T> and arrays to this method because they both implement IEnumerable
    private static void PrintEnumerable(IEnumerable<uint> ToPrint)
    {
        foreach (uint item in ToPrint)
            Console.WriteLine(item);
    }
}


问:
How to Auto Submit Form Using JS
I want to add code auto Auto Submit Form using JS once the page finish load
I need it submit the inputs values too
Submit and the captcha response works good when I click manually automatic work but didnt submit with  input "g-recaptcha-response" value
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $captcha_site_key ?>"></script>
</head>
    <form action="check.php" id="myform" method="POST">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="Submit" name="Submit">
</form>
<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('<?php echo $captcha_site_key ?>', {action:'validate_captcha'})
                  .then(function(token) {
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>
<script type="text/javascript">
window.onload = function(){
  document.getElementById("myform").submit();
}
</script>

</body>
</html>
</code>```

答:
In Javascript, with this little trick you can achieve your goals:

using Plain Javascript - this is how you can submit a form:

```<code>  document.getElementById("YourFormIdHere").submit();
</code>```

If you wish to submit that form only when the captcha is provided then you must run if statements.

First Stop the form from submitting, so that you can evaluate the Captcha before it's submitted.

```<code>document.getElementById("FormIdHere").addEventListener("submit", function(event) {
  event.preventDefault()
});
</code>```

from Here, you want to check if the captcha value was submitted. First try to get the value of the Captcha

```<code>var Captcha = document.GetElementById("capture ID here").value;

//check if captcha has value
if(Captcha){
    //then submit your form here
    document.getElementById("YourFormIdHere").submit();
}
</code>```

If Captcha value was empty, the form won't submit, thus forcing the user to create the captcha.

Title: How to Auto Submit Form Using JS

Body:
I want to add code auto Auto Submit Form using JS once the page finish load
I need it submit the inputs values too
Submit and the captcha response works good when I click manually automatic work but didnt submit with  input "g-recaptcha-response" value

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <form action="check.php" id="myform" method="POST">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="Submit" name="Submit">
</form>

Body:
In Javascript, with this little trick you can achieve your goals:

using Plain Javascript - this is how you can submit a form:

  document.getElementById("YourFormIdHere").submit();

If you wish to submit that form only when the captcha is provided then you must run if statements.

First Stop the form from submitting, so that you can evaluate the Captcha before it's submitted.

document.getElementById("FormIdHere").addEventListener("submit", function(event) {
  event.preventDefault()
});

from Here, you want to check if the captcha value was submitted. First try to get the value of the Captcha

var Captcha = document.GetElementById("capture ID here").value;

//check if captcha has value
if(Captcha){
    //then submit your form here
    document.getElementById("YourFormIdHere").submit();
}

If Captcha value was empty, the form won't submit, thus forcing the user to create the captcha.