问:
How to show Valid or Invalid Snackbar when user enters the credential in Flutter?
When the user enter wrong credentials the snackbar should show Login Failed and when right page should show successfully logged in snackbar.
I have used firebase to authentication.

```<code>  final _formKey = GlobalKey<FormState>();
  TextEditingController _emailLoginFormTextEditingController = new TextEditingController();
  TextEditingController _passwordLoginFormTextEditingController = new TextEditingController();

  void initState() {
    super.initState();
  }

  _signInUsingFirebase(String email, String password) {
    FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    firebaseAuth.signInWithEmailAndPassword(email: email, password: password)
        .then((AuthResult authResult) {
      FirebaseUser user = authResult.user;
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(email: email, userid: user.uid,),
      ));
    }).catchError((error) {
      debugPrint(error);
    });
  }

  Widget _loginPageSaffoldBody(BuildContext context) {
    return Form(
      key: _formKey,
      child: ListView(
        padding: EdgeInsets.all(32),
        children: <Widget>[
          TextFormField(
            controller: _emailLoginFormTextEditingController,
          ),
          TextFormField(
            controller: _passwordLoginFormTextEditingController,
          ),
          RaisedButton(
            onPressed: () {
              // If statement is validating the input fields.
              if (_formKey.currentState.validate()) {
                _signInUsingFirebase(_emailLoginFormTextEditingController.text,
                    _passwordLoginFormTextEditingController.text);
                Scaffold.of(context).showSnackBar(                          //Snackbar for Succesfull
                  SnackBar(
                    content: Text(
                      "Succesfull",
                    ),
                  ),
                );
              }
              else{
                Scaffold.of(context).showSnackBar(                        //Snackbar for unsuccesfull
                  SnackBar(
                    content: Text(
                      "Unsuccesfull",
                    ),
                  ),
                );
              }
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Icon(
                  Icons.lock_open,
                ),
                SizedBox(width: 4),
                Text(
                  "Submit",
                ),
              ],
            ),
          ), // Submit Button
        ],
      ),
    );
  }
</code>```

A little out of context question I also want to keep user logged in once they enter the credentials till they login in i want to use shared preference but unable to understand how if u can provide any link might help
Thank You !

答:
For start, check the official documentation, where some basic examples provided by Google itself.

In your case, retrieve the response of the Firebase Login and push it to the separate service, which will create the needed snack bar.

For the saving login - yes, you can use shared_preferences and save two separate strings - one for login, one for the password. When initially logged in, save those, and when a user opens an app once again, first check shared_preferences for the case of needed data, and if it exists - just push it to function

Feel free to ask anything :3

Body:
When the user enter wrong credentials the snackbar should show Login Failed and when right page should show successfully logged in snackbar.
I have used firebase to authentication.

  final _formKey = GlobalKey<FormState>();
  TextEditingController _emailLoginFormTextEditingController = new TextEditingController();
  TextEditingController _passwordLoginFormTextEditingController = new TextEditingController();

  void initState() {
    super.initState();
  }

  _signInUsingFirebase(String email, String password) {
    FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    firebaseAuth.signInWithEmailAndPassword(email: email, password: password)
        .then((AuthResult authResult) {
      FirebaseUser user = authResult.user;
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(email: email, userid: user.uid,),
      ));
    }).catchError((error) {
      debugPrint(error);
    });
  }

  Widget _loginPageSaffoldBody(BuildContext context) {
    return Form(
      key: _formKey,
      child: ListView(
        padding: EdgeInsets.all(32),
        children: <Widget>[
          TextFormField(
            controller: _emailLoginFormTextEditingController,
          ),
          TextFormField(
            controller: _passwordLoginFormTextEditingController,
          ),
          RaisedButton(
            onPressed: () {
              // If statement is validating the input fields.
              if (_formKey.currentState.validate()) {
                _signInUsingFirebase(_emailLoginFormTextEditingController.text,
                    _passwordLoginFormTextEditingController.text);
                Scaffold.of(context).showSnackBar(                          //Snackbar for Succesfull
                  SnackBar(
                    content: Text(
                      "Succesfull",
                    ),
                  ),
                );
              }
              else{
                Scaffold.of(context).showSnackBar(                        //Snackbar for unsuccesfull
                  SnackBar(
                    content: Text(
                      "Unsuccesfull",
                    ),
                  ),
                );
              }
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Icon(
                  Icons.lock_open,
                ),
                SizedBox(width: 4),
                Text(
                  "Submit",
                ),
              ],
            ),
          ), // Submit Button
        ],
      ),
    );
  }

A little out of context question I also want to keep user logged in once they enter the credentials till they login in i want to use shared preference but unable to understand how if u can provide any link might help
Thank You !


来源: stackexchange

问:
Need help some with simple python find in strings
I'm a newbie coder and I need some help with the xxx.find usages...

Summary

I am doing a web automation project with selenium.
This python project's main goal is

Step 1. To login into my school's LMS website automatically with provided username and password

Step 2. Get the page_source of a given website URL which my school hosts all the assignment PDF files

Step 3. Do a matching search of PDF viewer links on the page_source string

Step 4. Navigate to the matching PDF viewer URL and get the page_source again

Step 5. Search for var DEFAULT_URL = '/icom/files/b729266c557f5f7108894ade1668d55a.pdf' or relevant links which is the link that my school server hosts the pdf file

Step 6. Get the value /icom/files/xxxxxx.pdf and combine with a header like www.icom.org.cn/ so they become www.icom.org.cn/icom/files/xxxx.pdf

Step 7. Then perform a wget command or something to get the pdf file.

The problem now

I somehow got the login automation correctly but now stuck at the page_source matching process but somehow stuck at Step 3

After getting onto the website URL where my school hosts all PDF assignment.

I ran a sauce = driver.pages_source and I am trying to match it by

```<code>word = ("/icom/faculty/viewer/?id")
print(sauce.find(word))
</code>```

But the output of the find is 5122

I would like that the str.find usage to match and list up all matching result and output the values in lines but not numbers...

So ... how can I do that? I searched up the internet for this but still isn't too informative to me. Sorry that I'm just a beginner in programming and I don't speak English too well. Thank you in advance.

By the way, a problem popped out in my mind.

If I was able to match up the value in Step 3. How can I code it to include extra value inside of the PDF viewer link?

Because the full link will be like this:

/icom/faculty/viewer/?id=1260&type=2 For English assignment

/icom/faculty/viewer/?id=1254&type=2 For Mathematics assignment

/icom/faculty/viewer/?id=775&type=2 For assignment covers etc

The extra value id=xxxx always will be different. So... how can I code it to match up and list out all matching result + extra value?

Any help would be appreciated! Thank you very much!

Exact example of the page_source

```<code>  </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=FP102-001&varSemester_code=1/20&prog_id=FIM')">FP102-001</a></td>
        <td valign="top" width="150">MUSIC PERFORMANCE LAB </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:abcder@icom.edu.my">fafafan@icom.edu.my</a>)        </td>
        <td valign="top" width="100" align="center">3 </td>
                <td valign="top" width="30" align="center">THU<br>      </td>
        <td valign="top" width="100" align="center">1:00PM<br>      </td>
        <td valign="top" width="100" align="center">3:30PM<br>      </td>
        <td valign="top" width="100" align="center">E2<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1126&type=1')">FP102-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=470&type=2')">FP102-Assignment 1 Brief.pdf</a><br />II <a href="#" onclick="return popup('/icom/faculty/viewer/?id=471&type=2')">FP102-Assignment 2 Brief.pdf</a><br />III <a href="#" onclick="return popup('/icom/faculty/viewer/?id=788&type=2')">FP102-Peer Assessment Sheet.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=GE030-001&varSemester_code=1/20&prog_id=FIM')">GE030-001</a></td>
        <td valign="top" width="150">ELECTRONICS & COMPUTER SYSTEMS </td>
        <td valign="top" width="100" align="center">ZHZ<br>(<a href="mailto:fafafer@gmail.com">abcdef@gmail.com</a>)        </td>
        <td valign="top" width="100" align="center">3 </td>
                <td valign="top" width="30" align="center">MON<br>WED<br>       </td>
        <td valign="top" width="100" align="center">7:30PM<br>      </td>
        <td valign="top" width="100" align="center">8:45PM<br>      </td>
        <td valign="top" width="100" align="center">C2<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1203&type=1')">GE030-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=474&type=2')">GE030-Assignment Brief.pdf</a><br />II <a href="#" onclick="return popup('/icom/faculty/viewer/?id=684&type=2')">GE030-Oral Presentation Brief.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=HM010-001&varSemester_code=1/20&prog_id=FIM')">HM010-001</a></td>
        <td valign="top" width="150">SURVEY OF POP MUSIC </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:abcdef@icom.edu.my">abcder@icom.edu.my</a>)     </td>
        <td valign="top" width="100" align="center">2 </td>
                <td valign="top" width="30" align="center">FRI<br>      </td>
        <td valign="top" width="100" align="center">11:00AM<br>     </td>
        <td valign="top" width="100" align="center">12:40PM<br>     </td>
        <td valign="top" width="100" align="center">RH<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1220&type=1')">HM010-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left"></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=MT010-001&varSemester_code=1/20&prog_id=FIM')">MT010-001</a></td>
        <td valign="top" width="150">MUSIC TECHNOLOGY & MIDI SYSTEMS </td>
        <td valign="top" width="100" align="center">SKS<br>(<a href="mailto:faer@icom.edu.my">sdferfs@icom.edu.my</a>)      </td>
        <td valign="top" width="100" align="center">2 </td>
                <td valign="top" width="30" align="center">TUE<br>THU<br>       </td>
        <td valign="top" width="100" align="center">12:00PM<br>     </td>
        <td valign="top" width="100" align="center">12:50PM<br>     </td>
        <td valign="top" width="100" align="center">C3<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1131&type=1')">MT010-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=776&type=2')">MT010-Project Brief.pdf</a><br />II <a href="#" onclick="return popup('/icom/faculty/viewer/?id=775&type=2')">MT010-Assignment Brief.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=PF011-001&varSemester_code=1/20&prog_id=FIM')">PF011-001</a></td>
        <td valign="top" width="150">PERFORMANCE SEMINAR </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:fafafa@icom.edu.my">fafafaf@icom.edu.my</a>)        </td>
        <td valign="top" width="100" align="center">0 </td>
                <td valign="top" width="30" align="center"><br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1208&type=1')">PF011-PF031-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left"></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=PI041-001&varSemester_code=1/20&prog_id=FIM')">PI041-001</a></td>
        <td valign="top" width="150">VOICE </td>
        <td valign="top" width="100" align="center">IBS<br>(<a href="mailto:fafafa@icom.edu.my">fafan@icom.edu.my</a>)      </td>
        <td valign="top" width="100" align="center">1 </td>
                <td valign="top" width="30" align="center"><br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br>     </td>
        <td valign="top" width="100" align="center">BY APPT<br></td>
                <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=1143&type=1')">PI041-FIM CS.pdf</a><br /></td>
                  <td valign="top" align="left">I <a href="#" onclick="return popup('/icom/faculty/viewer/?id=795&type=2')">PI0XX mark sheet.pdf</a><br /></td>
      </tr>
          <tr>
                <td valign="top" width="100"><a href="javascript:void(0)" onclick="return popup2('/icom/student/main/report?varCrs_ID=PL001-001&varSemester_code=1/20&prog_id=FIM')">PL001-001</a></td>
        <td valign="top" width="150">English Placement </td>
        <td valign="top" width="100" align="center">VNS<br>(<a href="mailto:xxx@gmail.com">abcder@gmail.com</a>)        </td>
        <td valign="top" width="100" align="center">0 </td>
                <td valign="top" width="30" align="center"><br>     </td>
        <td valign="top" width="100" align="center">-<br>       </td>
        <td valign="top" width="100" align="center">-<br>       </td>
        <td valign="top" width="100" align="center">-<br></td>
                <td valign="top" align="left"></td>
</code>```

答:
You could try to use regex pattern matching for python

```<code>import re
path = re.compile("/icom/faculty/viewer/.[a-z]{2}.*")
lst = path.findall(sauce)
print(lst)
</code>```

lst will be a list with all "/icom/faculty/viewer/?id" strings containing the mentioned match are followed by any character until a new line is encountered.
So...you should get a list of strings which match the string and the unique index=xxx values.

You can iterate over this list and separate further the into smaller lists for each assignment you want.

ContentLicense: CC BY-SA 4.0

Body:
I'm a newbie coder and I need some help with the xxx.find usages...

Summary

I am doing a web automation project with selenium.
This python project's main goal is

Step 1. To login into my school's LMS website automatically with provided username and password

Step 2. Get the page_source of a given website URL which my school hosts all the assignment PDF files

Step 3. Do a matching search of PDF viewer links on the page_source string

Step 4. Navigate to the matching PDF viewer URL and get the page_source again

Step 5. Search for var DEFAULT_URL = '/icom/files/b729266c557f5f7108894ade1668d55a.pdf' or relevant links which is the link that my school server hosts the pdf file

Step 6. Get the value /icom/files/xxxxxx.pdf and combine with a header like www.icom.org.cn/ so they become www.icom.org.cn/icom/files/xxxx.pdf

Step 7. Then perform a wget command or something to get the pdf file.

The problem now

I somehow got the login automation correctly but now stuck at the page_source matching process but somehow stuck at Step 3

After getting onto the website URL where my school hosts all PDF assignment.

I ran a sauce = driver.pages_source and I am trying to match it by

word = ("/icom/faculty/viewer/?id")
print(sauce.find(word))

But the output of the find is 5122

I would like that the str.find usage to match and list up all matching result and output the values in lines but not numbers...

So ... how can I do that? I searched up the internet for this but still isn't too informative to me. Sorry that I'm just a beginner in programming and I don't speak English too well. Thank you in advance.

By the way, a problem popped out in my mind.

If I was able to match up the value in Step 3. How can I code it to include extra value inside of the PDF viewer link?

Because the full link will be like this:

/icom/faculty/viewer/?id=1260&type=2 For English assignment

/icom/faculty/viewer/?id=1254&type=2 For Mathematics assignment

/icom/faculty/viewer/?id=775&type=2 For assignment covers etc

The extra value id=xxxx always will be different. So... how can I code it to match up and list out all matching result + extra value?

Any help would be appreciated! Thank you very much!

Exact example of the page_source

                FP102-001
        MUSIC PERFORMANCE LAB
        IBS
(fafafan@icom.edu.my)
        3
                THU

        1:00PM

        3:30PM

        E2

                I FP102-FIM CS.pdf

                  I FP102-Assignment 1 Brief.pdf
II FP102-Assignment 2 Brief.pdf
III FP102-Peer Assessment Sheet.pdf

                GE030-001
        ELECTRONICS & COMPUTER SYSTEMS
        ZHZ
(abcdef@gmail.com)
        3
                MON
WED

        7:30PM

        8:45PM

        C2

                I GE030-FIM CS.pdf

                  I GE030-Assignment Brief.pdf
II GE030-Oral Presentation Brief.pdf

                HM010-001
        SURVEY OF POP MUSIC
        IBS
(abcder@icom.edu.my)
        2
                FRI

        11:00AM

        12:40PM

        RH

                I HM010-FIM CS.pdf

                MT010-001
        MUSIC TECHNOLOGY & MIDI SYSTEMS
        SKS
(sdferfs@icom.edu.my)
        2
                TUE
THU

        12:00PM

        12:50PM

        C3

                I MT010-FIM CS.pdf

                  I MT010-Project Brief.pdf
II MT010-Assignment Brief.pdf

                PF011-001
        PERFORMANCE SEMINAR
        IBS
(fafafaf@icom.edu.my)
        0

        BY APPT

        BY APPT

        BY APPT

                I PF011-PF031-FIM CS.pdf

                PI041-001
        VOICE
        IBS
(fafan@icom.edu.my)
        1

        BY APPT

        BY APPT

        BY APPT

                I PI041-FIM CS.pdf

                  I PI0XX mark sheet.pdf

                PL001-001
        English Placement
        VNS
(abcder@gmail.com)
        0

        -

        -

        -

Body:
You could try to use regex pattern matching for python

import re
path = re.compile("/icom/faculty/viewer/.[a-z]{2}.*")
lst = path.findall(sauce)
print(lst)

lst will be a list with all "/icom/faculty/viewer/?id" strings containing the mentioned match are followed by any character until a new line is encountered.
So...you should get a list of strings which match the string and the unique index=xxx values.

You can iterate over this list and separate further the into smaller lists for each assignment you want.


问:
Managing Jekyll Pages in Folders (on github-pages)
I have a Jekyll website hosted on GitHub Pages. Now I am having so many pages and I would like to manage them in a folder called _pages. I ideally want to have this structure:

```<code>root
  |-> _pages
      |-> Index.md
      |-> contact.md
      |-> cv
          |-> cv.md
          |-> my_cv.pdf
  |-> _posts
  |-> [other things such as config and gemfile]
</code>```

This I have done defining default permalinks in the _config.yml adding:

```<code>include:
  - _pages

defaults:
  - scope:
      path: "_pages"
      type: "pages"
    values:
      permalink: /:basename/ # make URL of pages in the folder _pages as on the root.
</code>```

That works perfectly.

However, as you see inside the _pages I would like to have another subfolder named cv and put my cv.md and my_cv.pdf in the same folder (in the actual website I have much more of these files for pages.). Ultimately I would like to have a benefit of using [Download my CV](my_cv.pdf) relative local linking, which I suppose because the pdf and the .md file are in the same folder it will recognize it. However it is not the case. cv.md has the permalink of /cv/ and not the cv folder. So when I use [Download my CV](my_cv.pdf) it creates root/cv/my_cv.pdf where this pdf file actually does not exist!

How can I manage to fix this thing? what is your trick?

答:
Unless this is something you plan to roll-out to dozens of sub-directories or dozens of sites, I'd just add the full path to the link. Something like [Download my CV]({{ '/path/my_cv.pdf' | relative_url }}) or [Download my CV]({{ '/path/my_cv.pdf' | absolute_url }}).

Failing that, you could add permalink: /path/where/pdf/lives/ in the cv.md frontmatter. This way they'll both be in the same directory. Of course, this means your cv.md won't build at example.com/cv/.

Body:
I have a Jekyll website hosted on GitHub Pages. Now I am having so many pages and I would like to manage them in a folder called _pages. I ideally want to have this structure:

root
  |-> _pages
      |-> Index.md
      |-> contact.md
      |-> cv
          |-> cv.md
          |-> my_cv.pdf
  |-> _posts
  |-> [other things such as config and gemfile]

This I have done defining default permalinks in the _config.yml adding:

include:
  - _pages

defaults:
  - scope:
      path: "_pages"
      type: "pages"
    values:
      permalink: /:basename/ # make URL of pages in the folder _pages as on the root.

That works perfectly.

However, as you see inside the _pages I would like to have another subfolder named cv and put my cv.md and my_cv.pdf in the same folder (in the actual website I have much more of these files for pages.). Ultimately I would like to have a benefit of using [Download my CV](my_cv.pdf) relative local linking, which I suppose because the pdf and the .md file are in the same folder it will recognize it. However it is not the case. cv.md has the permalink of /cv/ and not the cv folder. So when I use [Download my CV](my_cv.pdf) it creates root/cv/my_cv.pdf where this pdf file actually does not exist!

How can I manage to fix this thing? what is your trick?


问:
Is mongoose's connect a version specific?
The part mongoose.connect is giving me problems. If I don't include useNewUrlParser: true, useUnifiedTopology: true, running the app.js in terminal will give me DeprecationWarning about including these parts. However if I do add them, running app.js does nothing. It just freezes forever.

//jshint esversion:6

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/", {
    useNewUrlParser: true, useUnifiedTopology: true
});

//Schema is scaffolding of date. For instance here's one for fruits.
const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

//This part is also required for upper one to work.
const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "I loved it."
});

fruit.save();```

答:
```<code>mongoose.connect("mongodb://localhost:27017/fruitsDB", {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log("DB Connection Error: ${err.message}");
});
</code>```


问:
This code is displaying code on window console but not on the textArea which I had used
Below is my code:

```<code>package Project1;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class DonorChat extends JFrame {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    String get=null;
    String s1=null;
    DataOutputStream dos;
    DataInputStream dis;
    JButton btnNewButton;
    private JPanel contentPane;
    public JTextField textField;
    public JTextArea textArea ;
    public JButton btnNewButton_1;
    public DonorChat() {
        setTitle("Donor Chat");
//        setIconImage(Toolkit.getDefaultToolkit().getImage("E:\\algorithm\\Project1\\Project1\\Blood.png"));
        setIconImage(Toolkit.getDefaultToolkit().getImage("E:\\algorithm\\Project1\\Project1\\Blood.png"));
        setForeground(Color.RED);
        setFont(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0, 0, 800, 1000);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textArea= new JTextArea();
        textArea.setFont(new Font("Tahoma", Font.BOLD, 17));
        textArea.setBounds(31, 222, 707, 522);
        contentPane.add(textArea);

        textField = new JTextField();
        textField.setFont(new Font("Tahoma", Font.BOLD, 17));
        textField.setBounds(31, 793, 510, 105);
        contentPane.add(textField);
        textField.setColumns(10);
        textField.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub

            }

        });

        btnNewButton = new JButton("Send\r\n");
        btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 17));
        btnNewButton.setForeground(Color.RED);
        btnNewButton.setBackground(Color.LIGHT_GRAY);
        btnNewButton.setBounds(602, 820, 125, 47);
        contentPane.add(btnNewButton);

        JScrollBar scrollBar = new JScrollBar();
        scrollBar.setBounds(717, 222, 21, 522);
        contentPane.add(scrollBar);

        btnNewButton_1 = new JButton("CONNECT TO SERVER");
        btnNewButton_1.setBackground(Color.RED);
        btnNewButton_1.setForeground(Color.DARK_GRAY);
        btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 29));
        btnNewButton_1.setBounds(31, 60, 707, 86);
        contentPane.add(btnNewButton_1);
        btnNewButton_1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                try {
                    ServerSocket ss=new ServerSocket(9995);
                    Socket snSocket=ss.accept();
                    dos=new DataOutputStream(snSocket.getOutputStream());
                    dis=new DataInputStream(snSocket.getInputStream());
                    getValue();
                    ss.close();
                }
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        setVisible(true);
    }
    public void getValue() throws IOException{
        btnNewButton.removeActionListener(null);
        while(true){
            s1=dis.readUTF();
            if (s1.equals("stop")){
                textArea.setText("Client Want to Stop:"+s1);
                break;
            }
            else{
                System.out.println("Client Says:"+s1);
                textArea.setText("Client Says:"+s1);
            }
            System.out.println("Type Something for Client");
            btnNewButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0){
                    try {
                        dos.writeUTF(get);
                    }
                    catch(Exception e){

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

I am building a window for server which needs a connection button to connect with the server socket, but after setting up the client for that server and after sending client a message, the message is showing on the console for eclipse but not on the textarea which what I actually wants to be

So please help me out by having a look at my code.

答:
Two problems:

Your while (true) loop is blocking the AWT event dispatch thread.

You are adding a listener in every iteration of your loop.

Holding up the event queue

AWT/Swing is single threaded.  When your “CONNECT TO SERVER” button’s ActionListener is called, it is called in the AWT event dispatch thread.  No other events will be processed until that method returns.

So when that ActionListener calls getValue(), and getValue() reads from a socket until "stop" is encountered, all processing of events is suspended.  Nothing gets repainted.  There will be no response to mouse or keyboard input, because the MouseEvents and KeyEvents are not processed.

You must perform I/O operations like reading from a socket on a different thread.  However, Swing methods must be executed in the AWT event dispatch thread.

One solution is to use the SwingWorker class, whose publish and process methods allow you to send multiple data elements from a background thread to the AWT even dispatch thread.

For sending to the socket, you can use a thread-safe BlockingQueue to store the lines to send, then use a loop in a different thread (not the AWT event dispatch thread) to obtain the text from that BlockingQueue and send it to the socket.

Add a listener only once

The method addActionListener actually adds a listener to a button.  All of the listeners you add will be called when the button is pressed.

So, if you call addActionListener every time your loop executes, you will have added a listener for each piece of data you read from the socket!

You should only add an ActionListener to a button once—usually right after you have created the button.

Code

So, if we move the I/O to other threads and use a BlockingQueue to keep track of lines to send, it looks something like this:

```<code>private final BlockingQueue<String> linesToSend =
    new LinkedBlockingDeque<>();

public DonorChat() {

    // ...

    textField.addActionListener(new ActionListener() {
        linesToSend.add(textField.getText());
    });

    btnNewButton.addActionListener(new ActionListener() {
        linesToSend.add(textField.getText());
    });

    // ...
}

private void getValue(Socket snSocket) {

    textArea.setText("");

    SwingWorker<Void, String> socketReader =
        new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground()
            throws IOException {

                // Runs in another thread.
                // No AWT/Swing calls allowed here!

                dis = new DataInputStream(snSocket.getInputStream());

                while (true) {
                    String s1 = dis.readUTF();
                    if (s1.equals("stop")) {
                        publish("Client wants to stop.");
                        break;
                    }

                    publish("Client says: " + s1);
                }

                snSocket.close();

                return null;
            }

            @Override
            protected void process(List<String> linesRead) {

                // Runs in event dispatch thread thread.
                // AWT/Swing calls only;  no I/O allowed here!

                for (String line : linesRead) {
                    textArea.append(line + "\n");
                }
            }
        };

    socketReader.execute();

    // Lines to send were added in AWT event dispatch thread
    // by ActionListeners.
    // We want to send them to the socket in a different thread.

    Runnable linesSender = new Runnable() {
        @Override
        public void run() {
            try {
                dos = new DataOutputStream(snSocket.getOutputStream());
                while (true) {
                    dos.writeUTF(linesToSend.take());
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    new Thread(linesSender).start();
}
</code>```

Some other important notes:

Never write an empty catch block.  Exceptions tell you what went wrong and where, which is very valuable information.  If you’re not sure what to put in a catch block, write e.printStackTrace(); so you can see the full details of the exception.

Learn to use layout managers.  A null layout will make things look okay on your computer, but will have problems on other computers, where the installed fonts are different and the fonts are rendered at different sizes.  (“17 points” means ¹⁷⁄₇₂ inch, which is rendered with more pixels on a 120 DPI monitor than on a 96 DPI monitor.)  Also, a null layout means you cannot resize the window to make the JTextArea and JTextField larger or smaller.

Body:
Below is my code:

package Project1;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class DonorChat extends JFrame {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    String get=null;
    String s1=null;
    DataOutputStream dos;
    DataInputStream dis;
    JButton btnNewButton;
    private JPanel contentPane;
    public JTextField textField;
    public JTextArea textArea ;
    public JButton btnNewButton_1;
    public DonorChat() {
        setTitle("Donor Chat");
//        setIconImage(Toolkit.getDefaultToolkit().getImage("E:\\algorithm\\Project1\\Project1\\Blood.png"));
        setIconImage(Toolkit.getDefaultToolkit().getImage("E:\\algorithm\\Project1\\Project1\\Blood.png"));
        setForeground(Color.RED);
        setFont(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0, 0, 800, 1000);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textArea= new JTextArea();
        textArea.setFont(new Font("Tahoma", Font.BOLD, 17));
        textArea.setBounds(31, 222, 707, 522);
        contentPane.add(textArea);

        textField = new JTextField();
        textField.setFont(new Font("Tahoma", Font.BOLD, 17));
        textField.setBounds(31, 793, 510, 105);
        contentPane.add(textField);
        textField.setColumns(10);
        textField.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub

            }

        });

        btnNewButton = new JButton("Send\r\n");
        btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 17));
        btnNewButton.setForeground(Color.RED);
        btnNewButton.setBackground(Color.LIGHT_GRAY);
        btnNewButton.setBounds(602, 820, 125, 47);
        contentPane.add(btnNewButton);

        JScrollBar scrollBar = new JScrollBar();
        scrollBar.setBounds(717, 222, 21, 522);
        contentPane.add(scrollBar);

        btnNewButton_1 = new JButton("CONNECT TO SERVER");
        btnNewButton_1.setBackground(Color.RED);
        btnNewButton_1.setForeground(Color.DARK_GRAY);
        btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 29));
        btnNewButton_1.setBounds(31, 60, 707, 86);
        contentPane.add(btnNewButton_1);
        btnNewButton_1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                try {
                    ServerSocket ss=new ServerSocket(9995);
                    Socket snSocket=ss.accept();
                    dos=new DataOutputStream(snSocket.getOutputStream());
                    dis=new DataInputStream(snSocket.getInputStream());
                    getValue();
                    ss.close();
                }
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        setVisible(true);
    }
    public void getValue() throws IOException{
        btnNewButton.removeActionListener(null);
        while(true){
            s1=dis.readUTF();
            if (s1.equals("stop")){
                textArea.setText("Client Want to Stop:"+s1);
                break;
            }
            else{
                System.out.println("Client Says:"+s1);
                textArea.setText("Client Says:"+s1);
            }
            System.out.println("Type Something for Client");
            btnNewButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0){
                    try {
                        dos.writeUTF(get);
                    }
                    catch(Exception e){

                    }
                }
            });
        }
    }
}

I am building a window for server which needs a connection button to connect with the server socket, but after setting up the client for that server and after sending client a message, the message is showing on the console for eclipse but not on the textarea which what I actually wants to be

So please help me out by having a look at my code.

Body:
Two problems:

Your while (true) loop is blocking the AWT event dispatch thread.

You are adding a listener in every iteration of your loop.

Holding up the event queue

AWT/Swing is single threaded.  When your “CONNECT TO SERVER” button’s ActionListener is called, it is called in the AWT event dispatch thread.  No other events will be processed until that method returns.

So when that ActionListener calls getValue(), and getValue() reads from a socket until "stop" is encountered, all processing of events is suspended.  Nothing gets repainted.  There will be no response to mouse or keyboard input, because the MouseEvents and KeyEvents are not processed.

You must perform I/O operations like reading from a socket on a different thread.  However, Swing methods must be executed in the AWT event dispatch thread.

One solution is to use the SwingWorker class, whose publish and process methods allow you to send multiple data elements from a background thread to the AWT even dispatch thread.

For sending to the socket, you can use a thread-safe BlockingQueue to store the lines to send, then use a loop in a different thread (not the AWT event dispatch thread) to obtain the text from that BlockingQueue and send it to the socket.

Add a listener only once

The method addActionListener actually adds a listener to a button.  All of the listeners you add will be called when the button is pressed.

So, if you call addActionListener every time your loop executes, you will have added a listener for each piece of data you read from the socket!

You should only add an ActionListener to a button once—usually right after you have created the button.

Code

So, if we move the I/O to other threads and use a BlockingQueue to keep track of lines to send, it looks something like this:

private final BlockingQueue<String> linesToSend =
    new LinkedBlockingDeque<>();

public DonorChat() {

    // ...

    textField.addActionListener(new ActionListener() {
        linesToSend.add(textField.getText());
    });

    btnNewButton.addActionListener(new ActionListener() {
        linesToSend.add(textField.getText());
    });

    // ...
}

private void getValue(Socket snSocket) {

    textArea.setText("");

    SwingWorker<Void, String> socketReader =
        new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground()
            throws IOException {

                // Runs in another thread.
                // No AWT/Swing calls allowed here!

                dis = new DataInputStream(snSocket.getInputStream());

                while (true) {
                    String s1 = dis.readUTF();
                    if (s1.equals("stop")) {
                        publish("Client wants to stop.");
                        break;
                    }

                    publish("Client says: " + s1);
                }

                snSocket.close();

                return null;
            }

            @Override
            protected void process(List<String> linesRead) {

                // Runs in event dispatch thread thread.
                // AWT/Swing calls only;  no I/O allowed here!

                for (String line : linesRead) {
                    textArea.append(line + "\n");
                }
            }
        };

    socketReader.execute();

    // Lines to send were added in AWT event dispatch thread
    // by ActionListeners.
    // We want to send them to the socket in a different thread.

    Runnable linesSender = new Runnable() {
        @Override
        public void run() {
            try {
                dos = new DataOutputStream(snSocket.getOutputStream());
                while (true) {
                    dos.writeUTF(linesToSend.take());
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    new Thread(linesSender).start();
}

Some other important notes:

Never write an empty catch block.  Exceptions tell you what went wrong and where, which is very valuable information.  If you’re not sure what to put in a catch block, write e.printStackTrace(); so you can see the full details of the exception.

Learn to use layout managers.  A null layout will make things look okay on your computer, but will have problems on other computers, where the installed fonts are different and the fonts are rendered at different sizes.  (“17 points” means ¹⁷⁄₇₂ inch, which is rendered with more pixels on a 120 DPI monitor than on a 96 DPI monitor.)  Also, a null layout means you cannot resize the window to make the JTextArea and JTextField larger or smaller.


问:
how to create a CSV in gcloud command?
I am currently trying to search a group of ebooks to learn more about C#. The aim is to ask a question get a page in one or multiple of the ebooks to read. I went to the g_suite chat team and they have kindly directed me to vision commands that was easy enough to follow to make multiple json files.
https://cloud.google.com/vision/docs/pdf
 I want to implement  this files in to AUTO ML Natural Language Processing. To do so, a CSV file is required.
I do not know how to create a CSV file that would get me past this point and I am currently stuck.
How to create a CSV file using gcloud command and should not the Json file be Jsonl file to be accepted?
thanks for your answer in advance </p>

答:
The output from the Vision API (service) is a JSON file written to Cloud Storage.

The input dataset to Auto ML expects the data to be in CSV format and stored in Cloud Storage.

This isn't a gcloud issue but a general data-transformation problem: transforming JSON to CSV.

Google Cloud includes services that could help you with this but I suggest you start by writing a script that converts the data (i.e. loads then parses the JSON file creating a CSV file in the required format for Auto ML).

You may want to Google to see whether others have done similar and use their code as a starting point.

NOTE IIUC your solution, while an interesting use of these technologies may be overkill. If you're looking to learn Vision API and Auto ML, great. If not, most of this content is available more directly as searchable HTML and text on the web and indeed Stack overflow exists to answer developer questions on a myriad of topics including C#.

Title: how to create a CSV in gcloud command?


问:
AWS Lambda: cannot import name '_imaging' from 'PIL'
I currently try to get this AWS Lambda Getting started tutorial running: https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-deployment-pkg.html#with-s3-example-deployment-pkg-python

However, I always receive an error:

```<code>{
  "errorMessage": "Unable to import module 'CreateThumbnail': cannot import name '_imaging' from 'PIL' (/var/task/PIL/__init__.py)",
  "errorType": "Runtime.ImportModuleError"
}
</code>```

Log output

```<code>START RequestId: fefba1d1-443c-4617-a5ad-c3aac19e5591 Version: $LATEST
[ERROR] Runtime.ImportModuleError: Unable to import module 'CreateThumbnail': cannot import name '_imaging' from 'PIL' (/var/task/PIL/__init__.py)
END RequestId: fefba1d1-443c-4617-a5ad-c3aac19e5591
REPORT RequestId: fefba1d1-443c-4617-a5ad-c3aac19e5591  Duration: 1.52 ms   Billed Duration: 100 ms     Memory Size: 1024 MB    Max Memory Used: 71 MB
</code>```

I went that far to build my .zip from a lambci/docker-lambda image. But it didn't resolve my problem.

Here what's inside my .zip. Do you have any ideas, why I still get this error?

答:
This is because PIL contains compiled binaries (cython) with your pip install and lambda doesn't know how to handle it.

Instead of creating a lambda function with docker and adding all unnecessary overhead, you can simply creating a zip file by using the following method:

Download the "module-name"-"version"-cp"python-version"-cp"python-versionm-manylinux1_x86_64.whl file from pypi.org. Note: In your case, it should be Pillow-7.1.2-cp37-cp37m-manylinux1_x86_64.whl

Unzip your whl file, by running unzip Pillow-7.1.2-cp37-cp37m-manylinux1_x86_64.whl

Adding all the files along with your lambda_function.py into a new zip file

Upload your new zip file to lambda and you're good to go.

This solution works well for any packages contain compiled binaries (cython) such as numpy.

Reference:
https://aws.amazon.com/premiumsupport/knowledge-center/lambda-python-package-compatible

Body:
I currently try to get this AWS Lambda Getting started tutorial running: https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-deployment-pkg.html#with-s3-example-deployment-pkg-python

However, I always receive an error:

{
  "errorMessage": "Unable to import module 'CreateThumbnail': cannot import name '_imaging' from 'PIL' (/var/task/PIL/__init__.py)",
  "errorType": "Runtime.ImportModuleError"
}

Log output

START RequestId: fefba1d1-443c-4617-a5ad-c3aac19e5591 Version: $LATEST
[ERROR] Runtime.ImportModuleError: Unable to import module 'CreateThumbnail': cannot import name '_imaging' from 'PIL' (/var/task/PIL/__init__.py)
END RequestId: fefba1d1-443c-4617-a5ad-c3aac19e5591
REPORT RequestId: fefba1d1-443c-4617-a5ad-c3aac19e5591  Duration: 1.52 ms   Billed Duration: 100 ms     Memory Size: 1024 MB    Max Memory Used: 71 MB

I went that far to build my .zip from a lambci/docker-lambda image. But it didn't resolve my problem.

Here what's inside my .zip. Do you have any ideas, why I still get this error?


问:
Spring Boot maven unit tests not being executed
I have a Spring Boot project. I have written unit tests in the .../src/test/java/... directories. All of my unit tests are of the form *Test.java. When I run 'mvn test', I get the following output:

```<code>[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ frm-api ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/JoelRives/Projects/fasor/fasor-service/fatality-review/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.0:test (default-test) @ frm-api ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
</code>```

Clearly, maven sees the unit tests as it is compiling them. However, as you can see, it does not run them.

I have the following relevant maven dependencies in my pom:

```<code>  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <version>1.5.3.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
      <version>1.4.194</version>
  </dependency>
</code>```

My pom also includes the following plugin:

```<code>       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.3.0-M1</version>
                </dependency>
                <dependency>
                <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.2.0-M1</version>
                </dependency>
            </dependencies>
        </plugin>
</code>```

Any help regarding this is greatly appreciated.

I did not show my entire POM. Here is the Junit stuff:

```<code><dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <version>1.5.3.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
      <version>1.4.194</version>
  </dependency>
</code>```

答:
For me, I had written this in my pom.xml and I was using JUnit4

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
```

Once I removed the exclusions, it started executing.

Body:
I have a Spring Boot project. I have written unit tests in the .../src/test/java/... directories. All of my unit tests are of the form *Test.java. When I run 'mvn test', I get the following output:

[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ frm-api ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/JoelRives/Projects/fasor/fasor-service/fatality-review/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.0:test (default-test) @ frm-api ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]

Clearly, maven sees the unit tests as it is compiling them. However, as you can see, it does not run them.

I have the following relevant maven dependencies in my pom:

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <version>1.5.3.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
      <version>1.4.194</version>
  </dependency>

My pom also includes the following plugin:

       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.3.0-M1</version>
                </dependency>
                <dependency>
                <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.2.0-M1</version>
                </dependency>
            </dependencies>
        </plugin>

Any help regarding this is greatly appreciated.

I did not show my entire POM. Here is the Junit stuff:

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <version>1.5.3.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
      <version>1.4.194</version>
  </dependency>

Body:
For me, I had written this in my pom.xml and I was using JUnit4

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

Once I removed the exclusions, it started executing.


问:
type mismatch errors when upgrading from scala 2.9 to 2.13.2
I recently revived an old library that was written in scala 2.9, and I created a new scala project using scala 2.13.2

I am getting errors like the following:

```<code>type mismatch;
found   : scala.collection.mutable.Buffer[Any]
[error]  required: Seq[Any]
</code>```

Was there a specific change between 2.9 to 2.13.2 that involved not implicitly casting sequences or something that might solve many of these types of compile errors?

I had to add .toSeq to many of my function return statements that were vals of Buffer[Any] that needed to be passed as an arguement to a function expected a Sequence.

答:
Quite a lot things happened in the last 7+ years (including rewrite of the collections library).

If adding .toSeq solves your problem - just go for it.

If you want to know what exactly has changed - try upgrading version-by version: first upgrade to scala-2.10., then to 2.11., then 2.12.*, then, finally, to 2.13.2.

At each upgrade you'll probably see deprecation warnings. Fix them before upgrading to the next version.

Body:
I recently revived an old library that was written in scala 2.9, and I created a new scala project using scala 2.13.2

I am getting errors like the following:

type mismatch;
found   : scala.collection.mutable.Buffer[Any]
[error]  required: Seq[Any]

Was there a specific change between 2.9 to 2.13.2 that involved not implicitly casting sequences or something that might solve many of these types of compile errors?

I had to add .toSeq to many of my function return statements that were vals of Buffer[Any] that needed to be passed as an arguement to a function expected a Sequence.


答:
Brave, but perhaps bad form, to disturb the dead. Nevertheless, maybe pass mutable.Buffer as mutable.Seq instead of Seq which is by default immutable.Seq. Consider

```<code>val mb = mutable.Buffer(11, Some(42))
val ms: mutable.Seq[Any] = mb // OK
val is: Seq[Any] = mb         // NOK
</code>```

Title: type mismatch errors when upgrading from scala 2.9 to 2.13.2

Body:
Brave, but perhaps bad form, to disturb the dead. Nevertheless, maybe pass mutable.Buffer as mutable.Seq instead of Seq which is by default immutable.Seq. Consider

val mb = mutable.Buffer(11, Some(42))
val ms: mutable.Seq[Any] = mb // OK
val is: Seq[Any] = mb         // NOK


问:
when i submit my form in case the information are wrong i would like to show only ONE error message under the input , how to do it there?
here eachtime i submit the form with empty fields it's adding a new span under each input , i would like to add one one when the input is false and removing it when it's ok (but keeping the others if the fields are empty)</p>

```<code>handleAddEventForm: function(event) {
        const addEventForm = event.currentTarget;
        let eventTitle = addEventForm.querySelector('#eventTitle]');
        let eventDate = addEventForm.querySelector('#eventDate]');
        let eventTime = addEventForm.querySelector('#eventTime]')
        let eventDescription = addEventForm.querySelector('#eventDescription]');
        let arrayToTest = {}
        arrayToTest.title = eventTitle;
        arrayToTest.date = eventDate;
        arrayToTest.time = eventTime;
        arrayToTest.description = eventDescription;
        arrayToTest.error = '';
        for (const key in arrayToTest) {
          if (arrayToTest[key].value !== '') {
            arrayToTest[key].style.border = "";
          } else {
            event.preventDefault();
            let errorSpan = document.createElement('span');
            let message = 'Ce champs est obligatoire'
            errorSpan.innerText = message ;
            errorSpan.className = "errorSpan";
            errorSpan.style.color = "red";
            arrayToTest[key].style.border = "3px solid red";
            arrayToTest[key].after(errorSpan);
          }
        }
      },
    };
</code>```

答:
Remove all errorSpan, before loop:</p>

```<code>handleAddEventForm: function(event) {
    const addEventForm = event.currentTarget;
    let eventTitle = addEventForm.querySelector('#eventTitle]');
    let eventDate = addEventForm.querySelector('#eventDate]');
    let eventTime = addEventForm.querySelector('#eventTime]')
    let eventDescription = addEventForm.querySelector('#eventDescription]');
    let arrayToTest = {}
    arrayToTest.title = eventTitle;
    arrayToTest.date = eventDate;
    arrayToTest.time = eventTime;
    arrayToTest.description = eventDescription;
    arrayToTest.error = '';
    var errorSpans = document.getElementsByClassName('errorSpan');
        while(errorSpans[0]) {
        errorSpans[0].parentNode.removeChild(errorSpans[0]);
    }
    for (const key in arrayToTest) {
      if (arrayToTest[key].value !== '') {
        arrayToTest[key].style.border = "";
      } else {
        event.preventDefault();
        let errorSpan = document.createElement('span');
        let message = 'Ce champs est obligatoire'
        errorSpan.innerText = message ;
        errorSpan.className = "errorSpan";
        errorSpan.style.color = "red";
        arrayToTest[key].style.border = "3px solid red";
        arrayToTest[key].after(errorSpan);
      }
    }
  },
};
</code>```

Body:
here eachtime i submit the form with empty fields it's adding a new span under each input , i would like to add one one when the input is false and removing it when it's ok (but keeping the others if the fields are empty)

handleAddEventForm: function(event) {
        const addEventForm = event.currentTarget;
        let eventTitle = addEventForm.querySelector('#eventTitle]');
        let eventDate = addEventForm.querySelector('#eventDate]');
        let eventTime = addEventForm.querySelector('#eventTime]')
        let eventDescription = addEventForm.querySelector('#eventDescription]');
        let arrayToTest = {}
        arrayToTest.title = eventTitle;
        arrayToTest.date = eventDate;
        arrayToTest.time = eventTime;
        arrayToTest.description = eventDescription;
        arrayToTest.error = '';
        for (const key in arrayToTest) {
          if (arrayToTest[key].value !== '') {
            arrayToTest[key].style.border = "";
          } else {
            event.preventDefault();
            let errorSpan = document.createElement('span');
            let message = 'Ce champs est obligatoire'
            errorSpan.innerText = message ;
            errorSpan.className = "errorSpan";
            errorSpan.style.color = "red";
            arrayToTest[key].style.border = "3px solid red";
            arrayToTest[key].after(errorSpan);
          }
        }
      },
    };

Body:
Remove all errorSpan, before loop:

handleAddEventForm: function(event) {
    const addEventForm = event.currentTarget;
    let eventTitle = addEventForm.querySelector('#eventTitle]');
    let eventDate = addEventForm.querySelector('#eventDate]');
    let eventTime = addEventForm.querySelector('#eventTime]')
    let eventDescription = addEventForm.querySelector('#eventDescription]');
    let arrayToTest = {}
    arrayToTest.title = eventTitle;
    arrayToTest.date = eventDate;
    arrayToTest.time = eventTime;
    arrayToTest.description = eventDescription;
    arrayToTest.error = '';
    var errorSpans = document.getElementsByClassName('errorSpan');
        while(errorSpans[0]) {
        errorSpans[0].parentNode.removeChild(errorSpans[0]);
    }
    for (const key in arrayToTest) {
      if (arrayToTest[key].value !== '') {
        arrayToTest[key].style.border = "";
      } else {
        event.preventDefault();
        let errorSpan = document.createElement('span');
        let message = 'Ce champs est obligatoire'
        errorSpan.innerText = message ;
        errorSpan.className = "errorSpan";
        errorSpan.style.color = "red";
        arrayToTest[key].style.border = "3px solid red";
        arrayToTest[key].after(errorSpan);
      }
    }
  },
};


问:
show/hide section in wordpress with select values
I use Divi Theme in Wordpress.
I have sections that I gave IDs.
I have a select, and for each option value I use the sections IDs.
I want show one section by changing the select option and hide the other section that is showed.

Here is the select :

```<code><select name="years" id="mySelect" onchange="myFunction()">
      <option value="">TOUTES LES ANNÉES </option>
      <option value="section2020">2020</option>
      <option value="section2019">2019</option>
      <option value="section2018">2018</option>
      <option value="section2017">2017</option>
      <option value="section2016">2016</option>
      <option value="section2015">2015</option>
</select>
</code>```

Here is the javascript :

```<code><script>
function myFunction() {
  var x = document.getElementById("mySelect").value;
  if (x.style === "display:none;") {
    x.style = "display:block";
  } else {
    x.style = "display:none;";
  }
}
</script>
</code>```

Could you tell my why it's not working ?

thanks
Caroline

答:
In your code, you are trying to style a string value x.style

If we see closely var x = document.getElementById("mySelect").value; this is returning a string value not an html element. But yes we can use this string value to get html element and make it visible and hide other.

  function myFunction() {
    var selectElement = document.getElementById("mySelect");
    var selectedValue = selectElement.value;
    var selectedElement = document.getElementById(selectedValue);

    if (selectedElement.style.display === "none") {
       var elements = document.getElementsByClassName('section');
       for(var i = 0; i < elements.length; i++){
       elements[i].style.display = "none";
       }
       selectedElement.style.display = "block";
    }
    else {
            selectedElement.style.display = "none";
         }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <select name="years" id="mySelect" onchange="myFunction()">
              <option value="">TOUTES LES ANNÉES </option>
              <option value="section2020">2020</option>
              <option value="section2019">2019</option>
              <option value="section2018">2018</option>
              <option value="section2017">2017</option>
              <option value="section2016">2016</option>
              <option value="section2015">2015</option>
        </select>

    <div id="section2020" class='section' style='display:none'><h1>2020</h1></div>
    <div id="section2019" class='section' style='display:none'><h1>2019</h1></div>
    <div id="section2018" class='section' style='display:none'><h1>2018</h1></div>
    <div id="section2017" class='section' style='display:none'><h1>2017</h1></div>
    <div id="section2016" class='section' style='display:none'><h1>2016</h1></div>
    <div id="section2015" class='section' style='display:none'><h1>2015</h1></div>

        </code>```

Body:
I use Divi Theme in Wordpress.
I have sections that I gave IDs.
I have a select, and for each option value I use the sections IDs.
I want show one section by changing the select option and hide the other section that is showed.

Here is the select :

<select name="years" id="mySelect" onchange="myFunction()">
      <option value="">TOUTES LES ANNÉES </option>
      <option value="section2020">2020</option>
      <option value="section2019">2019</option>
      <option value="section2018">2018</option>
      <option value="section2017">2017</option>
      <option value="section2016">2016</option>
      <option value="section2015">2015</option>
</select>

Here is the javascript :

Could you tell my why it's not working ?

thanks
Caroline

Body:
In your code, you are trying to style a string value x.style

If we see closely var x = document.getElementById("mySelect").value; this is returning a string value not an html element. But yes we can use this string value to get html element and make it visible and hide other.

  function myFunction() {
    var selectElement = document.getElementById("mySelect");
    var selectedValue = selectElement.value;
    var selectedElement = document.getElementById(selectedValue);

    if (selectedElement.style.display === "none") {
       var elements = document.getElementsByClassName('section');
       for(var i = 0; i < elements.length; i++){
       elements[i].style.display = "none";
       }
       selectedElement.style.display = "block";
    }
    else {
            selectedElement.style.display = "none";
         }
}

        <select name="years" id="mySelect" onchange="myFunction()">
              <option value="">TOUTES LES ANNÉES </option>
              <option value="section2020">2020</option>
              <option value="section2019">2019</option>
              <option value="section2018">2018</option>
              <option value="section2017">2017</option>
              <option value="section2016">2016</option>
              <option value="section2015">2015</option>
        </select>

    <div id="section2020" class='section' style='display:none'><h1>2020</h1></div>
    <div id="section2019" class='section' style='display:none'><h1>2019</h1></div>
    <div id="section2018" class='section' style='display:none'><h1>2018</h1></div>
    <div id="section2017" class='section' style='display:none'><h1>2017</h1></div>
    <div id="section2016" class='section' style='display:none'><h1>2016</h1></div>
    <div id="section2015" class='section' style='display:none'><h1>2015</h1></div>


问:
Extracting certain elements from array of each row for a specific column
I'm trying to extract values from array rows of a specific column with specified indices.

A dummy example, if I have a column called 'arr' in my dataframe where each array below is a row-

```<code>[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

[11, 12, 13, 14, 15]

[16, 17, 18, 19, 20]
</code>```

I've tried:

```<code>for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(df.arr)[i1]

    i2 = [2,3]
    r2 = np.array(df.arr)[i2]
</code>```

which gives the rows 0, 1 and 2 from the dataframe.

And I've tried:

```<code>for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(row.arr)[i1]

    i2 = [2,3]
    r2 = np.array(row.arr)[i2]
</code>```

which gives the values from only the last row. I don't understand why.

What I want to get are the indices specified in i1 and i2 as two different variables (r1 and r2) for each row. So-

r1 should give-

```<code>[1, 2, 3]

[6, 7, 8]

[11, 12, 13]

[16, 17, 18]
</code>```

And r2 should give-

```<code>[3, 4]

[8, 9]

[13, 14]

[18, 19]
</code>```

I've also used iterrows() with no luck.

答:
Try:

```<code>i1, i2 = [0,1,2],[2,3]
number_rows = 4
r1, r2 = np.zeros((number_rows,3)), np.zeros((number_rows,2))
for i in range(number_rows):
    r1[i] = np.array(df.arr)[i][i1]
    r2[i] = np.array(df.arr)[i][i2]
</code>```

The problem with your first attempt was, that if you give a 2D (like np.array(df.arr)) array only one index, it will return the whole row for each index.

In your second attempt, you actually get the results you want in each row, but you overwrite the results of former rows, so you only get the values of the last row.
You can fix this by inserting the results of each row into your result arrays, as done above.

Body:
I'm trying to extract values from array rows of a specific column with specified indices.

A dummy example, if I have a column called 'arr' in my dataframe where each array below is a row-

[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

[11, 12, 13, 14, 15]

[16, 17, 18, 19, 20]

I've tried:

for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(df.arr)[i1]

    i2 = [2,3]
    r2 = np.array(df.arr)[i2]

which gives the rows 0, 1 and 2 from the dataframe.

And I've tried:

for row in df.itertuples():
    i1 = [0,1,2]
    r1 = np.array(row.arr)[i1]

    i2 = [2,3]
    r2 = np.array(row.arr)[i2]

which gives the values from only the last row. I don't understand why.

What I want to get are the indices specified in i1 and i2 as two different variables (r1 and r2) for each row. So-

r1 should give-

[1, 2, 3]

[6, 7, 8]

[11, 12, 13]

[16, 17, 18]

And r2 should give-

[3, 4]

[8, 9]

[13, 14]

[18, 19]

I've also used iterrows() with no luck.

Body:
Try:

i1, i2 = [0,1,2],[2,3]
number_rows = 4
r1, r2 = np.zeros((number_rows,3)), np.zeros((number_rows,2))
for i in range(number_rows):
    r1[i] = np.array(df.arr)[i][i1]
    r2[i] = np.array(df.arr)[i][i2]

The problem with your first attempt was, that if you give a 2D (like np.array(df.arr)) array only one index, it will return the whole row for each index.

In your second attempt, you actually get the results you want in each row, but you overwrite the results of former rows, so you only get the values of the last row.
You can fix this by inserting the results of each row into your result arrays, as done above.


问:
How to convert my string '310519' to date object?
I have strings with dates in format '310519' ( it's 05/31/2019 ). How to convert my strings to date object?  new Date('310519') not working.

答:
Use a regex to reformat the string, then use new Date(s):

var s = "310519";
s = s.replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3');
console.log(new Date(s));```

With .replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3'), you reformat the groups of two digits, bascally, swap the first and second group and insert / separators. \d{2} matches any two digits, (...) creates capturing groups that are referenced to with the help of placeholders like $1, $2, $3 from the replacement part.

Body:
Use a regex to reformat the string, then use new Date(s):

var s = "310519";
s = s.replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3');
console.log(new Date(s));

With .replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3'), you reformat the groups of two digits, bascally, swap the first and second group and insert / separators. \d{2} matches any two digits, (...) creates capturing groups that are referenced to with the help of placeholders like $1, $2, $3 from the replacement part.


问:
How to delete dynamically allocated array in destructor in C++?
enter image description here

As you can see, the destructor complains "Use of undeclared identifier 'a'

Is my array out of scope? How can i delete it, when i call the destructor?

答:
a needs to be a data member of hashtable in order for this to work. Right now it is a variable local to the constructor, and the memory allocation is therefore leaked when the constructor terminates.

However, even if you correct this problem, beware the rule of five: if you implement any of the following you need to implement or delete all of them:

Destructor

Copy constructor

Copy-assignment operator

Move constructor

Move-assignment operator

If you do not, the compiler will generate them for you and it will get them wrong in this case.  Simply copying the pointer value to the new object is not enough; a new allocation needs to be made and the contents copied (except in the case of a move).  The compiler-generated versions will result in a use-after-free or double-delete.

You can avoid all of this by using std::vector<int> instead of trying to manage your own memory.


问:
How to get data from firebase query based on value from another firebase query in FutureBuilder in Flutter?
I am new to flutter and I am sure there is a simple way of doing this. Let me first give you a background. I have 2 tables(collections). The first one store a mapping. Therefore it returns a key based on an id which will be used to query the second table and retrieve the data from firebase.

I have written 2 data models and 2 functions which return Future<> data. They are as follows-

```<code>Future<SpecificDevice> getSpecificDevice(String deviceId) {
    Future<SpecificDevice> obj =_database.reference().child("deviceMapping").orderByChild("deviceId").equalTo(deviceId).once().then((snapshot) {
      SpecificDevice specificDevice = new SpecificDevice(deviceId, "XXXX", new List<String> ());
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        snapshot.value.forEach((key,values) {
          if(values["deviceId"] == deviceId) {
            specificDevice.deviceKey = values["deviceDesc"];
            specificDevice.vendorList = List.from(values["vendorList"]);
          }
        });
      }
      return specificDevice;
    });
    return obj;
  }
</code>```

This function gets the mapping deviceId -> deviceKey.
This is the key of record stored in another table. Following is the function for it.

```<code>Future<Device> getDeviceDescription(String deviceKey) {
    Future<Device> device = _database.reference().child("deviceDescription").once().then((snapshot) {
      Device deviceObj = new Device("YYYY", "YYYY", "YYY", "YYYY", "YYYY");
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        //Future<SpecificDevice> obj = getSpecificDevice(deviceId);
        //obj.then((value) {
          snapshot.value.forEach((key,values) {
            if(key == deviceKey) { // compare with value.deviceKey instead
              print(values["deviceDescription"]); // I get the correct data here.
              deviceObj.manual = values["deviceManual"];
              deviceObj.deviceType = values["deviceType"];
              deviceObj.description = values["deviceDescription"];
              deviceObj.brand = values["deviceBrand"];
              deviceObj.picture = values["devicePicture"];
            }
         // });
        });
      }
      return deviceObj;
    });
    return device;
  }
</code>```

Now both of these functions work. I want to make it work one after the other. In the above function, if I  uncomment the lines of code, the data is retrieved properly in the inner function but it returns initial default values set because the values get returned before setting the obj of SpecificDevice.

Here is where I am getting the error. I am calling the second function in FutureBuilder<> code with the above lines uncommented and taking input param as deviceId.

```<code>return FutureBuilder<Device>(
              future: getDeviceDescription(deviceId),
              builder:(BuildContext context,AsyncSnapshot snapshot){... // using snapshot.data in its child.
</code>```

Here in snapshot.data. would give me YYYY. But it should get me the value from the database.
I am stuck with this for a while. Any help in fixing this? or if what I am trying to do is clear then please suggest me a better way to approach this. Thanks in advance!

答:
Solved the problem by changing the calling function to -</p>

```<code>return FutureBuilder<Device>(
              future: getSpecificDevice(deviceId).then((value){
                return getDeviceDescription(value.deviceKey);
              }),
              builder:(BuildContext context,AsyncSnapshot snapshot){
</code>```

Body:
I am new to flutter and I am sure there is a simple way of doing this. Let me first give you a background. I have 2 tables(collections). The first one store a mapping. Therefore it returns a key based on an id which will be used to query the second table and retrieve the data from firebase.

I have written 2 data models and 2 functions which return Future<> data. They are as follows-

Future<SpecificDevice> getSpecificDevice(String deviceId) {
    Future<SpecificDevice> obj =_database.reference().child("deviceMapping").orderByChild("deviceId").equalTo(deviceId).once().then((snapshot) {
      SpecificDevice specificDevice = new SpecificDevice(deviceId, "XXXX", new List<String> ());
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        snapshot.value.forEach((key,values) {
          if(values["deviceId"] == deviceId) {
            specificDevice.deviceKey = values["deviceDesc"];
            specificDevice.vendorList = List.from(values["vendorList"]);
          }
        });
      }
      return specificDevice;
    });
    return obj;
  }

This function gets the mapping deviceId -> deviceKey.
This is the key of record stored in another table. Following is the function for it.

Future<Device> getDeviceDescription(String deviceKey) {
    Future<Device> device = _database.reference().child("deviceDescription").once().then((snapshot) {
      Device deviceObj = new Device("YYYY", "YYYY", "YYY", "YYYY", "YYYY");
      if(snapshot.value.isNotEmpty){
        print(snapshot.value);
        //Future<SpecificDevice> obj = getSpecificDevice(deviceId);
        //obj.then((value) {
          snapshot.value.forEach((key,values) {
            if(key == deviceKey) { // compare with value.deviceKey instead
              print(values["deviceDescription"]); // I get the correct data here.
              deviceObj.manual = values["deviceManual"];
              deviceObj.deviceType = values["deviceType"];
              deviceObj.description = values["deviceDescription"];
              deviceObj.brand = values["deviceBrand"];
              deviceObj.picture = values["devicePicture"];
            }
         // });
        });
      }
      return deviceObj;
    });
    return device;
  }

Now both of these functions work. I want to make it work one after the other. In the above function, if I  uncomment the lines of code, the data is retrieved properly in the inner function but it returns initial default values set because the values get returned before setting the obj of SpecificDevice.

Here is where I am getting the error. I am calling the second function in FutureBuilder<> code with the above lines uncommented and taking input param as deviceId.

return FutureBuilder<Device>(
              future: getDeviceDescription(deviceId),
              builder:(BuildContext context,AsyncSnapshot snapshot){... // using snapshot.data in its child.

Here in snapshot.data. would give me YYYY. But it should get me the value from the database.
I am stuck with this for a while. Any help in fixing this? or if what I am trying to do is clear then please suggest me a better way to approach this. Thanks in advance!

Body:
Solved the problem by changing the calling function to -

return FutureBuilder<Device>(
              future: getSpecificDevice(deviceId).then((value){
                return getDeviceDescription(value.deviceKey);
              }),
              builder:(BuildContext context,AsyncSnapshot snapshot){


问:
How to decrement items in array Incrementally based on the given quantity in Javascript
I have this sample array of objects

```<code>   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

```<code>   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

```<code>   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]
</code>```

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

```<code>var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})
</code>```

答:
```<code>let x = 8;

const newMangoes = mangoes.map((mango) => {
    if (!x) return mango;
    if (x <= mango.quantity) {
        newMango =  {quantity: mango.quantity - x};
        x = 0;
        return newMango;
    } else {
        x = x - mango.quantity;
        return {quantity: 0};
    }
});
</code>```

Body:
I have this sample array of objects

   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})


问:
Can a website perform OS level surveillance functions such as screen capture and packet sniffing?
I am wondering if a website (with or without Javascript) can perform surveillance such as OS screen capture, packet sniffing, etc? I am curious specifically about IOS, but I will gladly hear about other OS' as well.</p>

答:
No. At least not if everything works as intended or without the user's knowledge.

Browsers do their utmost to protect their users from harm. It would be a major issue if any website would immediately have access to the user's whole device.

Websites can make use of features such as the Screen Capture API, but this is only possible if the user gives the website permission to use it. Packet sniffing is definitely not something that a website should be able to do.

Unfortunately, in software engineering, you can never guarantee that your software is free of exploits.

But when severe vulnerabilities become publicly known, they will be patched, so as long as you install your updates, you should be relatively save.


问:
flutter - Call function on rotate
Is there any way to call a function after user rotates device? I need to hide the AppBar after the device is rotated.

I tried SystemChrome DeviceOrientation.portraip methots but it's not works automatically.

答:
You could try OrientationBuilder. It lets you rebuild its child Widgets on rotation.

```<code>OrientationBuilder(
  builder: (context, orientation) {
    return GridView.count(
      crossAxisCount: orientation == Orientation.portrait ? 3 : 4,
    );
  },
);
</code>```

Title: flutter - Call function on rotate

Body:
You could try OrientationBuilder. It lets you rebuild its child Widgets on rotation.

OrientationBuilder(
  builder: (context, orientation) {
    return GridView.count(
      crossAxisCount: orientation == Orientation.portrait ? 3 : 4,
    );
  },
);


问:
Mule 4 : Streams : How to check if payload is a Stream in Mule 4?
I am new to Mule 4 and have following understanding/doubts regarding streams. I will really appreciate the help.

When will mule 4 component generate a stream? For example, database select can return both array of objects and a single value. So will the return payload be stream in both cases?

How to check if the payload returned by a mule 4 component is a stream and if it is, how to analyze the stream meaning where are the files created in case of Repeatable file store stream and how much payload is already consumed as a stream?

For example, I create the below Mule 4 application that reads a CSV file having 1 milion records and do the following :

Read the CSV file [ Streaming Strategy : Repeatable file store stream, in memory size: 512 KB ]

Using a for each loop of batch size 10k

inside for each, a transform message to transform the csv row to a Json and a file write operation that will create files with name as per the dw code:

```<code>p('destination.dir')  ++ "Output_" ++ vars.counter ++ ".txt"
</code>```

100 files are generated each containing 10 k records. When checked, each file has size 913 KB.

Expected : For each will process n records where size of n records is 512 KB and process the (batchsize-n) in next iteration
Actual: For each processed 10000 records in each batch.
How did it happen?

Mule flow code:

```<code><?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:http="http://www.mulesoft.org/schema/mule/http"
    xmlns:file="http://www.mulesoft.org/schema/mule/file"
    xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
    xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">

    <file:config name="File_Config_1" doc:name="File Config" doc:id="565a1655-beba-4048-942f-ae68887e9b96" />
    <file:config name="File_Config" doc:name="File Config" doc:id="5182b61a-dddf-41c1-8d3c-6dbd895b5db7" />
    <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="f5bdb2ca-dc6f-4b6b-8407-8543bf7522e2" >
        <http:listener-connection host="0.0.0.0" port="8081" />
    </http:listener-config>
    <flow name="dw-streamingFlow">
        <http:listener doc:name="Listener" doc:id="78635a2a-959d-41e9-a294-3cc7bb22d36f" config-ref="HTTP_Listener_config" path="/app/fileStream"/>
        <file:read path="C:\Users\bbazazx\Documents\TestFolder\InputDirectory\input.csv"
            config-ref="File_Config"
            outputMimeType="application/csv; streaming=true; header=true" />
        <foreach doc:name="For Each" doc:id="eacd49dc-c49f-437a-927e-976add7e57fc" batchSize="500" collection="payload">
            <ee:transform doc:name="Transform Message" doc:id="bec02dd1-4c15-47c0-81cf-a7d0bfd64b39">
            <ee:message>
                <ee:set-payload><![CDATA[%dw 2.0
output application/json
---
payload map(item,index) -> {
    "Country" : item."Country",
    "FoodItems" : item."Item Type"
}]]></ee:set-payload>
            </ee:message>
        </ee:transform>
            <file:write doc:name="Write" config-ref="File_Config_1" path='#["C:\\Users\\bbazazx\\Documents\\TestFolder\\OutputDirectory\\output" ++ vars.counter ++ ".json"]' />
            <logger level="INFO" doc:name="Logger" message="#[payload]" />
        </foreach>

</flow>

</mule>

</code>```

答:
It depends on each connector. Most of the connectors in Mule 4 allow streaming, and many allow to configure the streaming strategy. See https://docs.mulesoft.com/mule-runtime/4.3/streaming-about for details.

It maybe the case that the DB connectors returns an array enclosed into a stream. Mule will understand it and process it as an array transparently.

You can see in the debugger if the class of the payload is a kind of stream or iterable or a managed cursor. That seems to be an indication of streaming.

The 512 KB mentioned is the size of the buffer. For the file stored repeatable stream strategy the documentation links above explains it:

This strategy initially uses an in-memory buffer size of 512 KB. For
  larger streams, the strategy creates a temporary file to the disk to
  store the contents, without overflowing your memory.

Body:
I am new to Mule 4 and have following understanding/doubts regarding streams. I will really appreciate the help.

When will mule 4 component generate a stream? For example, database select can return both array of objects and a single value. So will the return payload be stream in both cases?

How to check if the payload returned by a mule 4 component is a stream and if it is, how to analyze the stream meaning where are the files created in case of Repeatable file store stream and how much payload is already consumed as a stream?

For example, I create the below Mule 4 application that reads a CSV file having 1 milion records and do the following :

Read the CSV file [ Streaming Strategy : Repeatable file store stream, in memory size: 512 KB ]

Using a for each loop of batch size 10k

inside for each, a transform message to transform the csv row to a Json and a file write operation that will create files with name as per the dw code:

p('destination.dir')  ++ "Output_" ++ vars.counter ++ ".txt"

100 files are generated each containing 10 k records. When checked, each file has size 913 KB.

Expected : For each will process n records where size of n records is 512 KB and process the (batchsize-n) in next iteration
Actual: For each processed 10000 records in each batch.
How did it happen?

Mule flow code:

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:http="http://www.mulesoft.org/schema/mule/http"
    xmlns:file="http://www.mulesoft.org/schema/mule/file"
    xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
    xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">

    <file:config name="File_Config_1" doc:name="File Config" doc:id="565a1655-beba-4048-942f-ae68887e9b96" />
    <file:config name="File_Config" doc:name="File Config" doc:id="5182b61a-dddf-41c1-8d3c-6dbd895b5db7" />
    <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="f5bdb2ca-dc6f-4b6b-8407-8543bf7522e2" >
        <http:listener-connection host="0.0.0.0" port="8081" />
    </http:listener-config>
    <flow name="dw-streamingFlow">
        <http:listener doc:name="Listener" doc:id="78635a2a-959d-41e9-a294-3cc7bb22d36f" config-ref="HTTP_Listener_config" path="/app/fileStream"/>
        <file:read path="C:\Users\bbazazx\Documents\TestFolder\InputDirectory\input.csv"
            config-ref="File_Config"
            outputMimeType="application/csv; streaming=true; header=true" />
        <foreach doc:name="For Each" doc:id="eacd49dc-c49f-437a-927e-976add7e57fc" batchSize="500" collection="payload">
            <ee:transform doc:name="Transform Message" doc:id="bec02dd1-4c15-47c0-81cf-a7d0bfd64b39">
            <ee:message>
                <ee:set-payload><![CDATA[%dw 2.0
output application/json
---
payload map(item,index) -> {
    "Country" : item."Country",
    "FoodItems" : item."Item Type"
}]]></ee:set-payload>
            </ee:message>
        </ee:transform>
            <file:write doc:name="Write" config-ref="File_Config_1" path='#["C:\\Users\\bbazazx\\Documents\\TestFolder\\OutputDirectory\\output" ++ vars.counter ++ ".json"]' />
            <logger level="INFO" doc:name="Logger" message="#[payload]" />
        </foreach>

</flow>

</mule>