问:
How to get Java Frame object to use in Reset method?
I am making a Tic-Tac-Toe game in Java. I have four classes:
TicTacTester just calls (creates an object) the TicTacToe class.
The TicTacToe class provides the GUI of the game (it's a subclass of JFrame). It also creates the 9 buttons for the JPanel to display and users to click.
The XOButton class defines what the buttons can do and actionPerformed method.
Lastly, the GameEnd class defines what happens when the game ends (a new JFrame is created to display score and give the user 2 buttons: exit and restart).

The problem is when I try to code the contents of what happens when the user clicks "restart". It is suppose to call the resetBoard() method, which is defined in TicTacToe class. The problem is, I do not know the name of the object created from the TicTacToe class (in the tester class' static void main method I just typed "new TicTacToe", didn't need to define a name). I cannot call resetBoard from a static standpoint (i.e. I can't do TicTacToe.resetBoard(); ) because resetBoard needs to be non-static.

What I've tried:
I've tried including in the constructor of the GameEnd class a TicTacToe object. If I do this, the GameEnd object creator has to go into TicTacToe class, so I can use 'this' keyword. This does not work because the GameEnd object needs to be created when the WinCondition is met, which is checked when a button is clicked in the XOButton class.

But if I put the GameEnd object creator in the XOButton class (where is is right now and, supposedly, where it should be), in the constructor for GameEnd(String s, TicTacToe a), I cannot use 'this' keyword for the TicTacToe object.

This is my button class. Most code is not relevant so it has been hidden.

public class XOButton extends JButton implements ActionListener {

//Hidden code
    private void winCheck() {
        for(int j = 0; j < 3; j++) {
            if(board[j][0] == 1 && board[j][1] == 1 && board[j][2] == 1 || board[0][j] == 1 && board[1][j] == 1 && board[2][j] == 1) {
                player1Score++;
                GameEnd end = new GameEnd("X wins this round!");
                finished = true;
                break;
            }
            else if(board[j][0] == 2 && board[j][1] == 2 && board[j][2] == 2 || board[0][j] == 2 && board[1][j] == 2 && board[2][j] == 2) {
                player2Score++;
                GameEnd end = new GameEnd("O wins this round!");
                finished = true;
                break;
            }
        }

        if(board[0][0] == 1 && board[1][1] == 1 && board[2][2] == 1 || board[0][2] == 1 && board[1][1] == 1 && board[2][0] == 1) {
            player1Score++;
            GameEnd end = new GameEnd("X wins this round!");
            finished = true;
        }
        else if(board[0][0] == 2 && board[1][1] == 2 && board[2][2] == 2 || board[0][2] == 2 && board[1][1] == 2 && board[2][0] == 2) {
            player2Score++;
            GameEnd end = new GameEnd("O wins this round!");
            finished = true;
        }
        if(turn == 9 && !finished) {
            GameEnd end = new GameEnd("This round is a Draw");
            finished = true;
        }

    }

    public void resetButton() {
        this.setIcon(null);
        markSpot(0);
        this.clicked = false;
    }

    public static void resetStatics() {
        turn = 0;
        finished = false;
    }

}
```

<p>This is the TicTacToe class. Most code is not relevant so it has been hidden.</p>

<pre class="lang-java prettyprint-override"><code>
public class TicTacToe extends JFrame {

//Hidden code

    public void resetBoard() {
        for(int j = 0; j < 3; j++) {
            for(int i = 0; i < 3; i++) {
                buttons[j][i].resetButton();
            }
        }
        XOButton.resetStatics();
    }

}
</code>```

This is the GameEnd class. An object of this is created when the WinCondition is met. Most code is not relevant so it has been hidden.

public class GameEnd extends JFrame implements ActionListener {

//Hidden code

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == exit) {
            System.exit(0);
        }
        else if(e.getSource() == retry) {
            TicTacToe.resetBoard();
        }

    }

}

```

<pre class="lang-java prettyprint-override"><code>//This is the Tester class

public class TicTacTester {
    public static void main(String[] args) {
        new TicTacToe();
    }
}
</code>```

What I expect to happen is the game board to restart.

答:
It seems like you are breaking the project down too far. If you have a class for a game, keep all of its methods inside that class. The only time I can think of to use separate classes are if you are trying to create this using the Model-View-Controller (MVC) architecture, or the like. This is a common approach for an application using GUI, data access, and controllers.

There might be other times, but this is all I can think of on the top of my head.

From what you are showing, I don't think it applies.

I think this would be a better approach:

TicTacToe.java

```<code>public class TicTacToe extends JFrame {
    private int scorePlayer1;
    private int scorePlayer2;
    private boolean initialized;    // default = false

    // Reset the board
    // Reset the markers, etc.
    public void resetGame() {}

    // Check to see if there is a winner
    // If so, announce the winner and return true
    // Otherwise, return false.
    public boolean winCheck() {}

    // Set up frame, buttons, score, etc.
    public void newGame(){
        // Create however many JPanels you need
        // Add it to a single JFrame

        // When you're ready...
        // and this game has not been initialized for the first time.
        // In this example jframe is an instance of JFrame
        if (!this.initialized)
            jframe.setVisible(true);
    }

    // Play the game
    public void play(){
        // For each round,
        // a player chooses where to put their "X" or "O"
        // add scores, etc.

        // Then at the end of each round
        if (this.winCheck())
            this.resetGame();
    }
}
</code>```

TicTacToeTester.java:

```<code>public class TicTacToeTester {
    public static void main(String[] args){
        TicTacToe game = new TicTacToe();
        game.play();
    }
}
</code>```

I hope this helps!

Let me know if you have any questions. :)

Body:
I am making a Tic-Tac-Toe game in Java. I have four classes:
TicTacTester just calls (creates an object) the TicTacToe class.
The TicTacToe class provides the GUI of the game (it's a subclass of JFrame). It also creates the 9 buttons for the JPanel to display and users to click.
The XOButton class defines what the buttons can do and actionPerformed method.
Lastly, the GameEnd class defines what happens when the game ends (a new JFrame is created to display score and give the user 2 buttons: exit and restart).

The problem is when I try to code the contents of what happens when the user clicks "restart". It is suppose to call the resetBoard() method, which is defined in TicTacToe class. The problem is, I do not know the name of the object created from the TicTacToe class (in the tester class' static void main method I just typed "new TicTacToe", didn't need to define a name). I cannot call resetBoard from a static standpoint (i.e. I can't do TicTacToe.resetBoard(); ) because resetBoard needs to be non-static.

What I've tried:
I've tried including in the constructor of the GameEnd class a TicTacToe object. If I do this, the GameEnd object creator has to go into TicTacToe class, so I can use 'this' keyword. This does not work because the GameEnd object needs to be created when the WinCondition is met, which is checked when a button is clicked in the XOButton class.

But if I put the GameEnd object creator in the XOButton class (where is is right now and, supposedly, where it should be), in the constructor for GameEnd(String s, TicTacToe a), I cannot use 'this' keyword for the TicTacToe object.

This is my button class. Most code is not relevant so it has been hidden.

public class XOButton extends JButton implements ActionListener {

//Hidden code
    private void winCheck() {
        for(int j = 0; j < 3; j++) {
            if(board[j][0] == 1 && board[j][1] == 1 && board[j][2] == 1 || board[0][j] == 1 && board[1][j] == 1 && board[2][j] == 1) {
                player1Score++;
                GameEnd end = new GameEnd("X wins this round!");
                finished = true;
                break;
            }
            else if(board[j][0] == 2 && board[j][1] == 2 && board[j][2] == 2 || board[0][j] == 2 && board[1][j] == 2 && board[2][j] == 2) {
                player2Score++;
                GameEnd end = new GameEnd("O wins this round!");
                finished = true;
                break;
            }
        }

        if(board[0][0] == 1 && board[1][1] == 1 && board[2][2] == 1 || board[0][2] == 1 && board[1][1] == 1 && board[2][0] == 1) {
            player1Score++;
            GameEnd end = new GameEnd("X wins this round!");
            finished = true;
        }
        else if(board[0][0] == 2 && board[1][1] == 2 && board[2][2] == 2 || board[0][2] == 2 && board[1][1] == 2 && board[2][0] == 2) {
            player2Score++;
            GameEnd end = new GameEnd("O wins this round!");
            finished = true;
        }
        if(turn == 9 && !finished) {
            GameEnd end = new GameEnd("This round is a Draw");
            finished = true;
        }

    }

    public void resetButton() {
        this.setIcon(null);
        markSpot(0);
        this.clicked = false;
    }

    public static void resetStatics() {
        turn = 0;
        finished = false;
    }

}

This is the TicTacToe class. Most code is not relevant so it has been hidden.

public class TicTacToe extends JFrame {

//Hidden code

    public void resetBoard() {
        for(int j = 0; j < 3; j++) {
            for(int i = 0; i < 3; i++) {
                buttons[j][i].resetButton();
            }
        }
        XOButton.resetStatics();
    }

}

This is the GameEnd class. An object of this is created when the WinCondition is met. Most code is not relevant so it has been hidden.

public class GameEnd extends JFrame implements ActionListener {

//Hidden code

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == exit) {
            System.exit(0);
        }
        else if(e.getSource() == retry) {
            TicTacToe.resetBoard();
        }

    }

}

//This is the Tester class

public class TicTacTester {
    public static void main(String[] args) {
        new TicTacToe();
    }
}

What I expect to happen is the game board to restart.

Body:
It seems like you are breaking the project down too far. If you have a class for a game, keep all of its methods inside that class. The only time I can think of to use separate classes are if you are trying to create this using the Model-View-Controller (MVC) architecture, or the like. This is a common approach for an application using GUI, data access, and controllers.

There might be other times, but this is all I can think of on the top of my head.

From what you are showing, I don't think it applies.

I think this would be a better approach:

TicTacToe.java

public class TicTacToe extends JFrame {
    private int scorePlayer1;
    private int scorePlayer2;
    private boolean initialized;    // default = false

    // Reset the board
    // Reset the markers, etc.
    public void resetGame() {}

    // Check to see if there is a winner
    // If so, announce the winner and return true
    // Otherwise, return false.
    public boolean winCheck() {}

    // Set up frame, buttons, score, etc.
    public void newGame(){
        // Create however many JPanels you need
        // Add it to a single JFrame

        // When you're ready...
        // and this game has not been initialized for the first time.
        // In this example jframe is an instance of JFrame
        if (!this.initialized)
            jframe.setVisible(true);
    }

    // Play the game
    public void play(){
        // For each round,
        // a player chooses where to put their "X" or "O"
        // add scores, etc.

        // Then at the end of each round
        if (this.winCheck())
            this.resetGame();
    }
}

TicTacToeTester.java:

public class TicTacToeTester {
    public static void main(String[] args){
        TicTacToe game = new TicTacToe();
        game.play();
    }
}

I hope this helps!

Let me know if you have any questions. :)


来源: stackexchange

问:
How to input time series data in R?
I'm rather new at R so I appreciate your help in advance.

I have an excel spreadsheet dataset including daily, closing prices for a financial asset ranging from Jan 3rd 2000 all the way to Mar 6th 2019. I am looking to use ARIMA models to forecast future prices for this asset but cannot input the data in R.

Simply put, I have an Excel file with 2 columns and 4736 rows as per below:

```<code>03/jan/00   1,8358
04/jan/00   1,8702
05/jan/00   1,8520
.
.
.
01/mar/19   3,7824
06/mar/19   3,8372
</code>```

Right after reading the file using the command read_excel(file.choose()) I've tried using ts commands to read the data as a time series. However considering data is only collected during market closing times on business days, this does not produce the desired results. Also tried researching and read about xts and zoo-type series but do not seem to be able to make these work. Please note that this data excludes weekends and holidays, which seems to be the root of the problem here.

```<code>my_data <- read_excel(file.choose())
series <- ts(my_data, start=c(2000,1,3), end=c(2019,3,6), frequency = 252)
</code>```

By using ts considering an average 252 business days per year, my time series ends on a different date as it should.

What kind of steps should I consider in order to 1) read the data from the excel file and 2) read the imported data in R as a time series?

Also thought about, instead of using dates as the first column, use numbers from 1 through 4736 to eliminate this necessity but it seems the first column is required to have the YYYY-m-d format.

Thanks a ton

答:
1) read_excel should read it in as a tibble. In case dates are read as values use janitor::excel_numeric_to_date to convert to correct date

2) To format date use lubridate. In your case dmy function would be it.

3) then convert the tibble to xts using tbl2xts; vignette:
https://cran.r-project.org/web/packages/tbl2xts/vignettes/tbl2xts_vignette.html

ContentLicense: CC BY-SA 4.0

Title: How to input time series data in R?

Body:
I'm rather new at R so I appreciate your help in advance.

I have an excel spreadsheet dataset including daily, closing prices for a financial asset ranging from Jan 3rd 2000 all the way to Mar 6th 2019. I am looking to use ARIMA models to forecast future prices for this asset but cannot input the data in R.

Simply put, I have an Excel file with 2 columns and 4736 rows as per below:

03/jan/00   1,8358
04/jan/00   1,8702
05/jan/00   1,8520
.
.
.
01/mar/19   3,7824
06/mar/19   3,8372

Right after reading the file using the command read_excel(file.choose()) I've tried using ts commands to read the data as a time series. However considering data is only collected during market closing times on business days, this does not produce the desired results. Also tried researching and read about xts and zoo-type series but do not seem to be able to make these work. Please note that this data excludes weekends and holidays, which seems to be the root of the problem here.

my_data <- read_excel(file.choose())
series <- ts(my_data, start=c(2000,1,3), end=c(2019,3,6), frequency = 252)

By using ts considering an average 252 business days per year, my time series ends on a different date as it should.

What kind of steps should I consider in order to 1) read the data from the excel file and 2) read the imported data in R as a time series?

Also thought about, instead of using dates as the first column, use numbers from 1 through 4736 to eliminate this necessity but it seems the first column is required to have the YYYY-m-d format.

Thanks a ton


问:
Individual Axios Call For Each Item In Array
I am not very experienced using axios calls with React and I am trying to make an axios call to get an array and then use that array to make an axios call for each item in the array. I am getting the array from the first call and then I am getting the array of objects from each individual call but after the state is updated nothing is rendered. Here is my code:

I tried to use a separate to update the state of the array of objects but that did not work.

```<code>state = {
    items: [],
    searchItem: "newstories",
    promises: [{}]
   };

 componentDidMount() {

     const { searchItem } = this.state;
     axios
       .get(
         "https://hacker-news.firebaseio.com/v0/" +
           this.state.searchItem +
           ".json?print=pretty"
       )
       .then(result => {

         const topStories = result.data;

         this.setState({ topStories });

        let promises = [];
         for (let i = 0; i < topStories.length; i++) {
           axios
              .get(base + topStories[i] + extension)
             .then(res => {
               const newItem = res.data;
               promises.push(newItem.title);
             })
             .catch(error => console.log("Something went wrong"));
         }
         // Set the state of the array of objects
        this.setState({ promises });

       });
   }

 render() {

let counter = 0;

return (
  <div>
        {this.state.promises.map(stories => (
          <li style={{ listStyle: "none" }} key=stories.id>
            {(counter += 1)}. {stories.title}
          </li>
        ))}
    </div>
     );
   }
 }
</code>```

I want to be able to map and get each object and use the attributes of each object accordingly. Each object looks like this:

{by: "thinksocrates" id: 20004127 kids: […] score: 28 title: "OKR" }

The render isn't returning any of the titles but I am able to see them in a console log after the state is changed so I am not sure what is happening. I am guessing that I am getting the array of promises incorrectly but I am not sure how to use axios.all for this situation.

答:
you need here to use Promise.all

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

your promise array fill with promises and not with objects to render them properly you need to wait for all response

moreover this action inside componentDidMount() will take an amount of time so it  will be better to considering initialise the state with a loader until all response retrieve

Body:
I am not very experienced using axios calls with React and I am trying to make an axios call to get an array and then use that array to make an axios call for each item in the array. I am getting the array from the first call and then I am getting the array of objects from each individual call but after the state is updated nothing is rendered. Here is my code:

I tried to use a separate to update the state of the array of objects but that did not work.

state = {
    items: [],
    searchItem: "newstories",
    promises: [{}]
   };

 componentDidMount() {

     const { searchItem } = this.state;
     axios
       .get(
         "https://hacker-news.firebaseio.com/v0/" +
           this.state.searchItem +
           ".json?print=pretty"
       )
       .then(result => {

         const topStories = result.data;

         this.setState({ topStories });

        let promises = [];
         for (let i = 0; i < topStories.length; i++) {
           axios
              .get(base + topStories[i] + extension)
             .then(res => {
               const newItem = res.data;
               promises.push(newItem.title);
             })
             .catch(error => console.log("Something went wrong"));
         }
         // Set the state of the array of objects
        this.setState({ promises });

       });
   }

 render() {

let counter = 0;

return (

        {this.state.promises.map(stories => (

            {(counter += 1)}. {stories.title}

        ))}

     );
   }
 }

I want to be able to map and get each object and use the attributes of each object accordingly. Each object looks like this:

{by: "thinksocrates" id: 20004127 kids: […] score: 28 title: "OKR" }

The render isn't returning any of the titles but I am able to see them in a console log after the state is changed so I am not sure what is happening. I am guessing that I am getting the array of promises incorrectly but I am not sure how to use axios.all for this situation.


问:
Does it necessary to put original credentials to UsernamePasswordAuthenticationToken after successful authentication in AuthenticationProvider?
I receive a already confirmed user id at the entrance. I decided to write my implementation of Authentication for incoming id - VkIdAuthentication. And implementation of AuthenticationProvider that receiving VkIdAuthentication then find the UserDetails and returns UsernamePasswordAuthenticationToken.

But i haven't got original credentials the user supplied. Is it ok to put null as credentials for UsernamePasswordAuthenticationToken?

One comment in AbstractUserDetailsAuthenticationProvider confuse me:

// Ensure we return the original credentials the user supplied,
          // so subsequent attempts are successful even with encoded passwords.

答:
From the following comment found at this:

More broadly: perhaps there are auth providers that do require
  credentials even after a session has been authenticated, or perhaps
  there are other use cases where having credentials around is necessary
  for some other purpose, but (from my naive perspective) it seems that
  user credentials are never needed after authentication has been
  completed successfully, so perhaps all authentication managers should
  clear credentials from Authentication instances, regardless of the
  type of token/provider involved?

And from what I see in the current source codes , the default behaviour is that even you return an UsernamePasswordAuthenticationToken from AbstractUserDetailsAuthenticationProvider it will then call UsernamePasswordAuthenticationToken#eraseCredentials() very soon to set the credentials to NULL again.

So I would say it is rather safe to return Authentication with NULL credentials if you do not require to use user credentials after successful authentication.


问:
Print JSON with two double-quotes
I want to print the list using two double-quotes

```<code>>>> l = ["ABC", "123"]
>>> print(l)
['ABC', '123']
>>> print(json.dumps(l))
["ABC", "123"]
>>> print('"{}"'.format(l))
"['ABC', '123']"
</code>```

I have tried to use json.dumps and format like above code. I need to print the list like this:

```<code>"[""ABC"", ""123""]"
</code>```

Any idea to print the list following this format?

Thanks!

答:
Putting answer of @cs95, for others to be helpful.</p>

```<code>json.dumps(l).replace('"', '""')
</code>```

Title: Print JSON with two double-quotes

Body:
I want to print the list using two double-quotes

>>> l = ["ABC", "123"]
>>> print(l)
['ABC', '123']
>>> print(json.dumps(l))
["ABC", "123"]
>>> print('"{}"'.format(l))
"['ABC', '123']"

I have tried to use json.dumps and format like above code. I need to print the list like this:

"[""ABC"", ""123""]"

Any idea to print the list following this format?

Thanks!

Body:
Putting answer of @cs95, for others to be helpful.

json.dumps(l).replace('"', '""')


问:
PostgreSQL: Can COPY command be used to copy columns from multiple tables?
I want to copy values from columns in multiple tables to a csv file, not sure if posgres COPY command support copying column from multiple tables.

Here's a simplified example of the kind of thing I want to do using the tables below:

```<code>environment
╔════════╦═══════════╦══════╦══════╗
║ env_id ║ placem_id ║ humd ║ wind ║
╠════════╬═══════════╬══════╬══════╣
║     104║        4  ║   48 ║  119 ║
║     68 ║        9  ║   39 ║  141 ║
╚════════╩═══════════╩══════╩══════╝

placement
╔═══════════╦════════╦═══════════════╦══════════════════════════╗
║ placem_id ║ loc_id ║  description  ║           date           ║
╠═══════════╬════════╬═══════════════╬══════════════════════════╣
║         4 ║     64 ║ description_1 ║ 2019-03-12T20:40:35.967Z ║
║         7 ║      5 ║ description_2 ║ 2019-03-12T20:56:51.319Z ║
╚═══════════╩════════╩═══════════════╩══════════════════════════╝

location
╔════════╦═══════════╦═══════════╦════════════════════╗
║ loc_id ║    log    ║    lat    ║      address       ║
╠════════╬═══════════╬═══════════╬════════════════════╣
║     64 ║ 13.3986   ║ 52.5547   ║ Bosebrucke Einkauf ║
║     71 ║ 21.150122 ║ -6.607044 ║ Charlotte Court    ║
╚════════╩═══════════╩═══════════╩════════════════════╝
</code>```

I want to select records from environment table and  location table using the placem_id and loc_id in the placement table.

It is possible to copy these columns coming from more than one table using the COPY function syntax below:

```<code>\copy products TO '/tmp/products.csv' CSV DELIMITER ','
</code>```

EDIT:

I'm interested in columns humd and wind from environment taable; then columns log lat and address from location table.

答:
You could send a query instead of using the console :

Copy (Select humd, wind, log, lat, address From location natural join placement natural join environment) To '/tmp/test.csv' With CSV DELIMITER ',';

Body:
I want to copy values from columns in multiple tables to a csv file, not sure if posgres COPY command support copying column from multiple tables.

Here's a simplified example of the kind of thing I want to do using the tables below:

environment
╔════════╦═══════════╦══════╦══════╗
║ env_id ║ placem_id ║ humd ║ wind ║
╠════════╬═══════════╬══════╬══════╣
║     104║        4  ║   48 ║  119 ║
║     68 ║        9  ║   39 ║  141 ║
╚════════╩═══════════╩══════╩══════╝

placement
╔═══════════╦════════╦═══════════════╦══════════════════════════╗
║ placem_id ║ loc_id ║  description  ║           date           ║
╠═══════════╬════════╬═══════════════╬══════════════════════════╣
║         4 ║     64 ║ description_1 ║ 2019-03-12T20:40:35.967Z ║
║         7 ║      5 ║ description_2 ║ 2019-03-12T20:56:51.319Z ║
╚═══════════╩════════╩═══════════════╩══════════════════════════╝

location
╔════════╦═══════════╦═══════════╦════════════════════╗
║ loc_id ║    log    ║    lat    ║      address       ║
╠════════╬═══════════╬═══════════╬════════════════════╣
║     64 ║ 13.3986   ║ 52.5547   ║ Bosebrucke Einkauf ║
║     71 ║ 21.150122 ║ -6.607044 ║ Charlotte Court    ║
╚════════╩═══════════╩═══════════╩════════════════════╝

I want to select records from environment table and  location table using the placem_id and loc_id in the placement table.

It is possible to copy these columns coming from more than one table using the COPY function syntax below:

\copy products TO '/tmp/products.csv' CSV DELIMITER ','

EDIT:

I'm interested in columns humd and wind from environment taable; then columns log lat and address from location table.


问:
i'm having trouble with permission overwrite in discord.js
i am creating a "ticket bot" in discord.js and have got most of it working but need help with permission overwrites

the discordjs guide shows this code  but when run it creates the channel but does not do permissions.

        guild.createChannel('new-channel', 'text', [
            {
                id: guild.defaultRole.id,
                deny: ['VIEW_CHANNEL'],
            },
            {
                id: user.id,
                allow: ['VIEW_CHANNEL'],
            },
        ]);
    }
```

答:
i had extra commas that my linter added, with 11.5 you need to add permissionOverwrites

        guild.createChannel('new-channel', 'text',
          permissionOverwrites[
            {
                id: guild.defaultRole.id,
                deny: ['VIEW_CHANNEL']
            },
            {
                id: user.id,
                allow: ['VIEW_CHANNEL']
            }
        ]);
    }
```


问:
Can't do a HTTP Post to a Web Service from my Android App
I've been working on an app that uses both GET and POST requests to Web Services.  The GET requests are no problems but the POST requests are killing me.  I've tried 2 different scenarios in the code.  The first looks like this...

```<code> HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost(ws);
 JSONObject jsonObject = new JSONObject();

 try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
jsonObject.put("action", "login");
jsonObject.put("username", "*********");
    jsonObject.put("password", "*********");

    httppost.setHeader("jsonString", jsonObject.toString());
StringEntity se = new StringEntity( jsonObject.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            textview.setText(getResponse(response.getEntity()));
        } catch (ClientProtocolException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (IOException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (JSONException e) {
            textview.setText(e.getLocalizedMessage());
        }
</code>```

This code gets this result for me...

"Bad Request (Invalid Header Name)"

Now here's my second piece of code...

```<code> HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(ws);
      JSONObject jsonObject = new JSONObject();

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            jsonObject.put("action", "login");
            jsonObject.put("username", "******");
            jsonObject.put("password", "******");

            nameValuePairs.add(new BasicNameValuePair("jsonString", jsonObject.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            textview.setText(getResponse(response.getEntity()));
        } catch (ClientProtocolException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (IOException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (JSONException e) {

        }
</code>```

This gives me an entirely different result.  It's a long garbled mess of xml and SOAP that does have a SOAP Exception mentioned in it...

"Server was unable to process request.  --- System.Xml.XmlException: Data at the root level is invalid.  Line 1, position 1."

Now, can anyone shed any light on what I am doing wrong.

答:
This is a bit old, but was having a similar issue myself.  The first example is the route I went; and the problem with the original example was this line httppost.setHeader("jsonString", jsonObject.toString());.  It's adding a Request Header which the server can't parse.

Additionally the declaration of nameValuePairs is unnecessary.

ContentLicense: CC BY-SA 2.5

Body:
I've been working on an app that uses both GET and POST requests to Web Services.  The GET requests are no problems but the POST requests are killing me.  I've tried 2 different scenarios in the code.  The first looks like this...

 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost(ws);
 JSONObject jsonObject = new JSONObject();

 try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
jsonObject.put("action", "login");
jsonObject.put("username", "*********");
    jsonObject.put("password", "*********");

    httppost.setHeader("jsonString", jsonObject.toString());
StringEntity se = new StringEntity( jsonObject.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            textview.setText(getResponse(response.getEntity()));
        } catch (ClientProtocolException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (IOException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (JSONException e) {
            textview.setText(e.getLocalizedMessage());
        }

This code gets this result for me...

"Bad Request (Invalid Header Name)"

Now here's my second piece of code...

 HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(ws);
      JSONObject jsonObject = new JSONObject();

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            jsonObject.put("action", "login");
            jsonObject.put("username", "******");
            jsonObject.put("password", "******");

            nameValuePairs.add(new BasicNameValuePair("jsonString", jsonObject.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            textview.setText(getResponse(response.getEntity()));
        } catch (ClientProtocolException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (IOException e) {
            textview.setText(e.getLocalizedMessage());
        } catch (JSONException e) {

        }

This gives me an entirely different result.  It's a long garbled mess of xml and SOAP that does have a SOAP Exception mentioned in it...

"Server was unable to process request.  --- System.Xml.XmlException: Data at the root level is invalid.  Line 1, position 1."

Now, can anyone shed any light on what I am doing wrong.

ContentLicense: CC BY-SA 3.0


答:
this.setState({ promises }); will run before all promise is resolve. This is better way to slove it.

```<code>.then(result => {
   const topStories = result.data;
   const promises = topStories.map(story => {
     return axios.get(base + story + extension).then(res => res.data)
   })
   Promise.all(promises).then(data => {
     console.log(data)
     this.setState({ promises: data })
   })
</code>```

Change the render

```<code>render() {
   return (
      <div>
         {this.state.promises.map((stories, index)=> (
            <li style={{ listStyle: "none" }} key=stories.id>
              {`${index + 1}}.${stories.by}`}
            </li>
         ))}
      </div>
     );
   }
</code>```

Title: Individual Axios Call For Each Item In Array

Body:
this.setState({ promises }); will run before all promise is resolve. This is better way to slove it.

.then(result => {
   const topStories = result.data;
   const promises = topStories.map(story => {
     return axios.get(base + story + extension).then(res => res.data)
   })
   Promise.all(promises).then(data => {
     console.log(data)
     this.setState({ promises: data })
   })

Change the render

render() {
   return (
      <div>
         {this.state.promises.map((stories, index)=> (
            <li style={{ listStyle: "none" }} key=stories.id>
              {`${index + 1}}.${stories.by}`}
            </li>
         ))}
      </div>
     );
   }


问:
CoreData: saving data to context
I am working on to use CoreData to save data of an object to an entity created in the datamodeld file.

In my scenario, I made a datamodeld called Product which represents an item available in the grocery store.

I have several categories for each type of products. For example, produce, dairy, meat, etc... If I save those products in the Product context, they will all be aggregated into one database and retrieving the data will be a hassle.

I'm wondering if it is possible to store my items into different databases of the Product context.

The only workaround I can think of is to create an entity for each categories which is a child of Product. I don't like this workaround because I am creating unnecessarily entities (every products in each categories have the same attributes).

答:
By "product context", I guess you mean managedObjextContext? Your data is not saved in moc, you write data on moc and it's reflected persistent store.

You can use multiple moc to save the data of your app but be extra careful to syncronize the moc to moc on main thread.

I did something on the same lines that you are proposing as a work around. It worked out fine in my case.

Title: CoreData: saving data to context


问:
Regex to find words with specific character
How to find all words which contain a specific letter in it?

For example, if my string is

```<code>This is a Station called South Yarra
</code>```

then I want to extract all words with the letter 'a' in them. The matches will be

```<code>"a", "Station", "called", "Yarra"
</code>```

So far I have tried

```<code>Regex regex = new Regex(@"\w[a]\w");

Regex regex = new Regex(@"\s[a*]\s");
</code>```

答:
Solution without regex using Linq :

```<code>List<string> arr = s.Split(' ').Where(x => x.Contains('a')).ToList();
</code>```

string.Split(' ') : It return array of strings that contains the substrings in this instance that are delimited by ' '

Enumerable.Where(predicate) : Filter sequence based on predicate

Enumerable.Contains() : Determines whether a sequence contains a specified element

POC: .net Fiddle

Body:
How to find all words which contain a specific letter in it?

For example, if my string is

This is a Station called South Yarra

then I want to extract all words with the letter 'a' in them. The matches will be

"a", "Station", "called", "Yarra"

So far I have tried

Regex regex = new Regex(@"\w[a]\w");

Regex regex = new Regex(@"\s[a*]\s");

Body:
Solution without regex using Linq :

List<string> arr = s.Split(' ').Where(x => x.Contains('a')).ToList();

string.Split(' ') : It return array of strings that contains the substrings in this instance that are delimited by ' '

Enumerable.Where(predicate) : Filter sequence based on predicate

Enumerable.Contains() : Determines whether a sequence contains a specified element

POC: .net Fiddle


问:
DomPDF display data table except last page
I am working to produce pdf in codeigniter data. All code runs perfectly, it's just that I have a problem when doing a condition for the last page, the question is simple, I have data in table form and I want to display it for the entire page except for the last page.

```<code>if ( isset($pdf) ) {
        $pdf->page_script('
        if ($PAGE_NUM != $PAGE_COUNT) {
        $font = $fontMetrics->get_font("Arial, Helvetica, sans-serif", "normal");
        $size = 12;
        $pageText = "Page " . $PAGE_NUM . " of " . $PAGE_COUNT;
        $y = 15;
        $x = 520;
        $pdf->text($x, $y, $pageText, $font, $size);
    }
    ');
}
</code>```

i'm tying to  change $pageText = "My string text" and this is working fine, but I got problem when I combine with html table. So in my case I change $pageText to $pageText = "

My content here

" but the results is

My content here

 this should be a table, anyone can help me? why the results is still string? and wont generate to be a table?

fyi, the code that I attach is running perfectly to display a page, it's just that I want to modify it so that it displays a table.

答:
the way you are loading in pdf is as a string and is not rendering html code. For rendering as html code you must put it inside loadHtml()

$pageText must be inside loadHtml().

You should keep the html codes inside loadHtml().

Or you can make a separate file using html for making pdf.  you can check out documentation

Body:
I am working to produce pdf in codeigniter data. All code runs perfectly, it's just that I have a problem when doing a condition for the last page, the question is simple, I have data in table form and I want to display it for the entire page except for the last page.

if ( isset($pdf) ) {
        $pdf->page_script('
        if ($PAGE_NUM != $PAGE_COUNT) {
        $font = $fontMetrics->get_font("Arial, Helvetica, sans-serif", "normal");
        $size = 12;
        $pageText = "Page " . $PAGE_NUM . " of " . $PAGE_COUNT;
        $y = 15;
        $x = 520;
        $pdf->text($x, $y, $pageText, $font, $size);
    }
    ');
}

i'm tying to  change $pageText = "My string text" and this is working fine, but I got problem when I combine with html table. So in my case I change $pageText to $pageText = "

My content here

" but the results is

My content here

 this should be a table, anyone can help me? why the results is still string? and wont generate to be a table?

fyi, the code that I attach is running perfectly to display a page, it's just that I want to modify it so that it displays a table.


问:
Why after installing vue CLI through npm 6.9.0 dosn't work?
When i use this command bellow :

```<code>vue create hello-world
</code>```

I got this message :

```<code>'vue' is not recognized as an internal or external command,
operable program or batch file.
</code>```

After 1 month I still haven't found the solution..

Some informations:

My OS : Windows 10

NPM version : 6.9.0

vue version : 2.6.10

Vue cli installed version : @vue/cli@3.8.2

==>

0 error message when i installed all these packages.

I correctly added npm path on environement variable.

答:
If you set the path correctly then you need to restart the system once because sometimes environment variables need restart after setting the path.

And Do this (If above not works):

Run command as administrator privileged.

```<code>npm install --global vue-cli
</code>```

Set this path to environment variables:

```<code>C:\Users\YourUserName\AppData\Roaming\npm
</code>```

This one too:

In last, restart the cmd, system and run the vue again. It should work just fine.

Body:
When i use this command bellow :

vue create hello-world

I got this message :

'vue' is not recognized as an internal or external command,
operable program or batch file.

After 1 month I still haven't found the solution..

Some informations:

My OS : Windows 10

NPM version : 6.9.0

vue version : 2.6.10

Vue cli installed version : @vue/cli@3.8.2

==>

0 error message when i installed all these packages.

I correctly added npm path on environement variable.

Body:
If you set the path correctly then you need to restart the system once because sometimes environment variables need restart after setting the path.

And Do this (If above not works):

Run command as administrator privileged.

npm install --global vue-cli

Set this path to environment variables:

C:\Users\YourUserName\AppData\Roaming\npm

This one too:

In last, restart the cmd, system and run the vue again. It should work just fine.


问:
python file was renamed, how to get 'rename time'
lets say that some files were renamed by Python script, is it possible to get this 'rename time' using Python (It can be seen in Far Manager)? (Windows)

It seems it is not possible through STAT, etc
Any ideas ?

答: It is impossible, OS does not store such info about files. Answered by 'atzz' in comment</p>


问:
Codeigniter select_sum generate wrong query
I worked on a Codeigniter 2 project, there I have an active record like:

```<code>$query = $this->db->select_sum('Cardit * GPA', 'sum')
                  ->get('marks_info');
</code>```

It generates query like:

```<code>SELECT SUM(`Cardit` * `GPA`) AS `sum` FROM `marks_info`
</code>```

Recently I migrated my project to Codeigniter 3, but the same active record generated little different query like:

```<code>SELECT SUM(`Cardit *` `GPA`) AS `sum` FROM `marks_info`
</code>```

that is wrong, it includes * with Cardit ('Cardit *') in SUM section.

Difference:

Can anybody tell me, how can I solve this issue in CodeIgniter 3 ?

答:
To avoid backticks within the query. You can assign false to protect_identifiers like :

```<code>$this->db->_protect_identifiers=false;
</code>```

and run your query accordingly.

Body:
I worked on a Codeigniter 2 project, there I have an active record like:

$query = $this->db->select_sum('Cardit * GPA', 'sum')
                  ->get('marks_info');

It generates query like:

SELECT SUM(`Cardit` * `GPA`) AS `sum` FROM `marks_info`

Recently I migrated my project to Codeigniter 3, but the same active record generated little different query like:

SELECT SUM(`Cardit *` `GPA`) AS `sum` FROM `marks_info`

that is wrong, it includes * with Cardit ('Cardit *') in SUM section.

Difference:

Can anybody tell me, how can I solve this issue in CodeIgniter 3 ?

Body:
To avoid backticks within the query. You can assign false to protect_identifiers like :

$this->db->_protect_identifiers=false;

and run your query accordingly.


问:
Typescript enum switch not working
i have the following enum

```<code>enum EditMode {
    View = 0,
    Edit = 1,
    Delete = 2
}
</code>```

Let's assume i have a variable of the enum type

```<code>var editMode = EditMode.Edit;
</code>```

Why does the following code not work (goes straight to default)?

```<code>switch (editMode) {
    case EditMode.Delete:
        ...
        break;
    case EditMode.Edit:
        ...
        break;
    default:
        ...
        break;
    }
</code>```

答:
Declare your enum using const:

```<code>const enum EditMode {
    View = 0,
    Edit = 1,
    Delete = 2
}
</code>```

Title: Typescript enum switch not working

Body:
i have the following enum

enum EditMode {
    View = 0,
    Edit = 1,
    Delete = 2
}

Let's assume i have a variable of the enum type

var editMode = EditMode.Edit;

Why does the following code not work (goes straight to default)?

switch (editMode) {
    case EditMode.Delete:
        ...
        break;
    case EditMode.Edit:
        ...
        break;
    default:
        ...
        break;
    }

Body:
Declare your enum using const:

const enum EditMode {
    View = 0,
    Edit = 1,
    Delete = 2
}


问:
Uploaded file is not visible in browser unless I force no cache browser reload
I am facing weird issue with file uploads. When I upload a new file to publicly visible folder, I can see it instantly  in anonymous mode. But if i try to access it in non-anonymous mode, the server responds with 404 unless I do hard refresh (ie ctrl + F5 for Mozzila).

I have already disabled cache control headers for that folder in apache, but that did not seem to resolve the issue. It seems to me that the apache is storing information that "there is actually no file at requested url" and serves it to user unless user clears cache even if the file is uploaded at that location. Anyone ran into similar issue in the past?

答:
By default, most browsers cache images, styles and scripts automatically. The easiest way to bypass this for development environments is to set the caching headers detailed here

Another common way to bypass caching is to set a random query parameter (usually ?v=<random value here>).

Chromium based browsers also have a disable cache option in the dev tools


问:
How can I make my program still run after running once
I wrote a program which interferes with the user. However it only works once. I want my program to run until the user writes "q" or "Q". So far I wrote this:</p>

```<code>import java.util.Scanner;
public class isbn {
    public static boolean validISBN(String isbnNumber) {
        isbnNumber = isbnNumber.replace("-", "").trim();
        if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+")) {
            int sum = 0;
            for(int i = 10; i > 0; i--) {
                if (isbnNumber.charAt(9) == 'X' && i == 1) {
                    sum += i * 10;
                } else {
                    sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
                }
            }
            if (sum % 11 == 0) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Input ISBN Number: ");
        String isbnNumber = keyboard.next();
        validISBN(isbnNumber);
    }
}
</code>```

答:
Add a loop which check if the user enter "q" or "Q"</p>

```<code>import java.util.Scanner;

public class isbn {

    public static boolean validISBN(String isbnNumber) {
        isbnNumber = isbnNumber.replace("-", "").trim();
        if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+")) {
            int sum = 0;
            for (int i = 10; i > 0; i--) {
                if (isbnNumber.charAt(9) == 'X' && i == 1) {
                    sum += i * 10;
                } else {
                    sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
                }
            }
            if (sum % 11 == 0) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String isbnNumber;
        do {
            System.out.print("Input ISBN Number: ");
            isbnNumber = keyboard.next();
            validISBN(isbnNumber);
            if ("q".equalsIgnoreCase(isbnNumber)) {
                break;
            }
        } while (true);
    }
}
</code>```

Body:
I wrote a program which interferes with the user. However it only works once. I want my program to run until the user writes "q" or "Q". So far I wrote this:

import java.util.Scanner;
public class isbn {
    public static boolean validISBN(String isbnNumber) {
        isbnNumber = isbnNumber.replace("-", "").trim();
        if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+")) {
            int sum = 0;
            for(int i = 10; i > 0; i--) {
                if (isbnNumber.charAt(9) == 'X' && i == 1) {
                    sum += i * 10;
                } else {
                    sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
                }
            }
            if (sum % 11 == 0) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Input ISBN Number: ");
        String isbnNumber = keyboard.next();
        validISBN(isbnNumber);
    }
}

Body:
Add a loop which check if the user enter "q" or "Q"

import java.util.Scanner;

public class isbn {

    public static boolean validISBN(String isbnNumber) {
        isbnNumber = isbnNumber.replace("-", "").trim();
        if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+")) {
            int sum = 0;
            for (int i = 10; i > 0; i--) {
                if (isbnNumber.charAt(9) == 'X' && i == 1) {
                    sum += i * 10;
                } else {
                    sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
                }
            }
            if (sum % 11 == 0) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String isbnNumber;
        do {
            System.out.print("Input ISBN Number: ");
            isbnNumber = keyboard.next();
            validISBN(isbnNumber);
            if ("q".equalsIgnoreCase(isbnNumber)) {
                break;
            }
        } while (true);
    }
}


问:
What is the function of pair[1] in Python3?
I’m reading python3 official document and encounter a syntax pair[1] which I can’t understand.</p>

```<code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])

print(pairs)
# [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
</code>```

答:
pairs is a list of tuples. (1, 'one') is an example of a tuple with two elements.

From the docs:

Tuples are immutable sequences, typically used to store collections of heterogeneous data

We then sort that list in-place on the 2nd element of the tuple via key=lambda pair: pair[1] (pair[1] signifies that the sorting key should be the 2nd element of the tuple)

Since the second element is a string, the sort is done lexicopgraphically, or alphabetically.

From the docs:

list.sort(key=None, reverse=False)

  Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

```<code>In [7]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

In [8]: pairs.sort(key=lambda pair: pair[1])

In [9]: pairs
Out[9]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
</code>```

If you sort on the first element of the tuple, the sort is done on the integers and is done numerically

```<code>In [10]: pairs.sort(key=lambda pair: pair[0])

In [11]: pairs
Out[11]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
</code>```

This questions here goes in more details about what a tuple is and
this question here goes in more details about how key works in sorting functions sort() and sorted()

Body:
I’m reading python3 official document and encounter a syntax pair[1] which I can’t understand.

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])

print(pairs)
# [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Body:
pairs is a list of tuples. (1, 'one') is an example of a tuple with two elements.

From the docs:

Tuples are immutable sequences, typically used to store collections of heterogeneous data

We then sort that list in-place on the 2nd element of the tuple via key=lambda pair: pair[1] (pair[1] signifies that the sorting key should be the 2nd element of the tuple)

Since the second element is a string, the sort is done lexicopgraphically, or alphabetically.

From the docs:

list.sort(key=None, reverse=False)

  Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

In [7]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

In [8]: pairs.sort(key=lambda pair: pair[1])

In [9]: pairs
Out[9]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

If you sort on the first element of the tuple, the sort is done on the integers and is done numerically

In [10]: pairs.sort(key=lambda pair: pair[0])

In [11]: pairs
Out[11]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

This questions here goes in more details about what a tuple is and
this question here goes in more details about how key works in sorting functions sort() and sorted()


问:
Python3 Unable to Decode POST Request Result
I am sending a POST request with sockets and trying to decode the received HTML and print to the terminal.

This works fine in my initial GET request but when I try to decode and print the POST request I just get garbled text.

How can I change my decode so that the text is readable?

POST

POST

```<code>body = "hash="+md5

headers = """\
POST / HTTP/1.1\r
Host: url.com:57555\r
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0\r
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r
Accept-Language: en-US,en;q=0.5\r
Accept-Encoding: gzip, deflate\r
Referer: http://url.com:57555/\r
Content-Type: application/x-www-form-urlencoded\r
Content-Length: 32\r
Connection: close\r
Cookie: PHPSESSID=some_cookie\r
Upgrade-Insecure-Requests: 1\r
\r\n"""

payload = headers + body

s.sendall(payload.encode('utf-8'))
res = s.recv(4096)

print(str(res, errors='replace'))
</code>```

Result...

```<code>python3 emdee5.py
HTTP/1.1 200 OK
Date: Sun, 26 May 2019 22:01:26 GMT
Server: Apache/2.4.18 (Ubuntu)
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 282
Connection: close
Content-Type: text/html; charset=UTF-8

]�1o� ���
ʒ��Ҩ��b�V��LN��
p�$����Py��d��FP��l�    ^�֞i�ĜmA��F7i�zd}��VͩK8}ߠ���!�n�W>�wL9ۅr�@Ȑ����� 4i��ec{"%��0���)������W���A�I��"��GD�;�܉"J��JA}x��l1��3٠.y�>Om�#5��9
                                                                                ��ڨ�p�j����JN���MQ̀)�:�p�P{K���4J^-��+�7�oV'E;'=�����l�
</code>```

答:
Your request explicitly says that you are willing to accept a compressed response:

```<code> Accept-Encoding: gzip, deflate\r
</code>```

And this is therefore what you get in the response

```<code>Content-Encoding: gzip
</code>```

So, the body is compressed with gzip (which explains the garbled output) and you would need to decompress it. Given that you currently don't seem to be able to properly deal with compressed responses you should not claim in your request that you support these, i.e. remove the Accept-Encoding.

Apart from that more is likely wrong with your request:

```<code>body = "hash="+md5
...
Content-Length: 32\r
...
payload = headers + body
...
</code>```

Given that md5 is 32 characters hex (or 16 byte binary) the body consisting of "hash"=+md5 is likely not 32 characters long as you claim in your Content-Length.

```<code>POST / HTTP/1.1\r
</code>```

Additionally you send a HTTP/1.1 request so you have to be able to deal with chunked responses - but your code does not deal with these.

```<code>res = s.recv(4096)
</code>```

Similarly your code blindly assumes that the full response can be retrieved within a single recv which does not need to be the case.

In summary: unless you have a deeper understanding of how HTTP works (which you do not seem to have) it is recommended that you use existing libraries to handle HTTP for you, since these were written by developers who have an understanding of HTTP.

And even if you already have an understanding of HTTP you'll likely will use these libraries anyway since you'll know that HTTP is far from trivial and that it makes no sense to implement all the necessary details and edge cases by yourself in your code if something robust already exists.

Body:
I am sending a POST request with sockets and trying to decode the received HTML and print to the terminal.

This works fine in my initial GET request but when I try to decode and print the POST request I just get garbled text.

How can I change my decode so that the text is readable?

POST

POST

body = "hash="+md5

headers = """\
POST / HTTP/1.1\r
Host: url.com:57555\r
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0\r
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r
Accept-Language: en-US,en;q=0.5\r
Accept-Encoding: gzip, deflate\r
Referer: http://url.com:57555/\r
Content-Type: application/x-www-form-urlencoded\r
Content-Length: 32\r
Connection: close\r
Cookie: PHPSESSID=some_cookie\r
Upgrade-Insecure-Requests: 1\r
\r\n"""

payload = headers + body

s.sendall(payload.encode('utf-8'))
res = s.recv(4096)

print(str(res, errors='replace'))

Result...

python3 emdee5.py
HTTP/1.1 200 OK
Date: Sun, 26 May 2019 22:01:26 GMT
Server: Apache/2.4.18 (Ubuntu)
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 282
Connection: close
Content-Type: text/html; charset=UTF-8

]�1o� ���
ʒ��Ҩ��b�V��LN��
p�$����Py��d��FP��l�    ^�֞i�ĜmA��F7i�zd}��VͩK8}ߠ���!�n�W>�wL9ۅr�@Ȑ����� 4i��ec{"%��0���)������W���A�I��"��GD�;�܉"J��JA}x��l1��3٠.y�>Om�#5��9
                                                                                ��ڨ�p�j����JN���MQ̀)�:�p�P{K���4J^-��+�7�oV'E;'=�����l�

Body:
Your request explicitly says that you are willing to accept a compressed response:

 Accept-Encoding: gzip, deflate\r

And this is therefore what you get in the response

Content-Encoding: gzip

So, the body is compressed with gzip (which explains the garbled output) and you would need to decompress it. Given that you currently don't seem to be able to properly deal with compressed responses you should not claim in your request that you support these, i.e. remove the Accept-Encoding.

Apart from that more is likely wrong with your request:

body = "hash="+md5
...
Content-Length: 32\r
...
payload = headers + body
...

Given that md5 is 32 characters hex (or 16 byte binary) the body consisting of "hash"=+md5 is likely not 32 characters long as you claim in your Content-Length.

POST / HTTP/1.1\r

Additionally you send a HTTP/1.1 request so you have to be able to deal with chunked responses - but your code does not deal with these.

res = s.recv(4096)

Similarly your code blindly assumes that the full response can be retrieved within a single recv which does not need to be the case.

In summary: unless you have a deeper understanding of how HTTP works (which you do not seem to have) it is recommended that you use existing libraries to handle HTTP for you, since these were written by developers who have an understanding of HTTP.

And even if you already have an understanding of HTTP you'll likely will use these libraries anyway since you'll know that HTTP is far from trivial and that it makes no sense to implement all the necessary details and edge cases by yourself in your code if something robust already exists.


答:
You can use an infinite loop and every time check for the input. If the input is q or Q, then break the loop.</p>

```<code>String input = null;
while(true) {
  input = keyboard.next();
  if("q".equalsIgnoreCase(input)) break;
  validISBN(isbnNumber);
}
</code>```

Title: How can I make my program still run after running once

Body:
You can use an infinite loop and every time check for the input. If the input is q or Q, then break the loop.

String input = null;
while(true) {
  input = keyboard.next();
  if("q".equalsIgnoreCase(input)) break;
  validISBN(isbnNumber);
}


问:
What's the correct way to pause the entire script execution contingent on an asynchronous function in JavaScript?
A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

```<code>let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT
</code>```

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

答:
You only have one thread to work with, so there's no getting around the fact that you need to perform the async fetch of you config and then get on with the rest of your program. Most javascript is event driven, so this isn't typically a big issue. You can write in a style where the primary entrance to your code is a main() function, then you can just call it with the config after it's fetched:

```<code>fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(main);

function main(config){
  // do stuff

}
</code>```

Any substantially large code-base will be refactored into smaller functions anyway, so ideally your main function should not really be that large to begin with.

Body:
A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

Body:
You only have one thread to work with, so there's no getting around the fact that you need to perform the async fetch of you config and then get on with the rest of your program. Most javascript is event driven, so this isn't typically a big issue. You can write in a style where the primary entrance to your code is a main() function, then you can just call it with the config after it's fetched:

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(main);

function main(config){
  // do stuff

}

Any substantially large code-base will be refactored into smaller functions anyway, so ideally your main function should not really be that large to begin with.


问:
Scheduling & DST
I am writing a calendar/scheduling app in PHP. Right now I take the day of the week you want the event to occur on and the time. I also ask for the timezone and adjust accordingly to get the event time in GMT.

Then I store that time as an offset from midnight of the day of the show. This is fine and works great, but what happens when I hit daylight savings time?  I'm not sure what to do when that happens.  The other problem is that not all countries have DST so I'm kind of in a bind there.

I am displaying these events on a calendar, so timing is important.

答:
Dealing with DST is a real pain.

For future events you should store the location and the local time when the event is to occur, not the GMT time. This is because sometimes governments change when DST starts and stops (it just happened last year in the US) and the events then shift in GMT, but not in local time.

Then if you need to notify when the event is occurring, every day collect the events for the next 24-48 hrs and convert their times to GMT then. To do that, you need a location-timezone database like this one. Get the GMT offset for each location at the time of the event and use that to convert the time to GMT, then you know exactly when the event will occur.

OwnerDisplayName: Gavin Schulz

Title: Scheduling & DST


问:
Issue with TreeView in an ASP.NET master page
If I click the treeview in master page's leftside menu, the file should open in contect place holder (main). Below is my code.</p>

```<code><form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:TreeView ID="TreeView1" runat="server">
                    <Nodes>
                        <asp:TreeNode Expanded="True" Text="Sample Links" Value="Sample Links">
                            <asp:TreeNode NavigateUrl="~/one.htm" Target="fmain" Text="First Node"
                                Value="First Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/two.htm" Target="fmain" Text="Second Node"
                                Value="Second Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/three.htm" Target="fmain" Text="Third Node"
                                Value="Third Node"></asp:TreeNode>
                        </asp:TreeNode>
                    </Nodes>
                </asp:TreeView>
            </td>
            <td>
                <asp:ContentPlaceHolder id="tmain" runat="server">
                </asp:ContentPlaceHolder>
            </td>
        </tr>
    </table>
</form>
</code>```

答:
```<code>protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
    Response.Redirect("Here goes the code that process the TreeView1.SelectedNode to get the appropriate URL");
}
</code>```

Body:
If I click the treeview in master page's leftside menu, the file should open in contect place holder (main). Below is my code.

<form id="form1" runat="server">

                <asp:TreeView ID="TreeView1" runat="server">
                    <Nodes>
                        <asp:TreeNode Expanded="True" Text="Sample Links" Value="Sample Links">
                            <asp:TreeNode NavigateUrl="~/one.htm" Target="fmain" Text="First Node"
                                Value="First Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/two.htm" Target="fmain" Text="Second Node"
                                Value="Second Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/three.htm" Target="fmain" Text="Third Node"
                                Value="Third Node"></asp:TreeNode>
                        </asp:TreeNode>
                    </Nodes>
                </asp:TreeView>

                <asp:ContentPlaceHolder id="tmain" runat="server">
                </asp:ContentPlaceHolder>

</form>


问:
Receiving error; AttributeError: 'NoneType' object has no attribute 'app' while using render_template in return statement
I am trying to display the plotted figure using the web browser. But the render template in return statement is throwing error. Below is the code used and the error received.

The python code:

```<code>from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,template_folder = 'D:/DATA_SETS')

@app.route('/html_example')
def myplot():
    with app.app_context():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig('D:/DATA_SETS/new_plot.png')
        return Response(render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))

f = myplot()

if 1 == 1:
    app.run(debug=True)
</code>```

The template template_1.html

```<code><!doctype html>
<html>
   <body>

      <h1>Performance</h1>

        <p>{{ name }}</p>

        <img src={{ url}} alt="Chart" height="42" width="42">

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

Expected : The image return from function should be displayed in the HTML format written.

Current : The webpage is displaying 'Not Found Error'.
Webpage looking at is 'http://localhost:5000/html_example'

答:
You need to wrap your code into with app.app_context function. Your code will be similar to this:</p>

```<code>app = Flask(__name__,template_folder = 'templates')

@app.route('/')
def myplot():
    with app.app_context():
       plt.figure()
       t = range(0,6,1)
       x= np.sin(t)
       plt.plot(t,x)
       plt.savefig('D:/DATA_SETS/new_plot.png')
       return Response(render_template('template_1.html', name = 'new_plot',
       url ='D:/DATA_SETS/new_plot.png'))

if __name__ == '__main__':
    app.run(debug=True)
</code>```

Body:
I am trying to display the plotted figure using the web browser. But the render template in return statement is throwing error. Below is the code used and the error received.

The python code:

from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,template_folder = 'D:/DATA_SETS')

@app.route('/html_example')
def myplot():
    with app.app_context():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig('D:/DATA_SETS/new_plot.png')
        return Response(render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))

f = myplot()

if 1 == 1:
    app.run(debug=True)

The template template_1.html

<!doctype html>

Performance

{{ name }}

Expected : The image return from function should be displayed in the HTML format written.

Current : The webpage is displaying 'Not Found Error'.
Webpage looking at is 'http://localhost:5000/html_example'

Body:
You need to wrap your code into with app.app_context function. Your code will be similar to this:

app = Flask(__name__,template_folder = 'templates')

@app.route('/')
def myplot():
    with app.app_context():
       plt.figure()
       t = range(0,6,1)
       x= np.sin(t)
       plt.plot(t,x)
       plt.savefig('D:/DATA_SETS/new_plot.png')
       return Response(render_template('template_1.html', name = 'new_plot',
       url ='D:/DATA_SETS/new_plot.png'))

if __name__ == '__main__':
    app.run(debug=True)


问:
CBC mode AES encryption problem with Pycrypto
I have the following code running like a charm

```<code>from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

key = b'Sixteen byte key'
data = 'some text to encrypt'.encode("UTF-8")
data = pad(data, AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC)
iv = encryptor.IV
decryptor = AES.new(key, AES.MODE_CBC, IV=iv)

ciphertext = encryptor.encrypt(data)
print(ciphertext)
plaintext = decryptor.decrypt(ciphertext)
print(unpad(plaintext, 16))
</code>```

But when I try to convert to a function I got an padding error. My adapted code is

```<code>def cbc(msg, op):
    key = b'Sixteen byte key'
    encryptor = AES.new(key, AES.MODE_CBC)
    iv = encryptor.IV
    decryptor = AES.new(key, AES.MODE_CBC, IV=iv)
    if op == 1:
        data = msg.encode("UTF-8")
        data = pad(data, AES.block_size)
        ciphertext = encryptor.encrypt(data)
        print(ciphertext)
    else:
        plaintext = decryptor.decrypt(msg)
        print(unpad(plaintext, 16))
</code>```

My log is

```<code>Traceback (most recent call last):
  File "D:/Google Drive/max/AES.py", line 48, in <module>
    cbc(b'*\xd3\xc1Y\xc2f;\xf0\xc0@\xd9E\xc5x\x11\xb4', 2)
  File "D:/Google Drive/max/AES.py", line 19, in cbc
    print(unpad(plaintext, 16))
  File "C:\Users\Evilmaax\AppData\Local\Programs\Python\Python36\lib\site-packages\Crypto\Util\Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.
</code>```

Error occurs in else statement when I try to decrypt a byte message like *\xd3\xc1Y\xc2f;\xf0\xc0@\xd9E\xc5x\x11\xb4. Important: This message was generated by the if statement of same function.

Does anyone know why this happens?
__________________________________________________________

EDIT:  Using Rob Napier's tip (thank you so much) I solved the problem. If you experiencing the same issue, this is a functional version:

```<code>def cbc(key, data, op):
if op == 1:
    cipher = AES.new(key, AES.MODE_CBC, iv)
    data = key.encrypt(data)
    print(f"Coded text: {data}")
else:
    decipher = AES.new(key, AES.MODE_CBC, IV=iv)
    print(f'Plaintext: {unpad(decipher.decrypt(data), BLOCK_SIZE).decode("utf-8")}')
</code>```

答:
You're generating a random IV, which is good, but you then throw it away, which means you can't decrypt the data.

This line creates an encryptor with a random IV:

```<code>encryptor = AES.new(key, AES.MODE_CBC)
</code>```

This line creates a decryptor with the same IV:

```<code>decryptor = AES.new(key, AES.MODE_CBC, IV=iv)
</code>```

That's fine in your initial code, but you don't save the IV anywhere, so when you put it in a function which you call twice, you're trying to decrypt with a different IV than you encrypted with.

You need to save the IV as part of the cipher text, and use it during decryption. If you want an example of such a format, see the RNCryptor spec, and if you want to see an example in Python, see RNCryptor-python.

Body:
I have the following code running like a charm

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

key = b'Sixteen byte key'
data = 'some text to encrypt'.encode("UTF-8")
data = pad(data, AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC)
iv = encryptor.IV
decryptor = AES.new(key, AES.MODE_CBC, IV=iv)

ciphertext = encryptor.encrypt(data)
print(ciphertext)
plaintext = decryptor.decrypt(ciphertext)
print(unpad(plaintext, 16))

But when I try to convert to a function I got an padding error. My adapted code is

def cbc(msg, op):
    key = b'Sixteen byte key'
    encryptor = AES.new(key, AES.MODE_CBC)
    iv = encryptor.IV
    decryptor = AES.new(key, AES.MODE_CBC, IV=iv)
    if op == 1:
        data = msg.encode("UTF-8")
        data = pad(data, AES.block_size)
        ciphertext = encryptor.encrypt(data)
        print(ciphertext)
    else:
        plaintext = decryptor.decrypt(msg)
        print(unpad(plaintext, 16))

My log is

Traceback (most recent call last):
  File "D:/Google Drive/max/AES.py", line 48, in <module>
    cbc(b'*\xd3\xc1Y\xc2f;\xf0\xc0@\xd9E\xc5x\x11\xb4', 2)
  File "D:/Google Drive/max/AES.py", line 19, in cbc
    print(unpad(plaintext, 16))
  File "C:\Users\Evilmaax\AppData\Local\Programs\Python\Python36\lib\site-packages\Crypto\Util\Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.

Error occurs in else statement when I try to decrypt a byte message like *\xd3\xc1Y\xc2f;\xf0\xc0@\xd9E\xc5x\x11\xb4. Important: This message was generated by the if statement of same function.

Does anyone know why this happens?
__________________________________________________________

EDIT:  Using Rob Napier's tip (thank you so much) I solved the problem. If you experiencing the same issue, this is a functional version:

def cbc(key, data, op):
if op == 1:
    cipher = AES.new(key, AES.MODE_CBC, iv)
    data = key.encrypt(data)
    print(f"Coded text: {data}")
else:
    decipher = AES.new(key, AES.MODE_CBC, IV=iv)
    print(f'Plaintext: {unpad(decipher.decrypt(data), BLOCK_SIZE).decode("utf-8")}')

Body:
You're generating a random IV, which is good, but you then throw it away, which means you can't decrypt the data.

This line creates an encryptor with a random IV:

encryptor = AES.new(key, AES.MODE_CBC)

This line creates a decryptor with the same IV:

decryptor = AES.new(key, AES.MODE_CBC, IV=iv)

That's fine in your initial code, but you don't save the IV anywhere, so when you put it in a function which you call twice, you're trying to decrypt with a different IV than you encrypted with.

You need to save the IV as part of the cipher text, and use it during decryption. If you want an example of such a format, see the RNCryptor spec, and if you want to see an example in Python, see RNCryptor-python.


问:
need help reading a file into a binary tree
enter code hereok for a class project i need to make a spell checker. but first i need to read the txt file into the binary tree and I just can not figure it out can anyone help me

```<code>#include <iostream>

#include <string>

#include <fstream>

#include "Binarytree.h"

#include "Spellchecking.h"

using namespace std;

int main()
{

    string sentence;
    Binarytree bintree("");
    cout << "Please enter a sentence" << endl;
    cin >> sentence;

    string line;
    ifstream myfile("words_nonalpha.txt", ios::binary);
    /*if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }   */

    myfile.open("words_nonalpha.txt");

    return 0;
}
</code>```

ok, so I am about to put in my binary tree.h I thought that if I would add an ifstream and the name of the file it would work but it does not. sorry if my code is just terrible i just started this spring

```<code>#ifndef BINARY_TREE_H
#define BINARY_TREE_H

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

class Binarytree {
public:
    string value;
    Binarytree* left;
    Binarytree* right;
    ifstream myfile("words_nonalpha.txt");

    Binarytree(string value);

    void Add(string value);
    void Addall(vector<string>);
    void OutputAll();
    bool Find(string value, Binarytree*& returningNode);
    vector<bool> FindAll(vector<string>, vector<Binarytree*>&);
    void remove(string, bool);
    vector<string> TreetoVector();

    Binarytree* FindGreatest(Binarytree*);

private:
    void Add(Binarytree*& node, string value);
    void OutputAll(Binarytree* node);
    Binarytree* Find(Binarytree* node, string value);
    void remove(Binarytree*, string);
    Binarytree*& ParentTrap(Binarytree*, string);
    void TreetoVector(Binarytree*, vector<string>&);
    int Compare(string, string);
};
#endif
</code>```

答:
Apply The Single-responsibility Principle

Classes should follow the single responsibility principle, which states that

...  Every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. (Taken from wikipedia)

This means that your Binarytree class has one purpose and one purpose only: to act as a binary tree. This means that the Binarytree class shouldn't store a file or a stream object. If creating a binary tree from a file is a common operation, you can provide it as one of the constructors for Binarytree, but the Binarytree object shouldn't own the file.

Creating a binary tree from an input stream

Using the definition of a binary tree you gave in your original question, this is pretty simple! This is what the constructor would look like:

```<code>BinaryTree::Binarytree(std::istream& source) {
    std::string word;
    while(source >> word) // This returns true if a word was read successfully
    {
        this->Add(word);
    }
}
</code>```

This constructor will accept an std::ifstream, or you could read directly from std::cin.

Body:
enter code hereok for a class project i need to make a spell checker. but first i need to read the txt file into the binary tree and I just can not figure it out can anyone help me

#include <iostream>

#include <string>

#include <fstream>

#include "Binarytree.h"

#include "Spellchecking.h"

using namespace std;

int main()
{

    string sentence;
    Binarytree bintree("");
    cout << "Please enter a sentence" << endl;
    cin >> sentence;

    string line;
    ifstream myfile("words_nonalpha.txt", ios::binary);
    /*if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }   */

    myfile.open("words_nonalpha.txt");

    return 0;
}

ok, so I am about to put in my binary tree.h I thought that if I would add an ifstream and the name of the file it would work but it does not. sorry if my code is just terrible i just started this spring

#ifndef BINARY_TREE_H
#define BINARY_TREE_H

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

class Binarytree {
public:
    string value;
    Binarytree* left;
    Binarytree* right;
    ifstream myfile("words_nonalpha.txt");

    Binarytree(string value);

    void Add(string value);
    void Addall(vector<string>);
    void OutputAll();
    bool Find(string value, Binarytree*& returningNode);
    vector<bool> FindAll(vector<string>, vector<Binarytree*>&);
    void remove(string, bool);
    vector<string> TreetoVector();

    Binarytree* FindGreatest(Binarytree*);

private:
    void Add(Binarytree*& node, string value);
    void OutputAll(Binarytree* node);
    Binarytree* Find(Binarytree* node, string value);
    void remove(Binarytree*, string);
    Binarytree*& ParentTrap(Binarytree*, string);
    void TreetoVector(Binarytree*, vector<string>&);
    int Compare(string, string);
};
#endif

Body:
Apply The Single-responsibility Principle

Classes should follow the single responsibility principle, which states that

...  Every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. (Taken from wikipedia)

This means that your Binarytree class has one purpose and one purpose only: to act as a binary tree. This means that the Binarytree class shouldn't store a file or a stream object. If creating a binary tree from a file is a common operation, you can provide it as one of the constructors for Binarytree, but the Binarytree object shouldn't own the file.

Creating a binary tree from an input stream

Using the definition of a binary tree you gave in your original question, this is pretty simple! This is what the constructor would look like:

BinaryTree::Binarytree(std::istream& source) {
    std::string word;
    while(source >> word) // This returns true if a word was read successfully
    {
        this->Add(word);
    }
}

This constructor will accept an std::ifstream, or you could read directly from std::cin.


问:
BrowserStack script fails with MaxRetryError
The script from https://www.browserstack.com/automate/python

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
    'browser': 'Chrome',
    'browser_version': '62.0',
    'os': 'Windows',
    'os_version': '10',
    'resolution': '1024x768',
    'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor='http://servinc1:key@hub.browserstack.com:80/wd/hub',
    desired_capabilities=desired_cap)

driver.get("http://www.google.com")
if not "Google" in driver.title:
    raise Exception("Unable to load google page!")
elem = driver.find_element_by_name("q")
elem.send_keys("BrowserStack")
elem.submit()
print driver.title
driver.quit()
</code>```

failed with

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='hub.browserstack.com', port=80): Max retries exceeded with url: /wd/hub/session (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))

on a system with a localhost HTTP proxy. The proxy is configured with the {http,https}_proxy environment variables: using requests works:

```<code>import requests
r = requests.get('https://api.github.com/events')
</code>```

and allowing connections to hub.browserstack.com also works.

The aim is to use BrowserStack with a local proxy. How is this fixed?

答:
Since your use-case involves sending traffic to the BrowserStack Hub using proxy, you will need to specify the proxy details in your code snippet as below-

```<code>//Set the appropriate proxy environment variable (HTTP_PROXY if it is a HTTP proxy, HTTPS_PROXY if it is a HTTPS proxy, etc.) before running the tests.
//You can set this as follows:

export HTTP_PROXY='http://<proxyhost>:<proxyport>'
</code>```

You can read more on this here- https://www.browserstack.com/automate/python#proxy

Body:
The script from https://www.browserstack.com/automate/python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
    'browser': 'Chrome',
    'browser_version': '62.0',
    'os': 'Windows',
    'os_version': '10',
    'resolution': '1024x768',
    'name': 'Bstack-[Python] Sample Test'
}

driver = webdriver.Remote(
    command_executor='http://servinc1:key@hub.browserstack.com:80/wd/hub',
    desired_capabilities=desired_cap)

driver.get("http://www.google.com")
if not "Google" in driver.title:
    raise Exception("Unable to load google page!")
elem = driver.find_element_by_name("q")
elem.send_keys("BrowserStack")
elem.submit()
print driver.title
driver.quit()

failed with

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='hub.browserstack.com', port=80): Max retries exceeded with url: /wd/hub/session (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))

on a system with a localhost HTTP proxy. The proxy is configured with the {http,https}_proxy environment variables: using requests works:

import requests
r = requests.get('https://api.github.com/events')

and allowing connections to hub.browserstack.com also works.

The aim is to use BrowserStack with a local proxy. How is this fixed?

Body:
Since your use-case involves sending traffic to the BrowserStack Hub using proxy, you will need to specify the proxy details in your code snippet as below-

//Set the appropriate proxy environment variable (HTTP_PROXY if it is a HTTP proxy, HTTPS_PROXY if it is a HTTPS proxy, etc.) before running the tests.
//You can set this as follows:

export HTTP_PROXY='http://<proxyhost>:<proxyport>'

You can read more on this here- https://www.browserstack.com/automate/python#proxy


问:
Datatable is not working when there is data from DB
Jquery datatable plugin is not working when it has data that selected from database by date. But it's working if there is no data in table. Here some code

Select all data from database table in controller :

```<code>$inbound['inbound'] = DB::table('REPORT_INBOUND')
    ->where('regdate', '=', date('Y-m-d', strtotime("2019-05-21")))
    ->get();
return view('/traffic', $inbound, $outbound);
</code>```

And i did copy paste that necessary scripts for example :

```<code><link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</code>```

```<code><table id="ahhhaa" width="90%" class="table table-striped table-bordered table-hover display">
            <thead class="thead-light">
            <tr>
                <th>ID</th>
                <th>RegDate</th>
                <th>HPMN Code</th>
                <th>Country</th>
                <th>HPMN Name</th>
            </tr>
            </head>
            <tbody>
            @foreach($inbound as $value)
                <tr class="table table-hover">
                    <td>{{ $value->id }}</td>
                    <td>{{ $value->regdate }}</td>
                    <td>{{ $value->hpmn_code }}</td>
                    <td>{{ $value->country }}</td>
                    <td>{{ $value->hpmn_name }}</td>
            @endforeach
            </tbody>
</table>
</code>```

```<code>$(document).ready(function () {
   $('#ahhhaa').DataTable()
});
</code>```

Is there any error ?

答:
Maybe because u did not close your thead.

Fix this and comment if not solved .

```<code><table id="ahhhaa" width="90%" class="table table-striped table-bordered table-hover
display">
        <thead class="thead-light">
        <tr>
            <th>ID</th>
            <th>RegDate</th>
            <th>HPMN Code</th>
            <th>Country</th>
            <th>HPMN Name</th>
        </tr>
        </thead><!-- Add this Line -->
        <tbody>
            loop...
        </tbody>
</code>```

Hope this works !

Body:
Jquery datatable plugin is not working when it has data that selected from database by date. But it's working if there is no data in table. Here some code

Select all data from database table in controller :

$inbound['inbound'] = DB::table('REPORT_INBOUND')
    ->where('regdate', '=', date('Y-m-d', strtotime("2019-05-21")))
    ->get();
return view('/traffic', $inbound, $outbound);

And i did copy paste that necessary scripts for example :

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

                ID
                RegDate
                HPMN Code
                Country
                HPMN Name

            @foreach($inbound as $value)

                    {{ $value->id }}
                    {{ $value->regdate }}
                    {{ $value->hpmn_code }}
                    {{ $value->country }}
                    {{ $value->hpmn_name }}
            @endforeach

$(document).ready(function () {
   $('#ahhhaa').DataTable()
});

Is there any error ?

Body:
Maybe because u did not close your thead.

Fix this and comment if not solved .

<table id="ahhhaa" width="90%" class="table table-striped table-bordered table-hover
display">
        <thead class="thead-light">
        <tr>
            <th>ID</th>
            <th>RegDate</th>
            <th>HPMN Code</th>
            <th>Country</th>
            <th>HPMN Name</th>
        </tr>
        </thead><!-- Add this Line -->
        <tbody>
            loop...
        </tbody>

Hope this works !


问:
Create a variable from a Remote Ping Response IP Address
I need to be able to ping a range of IP addresses and when I get a reply on one, then capture that IP to put in a variable which I can use to update the local computers host file.

The purpose of this script is to be used for a Point-to-Site Azure VPN service. A remote server is connecting as a client and is given a second IP address which changes on each connection. The other server can only communicate to the remote server on this IP address, but the application it uses only uses DNS Names, so I will need to update the hosts file with the connecting servers IP each time it dials in.

```<code>$subnet = "172.16.201.0"
$start = 1
$end = 10
$ping = 1
while ($start -le $end) {
$IP = "172.16.201.$start"
Write-Host "Pinging $IP" -ForegroundColor Cyan
Test-Connection -ComputerName $IP -count 1 -Quiet
$start++
}
</code>```

So far the above code only does a IP Sweep and outputs the success/failure of each IP. I need to capture the success IP and put that in a variable

答:
i presume you want only the 1st responding IP address, not all the addresses in the range. [grin] you can turn this into a function fairly easily. you can also turn OFF the verbose output by commenting out the 2nd line.

```<code>$Old_VPref = $VerbosePreference
$VerbosePreference = 'Continue'

$Subnet = '192.168.1'
$RangeStart = 60
$RangeEnd = 69

$1stRespondingIPv4 = foreach ($Octet in $RangeStart..$RangeEnd)
    {
    $IP = $Subnet, $Octet -join '.'
    $WV_Msg = 'Testing {0} ...' -f $IP
    Write-Verbose -Message $WV_Msg
    $Pingable = Test-Connection -ComputerName $IP -Count 1 -Quiet

    if ($Pingable)
        {
        $IP
        # the next line stops the foreach loop
        break
        }
    }

''
$1stRespondingIPv4

$VerbosePreference = $Old_VPref
</code>```

output ...

```<code>VERBOSE: Testing 192.168.1.60 ...
VERBOSE: Testing 192.168.1.61 ...
VERBOSE: Testing 192.168.1.62 ...
VERBOSE: Testing 192.168.1.63 ...
VERBOSE: Testing 192.168.1.64 ...

192.168.1.64
</code>```

Body:
I need to be able to ping a range of IP addresses and when I get a reply on one, then capture that IP to put in a variable which I can use to update the local computers host file.

The purpose of this script is to be used for a Point-to-Site Azure VPN service. A remote server is connecting as a client and is given a second IP address which changes on each connection. The other server can only communicate to the remote server on this IP address, but the application it uses only uses DNS Names, so I will need to update the hosts file with the connecting servers IP each time it dials in.

$subnet = "172.16.201.0"
$start = 1
$end = 10
$ping = 1
while ($start -le $end) {
$IP = "172.16.201.$start"
Write-Host "Pinging $IP" -ForegroundColor Cyan
Test-Connection -ComputerName $IP -count 1 -Quiet
$start++
}

So far the above code only does a IP Sweep and outputs the success/failure of each IP. I need to capture the success IP and put that in a variable

Body:
i presume you want only the 1st responding IP address, not all the addresses in the range. [grin] you can turn this into a function fairly easily. you can also turn OFF the verbose output by commenting out the 2nd line.

$Old_VPref = $VerbosePreference
$VerbosePreference = 'Continue'

$Subnet = '192.168.1'
$RangeStart = 60
$RangeEnd = 69

$1stRespondingIPv4 = foreach ($Octet in $RangeStart..$RangeEnd)
    {
    $IP = $Subnet, $Octet -join '.'
    $WV_Msg = 'Testing {0} ...' -f $IP
    Write-Verbose -Message $WV_Msg
    $Pingable = Test-Connection -ComputerName $IP -Count 1 -Quiet

    if ($Pingable)
        {
        $IP
        # the next line stops the foreach loop
        break
        }
    }

''
$1stRespondingIPv4

$VerbosePreference = $Old_VPref

output ...

VERBOSE: Testing 192.168.1.60 ...
VERBOSE: Testing 192.168.1.61 ...
VERBOSE: Testing 192.168.1.62 ...
VERBOSE: Testing 192.168.1.63 ...
VERBOSE: Testing 192.168.1.64 ...

192.168.1.64


问:
How to check if all array values are blank in Javascript
I have an array like:

```<code>["", "", "", "1", "", ""]
</code>```

I want to alert when all the array values are blanks, i.e, when the array is like this:

```<code>["", "", "", "", "", ""]
</code>```

How can I achieve this.

Body:
I have an array like:

["", "", "", "1", "", ""]

I want to alert when all the array values are blanks, i.e, when the array is like this:

["", "", "", "", "", ""]

How can I achieve this.

Body:
Use every():

const allEmpty = arr => arr.every(e => e === "");
console.log(allEmpty(["", "", "", "1", "", ""]));
console.log(allEmpty(["", "", "", "", "", ""]));


问:
Pip on only installs to python27 while i need it to install on python37
I have multiple instances of python in my computer namely python27, python3.6 and python 3.7.

The import module for docx worked daily on python27 until suddenly it stopped working today. I tried installing the module again using pip in windows command line.

It says only installed in python27 directory. But there's an
  importError on my script.

I guess I should be high time i transferred into python37 but I can't seem to make pip install into python 3.7

Can someone offer some advice as to the messy situation I'm in?
I want to transfer to python3 and install docx in python3

Already checked modules using pip and docx is not there.

答:
for python 3 try below given approaches.

```<code>sudo apt-get install python3-pip
</code>```

this should get you pip3 and you can use pip3 to install packages specific to python3

and also

```<code>python3 -m pip install  <package name>
</code>```

Body:
for python 3 try below given approaches.

sudo apt-get install python3-pip

this should get you pip3 and you can use pip3 to install packages specific to python3

and also

python3 -m pip install  <package name>


答:
Try this,

```<code>["", "", "", "", "", ""].join("").length==0
</code>```

If you want to remove spaces,

```<code>["", "", "", "", "", ""].join("").replace(/\s/gi,'').length==0
</code>```

Note :

This will not work for inputs like  ["", [], "", null, undefined, ""]

Title: How to check if all array values are blank in Javascript

Body:
Try this,

["", "", "", "", "", ""].join("").length==0

If you want to remove spaces,

["", "", "", "", "", ""].join("").replace(/\s/gi,'').length==0

Note :

This will not work for inputs like  ["", [], "", null, undefined, ""]