问:
Is there more to enumerate() than just zip(range(len()))?
Everything in Python is there for a reason. All systems powered by Python depend on something like 50 built-in functions, most of which are extremely useful and unique, like format(), len(), list(), or range(). I can't understand why enumerate() exists.

It's been introduced in PEP 279 (2002) and was kept until now. I really don't understand why it exists because it can be done using other more important built-in functions in 2-3 characters more. From the Python Docs:

```<code>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
</code>```

```<code>for i in enumerate(seasons):
    print(i)
</code>```

An implementation using more important built-in functions is this:

```<code>for i in zip(range(len(seasons)), seasons):
    print(i)
</code>```

```<code>[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
</code>```

These two are the same, and we all know how critically important zip() and range() are. So why add a built-in function that would seemingly add no value beyond these two?

In the Python Docs, here is the equivalent of enumerate():

```<code>def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
</code>```

The bottom line: I'm wondering if enumerate() has some unique capabilities that I'm not seeing.

答:
Because not every iterable has a length.

```<code>>>> def countdown(x):
...     while x >= 0:
...         yield x
...         x -= 1
...
>>> down = countdown(3)
>>> len(down)
Traceback (most recent call last):
[...]
TypeError: object of type 'generator' has no len()
>>> enum = enumerate(down)
>>> next(enum)
(0, 3)
>>> next(enum)
(1, 2)
</code>```

This is a trivial example, of course. But I could think of lots of real world objects where you can't reasonably pre-compute a length. Either because the length is infinite (see itertools.count) or because the object you are iterating over does itself not know when the party is over.

Your iterator could be fetching chunks of data from a remote database of unknown size or to which the connection might get lost without warning. Or it could process user input.

```<code>def get_user_input():
     while True:
        i = input('input value or Q to quit: ')
        if i == 'Q':
            break
        yield i
</code>```

You cannot get the length of get_user_input(), but you can enumerate all inputs as you fetch them via next (or iteration).

Body:
Everything in Python is there for a reason. All systems powered by Python depend on something like 50 built-in functions, most of which are extremely useful and unique, like format(), len(), list(), or range(). I can't understand why enumerate() exists.

It's been introduced in PEP 279 (2002) and was kept until now. I really don't understand why it exists because it can be done using other more important built-in functions in 2-3 characters more. From the Python Docs:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

for i in enumerate(seasons):
    print(i)

An implementation using more important built-in functions is this:

for i in zip(range(len(seasons)), seasons):
    print(i)

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

These two are the same, and we all know how critically important zip() and range() are. So why add a built-in function that would seemingly add no value beyond these two?

In the Python Docs, here is the equivalent of enumerate():

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

The bottom line: I'm wondering if enumerate() has some unique capabilities that I'm not seeing.

Body:
Because not every iterable has a length.

>>> def countdown(x):
...     while x >= 0:
...         yield x
...         x -= 1
...
>>> down = countdown(3)
>>> len(down)
Traceback (most recent call last):
[...]
TypeError: object of type 'generator' has no len()
>>> enum = enumerate(down)
>>> next(enum)
(0, 3)
>>> next(enum)
(1, 2)

This is a trivial example, of course. But I could think of lots of real world objects where you can't reasonably pre-compute a length. Either because the length is infinite (see itertools.count) or because the object you are iterating over does itself not know when the party is over.

Your iterator could be fetching chunks of data from a remote database of unknown size or to which the connection might get lost without warning. Or it could process user input.

def get_user_input():
     while True:
        i = input('input value or Q to quit: ')
        if i == 'Q':
            break
        yield i

You cannot get the length of get_user_input(), but you can enumerate all inputs as you fetch them via next (or iteration).


来源: stackexchange

问:
C how to get input correctly
I'm trying to get a sentence and a letter from the user and for some reason it's not getting the letter
it's not doing the scanf the same with getcahr();

```<code>void main(){

    char str[100];
    char letter;
    printf("Enter a line: \n");
    scanf("%s", str);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("%c", letter);
}
</code>```

tried putting NULL in the letter no difference

答:
One possible reason could be it is taking the new line you get after pressing enter when you get the string.so we need to tell scanf to avoid new line character.try this put a blank space infront of %c this will tell scanf to ignore new line characters.
scanf(" %c",&letter)</p>

ContentLicense: CC BY-SA 4.0

Title: C how to get input correctly

Body:
I'm trying to get a sentence and a letter from the user and for some reason it's not getting the letter
it's not doing the scanf the same with getcahr();

void main(){

    char str[100];
    char letter;
    printf("Enter a line: \n");
    scanf("%s", str);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("%c", letter);
}

tried putting NULL in the letter no difference


问:
Easiest way to print the head of a data in python?
I'm not defining my array with pandas, I'm using numpy to do it and I would like to know if there is any other way to print the first 5 rows of a data. Using pandas this is how I would do it: print(data.head()).

This is how i defined my data:

```<code>with open('B0_25.txt', 'r') as simulation_data:
simulation_data = [x.strip() for x in simulation_data if x.strip()]

data = [tuple(map(float, x.split())) for x in simulation_data[2:100]]

x = [x[1] for x in data]
y = [x[2] for x in data]
z = [x[3] for x in data]
mx = [x[4] for x in data]
my = [x[5] for x in data]
mz = [x[6] for x in data]

mydata = np.array([x, y, z, mx, my, mz])
</code>```

答:
You need the transpose of mydata, otherwise x, y, z, mx, my, mz are the rows rather than the columns.</p>

```<code>mydata = np.array([x, y, z, mx, my, mz]).T
print(mydata[:5, :])
</code>```

Body:
I'm not defining my array with pandas, I'm using numpy to do it and I would like to know if there is any other way to print the first 5 rows of a data. Using pandas this is how I would do it: print(data.head()).

This is how i defined my data:

with open('B0_25.txt', 'r') as simulation_data:
simulation_data = [x.strip() for x in simulation_data if x.strip()]

data = [tuple(map(float, x.split())) for x in simulation_data[2:100]]

x = [x[1] for x in data]
y = [x[2] for x in data]
z = [x[3] for x in data]
mx = [x[4] for x in data]
my = [x[5] for x in data]
mz = [x[6] for x in data]

mydata = np.array([x, y, z, mx, my, mz])

Body:
You need the transpose of mydata, otherwise x, y, z, mx, my, mz are the rows rather than the columns.

mydata = np.array([x, y, z, mx, my, mz]).T
print(mydata[:5, :])


问:
Using Android to submit to a Google Spreadsheet Form
First time asking a question here. Usually I can find my answer without having to ask, but this time I'm stuck and can't figure out what I'm missing.

I'm just trying to have my Android app fill out a form on a website and submit it. I don't need the app to do anything with any data being sent back, just fill out the form and submit it. Basically I'm trying to collect the results of a voting app. I thought form submission would be simple so I created a Google Spreadsheet and made a form out of it. I figured I'd point the Android app to the form and then I would have all the data in the spreadsheet for later viewing. I can't get the Android app to actually fill out the form though. Here's the resources.

Form

Spreadsheet

```<code>private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        client.execute(post);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
}
</code>```

I made both the form and the spreadsheet public so feel free to mess around with it and try and get it to work yourself.

I get no errors from my program, no compile errors, no errors in DDMS. When I actually run the program and click the button that executes this code I can see the delay since right now this is in the UI thread, so I know it's executing it. It appears as if everything is working perfectly, but my spreadsheet doesn't update at all.

Any thoughts? I'm sure it's something stupid that I'm missing, but any help would be appreciated.

Here's the updated code with lots of logging and debugging stuff.

```<code>private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        HttpResponse httpResponse = client.execute(post);
        Log.e("RESPONSE", "info: " + httpResponse);

        BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String line;
        while ((line = rd.readLine()) != null) {
        Log.i("words", line);
        }

        Intent intent = new Intent(this, ReadingView.class);
        intent.putExtra("html", line);
        startActivity(intent);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "client protocol exception", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "io exception", e);
    }
}
</code>```

I use ReadingView.class for something else in my app, but hijacked it for this logging purpose right now. It only has an onCreate() method, which is below.

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.readingview);

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    //mWebView.loadUrl(getIntent().getExtras().getString("url"));
    mWebView.loadData(getIntent().getExtras().getString("html"), "text/html", "utf-8");
}
</code>```

Also worth noting that in the DDMS it only logs one output of line. I believe this is just because the html code is returned all as one line. Correct me if I'm wrong.

答: Have a look at the source for Acra. This uploads stack traces to a Google spreadsheet.</p>

ContentLicense: CC BY-SA 3.0

Body:
First time asking a question here. Usually I can find my answer without having to ask, but this time I'm stuck and can't figure out what I'm missing.

I'm just trying to have my Android app fill out a form on a website and submit it. I don't need the app to do anything with any data being sent back, just fill out the form and submit it. Basically I'm trying to collect the results of a voting app. I thought form submission would be simple so I created a Google Spreadsheet and made a form out of it. I figured I'd point the Android app to the form and then I would have all the data in the spreadsheet for later viewing. I can't get the Android app to actually fill out the form though. Here's the resources.

Form

Spreadsheet

private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        client.execute(post);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
}

I made both the form and the spreadsheet public so feel free to mess around with it and try and get it to work yourself.

I get no errors from my program, no compile errors, no errors in DDMS. When I actually run the program and click the button that executes this code I can see the delay since right now this is in the UI thread, so I know it's executing it. It appears as if everything is working perfectly, but my spreadsheet doesn't update at all.

Any thoughts? I'm sure it's something stupid that I'm missing, but any help would be appreciated.

Here's the updated code with lots of logging and debugging stuff.

private void submitVote(String outcome) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");

    List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
    results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
    results.add(new BasicNameValuePair("entry.1.single", outcome));
    results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));

    try {
        post.setEntity(new UrlEncodedFormEntity(results));
    } catch (UnsupportedEncodingException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "An error has occurred", e);
    }
    try {
        HttpResponse httpResponse = client.execute(post);
        Log.e("RESPONSE", "info: " + httpResponse);

        BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String line;
        while ((line = rd.readLine()) != null) {
        Log.i("words", line);
        }

        Intent intent = new Intent(this, ReadingView.class);
        intent.putExtra("html", line);
        startActivity(intent);
    } catch (ClientProtocolException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "client protocol exception", e);
    } catch (IOException e) {
        // Auto-generated catch block
        Log.e("YOUR_TAG", "io exception", e);
    }
}

I use ReadingView.class for something else in my app, but hijacked it for this logging purpose right now. It only has an onCreate() method, which is below.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.readingview);

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    //mWebView.loadUrl(getIntent().getExtras().getString("url"));
    mWebView.loadData(getIntent().getExtras().getString("html"), "text/html", "utf-8");
}

Also worth noting that in the DDMS it only logs one output of line. I believe this is just because the html code is returned all as one line. Correct me if I'm wrong.


问:
not able to get user input in javascript from html
I know that I should use document.getelemtbyID but for some reason it has not worked for me. I am trying to build a simple rock paper scissor game where I have a rock paper scissor class and one index.js, I have to pass the username as a function to my class but I am unable to get it working.

Here is my Javascript code -

const userName = document.getElementById(`username`).value;
```

<p>and then i pass it to the class -</p>

```let game=new RockPaperScissors(userName)
game.play(userName); (which is a function in the class)
```

<p>Here is my HTML for taking in username - </p>

```

           <form id="name-form">

                   Your name
                   <input type="text" id="username" class="form-control"
                          name="username" placeholder="Enter Name Here...">
                   <button type="button" id="start-game-button"
                           class="btn btn-primary">Start Game!</button>

           </form>
```

I tried several ways to be able to log in the username in my javascript but it's not working, I tried logging it in console and i still don't see a result.

答:
Here is the answer

About your above code : there is no pre-defined method of click event in the core javascript, so i have created one function in javascript and just called it on button onclick event.

your code is just got value of the textbox, but there is no event triggered, to get the value of textbox.

var name = "";
function getname() {
  name = document.getElementById(`username`).value;
  alert(name);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="welcome-screen">
    <form id="name-form">
      <div class="form-group">
        <label for="username">Your name</label>
        <input type="text" id="username" class="form-control" name="username" placeholder="Enter Name Here...">
        <button type="button" onclick="getname()" id="start-game-button" class="btn btn-primary">Start Game!</button>
      </div>
    </form></code>```

Body:
I know that I should use document.getelemtbyID but for some reason it has not worked for me. I am trying to build a simple rock paper scissor game where I have a rock paper scissor class and one index.js, I have to pass the username as a function to my class but I am unable to get it working.

Here is my Javascript code -

const userName = document.getElementById(`username`).value;

and then i pass it to the class -

let game=new RockPaperScissors(userName)
game.play(userName); (which is a function in the class)

Here is my HTML for taking in username -

           <form id="name-form">

                   Your name
                   <input type="text" id="username" class="form-control"
                          name="username" placeholder="Enter Name Here...">
                   <button type="button" id="start-game-button"
                           class="btn btn-primary">Start Game!</button>

           </form>

I tried several ways to be able to log in the username in my javascript but it's not working, I tried logging it in console and i still don't see a result.

Body:
Here is the answer

About your above code : there is no pre-defined method of click event in the core javascript, so i have created one function in javascript and just called it on button onclick event.

your code is just got value of the textbox, but there is no event triggered, to get the value of textbox.

var name = "";
function getname() {
  name = document.getElementById(`username`).value;
  alert(name);
}

<div id="welcome-screen">
    <form id="name-form">
      <div class="form-group">
        <label for="username">Your name</label>
        <input type="text" id="username" class="form-control" name="username" placeholder="Enter Name Here...">
        <button type="button" onclick="getname()" id="start-game-button" class="btn btn-primary">Start Game!</button>
      </div>
    </form>


问:
Track event to Google TagManager inside a ServiceWorker
I'm working on a service-worker (really a firebase cloud-messaging serviceworker like this) and I would like to track each time a user receives a push on Google TagManager.

Any help on how to include the script and send tracks within a SW?

Thanks.

答:
The Service worker runs outside the main thread and does not have
  access to the Window object, meaning that it cannot access the data
  layer or the ga command queue to create trackers. In short, the
  actions of a service worker cannot be tracked using the normal
  on-page, JavaScript-based tracking snippets. What we can do, however,
  is configure our service worker to send HTTP hits directly to GA.

Here is a sample code

```<code>fetch('https://www.google-analytics.com/collect', {
  method: 'post',
  body: JSON.stringify({
    v: 1, // Version Number
    t: eventName, // Hit Type
    ec: eventCategory, // Event Category
    ea: eventAction, // Event Action
    el: 'serviceworker' // Event Label
  })
})
</code>```

If you want to get into more details, I would recommend reading this article. https://builtvisible.com/google-analytics-for-pwas-tracking-offline-behaviour-and-more/

Body:
The Service worker runs outside the main thread and does not have
  access to the Window object, meaning that it cannot access the data
  layer or the ga command queue to create trackers. In short, the
  actions of a service worker cannot be tracked using the normal
  on-page, JavaScript-based tracking snippets. What we can do, however,
  is configure our service worker to send HTTP hits directly to GA.

Here is a sample code

fetch('https://www.google-analytics.com/collect', {
  method: 'post',
  body: JSON.stringify({
    v: 1, // Version Number
    t: eventName, // Hit Type
    ec: eventCategory, // Event Category
    ea: eventAction, // Event Action
    el: 'serviceworker' // Event Label
  })
})

If you want to get into more details, I would recommend reading this article. https://builtvisible.com/google-analytics-for-pwas-tracking-offline-behaviour-and-more/


问:
Can i save a screenshot taken from netbeans to Mysql
I am doing a project in which i decided to save screenshot of the bill to mysql database. But the ImageIcon used to take the screenshot does not provide the length of file so, the setBinaryStream() isn't working, i have tried pstmt.setBlob (1, (BLOB)icon), still not working.

Can you save the taken screenshot directly to database, if so please tell me.
Or can i create and save custom bills in netbeans.

```<code>try
{
    Rectangle screen = new Rectangle (Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture = new Robot().createScreenCapture(screen);
    ImageIcon icon = new ImageIcon(capture);
    int len = icon.getWidth();
    ImageIO.write(capture,"jpg",new File("screenshot.jpg"));

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Sign_up.class.getName()).log(Level.SEVERE, null, ex);
        }
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webapp","root","")) {
            Statement at = con.createStatement();
            String qt = "insert into picture (Pictures) values (?)";
            PreparedStatement pstmt = con.prepareStatement(qt);
            pstmt.setBinaryStream (icon,);

}
</code>```

答:
You can create a ByteArrayInputStream using the bytes of the screenshot, and then pass it to the prepared statement using setBinaryStream(int,InputStream) like this...

ps.setBinaryStream (1,new ByteArrayInputStream(baos.toByteArray()));

Here is a full program that takes a screenshot, writes it to a BLOB, and then reads it from the BLOB, and writes it to a file (for verification).

```<code>import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.imageio.ImageIO;

public class ScreenShot {

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            // Note: Don't pass passwords on the command line in real life.
            System.err.println("Usage: java ScreenShot <dbUrl> <dbUser> <dbPwd>");
            return;
        }
        // Capture the screenshot
        Rectangle screen = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage capture = new Robot().createScreenCapture(screen);

        // Write it to a ByteArrayOutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(capture, "jpg", baos);

        // Insert the bytes into the database
        Connection connection = DriverManager.getConnection(args[0], args[1], args[2]);
        String sql =  "insert into picture (Pictures) values (?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setBinaryStream (1,new ByteArrayInputStream(baos.toByteArray()));
        ps.execute();

        // Select the image from the database.
        sql = "select Pictures from picture where id = 1";
        ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery(sql);
        if (rs.next()) {
            InputStream input = rs.getBinaryStream(1);
            // Write the image to a file (for verification).
            FileOutputStream fos = new FileOutputStream("screenshot.jpg");
            byte[] buffer = new byte[1024];
            while (input.read(buffer) > 0) {
                fos.write(buffer);
            }
            input.close();
            fos.close();
        }
    }

}
</code>```

Note, this requires a table like below to exist in the default schema connected to.

```<code>CREATE TABLE test.picture (
    id int AUTO_INCREMENT ,
    Pictures MEDIUMBLOB,
PRIMARY KEY (id)
);
</code>```

Body:
I am doing a project in which i decided to save screenshot of the bill to mysql database. But the ImageIcon used to take the screenshot does not provide the length of file so, the setBinaryStream() isn't working, i have tried pstmt.setBlob (1, (BLOB)icon), still not working.

Can you save the taken screenshot directly to database, if so please tell me.
Or can i create and save custom bills in netbeans.

try
{
    Rectangle screen = new Rectangle (Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture = new Robot().createScreenCapture(screen);
    ImageIcon icon = new ImageIcon(capture);
    int len = icon.getWidth();
    ImageIO.write(capture,"jpg",new File("screenshot.jpg"));

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Sign_up.class.getName()).log(Level.SEVERE, null, ex);
        }
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webapp","root","")) {
            Statement at = con.createStatement();
            String qt = "insert into picture (Pictures) values (?)";
            PreparedStatement pstmt = con.prepareStatement(qt);
            pstmt.setBinaryStream (icon,);

}

Body:
You can create a ByteArrayInputStream using the bytes of the screenshot, and then pass it to the prepared statement using setBinaryStream(int,InputStream) like this...

ps.setBinaryStream (1,new ByteArrayInputStream(baos.toByteArray()));

Here is a full program that takes a screenshot, writes it to a BLOB, and then reads it from the BLOB, and writes it to a file (for verification).

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.imageio.ImageIO;

public class ScreenShot {

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            // Note: Don't pass passwords on the command line in real life.
            System.err.println("Usage: java ScreenShot <dbUrl> <dbUser> <dbPwd>");
            return;
        }
        // Capture the screenshot
        Rectangle screen = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage capture = new Robot().createScreenCapture(screen);

        // Write it to a ByteArrayOutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(capture, "jpg", baos);

        // Insert the bytes into the database
        Connection connection = DriverManager.getConnection(args[0], args[1], args[2]);
        String sql =  "insert into picture (Pictures) values (?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setBinaryStream (1,new ByteArrayInputStream(baos.toByteArray()));
        ps.execute();

        // Select the image from the database.
        sql = "select Pictures from picture where id = 1";
        ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery(sql);
        if (rs.next()) {
            InputStream input = rs.getBinaryStream(1);
            // Write the image to a file (for verification).
            FileOutputStream fos = new FileOutputStream("screenshot.jpg");
            byte[] buffer = new byte[1024];
            while (input.read(buffer) > 0) {
                fos.write(buffer);
            }
            input.close();
            fos.close();
        }
    }

}

Note, this requires a table like below to exist in the default schema connected to.

CREATE TABLE test.picture (
    id int AUTO_INCREMENT ,
    Pictures MEDIUMBLOB,
PRIMARY KEY (id)
);


问:
Using a struct as advanced enum type and attempting to access the properties by index
I followed this guide on making a more complicated enum type for my implementation.
http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

So far so good, however now I need to access the struct properties I have made ideally by index. A use case is if I get in a list of integers, I want to be able to provide a list of strings with the seasons in, e.g. {1,4,7} would get me {"Winter", "Spring", "Summer"} for example.

So in effect, using this example, I would like to be able to select Month where the index is 7 for example and get out the season of "Summer".

My first step was to get the names like so:

```<code>IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);
</code>```

I then attempted to get the particular Month with:

```<code>foreach(string name in names) {
  Month m = (Month) typeof(Month).GetType().GetProperties()
  .Single(info => info.Name == name)
  .GetValue(typeof(Month),null);
}
</code>```

however this is going to cause me to iterate over the entire collection for every value I want to get.

Ultimately I think I'm headed in the wrong direction and would really appreciate a pointer. At the moment I'm trying to do this in a method in another class, but don't see why it couldn't be a getter in the struct itself, although that may be complicated given the binding attributes in use.

答:
An alternate approach if you still wanted to use Enums for the months would be to create an extension class:

```<code>public enum Month
{
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12
}

public static class MonthExtensions
{
    private static readonly Dictionary<int, string> _seasons = new Dictionary<int, string>
    {
        {1, "Spring" },
        {2, "Summer" },
        {3, "Autumn" },
        {4, "Winter" }
    };

    private static readonly Dictionary<int, string> _names = new Dictionary<int, string>
    {
        {1,  "January"},
        {2,  "February"},
        {3,  "March"},
        {4,  "April"},
        {5,  "May"},
        {6,  "June"},
        {7,  "July"},
        {8,  "August"},
        {9,  "September"},
        {10, "October"},
        {11, "November"},
        {12, "December"}
    };

    private static readonly Dictionary<int, int> _seasonMap = new Dictionary<int, int>
    {
        {1,  4},
        {2,  4},
        {3,  1},
        {4,  1},
        {5,  1},
        {6,  2},
        {7,  2},
        {8,  2},
        {9,  3},
        {10, 3},
        {11, 3},
        {12, 4}
    };

    public static string GetSeason(int monthIndex)
        => ((Month)monthIndex).Season();

    public static IEnumerable<string> GetSeasons(IEnumerable<int> monthIndexes)
        => monthIndexes.Select(i => GetSeason(i));

    public static string Season(this Month month)
        => _seasons[_seasonMap[Index(month)]];

    public static int Index(this Month month)
        => (int)month;

    public static string Name(this Month month)
        => _names[Index(month)];
}
</code>```

Body:
I followed this guide on making a more complicated enum type for my implementation.
http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

So far so good, however now I need to access the struct properties I have made ideally by index. A use case is if I get in a list of integers, I want to be able to provide a list of strings with the seasons in, e.g. {1,4,7} would get me {"Winter", "Spring", "Summer"} for example.

So in effect, using this example, I would like to be able to select Month where the index is 7 for example and get out the season of "Summer".

My first step was to get the names like so:

IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);

I then attempted to get the particular Month with:

foreach(string name in names) {
  Month m = (Month) typeof(Month).GetType().GetProperties()
  .Single(info => info.Name == name)
  .GetValue(typeof(Month),null);
}

however this is going to cause me to iterate over the entire collection for every value I want to get.

Ultimately I think I'm headed in the wrong direction and would really appreciate a pointer. At the moment I'm trying to do this in a method in another class, but don't see why it couldn't be a getter in the struct itself, although that may be complicated given the binding attributes in use.

Body:
An alternate approach if you still wanted to use Enums for the months would be to create an extension class:

public enum Month
{
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12
}

public static class MonthExtensions
{
    private static readonly Dictionary<int, string> _seasons = new Dictionary<int, string>
    {
        {1, "Spring" },
        {2, "Summer" },
        {3, "Autumn" },
        {4, "Winter" }
    };

    private static readonly Dictionary<int, string> _names = new Dictionary<int, string>
    {
        {1,  "January"},
        {2,  "February"},
        {3,  "March"},
        {4,  "April"},
        {5,  "May"},
        {6,  "June"},
        {7,  "July"},
        {8,  "August"},
        {9,  "September"},
        {10, "October"},
        {11, "November"},
        {12, "December"}
    };

    private static readonly Dictionary<int, int> _seasonMap = new Dictionary<int, int>
    {
        {1,  4},
        {2,  4},
        {3,  1},
        {4,  1},
        {5,  1},
        {6,  2},
        {7,  2},
        {8,  2},
        {9,  3},
        {10, 3},
        {11, 3},
        {12, 4}
    };

    public static string GetSeason(int monthIndex)
        => ((Month)monthIndex).Season();

    public static IEnumerable<string> GetSeasons(IEnumerable<int> monthIndexes)
        => monthIndexes.Select(i => GetSeason(i));

    public static string Season(this Month month)
        => _seasons[_seasonMap[Index(month)]];

    public static int Index(this Month month)
        => (int)month;

    public static string Name(this Month month)
        => _names[Index(month)];
}


答:
The biggest issue I see is an Iterable is not necessarily finite. len does not make sense for every structure:

```<code>def infinite():
    n = 0
    while True:
        yield n
        n += 1

for i, n in enumerate(infinite()):
    print(i, n)
</code>```

It would not be possible to use your implementation to enumerate infinite.

If you used infinite (or itertools.count) as a substitute for range, it would work:

```<code>for i, n in zip(infinite(), seasons):
    print(i, n)
</code>```

But, unlike languages like Clojure, range cannot be infinite unfortunately. You must specify the end, which requires knowing the length ahead of time, which complicates things here.

Title: Is there more to enumerate() than just zip(range(len()))?

Body:
The biggest issue I see is an Iterable is not necessarily finite. len does not make sense for every structure:

def infinite():
    n = 0
    while True:
        yield n
        n += 1

for i, n in enumerate(infinite()):
    print(i, n)

It would not be possible to use your implementation to enumerate infinite.

If you used infinite (or itertools.count) as a substitute for range, it would work:

for i, n in zip(infinite(), seasons):
    print(i, n)

But, unlike languages like Clojure, range cannot be infinite unfortunately. You must specify the end, which requires knowing the length ahead of time, which complicates things here.


问:
c++ standard library header not recognized
I'm working on a multithreaded project in c++ and am trying to use a semaphore, from what I read in the documentation c++ has a semaphore, but when I try to include the header

#include <semaphore>

It does not autocomplete and I get a compiler error saying the header file is not recognized.

According to the documentation,

This header is part of the thread support library.

Does this mean I would need to add some prefix to the #include? Or include some other dependant header?  I can't figure out why this won't work and I can't find anything about this anywhere, any help would be appreciated.

I'm on a temporary machine and just installed visual studio on it a couple of days ago, so everything should be up to date.

答: As can be seen here, none of the listed compilers have currently implemented this c++20 feature.</p>


问:
"The uploaded file could not be moved to wp-content/uploads/2020/05."-when uploading a media, getting this error on wordpress
I have already tried changing the following to get this issue fixed but still didn't work:

changing permission to 777,755,744,766,644

change in wp-config.php

```<code>define('UPLOADS','wp-content/uploads');
require_once( ABSPATH . 'wp-settings.php' );
</code>```

Please Note: I don't have this option in media settings (settings > media)

Blockquote store uploads in this folder.

答:
You shouldn't have to define UPLOADS - WordPress knows where to find its upload directory, and changing the defaults may cause issues later, so start by removing the 'define...' line from your wp-config file.

On the server, I'm assuming you're on some kind of linux box (you don't specify), but the first thing to do is find out what user the server is running the Apache web process under.

```<code>ps aux | egrep '(apache|httpd)'
</code>```

This will list all running apache processes, and in the first column you should see the user - on mine, it's www-data. You may see some with root as the user, ignore those.

```<code>www-data 22052  1.0  3.3 482980 135680 ?       S    11:50   0:03 /usr/sbin/apache2 -k start
</code>```

Knowing the user now allows us to make sure that user has permissions to write to the WordPress directory as a whole - this includes making changes to the .htaccess files to update symlinks, as well as installing plugins, updates, and uploading files and media.

Navigate to the main wp-directory containing your wp-config.php file and run ls -l

You should see a list of all the files with the user and group associated with them, and their permission. Don't change permissions here. You should find most or all of the files have that same apache user (again, mine is www-data) as the owner of the files - the first column.

```<code>-rw-r--r--  1 www-data customuser  3168 Apr  3 13:58 wp-config.php
</code>```

Now we want to make sure every file and directory in the install is owned by this user, so that it can make changes based on the specific r/w privileges assigned. Make sure you're in your WordPress directory before doing this!

Replace 'www-data' here with whatever user you determined apache is running under from the previous step. 'www-data' is correct on my server, but it may be different on yours.

```<code>chown -R www-data *
</code>```

This changes the ownership [chown] recursively [-R], on the files in the directory, as well as any files and directories nested within the directory, to [www-data] the user we determined the web service is running under [*] to everything.

Test and see if that fixes the problem.

If not, navigate to the actual standard location of the uploads directory.

[your-wp-root-folder]/wp-content

run ls -l again

```<code> drwxr-xr-x 14 www-data www-data 4096 Apr  3 13:47 uploads
</code>```

The permissions are at the start - [drwxr-xr-x]

[d] - directory

[rwx] owner has read/write/execute - 7

[r-x] group has read/--/execute - 5

[r-x] everyone has read/--/execute - 5

So this would be 755 permissions

You can use chmod to change permissions here:

```<code>chmod -R 755 ./uploads
</code>```

[./uploads] the [.] means 'start in the current directory', the [/uploads] means 'affect the uploads directory'. [-R] as before makes the change recursively, so it will affect any files and directories contained within the uploads directory.

This should fix any permissions issues on the upload directory.

Body:
I have already tried changing the following to get this issue fixed but still didn't work:

changing permission to 777,755,744,766,644

change in wp-config.php

define('UPLOADS','wp-content/uploads');
require_once( ABSPATH . 'wp-settings.php' );

Please Note: I don't have this option in media settings (settings > media)

Blockquote store uploads in this folder.

Body:
You shouldn't have to define UPLOADS - WordPress knows where to find its upload directory, and changing the defaults may cause issues later, so start by removing the 'define...' line from your wp-config file.

On the server, I'm assuming you're on some kind of linux box (you don't specify), but the first thing to do is find out what user the server is running the Apache web process under.

ps aux | egrep '(apache|httpd)'

This will list all running apache processes, and in the first column you should see the user - on mine, it's www-data. You may see some with root as the user, ignore those.

www-data 22052  1.0  3.3 482980 135680 ?       S    11:50   0:03 /usr/sbin/apache2 -k start

Knowing the user now allows us to make sure that user has permissions to write to the WordPress directory as a whole - this includes making changes to the .htaccess files to update symlinks, as well as installing plugins, updates, and uploading files and media.

Navigate to the main wp-directory containing your wp-config.php file and run ls -l

You should see a list of all the files with the user and group associated with them, and their permission. Don't change permissions here. You should find most or all of the files have that same apache user (again, mine is www-data) as the owner of the files - the first column.

-rw-r--r--  1 www-data customuser  3168 Apr  3 13:58 wp-config.php

Now we want to make sure every file and directory in the install is owned by this user, so that it can make changes based on the specific r/w privileges assigned. Make sure you're in your WordPress directory before doing this!

Replace 'www-data' here with whatever user you determined apache is running under from the previous step. 'www-data' is correct on my server, but it may be different on yours.

chown -R www-data *

This changes the ownership [chown] recursively [-R], on the files in the directory, as well as any files and directories nested within the directory, to [www-data] the user we determined the web service is running under [*] to everything.

Test and see if that fixes the problem.

If not, navigate to the actual standard location of the uploads directory.

[your-wp-root-folder]/wp-content

run ls -l again

 drwxr-xr-x 14 www-data www-data 4096 Apr  3 13:47 uploads

The permissions are at the start - [drwxr-xr-x]

[d] - directory

[rwx] owner has read/write/execute - 7

[r-x] group has read/--/execute - 5

[r-x] everyone has read/--/execute - 5

So this would be 755 permissions

You can use chmod to change permissions here:

chmod -R 755 ./uploads

[./uploads] the [.] means 'start in the current directory', the [/uploads] means 'affect the uploads directory'. [-R] as before makes the change recursively, so it will affect any files and directories contained within the uploads directory.

This should fix any permissions issues on the upload directory.


问:
Problems connecting to Neptune from Lambda
I have created a simple AWS Neptune cluster, with a writer and no read replicas. I used the option to create a new VPC for it, and two security groups were automatically created for it, too.

I also have a Lambda that calls that Nepture cluster's endpoint. I have configured the Lambda with the Neptune cluster's VPC, specifying all of its subnets and the two security groups mentioned above. I didn't manually modified the inbound and outbound rules once they have been automatically assigned upon me performing the VPC configuration from the AWS Console (just going through the steps).

The Lambda is written in Python and uses the requests library to make HTTPS calls, with AWS Singature V4. The execution role for the Lambda has NeptuneFullAccess and an inline policy to allow configuring a VPC for the Lambda (which has been done, so that policy works).

The Lambda calls the Neptune cluster's endpoint, with the cluster's name and ID redacted, on port 8182:

```<code>https://NAME.cluster-ID.us-east-1.neptune.amazonaws.com:8182
</code>```

I get the following error:

```<code>{
  "errorMessage": "2020-05-20T21:26:35.066Z c8ee70ac-6390-48fd-a32e-36f80d58a24e Task timed out after 3.00 seconds"
}
</code>```

What am I doing wrong?

UPDATE: So, it looks like the second security group for the Neptune cluster was created by me selecting an option when creating the cluster. So, I tried again with Choose existing option for the security group, instead of Create new. (I guess I was confused before, because I was creating a whole new VPC, so how could a security group already exist? But the wizard just assumes the default security group that would be created by then.)

Now, I no longer get the same error. However, what I see is this:

```<code>{
  "errorType": "Runtime.ExitError",
  "errorMessage": "RequestId: 48e3b4fb-1b88-48d3-8834-247dbb1a4f3f Error: Runtime exited without providing a reason"
}
</code>```

The log shows this:

```<code>{
  "requestId": "b8b91c18-34cd-c5f6-9103-ed3357b9241e",
  "code": "BadRequestException",
  "detailedMessage": "Bad request."
}
</code>```

The query was (given the Lambda code described in https://docs.amazonaws.cn/en_us/neptune/latest/userguide/iam-auth-connecting-python.html):

```<code>{
  "host": "NAME.cluster-ID.us-east-1.neptune.amazonaws.com:8182",
  "method": "GET",
  "query_type": "status",
  "query": ""
}
</code>```

Any suggestions?

UPDATE: Trying against another Neptune cluster, the [Errno 111] Connection refused' error comes back. I have noticed an odd thing, however: I have some orphaned network interfaces, from when the Lambda was associated with the VPCs of now-deleted Neptune clusters. The network interfaces are marked in use, however, and I cannot detach and delete them, not even with the Force detachment option. Getting the You are not allowed to manage 'ela-attach' attachments error.

UPDATE: Starting with a fresh Lambda (no redoing its VPC configuration, and so no orphaned network interfaces anymore) and a fresh Neptune cluster with IAM Auth enabled and configured (and even with the Lambda's execution role given full admin access for the purposes of debugging, to eliminate any missing permissions), still getting this error:

```<code>{
  "errorMessage": "HTTPSConnectionPool(host='NAME.cluster-ID.us-east-1.neptune.amazonaws.com', port=8182): Max retries exceeded with url: /status/ (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f1f9f98c310>: Failed to establish a new connection: [Errno 111] Connection refused'))",
  "errorType": "ConnectionError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 71, in lambda_handler\n    return make_signed_request(host, method, query_type, query)\n",
    "  File \"/var/task/lambda_function.py\", line 264, in make_signed_request\n    r = requests.get(request_url, headers=headers, verify=False, params=request_parameters)\n",
    "  File \"/var/task/requests/api.py\", line 76, in get\n    return request('get', url, params=params, **kwargs)\n",
    "  File \"/var/task/requests/api.py\", line 61, in request\n    return session.request(method=method, url=url, **kwargs)\n",
    "  File \"/var/task/requests/sessions.py\", line 530, in request\n    resp = self.send(prep, **send_kwargs)\n",
    "  File \"/var/task/requests/sessions.py\", line 643, in send\n    r = adapter.send(request, **kwargs)\n",
    "  File \"/var/task/requests/adapters.py\", line 516, in send\n    raise ConnectionError(e, request=request)\n"
  ]
}
</code>```

答:
Thanks to the help of the Neptune team (an amazing response! they called me to discuss this), I was able to figure this out.

First, the Connection refused error disappeared once I redid the setup with a fresh Neptune cluster and the Use existing option for the security group, as well as a brand new Lambda added to the Neptune cluster's VPC. Apparently, redoing VPC configuration on a Lambda sometimes leaves orphaned network interfaces that are hard to delete. So, do the VPC config on a Lambda only once!

Second, the runtime error that started showing up after that is due to a bug in the Python code provided by AWS here: https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth-connecting-python.html

Namely, the make_signed_request function in that script doesn't return a value. It should return r.text or, better yet, json.loads(r.text). Then, everything works just fine.

Body:
I have created a simple AWS Neptune cluster, with a writer and no read replicas. I used the option to create a new VPC for it, and two security groups were automatically created for it, too.

I also have a Lambda that calls that Nepture cluster's endpoint. I have configured the Lambda with the Neptune cluster's VPC, specifying all of its subnets and the two security groups mentioned above. I didn't manually modified the inbound and outbound rules once they have been automatically assigned upon me performing the VPC configuration from the AWS Console (just going through the steps).

The Lambda is written in Python and uses the requests library to make HTTPS calls, with AWS Singature V4. The execution role for the Lambda has NeptuneFullAccess and an inline policy to allow configuring a VPC for the Lambda (which has been done, so that policy works).

The Lambda calls the Neptune cluster's endpoint, with the cluster's name and ID redacted, on port 8182:

https://NAME.cluster-ID.us-east-1.neptune.amazonaws.com:8182

I get the following error:

{
  "errorMessage": "2020-05-20T21:26:35.066Z c8ee70ac-6390-48fd-a32e-36f80d58a24e Task timed out after 3.00 seconds"
}

What am I doing wrong?

UPDATE: So, it looks like the second security group for the Neptune cluster was created by me selecting an option when creating the cluster. So, I tried again with Choose existing option for the security group, instead of Create new. (I guess I was confused before, because I was creating a whole new VPC, so how could a security group already exist? But the wizard just assumes the default security group that would be created by then.)

Now, I no longer get the same error. However, what I see is this:

{
  "errorType": "Runtime.ExitError",
  "errorMessage": "RequestId: 48e3b4fb-1b88-48d3-8834-247dbb1a4f3f Error: Runtime exited without providing a reason"
}

The log shows this:

{
  "requestId": "b8b91c18-34cd-c5f6-9103-ed3357b9241e",
  "code": "BadRequestException",
  "detailedMessage": "Bad request."
}

The query was (given the Lambda code described in https://docs.amazonaws.cn/en_us/neptune/latest/userguide/iam-auth-connecting-python.html):

{
  "host": "NAME.cluster-ID.us-east-1.neptune.amazonaws.com:8182",
  "method": "GET",
  "query_type": "status",
  "query": ""
}

Any suggestions?

UPDATE: Trying against another Neptune cluster, the [Errno 111] Connection refused' error comes back. I have noticed an odd thing, however: I have some orphaned network interfaces, from when the Lambda was associated with the VPCs of now-deleted Neptune clusters. The network interfaces are marked in use, however, and I cannot detach and delete them, not even with the Force detachment option. Getting the You are not allowed to manage 'ela-attach' attachments error.

UPDATE: Starting with a fresh Lambda (no redoing its VPC configuration, and so no orphaned network interfaces anymore) and a fresh Neptune cluster with IAM Auth enabled and configured (and even with the Lambda's execution role given full admin access for the purposes of debugging, to eliminate any missing permissions), still getting this error:

{
  "errorMessage": "HTTPSConnectionPool(host='NAME.cluster-ID.us-east-1.neptune.amazonaws.com', port=8182): Max retries exceeded with url: /status/ (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f1f9f98c310>: Failed to establish a new connection: [Errno 111] Connection refused'))",
  "errorType": "ConnectionError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 71, in lambda_handler\n    return make_signed_request(host, method, query_type, query)\n",
    "  File \"/var/task/lambda_function.py\", line 264, in make_signed_request\n    r = requests.get(request_url, headers=headers, verify=False, params=request_parameters)\n",
    "  File \"/var/task/requests/api.py\", line 76, in get\n    return request('get', url, params=params, **kwargs)\n",
    "  File \"/var/task/requests/api.py\", line 61, in request\n    return session.request(method=method, url=url, **kwargs)\n",
    "  File \"/var/task/requests/sessions.py\", line 530, in request\n    resp = self.send(prep, **send_kwargs)\n",
    "  File \"/var/task/requests/sessions.py\", line 643, in send\n    r = adapter.send(request, **kwargs)\n",
    "  File \"/var/task/requests/adapters.py\", line 516, in send\n    raise ConnectionError(e, request=request)\n"
  ]
}


问:
Flutter: Remove space between widgets
By using CustomPainter i have created a half circle.Now i have this widget tree:

```<code>return Scaffold(
  body: Center(
    child: SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            // card view
            height: 100,
            alignment: Alignment.center,
            margin: EdgeInsets.only(
                top: 20.0, bottom: 0.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              boxShadow: ([
                BoxShadow(
                  color: color_transparent_black,
                  spreadRadius: 5,
                  blurRadius: 3.0,
                  offset: Offset(2, 3),
                ),
              ]),
              borderRadius: BorderRadius.circular(14.0),
            ),),
            MyArc(diameter: 200),
</code>```

This is MyArc:

```<code>class MyArc extends StatelessWidget {
  final double diameter;

  const MyArc({Key key, this.diameter = 200}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: MyPainter(),
      size: Size(diameter, diameter),
    );
  }
}

// This is the Painter class
class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.blue;
    canvas.drawArc(
      Rect.fromCenter(
        center: Offset(size.height / 2, 0),
        height: size.height,
        width: size.width,
      ),
      6.4,
      2.9,
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
</code>```

But i got this problem:

I don't want any space between gray and blue shape!!!

答:
try changing the spreadRadius to 3.0
Its possible that it's creating a boundary greater than the container's Blur Radius boundary.

BoxShadow(
                  color: color_transparent_black,
                  spreadRadius: 5,
                  blurRadius: 3.0,
                  offset: Offset(2, 3),
                ),

Title: Flutter: Remove space between widgets

Body:
By using CustomPainter i have created a half circle.Now i have this widget tree:

return Scaffold(
  body: Center(
    child: SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            // card view
            height: 100,
            alignment: Alignment.center,
            margin: EdgeInsets.only(
                top: 20.0, bottom: 0.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              boxShadow: ([
                BoxShadow(
                  color: color_transparent_black,
                  spreadRadius: 5,
                  blurRadius: 3.0,
                  offset: Offset(2, 3),
                ),
              ]),
              borderRadius: BorderRadius.circular(14.0),
            ),),
            MyArc(diameter: 200),

This is MyArc:

class MyArc extends StatelessWidget {
  final double diameter;

  const MyArc({Key key, this.diameter = 200}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: MyPainter(),
      size: Size(diameter, diameter),
    );
  }
}

// This is the Painter class
class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.blue;
    canvas.drawArc(
      Rect.fromCenter(
        center: Offset(size.height / 2, 0),
        height: size.height,
        width: size.width,
      ),
      6.4,
      2.9,
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

But i got this problem:

I don't want any space between gray and blue shape!!!


问:
Is there a way to output a string from one excel cell to another?
I want to output a string from one cell into another cell. The string will always start with #0, and then there will be 4 to 7 characters following it. For example, for this cell:

```<code>UI-ESR25893-TA-03-0022 STEAMPLANT-#0009-R1 - Utility Tie-In Drawings-handled out of DRS - close
</code>```

I'd want to output "0009-R1" to the new cell.

答:
You can do this by using below formula where the example text resides in cell A1

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

where,

FIND("#0",A1,1) locates position where #0 exists and then we add 1 to it to get rid of #.

FIND(" ",A1,FIND("#0",A1,1)) locates the first space after #0 occurs

FIND(" ",A1,FIND("#0",A1,1))-FIND("#0",A1,1)-1 works out the exact length of the string.

Body:
I want to output a string from one cell into another cell. The string will always start with #0, and then there will be 4 to 7 characters following it. For example, for this cell:

UI-ESR25893-TA-03-0022 STEAMPLANT-#0009-R1 - Utility Tie-In Drawings-handled out of DRS - close

I'd want to output "0009-R1" to the new cell.


问:
How to define an embedding column in tensorflow 2.0?
I'm new to Tensorflow and I was following this tutorial using my csv data from local drive https://www.tensorflow.org/tutorials/structured_data/feature_columns, I could load the csv file and print column heads with

```<code>for feature_batch, label_batch in train_ds.take(1):
  print('Every feature:', list(feature_batch.keys()))
  print('A batch of traffic_type',label_batch)
</code>```

When I was trying to create an embedding feature column with

```<code>_mt_datetime_embedding = feature_column.embedding_column(_mt_datetime, dimension=8)
demo(_mt_datetime_embedding)
</code>```

This error showed up

AttributeError: 'EmbeddingColumn' object has no attribute 'num_buckets'.
I don't know what is wrong? Could someone please help me? Many thanks.

答:
According to Tensorflow documentation about Embedding columns:

Suppose instead of having just a few possible strings, we have
  thousands (or more) values per category. For a number of reasons, as
  the number of categories grow large, it becomes infeasible to train a
  neural network using one-hot encodings. We can use an embedding column
  to overcome this limitation. Instead of representing the data as a
  one-hot vector of many dimensions, an embedding column represents that
  data as a lower-dimensional, dense vector in which each cell can
  contain any number, not just 0 or 1.

Using an embedding column is best when a categorical column has many possible values.

Inputs for tf.feature_column.embedding_column must be a CategoricalColumn created by any of the categorical_column_* function

Syntax :

```<code>tf.feature_column.embedding_column(
    categorical_column, dimension, combiner='mean', initializer=None,
    ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True,
    use_safe_embedding_lookup=True
)
</code>```

When i have added input  as a numeric_column instead of categorical_column then received AttributeError: 'NumericColumn' object has no attribute 'num_buckets'

```<code>age_embedding = feature_column.embedding_column(age, dimension=8)
demo(age_embedding)
</code>```

Output:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-94a5fc74016e> in <module>()
      1 age_embedding = feature_column.embedding_column(age, dimension=8)
----> 2 demo(age_embedding)

4 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/feature_column/feature_column_v2.py in create_state(self, state_manager)
   3181     """Creates the embedding lookup variable."""
   3182     default_num_buckets = (self.categorical_column.num_buckets
-> 3183                            if self._is_v2_column
   3184                            else self.categorical_column._num_buckets)   # pylint: disable=protected-access
   3185     num_buckets = getattr(self.categorical_column, 'num_buckets',

AttributeError: 'NumericColumn' object has no attribute 'num_buckets'
</code>```

When i have added input as a categorical_column then it convert them to a dense representation. Here is the complete code.

```<code>import numpy as np
import pandas as pd

import tensorflow as tf

from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split

URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
dataframe = pd.read_csv(URL)

train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)
print(len(train), 'train examples')
print(len(val), 'validation examples')
print(len(test), 'test examples')

def df_to_dataset(dataframe, shuffle=True, batch_size=32):
  dataframe = dataframe.copy()
  labels = dataframe.pop('target')
  ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
  if shuffle:
    ds = ds.shuffle(buffer_size=len(dataframe))
  ds = ds.batch(batch_size)
  return ds

batch_size = 5 # A small batch sized is used for demonstration purposes
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)

example_batch = next(iter(train_ds))[0]

def demo(feature_column):
  feature_layer = layers.DenseFeatures(feature_column)
  print(feature_layer(example_batch).numpy())

age = feature_column.numeric_column("age")

thal = feature_column.categorical_column_with_vocabulary_list(
      'thal', ['fixed', 'normal', 'reversible'])

thal_embedding = feature_column.embedding_column(thal, dimension=8)
demo(thal_embedding)
</code>```

Output:

```<code>193 train examples
49 validation examples
61 test examples

[[-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]
 [-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]
 [-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]
 [ 0.3212179   0.29932576 -0.44579896 -0.4998746   0.064592    0.16934885
   0.02404759  0.5051637 ]
 [-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]]
</code>```

For more details please refer here

Body:
I'm new to Tensorflow and I was following this tutorial using my csv data from local drive https://www.tensorflow.org/tutorials/structured_data/feature_columns, I could load the csv file and print column heads with

for feature_batch, label_batch in train_ds.take(1):
  print('Every feature:', list(feature_batch.keys()))
  print('A batch of traffic_type',label_batch)

When I was trying to create an embedding feature column with

_mt_datetime_embedding = feature_column.embedding_column(_mt_datetime, dimension=8)
demo(_mt_datetime_embedding)

This error showed up

AttributeError: 'EmbeddingColumn' object has no attribute 'num_buckets'.
I don't know what is wrong? Could someone please help me? Many thanks.

Body:
According to Tensorflow documentation about Embedding columns:

Suppose instead of having just a few possible strings, we have
  thousands (or more) values per category. For a number of reasons, as
  the number of categories grow large, it becomes infeasible to train a
  neural network using one-hot encodings. We can use an embedding column
  to overcome this limitation. Instead of representing the data as a
  one-hot vector of many dimensions, an embedding column represents that
  data as a lower-dimensional, dense vector in which each cell can
  contain any number, not just 0 or 1.

Using an embedding column is best when a categorical column has many possible values.

Inputs for tf.feature_column.embedding_column must be a CategoricalColumn created by any of the categorical_column_* function

Syntax :

tf.feature_column.embedding_column(
    categorical_column, dimension, combiner='mean', initializer=None,
    ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True,
    use_safe_embedding_lookup=True
)

When i have added input  as a numeric_column instead of categorical_column then received AttributeError: 'NumericColumn' object has no attribute 'num_buckets'

age_embedding = feature_column.embedding_column(age, dimension=8)
demo(age_embedding)

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-94a5fc74016e> in <module>()
      1 age_embedding = feature_column.embedding_column(age, dimension=8)
----> 2 demo(age_embedding)

4 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/feature_column/feature_column_v2.py in create_state(self, state_manager)
   3181     """Creates the embedding lookup variable."""
   3182     default_num_buckets = (self.categorical_column.num_buckets
-> 3183                            if self._is_v2_column
   3184                            else self.categorical_column._num_buckets)   # pylint: disable=protected-access
   3185     num_buckets = getattr(self.categorical_column, 'num_buckets',

AttributeError: 'NumericColumn' object has no attribute 'num_buckets'

When i have added input as a categorical_column then it convert them to a dense representation. Here is the complete code.

import numpy as np
import pandas as pd

import tensorflow as tf

from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split

URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
dataframe = pd.read_csv(URL)

train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)
print(len(train), 'train examples')
print(len(val), 'validation examples')
print(len(test), 'test examples')

def df_to_dataset(dataframe, shuffle=True, batch_size=32):
  dataframe = dataframe.copy()
  labels = dataframe.pop('target')
  ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
  if shuffle:
    ds = ds.shuffle(buffer_size=len(dataframe))
  ds = ds.batch(batch_size)
  return ds

batch_size = 5 # A small batch sized is used for demonstration purposes
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)

example_batch = next(iter(train_ds))[0]

def demo(feature_column):
  feature_layer = layers.DenseFeatures(feature_column)
  print(feature_layer(example_batch).numpy())

age = feature_column.numeric_column("age")

thal = feature_column.categorical_column_with_vocabulary_list(
      'thal', ['fixed', 'normal', 'reversible'])

thal_embedding = feature_column.embedding_column(thal, dimension=8)
demo(thal_embedding)

Output:

193 train examples
49 validation examples
61 test examples

[[-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]
 [-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]
 [-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]
 [ 0.3212179   0.29932576 -0.44579896 -0.4998746   0.064592    0.16934885
   0.02404759  0.5051637 ]
 [-0.4675103   0.61985296  0.06297898  0.00818724  0.05449321 -0.6865342
  -0.05250816 -0.13339798]]

For more details please refer here


问:
Kotlin initialize array of arrays like python
Why cant i do something like that ?

```<code>var a=[[1, 0], [0, 1]]
</code>```

or at least

```<code>var a: Array<Array<Int>> = [[1, 0], [0, 1]]
</code>```

is it just impossible to do in kotlin?

答:
Kotlin is different language and has different array initialization for example you could use arrayOf and also primitive method like intArrayOf for integers

```<code>arrayOf(intArrayOf(1,0), intArrayOf(0,1))
</code>```

Body:
Why cant i do something like that ?

var a=[[1, 0], [0, 1]]

or at least

var a: Array<Array<Int>> = [[1, 0], [0, 1]]

is it just impossible to do in kotlin?

Body:
Kotlin is different language and has different array initialization for example you could use arrayOf and also primitive method like intArrayOf for integers

arrayOf(intArrayOf(1,0), intArrayOf(0,1))


问:
Calculate shortest route of subset of a graph
I am trying to calculate the shortest distance between a subset of this graph:

```<code>graph = {'a': {'b':10, 'c':3}, 'b':{'c':1, 'd':2}, 'c':{'b':4, 'd':8, 'e':2}, 'd':{'e':7}, 'e':{'d':9}}
</code>```

I am trying to use Dijkstra's algorithm, but I am not sure exactly how to convert it the above:

Current code:

```<code>graph = {'c1': {'c2':4, 'L1':3}, 'c2':{'c1':4, 'c3':3, 'L1':2.5}, 'c3':{'c2':3, 'L1':2}, 'L1':{'c1':3, 'c2':2.5, 'c3':2}}

def dijkstra(graph, start, goal):
    shortest_distance = {}
    predecessor = {}
    unseenNodes = {'c1': {'c2':4, 'L1':3}, 'c2':{'c1':4, 'c3':3, 'L1':2.5}, 'c3':{'c2':3, 'L1':2}, 'L1':{'c1':3, 'c2':2.5, 'c3':2}}
    infinity = float('inf')
    path = []

    for node in unseenNodes:
        shortest_distance[node] = infinity
    shortest_distance[start] = 0
    #print(shortest_distance)

    while unseenNodes:
        minNode = None
        for node in unseenNodes:
            if minNode is None:
                minNode = node
            elif shortest_distance[node] < shortest_distance[minNode]:
                minNode = node
        for childNode, weight in graph[minNode].items():
            if weight + shortest_distance[minNode] < shortest_distance[childNode]:
                shortest_distance[childNode] = weight + shortest_distance[minNode]
                predecessor[childNode] = minNode
        unseenNodes.pop(minNode)

    currentNode = goal
    while currentNode != start:
        try:
            path.insert(0, currentNode)
            currentNode = predecessor[currentNode]
        except KeyError:
            print('Path not reachable')
            break
    path.insert(0, start)

    if shortest_distance[goal] != infinity:
        print('Shortest distance: ' + str(shortest_distance[goal]))
        print('Path:' + str(path))

def multi_dijkstra(*args):
    # TODO: run dijkstra function for each: X
    # TODO: Add trip to 2nd (or3rd/4th) node back L1
    for args in args:
        dijkstra(graph, args, 'L1')
        dijkstra(graph, 'L1', args[])

    # print total cost

    # print total distance
    #print(args)

#dijkstra(graph, 'L1', 'c2')
#dijkstra(graph, 'c2', 'c3')
multi_dijkstra('c1', 'c2')

</code>```

The route can start at any point but has to finish at L1. For example c2(start) -> c1 -> L1 (finish).

答:
You can use the Python module NetworkX:</p>

```<code>from networkx import DiGraph
from networkx.algorithms.shortest_paths.generic import shortest_path

graph = {'c1': {'c2': 4, 'L1': 3},
         'c2': {'c1': 4, 'c3': 3, 'L1': 2.5},
         'c3': {'c2': 3, 'L1': 2},
         'L1': {'c1': 3, 'c2': 2.5, 'c3': 2}}

# Build the graph
G = DiGraph()
G.add_weighted_edges_from(((source, target, weight)
                           for source, d in graph.items()
                           for target, weight in d.items()))

# Find shortest path (using Dijkstra algorithm)
result = shortest_path(G, source='c1', target='c3', weight='weight')

# result: ['c1', 'L1', 'c3']
</code>```

Body:
I am trying to calculate the shortest distance between a subset of this graph:

graph = {'a': {'b':10, 'c':3}, 'b':{'c':1, 'd':2}, 'c':{'b':4, 'd':8, 'e':2}, 'd':{'e':7}, 'e':{'d':9}}

I am trying to use Dijkstra's algorithm, but I am not sure exactly how to convert it the above:

Current code:

graph = {'c1': {'c2':4, 'L1':3}, 'c2':{'c1':4, 'c3':3, 'L1':2.5}, 'c3':{'c2':3, 'L1':2}, 'L1':{'c1':3, 'c2':2.5, 'c3':2}}

def dijkstra(graph, start, goal):
    shortest_distance = {}
    predecessor = {}
    unseenNodes = {'c1': {'c2':4, 'L1':3}, 'c2':{'c1':4, 'c3':3, 'L1':2.5}, 'c3':{'c2':3, 'L1':2}, 'L1':{'c1':3, 'c2':2.5, 'c3':2}}
    infinity = float('inf')
    path = []

    for node in unseenNodes:
        shortest_distance[node] = infinity
    shortest_distance[start] = 0
    #print(shortest_distance)

    while unseenNodes:
        minNode = None
        for node in unseenNodes:
            if minNode is None:
                minNode = node
            elif shortest_distance[node] < shortest_distance[minNode]:
                minNode = node
        for childNode, weight in graph[minNode].items():
            if weight + shortest_distance[minNode] < shortest_distance[childNode]:
                shortest_distance[childNode] = weight + shortest_distance[minNode]
                predecessor[childNode] = minNode
        unseenNodes.pop(minNode)

    currentNode = goal
    while currentNode != start:
        try:
            path.insert(0, currentNode)
            currentNode = predecessor[currentNode]
        except KeyError:
            print('Path not reachable')
            break
    path.insert(0, start)

    if shortest_distance[goal] != infinity:
        print('Shortest distance: ' + str(shortest_distance[goal]))
        print('Path:' + str(path))

def multi_dijkstra(*args):
    # TODO: run dijkstra function for each: X
    # TODO: Add trip to 2nd (or3rd/4th) node back L1
    for args in args:
        dijkstra(graph, args, 'L1')
        dijkstra(graph, 'L1', args[])

    # print total cost

    # print total distance
    #print(args)

#dijkstra(graph, 'L1', 'c2')
#dijkstra(graph, 'c2', 'c3')
multi_dijkstra('c1', 'c2')

The route can start at any point but has to finish at L1. For example c2(start) -> c1 -> L1 (finish).

Body:
You can use the Python module NetworkX:

from networkx import DiGraph
from networkx.algorithms.shortest_paths.generic import shortest_path

graph = {'c1': {'c2': 4, 'L1': 3},
         'c2': {'c1': 4, 'c3': 3, 'L1': 2.5},
         'c3': {'c2': 3, 'L1': 2},
         'L1': {'c1': 3, 'c2': 2.5, 'c3': 2}}

# Build the graph
G = DiGraph()
G.add_weighted_edges_from(((source, target, weight)
                           for source, d in graph.items()
                           for target, weight in d.items()))

# Find shortest path (using Dijkstra algorithm)
result = shortest_path(G, source='c1', target='c3', weight='weight')

# result: ['c1', 'L1', 'c3']


问:
Is %matplot inline obsolete?
Based on my understanding from this question %matplotlib inline is used so figures can be shown in Jupyter. But figures are shown in Jupyter without using %matplotlib inline perfectly fine. for example the following code:

```<code>import numpy as np
import matplotlib.pyplot as plt

plt.plot(np.random.randn(50).cumsum())
plt.show()
</code>```

So is %matplotlib inline obsolete or am I misunderstanding it's purpose?

答:
The default matplotlib backend in a jupyter notebook is inline.  You can inspect this by using print(plt.get_backend()) after loading matplotlib.  For example:

import matplotlib.pyplot as plt
print(plt.get_backend())
```

<p>returns <code>module://ipykernel.pylab.backend_inline</code></p>

<p>The magic <code>%matplotlib</code> can be used to switch back to <code>inline</code> if you had switched to some other backend.  The following cells can illustrate this when run in a notebook.</p>

<p>In [100]:</p>

<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
plt.plot(np.random.randn(50).cumsum())
</code>```

In [101]:

%matplotlib notebook
plt.plot(np.random.randn(50).cumsum())
```

<p>In [103]:</p>

<pre class="lang-py prettyprint-override"><code>%matplotlib inline
plt.plot(np.random.randn(50).cumsum())
</code>```

Title: Is %matplot inline obsolete?

Body:
Based on my understanding from this question %matplotlib inline is used so figures can be shown in Jupyter. But figures are shown in Jupyter without using %matplotlib inline perfectly fine. for example the following code:

import numpy as np
import matplotlib.pyplot as plt

plt.plot(np.random.randn(50).cumsum())
plt.show()

So is %matplotlib inline obsolete or am I misunderstanding it's purpose?

Body:
The default matplotlib backend in a jupyter notebook is inline.  You can inspect this by using print(plt.get_backend()) after loading matplotlib.  For example:

import matplotlib.pyplot as plt
print(plt.get_backend())

returns module://ipykernel.pylab.backend_inline

The magic %matplotlib can be used to switch back to inline if you had switched to some other backend.  The following cells can illustrate this when run in a notebook.

In [100]:

import matplotlib.pyplot as plt
plt.plot(np.random.randn(50).cumsum())

In [101]:

%matplotlib notebook
plt.plot(np.random.randn(50).cumsum())

In [103]:

%matplotlib inline
plt.plot(np.random.randn(50).cumsum())


问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答: Python does have a Decimal class (in the decimal module), which you could use to avoid the imprecision of floats.

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.


问:
How to Fix: TypeError: Super expression must either be null or a function
Im making a little app and connecting it with an API to retrieve some info and show it. I had seen a way of doing it in a class and wanted to try it out, but it keeps giving the following error: "TypeError: Super expression must either be null or a function".

I did make the page in App.js, which I'm not sure might be a problem or not, since I wasnt sure how to load a component/screen on launch of the app. I changed the export default function App() to class App extends React.component to be able to use a state to save the data from the api.

I already tried changing export class ShowCustomerOrders extends React.Component to export class ShowCustomerOrders extends Component. But the result doesn't change.

```<code>import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

class App extends React.component {
  constructor(){
    super();
    this.state = {
      orders: []
    };
  }

  render(){
    getOrders();
  return (
      <View style={styles.container}>
          <Image style={styles.Map} source={{
              uri: 'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24'
          }}/>
          <FlatList data={this.state.orders}
          renderItem={({ item }) => <ShowCustomerOrders navigation={this.props.navigation} order={item}/>}/>
      </View>
    );
  }
}

function Map(){
  return(
    <Stack.Navigator>
      <Stack.Screen name="Map" component={MapScreen}/>
    </Stack.Navigator>
  );
}

getOrders = async() =>{
  const response =
    await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
  const data = await response.json();

  this.setState({
      orders: data.orders
  });
}

export class ShowCustomerOrders extends React.Component{
  render(){
    return(
      <TouchableOpacity onPress={() => this.props.Navigation.navigate('Map', {order:this.props.order})}>
        <Text> {this.props.order.naam} </Text>
        <Text> {this.props.order.adres} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%'
  }
});
</code>```

答:
Try with hooks...</p>

```<code>import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

function ShowCustomerOrders(props) {
  return (
    <TouchableOpacity
      onPress={() => props.navigation.navigate('Map', { order: props.order })}>
      <Text>{props.order.naam}</Text>
      <Text>{props.order.adres}</Text>
    </TouchableOpacity>
  );
}

function OrdersScreen(props) {
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    getOrders();
  }, []);

  const getOrders = async () => {
    const response = await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
    const data = await response.json();

    setOrders(data.orders);
  };

  return (
    <View style={styles.container}>
      <Image
        style={styles.Map}
        source={{
          uri:
            'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24',
        }}
      />
      <FlatList
        data={orders}
        renderItem={({ item }) => (
          <ShowCustomerOrders navigation={props.navigation} order={item} />
        )}
      />
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Orders" component={OrdersScreen} />
        <Stack.Screen name="Map" component={MapScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%',
  },
});
</code>```

Body:
Im making a little app and connecting it with an API to retrieve some info and show it. I had seen a way of doing it in a class and wanted to try it out, but it keeps giving the following error: "TypeError: Super expression must either be null or a function".

I did make the page in App.js, which I'm not sure might be a problem or not, since I wasnt sure how to load a component/screen on launch of the app. I changed the export default function App() to class App extends React.component to be able to use a state to save the data from the api.

I already tried changing export class ShowCustomerOrders extends React.Component to export class ShowCustomerOrders extends Component. But the result doesn't change.

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

class App extends React.component {
  constructor(){
    super();
    this.state = {
      orders: []
    };
  }

  render(){
    getOrders();
  return (
      <View style={styles.container}>
          <Image style={styles.Map} source={{
              uri: 'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24'
          }}/>
          <FlatList data={this.state.orders}
          renderItem={({ item }) => <ShowCustomerOrders navigation={this.props.navigation} order={item}/>}/>
      </View>
    );
  }
}

function Map(){
  return(
    <Stack.Navigator>
      <Stack.Screen name="Map" component={MapScreen}/>
    </Stack.Navigator>
  );
}

getOrders = async() =>{
  const response =
    await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
  const data = await response.json();

  this.setState({
      orders: data.orders
  });
}

export class ShowCustomerOrders extends React.Component{
  render(){
    return(
      <TouchableOpacity onPress={() => this.props.Navigation.navigate('Map', {order:this.props.order})}>
        <Text> {this.props.order.naam} </Text>
        <Text> {this.props.order.adres} </Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%'
  }
});

Body:
Try with hooks...

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import MapScreen from './components/MapScreen';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

const Stack = createStackNavigator();

function ShowCustomerOrders(props) {
  return (
    <TouchableOpacity
      onPress={() => props.navigation.navigate('Map', { order: props.order })}>
      <Text>{props.order.naam}</Text>
      <Text>{props.order.adres}</Text>
    </TouchableOpacity>
  );
}

function OrdersScreen(props) {
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    getOrders();
  }, []);

  const getOrders = async () => {
    const response = await fetch('https://api.summa.1ku.nl/mad/oefenexamen/');
    const data = await response.json();

    setOrders(data.orders);
  };

  return (
    <View style={styles.container}>
      <Image
        style={styles.Map}
        source={{
          uri:
            'https://open.mapquestapi.com/staticmap/v5/map?center=eindhoven,5611DE,kerkstraat+7&locations=eindhoven,5611DE,kerkstraat+7|marker-md-FF0000-M&size=@2x&key=lYrP4vF3Uk5zgTiGGuEzQGwGIVDGuy24',
        }}
      />
      <FlatList
        data={orders}
        renderItem={({ item }) => (
          <ShowCustomerOrders navigation={props.navigation} order={item} />
        )}
      />
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Orders" component={OrdersScreen} />
        <Stack.Screen name="Map" component={MapScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  Map: {
    width: '80%',
    height: '40%',
    bottom: '20%',
  },
});


问:
How can I get an item by a string key using web api?
I can't figure out how to hit an endpoint like "api/GetItems/AB123" (AB123 of course being a string) and have it return that item from my data set. I read the docs on the FindAsync() method and it seemed to indicate that it would accept a string by default. Is there something I need to do to 'id' before passing it into FindAsync()? My DB does not have a primary key, if that matters. (I can't change that either, this is legacy data and I have no control over schema)

My db doesn't have a PK ID field. I need to do the next best thing and target a unique string field.

My GET method:

```<code>        // GET: api/Items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(string id)
        {
            var item = await _context.Items.FindAsync(id); // Error happens here: "InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int64'."

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }
</code>```

Relevant from my model:

```<code>    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string ItemId { get; set; }

</code>```

答:
Hello and welcome to the Stack Overflow Community!!

Instead of find you could do .SingleAsync() like the below.
You could also do a .Where(x => x.ItemId == id).SingleAsync(). But this is up to you.

```<code>        // GET: api/Items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(string id)
        {
            var item = await _context.Items.SingleAsync(x => x.ItemId == id);

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }
</code>```

Body:
I can't figure out how to hit an endpoint like "api/GetItems/AB123" (AB123 of course being a string) and have it return that item from my data set. I read the docs on the FindAsync() method and it seemed to indicate that it would accept a string by default. Is there something I need to do to 'id' before passing it into FindAsync()? My DB does not have a primary key, if that matters. (I can't change that either, this is legacy data and I have no control over schema)

My db doesn't have a PK ID field. I need to do the next best thing and target a unique string field.

My GET method:

        // GET: api/Items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(string id)
        {
            var item = await _context.Items.FindAsync(id); // Error happens here: "InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int64'."

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }

Relevant from my model:

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string ItemId { get; set; }

Body:
Hello and welcome to the Stack Overflow Community!!

Instead of find you could do .SingleAsync() like the below.
You could also do a .Where(x => x.ItemId == id).SingleAsync(). But this is up to you.

        // GET: api/Items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(string id)
        {
            var item = await _context.Items.SingleAsync(x => x.ItemId == id);

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }