问:
Is there a way to put these images in an array?
Im a student and currently working on a project, I am definitely a beginner and am struggling with this project as I am not that familiar with arrays. My HTML, CSS, and Javascript is all listed. Basically what I want to do is somehow keep my click function working and then incorporate the code I have commented out so that it recognizes its at the bottom of each array and stop but I have no idea how to do that. Any input would be much appreciated!!

let currentPlayer = "deer";
let column1 = [0, 0, 0, 0, 0, 0, 0];
let column2 = [0, 0, 0, 0, 0, 0, 0];
let column3 = [0, 0, 0, 0, 0, 0, 0];
let column4 = [0, 0, 0, 0, 0, 0, 0];
let column5 = [0, 0, 0, 0, 0, 0, 0];
let column6 = [0, 0, 0, 0, 0, 0, 0];
let column7 = [0, 0, 0, 0, 0, 0, 0];
const board = [column1, column2, column3, column4, column5, column6, column7];
//if clicked in the column drop the item to the end of the array
//dont allow anything else to drop on to the item in its place
//for loop- look for first empty spot from the bottom????
//board[0][0] is the board column 1 and row 1
// let row = $(this).attr("row");
// let col = $(this).attr("col");
// board[row][col];

$(".cell").on("click", function () {
  if (currentPlayer == "deer" && $(this).hasClass(".taken1" || ".taken2")) {
    ("");
  } else if (currentPlayer == "deer") {
    $(this).html(
      ''
    );
    $(this).addClass(".taken1");
    playerChange();
  }
  if (currentPlayer == "tree" && $(this).hasClass(".taken1" || ".taken2")) {
    ("");
  } else if (currentPlayer == "tree") {
    $(this).html(
      ''
    );
    $(this).addClass(".taken2");
    playerChange();
  }
});

function playerChange() {
  if (currentPlayer === "deer") {
    //if current player is deer, then switch to tree
    currentPlayer = "tree";
  } else {
    currentPlayer = "deer"; //if current player is not deer then switch to deer
  }
  //PUT WINNER DECLARATION FUNCTION IN HERE
}

$("button").on("click", function () {
  //click function for restart game button
  $(".cell").html(""); //removes all added text from the cells
  $(".cell").removeClass(".taken1"); //removes the taken class from the cells
  $(".cell").removeClass(".taken2"); //removes the taken class from the cells
  $("div.container").css("pointer-events", "all"); //returns click events to normal
  if (currentPlayer == "tree") {
    playerChange(); //changes back to player deer so tree doesnt play first
  }
  //UPDATE CLICK FUNCTION AS NEW THINGS ARE ADDED FOR WINS!
});

//WRITE WINNING CONDITIONS DOWN HERE DONT FORGET HAHAHA```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*general page styling*/
body {
    background-image: url('https://images.hdqwalls.com/wallpapers/minimalist-landscape-to.jpg');
    font-family: 'Amatic SC', cursive;
}

/*page heading styling*/
h1 {
    font-size: 75px;
    align-items: center;
    text-align: center;
    text-shadow: 2px 2px #412846;
    color: white;
}

/*help with centering*/
section {
    text-align: center;
    justify-content: center;
}

/*styling for button*/
button {
    transition-duration: 0.4s;
    background-color: rgb(78, 29, 214);
    font-family: 'Amatic SC', cursive;
    color: white;
    text-align: center;
    padding: 5px 5px;
    border: none;
    text-decoration: none;
    font-size: 30px;
    text-shadow: 1px 1px 1px rgb(24, 0, 70);
    box-shadow: 0 10px 15px 0 rgb(24, 0, 70);
    outline: none;
}

/*styling for button hover*/
button:hover {
    box-shadow: 0 10px 15px 0 rgb(24, 0 , 70);
    background-color: rgb(192, 128, 252);
    color: rgb(24, 0, 70);
}

/*styling for footer*/
footer {
    font-size: 20px;
    bottom: 0;
    width: 100%;
    height: 0%;
    color: rgb(218, 198, 255);
    padding-top: 15px;
}

/*styling for connect 4 board*/
.container {
    display: grid;
    grid-template-columns: repeat(7, auto);
    width: 600px;
    margin: 50px auto;
    justify-content: center;
    align-items: center;
    text-align: center;
}

/*styling for individual cells on board*/
.cell {
    font-family: 'Major Mono Display', monospace;
    width: 100px;
    height: 100px;
    border: 1px solid rgb(218, 198, 255);
    font-size: 20px;
    color: rgb(24, 0, 70);
    display: flex;
    justify-content: center;
    text-align: center;
    align-items: center;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Major+Mono+Display&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />

    <title>c o n n e c t 4</title>

C O N N E C T 4

      <button>Restart Game</button>

      Made by Falon B. Landers

```

答:
Your existing code would require a bit of a refactor, some suggestions:

Set some variables for numRows = X and numCols = Y. Use those to generate your board arrow.

const numRows = 7;
const numCols = numRows;
const board = Array.from(Array(numCols), c => Array(numRows).fill(0));
console.log(board);```
</div>
</div>
</p>

<ul>
<li><p>Write a function to generate the HTML of your board from the state of that array and place it into the page (rather than hard coding all the divs).</p>

<ul>
<li>Use <code>data-*</code> attributes to label your divs as row and col (e.g. <code>data-row="1"</code> not just <code>row="1"</code>).</li>
<li>Assign a class name to indicate who owns the square. Use CSS to place the image on that square (e.g. via <code>background-image</code>).</li>
</ul></li>
<li><p>Each time a player takes a space, set into your board array a value representing them (e.g. player 1 is <code>1</code>, player 2 is <code>-1</code> or whatever you'd like).</p></li>
<li><p>Each time there is a change to the board, recall your "generate board HTML" function to produce an up-to-date. It can clear a containing div and repopulate the board's current state.</p></li>
</ul>

<p>If you get stuck or I can add additional detail if you have particular questions, let me know.</p>

<hr>

<p>EDIT: An incomplete, but functional example to demonstrate:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const noPlayer = 0;
let currentPlayer = 1;

const numRows = 7;
const numCols = numRows;
const board = Array.from(Array(numCols), c => Array(numRows).fill(0));

function playerChange() {
  currentPlayer = -currentPlayer;
}

const playerClasses = {
  [-1]: `tree`,
  [noPlayer]: `none`,
  [1]: `deer`,
};

function drawBoard() {
  const $container = $('.container');
  $container.html('');
  for (let rIdx = 0; rIdx < numRows; rIdx++) {
    board.forEach((c, cIdx) => {
      const playerId = c[rIdx];
      const playerClass = playerClasses[playerId];
      $container.append(`<div data-row="${rIdx}" data-col="${cIdx}" class="cell ${playerClass}"></div>`);
    });
  }
}
drawBoard();

$("button").on("click", function () {
  drawBoard();
  $("div.container").css("pointer-events", "all"); //returns click events to normal
  if (currentPlayer !== 1) {
    playerChange();
  }
});

$(".container").on("click", ".cell" , function (e) {
  const targetRow = $(e.currentTarget).data('row');
  const targetCol = $(e.currentTarget).data('col');
  const currentVal = board[targetCol][targetRow];
  if (currentVal !== noPlayer) {
    return;
  }
  const takenRow = board[targetCol].findIndex(x => x !== noPlayer);
  const lowestRow = takenRow === -1 ? numRows -1 : takenRow -1;
  board[targetCol][lowestRow] = currentPlayer;
  drawBoard();
  playerChange();
});</code>```

/*general page styling*/
body {
    background-image: url('https://images.hdqwalls.com/wallpapers/minimalist-landscape-to.jpg');
    font-family: 'Amatic SC', cursive;
}

/*page heading styling*/
h1 {
    font-size: 75px;
    align-items: center;
    text-align: center;
    text-shadow: 2px 2px #412846;
    color: white;
}

/*help with centering*/
section {
    text-align: center;
    justify-content: center;
}

/*styling for button*/
button {
    transition-duration: 0.4s;
    background-color: rgb(78, 29, 214);
    font-family: 'Amatic SC', cursive;
    color: white;
    text-align: center;
    padding: 5px 5px;
    border: none;
    text-decoration: none;
    font-size: 30px;
    text-shadow: 1px 1px 1px rgb(24, 0, 70);
    box-shadow: 0 10px 15px 0 rgb(24, 0, 70);
    outline: none;
}

/*styling for button hover*/
button:hover {
    box-shadow: 0 10px 15px 0 rgb(24, 0 , 70);
    background-color: rgb(192, 128, 252);
    color: rgb(24, 0, 70);
}

/*styling for footer*/
footer {
    font-size: 20px;
    bottom: 0;
    width: 100%;
    height: 0%;
    color: rgb(218, 198, 255);
    padding-top: 15px;
}

/*styling for connect 4 board*/
.container {
    display: grid;
    grid-template-columns: repeat(7, auto);
    width: 600px;
    margin: 50px auto;
    justify-content: center;
    align-items: center;
    text-align: center;
}

/*styling for individual cells on board*/
.cell {
    font-family: 'Major Mono Display', monospace;
    width: 100px;
    height: 100px;
    border: 1px solid rgb(218, 198, 255);
    font-size: 20px;
    color: rgb(24, 0, 70);
    display: flex;
    justify-content: center;
    text-align: center;
    align-items: center;
    background-repeat: no-repeat;
    background-size: 50px 50px;
    background-position: center;
}

.cell.deer {
  background-image: url('https://i.ya-webdesign.com/images/reindeer-black-antlers-png-picture-8.png');
}
.cell.tree {
  background-image: url('https://www.pngkey.com/png/full/24-242635_white-pine-tree-clipart-clipart-free-pine-tree.png');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Major+Mono+Display&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <script defer src="app.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <title>c o n n e c t 4</title>
  </head>
  <body>
    <section>
      <!--PAGE HEADING-->
      <h1>C O N N E C T 4</h1>
      <!--CONNECT 4 GAME BOARD-->
      <!--class cell for general-->
      <div class="container"></div>
      <!--RESTART GAME BUTTON-->
      <button>Restart Game</button>
      <!--PAGE FOOTER-->
      <footer>Made by Falon B. Landers</footer>
    </section>
  </body>
</html></code>```

Body:
Im a student and currently working on a project, I am definitely a beginner and am struggling with this project as I am not that familiar with arrays. My HTML, CSS, and Javascript is all listed. Basically what I want to do is somehow keep my click function working and then incorporate the code I have commented out so that it recognizes its at the bottom of each array and stop but I have no idea how to do that. Any input would be much appreciated!!

let currentPlayer = "deer";
let column1 = [0, 0, 0, 0, 0, 0, 0];
let column2 = [0, 0, 0, 0, 0, 0, 0];
let column3 = [0, 0, 0, 0, 0, 0, 0];
let column4 = [0, 0, 0, 0, 0, 0, 0];
let column5 = [0, 0, 0, 0, 0, 0, 0];
let column6 = [0, 0, 0, 0, 0, 0, 0];
let column7 = [0, 0, 0, 0, 0, 0, 0];
const board = [column1, column2, column3, column4, column5, column6, column7];
//if clicked in the column drop the item to the end of the array
//dont allow anything else to drop on to the item in its place
//for loop- look for first empty spot from the bottom????
//board[0][0] is the board column 1 and row 1
// let row = $(this).attr("row");
// let col = $(this).attr("col");
// board[row][col];

$(".cell").on("click", function () {
  if (currentPlayer == "deer" && $(this).hasClass(".taken1" || ".taken2")) {
    ("");
  } else if (currentPlayer == "deer") {
    $(this).html(
      ''
    );
    $(this).addClass(".taken1");
    playerChange();
  }
  if (currentPlayer == "tree" && $(this).hasClass(".taken1" || ".taken2")) {
    ("");
  } else if (currentPlayer == "tree") {
    $(this).html(
      ''
    );
    $(this).addClass(".taken2");
    playerChange();
  }
});

function playerChange() {
  if (currentPlayer === "deer") {
    //if current player is deer, then switch to tree
    currentPlayer = "tree";
  } else {
    currentPlayer = "deer"; //if current player is not deer then switch to deer
  }
  //PUT WINNER DECLARATION FUNCTION IN HERE
}

$("button").on("click", function () {
  //click function for restart game button
  $(".cell").html(""); //removes all added text from the cells
  $(".cell").removeClass(".taken1"); //removes the taken class from the cells
  $(".cell").removeClass(".taken2"); //removes the taken class from the cells
  $("div.container").css("pointer-events", "all"); //returns click events to normal
  if (currentPlayer == "tree") {
    playerChange(); //changes back to player deer so tree doesnt play first
  }
  //UPDATE CLICK FUNCTION AS NEW THINGS ARE ADDED FOR WINS!
});

//WRITE WINNING CONDITIONS DOWN HERE DONT FORGET HAHAHA

/*general page styling*/
body {
    background-image: url('https://images.hdqwalls.com/wallpapers/minimalist-landscape-to.jpg');
    font-family: 'Amatic SC', cursive;
}

/*page heading styling*/
h1 {
    font-size: 75px;
    align-items: center;
    text-align: center;
    text-shadow: 2px 2px #412846;
    color: white;
}

/*help with centering*/
section {
    text-align: center;
    justify-content: center;
}

/*styling for button*/
button {
    transition-duration: 0.4s;
    background-color: rgb(78, 29, 214);
    font-family: 'Amatic SC', cursive;
    color: white;
    text-align: center;
    padding: 5px 5px;
    border: none;
    text-decoration: none;
    font-size: 30px;
    text-shadow: 1px 1px 1px rgb(24, 0, 70);
    box-shadow: 0 10px 15px 0 rgb(24, 0, 70);
    outline: none;
}

/*styling for button hover*/
button:hover {
    box-shadow: 0 10px 15px 0 rgb(24, 0 , 70);
    background-color: rgb(192, 128, 252);
    color: rgb(24, 0, 70);
}

/*styling for footer*/
footer {
    font-size: 20px;
    bottom: 0;
    width: 100%;
    height: 0%;
    color: rgb(218, 198, 255);
    padding-top: 15px;
}

/*styling for connect 4 board*/
.container {
    display: grid;
    grid-template-columns: repeat(7, auto);
    width: 600px;
    margin: 50px auto;
    justify-content: center;
    align-items: center;
    text-align: center;
}

/*styling for individual cells on board*/
.cell {
    font-family: 'Major Mono Display', monospace;
    width: 100px;
    height: 100px;
    border: 1px solid rgb(218, 198, 255);
    font-size: 20px;
    color: rgb(24, 0, 70);
    display: flex;
    justify-content: center;
    text-align: center;
    align-items: center;
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Major+Mono+Display&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />

    <title>c o n n e c t 4</title>

C O N N E C T 4

      <button>Restart Game</button>

      Made by Falon B. Landers

Body:
Your existing code would require a bit of a refactor, some suggestions:

Set some variables for numRows = X and numCols = Y. Use those to generate your board arrow.

const numRows = 7;
const numCols = numRows;
const board = Array.from(Array(numCols), c => Array(numRows).fill(0));
console.log(board);

Write a function to generate the HTML of your board from the state of that array and place it into the page (rather than hard coding all the divs).

Use data-* attributes to label your divs as row and col (e.g. data-row="1" not just row="1").

Assign a class name to indicate who owns the square. Use CSS to place the image on that square (e.g. via background-image).

Each time a player takes a space, set into your board array a value representing them (e.g. player 1 is 1, player 2 is -1 or whatever you'd like).

Each time there is a change to the board, recall your "generate board HTML" function to produce an up-to-date. It can clear a containing div and repopulate the board's current state.

If you get stuck or I can add additional detail if you have particular questions, let me know.

EDIT: An incomplete, but functional example to demonstrate:

const noPlayer = 0;
let currentPlayer = 1;

const numRows = 7;
const numCols = numRows;
const board = Array.from(Array(numCols), c => Array(numRows).fill(0));

function playerChange() {
  currentPlayer = -currentPlayer;
}

const playerClasses = {
  [-1]: `tree`,
  [noPlayer]: `none`,
  [1]: `deer`,
};

function drawBoard() {
  const $container = $('.container');
  $container.html('');
  for (let rIdx = 0; rIdx < numRows; rIdx++) {
    board.forEach((c, cIdx) => {
      const playerId = c[rIdx];
      const playerClass = playerClasses[playerId];
      $container.append(`<div data-row="${rIdx}" data-col="${cIdx}" class="cell ${playerClass}"></div>`);
    });
  }
}
drawBoard();

$("button").on("click", function () {
  drawBoard();
  $("div.container").css("pointer-events", "all"); //returns click events to normal
  if (currentPlayer !== 1) {
    playerChange();
  }
});

$(".container").on("click", ".cell" , function (e) {
  const targetRow = $(e.currentTarget).data('row');
  const targetCol = $(e.currentTarget).data('col');
  const currentVal = board[targetCol][targetRow];
  if (currentVal !== noPlayer) {
    return;
  }
  const takenRow = board[targetCol].findIndex(x => x !== noPlayer);
  const lowestRow = takenRow === -1 ? numRows -1 : takenRow -1;
  board[targetCol][lowestRow] = currentPlayer;
  drawBoard();
  playerChange();
});

/*general page styling*/
body {
    background-image: url('https://images.hdqwalls.com/wallpapers/minimalist-landscape-to.jpg');
    font-family: 'Amatic SC', cursive;
}

/*page heading styling*/
h1 {
    font-size: 75px;
    align-items: center;
    text-align: center;
    text-shadow: 2px 2px #412846;
    color: white;
}

/*help with centering*/
section {
    text-align: center;
    justify-content: center;
}

/*styling for button*/
button {
    transition-duration: 0.4s;
    background-color: rgb(78, 29, 214);
    font-family: 'Amatic SC', cursive;
    color: white;
    text-align: center;
    padding: 5px 5px;
    border: none;
    text-decoration: none;
    font-size: 30px;
    text-shadow: 1px 1px 1px rgb(24, 0, 70);
    box-shadow: 0 10px 15px 0 rgb(24, 0, 70);
    outline: none;
}

/*styling for button hover*/
button:hover {
    box-shadow: 0 10px 15px 0 rgb(24, 0 , 70);
    background-color: rgb(192, 128, 252);
    color: rgb(24, 0, 70);
}

/*styling for footer*/
footer {
    font-size: 20px;
    bottom: 0;
    width: 100%;
    height: 0%;
    color: rgb(218, 198, 255);
    padding-top: 15px;
}

/*styling for connect 4 board*/
.container {
    display: grid;
    grid-template-columns: repeat(7, auto);
    width: 600px;
    margin: 50px auto;
    justify-content: center;
    align-items: center;
    text-align: center;
}

/*styling for individual cells on board*/
.cell {
    font-family: 'Major Mono Display', monospace;
    width: 100px;
    height: 100px;
    border: 1px solid rgb(218, 198, 255);
    font-size: 20px;
    color: rgb(24, 0, 70);
    display: flex;
    justify-content: center;
    text-align: center;
    align-items: center;
    background-repeat: no-repeat;
    background-size: 50px 50px;
    background-position: center;
}

.cell.deer {
  background-image: url('https://i.ya-webdesign.com/images/reindeer-black-antlers-png-picture-8.png');
}
.cell.tree {
  background-image: url('https://www.pngkey.com/png/full/24-242635_white-pine-tree-clipart-clipart-free-pine-tree.png');
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Major+Mono+Display&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <script defer src="app.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <title>c o n n e c t 4</title>
  </head>
  <body>
    <section>
      <!--PAGE HEADING-->
      <h1>C O N N E C T 4</h1>
      <!--CONNECT 4 GAME BOARD-->
      <!--class cell for general-->
      <div class="container"></div>
      <!--RESTART GAME BUTTON-->
      <button>Restart Game</button>
      <!--PAGE FOOTER-->
      <footer>Made by Falon B. Landers</footer>
    </section>
  </body>
</html>


来源: stackexchange

问:
Using URL parameter in Java Class
I want to make a basic "forgot password" system and I gave a random generated token for each user and stored it in database. The user has to enter his email on a form to request a link for the password reset. Then, he receives an email with a specific link like: http://localhost:8080/login/reset-password.jsp?token=fd6256666910438486e76760952ea71d where the parameter "token" retrieves the token value that is associated with his email in database.

Now, my question is, how can I get the password updated while getting the token value in URL?

I have tried to request the parameter from URL but I don't know what I'm missing here because when I'm debugging it shows me that reset_token is NULL and because of that, nothing is updated. Please help.

Here's my table:

```<code>CREATE TABLE user (
id bigint identity NOT NULL,
username varchar(50) NOT NULL,
email varchar(50) NOT NULL,
password varchar(50) NOT NULL,
attempts int DEFAULT 3,
state varchar(50) DEFAULT 'Active’,
reset_token varchar(50),
time_token TIMESTAMP,
PRIMARY KEY (id)
);
</code>```

Here's my servlet:

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String password = request.getParameter("password");
        String token = request.getParameter("token");

                ForgotPasswordHandler.UpdatePassword(password, token);

                String message = "Password changed!";
                request.setAttribute("message", message);
                request.getRequestDispatcher("reset-password.jsp?token=" + token).forward(request, response);

    }
</code>```

And this is the method from ForgotPasswordHandler.java:

```<code>public static void UpdatePassword(String password, String token) throws SQLException {

            PreparedStatement ps = null;
            try
            {
                if (con == null){
                    System.out.println("Failed connection");
                } else {
                    ps = con.prepareStatement(
                        "UPDATE user SET password = ? WHERE reset_token = ?");

                    ps.setString(1,password);
                    ps.setString(2,token);

                    ps.executeUpdate();

                   if (!con.getAutoCommit()) {
                      con.commit();
                   }
                }
            }
            catch (Exception e) {
                    e.printStackTrace(System.out);
            }
            finally {
                if (ps != null) {
                    ps.close();
                }
            }
</code>```

答:
So, after long hours searching, I figured out that the token parameter isn't retrieving anything because in a post request it gets values from the body and not from URL, so I simply added an hidden input inside the form like this:

```<code><input type="hidden" name="token" value="<%= request.getParameter("token")%>">
</code>```

And it worked perfectly. Hope this helps someone in the future.

ContentLicense: CC BY-SA 4.0

Title: Using URL parameter in Java Class

Body:
I want to make a basic "forgot password" system and I gave a random generated token for each user and stored it in database. The user has to enter his email on a form to request a link for the password reset. Then, he receives an email with a specific link like: http://localhost:8080/login/reset-password.jsp?token=fd6256666910438486e76760952ea71d where the parameter "token" retrieves the token value that is associated with his email in database.

Now, my question is, how can I get the password updated while getting the token value in URL?

I have tried to request the parameter from URL but I don't know what I'm missing here because when I'm debugging it shows me that reset_token is NULL and because of that, nothing is updated. Please help.

Here's my table:

CREATE TABLE user (
id bigint identity NOT NULL,
username varchar(50) NOT NULL,
email varchar(50) NOT NULL,
password varchar(50) NOT NULL,
attempts int DEFAULT 3,
state varchar(50) DEFAULT 'Active’,
reset_token varchar(50),
time_token TIMESTAMP,
PRIMARY KEY (id)
);

Here's my servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String password = request.getParameter("password");
        String token = request.getParameter("token");

                ForgotPasswordHandler.UpdatePassword(password, token);

                String message = "Password changed!";
                request.setAttribute("message", message);
                request.getRequestDispatcher("reset-password.jsp?token=" + token).forward(request, response);

    }

And this is the method from ForgotPasswordHandler.java:

public static void UpdatePassword(String password, String token) throws SQLException {

            PreparedStatement ps = null;
            try
            {
                if (con == null){
                    System.out.println("Failed connection");
                } else {
                    ps = con.prepareStatement(
                        "UPDATE user SET password = ? WHERE reset_token = ?");

                    ps.setString(1,password);
                    ps.setString(2,token);

                    ps.executeUpdate();

                   if (!con.getAutoCommit()) {
                      con.commit();
                   }
                }
            }
            catch (Exception e) {
                    e.printStackTrace(System.out);
            }
            finally {
                if (ps != null) {
                    ps.close();
                }
            }

Body:
So, after long hours searching, I figured out that the token parameter isn't retrieving anything because in a post request it gets values from the body and not from URL, so I simply added an hidden input inside the form like this:

<input type="hidden" name="token" value="<%= request.getParameter("token")%>">

And it worked perfectly. Hope this helps someone in the future.


问:
Select some parts of text from one Word document and copy into another Word document
I have a word file with some spaces, for example:

Word File XXXXX

Title: XXXXX

etc

And I have another word file which have that data that is missing:

Word File 20248

Title: Example of word file

etc

My question is, how can I use vba to recognize the data from the first file to be copied into the second file in the spaces I want. Furthermore I'd prefer that you can select the word file you want with a dialog box rather than putting in the code where the file is located as I have different files that can have the location changed.

Thank you so much for your answers. I'm pretty new in vba and I have never used it on word.

By now I have this code to choose the word file from which I want to copy the data:

```<code>Sub CopyData()
 Dim DC As Document
 Dim wD As Document, strD As String, wDNumb As Variant

 Dim I As Long

 Set wD = ActiveDocument
DSelection:
 For I = 1 To Documents.Count
    strD = strD & Documents(I).Name & " - " & I & vbCrLf
 Next I

 wDNumb = InputBox("Please, choose the number of the word file from which you are choosing the data to copy:" & vbCrLf & _
                vbCrLf & strD, "Choose the word document from which you are copying the data!", 1)

If wDNumb <= Documents.Count And wDNumb >= 1 Then
    GoTo DSelection2
ElseIf wDNumb = "" Then MsgBox "Operation cancelled", vbCritical, "Cancelled"
    Exit Sub
ElseIf wDNumb > Documents.Count Or wDNumb < 1 Then MsgBox "Wrong number, input a correct number", vbExclamation, "Wrong number"
    Exit Sub
End If

DSelection2:
If IsNumeric(wDNumb) Then
    Set DC = Documents(CLng(wDNumb))
Else
    MsgBox "Please choose the number on the right of the document chosen!": GoTo DSelection
End If
End Sub
</code>```

I have the following part of the code to copy some part of the Word to the other using bookmarks:

```<code>DC.Activate

Set Rng = DC.Range
With Rng.Find
    .ClearFormatting
    .Execute FindText:="TITLE:", Forward:=True, _
             Format:=False, Wrap:=wdFindStop
    Fnd = .Found
End With

If Fnd = True Then
    With Rng
        .MoveStart wdCharacter, 10
        .MoveEnd wdSentence, 1
    End With
End If

Rng.Select
Selection.Copy

wD.Activate
Selection.GoTo What:=wdGoToBookmark, Name:="TITLE"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Paste
</code>```

答:
There are multiple possible ways of approaching this, but your problem description lacks sufficient detail. For example, one could insert:

bookmarks;

content controls;

Section breaks;

tables;

etc.,

into the target document so that content from the source document can be inserted there.

Alternatively, one might use Find/Replace to locate a predefined string that can be replaced with the desired content.

With your updated problem description, you might use:

```<code>Dim RngDC As Range, wDRng As Range, BkMkNm As String
BkMkNm "TITLE"
With DC
  With .Range.Find
    .ClearFormatting
    .Execute FindText:=BkMkNm, Forward:=True, Format:=False, Wrap:=wdFindStop
  End With
  If .Found = True Then
    .MoveStart wdCharacter, 10
    .MoveEnd wdSentence, 1
    Set RngDC = .Duplicate
  End If
End With
With wD
  Set wDRng = .Bookmarks(BkMkNm).Range
  wDRng.FormattedText = RngDC.FormattedText
  .Bookmarks.Add BkMkNm, wDRng
End With
</code>```

Body:
I have a word file with some spaces, for example:

Word File XXXXX

Title: XXXXX

etc

And I have another word file which have that data that is missing:

Word File 20248

Title: Example of word file

etc

My question is, how can I use vba to recognize the data from the first file to be copied into the second file in the spaces I want. Furthermore I'd prefer that you can select the word file you want with a dialog box rather than putting in the code where the file is located as I have different files that can have the location changed.

Thank you so much for your answers. I'm pretty new in vba and I have never used it on word.

By now I have this code to choose the word file from which I want to copy the data:

Sub CopyData()
 Dim DC As Document
 Dim wD As Document, strD As String, wDNumb As Variant

 Dim I As Long

 Set wD = ActiveDocument
DSelection:
 For I = 1 To Documents.Count
    strD = strD & Documents(I).Name & " - " & I & vbCrLf
 Next I

 wDNumb = InputBox("Please, choose the number of the word file from which you are choosing the data to copy:" & vbCrLf & _
                vbCrLf & strD, "Choose the word document from which you are copying the data!", 1)

If wDNumb <= Documents.Count And wDNumb >= 1 Then
    GoTo DSelection2
ElseIf wDNumb = "" Then MsgBox "Operation cancelled", vbCritical, "Cancelled"
    Exit Sub
ElseIf wDNumb > Documents.Count Or wDNumb < 1 Then MsgBox "Wrong number, input a correct number", vbExclamation, "Wrong number"
    Exit Sub
End If

DSelection2:
If IsNumeric(wDNumb) Then
    Set DC = Documents(CLng(wDNumb))
Else
    MsgBox "Please choose the number on the right of the document chosen!": GoTo DSelection
End If
End Sub

I have the following part of the code to copy some part of the Word to the other using bookmarks:

DC.Activate

Set Rng = DC.Range
With Rng.Find
    .ClearFormatting
    .Execute FindText:="TITLE:", Forward:=True, _
             Format:=False, Wrap:=wdFindStop
    Fnd = .Found
End With

If Fnd = True Then
    With Rng
        .MoveStart wdCharacter, 10
        .MoveEnd wdSentence, 1
    End With
End If

Rng.Select
Selection.Copy

wD.Activate
Selection.GoTo What:=wdGoToBookmark, Name:="TITLE"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Paste

Body:
There are multiple possible ways of approaching this, but your problem description lacks sufficient detail. For example, one could insert:

bookmarks;

content controls;

Section breaks;

tables;

etc.,

into the target document so that content from the source document can be inserted there.

Alternatively, one might use Find/Replace to locate a predefined string that can be replaced with the desired content.

With your updated problem description, you might use:

Dim RngDC As Range, wDRng As Range, BkMkNm As String
BkMkNm "TITLE"
With DC
  With .Range.Find
    .ClearFormatting
    .Execute FindText:=BkMkNm, Forward:=True, Format:=False, Wrap:=wdFindStop
  End With
  If .Found = True Then
    .MoveStart wdCharacter, 10
    .MoveEnd wdSentence, 1
    Set RngDC = .Duplicate
  End If
End With
With wD
  Set wDRng = .Bookmarks(BkMkNm).Range
  wDRng.FormattedText = RngDC.FormattedText
  .Bookmarks.Add BkMkNm, wDRng
End With


问:
Treat first column with spaces as one column using awk
I have this data that wanted to extract. However, im having trouble with the first column since some data has space in it making it hard for me to parse it using awk

```<code>6_MB06 SA003              1550        None                                          uats           admin     1270           1478640      1211360         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000521D3   no         no               0                                  no              yes            no                      no                supported       no        no                                18                              2.60                      193                       no            0        Active optimized   0000         Not Available
6_VLS01 G                 516         None                                          uats           admin     0              492880       176             none    1008291840          no                               0                   no                                                                                60021AA29H38028200000000000521D4   no         no               0                                  no              yes            no                      no                supported       no        no                                99                              2.20                      0                         no            0        Active optimized   0000         Not Available
6_VLS01 R                 1550        None                                          uats           admin     1361           1478640      1297994         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000521D5   no         no               0                                  no              yes            no                      no                supported       no        no                                12                              3.58                      375                       no            0        Active optimized   0000         Not Available
irexenvdi_np_cl1_2_001    10956       None                                          ire_ct2_pool   admin     8689           10449056     8286854         none    21396484375         no                               0                   no                                                                                60021AA29H38028200000000000521D6   no         no               0                                  no              yes            no                      no                supported       no        no                                20                              1.38                      1050                      no            0        Active optimized   0000         Not Available
irexenvdi_np_cl1_2_002    10956       None                                          ire_ct2_pool   admin     8696           10449056     8293878         none    21396484375         no                               0                   no                                                                                60021AA29H38028200000000000521D7   no         no               0                                  no              yes            no                      no                supported       no        no                                20                              1.36                      1132                      no            0        Active optimized   0000         Not Available
4_MA04-SA025              1550        None                                          uats           admin     1270           1478640      1211856         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000630EC   no         no               0                                  no              yes            no                      no                supported       no        no                                18                              1.92                      316                       no            0        Active optimized   0000         Not Available
4_G VLS01                 516         None                                          uats           admin     7              492880       7264            none    1008291840          no                               0                   no                                                                                60021AA29H38028200000000000630ED   no         no               0                                  no              yes            no                      no                supported       no        no                                98                              1.26                      0                         no            0        Active optimized   0000         Not Available
4_R VLS01                 1550        None                                          uats           admin     1278           1478640      1218864         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000630EE   no         no               0                                  no              yes            no                      no                supported       no        no                                17                              2.19                      423                       no            0        Active optimized   0000         Not Available
</code>```

Tried this command which i use in another script since output is somehow similar but it did not work as intended.

```<code>cat file | awk 'match($0, /[[:alnum:]]{32}/){ print $1, $2, substr($0, RSTART, RLENGTH)}' |column -t
</code>```

Running that produces this:

```<code>6_MB06                  SA003  60021AA29H38028200000000000521D3
6_VLS01                 G      60021AA29H38028200000000000521D4
6_VLS01                 R      60021AA29H38028200000000000521D5
irexenvdi_np_cl1_2_001  10956  60021AA29H38028200000000000521D6
irexenvdi_np_cl1_2_002  10956  60021AA29H38028200000000000521D7
4_MA04-SA025            1550   60021AA29H38028200000000000630EC
4_G                     VLS01  60021AA29H38028200000000000630ED
4_R                     VLS01  60021AA29H38028200000000000630EE
</code>```

But wanted this:

```<code>6_MB06 SA003              1550      60021AA29H38028200000000000521D3
6_VLS01 G                 516       60021AA29H38028200000000000521D4
6_VLS01 R                 1550      60021AA29H38028200000000000521D5
irexenvdi_np_cl1_2_001    10956     60021AA29H38028200000000000521D6
irexenvdi_np_cl1_2_002    10956     60021AA29H38028200000000000521D7
4_MA04-SA025              1550      60021AA29H38028200000000000630EC
4_G VLS01                 516       60021AA29H38028200000000000630ED
4_R VLS01                 1550      60021AA29H38028200000000000630EE
</code>```

答:
If your first word has at most one space in it, you can try

```<code>awk 'NF == 35 { print $1"@"$2, $3, $15} NF == 34 { print $1, $2, $14 }' file | column -t | sed 's/@/ /'
</code>```

This recognizes rows with the first word containing a space as having an extra column (field in awk parlance), printing the space as a @ symbol, then formatting with column -t, then replacing the @ with a space using sed.

Body:
I have this data that wanted to extract. However, im having trouble with the first column since some data has space in it making it hard for me to parse it using awk

6_MB06 SA003              1550        None                                          uats           admin     1270           1478640      1211360         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000521D3   no         no               0                                  no              yes            no                      no                supported       no        no                                18                              2.60                      193                       no            0        Active optimized   0000         Not Available
6_VLS01 G                 516         None                                          uats           admin     0              492880       176             none    1008291840          no                               0                   no                                                                                60021AA29H38028200000000000521D4   no         no               0                                  no              yes            no                      no                supported       no        no                                99                              2.20                      0                         no            0        Active optimized   0000         Not Available
6_VLS01 R                 1550        None                                          uats           admin     1361           1478640      1297994         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000521D5   no         no               0                                  no              yes            no                      no                supported       no        no                                12                              3.58                      375                       no            0        Active optimized   0000         Not Available
irexenvdi_np_cl1_2_001    10956       None                                          ire_ct2_pool   admin     8689           10449056     8286854         none    21396484375         no                               0                   no                                                                                60021AA29H38028200000000000521D6   no         no               0                                  no              yes            no                      no                supported       no        no                                20                              1.38                      1050                      no            0        Active optimized   0000         Not Available
irexenvdi_np_cl1_2_002    10956       None                                          ire_ct2_pool   admin     8696           10449056     8293878         none    21396484375         no                               0                   no                                                                                60021AA29H38028200000000000521D7   no         no               0                                  no              yes            no                      no                supported       no        no                                20                              1.36                      1132                      no            0        Active optimized   0000         Not Available
4_MA04-SA025              1550        None                                          uats           admin     1270           1478640      1211856         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000630EC   no         no               0                                  no              yes            no                      no                supported       no        no                                18                              1.92                      316                       no            0        Active optimized   0000         Not Available
4_G VLS01                 516         None                                          uats           admin     7              492880       7264            none    1008291840          no                               0                   no                                                                                60021AA29H38028200000000000630ED   no         no               0                                  no              yes            no                      no                supported       no        no                                98                              1.26                      0                         no            0        Active optimized   0000         Not Available
4_R VLS01                 1550        None                                          uats           admin     1278           1478640      1218864         none    2957656064          no                               0                   no                                                                                60021AA29H38028200000000000630EE   no         no               0                                  no              yes            no                      no                supported       no        no                                17                              2.19                      423                       no            0        Active optimized   0000         Not Available

Tried this command which i use in another script since output is somehow similar but it did not work as intended.

cat file | awk 'match($0, /[[:alnum:]]{32}/){ print $1, $2, substr($0, RSTART, RLENGTH)}' |column -t

Running that produces this:

6_MB06                  SA003  60021AA29H38028200000000000521D3
6_VLS01                 G      60021AA29H38028200000000000521D4
6_VLS01                 R      60021AA29H38028200000000000521D5
irexenvdi_np_cl1_2_001  10956  60021AA29H38028200000000000521D6
irexenvdi_np_cl1_2_002  10956  60021AA29H38028200000000000521D7
4_MA04-SA025            1550   60021AA29H38028200000000000630EC
4_G                     VLS01  60021AA29H38028200000000000630ED
4_R                     VLS01  60021AA29H38028200000000000630EE

But wanted this:

6_MB06 SA003              1550      60021AA29H38028200000000000521D3
6_VLS01 G                 516       60021AA29H38028200000000000521D4
6_VLS01 R                 1550      60021AA29H38028200000000000521D5
irexenvdi_np_cl1_2_001    10956     60021AA29H38028200000000000521D6
irexenvdi_np_cl1_2_002    10956     60021AA29H38028200000000000521D7
4_MA04-SA025              1550      60021AA29H38028200000000000630EC
4_G VLS01                 516       60021AA29H38028200000000000630ED
4_R VLS01                 1550      60021AA29H38028200000000000630EE

Body:
If your first word has at most one space in it, you can try

awk 'NF == 35 { print $1"@"$2, $3, $15} NF == 34 { print $1, $2, $14 }' file | column -t | sed 's/@/ /'

This recognizes rows with the first word containing a space as having an extra column (field in awk parlance), printing the space as a @ symbol, then formatting with column -t, then replacing the @ with a space using sed.


问:
Empty EditText value displayed in AlertDialog
I am new in Android development and I got a problem. I have 2 EditText fields of login and password and 1 Button. When I click on the Button, I am getting AlertDialog with message "Logged in as " but I need it to be "Logged in as *value entered into "login" EditText".
The EditText value is always empty. It's just a simple implementation, but it doesn't work.
What am I doing wrong here?

Here is the code:

```<code>public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View view2 = inflater.inflate(R.layout.fragment_first, null, false);

        loginText = (EditText)view2.findViewById(R.id.loginText);
        passwText = (EditText)view2.findViewById(R.id.passText);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

        String st = loginText.getText().toString();

        if (loginText != null && passwText != null){
            builder.setMessage("Logged in as " + st);
        }
        else
            builder.setMessage("Login or password was not entered!" );
        builder.show();
    }
}
</code>```

答:
Maybe you can try this, But this does not use onViewCreated</p>

```<code>public class FirstFragment extends Fragment {
EditText loginText;
EditText passText;
Button btnLogin;
@Override
public View onCreateView(
        LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState
) {
    View view2 = inflater.inflate(R.layout.fragment_first, null, false);

    loginText = (EditText)view2.findViewById(R.id.loginText);
    passText = (EditText)view2.findViewById(R.id.passText);
    btnLogin = (Button) view2.findViewById(R.id.button_first);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handleLoginDialog();
        }
    });

    return view2;
}

private void handleLoginDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

    String st = loginText.getText().toString().trim();
    String pt = passText.getText().toString().trim();

    if (st.isEmpty() && pt.isEmpty()){
        builder.setMessage("Login or password was not entered!" );
    }
    else
        builder.setMessage("Logged in as " + st);
    builder.show();
}
</code>```

Body:
I am new in Android development and I got a problem. I have 2 EditText fields of login and password and 1 Button. When I click on the Button, I am getting AlertDialog with message "Logged in as " but I need it to be "Logged in as *value entered into "login" EditText".
The EditText value is always empty. It's just a simple implementation, but it doesn't work.
What am I doing wrong here?

Here is the code:

public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View view2 = inflater.inflate(R.layout.fragment_first, null, false);

        loginText = (EditText)view2.findViewById(R.id.loginText);
        passwText = (EditText)view2.findViewById(R.id.passText);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

        String st = loginText.getText().toString();

        if (loginText != null && passwText != null){
            builder.setMessage("Logged in as " + st);
        }
        else
            builder.setMessage("Login or password was not entered!" );
        builder.show();
    }
}

Body:
Maybe you can try this, But this does not use onViewCreated

public class FirstFragment extends Fragment {
EditText loginText;
EditText passText;
Button btnLogin;
@Override
public View onCreateView(
        LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState
) {
    View view2 = inflater.inflate(R.layout.fragment_first, null, false);

    loginText = (EditText)view2.findViewById(R.id.loginText);
    passText = (EditText)view2.findViewById(R.id.passText);
    btnLogin = (Button) view2.findViewById(R.id.button_first);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handleLoginDialog();
        }
    });

    return view2;
}

private void handleLoginDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

    String st = loginText.getText().toString().trim();
    String pt = passText.getText().toString().trim();

    if (st.isEmpty() && pt.isEmpty()){
        builder.setMessage("Login or password was not entered!" );
    }
    else
        builder.setMessage("Logged in as " + st);
    builder.show();
}


问:
Unity 2019.3.1 SDK/JDK/NDK/GRADLE which version should I download?
Hello I want to build my game to android but I need to know which version should I use of sdk,jdk,ndk and gradle? If you guys know, can give me the download links?</p>

答:
The manual for 2019.3 https://docs.unity3d.com/Manual/android-sdksetup.html recommends using the unity installer to add these components for you.

Otherwise it states a minimum supported version is Android 4.4, "KitKat", API level 19. you could follow these older steps https://docs.unity3d.com/2018.4/Documentation/Manual/android-sdksetup.html to manually download the needed components. I would personally use the latest available, unless I am targeting a device which requires a specific version


问:
Button Action on login Button click in FBConnect API
I am using fbconnect api in my project.When the login dialog gets opened where we entered our credentials ,when I click on login button there is something performed and it is redirected to the publish page.
My problem is I am not getting which action is performed on that login button so that I can put an indicator over there.

I have attached a screenshot to specify which button I am talking about.

Any suggestions will be highly appreciated!

答:
When you push login button - the login request will send to FB server only. To get answer you need to implement FBSessionDelegate protocol:

```<code>/**
 * Called when the user successfully logged in.
 */
- (void)fbDidLogin;

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)fbDidNotLogin:(BOOL)cancelled;

/**
 * Called when the user logged out.
 */
- (void)fbDidLogout;
</code>```

Read also comments in Facebook.m:

Starts a dialog which prompts the user to log in to Facebook and grant

the requested permissions to the application.
*

If the device supports multitasking, we use fast app switching to show

the dialog in the Facebook app or, if the Facebook app isn't installed,

in Safari (this enables single sign-on by allowing multiple apps on

the device to share the same user session).

When the user grants or denies the permissions, the app that

showed the dialog (the Facebook app or Safari) redirects back to

the calling application, passing in the URL the access token

and/or any other parameters the Facebook backend includes in

the result (such as an error code if an error occurs).

ContentLicense: CC BY-SA 3.0

Body:
When you push login button - the login request will send to FB server only. To get answer you need to implement FBSessionDelegate protocol:

/**
 * Called when the user successfully logged in.
 */
- (void)fbDidLogin;

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)fbDidNotLogin:(BOOL)cancelled;

/**
 * Called when the user logged out.
 */
- (void)fbDidLogout;

Read also comments in Facebook.m:

Starts a dialog which prompts the user to log in to Facebook and grant

the requested permissions to the application.
*

If the device supports multitasking, we use fast app switching to show

the dialog in the Facebook app or, if the Facebook app isn't installed,

in Safari (this enables single sign-on by allowing multiple apps on

the device to share the same user session).

When the user grants or denies the permissions, the app that

showed the dialog (the Facebook app or Safari) redirects back to

the calling application, passing in the URL the access token

and/or any other parameters the Facebook backend includes in

the result (such as an error code if an error occurs).


问:
Spring Scheduled Task running in clustered environment
I am writing an application that has a cron job that executes every 60 seconds. The application is configured to scale when required onto multiple instances. I only want to execute the task on 1 instance every 60 seconds (On any node). Out of the box I can not find a solution to this and I am surprised it has not been asked multiple times before. I am using Spring 4.1.6.</p>

```<code>    <task:scheduled-tasks>
        <task:scheduled ref="beanName" method="execute" cron="0/60 * * * * *"/>
    </task:scheduled-tasks>
</code>```

答:
Spring context is not clustered so manage the task in distributed application is a little bit difficult and you need to use systems supporting jgroup to synchronis the state and let your task take the priority to execute the action. Or you could use ejb context to manage clustered ha singleton service like jboss ha environment
https://developers.redhat.com/quickstarts/eap/cluster-ha-singleton/?referrer=jbd
Or you could use clustered cache and access lock resource between the service and first service take the lock will beform the action or implement you own jgroup to communicat your service and perform the action one one node</p>

Body:
I am writing an application that has a cron job that executes every 60 seconds. The application is configured to scale when required onto multiple instances. I only want to execute the task on 1 instance every 60 seconds (On any node). Out of the box I can not find a solution to this and I am surprised it has not been asked multiple times before. I am using Spring 4.1.6.

    <task:scheduled-tasks>
        <task:scheduled ref="beanName" method="execute" cron="0/60 * * * * *"/>
    </task:scheduled-tasks>


问:
Is retainCount giving me the correct information for my NSDate?
I have NSDate property

In .h

```<code>...
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
...
      NSDate *pageStartDate;
...
}
...
@property (nonatomic, retain) NSDate *pageStartDate;
...
</code>```

In .m

```<code>...
-(void)myMethod
{
   ...
   // set date of start showing page
   NSDate *tempStartDate = [NSDate date];
   [tempStartDate retain];
   pageStartDate = tempStartDate;
   [tempStartDate release];
   ...
}
...
</code>```

After running this code the [tempStartDate retainCount] = 1 - is it normal?
If I write self.pageStartDate = tempStartDate than [pageStartDate retainCount] = 2.

Is there right use of NSDate, or not is?

答:
The problem isn't just your NSDate its because you've used retainCount

Annotation:

```<code>NSDate *tempStartDate = [NSDate date]; // No alloc, retain, copy, or mutableCopy - so assume autoreleased instance
[tempStartDate retain]; // You call retain - you own this now
pageStartDate = tempStartDate; // Not going through the setter. :(
[tempStartDate release];  // You've released this correctly, except for the step above.
                          // pageStartDate is now pointing to a garbage pointer.
</code>```

You've done the right thing by releasing what you've retained, but pageStartDate didn't hold on to the value.

Try this

```<code>self.pageStartDate = [NSDate date];
</code>```

Since you are using retain for the pageStartDate property, this will retain the value for you.

But - trying to use retainCount to check your memory management is, basically, doing it wrong.

Body:
I have NSDate property

In .h

...
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
...
      NSDate *pageStartDate;
...
}
...
@property (nonatomic, retain) NSDate *pageStartDate;
...

In .m

...
-(void)myMethod
{
   ...
   // set date of start showing page
   NSDate *tempStartDate = [NSDate date];
   [tempStartDate retain];
   pageStartDate = tempStartDate;
   [tempStartDate release];
   ...
}
...

After running this code the [tempStartDate retainCount] = 1 - is it normal?
If I write self.pageStartDate = tempStartDate than [pageStartDate retainCount] = 2.

Is there right use of NSDate, or not is?

Body:
The problem isn't just your NSDate its because you've used retainCount

Annotation:

NSDate *tempStartDate = [NSDate date]; // No alloc, retain, copy, or mutableCopy - so assume autoreleased instance
[tempStartDate retain]; // You call retain - you own this now
pageStartDate = tempStartDate; // Not going through the setter. :(
[tempStartDate release];  // You've released this correctly, except for the step above.
                          // pageStartDate is now pointing to a garbage pointer.

You've done the right thing by releasing what you've retained, but pageStartDate didn't hold on to the value.

Try this

self.pageStartDate = [NSDate date];

Since you are using retain for the pageStartDate property, this will retain the value for you.

But - trying to use retainCount to check your memory management is, basically, doing it wrong.


问:
Email template pre-wrap not working in Outlook
I am rendering a html email template and i have a pre-wrapped text i want to show.

Using white-space: pre-wrap; works perfectly everywhere (gmail, yahoo...) except Outlook. I tried using ```/``` this also works perfectly everywhere (gmail, yahoo, even Outlook desktop app), but it doesn't work in Outlook web app.

Any suggestions what should i try next?

Code example 1:

Code example 2:

```

答:
Best way forward probably is then to use Outlook conditional code, i.e.:</p>

```<code><td style="color: #153643; font-family: Arial, sans-serif; font-size: 24px;">
    <!--[if !mso]><!-- --><div style="white-space: pre-wrap; text-align: left; font-weight: bold" th:text="${content}"></div><!--<![endif]-->
    <!--[if mso]><!-- --><pre style="text-align: left; font-weight: bold" th:text="${content}">```<!--<![endif]-->
</td>
</code>```

Body:
I am rendering a html email template and i have a pre-wrapped text i want to show.

Using white-space: pre-wrap; works perfectly everywhere (gmail, yahoo...) except Outlook. I tried using
/
 this also works perfectly everywhere (gmail, yahoo, even Outlook desktop app), but it doesn't work in Outlook web app.

Any suggestions what should i try next?

Code example 1:

Code example 2:

Body:
Best way forward probably is then to use Outlook conditional code, i.e.:

<td style="color: #153643; font-family: Arial, sans-serif; font-size: 24px;">
    <!--[if !mso]><!-- --><div style="white-space: pre-wrap; text-align: left; font-weight: bold" th:text="${content}"></div><!--<![endif]-->
    <!--[if mso]><!-- --><pre style="text-align: left; font-weight: bold" th:text="${content}"></pre><!--<![endif]-->
</td>


问:
Extract sentences containing specific word(s)
I have a get_sentences (sentimentr) list, and need to extract only those sentences containing specific words.
This is how the data looks like:

```<code>> class(frasi_negative)
[1] "get_sentences"           "get_sentences_character" "list"
> frasi_negative[2:3]
[[1]]
[1] "Al mio cellulare (Xiaomi Redmi Note 5) si mostrano singolarmente, separate, quando cerco di connetterle."
[2] "O si connette alla destra, o alla sinistra, e in ogni caso il suono poi esce dalle casse del cellulare (nonostante aver dato alle cuffie tutti i permessi)."
[3] "Non capisco perché, data che la prima connessione era andata come si deve; spente e riaccese, hanno iniziato a comportarsi così."
[4] "Ho provato a riavviare sia loro che cellulare, a rimetterle nella scatoletta e ritoglierle, ma il problema persiste."
[5] "Non penso c'entri il mio cellulare (mai avuto problemi con prodotti simili), in ogni caso effettuo reso con rimborso."

[[2]]
[1] "Comprate due mesi fa."
[2] "All'inizio funzionavano perfettamente, ma dopo qualche settimana hanno iniziato a disconnettersi tra loro di tanto in tanto."
[3] "qualche giorno fa estraendo la sinistra dall'astuccio magnetico è saltata la saldatura che la teneva chiusa e questo è il risultato."
[4] "Usandole in chiamata rendono un suono non limpido."
[5] "Il suono è accettabile ma nulla di speciale."
[6] "Ormai sono inutilizzabili."
[7] "Per il prezzo mi aspettavo un prodotto migliore e più duraturo (avendo già provato auricolari wireless della stessa fascia di prezzo di altri brand)"
</code>```

As an example, if I search "wireless", only the [[2]][7] element should show up.

How can I achieve this?

Thank you in advance.

答:
We can use str_detect

```<code>library(purrr)
library(stringr)
keyword <- 'wireless'
map(frasi_negative, ~  .x[str_detect(.x, keyword)])
</code>```

Body:
I have a get_sentences (sentimentr) list, and need to extract only those sentences containing specific words.
This is how the data looks like:

> class(frasi_negative)
[1] "get_sentences"           "get_sentences_character" "list"
> frasi_negative[2:3]
[[1]]
[1] "Al mio cellulare (Xiaomi Redmi Note 5) si mostrano singolarmente, separate, quando cerco di connetterle."
[2] "O si connette alla destra, o alla sinistra, e in ogni caso il suono poi esce dalle casse del cellulare (nonostante aver dato alle cuffie tutti i permessi)."
[3] "Non capisco perché, data che la prima connessione era andata come si deve; spente e riaccese, hanno iniziato a comportarsi così."
[4] "Ho provato a riavviare sia loro che cellulare, a rimetterle nella scatoletta e ritoglierle, ma il problema persiste."
[5] "Non penso c'entri il mio cellulare (mai avuto problemi con prodotti simili), in ogni caso effettuo reso con rimborso."

[[2]]
[1] "Comprate due mesi fa."
[2] "All'inizio funzionavano perfettamente, ma dopo qualche settimana hanno iniziato a disconnettersi tra loro di tanto in tanto."
[3] "qualche giorno fa estraendo la sinistra dall'astuccio magnetico è saltata la saldatura che la teneva chiusa e questo è il risultato."
[4] "Usandole in chiamata rendono un suono non limpido."
[5] "Il suono è accettabile ma nulla di speciale."
[6] "Ormai sono inutilizzabili."
[7] "Per il prezzo mi aspettavo un prodotto migliore e più duraturo (avendo già provato auricolari wireless della stessa fascia di prezzo di altri brand)"

As an example, if I search "wireless", only the [[2]][7] element should show up.

How can I achieve this?

Thank you in advance.

Body:
We can use str_detect

library(purrr)
library(stringr)
keyword <- 'wireless'
map(frasi_negative, ~  .x[str_detect(.x, keyword)])


问:
Prophet fit() does not recognize dataframe
I am trying to run a Prophet time series model on a standard pandas dataframe.  First column is a date datatype.  I made sure the second column is a float.  However, I keep getting told that the argument needs to be a dataframe.  It is a dataframe and a dataframe in the format that Prophet us supposed to be.  Any ideas why I am getting: fit() missing 1 required positional argument: 'df'?</p>

```<code>import io
import requests
import pandas as pd
from fbprophet import Prophet
from fbprophet.plot import add_changepoints_to_plot

df = pd.read_csv("C://Users//initialClaims.csv", header=None, encoding='utf-8' )
df[1] = df[1].astype(float)
df[0] = pd.to_datetime(df[0])
ds = pd.to_datetime(df[0])
y = df[1].astype(float)

# Fit prophet model
m = Prophet
m.fit(df)
</code>```

答: Replace m = Prophet with m = Prophet() as per the documentation and see if that helps

Body:
I am trying to run a Prophet time series model on a standard pandas dataframe.  First column is a date datatype.  I made sure the second column is a float.  However, I keep getting told that the argument needs to be a dataframe.  It is a dataframe and a dataframe in the format that Prophet us supposed to be.  Any ideas why I am getting: fit() missing 1 required positional argument: 'df'?

import io
import requests
import pandas as pd
from fbprophet import Prophet
from fbprophet.plot import add_changepoints_to_plot

df = pd.read_csv("C://Users//initialClaims.csv", header=None, encoding='utf-8' )
df[1] = df[1].astype(float)
df[0] = pd.to_datetime(df[0])
ds = pd.to_datetime(df[0])
y = df[1].astype(float)

# Fit prophet model
m = Prophet
m.fit(df)


问:
hausdorff distance in python of 2xN matrices with different number of columns
I have two 2xN matrices of values and I want to find the hausdorff distance of them using "directed_hausdorff(u,v)" function. However, since the number of columns are not equal in both matrices I want to find the hausdorff distance of using the matrices with the lower number of columns. For example if I have

```<code>t = [(1,2,3,9), (4,5,6,7)]
l = [(3,4,5), (7,8,9)]
</code>```

l has 3 columns and t has 4 columns. Since t is bigger than l I would like to modify t so that it is instead the same size of l so that I may compute the hausdorff distance between to equally sized matrices, essentially becoming

```<code>t = [(1,2,3), (4,5,6)]
l = (3,4,5), (7,8,9)]
</code>```

I would like to apply this to any two matrices of 2xN (different sizes) where I determine which matrix has more columns and then modify the larger matrix by eliminating elements starting from the last column so that it would equal the size of the smaller matrix. Is there a shortcut method to do this that will output the two lists themselves?

答:
I'm not aware of an existing function for this, but if t and l were Numpy arrays then you could accomplish this with fairly short code and without duplicating the data in memory.

```<code>import numpy as np
from scipy.spatial.distance import directed_hausdorff

...

t = np.array(t)
l = np.array(l)
num_cols = min(t.shape[1], l.shape[1])
distance = directed_hausdorff(t[:, :num_cols], l[:, :num_cols])

</code>```

The expression t.shape[1] means the size of the array along dimension (or "axis") 1, i.e. the number of columns (whereas the number of rows would be t.shape[0]). The indexing syntax t[:, :num_cols] means for every row (":"), get the first num_cols columns (":num_columns"). The comma separates the range of indices for each dimension.

Body:
I have two 2xN matrices of values and I want to find the hausdorff distance of them using "directed_hausdorff(u,v)" function. However, since the number of columns are not equal in both matrices I want to find the hausdorff distance of using the matrices with the lower number of columns. For example if I have

t = [(1,2,3,9), (4,5,6,7)]
l = [(3,4,5), (7,8,9)]

l has 3 columns and t has 4 columns. Since t is bigger than l I would like to modify t so that it is instead the same size of l so that I may compute the hausdorff distance between to equally sized matrices, essentially becoming

t = [(1,2,3), (4,5,6)]
l = (3,4,5), (7,8,9)]

I would like to apply this to any two matrices of 2xN (different sizes) where I determine which matrix has more columns and then modify the larger matrix by eliminating elements starting from the last column so that it would equal the size of the smaller matrix. Is there a shortcut method to do this that will output the two lists themselves?

Body:
I'm not aware of an existing function for this, but if t and l were Numpy arrays then you could accomplish this with fairly short code and without duplicating the data in memory.

import numpy as np
from scipy.spatial.distance import directed_hausdorff

...

t = np.array(t)
l = np.array(l)
num_cols = min(t.shape[1], l.shape[1])
distance = directed_hausdorff(t[:, :num_cols], l[:, :num_cols])

The expression t.shape[1] means the size of the array along dimension (or "axis") 1, i.e. the number of columns (whereas the number of rows would be t.shape[0]). The indexing syntax t[:, :num_cols] means for every row (":"), get the first num_cols columns (":num_columns"). The comma separates the range of indices for each dimension.


问:
can I reinstall npm in a angular project to fix it?
I have an angular 9 project. I have installed different libraries on it and after installing ngx-gallery and some issues for Rendere2 and etc, I edited some file in node-Module/angular/core like core.d.ts. I am very new to angular. now my project does not running, then I tried to delete node_module to install it again but I couldn't.
I wanna know Do I have any chance to fix all these with reinstalling npm or not.
Thanks so much

update:I attached an image of errors that I have now.

答: You would need to provide some more information about the file you modified that is causing issues, as I'm not clear what error you are getting. If you are asking if you can retain the content of the projects folder while reinstalling dependencies, just run npm install from within the directory.


问:
list of regular expressions
I'm looking for a concise list of all the regular expression syntax (sort of like a cheatsheet) and I found this tool: http://erik.eae.net/playground/regexp/regexp.html

in which if you click on the question mark on the top right corner it will display some sort of dictionary of regular expressions...

my question is....is this list comprehensive or is it missing something?

if anyone knows a better list, please let me know as well

答:
Regex syntax varies between different implementations. Therefore, there is unlikely to be an absolutely definitive syntax list which covers everything. You may get one which covers all possible options for regex in a given language, but you'd need a different reference for regex implementations in other languages.

For example, some regex implementations allow named classes such as [:space:] or [:digit:], which don't exist in others.

My favourite reference site for regular expressions is http://www.regular-expressions.info, which does include details of differences in regex between various languages, but I'll be the first to acknowledge that it doesn't cover everything.

Title: list of regular expressions


问:
OIDC Provider Flask. Password Credentials Grant
Does anybody know wether authlib python library support the Resource Owner Password Credentials Grant flow for Flask OIDC Provider?

In the documentation only appear Code, Implicit and Hybrid Flow.

https://docs.authlib.org/en/latest/flask/2/openid-connect.html

If so, please could you tell me how do you implement the functionality?

答:
There is no Password Credentials Grant in OpenID Connect. Password Credentials Grant is a normal OAuth 2.0 grant type, please check https://docs.authlib.org/en/latest/flask/2/grants.html

Here is the documentation of OpenID Connect, you can find it has only code, implicit and hybrid grants: https://openid.net/specs/openid-connect-core-1_0.html


问:
Removing whitespaces in a txt line and adding the values to a list
I have the following line of text from a .txt file

```<code>  0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002     \n
</code>```

I've been facing a problem on how to make this first line into a list. I've tried line.strip() but that only took care of the first and last spaces. There are still spaces left that I couldn't get rid of. As seen below:

```<code>'0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'
</code>```

I also can't just replace all " " with "" as all numbers would get crumpled together. I also can't assume the number of whitespaces, nor the number of spaces before the ".", as I may have numbers greater than or equal to 10 down the line.

答:
You don't even need re. Just use split on the line.

' 1 2  3   4    5 '.split()
['1', '2', '3', '4', '5']
```

Body:
I have the following line of text from a .txt file

  0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002     \n

I've been facing a problem on how to make this first line into a list. I've tried line.strip() but that only took care of the first and last spaces. There are still spaces left that I couldn't get rid of. As seen below:

'0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'

I also can't just replace all " " with "" as all numbers would get crumpled together. I also can't assume the number of whitespaces, nor the number of spaces before the ".", as I may have numbers greater than or equal to 10 down the line.


问:
Konva possible to dynamically change the text of a Konva
My question is it possible to dynamically change the text of a Konva.text by doble clicking and entering the new text with the keyboard?</p>

答:
Konva has no out-the-box editable Text.

The docs page suggests placing an editable HTML element on top of your canvas, let the user make edits, then remove it when done. With this approach, your main problem would be to keep the text styles consistent between the Konva element and the DOM element, to some degree. Otherwise, the transition between the two modes might not look truly WYSIWYG-like. However, depending on what you need, this solution might be just close enough.

Another approach would be to create a hidden textarea/input, capture its events, and fully emulate text interactions, like cursor movements and text selection, on canvas. This would be hard to do properly but could arguably lead to a more seamless UX. In fact, this is what fabric.js does under the hood for its editable text.


问:
problems with a perl "system" script
Im trying to write a very simple script that copies files from several remote computers to my computer. I've written the following in perl:

```<code>@Comps = ("comp1","comp2","comp3","comp4");

foreach $comp (@Comps)
{
  system("copy /Y \\\\$comp\\c\$\\myfolder\\$comp*.log   C:\\Program Files\\My Cont Folder\\input\\");
}
</code>```

I get a syntax error and cant understand why.

Thanks!

答:
Given the case that Perl is passing the characters to the shell, the only way that the shell will process "C:\Program Files" as one argument is to put double quotes around it. (Or sometimes just with one double quote preceding it.)

So you might need a few more backslashes (so I qq-ed it):

```<code>system( qq{cmd /c copy /Y \\\\$comp\\c\$\\myfolder\\$comp*.log "C:\\Program Files\\My Cont Folder\\input\\"} )
</code>```

Title: problems with a perl "system" script

Body:
Im trying to write a very simple script that copies files from several remote computers to my computer. I've written the following in perl:

@Comps = ("comp1","comp2","comp3","comp4");

foreach $comp (@Comps)
{
  system("copy /Y \\\\$comp\\c\$\\myfolder\\$comp*.log   C:\\Program Files\\My Cont Folder\\input\\");
}

I get a syntax error and cant understand why.

Thanks!

Body:
Given the case that Perl is passing the characters to the shell, the only way that the shell will process "C:\Program Files" as one argument is to put double quotes around it. (Or sometimes just with one double quote preceding it.)

So you might need a few more backslashes (so I qq-ed it):

system( qq{cmd /c copy /Y \\\\$comp\\c\$\\myfolder\\$comp*.log "C:\\Program Files\\My Cont Folder\\input\\"} )


问:
How to fix ERROR: No signature of method: build_ap86oam3dut3pxce3x49rdtma.android()?
ERROR: No signature of method: build_ap86oam3dut3pxce3x49rdtma.android() is applicable for argument types: (build_ap86oam3dut3pxce3x49rdtma$_run_closure1) values: [build_ap86oam3dut3pxce3x49rdtma$_run_closure1@47588b04]

The build gradle is:

```<code>apply plugin: 'com.android.application'

    android{
    implementationSdkVersion 28
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.uiresource.taksiku"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        androidTestImplementation('com.android.support.test.espresso:espresso-core:2.3-alpha', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        implementation "com.android.support:appcompat-v7:$var"
        implementation 'com.android.support:design:28.0.0'
        testimplementation 'junit:junit:4.13'
        implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta5'
        implementation 'de.hdodenhof:circleimageview:3.1.0'
        }
</code>```

答:
I'm new to Android but i got a message similar to yours today when i try to use a different version (not the suggested ones) of the Gradle plugin and gradle engine on Android Studio 4.1 canary.

When I had on my App build.gradle these lines:

```<code>task wrapper(type: Wrapper){
    gradleVersion = '5.6.4'
}
</code>```

and on my build.gradle for the module this line

```<code>classpath 'com.android.tools.build:gradle:3.6.3'
</code>```

This was the message i got with previous settings:

```<code>A problem occurred evaluating project ':app'.
> No signature of method: build_5dcjpn4h9nkpym0yszxs5w2uh.android() is applicable for argument types: (build_5dcjpn4h9nkpym0yszxs5w2uh$_run_closure1) values: [build_5dcjpn4h9nkpym0yszxs5w2uh$_run_closure1@2e4515b3]
</code>```

The way i found to solve this error was changing version for the gradle plugin on my build.gradle for the module like this

```<code>classpath 'com.android.tools.build:gradle:4.0.0'
</code>```

I hope this could help you.
Happy coding!

Body:
ERROR: No signature of method: build_ap86oam3dut3pxce3x49rdtma.android() is applicable for argument types: (build_ap86oam3dut3pxce3x49rdtma$_run_closure1) values: [build_ap86oam3dut3pxce3x49rdtma$_run_closure1@47588b04]

The build gradle is:

apply plugin: 'com.android.application'

    android{
    implementationSdkVersion 28
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.uiresource.taksiku"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        androidTestImplementation('com.android.support.test.espresso:espresso-core:2.3-alpha', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        implementation "com.android.support:appcompat-v7:$var"
        implementation 'com.android.support:design:28.0.0'
        testimplementation 'junit:junit:4.13'
        implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta5'
        implementation 'de.hdodenhof:circleimageview:3.1.0'
        }

Body:
I'm new to Android but i got a message similar to yours today when i try to use a different version (not the suggested ones) of the Gradle plugin and gradle engine on Android Studio 4.1 canary.

When I had on my App build.gradle these lines:

task wrapper(type: Wrapper){
    gradleVersion = '5.6.4'
}

and on my build.gradle for the module this line

classpath 'com.android.tools.build:gradle:3.6.3'

This was the message i got with previous settings:

A problem occurred evaluating project ':app'.
> No signature of method: build_5dcjpn4h9nkpym0yszxs5w2uh.android() is applicable for argument types: (build_5dcjpn4h9nkpym0yszxs5w2uh$_run_closure1) values: [build_5dcjpn4h9nkpym0yszxs5w2uh$_run_closure1@2e4515b3]

The way i found to solve this error was changing version for the gradle plugin on my build.gradle for the module like this

classpath 'com.android.tools.build:gradle:4.0.0'

I hope this could help you.
Happy coding!


问:
How to parse a string with multiple underscores and dashes
I need some guidance and looking for a better way to parse strings.

Example 1:

String: Automation_LOY_Loyalty_PC_CampaignName3-Abandoners-Email1_NoPromo_USA

CSV: Automation, LOY, Loyalty, PC, CampaignName3, Abandoners, Email1, NoPromo, USA

Example 2:

String: 20200601_LOY_Functional_PC_CampaignName1_NoPromo_CAN

CSV: 20200601, LOY, Functional, PC, CampaignName1,,, No Promo, CAN

As you can see, some strings don’t have all the fields, so some csv fields need to be left blank blank.

Right now I’m using this code below and it’s very messy. Is there a better way to handle it other than using CHARINDEX like this?

SELECT [EmailName]
      -- Deployment Type
      ,CASE LEFT([EmailName], (CHARINDEX('_', [EmailName])) - 1)
        WHEN 'Automation' THEN 'Automation'
        ELSE 'AdHoc' END AS [Deployment]
      -- Type
      ,SUBSTRING([EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1, CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1) + 1) - CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1) - 1) AS [Type]
      -- Customer_Type
      ,SUBSTRING([EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1) + 1) + 1, CHARINDEX('_', [EmailName],CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1)) - CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) - 1) AS [Customer_Type]
      -- Campaign_Name
      ,CASE WHEN (CHARINDEX('-', [EmailName])) = 0 THEN SUBSTRING([EmailName], (CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1))) + 1, (CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1)) + 1))) - (CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1))) - 1)
            WHEN (CHARINDEX('-', [EmailName])) > 0 THEN SUBSTRING([EmailName], (CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1))) + 1, ((CHARINDEX('-', [EmailName])) - (CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1)))) - 1)
            ELSE NULL END AS [Campaign_Name]
      ,CASE WHEN (CHARINDEX('-', [EmailName])) = 0 THEN 1
            WHEN (CHARINDEX('-', [EmailName])) > 0 THEN REPLACE(SUBSTRING([EmailName], ((CHARINDEX('-', [EmailName])) + 1), (CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName], (CHARINDEX('_', [EmailName])) + 1)) + 1) + 1)) + 1))) - (CHARINDEX('-', [EmailName])) - 1),'Email','')
            ELSE NULL END AS [Email_Num]
FROM TableName
```

答:
Another option is a little XML

Not clear if you want a comma delimited string or separate columns

Example

```<code>Declare @YourTable Table ([ID] varchar(50),[SomeCol] varchar(150))
Insert Into @YourTable Values
 (1,'Automation_LOY_Loyalty_PC_CampaignName3-Abandoners-Email1_NoPromo_USA')
,(2,'20200601_LOY_Functional_PC_CampaignName1_NoPromo_CAN')

Select A.ID
      ,B.Pos1
      ,B.Pos2
      ,B.Pos3
      ,B.Pos4
      ,Pos5a = xmlData.value('/x[1]','varchar(max)')
      ,Pos5b = xmlData.value('/x[2]','varchar(max)')
      ,Pos5c = xmlData.value('/x[3]','varchar(max)')
      ,B.Pos6
      ,B.Pos7
 From  @YourTable A
 Cross Apply (
                Select Pos1 = xDim.value('/x[1]','varchar(max)')
                      ,Pos2 = xDim.value('/x[2]','varchar(max)')
                      ,Pos3 = xDim.value('/x[3]','varchar(max)')
                      ,Pos4 = xDim.value('/x[4]','varchar(max)')
                      ,Pos5 = xDim.value('/x[5]','varchar(max)')
                      ,Pos6 = xDim.value('/x[6]','varchar(max)')
                      ,Pos7 = xDim.value('/x[7]','varchar(max)')
                From  ( values (cast('<x>' + replace((Select replace(SomeCol,'_','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml)))  A(xDim)
             ) B
 Cross Apply ( values (cast('<x>' + replace((Select replace(Pos5,'-','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) ) ) C(xmlData)
</code>```

Returns

Body:
Another option is a little XML

Not clear if you want a comma delimited string or separate columns

Example

Declare @YourTable Table ([ID] varchar(50),[SomeCol] varchar(150))
Insert Into @YourTable Values
 (1,'Automation_LOY_Loyalty_PC_CampaignName3-Abandoners-Email1_NoPromo_USA')
,(2,'20200601_LOY_Functional_PC_CampaignName1_NoPromo_CAN')

Select A.ID
      ,B.Pos1
      ,B.Pos2
      ,B.Pos3
      ,B.Pos4
      ,Pos5a = xmlData.value('/x[1]','varchar(max)')
      ,Pos5b = xmlData.value('/x[2]','varchar(max)')
      ,Pos5c = xmlData.value('/x[3]','varchar(max)')
      ,B.Pos6
      ,B.Pos7
 From  @YourTable A
 Cross Apply (
                Select Pos1 = xDim.value('/x[1]','varchar(max)')
                      ,Pos2 = xDim.value('/x[2]','varchar(max)')
                      ,Pos3 = xDim.value('/x[3]','varchar(max)')
                      ,Pos4 = xDim.value('/x[4]','varchar(max)')
                      ,Pos5 = xDim.value('/x[5]','varchar(max)')
                      ,Pos6 = xDim.value('/x[6]','varchar(max)')
                      ,Pos7 = xDim.value('/x[7]','varchar(max)')
                From  ( values (cast('<x>' + replace((Select replace(SomeCol,'_','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml)))  A(xDim)
             ) B
 Cross Apply ( values (cast('<x>' + replace((Select replace(Pos5,'-','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) ) ) C(xmlData)

Returns


问:
How are client requests related to a specific session routed?
Let's say you are using spring MVC in the backend, now imagine a client makes a request to the server, a session object for that request is made and saved in the server for a specific amount of time before it expires, now each time a individual request is made by that client the server remembers through the session object which client it is.

My question is that in a production setup there can be thousands of these servers in an application, what is responsible for making sure that any subsequent requests made by a client ends up going to the server that contains the session information about the client?

like let's say in an application where there are 5 servers 1,2,3,4,5. A client makes a request to the application and the request ends up going to server 4, when the request goes to server 4 a session is created for the client. Now imagine the client makes another(completely new) request to the server, how does the application know that the request should be routed to server 4 where the session information for that client was stored previously?

答:
The application doesn't. There are two general approaches:

"Sticky sessions", where the load balancer in front of the instances keeps track of the sessions and routes them to the same instances every time. This is quick and dirty, but it has the major downside of being fragile. For example, if an instance crashes or is shut down for upgrade or downscaling, you lose.

Store the session information somewhere else. Spring makes this trivially easy with Spring Session. (I personally prefer to use Redis and JSON serialization.) In this case, a filter retrieves the session for each request and updates the stored version if necessary.