问:
Proper way to use fetch with github api v3?
I want to map all the issue titles for a repo and render them to li in a react component. I've been able to extract only the issue title using octokat library but unfortunately that library does not play nice with some other stuff i've got going on. Also, I'm sure i can do this with es6 and the fetch api.

Original Post:

Been having a hellava time finding info on using es6 fetch / promises with the github api. I'm trying to fetch issues for a repo but i'm obviously missing something... I've used a few different libraries to try and accomplish this but I'd like to just use fetch.

Update: Now my new goal is merely to console.log the titles... baby steps.

```<code>import React from "react";

export default class extends React.Component {
  constructor() {
    super()
    this.state = {
      issues: []
    }
  }
  componentWillMount() {
    // let issueArry = []
    const url = "https://api.github.com/repos/fightplights/chode-stream/issues"
    fetch(url)
      .then(response => response) // i've tried with and without .json()
      .then(body => console.log(body))
      // this logs the same response

  }
  render() {
    return (
      <div>
        <ul>
          {here i will map this.state.issues (once i can get them =))}
        </ul>
      </div>
    )
  }
}
</code>```

I know it's a simple error on my part. I'm still a fledgling. =)

...and obviously i need to render to the dom (not shown here)

@Andy_D is right that I wasn't parsing the body of the response, only the response itself (doh!) however now that i'm trying to data.map(issue => ...) I still get the error that data.map() is not a function. This leads me to believe that the data object is not the object the droids are looking for... hand waves in front of screen

Here's the response object in the first promise:

```<code>Response {
  type: "cors",
  url: "https://api.github.com/repos/fightp…",
  redirected: false,
  status: 200,
  ok: true,
  statusText: "OK",
  headers: Headers,
  bodyUsed: false
}
</code>```

But when I take that response in the next
    .then(data => console.log(data))
It is undefined...
I have tried returning the first response => response.json() (as andy suggested) but it's already json... am i wrong?

答:
You need to read the JSON from the body of the response, what you are attempting to render is the full response body.

So:

```<code>fetch(url)
  .then(response => response.json())
  .then(data => data.map(...)
</code>```

response.json() returns a promise, so you can .then it, the return value (data) will be the JS object/array you're looking for.

https://developer.mozilla.org/en-US/docs/Web/API/Body/json

Body:
I want to map all the issue titles for a repo and render them to li in a react component. I've been able to extract only the issue title using octokat library but unfortunately that library does not play nice with some other stuff i've got going on. Also, I'm sure i can do this with es6 and the fetch api.

Original Post:

Been having a hellava time finding info on using es6 fetch / promises with the github api. I'm trying to fetch issues for a repo but i'm obviously missing something... I've used a few different libraries to try and accomplish this but I'd like to just use fetch.

Update: Now my new goal is merely to console.log the titles... baby steps.

import React from "react";

export default class extends React.Component {
  constructor() {
    super()
    this.state = {
      issues: []
    }
  }
  componentWillMount() {
    // let issueArry = []
    const url = "https://api.github.com/repos/fightplights/chode-stream/issues"
    fetch(url)
      .then(response => response) // i've tried with and without .json()
      .then(body => console.log(body))
      // this logs the same response

  }
  render() {
    return (

          {here i will map this.state.issues (once i can get them =))}

    )
  }
}

I know it's a simple error on my part. I'm still a fledgling. =)

...and obviously i need to render to the dom (not shown here)

@Andy_D is right that I wasn't parsing the body of the response, only the response itself (doh!) however now that i'm trying to data.map(issue => ...) I still get the error that data.map() is not a function. This leads me to believe that the data object is not the object the droids are looking for... hand waves in front of screen

Here's the response object in the first promise:

Response {
  type: "cors",
  url: "https://api.github.com/repos/fightp…",
  redirected: false,
  status: 200,
  ok: true,
  statusText: "OK",
  headers: Headers,
  bodyUsed: false
}

But when I take that response in the next
    .then(data => console.log(data))
It is undefined...
I have tried returning the first response => response.json() (as andy suggested) but it's already json... am i wrong?

Body:
You need to read the JSON from the body of the response, what you are attempting to render is the full response body.

So:

fetch(url)
  .then(response => response.json())
  .then(data => data.map(...)

response.json() returns a promise, so you can .then it, the return value (data) will be the JS object/array you're looking for.

https://developer.mozilla.org/en-US/docs/Web/API/Body/json


来源: stackexchange

问:
Extract data from list with some conditions
Basically, I am trying to adding two midi files and there is not much information on internet about it, so I am trying my own.

What I did so far is I have added two midi's messages (type of midi's data)
and I have list of both midi messages. This means I have all the data in which I need to merge two midi now. The problem is that I can't add data in a particular format.

So my code is :

```<code>  from mido import MidiFile, MidiTrack

mid = MidiFile('har.mid')
mid2 = MidiFile('har2.mid')

l = [msg for track in mid.tracks for msg in track]
l.pop()
ka = [msg for track in mid2.tracks for msg in track]
ka.pop()

result = l + ka

for messagess in result:
    print(messagess)
</code>```

I am getting this output :

```<code>note_on channel=0 note=59 velocity=40 time=0
note_on channel=0 note=60 velocity=40 time=0
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=59 velocity=0 time=55
note_off channel=0 note=64 velocity=0 time=0
note_on channel=0 note=52 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_on channel=0 note=67 velocity=40 time=0
note_off channel=0 note=67 velocity=0 time=55
note_on channel=0 note=57 velocity=40 time=0
note_off channel=0 note=52 velocity=0 time=55
note_off channel=0 note=57 velocity=0 time=0
note_off channel=0 note=64 velocity=0 time=0
note_on channel=0 note=57 velocity=40 time=55
note_off channel=0 note=57 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_on channel=0 note=67 velocity=40 time=0
note_off channel=0 note=64 velocity=0 time=55
note_off channel=0 note=67 velocity=0 time=0
note_on channel=0 note=57 velocity=40 time=110
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=57 velocity=0 time=55
note_off channel=0 note=64 velocity=0 time=0
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=62 velocity=0 time=55
note_on channel=0 note=57 velocity=40 time=110
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=57 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_on channel=0 note=60 velocity=40 time=0
note_on channel=0 note=62 velocity=40 time=0
note_on channel=0 note=67 velocity=40 time=0
note_on channel=0 note=60 velocity=40 time=55
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_off channel=0 note=64 velocity=0 time=0
note_off channel=0 note=67 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=64 velocity=0 time=55
note_on channel=0 note=60 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=62 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=64 velocity=0 time=55
note_on channel=0 note=60 velocity=40 time=110
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_on channel=0 note=48 velocity=40 time=110
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=48 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_on channel=0 note=57 velocity=40 time=55
note_on channel=0 note=60 velocity=40 time=0
</code>```

Now this is ok but the problem is i can add messages to track in this format :

```<code>from mido import Message, MidiFile, MidiTrack

mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)

track.append(Message('program_change', program=12, time=0))
track.append(Message('note_on', note=64, velocity=64, time=32))
track.append(Message('note_off', note=64, velocity=127, time=32))

mid.save('new_song.mid')
</code>```

so my question how append each line from this format :

```<code>note_off channel=0 note=62 velocity=0 time=0
</code>```

to this format

'note_off', note=62, velocity=0, time=0

in  track.append(Message())

because track.append support only this format method :

```<code>track.append(Message('note_off', note=62, velocity=0, time=0))
</code>```

Thanks in advance.

答:
```<code>from mido import MidiFile, MidiTrack

mid = MidiFile('har.mid')
mid2 = MidiFile('har2.mid')

l = [msg for track in mid.tracks for msg in track]
l.pop()
ka = [msg for track in mid2.tracks for msg in track]
ka.pop()

result = l + ka

mid3 = MidiFile()
track = MidiTrack()
mid3.tracks.append(track)

for m in result:
    track.append(m)

mid3.save('new_song.mid')
</code>```

The objects in result should already be Message objects, so you should't need to construct them again.  Try this code, and if it doesn't work please copy the full error message you get back.

ContentLicense: CC BY-SA 3.0

Body:
Basically, I am trying to adding two midi files and there is not much information on internet about it, so I am trying my own.

What I did so far is I have added two midi's messages (type of midi's data)
and I have list of both midi messages. This means I have all the data in which I need to merge two midi now. The problem is that I can't add data in a particular format.

So my code is :

  from mido import MidiFile, MidiTrack

mid = MidiFile('har.mid')
mid2 = MidiFile('har2.mid')

l = [msg for track in mid.tracks for msg in track]
l.pop()
ka = [msg for track in mid2.tracks for msg in track]
ka.pop()

result = l + ka

for messagess in result:
    print(messagess)

I am getting this output :

note_on channel=0 note=59 velocity=40 time=0
note_on channel=0 note=60 velocity=40 time=0
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=59 velocity=0 time=55
note_off channel=0 note=64 velocity=0 time=0
note_on channel=0 note=52 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_on channel=0 note=67 velocity=40 time=0
note_off channel=0 note=67 velocity=0 time=55
note_on channel=0 note=57 velocity=40 time=0
note_off channel=0 note=52 velocity=0 time=55
note_off channel=0 note=57 velocity=0 time=0
note_off channel=0 note=64 velocity=0 time=0
note_on channel=0 note=57 velocity=40 time=55
note_off channel=0 note=57 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_on channel=0 note=67 velocity=40 time=0
note_off channel=0 note=64 velocity=0 time=55
note_off channel=0 note=67 velocity=0 time=0
note_on channel=0 note=57 velocity=40 time=110
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=57 velocity=0 time=55
note_off channel=0 note=64 velocity=0 time=0
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=62 velocity=0 time=55
note_on channel=0 note=57 velocity=40 time=110
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=57 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_on channel=0 note=60 velocity=40 time=0
note_on channel=0 note=62 velocity=40 time=0
note_on channel=0 note=67 velocity=40 time=0
note_on channel=0 note=60 velocity=40 time=55
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_off channel=0 note=64 velocity=0 time=0
note_off channel=0 note=67 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=64 velocity=0 time=55
note_on channel=0 note=60 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=62 velocity=0 time=55
note_on channel=0 note=64 velocity=40 time=0
note_off channel=0 note=64 velocity=0 time=55
note_on channel=0 note=60 velocity=40 time=110
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=60 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_on channel=0 note=48 velocity=40 time=110
note_on channel=0 note=62 velocity=40 time=0
note_off channel=0 note=48 velocity=0 time=55
note_off channel=0 note=62 velocity=0 time=0
note_on channel=0 note=57 velocity=40 time=55
note_on channel=0 note=60 velocity=40 time=0

Now this is ok but the problem is i can add messages to track in this format :

from mido import Message, MidiFile, MidiTrack

mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)

track.append(Message('program_change', program=12, time=0))
track.append(Message('note_on', note=64, velocity=64, time=32))
track.append(Message('note_off', note=64, velocity=127, time=32))

mid.save('new_song.mid')

so my question how append each line from this format :

note_off channel=0 note=62 velocity=0 time=0

to this format

'note_off', note=62, velocity=0, time=0

in  track.append(Message())

because track.append support only this format method :

track.append(Message('note_off', note=62, velocity=0, time=0))

Thanks in advance.

Body:
from mido import MidiFile, MidiTrack

mid = MidiFile('har.mid')
mid2 = MidiFile('har2.mid')

l = [msg for track in mid.tracks for msg in track]
l.pop()
ka = [msg for track in mid2.tracks for msg in track]
ka.pop()

result = l + ka

mid3 = MidiFile()
track = MidiTrack()
mid3.tracks.append(track)

for m in result:
    track.append(m)

mid3.save('new_song.mid')

The objects in result should already be Message objects, so you should't need to construct them again.  Try this code, and if it doesn't work please copy the full error message you get back.


问:
Swift - Get data from Alamofire POST request
I'm stuck in Swift project. I call "SendPost" from button IBAction and I need it returns the data from Alamofire.request, but I don't know how to reach this. I can't get to "utf8Text" variable from out of Alamofire.request. How can I get to the data?

Thank you. :)

```<code>import Foundation
import Alamofire

  func SendPost(parameters: Parameters) -> String {

  Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
        print("Request: \(response.request)")
        print("Response: \(response.response)")
        print("Error: \(response.error)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")

        }
    }

 return "I don't know. :(";
 }
</code>```

答:
For Swift 3

Use a completion to return de data obtained from Request:

First create a typealias which will be used as a closure :

typealias SendPostCompletion = (_ data: String) -> Void

Then:

```<code>@IBAction func yourAction(_ sender: UIButton) {
        SendPost(parameters: ...) { (data) in
            print(data)
        }
}

func SendPost(parameters: Parameters, completion: @escaping SendPostCompletion) -> String {

        Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                var data = ("Data: \(utf8Text)")
                completion(data)
            }
        }

        completion("I don't know. :(")
}
</code>```

Hope it helps you!

Body:
I'm stuck in Swift project. I call "SendPost" from button IBAction and I need it returns the data from Alamofire.request, but I don't know how to reach this. I can't get to "utf8Text" variable from out of Alamofire.request. How can I get to the data?

Thank you. :)

import Foundation
import Alamofire

  func SendPost(parameters: Parameters) -> String {

  Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
        print("Request: \(response.request)")
        print("Response: \(response.response)")
        print("Error: \(response.error)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)")

        }
    }

 return "I don't know. :(";
 }

Body:
For Swift 3

Use a completion to return de data obtained from Request:

First create a typealias which will be used as a closure :

typealias SendPostCompletion = (_ data: String) -> Void

Then:

@IBAction func yourAction(_ sender: UIButton) {
        SendPost(parameters: ...) { (data) in
            print(data)
        }
}

func SendPost(parameters: Parameters, completion: @escaping SendPostCompletion) -> String {

        Alamofire.request("https://hovnocuc.com/main.php", method: .post, parameters: parameters).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                var data = ("Data: \(utf8Text)")
                completion(data)
            }
        }

        completion("I don't know. :(")
}

Hope it helps you!


问:
SQL Server Stored Proc - What is returned to a variable if no data?
If, using the following code in a MS SQL Server 2008 stored procedure:

```<code>    DECLARE @PROD_ID VARCHAR(20)

    SELECT @PROD_ID = MYTABLE.PROD
    FROM MYTABLE
    WHERE MYTABLE.DEVID = @DEVCODE
</code>```

DEVCODE does not exist, what will PROD_ID contain? I've tried printing it, but it prints what seems to be a space. However, testing it for space fails. Also, testing for NULL fails. OR, should I be testing for empty in a different manner?

Thanks for reading
BBz

答:
@PROD_ID should remain NULL if @DEVCODE does not exist.

Are you testing appropriately using

```<code>...@PROD_ID IS NULL...
</code>```

and not trying to test

```<code>...@PROD_ID = NULL...
</code>```

which would be incorrect?

ContentLicense: CC BY-SA 2.5

Body:
If, using the following code in a MS SQL Server 2008 stored procedure:

    DECLARE @PROD_ID VARCHAR(20)

    SELECT @PROD_ID = MYTABLE.PROD
    FROM MYTABLE
    WHERE MYTABLE.DEVID = @DEVCODE

DEVCODE does not exist, what will PROD_ID contain? I've tried printing it, but it prints what seems to be a space. However, testing it for space fails. Also, testing for NULL fails. OR, should I be testing for empty in a different manner?

Thanks for reading
BBz

Body:
@PROD_ID should remain NULL if @DEVCODE does not exist.

Are you testing appropriately using

...@PROD_ID IS NULL...

and not trying to test

...@PROD_ID = NULL...

which would be incorrect?


问:
Efficient Multi-threading in C
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

```<code> for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

```<code> for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?

答:
There are m operations involving multiplying a row of the left matrix by a column of the right matrix. For t threads, each thread could perform m/t operations. If m is not a multiple of t, then decide how to split up the work. Using m/t means the last thread does more work, using (m+t-1)/t means the last thread does less work, or use (m/t)+1 operations on some threads and (m/t) operations on the remaining threads.

This is probably not a good case for multi-threading, but at least you get an idea of the concept.

Here's a link to an example of Windows based multi-threading used for a merge sort, using 4 threads for about a 3x increase in performance. I had previously thought that the key loops in the merge function were so small that the process would be memory bound, but it turned out to be cpu bound.

https://codereview.stackexchange.com/questions/148025/multithreaded-bottom-up-merge-sort

Title: Efficient Multi-threading in C

Body:
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

 for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

 for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?


问:
Google Cloud Endpoints REST Discovery Document missing format
I've upgraded to Cloud Endpoints 2.0 which no longer supports RPC. Therefore, I generated a new discovery document and used the service generator with the REST discovery doc as input in order to generate the client library for my iOS app.

Using the new REST discovery doc I am getting the following error when trying to generate the library:

```<code>~/workspace/google-api-objectivec-client-for-rest/Source/Tools/ServiceGenerator/build/Release/ServiceGenerator discovery/servUsApi-v1-rest.discovery --outputDir GTLAPI --gtlrFrameworkName GoogleAPIClientForREST

ERROR: Failure, exception: Looking at parameter 'creditKickbackKash:creditAmount', found a type/format pair of 'number/(null)', and don't how to map that to Objective-C
</code>```

I was able to manually fix this by adding (in numerous places) in the discovery doc, the "format": "double" key and value for all double parameters. Notice creditAmount below is missing a format, like all other doubles.

The generated discovery doc looks like this:

```<code>"creditKickbackKash": {
 "httpMethod": "PUT",
 "id": "servUsApi.admin.creditKickbackKash",
 "parameterOrder": [
  "userId",
  "creditAmount"
 ],
 "parameters": {
  "userId": {
   "format": "int64",
   "location": "path",
   "required": true,
   "type": "string"
  },
  "creditAmount": {
   "location": "path",
   "required": true,
   "type": "number"
  }
 },
 "path": "creditKickbackKash/{userId}/{creditAmount}",
 "response": {
  "$ref": "ResultDTO"
 },
 "scopes": [
  "https://www.googleapis.com/auth/userinfo.email"
 ]
}
</code>```

Is anyone else having this issue? How can I get the discovery document generation to properly format the document including double number types?

答: I had the same problem. I rolled back from 1.9.50 to 1.9.48 and the problem is gone. </p>

Body:
I've upgraded to Cloud Endpoints 2.0 which no longer supports RPC. Therefore, I generated a new discovery document and used the service generator with the REST discovery doc as input in order to generate the client library for my iOS app.

Using the new REST discovery doc I am getting the following error when trying to generate the library:

~/workspace/google-api-objectivec-client-for-rest/Source/Tools/ServiceGenerator/build/Release/ServiceGenerator discovery/servUsApi-v1-rest.discovery --outputDir GTLAPI --gtlrFrameworkName GoogleAPIClientForREST

ERROR: Failure, exception: Looking at parameter 'creditKickbackKash:creditAmount', found a type/format pair of 'number/(null)', and don't how to map that to Objective-C

I was able to manually fix this by adding (in numerous places) in the discovery doc, the "format": "double" key and value for all double parameters. Notice creditAmount below is missing a format, like all other doubles.

The generated discovery doc looks like this:

"creditKickbackKash": {
 "httpMethod": "PUT",
 "id": "servUsApi.admin.creditKickbackKash",
 "parameterOrder": [
  "userId",
  "creditAmount"
 ],
 "parameters": {
  "userId": {
   "format": "int64",
   "location": "path",
   "required": true,
   "type": "string"
  },
  "creditAmount": {
   "location": "path",
   "required": true,
   "type": "number"
  }
 },
 "path": "creditKickbackKash/{userId}/{creditAmount}",
 "response": {
  "$ref": "ResultDTO"
 },
 "scopes": [
  "https://www.googleapis.com/auth/userinfo.email"
 ]
}

Is anyone else having this issue? How can I get the discovery document generation to properly format the document including double number types?


问:
SAS: Merging two tables with identical columns while dropping null values
I'm not sure if the title does this question justice, but here it goes:

I have three datasets Forecasts1, Forecasts2 and Forecasts3. They are all time series data composed of a date variable and variables r1 through r241.

For a given r variable (lets just use r1-r3, and only Forecasts 1 and 2 for now) each dataset has only one row where the value isn't null, and it is a different row in each dataset.

Forecast 1 looks like this:

Forecast 2 looks like this:

I need to be able to combine them such that r1-r3 contain all the non-null values, without creating duplicate date rows to hold the null values.

So ideally the finished produce would look like this:

I've tried various types of merges and sets, but I keep getting duplicate date rows. How would I go about doing this properly for all 241 (or more) variables? (specifically in SAS or Proc SQL?)

LINKS TO GOOGLE DOCS CONTAINING DATA:

Forecasts1: https://docs.google.com/spreadsheets/d/1iUEwPltU6V6ijgnkALFiIdrwrolDFt8xaITZaFC4WN8/edit?usp=sharing

Forecasts2:
https://docs.google.com/spreadsheets/d/1lQGKYJlz6AAR-DWtoWnl8SwzCNAmSpj7yxRqRgnybr8/edit?usp=sharing

答:
A different solution would be to append all and delete rows where all are missing. </p>

```<code>data want;
  set forecast1-forecast3 indsname=fc;
  model = fc; *store name of forecast model;
  if nmiss(of r1-r3) = 3 then delete;
run;
</code>```

Body:
A different solution would be to append all and delete rows where all are missing.

data want;
  set forecast1-forecast3 indsname=fc;
  model = fc; *store name of forecast model;
  if nmiss(of r1-r3) = 3 then delete;
run;


问:
Conditional data.table merge with .EACHI
I have been playing around with the newer data.table conditional merge feature and it is very cool. I have a situation where I have two tables, dtBig and dtSmall, and there are multiple row matches in both datasets when this conditional merge takes place. Is there a way to aggregate these matches using a function like max or min for these multiple matches? Here is a reproducible example that tries to mimic what I am trying to accomplish.

Set up environment

```<code>## docker run --rm -ti rocker/r-base
## install.packages("data.table", type = "source",repos = "http://Rdatatable.github.io/data.table")
</code>```

Create two fake datasets

A create a "big" table with 50 rows (10 values for each ID).

```<code>library(data.table)
set.seed(1L)

# Simulate some data
dtBig <- data.table(ID=c(sapply(LETTERS[1:5], rep, 10, simplify = TRUE)), ValueBig=ceiling(runif(50, min=0, max=1000)))
dtBig[, Rank := frank(ValueBig, ties.method = "first"), keyby=.(ID)]

    ID ValueBig Rank
 1:  A      266    3
 2:  A      373    4
 3:  A      573    5
 4:  A      909    9
 5:  A      202    2
---
46:  E      790    9
47:  E       24    1
48:  E      478    2
49:  E      733    7
50:  E      693    6
</code>```

Create a "small" dataset similar to the first, but with 10 rows (2 values for each ID)

```<code>dtSmall <- data.table(ID=c(sapply(LETTERS[1:5], rep, 2, simplify = TRUE)), ValueSmall=ceiling(runif(10, min=0, max=1000)))

    ID ValueSmall
 1:  A        478
 2:  A        862
 3:  B        439
 4:  B        245
 5:  C         71
 6:  C        100
 7:  D        317
 8:  D        519
 9:  E        663
10:  E        407
</code>```

Merge

I next want to perform a merge by ID and needs to merge only where ValueSmall is greater than or equal to ValueBig. For the matches, I want to grab the max ranked value in dtBig. I tried doing this two different ways. Method 2 gives me the desired output, but I am unclear why the output is different at all. It seems like it is just returning the last matched value.

```<code>## Method 1
dtSmall[dtBig, RankSmall := max(i.Rank), by=.EACHI, on=.(ID, ValueSmall >= ValueBig)]

## Method 2
setorder(dtBig, ValueBig)
dtSmall[dtBig, RankSmall2 := max(i.Rank), by=.EACHI, on=.(ID, ValueSmall >= ValueBig)]
</code>```

Results

```<code>    ID ValueSmall RankSmall RankSmall2 DesiredRank
 1:  A        478         1          4           4
 2:  A        862         1          7           7
 3:  B        439         3          4           4
 4:  B        245         1          2           2
 5:  C         71         1          1           1
 6:  C        100         1          1           1
 7:  D        317         1          2           2
 8:  D        519         3          5           5
 9:  E        663         2          5           5
10:  E        407         1          1           1
</code>```

Is there a better data.table way of grabbing the max value in another data.table with multiple matches?

答:
I next want to perform a merge by ID and needs to merge only where ValueSmall is greater than or equal to ValueBig. For the matches, I want to grab the max ranked value in dtBig.

```<code>setorder(dtBig, ID, ValueBig, Rank)
dtSmall[, r :=
  dtBig[.SD, on=.(ID, ValueBig <= ValueSmall), mult="last", x.Rank ]
]

    ID ValueSmall r
 1:  A        478 4
 2:  A        862 7
 3:  B        439 4
 4:  B        245 2
 5:  C         71 1
 6:  C        100 1
 7:  D        317 2
 8:  D        519 5
 9:  E        663 5
10:  E        407 1
</code>```

I imagine it is considerably faster to sort dtBig and take the last matching row rather than to compute the max by .EACHI, but am not entirely sure. If you don't like sorting, just save the previous sort order so it can be reverted to afterwards.

Is there a way to aggregate these matches using a function like max or min for these multiple matches?

For this more general problem, .EACHI works, just making sure you're doing it for each row of the target table (dtSmall in this case), so...

```<code>dtSmall[, r :=
  dtBig[.SD, on=.(ID, ValueBig <= ValueSmall), max(x.Rank), by=.EACHI ]$V1
]
</code>```

Body:
I have been playing around with the newer data.table conditional merge feature and it is very cool. I have a situation where I have two tables, dtBig and dtSmall, and there are multiple row matches in both datasets when this conditional merge takes place. Is there a way to aggregate these matches using a function like max or min for these multiple matches? Here is a reproducible example that tries to mimic what I am trying to accomplish.

Set up environment

## docker run --rm -ti rocker/r-base
## install.packages("data.table", type = "source",repos = "http://Rdatatable.github.io/data.table")

Create two fake datasets

A create a "big" table with 50 rows (10 values for each ID).

library(data.table)
set.seed(1L)

# Simulate some data
dtBig <- data.table(ID=c(sapply(LETTERS[1:5], rep, 10, simplify = TRUE)), ValueBig=ceiling(runif(50, min=0, max=1000)))
dtBig[, Rank := frank(ValueBig, ties.method = "first"), keyby=.(ID)]

    ID ValueBig Rank
 1:  A      266    3
 2:  A      373    4
 3:  A      573    5
 4:  A      909    9
 5:  A      202    2
---
46:  E      790    9
47:  E       24    1
48:  E      478    2
49:  E      733    7
50:  E      693    6

Create a "small" dataset similar to the first, but with 10 rows (2 values for each ID)

dtSmall <- data.table(ID=c(sapply(LETTERS[1:5], rep, 2, simplify = TRUE)), ValueSmall=ceiling(runif(10, min=0, max=1000)))

    ID ValueSmall
 1:  A        478
 2:  A        862
 3:  B        439
 4:  B        245
 5:  C         71
 6:  C        100
 7:  D        317
 8:  D        519
 9:  E        663
10:  E        407

Merge

I next want to perform a merge by ID and needs to merge only where ValueSmall is greater than or equal to ValueBig. For the matches, I want to grab the max ranked value in dtBig. I tried doing this two different ways. Method 2 gives me the desired output, but I am unclear why the output is different at all. It seems like it is just returning the last matched value.

## Method 1
dtSmall[dtBig, RankSmall := max(i.Rank), by=.EACHI, on=.(ID, ValueSmall >= ValueBig)]

## Method 2
setorder(dtBig, ValueBig)
dtSmall[dtBig, RankSmall2 := max(i.Rank), by=.EACHI, on=.(ID, ValueSmall >= ValueBig)]

Results

    ID ValueSmall RankSmall RankSmall2 DesiredRank
 1:  A        478         1          4           4
 2:  A        862         1          7           7
 3:  B        439         3          4           4
 4:  B        245         1          2           2
 5:  C         71         1          1           1
 6:  C        100         1          1           1
 7:  D        317         1          2           2
 8:  D        519         3          5           5
 9:  E        663         2          5           5
10:  E        407         1          1           1

Is there a better data.table way of grabbing the max value in another data.table with multiple matches?

Body:
I next want to perform a merge by ID and needs to merge only where ValueSmall is greater than or equal to ValueBig. For the matches, I want to grab the max ranked value in dtBig.

setorder(dtBig, ID, ValueBig, Rank)
dtSmall[, r :=
  dtBig[.SD, on=.(ID, ValueBig <= ValueSmall), mult="last", x.Rank ]
]

    ID ValueSmall r
 1:  A        478 4
 2:  A        862 7
 3:  B        439 4
 4:  B        245 2
 5:  C         71 1
 6:  C        100 1
 7:  D        317 2
 8:  D        519 5
 9:  E        663 5
10:  E        407 1

I imagine it is considerably faster to sort dtBig and take the last matching row rather than to compute the max by .EACHI, but am not entirely sure. If you don't like sorting, just save the previous sort order so it can be reverted to afterwards.

Is there a way to aggregate these matches using a function like max or min for these multiple matches?

For this more general problem, .EACHI works, just making sure you're doing it for each row of the target table (dtSmall in this case), so...

dtSmall[, r :=
  dtBig[.SD, on=.(ID, ValueBig <= ValueSmall), max(x.Rank), by=.EACHI ]$V1
]


问:
Why do we namespace staticmethod in Python?
```<code>class A(object):
    def __init__(self, val):
        self.val = A.plus_one(val)

    @staticmethod
    def plus_one(val):
        return val + 1
</code>```

We can define a static method in a class and use it in any places. My question is, why do we have to namespace the static method even when we use this static method within this class, that is, to add A. before the method name.

My idea is, can we simply change the mechanism so that the static method name within the class does not have to be namespaces as in: (although Python does not support it now):

```<code>class A(object):
    def __init__(self, val):
        self.val = plus_one(val)

    @staticmethod
    def plus_one(val):
        return val + 1
</code>```

My intuition is, since we are calling from within the class, the priority of class members should be higher than global functions, and thus there won't be any ambiguity. Why does Python force us to namespace it?

答:
Methods defined in a class are not accessible by bare name, except by code running directly in the class namespace (not inside another method). If you want to call a method, you usually have to look it up on some kind of object (either an instance, or the class itself). The different kinds of methods differ in how they behave when for different kinds of lookups.</p>

```<code>class Test(object):
    def normal_method(self, foo):
        print("normal_method", self, foo)
        # none of the method names are valid here as bare names, only via self or Test
        try:
            class_method(type(self), foo) # raises NameError
        except NameError:
            pass

        self.class_method(foo) # this works
        Test.class_method(foo) # so does this

    @classmethod
    def class_method(cls, foo):
        print("class_method", cls, foo)
        # from a class method, you can call a method via the automatically provided cls
        cls.static_method(foo)

    @staticmethod
    def static_method(foo):
        print("static_method", foo)
        # a static method can only use the global class name to call other methods
        if isinstance(foo, int) and foo > 0:
            Test.static_method(foo - 1)

    # Class level code is perilous.
    #normal_method('x', 2) # could work in Python 3 (Python 2 checks the type of self)
                           # but it probably won't be useful (since self is not an instance)
    #class_method('x', 2) # Won't work. A classmethod descriptor isn't directly callable
    #staticmethod(2)      # Nor is a staticmethod

# Top level code (these are all valid)
Test().normal_method(2) # also could be Test.normal_method(Test(), 2)
Test.class_method(2)  # could also be Test().class_method(2) (type of the instance is used)
Test.static_method(2) # could also be Test().static_method(2) (instance is ignored)
</code>```

Body:
class A(object):
    def __init__(self, val):
        self.val = A.plus_one(val)

    @staticmethod
    def plus_one(val):
        return val + 1

We can define a static method in a class and use it in any places. My question is, why do we have to namespace the static method even when we use this static method within this class, that is, to add A. before the method name.

My idea is, can we simply change the mechanism so that the static method name within the class does not have to be namespaces as in: (although Python does not support it now):

class A(object):
    def __init__(self, val):
        self.val = plus_one(val)

    @staticmethod
    def plus_one(val):
        return val + 1

My intuition is, since we are calling from within the class, the priority of class members should be higher than global functions, and thus there won't be any ambiguity. Why does Python force us to namespace it?

Body:
Methods defined in a class are not accessible by bare name, except by code running directly in the class namespace (not inside another method). If you want to call a method, you usually have to look it up on some kind of object (either an instance, or the class itself). The different kinds of methods differ in how they behave when for different kinds of lookups.

class Test(object):
    def normal_method(self, foo):
        print("normal_method", self, foo)
        # none of the method names are valid here as bare names, only via self or Test
        try:
            class_method(type(self), foo) # raises NameError
        except NameError:
            pass

        self.class_method(foo) # this works
        Test.class_method(foo) # so does this

    @classmethod
    def class_method(cls, foo):
        print("class_method", cls, foo)
        # from a class method, you can call a method via the automatically provided cls
        cls.static_method(foo)

    @staticmethod
    def static_method(foo):
        print("static_method", foo)
        # a static method can only use the global class name to call other methods
        if isinstance(foo, int) and foo > 0:
            Test.static_method(foo - 1)

    # Class level code is perilous.
    #normal_method('x', 2) # could work in Python 3 (Python 2 checks the type of self)
                           # but it probably won't be useful (since self is not an instance)
    #class_method('x', 2) # Won't work. A classmethod descriptor isn't directly callable
    #staticmethod(2)      # Nor is a staticmethod

# Top level code (these are all valid)
Test().normal_method(2) # also could be Test.normal_method(Test(), 2)
Test.class_method(2)  # could also be Test().class_method(2) (type of the instance is used)
Test.static_method(2) # could also be Test().static_method(2) (instance is ignored)


问:
How do I pass an std::string to a function that expects char*?

Possible Duplicate:

  Can I get a non-const C string back from a C++ string?

Do I need to convert it first? I saw in another post that .c_str() can be used if the function expected const char*. What about for just char*?

答:
It's a dirty solution but I guess it works

std::string foo("example");

char* cpy = (char*)malloc(foo.size()+1);

memcpy(cpy, foo.c_str(), foo.size()+1);


答:
From the log output, we can see that the second call to your view function is triggered by the URL /test/images/favicon.ico. You probably have a line like this in your template:

```<code><link rel="shortcut icon" href="images/favicon.ico">
</code>```

Note that there's no slash before images, which means that the URL will be treated as relative to the current page URL, /test/. You should change this line to point to the correct location of your favicon (probably something like /static/img/favicon.ico), or delete it completely if you don't have one.

The URL /test/images/favicon.ico is triggering your view function because
the pattern r'^test/' matches all URLs beginning with /test/. If you want it to only match the specific URL /test/, the line should be:

```<code>url(r'^test/$', views.test, name='test'),
</code>```

Title: Django calling view method twice

Body:
This is my url.py code:

urlpatterns = [
    url(r'^test/', views.test, name='test'),
]

This is my views.py code:

def test(request):

    print  ("++++++++++++++++++++++++++++++++++++++++++++++++")

    return render(request, 'my_app/index_test.html')

This is my output from console

Django version 1.10.6, using settings 'some_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
++++++++++++++++++++++++++++++++++++++++++++++++++++++
[03/Apr/2017 01:24:41] "GET /test/ HTTP/1.1" 200 26814
[03/Apr/2017 01:24:41] "GET /static/css/normalize.css HTTP/1.1" 200 8053
[03/Apr/2017 01:24:41] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 102897
[03/Apr/2017 01:24:41] "GET /static/css/font-awesome.min.css HTTP/1.1" 200 21979
[03/Apr/2017 01:24:41] "GET /static/css/animate.css HTTP/1.1" 200 63414
[03/Apr/2017 01:24:41] "GET /static/css/gg_preloading.css HTTP/1.1" 200 3816
[03/Apr/2017 01:24:41] "GET /static/css/prettyPhoto.css HTTP/1.1" 200 19888
[03/Apr/2017 01:24:41] "GET /static/css/style.css HTTP/1.1" 200 23649
[03/Apr/2017 01:24:41] "GET /static/js/jquery-1.10.2.min.js HTTP/1.1" 200 93107
[03/Apr/2017 01:24:41] "GET /static/js/bootstrap.js HTTP/1.1" 200 58327
[03/Apr/2017 01:24:41] "GET /static/js/waypoints.min.js HTTP/1.1" 200 8044
[03/Apr/2017 01:24:41] "GET /static/js/jquery.scrollto.min.js HTTP/1.1" 200 2434
[03/Apr/2017 01:24:41] "GET /static/js/jquery.localscroll.min.js HTTP/1.1" 200 1560
[03/Apr/2017 01:24:41] "GET /static/js/scripts.js HTTP/1.1" 200 5183
[03/Apr/2017 01:24:41] "GET /static/js/less.min.js HTTP/1.1" 200 143621
[03/Apr/2017 01:24:41] "GET /static/img/empty_1.png HTTP/1.1" 200 15358
[03/Apr/2017 01:24:41] "GET /static/img/empty_2.png HTTP/1.1" 200 15411
[03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-6.jpg HTTP/1.1" 200 47285
[03/Apr/2017 01:24:41] "GET /static/pic/hotlog_counter.png HTTP/1.1" 200 1700
[03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-5.jpg HTTP/1.1" 200 31588
[03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-1.jpg HTTP/1.1" 200 33355
[03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-2.jpg HTTP/1.1" 200 29322
[03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-3.jpg HTTP/1.1" 200 24960
[03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-4.jpg HTTP/1.1" 200 23886
[03/Apr/2017 01:24:42] "GET /static/less/style.less HTTP/1.1" 200 4607
[03/Apr/2017 01:24:42] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-5.jpg HTTP/1.1" 200 129141
[03/Apr/2017 01:24:42] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-6.jpg HTTP/1.1" 200 95125
[03/Apr/2017 01:24:42] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-7.jpg HTTP/1.1" 200 101621
[03/Apr/2017 01:24:42] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-4.jpg HTTP/1.1" 200 110054
[03/Apr/2017 01:24:43] "GET /static/img/fairy_logo_large.png HTTP/1.1" 200 5794
[03/Apr/2017 01:24:43] "GET /static/font/fontawesome-webfont.woff?v=4.2.0 HTTP/1.1" 200 65452
[03/Apr/2017 01:24:43] "GET /static/img/fairy_bckgrnd.jpg HTTP/1.1" 200 226213
[03/Apr/2017 01:24:43] "GET /static/img/sprite_social_element.png HTTP/1.1" 200 11187
[03/Apr/2017 01:24:43] "GET /static/img/lang_picto.png HTTP/1.1" 200 6577
[03/Apr/2017 01:24:43] "GET /static/img/bullet.png HTTP/1.1" 200 2828
++++++++++++++++++++++++++++++++++++++++++++++++++++++
[03/Apr/2017 01:24:43] "GET /test/images/favicon.ico HTTP/1.1" 200 26814
[03/Apr/2017 01:24:43] "GET /static/img/fairies_features.png HTTP/1.1" 200 482983
[03/Apr/2017 01:24:43] "GET /static/img/best.png HTTP/1.1" 200 72272
[03/Apr/2017 01:24:43] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-11.jpg HTTP/1.1" 200 262491
[03/Apr/2017 01:24:43] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-8.jpg HTTP/1.1" 200 255375
[03/Apr/2017 01:24:43] "GET /static/img/video.png HTTP/1.1" 200 2672
[03/Apr/2017 01:24:43] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-9.jpg HTTP/1.1" 200 329229
[03/Apr/2017 01:24:43] "GET /static/pic/%D0%9D%D0%91_%D0%98%D1%81%D1%85%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-10.jpg HTTP/1.1" 200 160719

After I reload my page or just go to it,
you can see it prints ++++++++++++++++++++++++++++++++++ two times.

What do I do??

Body:
From the log output, we can see that the second call to your view function is triggered by the URL /test/images/favicon.ico. You probably have a line like this in your template:

<link rel="shortcut icon" href="images/favicon.ico">

Note that there's no slash before images, which means that the URL will be treated as relative to the current page URL, /test/. You should change this line to point to the correct location of your favicon (probably something like /static/img/favicon.ico), or delete it completely if you don't have one.

The URL /test/images/favicon.ico is triggering your view function because
the pattern r'^test/' matches all URLs beginning with /test/. If you want it to only match the specific URL /test/, the line should be:

url(r'^test/$', views.test, name='test'),


问:
How to find frequency of each element in DatagridView
I have a DataGridView which looks a little like this:

```<code>ColumnName
hello
hello
bye
hello
bye
crocodile
hello
crocodile
</code>```

How do I find the count of each element? i.e Hello = 4, bye = 3 and crocodile = 2
Seeing as they're outputted in a DataGridView column.

Please help

答:
There is probably a better way to query the DataGridView but looping and creating groups with Linq also works. So this is my idea to do it:

```<code>Sub CountRows()

    Dim lstCountRows as List(Of String)
    For Each row As DataGridViewRow In MyDataGridView.Rows
        '2 is the index of the column you are querying
        lstCountRows.Add(row.Cells(2).Value)
    Next
    'Create groups for the values on lstCountRows
    Dim groups = lstCountRows.GroupBy(Function(value) value)
    'Loop and print the groups count
    For Each group In groups
        MsgBox(group(0) & "-" & group.Count)
    Next

End Sub
</code>```

Give it a try and let me know your comments

Body:
I have a DataGridView which looks a little like this:

ColumnName
hello
hello
bye
hello
bye
crocodile
hello
crocodile

How do I find the count of each element? i.e Hello = 4, bye = 3 and crocodile = 2
Seeing as they're outputted in a DataGridView column.

Please help

Body:
There is probably a better way to query the DataGridView but looping and creating groups with Linq also works. So this is my idea to do it:

Sub CountRows()

    Dim lstCountRows as List(Of String)
    For Each row As DataGridViewRow In MyDataGridView.Rows
        '2 is the index of the column you are querying
        lstCountRows.Add(row.Cells(2).Value)
    Next
    'Create groups for the values on lstCountRows
    Dim groups = lstCountRows.GroupBy(Function(value) value)
    'Loop and print the groups count
    For Each group In groups
        MsgBox(group(0) & "-" & group.Count)
    Next

End Sub

Give it a try and let me know your comments


问:
Flask:validate_on_submit always false, form.errors empty
The validate_on_submit is always false and the form.errors is empty. I'm clueless. Tips? thanks.

app.py:

```<code>def set_comment(page):
    f = form.CommentForm()
    if f.validate_on_submit():
        db.set_comment(f.text.data, datetime.datetime.utcnow(), page, 1)
    else:
        flash(f.errors)
</code>```

form.py

```<code>class CommentForm(Form):
    text = TextField('Message')
</code>```

show.html

```<code><div id="post_comment">
      <form action="" method="post" name="comment">
        {{form.hidden_tag()}}
        {{form.text}}
  </div>
</code>```

答:
In your template, the submit button is missing:</p>

```<code><div id="post_comment">
  <form action="" method="post" name="comment">
    {{form.hidden_tag()}}
    {{form.text}}
    <input type="submit" value="Submit"> <!-- this line -->
  </form>
</div>
</code>```

Body:
The validate_on_submit is always false and the form.errors is empty. I'm clueless. Tips? thanks.

app.py:

def set_comment(page):
    f = form.CommentForm()
    if f.validate_on_submit():
        db.set_comment(f.text.data, datetime.datetime.utcnow(), page, 1)
    else:
        flash(f.errors)

form.py

class CommentForm(Form):
    text = TextField('Message')

show.html

      <form action="" method="post" name="comment">
        {{form.hidden_tag()}}
        {{form.text}}

Body:
In your template, the submit button is missing:

<div id="post_comment">
  <form action="" method="post" name="comment">
    {{form.hidden_tag()}}
    {{form.text}}
    <input type="submit" value="Submit"> <!-- this line -->
  </form>
</div>


问:
How session works in coldfusion?
I have some doubts regarding the session and client management in coldfusion.

Note: The behavior is as follows when CFID and CFTOKEN are provided in the URL: If session exists, the CFID and CFTOKEN from the URL are ignored. If the session does not exist, CFID and CFTOKEN from the URL are used to validate the session and the session is used if it is valid. If the session is not valid, a new session is created. CFID and CFTOKEN are regenerated.

This is a statement from adobe ColdFusion online documentation. Below are my questions

How ColdFusion checks if the session exists without the help of CFID and CFTOKEN as in the first sentence?

Suppose we are using ColdFusion session management, if the CFTOKEN and CFID doesn't change after login can we hijack the session?

答:
Using client and session variables without cookies

It's possible for users to disable cookies in their browsers. In this case, ColdFusion cannot maintain the client state automatically. You can use client or session variables without using cookies, by passing the client identification information between application pages. However, this technique has significant limitations, as follows:

Client variables are effectively the same as session variables, except that they leave unusable data in the client data store.
Because the client’s system does not retain any identification information, the next time the user logs on, ColdFusion cannot identify the user with the previous client and must create a new client ID for the user. Any information about the user from a previous session is not available, but remains in client data storage until ColdFusion deletes it. If you clear the Purge Data for Clients that Remain Unvisited option in the ColdFusion Administrator, ColdFusion never deletes this data.
Therefore, do not use client variables, if you allow users to disable cookies. To retain client information without cookies, require users to login with a unique ID. You can then save user-specific information in a database with the user’s ID as a key.

ColdFusion creates a new session each time the user requests a page directly in the browser, because the new request contains no state information to indicate the session or client.

Note: You can prevent ColdFusion from sending client information to the browser as cookies by setting This.setClientCookies variable in Application.cfc or the setClientCookies attribute of the cfapplication tag to No.

To use ColdFusion session variables without using cookies, each page must pass the CFID and CFToken values to any page that it calls as part of the request URL. If a page contains any HTML hrefa= links, cflocation tags, form tags, or cfform tags the tags must pass the CFID and CFToken values in the tag URL. To use J2EE session management, pass the jsessionid value in page requests. To use ColdFusion client variables and J2EE session variables, pass the CFID, CFToken, and jsessionid values in URLs.

Note: The behavior is as follows when CFID and CFTOKEN are provided in the URL: If session exists, the CFID and CFTOKEN from the URL are ignored. If the session does not exist, CFID and CFTOKEN from the URL are used to validate the session and the session is used if it is valid. If the session is not valid, a new session is created. CFID and CFTOKEN are regenerated.

ColdFusion provides the URLSessionFormat function, which does the following:

If the client does not accept cookies, automatically appends all required client identification information to a URL.

If the client accepts cookies, does not append the information.
The URLSessionFormat function automatically determines which identifiers are required, and sends only the required information. It also provides a more secure and robust method for supporting client identification than manually encoding the information in each URL, because it only sends the information that is required, when it is required, and it is easier to code.

To use the URLSessionFormat function, enclose the request URL in the function. For example, the following cfform tag posts a request to another page and sends the client identification, if necessary:

```<code><cfform method="Post" action="#URLSessionFormat("MyActionPage.cfm")#>
</code>```

If you use the same page URL in multiple URLSessionFormat functions, you can gain a small performance improvement and simplify your code if you assign the formatted page URL to a variable, for example:

```<code><cfset myEncodedURL=URLSessionFormat(MyActionPage.cfm)>
<cfform method="Post" action="#myEncodedURL#">
</code>```

Title: How session works in coldfusion?

Body:
Using client and session variables without cookies

It's possible for users to disable cookies in their browsers. In this case, ColdFusion cannot maintain the client state automatically. You can use client or session variables without using cookies, by passing the client identification information between application pages. However, this technique has significant limitations, as follows:

Client variables are effectively the same as session variables, except that they leave unusable data in the client data store.
Because the client’s system does not retain any identification information, the next time the user logs on, ColdFusion cannot identify the user with the previous client and must create a new client ID for the user. Any information about the user from a previous session is not available, but remains in client data storage until ColdFusion deletes it. If you clear the Purge Data for Clients that Remain Unvisited option in the ColdFusion Administrator, ColdFusion never deletes this data.
Therefore, do not use client variables, if you allow users to disable cookies. To retain client information without cookies, require users to login with a unique ID. You can then save user-specific information in a database with the user’s ID as a key.

ColdFusion creates a new session each time the user requests a page directly in the browser, because the new request contains no state information to indicate the session or client.

Note: You can prevent ColdFusion from sending client information to the browser as cookies by setting This.setClientCookies variable in Application.cfc or the setClientCookies attribute of the cfapplication tag to No.

To use ColdFusion session variables without using cookies, each page must pass the CFID and CFToken values to any page that it calls as part of the request URL. If a page contains any HTML hrefa= links, cflocation tags, form tags, or cfform tags the tags must pass the CFID and CFToken values in the tag URL. To use J2EE session management, pass the jsessionid value in page requests. To use ColdFusion client variables and J2EE session variables, pass the CFID, CFToken, and jsessionid values in URLs.

Note: The behavior is as follows when CFID and CFTOKEN are provided in the URL: If session exists, the CFID and CFTOKEN from the URL are ignored. If the session does not exist, CFID and CFTOKEN from the URL are used to validate the session and the session is used if it is valid. If the session is not valid, a new session is created. CFID and CFTOKEN are regenerated.

ColdFusion provides the URLSessionFormat function, which does the following:

If the client does not accept cookies, automatically appends all required client identification information to a URL.

If the client accepts cookies, does not append the information.
The URLSessionFormat function automatically determines which identifiers are required, and sends only the required information. It also provides a more secure and robust method for supporting client identification than manually encoding the information in each URL, because it only sends the information that is required, when it is required, and it is easier to code.

To use the URLSessionFormat function, enclose the request URL in the function. For example, the following cfform tag posts a request to another page and sends the client identification, if necessary:

<cfform method="Post" action="#URLSessionFormat("MyActionPage.cfm")#>

If you use the same page URL in multiple URLSessionFormat functions, you can gain a small performance improvement and simplify your code if you assign the formatted page URL to a variable, for example:

<cfset myEncodedURL=URLSessionFormat(MyActionPage.cfm)>
<cfform method="Post" action="#myEncodedURL#">


问:
Undefined local variable or method `git_source' for Gemfile
Cloned a rails application from github, works on the original dev's machine using the same version of rails (5.0.1).

Any rails command run from the app directory fails with:

```<code>Undefined local variable or method `git_source' for Gemfile
</code>```

Relevant Gemfile section:

```<code>git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end
</code>```

答:
In your console, run…</p>

```<code>gem update bundler
bundle install
</code>```

Body:
Cloned a rails application from github, works on the original dev's machine using the same version of rails (5.0.1).

Any rails command run from the app directory fails with:

Undefined local variable or method `git_source' for Gemfile

Relevant Gemfile section:

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

Body:
In your console, run…

gem update bundler
bundle install


问:
order_by creates duplicate entries
I have 4 model classes: User, Stack, Article and Rating. Users can create stacks, add articles, put them on a stack, rate the articles and share the stacks.
I want to get a QuerySet of all articles of a specific stack (got by pk) and ordered by the current users rating. My query leads to duplicate entries in my QuerySet if the stack was shared and an article was rated by another user, so that there exists a rating object for an article twice:

```<code>qs = stack.article_set.all().order_by("ratings__rating", "-pk")
</code>```

models:

```<code>class Rating(models.Model):
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name='ratings'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='ratings'
    )
    rating = models.IntegerField()

class Stack(models.Model):
    title = models.CharField(null=True, max_length=100)

    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Article(models.Model):
    stack = models.ForeignKey(Stack, null=True, blank=True, on_delete=models.CASCADE)

    text = models.TextField(null=True, blank=True)
</code>```

How can I get the ordered QuerySet without the duplicates, just ordered by the request.user ratings.

Update

What I do for now is to query twice. One time to get the already rated article objects ordered by the rating and a second time to get the currently not rated article objects unsorted.

```<code>    context['rated_articles'] = deck.article_set.filter(
        ratings__user__exact=self.request.user
        ).order_by("ratings__rating", "-pk")

    context['not_rated_articles'] = deck.article_set.all().exclude(
        ratings__user__exact=self.request.user
    )
</code>```

答:
You should be able to filter the article set before you order it, based on the stacks owner</p>

```<code>user = stack.owner
stack.article_set.filter(rating__user__exact=user).order_by("ratings__rating", "-pk")
</code>```

Title: order_by creates duplicate entries

Body:
I have 4 model classes: User, Stack, Article and Rating. Users can create stacks, add articles, put them on a stack, rate the articles and share the stacks.
I want to get a QuerySet of all articles of a specific stack (got by pk) and ordered by the current users rating. My query leads to duplicate entries in my QuerySet if the stack was shared and an article was rated by another user, so that there exists a rating object for an article twice:

qs = stack.article_set.all().order_by("ratings__rating", "-pk")

models:

class Rating(models.Model):
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name='ratings'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='ratings'
    )
    rating = models.IntegerField()

class Stack(models.Model):
    title = models.CharField(null=True, max_length=100)

    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Article(models.Model):
    stack = models.ForeignKey(Stack, null=True, blank=True, on_delete=models.CASCADE)

    text = models.TextField(null=True, blank=True)

How can I get the ordered QuerySet without the duplicates, just ordered by the request.user ratings.

Update

What I do for now is to query twice. One time to get the already rated article objects ordered by the rating and a second time to get the currently not rated article objects unsorted.

    context['rated_articles'] = deck.article_set.filter(
        ratings__user__exact=self.request.user
        ).order_by("ratings__rating", "-pk")

    context['not_rated_articles'] = deck.article_set.all().exclude(
        ratings__user__exact=self.request.user
    )

Body:
You should be able to filter the article set before you order it, based on the stacks owner

user = stack.owner
stack.article_set.filter(rating__user__exact=user).order_by("ratings__rating", "-pk")


问:
Redux Form: MapStateToProps is breaking form
The goal of the MapStateToProps in this Redux Form is to check whether the user is in the database and to pass back a validuser state back to the submitted form so that I can either render an error message, or redirect the user to the home page. The problem is that when I try to connect MapStateToProps to the form, it throws an error.

Redux Form:

```<code>import React, { Component } from "react";
import { connect } from 'react-redux';
import { reduxForm, Field, Form, reset } from "redux-form";
import { Link } from 'react-router-dom';
import { checkUser } from "../actions/index";

class SignIn extends Component {
  constructor(props) {
    super(props)

    this.state = {
      user: {
        validUser: {
          username: null,
          validUser: null
        }
      }
    }
  }

  onSubmit = (props) => {
    this.props.dispatch(checkUser(props));
  }

  render() {
    const { handleSubmit, reset } = this.props;

    return(
      <div>
      <form onSubmit={ handleSubmit(this.onSubmit.bind(this)) }>
        <h3>Sign In!</h3>

        <div>
          <label><h3>Username</h3></label>
          <div>
            <Field name="username" component="input" type="text" />
          </div>
        </div>

        <div>
          <label><h3>Password</h3></label>
          <div>
            <Field name="password" component="input" type="password" />
          </div>
        </div>

        <button type="submit" className="btn btn-primary">Submit</button>
        <button><Link to="/me" className="btn btn-danger">Cancel</Link></button>
      </form>

    </div>
    )
  }
};

function mapStateToProps(state) {
  return {
    user: state.user.validUser
  };
};

let signInForm = reduxForm(
  { form: "signInForm" })(SignIn);

export default signInForm = connect(mapStateToProps, null)(SignIn);
</code>```

However I get the following error:

```<code>Uncaught TypeError: handleSubmit is not a function
    at SignIn.render (signin.js:33)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
</code>```

Can anyone advise on debugging this issue?

答:
The issue here is that you're passing your original component to connect.

```<code>const ReduxFormSigninForm = reduxForm({ form: "signInForm" })(SignIn);

const connected ReduxFormSigninForm = connect(mapStateToProps)(ReduxFormSigninForm);
</code>```

An alternate way to write this would be to use compose, which you can import from redux.

```<code>import { compose } from 'redux';

export default compose(
  connect(mapStateToProps),
  reduxForm({ form: "signInForm" })
)(SignIn);
</code>```

Body:
The goal of the MapStateToProps in this Redux Form is to check whether the user is in the database and to pass back a validuser state back to the submitted form so that I can either render an error message, or redirect the user to the home page. The problem is that when I try to connect MapStateToProps to the form, it throws an error.

Redux Form:

import React, { Component } from "react";
import { connect } from 'react-redux';
import { reduxForm, Field, Form, reset } from "redux-form";
import { Link } from 'react-router-dom';
import { checkUser } from "../actions/index";

class SignIn extends Component {
  constructor(props) {
    super(props)

    this.state = {
      user: {
        validUser: {
          username: null,
          validUser: null
        }
      }
    }
  }

  onSubmit = (props) => {
    this.props.dispatch(checkUser(props));
  }

  render() {
    const { handleSubmit, reset } = this.props;

    return(

      <form onSubmit={ handleSubmit(this.onSubmit.bind(this)) }>

Sign In!

Username

            <Field name="username" component="input" type="text" />

Password

            <Field name="password" component="input" type="password" />

        <button type="submit" className="btn btn-primary">Submit</button>
        <button><Link to="/me" className="btn btn-danger">Cancel</Link></button>
      </form>

    )
  }
};

function mapStateToProps(state) {
  return {
    user: state.user.validUser
  };
};

let signInForm = reduxForm(
  { form: "signInForm" })(SignIn);

export default signInForm = connect(mapStateToProps, null)(SignIn);

However I get the following error:

Uncaught TypeError: handleSubmit is not a function
    at SignIn.render (signin.js:33)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)

Can anyone advise on debugging this issue?

Body:
The issue here is that you're passing your original component to connect.

const ReduxFormSigninForm = reduxForm({ form: "signInForm" })(SignIn);

const connected ReduxFormSigninForm = connect(mapStateToProps)(ReduxFormSigninForm);

An alternate way to write this would be to use compose, which you can import from redux.

import { compose } from 'redux';

export default compose(
  connect(mapStateToProps),
  reduxForm({ form: "signInForm" })
)(SignIn);


问:
Setting function pointer inside class
Im trying to create a simple windows api.

I need a little help in setting a function pointer in side class
Im getting errors trying to set the function to a function that is inside a class, Is there anyway this can be done without using static in the class?

```<code>class Window
{
public:
    WIN_API Window();

    struct WIN_API
    {
        bool(*OnMouseClick)(Vector2D position, MouseButton button);
        bool(*OnCreate)();
    }Event;
};

class MainWindow : public Window
{
public:
    MainWindow() : Window()
    {
        //error here
        this->Event.OnCreate = OnCreate;
        this->Event.OnMouseClick = OnMouseClick;
    }

    bool OnCreate()
    {
        return true;
    }

    bool OnMouseClick(Vector2D position, MouseButton button)
    {
        return true;
    }
};
</code>```

答:
You have to bind the member function of a particular instance.  This is best done using a lambda and std::function objects.

```<code>class Window
{
public:
    Window();

    struct WIN_API
    {
      std::function<bool(Vector2D, MouseButton)> OnMouseClick;
      std::function<bool()> OnCreate;
    } Event;
};

class MainWindow : public Window
{
public:
    MainWindow()
    {
      this->Event.OnCreate =
        [this] () { return this->OnCreate(); };

      this->Event.OnMouseClick =
        [this] (Vector2D position, MouseButton button)
        { return this->OnMouseClick(position, button); };
    }

    bool OnCreate()
    {
        return true;
    }

    bool OnMouseClick(Vector2D position, MouseButton button)
    {
        return true;
    }
};
</code>```

Title: Setting function pointer inside class

Body:
Im trying to create a simple windows api.

I need a little help in setting a function pointer in side class
Im getting errors trying to set the function to a function that is inside a class, Is there anyway this can be done without using static in the class?

class Window
{
public:
    WIN_API Window();

    struct WIN_API
    {
        bool(*OnMouseClick)(Vector2D position, MouseButton button);
        bool(*OnCreate)();
    }Event;
};

class MainWindow : public Window
{
public:
    MainWindow() : Window()
    {
        //error here
        this->Event.OnCreate = OnCreate;
        this->Event.OnMouseClick = OnMouseClick;
    }

    bool OnCreate()
    {
        return true;
    }

    bool OnMouseClick(Vector2D position, MouseButton button)
    {
        return true;
    }
};

Body:
You have to bind the member function of a particular instance.  This is best done using a lambda and std::function objects.

class Window
{
public:
    Window();

    struct WIN_API
    {
      std::function<bool(Vector2D, MouseButton)> OnMouseClick;
      std::function<bool()> OnCreate;
    } Event;
};

class MainWindow : public Window
{
public:
    MainWindow()
    {
      this->Event.OnCreate =
        [this] () { return this->OnCreate(); };

      this->Event.OnMouseClick =
        [this] (Vector2D position, MouseButton button)
        { return this->OnMouseClick(position, button); };
    }

    bool OnCreate()
    {
        return true;
    }

    bool OnMouseClick(Vector2D position, MouseButton button)
    {
        return true;
    }
};


问:
warning: invalid credential line: [0x7FFEF7EABC10] ANOMALY: meaningless REX prefix used?
I'm following this guide:
https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails-cli-nodejs

I'm getting this error when i try to

```<code> git push azure master
</code>```

Error:
warning: invalid credential line: [0x7FFEF7EABC10] ANOMALY: meaningless REX prefix
used?

What is exactly happening?

Thanks,

答:
The error code when converted to ASCII is showing up as "þ÷ê¼"
It could point to a problem with the credentials you used in the earlier step2.3</p>

Body:
I'm following this guide:
https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails-cli-nodejs

I'm getting this error when i try to

 git push azure master

Error:
warning: invalid credential line: [0x7FFEF7EABC10] ANOMALY: meaningless REX prefix
used?

What is exactly happening?

Thanks,


问:
How to transform a projected 3D rectangle into a 2D axis aligned rectangle
I have an image of a 3D rectangle (which due to the projection distortion is not a rectangle in the image). I know the all world and image coordinates of all corners of this rectangle.

What I need is to determine the world coordinate of a point in the image inside this rectangle. To do that I need to compute a transformation to unproject that rectangle to a 2D rectangle.

How can I compute that transform?

Thanks in advance

答:
This is a special case of finding mappings between quadrilaterals that preserve straight lines.  These are generally called homographic transforms.  Here, one of the quads is a rectangle, so this is a popular special case. You can google these terms ("quad to quad", etc) to find explanations and code, but here are some sites for you.

Perspective Transform Estimation

a gaming forum discussion

extracting a quadrilateral image to a rectangle

Projective Warping & Mapping

ProjectiveMappings for ImageWarping by Paul Heckbert.

The math isn't particularly pleasant, but it isn't that hard either.  You can also find some code from one of the above links.


问:
How to use regular expressions to pull something from a terminal output?
I'm attempting to use the re module to look through some terminal output. When I ping a server through terminal using ping -n 1 host (I'm using Windows), it gives me much more information than I want. I want just the amount of time that it takes to get a reply from the server, which in this case is always denoted by an integer and then the letters 'ms'. The error I get explains that the output from the terminal is not a string, so I cannot use regular expressions on it.

```<code>from os import system as system_call
import re

def ping(host):
    return system_call("ping -n 1 " + host) == 0

host = input("Select a host to ping: ")

regex = re.compile(r"\w\wms")
final_ping = regex.search(ping(host))
print(final_ping)
</code>```

答:
There are two problems with your code:

Your ping function doesn't return the terminal output. It only returns a bool that reports if the ping succeeded. The ping output is directly forwarded to the terminal that runs the Python script.

Python 3 differentiates between strings (for text, consisting of Unicode codepoints) and bytes (for any data, consisting of bytes). As Python cannot know that ping only outputs ASCII text, you will get a bytes object if you don't specify which text encoding is in use.

It would be the best to use the subprocess module instead of os.system. This is also suggested by the Python documentation.

One possible way is to use subprocess.check_output with the encoding parameter to get a string instead of bytes:

```<code>from subprocess import check_output
import sys

def ping(host):
    return check_output(
       "ping -n 1 " + host,
       shell=True,
       encoding=sys.getdefaultencoding()
     )

...
</code>```

EDIT: The encoding parameter is only supported since Python 3.6. If you are using an older version, try this:

```<code>from subprocess import check_output
import sys

def ping(host):
    return check_output(
       "ping -n 1 " + host,
       shell=True
     ).decode()

...
</code>```

Body:
I'm attempting to use the re module to look through some terminal output. When I ping a server through terminal using ping -n 1 host (I'm using Windows), it gives me much more information than I want. I want just the amount of time that it takes to get a reply from the server, which in this case is always denoted by an integer and then the letters 'ms'. The error I get explains that the output from the terminal is not a string, so I cannot use regular expressions on it.

from os import system as system_call
import re

def ping(host):
    return system_call("ping -n 1 " + host) == 0

host = input("Select a host to ping: ")

regex = re.compile(r"\w\wms")
final_ping = regex.search(ping(host))
print(final_ping)

Body:
There are two problems with your code:

Your ping function doesn't return the terminal output. It only returns a bool that reports if the ping succeeded. The ping output is directly forwarded to the terminal that runs the Python script.

Python 3 differentiates between strings (for text, consisting of Unicode codepoints) and bytes (for any data, consisting of bytes). As Python cannot know that ping only outputs ASCII text, you will get a bytes object if you don't specify which text encoding is in use.

It would be the best to use the subprocess module instead of os.system. This is also suggested by the Python documentation.

One possible way is to use subprocess.check_output with the encoding parameter to get a string instead of bytes:

from subprocess import check_output
import sys

def ping(host):
    return check_output(
       "ping -n 1 " + host,
       shell=True,
       encoding=sys.getdefaultencoding()
     )

...

EDIT: The encoding parameter is only supported since Python 3.6. If you are using an older version, try this:

from subprocess import check_output
import sys

def ping(host):
    return check_output(
       "ping -n 1 " + host,
       shell=True
     ).decode()

...


问:
Appium 1.6 Android. : Location alert
Android Real device with Appium 1.6 -> I have Location alert at start of my app. However Appium is not handling this location alert and gives error that it failed to start the init activity of all.

I have tried following :

```<code>capabilities.setCapability("locationServicesAuthorized", true);
capabilities.setCapability("autoAcceptAlerts", true);
capabilities.setCapability("fullReset", true);
</code>```

Log :

Appium]   autoAcceptAlerts: true
[BaseDriver] The following capabilities were provided, but are not recognized by appium: locationServicesAuthorized, autoAcceptAlerts.
[BaseDriver] Session created with session id: 203a02af-a52f-41ff-b9ec-b71b822bcbff

[ADB] Found package: 'com.android.packageinstaller' and fully qualified activity name : 'com.android.packageinstaller.permission.ui.GrantPermissionsActivity'
[ADB] Incorrect package and activity. Retrying.

[UiAutomator2] UiAutomator2 did not start the activity we were waiting for, '.mobile.ui.main.SplashScreenActivity'. Starting it ourselves

Appium is stuck at com.android.packageinstaller.permission.ui.GrantPermissionsActivity activity and its not able to start main init activity.

Can you please help me to get through it .

Also tried following but no use.

```<code>driver.switchTo().alert().accept();
WebDriverWait wait = new WebDriverWait(driver, 15);
Alert alert = driver.switchTo().alert();
alert.accept();
</code>```

Thanks,
Sumit

答:
This issue was resolved by adding following capabilities </p>

```<code>capabilities.setCapability("appWaitPackage", "com.android.packageinstaller");
capabilities.setCapability("appWaitActivity", ".permission.ui.GrantPermissionsActivity");
</code>```

Title: Appium 1.6 Android. : Location alert

Body:
Android Real device with Appium 1.6 -> I have Location alert at start of my app. However Appium is not handling this location alert and gives error that it failed to start the init activity of all.

I have tried following :

capabilities.setCapability("locationServicesAuthorized", true);
capabilities.setCapability("autoAcceptAlerts", true);
capabilities.setCapability("fullReset", true);

Log :

Appium]   autoAcceptAlerts: true
[BaseDriver] The following capabilities were provided, but are not recognized by appium: locationServicesAuthorized, autoAcceptAlerts.
[BaseDriver] Session created with session id: 203a02af-a52f-41ff-b9ec-b71b822bcbff

[ADB] Found package: 'com.android.packageinstaller' and fully qualified activity name : 'com.android.packageinstaller.permission.ui.GrantPermissionsActivity'
[ADB] Incorrect package and activity. Retrying.

[UiAutomator2] UiAutomator2 did not start the activity we were waiting for, '.mobile.ui.main.SplashScreenActivity'. Starting it ourselves

Appium is stuck at com.android.packageinstaller.permission.ui.GrantPermissionsActivity activity and its not able to start main init activity.

Can you please help me to get through it .

Also tried following but no use.

driver.switchTo().alert().accept();
WebDriverWait wait = new WebDriverWait(driver, 15);
Alert alert = driver.switchTo().alert();
alert.accept();

Thanks,
Sumit

Body:
This issue was resolved by adding following capabilities

capabilities.setCapability("appWaitPackage", "com.android.packageinstaller");
capabilities.setCapability("appWaitActivity", ".permission.ui.GrantPermissionsActivity");


答:
First, mapStateToProps is not something exclusive to redux form, it is from redux/react-redux.

The problem with your code is that you are passing the SignIn component to the connect function, and not the redux-form's HOC component you've just created.

```<code>let signInForm = reduxForm(
   { form: "signInForm" })(SignIn);

export default signInForm = connect(mapStateToProps, null)(SignIn);
</code>```

SignIn is not a redux-form component so it will not have the handleSubmit function.

What you want is this:

```<code>export default connect(mapStateToProps, null)(signInForm);
</code>```

Title: Redux Form: MapStateToProps is breaking form

Body:
First, mapStateToProps is not something exclusive to redux form, it is from redux/react-redux.

The problem with your code is that you are passing the SignIn component to the connect function, and not the redux-form's HOC component you've just created.

let signInForm = reduxForm(
   { form: "signInForm" })(SignIn);

export default signInForm = connect(mapStateToProps, null)(SignIn);

SignIn is not a redux-form component so it will not have the handleSubmit function.

What you want is this:

export default connect(mapStateToProps, null)(signInForm);


问:
Is there a "Group Box" equivalent in Java Swing?
Trying to build a GUI application in Java/Swing. I'm mainly used to "painting" GUIs on the Windows side with tools like VB (or to be more precise, Gupta SQLWindows... wonder how many people know what that is ;-)).

I can't find an equivalent of a Group Box in Swing...

With a group box, you have a square box (usually with a title) around a couple of related widgets. One example is a group box around a few radio buttons (with the title explaining what the radio buttons are about, e.g. Group Box entitled "Sex" with "Male" and "Female" radio buttons).

I've searched around a bit... the only way I found was to add a sub-pane, set the border on the sub-pane and then add all the widgets in the "group" to the sub-pane. Is there a more elegant way to do that?

答:
A Group box is just a set of 'logically grouped widgets'.
This in the swing world is a JPanel.

Add your widgets to a JPanel.

Set its border type to 'Titled Border' and give the title, same as the name of the VB6 'frame'.

Voila. You have your group box.

OwnerDisplayName: IronGoofy

LastEditorDisplayName: A. Rex

OwnerDisplayName: Nivas


问:
How to unpack a list?
When extracting data from a list this way

```<code>line[0:3], line[3][:2], line[3][2:]
</code>```

I receive an array and two variables after it, as should be expected:

```<code>(['a', 'b', 'c'], 'd', 'e')
</code>```

I need to manipulate the list so the end result is

```<code>('a', 'b', 'c', 'd', 'e')
</code>```

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

答:
```<code>def is_iterable(i):
    return hasattr(i,'__iter__')

def iterative_flatten(List):
    for item in List:
        if is_iterable(item):
            for sub_item in iterative_flatten(item):
                yield sub_item
        else:
            yield item

def flatten_iterable(to_flatten):
    return tuple(iterative_flatten(to_flatten))
</code>```

this should work for any level of nesting

Title: How to unpack a list?

Body:
When extracting data from a list this way

line[0:3], line[3][:2], line[3][2:]

I receive an array and two variables after it, as should be expected:

(['a', 'b', 'c'], 'd', 'e')

I need to manipulate the list so the end result is

('a', 'b', 'c', 'd', 'e')

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

Body:
def is_iterable(i):
    return hasattr(i,'__iter__')

def iterative_flatten(List):
    for item in List:
        if is_iterable(item):
            for sub_item in iterative_flatten(item):
                yield sub_item
        else:
            yield item

def flatten_iterable(to_flatten):
    return tuple(iterative_flatten(to_flatten))

this should work for any level of nesting


问:
GDB pipe input to debugged file without using a file
I'm trying to pass the debugged program the output of python scrip like this:

```<code>(gdb) run $(python -c "print('A'*60)")
</code>```

However this is passed as argument.

```<code>(gdb) run < $(python -c "print('A'*60)")
</code>```

This reports an error as it replaces the right part withs the 'A's and fails to open a file with such name.

I'm looking for sort of piping mechanism in gdb.

```<code>python -c "print('A'*60)" > input.txt
(gdb) run < input.txt
</code>```

Would be a solution but I don't have the permission to create a file (I'm trying to solve a stack-smashing based CTF)

答:
You are looking for:

```<code>(gdb) run <(python -c "print('A'*60)")
</code>```

(This is a shell redirection feature, not GDB redirection feature).

I don't have the permission to create a file

It's rare for the system to not allow you to create files in /tmp.

```<code>python -c "print('A'*60)" > /tmp/input.txt
(gdb) run < /tmp/input.txt
</code>```

Body:
I'm trying to pass the debugged program the output of python scrip like this:

(gdb) run $(python -c "print('A'*60)")

However this is passed as argument.

(gdb) run < $(python -c "print('A'*60)")

This reports an error as it replaces the right part withs the 'A's and fails to open a file with such name.

I'm looking for sort of piping mechanism in gdb.

python -c "print('A'*60)" > input.txt
(gdb) run < input.txt

Would be a solution but I don't have the permission to create a file (I'm trying to solve a stack-smashing based CTF)

Body:
You are looking for:

(gdb) run <(python -c "print('A'*60)")

(This is a shell redirection feature, not GDB redirection feature).

I don't have the permission to create a file

It's rare for the system to not allow you to create files in /tmp.

python -c "print('A'*60)" > /tmp/input.txt
(gdb) run < /tmp/input.txt


问:
Unable to Model Array of Invariant Polymorphic Classes
Is there a way to model this without annotating A<+T>?

```<code>class A<T> {
  static value: T
}

declare var Bar: Class<A<string>>
declare var Baz: Class<A<number>>

function foo<T, U: T>(...rest: $ReadOnlyArray<Class<A<U>>>): Array<T> {
  return rest.reduce((init, { value }) => ([ ...init, value ]), [])
}

(foo(Bar, Baz): Array<string | number>)
</code>```

Error

```<code>5: declare var Bar: Class<A<string>>
                            ^ string. This type is incompatible with
6: declare var Baz: Class<A<number>>
                            ^ number
6: declare var Baz: Class<A<number>>
                            ^ number. This type is incompatible with
5: declare var Bar: Class<A<string>>
                            ^ string
</code>```

https://flow.org/try/#0MYGwhgzhAECCA8AVAfNA3gKGtCAXMuAlsNAG5ggCuApgFzSLYYC+GGAJtaGAE7Vm9oAIV70AwuCjwEeHoQB2Ac2TIOXcHwE9hYAF7jJEafHmUAtgCNqPFVmz2MAM0rzgRAPbzoj9+6QAaaABVehQACgA6KL48egASACVqMHYAeXkQAE9YHh4wTPgJSCMEIJVkAEp6HLyClHQ7PlxKHi8Y3Ai+dkpgajCwhUJcQLQBKn5mCugAXlQwgG1oKIjB4bGaaABdCsD57ZY7ewcwn3cwkR5AkV0quFz8+FkFRWgAH2hTS2tKoA

答:
I am not an expert on Flow, but I believe you can get this working by changing

```<code>$ReadOnlyArray<Class<A<U>>>
</code>```

to

```<code>$ReadOnlyArray<{+value: U}>
</code>```

Body:
Is there a way to model this without annotating A<+T>?

class A<T> {
  static value: T
}

declare var Bar: Class<A<string>>
declare var Baz: Class<A<number>>

function foo<T, U: T>(...rest: $ReadOnlyArray<Class<A>>): Array<T> {
  return rest.reduce((init, { value }) => ([ ...init, value ]), [])
}

(foo(Bar, Baz): Array<string | number>)

Error

5: declare var Bar: Class<A<string>>
                            ^ string. This type is incompatible with
6: declare var Baz: Class<A<number>>
                            ^ number
6: declare var Baz: Class<A<number>>
                            ^ number. This type is incompatible with
5: declare var Bar: Class<A<string>>
                            ^ string

https://flow.org/try/#0MYGwhgzhAECCA8AVAfNA3gKGtCAXMuAlsNAG5ggCuApgFzSLYYC+GGAJtaGAE7Vm9oAIV70AwuCjwEeHoQB2Ac2TIOXcHwE9hYAF7jJEafHmUAtgCNqPFVmz2MAM0rzgRAPbzoj9+6QAaaABVehQACgA6KL48egASACVqMHYAeXkQAE9YHh4wTPgJSCMEIJVkAEp6HLyClHQ7PlxKHi8Y3Ai+dkpgajCwhUJcQLQBKn5mCugAXlQwgG1oKIjB4bGaaABdCsD57ZY7ewcwn3cwkR5AkV0quFz8+FkFRWgAH2hTS2tKoA

Body:
I am not an expert on Flow, but I believe you can get this working by changing

$ReadOnlyArray<Class<A<U>>>

to

$ReadOnlyArray<{+value: U}>


问:
How to determine whether an array is contained in another array
The question is, given [1,2,3,4,5] and [2,4,5], to determine whether (every element in) the second array is contained in the first one. The answer is true.

What's the most succinct and efficient way to do better than:

```<code>arr2.reject { |e| arr1.include?(e) } .empty?
</code>```

答:
The bad O(n²) one-liner would look like this:

```<code>arr2.all? { |x| arr1.include? x }
arr2.all? &arr1.method(:include?)  # alternative
</code>```

If your objects are hashable, you can make this O(n) by making a set out of the first array:

```<code>require 'set'

arr2.all? &Set.new(arr1).method(:include?)
</code>```

If your objects are totally, like, ordered, you can make it O(n log n) with a sort and a binary search:

```<code>arr1.sort!
arr2.all? { |x| arr1.bsearch { |y| x <=> y } }
</code>```

Body:
The question is, given [1,2,3,4,5] and [2,4,5], to determine whether (every element in) the second array is contained in the first one. The answer is true.

What's the most succinct and efficient way to do better than:

arr2.reject { |e| arr1.include?(e) } .empty?

Body:
The bad O(n²) one-liner would look like this:

arr2.all? { |x| arr1.include? x }
arr2.all? &arr1.method(:include?)  # alternative

If your objects are hashable, you can make this O(n) by making a set out of the first array:

require 'set'

arr2.all? &Set.new(arr1).method(:include?)

If your objects are totally, like, ordered, you can make it O(n log n) with a sort and a binary search:

arr1.sort!
arr2.all? { |x| arr1.bsearch { |y| x <=> y } }


问:
ER diagram, is this allowed?
I have to create an ER diagram based on a relational schema.

There is a table of players, and a table of zones. A player can 'live' in many zones, and each zone is owned by one or more players.

I've come up with this simple ER diagram but I'm not sure having relationships going each way is allowed?

Cheers

答:
I am not able to see your images (blocked!) so I'll just try to describe the "correct" design. If a player living in a zone doesn't necessarily mean they own it, you should have four tables:

```<code>PLAYER (playerid, <other fields>)
ZONE (zoneid, <other fields>
PLAYER_ZONE(playerid, lives_in_zoneid)
ZONE_OWNER (zoneid, owner_playerid)
</code>```

Otherwise three tables would suffice.

Title: ER diagram, is this allowed?

Body:
I am not able to see your images (blocked!) so I'll just try to describe the "correct" design. If a player living in a zone doesn't necessarily mean they own it, you should have four tables:

PLAYER (playerid, <other fields>)
ZONE (zoneid, <other fields>
PLAYER_ZONE(playerid, lives_in_zoneid)
ZONE_OWNER (zoneid, owner_playerid)

Otherwise three tables would suffice.


问:
`Uncaught SyntaxError: Unexpected token <` when referencing existing javascript file
Important edit at bottom of some strange behavior.

I'm trying to include a javascript file into my html via a
    <script type="text/javascript" src="../static/js/filter.js"></script>

```

<hr>

<p><strong>And here is the javascript file.</strong></p>

```function filter(element) {
    $.ajax({
        url: '/updateFilter?filter=' + element.value,
        success: location.reload(true),
        error: location.reload(true)
    })
}
```

Editing to add this image. For some reason this is the filter.js file when I inspect the sources in Chrome.

EDIT: For some reason, every request other than the one I have mapped to the controller, including filter.js, is returning the raw html from index.vm

答:
You have an unnecessary closing tag for your  element - pasting your html into plnkr highlights this.

I would also perform a "trial and error" process of elimination, as it may not be the inclusion of the JS file that is the cause.

Body:
Important edit at bottom of some strange behavior.

I'm trying to include a javascript file into my html via a

And here is the javascript file.

function filter(element) {
    $.ajax({
        url: '/updateFilter?filter=' + element.value,
        success: location.reload(true),
        error: location.reload(true)
    })
}

Editing to add this image. For some reason this is the filter.js file when I inspect the sources in Chrome.

EDIT: For some reason, every request other than the one I have mapped to the controller, including filter.js, is returning the raw html from index.vm