问:
How can I collect the user's correct choice in my Trivia game?
I have tried multiple things to collect the right answer when the radio button is pressed, but after the game is done I still get a 0 out of 5.
I'm not sure what else to do and have been stuck on this for a while.  Any help will be greatly appreciated!

$(document).ready(function() {

  $("#clickStart").click(function() {
    $('#questions').show(600);
    $('#clock').show(700);
    $('#hide').hide(500);

  });

  (function() {
    var questions = [{
        question: "The great Victoria Desert is located in?",
        choices: ['Canada', 'West Africa', 'Australia', 'North America'],
        correctAnswer: 'Australia'
      },
      {
        question: "The intersecting lines drawn on maps and globes are?",
        choices: ['lattitudes', 'longitudes', 'geographic grids', 'none of the above'],
        correctAnswer: 'geographic gird'
      },
      {
        question: "The landmass of which of the following continents is the least?",
        choices: ['Africa', 'Asia', 'Australia', 'Europe'],
        correctAnswer: 'Australia'
      },
      {
        question: "Without ____ the equator would be much hotter than it is while the poles would be much cooler",
        choices: ['Lattitude of redistribution of heat', 'Cycle of air circulation', 'Global wind pattern', 'All are similiar'],
        correctAnswer: 'All are simliar'
      },
      {
        question: "The habitats valuable for commercially harvested species are called?",
        choices: ['Coral reefs', 'Sea grass bed', 'hot spots', 'None of the above'],
        correctAnswer: 'Sea grass bed'
      }
    ];

    var questionCounter = 0; //Tracks question number
    var selections = []; //Array containing user choices
    var quiz = $("#quiz"); //Quiz div object

    // Display initial question
    displayNext();

    //  'next' button
    $("#next").on("click", function(e) {
      e.preventDefault();

      // Suspend click listener during fade animation
      if (quiz.is(":animated")) {
        return false;
      }
      choose();

      // If no user selection, progress is stopped
      if (isNaN(selections[questionCounter])) {
        alert("Please make a selection!");
      } else {
        questionCounter++;
        displayNext();
      }
    });

    // 'prev' button
    $("#prev").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      choose();
      questionCounter--;
      displayNext();
    });

    // 'Start Over' button
    $("#start").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      questionCounter = 0;
      selections = [];
      displayNext();
      $("#start").hide();
    });

    // Animates buttons on hover
    $(".button").on("mouseenter", function() {
      $(this).addClass("active");
    });
    $(".button").on("mouseleave", function() {
      $(this).removeClass("active");
    });

    // Creates and returns the div that contains the questions and
    // the answer selections
    function createQuestionElement(index) {
      var qElement = $("
", {
        id: "question"
      });

      var header = $("
Question " + (index + 1) + ":
");
      qElement.append(header);

      var question = $("
").append(questions[index].question);
      qElement.append(question);

      var radioButtons = createRadios(index);
      qElement.append(radioButtons);

      return qElement;
    }

    // Creates a list of the answer choices as radio inputs
    function createRadios(index) {
      var radioList = $("
");
      var item;
      var input = "";
      for (var i = 0; i < questions[index].choices.length; i++) {
        item = $("
");
        input = '<input type="radio" name="answer" value=' + i + " />";
        input += questions[index].choices[i];
        item.append(input);
        radioList.append(item);
      }
      return radioList;
    }

    // Reads the user selection and pushes the value to an array
    function choose() {
      selections[questionCounter] = +$('input[name="answer"]:checked').val();
    }

    // Displays next requested element
    function displayNext() {
      quiz.fadeOut(function() {
        $("#question").remove();

        if (questionCounter < questions.length) {
          var nextQuestion = createQuestionElement(questionCounter);
          quiz.append(nextQuestion).fadeIn();
          if (!isNaN(selections[questionCounter])) {
            $("input[value=" + selections[questionCounter] + "]").prop(
              "checked",
              true
            );
          }

          // Controls display of 'prev' button
          if (questionCounter === 1) {
            $("#prev").show();
          } else if (questionCounter === 0) {
            $("#prev").hide();
            $("#next").show();
          }
        } else {
          var scoreElem = displayScore();
          quiz.append(scoreElem).fadeIn();
          $("#next").hide();
          $("#prev").hide();
          $("#start").show();
        }
      });
    }

    // Computes score and returns a paragraph element to be displayed
    function displayScore() {
      var score = $("
", {
        id: "question"
      });

      var numCorrect = 0;
      for (var i = 0; i < selections.length; i++) {
        if (selections[i] === questions[i].correctAnswer) {
          numCorrect++;
        }
      }

      score.append(
        "You got " +
        numCorrect +
        " questions out of " +
        questions.length +
        " right!!!"
      );
      return score;
    }
  })();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 0;
  margin: 0;
  width: 100%;
  background: url(../images/background.png);
  height: 1vh;
  background-repeat: no-repeat;
}

h1 {
  font-family: sans-serif;
  font-size: 3em;
  font-weight: 700;
  color: #fff;
  text-align: center;
}

#title {
  text-decoration: underline;
}

#header {
  text-align: center;
  font-size: 30px;
  font-weight: 700px;
  color: #fff;
  width: 100%;
  height: 200px;
  padding: 7%;
}

.start-button {
  background-color: rgba(0, 0, 0, .7);
  margin-top: 5%;
  width: 300px;
  height: 100px;
}

.start-button:hover {
  background-color: #0246e2;
  color: #f5684f;
  font-size: 50px;
}

button {
  text-align: center;
}

#clock {
  display: none;
  color: #fff;
  font-size: 100px;
  z-index: 1000;
}

#quiz {
  text-indent: 10px;
}

.button {
  border: 4px solid;
  border-radius: 5px;
  width: 40px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  float: right;
  background-color: #DCDCDC;
  color: black;
  margin: 0 2px 0 2px;
}

.button.active {
  background-color: #F8F8FF;
  color: #525252;
}

#questions {
  display: none;
  padding-top: 10%;
  width: 100%;
  height: auto;
}

.button a {
  text-decoration: none;
  color: black;
}

#content {
  width: 100%;
  margin: auto;
  padding: 0 25px 40px 10px;
  background-color: rgba(0, 0, 0, .7);
  border: 4px solid #B0E0E6;
  border-radius: 5px;
  color: #FFFFFF;
  font-weight: bold;
  box-shadow: 5px 5px 5px #888;
  height: 500px;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#prev {
  display: none;
}

#start {
  display: none;
  width: 90px;
}</code>```

<!DOCTYPE html>

  <title>Trivia Game</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">

How Well Do You Know Your Geography?

You have 2 min to guess all the questions...Good Luck!

          <button id="clickStart" class="start-button">Start!</button>

00:00

Next

Prev

 Start Over

```

答:
The problem is here:

```<code>function choose() {
  selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
</code>```

The value of the input is its index. So index===correctAnswer will fail.
You either do:

```<code>if (questions[i].choices[selections[i]] === questions[i].correctAnswer) {
          numCorrect++;
}
</code>```

or you store the index in correctAnswer...

$(document).ready(function() {

  $("#clickStart").click(function() {
    $('#questions').show(600);
    $('#clock').show(700);
    $('#hide').hide(500);

  });

  (function() {
    var questions = [{
        question: "The great Victoria Desert is located in?",
        choices: ['Canada', 'West Africa', 'Australia', 'North America'],
        correctAnswer: 'Australia'
      },
      {
        question: "The intersecting lines drawn on maps and globes are?",
        choices: ['lattitudes', 'longitudes', 'geographic grids', 'none of the above'],
        correctAnswer: 'geographic gird'
      },
      {
        question: "The landmass of which of the following continents is the least?",
        choices: ['Africa', 'Asia', 'Australia', 'Europe'],
        correctAnswer: 'Australia'
      },
      {
        question: "Without ____ the equator would be much hotter than it is while the poles would be much cooler",
        choices: ['Lattitude of redistribution of heat', 'Cycle of air circulation', 'Global wind pattern', 'All are similiar'],
        correctAnswer: 'All are simliar'
      },
      {
        question: "The habitats valuable for commercially harvested species are called?",
        choices: ['Coral reefs', 'Sea grass bed', 'hot spots', 'None of the above'],
        correctAnswer: 'Sea grass bed'
      }
    ];

    var questionCounter = 0; //Tracks question number
    var selections = []; //Array containing user choices
    var quiz = $("#quiz"); //Quiz div object

    // Display initial question
    displayNext();

    //  'next' button
    $("#next").on("click", function(e) {
      e.preventDefault();

      // Suspend click listener during fade animation
      if (quiz.is(":animated")) {
        return false;
      }
      choose();

      // If no user selection, progress is stopped
      if (isNaN(selections[questionCounter])) {
        alert("Please make a selection!");
      } else {
        questionCounter++;
        displayNext();
      }
    });

    // 'prev' button
    $("#prev").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      choose();
      questionCounter--;
      displayNext();
    });

    // 'Start Over' button
    $("#start").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      questionCounter = 0;
      selections = [];
      displayNext();
      $("#start").hide();
    });

    // Animates buttons on hover
    $(".button").on("mouseenter", function() {
      $(this).addClass("active");
    });
    $(".button").on("mouseleave", function() {
      $(this).removeClass("active");
    });

    // Creates and returns the div that contains the questions and
    // the answer selections
    function createQuestionElement(index) {
      var qElement = $("
", {
        id: "question"
      });

      var header = $("
Question " + (index + 1) + ":
");
      qElement.append(header);

      var question = $("
").append(questions[index].question);
      qElement.append(question);

      var radioButtons = createRadios(index);
      qElement.append(radioButtons);

      return qElement;
    }

    // Creates a list of the answer choices as radio inputs
    function createRadios(index) {
      var radioList = $("
");
      var item;
      var input = "";
      for (var i = 0; i < questions[index].choices.length; i++) {
        item = $("
");
        input = '<input type="radio" name="answer" value=' + i + " />";
        input += questions[index].choices[i];
        item.append(input);
        radioList.append(item);
      }
      return radioList;
    }

    // Reads the user selection and pushes the value to an array
    function choose() {
      selections[questionCounter] = +$('input[name="answer"]:checked').val();
    }

    // Displays next requested element
    function displayNext() {
      quiz.fadeOut(function() {
        $("#question").remove();

        if (questionCounter < questions.length) {
          var nextQuestion = createQuestionElement(questionCounter);
          quiz.append(nextQuestion).fadeIn();
          if (!isNaN(selections[questionCounter])) {
            $("input[value=" + selections[questionCounter] + "]").prop(
              "checked",
              true
            );
          }

          // Controls display of 'prev' button
          if (questionCounter === 1) {
            $("#prev").show();
          } else if (questionCounter === 0) {
            $("#prev").hide();
            $("#next").show();
          }
        } else {
          var scoreElem = displayScore();
          quiz.append(scoreElem).fadeIn();
          $("#next").hide();
          $("#prev").hide();
          $("#start").show();
        }
      });
    }

    // Computes score and returns a paragraph element to be displayed
    function displayScore() {
      var score = $("
", {
        id: "question"
      });

      var numCorrect = 0;
      console.log(selections.map((el,i)=>questions[i].choices[el]),questions.map(e=>e.correctAnswer));
      for (var i = 0; i < selections.length; i++) {
        if (questions[i].choices[selections[i]] === questions[i].correctAnswer) {
          numCorrect++;
        }
      }

      score.append(
        "You got " +
        numCorrect +
        " questions out of " +
        questions.length +
        " right!!!"
      );
      return score;
    }
  })();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 0;
  margin: 0;
  width: 100%;
  background: url(../images/background.png);
  height: 1vh;
  background-repeat: no-repeat;
}

h1 {
  font-family: sans-serif;
  font-size: 3em;
  font-weight: 700;
  color: #fff;
  text-align: center;
}

#title {
  text-decoration: underline;
}

#header {
  text-align: center;
  font-size: 30px;
  font-weight: 700px;
  color: #fff;
  width: 100%;
  height: 200px;
  padding: 7%;
}

.start-button {
  background-color: rgba(0, 0, 0, .7);
  margin-top: 5%;
  width: 300px;
  height: 100px;
}

.start-button:hover {
  background-color: #0246e2;
  color: #f5684f;
  font-size: 50px;
}

button {
  text-align: center;
}

#clock {
  display: none;
  color: #fff;
  font-size: 100px;
  z-index: 1000;
}

#quiz {
  text-indent: 10px;
}

.button {
  border: 4px solid;
  border-radius: 5px;
  width: 40px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  float: right;
  background-color: #DCDCDC;
  color: black;
  margin: 0 2px 0 2px;
}

.button.active {
  background-color: #F8F8FF;
  color: #525252;
}

#questions {
  display: none;
  padding-top: 10%;
  width: 100%;
  height: auto;
}

.button a {
  text-decoration: none;
  color: black;
}

#content {
  width: 100%;
  margin: auto;
  padding: 0 25px 40px 10px;
  background-color: rgba(0, 0, 0, .7);
  border: 4px solid #B0E0E6;
  border-radius: 5px;
  color: #FFFFFF;
  font-weight: bold;
  box-shadow: 5px 5px 5px #888;
  height: 500px;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#prev {
  display: none;
}

#start {
  display: none;
  width: 90px;
}</code>```

<!DOCTYPE html>

  <title>Trivia Game</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">

How Well Do You Know Your Geography?

You have 2 min to guess all the questions...Good Luck!

          <button id="clickStart" class="start-button">Start!</button>

00:00

Next

Prev

 Start Over

```

Body:
I have tried multiple things to collect the right answer when the radio button is pressed, but after the game is done I still get a 0 out of 5.
I'm not sure what else to do and have been stuck on this for a while.  Any help will be greatly appreciated!

$(document).ready(function() {

  $("#clickStart").click(function() {
    $('#questions').show(600);
    $('#clock').show(700);
    $('#hide').hide(500);

  });

  (function() {
    var questions = [{
        question: "The great Victoria Desert is located in?",
        choices: ['Canada', 'West Africa', 'Australia', 'North America'],
        correctAnswer: 'Australia'
      },
      {
        question: "The intersecting lines drawn on maps and globes are?",
        choices: ['lattitudes', 'longitudes', 'geographic grids', 'none of the above'],
        correctAnswer: 'geographic gird'
      },
      {
        question: "The landmass of which of the following continents is the least?",
        choices: ['Africa', 'Asia', 'Australia', 'Europe'],
        correctAnswer: 'Australia'
      },
      {
        question: "Without ____ the equator would be much hotter than it is while the poles would be much cooler",
        choices: ['Lattitude of redistribution of heat', 'Cycle of air circulation', 'Global wind pattern', 'All are similiar'],
        correctAnswer: 'All are simliar'
      },
      {
        question: "The habitats valuable for commercially harvested species are called?",
        choices: ['Coral reefs', 'Sea grass bed', 'hot spots', 'None of the above'],
        correctAnswer: 'Sea grass bed'
      }
    ];

    var questionCounter = 0; //Tracks question number
    var selections = []; //Array containing user choices
    var quiz = $("#quiz"); //Quiz div object

    // Display initial question
    displayNext();

    //  'next' button
    $("#next").on("click", function(e) {
      e.preventDefault();

      // Suspend click listener during fade animation
      if (quiz.is(":animated")) {
        return false;
      }
      choose();

      // If no user selection, progress is stopped
      if (isNaN(selections[questionCounter])) {
        alert("Please make a selection!");
      } else {
        questionCounter++;
        displayNext();
      }
    });

    // 'prev' button
    $("#prev").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      choose();
      questionCounter--;
      displayNext();
    });

    // 'Start Over' button
    $("#start").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      questionCounter = 0;
      selections = [];
      displayNext();
      $("#start").hide();
    });

    // Animates buttons on hover
    $(".button").on("mouseenter", function() {
      $(this).addClass("active");
    });
    $(".button").on("mouseleave", function() {
      $(this).removeClass("active");
    });

    // Creates and returns the div that contains the questions and
    // the answer selections
    function createQuestionElement(index) {
      var qElement = $("
", {
        id: "question"
      });

      var header = $("
Question " + (index + 1) + ":
");
      qElement.append(header);

      var question = $("
").append(questions[index].question);
      qElement.append(question);

      var radioButtons = createRadios(index);
      qElement.append(radioButtons);

      return qElement;
    }

    // Creates a list of the answer choices as radio inputs
    function createRadios(index) {
      var radioList = $("
");
      var item;
      var input = "";
      for (var i = 0; i < questions[index].choices.length; i++) {
        item = $("
");
        input = '<input type="radio" name="answer" value=' + i + " />";
        input += questions[index].choices[i];
        item.append(input);
        radioList.append(item);
      }
      return radioList;
    }

    // Reads the user selection and pushes the value to an array
    function choose() {
      selections[questionCounter] = +$('input[name="answer"]:checked').val();
    }

    // Displays next requested element
    function displayNext() {
      quiz.fadeOut(function() {
        $("#question").remove();

        if (questionCounter < questions.length) {
          var nextQuestion = createQuestionElement(questionCounter);
          quiz.append(nextQuestion).fadeIn();
          if (!isNaN(selections[questionCounter])) {
            $("input[value=" + selections[questionCounter] + "]").prop(
              "checked",
              true
            );
          }

          // Controls display of 'prev' button
          if (questionCounter === 1) {
            $("#prev").show();
          } else if (questionCounter === 0) {
            $("#prev").hide();
            $("#next").show();
          }
        } else {
          var scoreElem = displayScore();
          quiz.append(scoreElem).fadeIn();
          $("#next").hide();
          $("#prev").hide();
          $("#start").show();
        }
      });
    }

    // Computes score and returns a paragraph element to be displayed
    function displayScore() {
      var score = $("
", {
        id: "question"
      });

      var numCorrect = 0;
      for (var i = 0; i < selections.length; i++) {
        if (selections[i] === questions[i].correctAnswer) {
          numCorrect++;
        }
      }

      score.append(
        "You got " +
        numCorrect +
        " questions out of " +
        questions.length +
        " right!!!"
      );
      return score;
    }
  })();
});

body {
  padding: 0;
  margin: 0;
  width: 100%;
  background: url(../images/background.png);
  height: 1vh;
  background-repeat: no-repeat;
}

h1 {
  font-family: sans-serif;
  font-size: 3em;
  font-weight: 700;
  color: #fff;
  text-align: center;
}

#title {
  text-decoration: underline;
}

#header {
  text-align: center;
  font-size: 30px;
  font-weight: 700px;
  color: #fff;
  width: 100%;
  height: 200px;
  padding: 7%;
}

.start-button {
  background-color: rgba(0, 0, 0, .7);
  margin-top: 5%;
  width: 300px;
  height: 100px;
}

.start-button:hover {
  background-color: #0246e2;
  color: #f5684f;
  font-size: 50px;
}

button {
  text-align: center;
}

#clock {
  display: none;
  color: #fff;
  font-size: 100px;
  z-index: 1000;
}

#quiz {
  text-indent: 10px;
}

.button {
  border: 4px solid;
  border-radius: 5px;
  width: 40px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  float: right;
  background-color: #DCDCDC;
  color: black;
  margin: 0 2px 0 2px;
}

.button.active {
  background-color: #F8F8FF;
  color: #525252;
}

#questions {
  display: none;
  padding-top: 10%;
  width: 100%;
  height: auto;
}

.button a {
  text-decoration: none;
  color: black;
}

#content {
  width: 100%;
  margin: auto;
  padding: 0 25px 40px 10px;
  background-color: rgba(0, 0, 0, .7);
  border: 4px solid #B0E0E6;
  border-radius: 5px;
  color: #FFFFFF;
  font-weight: bold;
  box-shadow: 5px 5px 5px #888;
  height: 500px;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#prev {
  display: none;
}

#start {
  display: none;
  width: 90px;
}

<!DOCTYPE html>

  <title>Trivia Game</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">

How Well Do You Know Your Geography?

You have 2 min to guess all the questions...Good Luck!

          <button id="clickStart" class="start-button">Start!</button>

00:00

Next

Prev

 Start Over

Body:
The problem is here:

function choose() {
  selections[questionCounter] = +$('input[name="answer"]:checked').val();
}

The value of the input is its index. So index===correctAnswer will fail.
You either do:

if (questions[i].choices[selections[i]] === questions[i].correctAnswer) {
          numCorrect++;
}

or you store the index in correctAnswer...

$(document).ready(function() {

  $("#clickStart").click(function() {
    $('#questions').show(600);
    $('#clock').show(700);
    $('#hide').hide(500);

  });

  (function() {
    var questions = [{
        question: "The great Victoria Desert is located in?",
        choices: ['Canada', 'West Africa', 'Australia', 'North America'],
        correctAnswer: 'Australia'
      },
      {
        question: "The intersecting lines drawn on maps and globes are?",
        choices: ['lattitudes', 'longitudes', 'geographic grids', 'none of the above'],
        correctAnswer: 'geographic gird'
      },
      {
        question: "The landmass of which of the following continents is the least?",
        choices: ['Africa', 'Asia', 'Australia', 'Europe'],
        correctAnswer: 'Australia'
      },
      {
        question: "Without ____ the equator would be much hotter than it is while the poles would be much cooler",
        choices: ['Lattitude of redistribution of heat', 'Cycle of air circulation', 'Global wind pattern', 'All are similiar'],
        correctAnswer: 'All are simliar'
      },
      {
        question: "The habitats valuable for commercially harvested species are called?",
        choices: ['Coral reefs', 'Sea grass bed', 'hot spots', 'None of the above'],
        correctAnswer: 'Sea grass bed'
      }
    ];

    var questionCounter = 0; //Tracks question number
    var selections = []; //Array containing user choices
    var quiz = $("#quiz"); //Quiz div object

    // Display initial question
    displayNext();

    //  'next' button
    $("#next").on("click", function(e) {
      e.preventDefault();

      // Suspend click listener during fade animation
      if (quiz.is(":animated")) {
        return false;
      }
      choose();

      // If no user selection, progress is stopped
      if (isNaN(selections[questionCounter])) {
        alert("Please make a selection!");
      } else {
        questionCounter++;
        displayNext();
      }
    });

    // 'prev' button
    $("#prev").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      choose();
      questionCounter--;
      displayNext();
    });

    // 'Start Over' button
    $("#start").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      questionCounter = 0;
      selections = [];
      displayNext();
      $("#start").hide();
    });

    // Animates buttons on hover
    $(".button").on("mouseenter", function() {
      $(this).addClass("active");
    });
    $(".button").on("mouseleave", function() {
      $(this).removeClass("active");
    });

    // Creates and returns the div that contains the questions and
    // the answer selections
    function createQuestionElement(index) {
      var qElement = $("<div>", {
        id: "question"
      });

      var header = $("<h2>Question " + (index + 1) + ":</h2>");
      qElement.append(header);

      var question = $("<p>").append(questions[index].question);
      qElement.append(question);

      var radioButtons = createRadios(index);
      qElement.append(radioButtons);

      return qElement;
    }

    // Creates a list of the answer choices as radio inputs
    function createRadios(index) {
      var radioList = $("<ul>");
      var item;
      var input = "";
      for (var i = 0; i < questions[index].choices.length; i++) {
        item = $("<li>");
        input = '<input type="radio" name="answer" value=' + i + " />";
        input += questions[index].choices[i];
        item.append(input);
        radioList.append(item);
      }
      return radioList;
    }

    // Reads the user selection and pushes the value to an array
    function choose() {
      selections[questionCounter] = +$('input[name="answer"]:checked').val();
    }

    // Displays next requested element
    function displayNext() {
      quiz.fadeOut(function() {
        $("#question").remove();

        if (questionCounter < questions.length) {
          var nextQuestion = createQuestionElement(questionCounter);
          quiz.append(nextQuestion).fadeIn();
          if (!isNaN(selections[questionCounter])) {
            $("input[value=" + selections[questionCounter] + "]").prop(
              "checked",
              true
            );
          }

          // Controls display of 'prev' button
          if (questionCounter === 1) {
            $("#prev").show();
          } else if (questionCounter === 0) {
            $("#prev").hide();
            $("#next").show();
          }
        } else {
          var scoreElem = displayScore();
          quiz.append(scoreElem).fadeIn();
          $("#next").hide();
          $("#prev").hide();
          $("#start").show();
        }
      });
    }

    // Computes score and returns a paragraph element to be displayed
    function displayScore() {
      var score = $("<p>", {
        id: "question"
      });

      var numCorrect = 0;
      console.log(selections.map((el,i)=>questions[i].choices[el]),questions.map(e=>e.correctAnswer));
      for (var i = 0; i < selections.length; i++) {
        if (questions[i].choices[selections[i]] === questions[i].correctAnswer) {
          numCorrect++;
        }
      }

      score.append(
        "You got " +
        numCorrect +
        " questions out of " +
        questions.length +
        " right!!!"
      );
      return score;
    }
  })();
});

body {
  padding: 0;
  margin: 0;
  width: 100%;
  background: url(../images/background.png);
  height: 1vh;
  background-repeat: no-repeat;
}

h1 {
  font-family: sans-serif;
  font-size: 3em;
  font-weight: 700;
  color: #fff;
  text-align: center;
}

#title {
  text-decoration: underline;
}

#header {
  text-align: center;
  font-size: 30px;
  font-weight: 700px;
  color: #fff;
  width: 100%;
  height: 200px;
  padding: 7%;
}

.start-button {
  background-color: rgba(0, 0, 0, .7);
  margin-top: 5%;
  width: 300px;
  height: 100px;
}

.start-button:hover {
  background-color: #0246e2;
  color: #f5684f;
  font-size: 50px;
}

button {
  text-align: center;
}

#clock {
  display: none;
  color: #fff;
  font-size: 100px;
  z-index: 1000;
}

#quiz {
  text-indent: 10px;
}

.button {
  border: 4px solid;
  border-radius: 5px;
  width: 40px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  float: right;
  background-color: #DCDCDC;
  color: black;
  margin: 0 2px 0 2px;
}

.button.active {
  background-color: #F8F8FF;
  color: #525252;
}

#questions {
  display: none;
  padding-top: 10%;
  width: 100%;
  height: auto;
}

.button a {
  text-decoration: none;
  color: black;
}

#content {
  width: 100%;
  margin: auto;
  padding: 0 25px 40px 10px;
  background-color: rgba(0, 0, 0, .7);
  border: 4px solid #B0E0E6;
  border-radius: 5px;
  color: #FFFFFF;
  font-weight: bold;
  box-shadow: 5px 5px 5px #888;
  height: 500px;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#prev {
  display: none;
}

#start {
  display: none;
  width: 90px;
}

<!DOCTYPE html>
<html>

<head>
  <title>Trivia Game</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">
</head>

<body>

  <body>
    <div class="container">
      <div id="hide" class="row">
        <div id="header" class="text-center col-12-lg">
          <h1>How Well Do You Know Your Geography?</h1>
          <p>You have 2 min to guess all the questions...Good Luck!</p>
          <button id="clickStart" class="start-button">Start!</button>
        </div>
      </div>
      <div id="clock" class="row">
        <div class="col-12-lg text-center" id="display">
          <h3>00:00</h3>
        </div>
      </div>
      <div id="questions" class="row">
        <div class="col-12-lg">
          <div id='content'>
            <br/>
            <div id='quiz'></div>
            <div class='button' id='next'><a href='#'>Next</a></div>
            <div class='button' id='prev'><a href='#'>Prev</a></div>
            <div class='button' id='start'> <a href='#'>Start Over</a></div>
          </div>
        </div>
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="./assets/js/app.js"></script>
  </body>

</html>


来源: stackexchange

问:
Arrays as result type and input for functions
in delphi7 i have a function that i need to return a array as a result type b

"function createsbox(key:tkey):array[0..255] of byte;" this is not allowed it is expecting a "identifyer expected but array found" is the error throw up. seems to work fine if i declare a record type of array but it seems pointless to do this for one function.

答:
The issue is that you're not allowed to create a new type in a function declaration. But that's what you're doing when you specify the return type as array[0..255] of Byte. Instead, declare a named type, and then use it for the return type:

```<code>type
  TSBox = array[0..255] of Byte;

function CreateSBox(const Key: TKey): TSBox;
</code>```

OwnerDisplayName: Arthur

ContentLicense: CC BY-SA 2.5

Body:
The issue is that you're not allowed to create a new type in a function declaration. But that's what you're doing when you specify the return type as array[0..255] of Byte. Instead, declare a named type, and then use it for the return type:

type
  TSBox = array[0..255] of Byte;

function CreateSBox(const Key: TKey): TSBox;

OwnerDisplayName: Rob Kennedy


问:
HTML block stored as var javascript
I am trying to store a block of HTML in javascript variable like this,

```<code>var element = <div class="MMinfoboxRoot">
  <div class="MMinfoboxaddress">
    <div>
      <span class="MMrecordName">leicester
      </span>
      <br>
      <span class="MMdaySpan MMdaySpanTitle">Opening Times
      </span>
      <br>
      <br>
      <span class="MMdaysRoot MMdaysmonday">
        <span class="MMdaySpan">Monday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaystuesday">
        <span class="MMdaySpan">Tuesday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayswednesday">
        <span class="MMdaySpan">Wednesday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaysthursday">
        <span class="MMdaySpan">Thursday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaysfriday">
        <span class="MMdaySpan">Friday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayssaturday">
        <span class="MMdaySpan">Saturday:
        </span>
        <span class="MMdayHoursSpan">9am - 6pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayssunday">
        <span class="MMdaySpan">Sunday:
        </span>
        <span class="MMdayHoursSpan">11am - 5pm
        </span>
      </span>
      <br>
      <br>
      <br>
      <div class="links">
        <strong style="color: rgb(0, 0, 102);">Get directions
        </strong>
        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          <label for="infoboxDir1">From
            <input type="text" id="infoboxDir1" value="birstall" class="text">
          </label>
          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        <a class="go-to-location" onclick="ZoomToLocation( 0 ); return false;" href="#">Zoom to this location
        </a>
      </div>
    </div>
  </div>
</div>
</code>```

However it is throwing js errors saying unecapuslated strings. How can I do this please?

答:
You could store it inside an ID'ed script tag instead:

```<code><html>
<head>
<script id="htmlTemplate" type="text/x-tmpl">
    This <h1>is</h1> templated.
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    $(document).ready(
        function() {
            $('#2nd').html($('#htmlTemplate').text());
        }
    );
</script>
</head>
<body>
    <div id="1st">First div</div>
    <div id="2nd">Second div</div>
</body>
</html>
</code>```

By the way, there's a jQuery plugin using this method: http://api.jquery.com/category/plugins/templates/

Title: HTML block stored as var javascript

Body:
I am trying to store a block of HTML in javascript variable like this,

var element =

      leicester

      Opening Times

        Monday:

        9am - 8pm

        Tuesday:

        9am - 8pm

        Wednesday:

        9am - 8pm

        Thursday:

        9am - 8pm

        Friday:

        9am - 8pm

        Saturday:

        9am - 6pm

        Sunday:

        11am - 5pm

        Get directions

        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          From
            <input type="text" id="infoboxDir1" value="birstall" class="text">

          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        Zoom to this location

However it is throwing js errors saying unecapuslated strings. How can I do this please?

Body:
You could store it inside an ID'ed script tag instead:

<html>
<head>
<script id="htmlTemplate" type="text/x-tmpl">
    This <h1>is</h1> templated.
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    $(document).ready(
        function() {
            $('#2nd').html($('#htmlTemplate').text());
        }
    );
</script>
</head>
<body>
    <div id="1st">First div</div>
    <div id="2nd">Second div</div>
</body>
</html>

By the way, there's a jQuery plugin using this method: http://api.jquery.com/category/plugins/templates/

ContentLicense: CC BY-SA 3.0


问:
jPlayer - how to find out if it's playing
How can I find out if jPlayer is playing?
I tried this alert($.jPlayer.event.playing); but it doesn't work.

答:
```<code>var duration = $('#jquery_jplayer_1').data("jPlayer").status.currentTime;

if(duration){
  // Source is loaded and playing
}
</code>```


问:
sqlalchemy automatically extend query or update or insert upon table definition
in my app I have a mixin that defines 2 fields like start_date and end_date. I've added this mixin to all table declarations which require these fields.

I've also defined a function that returns filters (conditions) to test a timestamp (e.g. now) to be >= start_date and < end_date. Currently I'm manually adding these filters whenever I need to query a table with these fields.

However sometimes me or my colleagues forget to add the filters, and I wonder whether it is possible to automatically extend any query on such a table. Like e.g. an additional function in the mixin that is invoked by SQLalchemy whenever it "compiles" the statement. I'm using 'compile' only as an example here, actually I don't know when or how to best do that.

Any idea how to achieve this?

In case it works for SELECT, does it also work for INSERT and UPDATE?

thanks a lot for your help

Juergen

答:
I tried extending Query but had a hard time. Eventually (and unfortunately) I moved back to my previous approach of little helper functions returning filters and applying them to queries.

I still wish I would find an approach that automatically adds certain filters if a table (Base) has certain columns.

Juergen


问:
Why does my code thinks that 60 is bigger than 135?

i want to get the bigger number and subtract by the smaller number (input's value) even tho they are in the wrong order when you put them into the input like -1 = inputX / 1 = inputY then 1 = greater and -1 smaller, it works with other numbers, but these kinda break it idk why tho what did I do wrong?
  why does it think 60 is bigger than 135? look at the img...

```<code><script type="text/javascript">
var x;
var y;
var big;
var small;
var result;
function calcT() {
    x = document.getElementById("inputX").value;
    y = document.getElementById("inputY").value;
    //result = x - y;
    if(x > y) {
      big = x;
      small = y;
       } else if(x < y) {
      big = y;
      small = x;
       }
    result = parseInt(big) - parseInt(small);
    document.getElementById("resultHere").innerHTML = result;

}
</code>```

答:
You are comparing two strings.  You need to parse them to ints before you do the comparison:

console.log('as strings...', '123' > '50')
console.log('as numbers...', Number('123') > Number('50'))```


问:
EDITLogBack Syslog not working java
I have wrote a simple project to run the log in Ubuntu by follow this example.

ApplicationStarter

```<code>package com.javacodegeeks.examples.logbacksyslogexample;

import com.javacodegeeks.examples.logbacksyslogexample.message.IMessageTransmitter;
import com.javacodegeeks.examples.logbacksyslogexample.message.kiwi.KiwiMessageTransmitterImpl;
import com.javacodegeeks.examples.logbacksyslogexample.message.rsyslog.RsyslogMessageTransmitterImpl;

public class ApplicationStarter {

    /**
     * Main method
     */
    public static void main( final String[] args ) {

        final IMessageTransmitter kiwiMessageTransmitter = new KiwiMessageTransmitterImpl();
        kiwiMessageTransmitter.send( "I am learning to send message to Syslog server" );

        final IMessageTransmitter rsyslogMessageTransmitter = new RsyslogMessageTransmitterImpl();
        rsyslogMessageTransmitter.send( "Logback can easily send message to Syslog server" );
    }
}
</code>```

KiwiMessageTransmitterImpl

```<code>package com.javacodegeeks.examples.logbacksyslogexample.message.kiwi;

import com.javacodegeeks.examples.logbacksyslogexample.message.IMessageTransmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KiwiMessageTransmitterImpl implements IMessageTransmitter {

    private static final Logger LOGGER  = LoggerFactory.getLogger( KiwiMessageTransmitterImpl.class );

    @Override
    public void send( final String message ) {
        LOGGER.info( "Hello! My message is : {}", message );
    }
}
</code>```

RsyslogMessageTransmitterImpl

```<code>package com.javacodegeeks.examples.logbacksyslogexample.message.rsyslog;

import com.javacodegeeks.examples.logbacksyslogexample.message.IMessageTransmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RsyslogMessageTransmitterImpl implements IMessageTransmitter {

    private static final Logger LOGGER  = LoggerFactory.getLogger( RsyslogMessageTransmitterImpl.class );

    @Override
    public void send( final String message ) {
        LOGGER.info( "Hello! My message is : {}", message );
    }
}
</code>```

IMessageTransmitter

```<code>package com.javacodegeeks.examples.logbacksyslogexample.message;

public interface IMessageTransmitter {

    void send(final String message);
}
</code>```

When I run my project , I get the same things! The
message from Java are not sending to syslog !

Here the logback.xml. I put in resources folder.

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

    <appender name="KIWI" class="ch.qos.logback.classic.net.SyslogAppender">
        <syslogHost>localhost</syslogHost>
        <facility>LOCAL0</facility>
        <suffixPattern>%thread: %-5level %logger{36} - %msg%n</suffixPattern>
    </appender>

    <appender name="RSYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
        <!-- Ubuntu Server host name -->
        <syslogHost>centol</syslogHost>
        <facility>LOCAL1</facility>
        <suffixPattern>%thread: %-5level %logger{36} - %msg%n</suffixPattern>
    </appender>

    <logger name="com.javacodegeeks.examples.logbacksyslogexample.message.kiwi" level="INFO">
        <appender-ref ref="KIWI" />
    </logger>

    <logger name="com.javacodegeeks.examples.logbacksyslogexample.message.rsyslog" level="INFO">
        <appender-ref ref="RSYSLOG" />
    </logger>

</configuration>
</code>```

I use this command to examine syslog. The syslog output looked correctly now. Unfortunately, the message send from Netbeans(JAVA) still not receiving in the syslog.

Try cat /var/log/syslog (small part of the output)

```<code>Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$
</code>```

Not sure is it because of the syslogHost and facility.

答:
FINALLY I get it to work! What a nightmare...

I follow Rsyslog : Output Logs to Remote Host to configure Syslog server.

Go to rsyslog.conf

```<code>sudo vim etc/rsyslog.conf
</code>```

Uncomment these two lines.

```<code>module(load="imtcp")
input(type="imtcp" port="514")
</code>```

Save and exit. Then Restart service.

```<code>sudo service rsyslog restart
</code>```

MAGIC !

Title: EDITLogBack Syslog not working java

Body:
I have wrote a simple project to run the log in Ubuntu by follow this example.

ApplicationStarter

package com.javacodegeeks.examples.logbacksyslogexample;

import com.javacodegeeks.examples.logbacksyslogexample.message.IMessageTransmitter;
import com.javacodegeeks.examples.logbacksyslogexample.message.kiwi.KiwiMessageTransmitterImpl;
import com.javacodegeeks.examples.logbacksyslogexample.message.rsyslog.RsyslogMessageTransmitterImpl;

public class ApplicationStarter {

    /**
     * Main method
     */
    public static void main( final String[] args ) {

        final IMessageTransmitter kiwiMessageTransmitter = new KiwiMessageTransmitterImpl();
        kiwiMessageTransmitter.send( "I am learning to send message to Syslog server" );

        final IMessageTransmitter rsyslogMessageTransmitter = new RsyslogMessageTransmitterImpl();
        rsyslogMessageTransmitter.send( "Logback can easily send message to Syslog server" );
    }
}

KiwiMessageTransmitterImpl

package com.javacodegeeks.examples.logbacksyslogexample.message.kiwi;

import com.javacodegeeks.examples.logbacksyslogexample.message.IMessageTransmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KiwiMessageTransmitterImpl implements IMessageTransmitter {

    private static final Logger LOGGER  = LoggerFactory.getLogger( KiwiMessageTransmitterImpl.class );

    @Override
    public void send( final String message ) {
        LOGGER.info( "Hello! My message is : {}", message );
    }
}

RsyslogMessageTransmitterImpl

package com.javacodegeeks.examples.logbacksyslogexample.message.rsyslog;

import com.javacodegeeks.examples.logbacksyslogexample.message.IMessageTransmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RsyslogMessageTransmitterImpl implements IMessageTransmitter {

    private static final Logger LOGGER  = LoggerFactory.getLogger( RsyslogMessageTransmitterImpl.class );

    @Override
    public void send( final String message ) {
        LOGGER.info( "Hello! My message is : {}", message );
    }
}

IMessageTransmitter

package com.javacodegeeks.examples.logbacksyslogexample.message;

public interface IMessageTransmitter {

    void send(final String message);
}

When I run my project , I get the same things! The
message from Java are not sending to syslog !

Here the logback.xml. I put in resources folder.

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

    <appender name="KIWI" class="ch.qos.logback.classic.net.SyslogAppender">
        <syslogHost>localhost</syslogHost>
        <facility>LOCAL0</facility>
        <suffixPattern>%thread: %-5level %logger{36} - %msg%n</suffixPattern>
    </appender>

    <appender name="RSYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">

        <syslogHost>centol</syslogHost>
        <facility>LOCAL1</facility>
        <suffixPattern>%thread: %-5level %logger{36} - %msg%n</suffixPattern>
    </appender>

    <logger name="com.javacodegeeks.examples.logbacksyslogexample.message.kiwi" level="INFO">
        <appender-ref ref="KIWI" />
    </logger>

    <logger name="com.javacodegeeks.examples.logbacksyslogexample.message.rsyslog" level="INFO">
        <appender-ref ref="RSYSLOG" />
    </logger>

</configuration>

I use this command to examine syslog. The syslog output looked correctly now. Unfortunately, the message send from Netbeans(JAVA) still not receiving in the syslog.

Try cat /var/log/syslog (small part of the output)

Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$

Not sure is it because of the syslogHost and facility.

Body:
FINALLY I get it to work! What a nightmare...

I follow Rsyslog : Output Logs to Remote Host to configure Syslog server.

Go to rsyslog.conf

sudo vim etc/rsyslog.conf

Uncomment these two lines.

module(load="imtcp")
input(type="imtcp" port="514")

Save and exit. Then Restart service.

sudo service rsyslog restart

MAGIC !


问:
Where is EJB method run
I'm calling an EJB method remotly using next code:

```<code>RemCallRemote rc = null;
String Text = "";
Properties props = new Properties();

//Filling the properties for connection to a remote server
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sap.engine.services.jndi.InitialContextFactoryImpl");

props.put(Context.PROVIDER_URL, "hostaddress:50004");

props.put(Context.SECURITY_PRINCIPAL, "LOGINNAME");

props.put(Context.SECURITY_CREDENTIALS, "*****");

props.put(Context.URL_PKG_PREFIXES, "com.sap.engine.services");

InitialContext ctx = new InitialContext(props);

//getting a reference to an interface
rc = (RemCallRemote)ctx.lookup("ejb:/appName=sap.com/RemoteCallEAR, jarName=RemoteCallEJB.jar, beanName=RemCall, interfaceName=RemCallRemote");

//calling an EJB method
Text = rc.Check();
</code>```

The code works fine, but my question is: Where is the EJB method run? Is it run always on 'hostaddress' machine or anywhere else?

答:
The host address is where the JNDI server is. It's not always the same server where the EJB's themselves are running, though in most cases it is.

For exceptional cases, you can register an EJB from server1 in a JNDI server on server2 that serves as some sort of cluster manager. Not really sure if it's possible with SAP, but on e.g. WebSphere you can.

Title: Where is EJB method run

Body:
I'm calling an EJB method remotly using next code:

RemCallRemote rc = null;
String Text = "";
Properties props = new Properties();

//Filling the properties for connection to a remote server
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sap.engine.services.jndi.InitialContextFactoryImpl");

props.put(Context.PROVIDER_URL, "hostaddress:50004");

props.put(Context.SECURITY_PRINCIPAL, "LOGINNAME");

props.put(Context.SECURITY_CREDENTIALS, "*****");

props.put(Context.URL_PKG_PREFIXES, "com.sap.engine.services");

InitialContext ctx = new InitialContext(props);

//getting a reference to an interface
rc = (RemCallRemote)ctx.lookup("ejb:/appName=sap.com/RemoteCallEAR, jarName=RemoteCallEJB.jar, beanName=RemCall, interfaceName=RemCallRemote");

//calling an EJB method
Text = rc.Check();

The code works fine, but my question is: Where is the EJB method run? Is it run always on 'hostaddress' machine or anywhere else?


问:
How can I retrieve product description using Amazon API
Does anyone know how to retrieve the product description from the Amazon API? I have asked their forum with no success. I can access the detailed page URL from an ItemLookUp but then I have to screenscrape which is not ideal.</p>

答:
Hey, I know this is a bit old, but I've found the EditorialReview part of the response contains the product description. I guess the cravet that Tom talks about still applies, but at least its a way to get to the description without reverting to screen scraping (which is never a good thing!) :)

See this page of the Amazon product API: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/

EditorialReview Response Group

For each item in the response, the
  EditorialReview response group returns
  Amazon's review of the item, which, on
  the Detail page, is labeled the
  Product Description.

No nasty screen scraping required! :)

Andy.

ContentLicense: CC BY-SA 4.0


问:
How to Query parquet data from Amazon Athena?
Athena creates a temporary table using fields in S3 table. I have done this using JSON data. Could you help me on how to create table using parquet data?

I have tried following:

Converted sample JSON data to parquet data.

Uploaded parquet data to S3.

Created temporary table using columns of JSON data.

By doing this I am able to a execute query but the result is empty.

Is this approach right or is there any other approach to be followed on parquet data?

Sample json data:

```<code>{"_id":"0899f824e118d390f57bc2f279bd38fe","_rev":"1-81cc25723e02f50cb6fef7ce0b0f4f38","deviceId":"BELT001","timestamp":"2016-12-21T13:04:10:066Z","orgid":"fedex","locationId":"LID001","UserId":"UID001","SuperviceId":"SID001"},
{"_id":"0899f824e118d390f57bc2f279bd38fe","_rev":"1-81cc25723e02f50cb6fef7ce0b0f4f38","deviceId":"BELT001","timestamp":"2016-12-21T13:04:10:066Z","orgid":"fedex","locationId":"LID001","UserId":"UID001","SuperviceId":"SID001"}
</code>```

答:
If your table definition is valid but not getting any rows, try this

-- The MSCK REPAIR TABLE command will load all partitions into the table.
-- This command can take a while to run depending on the number of partitions to be loaded.

MSCK REPAIR TABLE {tablename}

Body:
Athena creates a temporary table using fields in S3 table. I have done this using JSON data. Could you help me on how to create table using parquet data?

I have tried following:

Converted sample JSON data to parquet data.

Uploaded parquet data to S3.

Created temporary table using columns of JSON data.

By doing this I am able to a execute query but the result is empty.

Is this approach right or is there any other approach to be followed on parquet data?

Sample json data:

{"_id":"0899f824e118d390f57bc2f279bd38fe","_rev":"1-81cc25723e02f50cb6fef7ce0b0f4f38","deviceId":"BELT001","timestamp":"2016-12-21T13:04:10:066Z","orgid":"fedex","locationId":"LID001","UserId":"UID001","SuperviceId":"SID001"},
{"_id":"0899f824e118d390f57bc2f279bd38fe","_rev":"1-81cc25723e02f50cb6fef7ce0b0f4f38","deviceId":"BELT001","timestamp":"2016-12-21T13:04:10:066Z","orgid":"fedex","locationId":"LID001","UserId":"UID001","SuperviceId":"SID001"}


问:
How do I save a list in a .py file?
I am reading the contents of a normal text file and then trying to save it in  a .py file as a list variable.

Initially what I tried was reading the contents of the file and then storing them in a list. Then I wrote them to a .py file by myself.

```<code>>>> f = open("word.txt","r+")
>>> string = f.read()
>>> string = (string.split("\n")) #checkpoint
>>> string = "\',\' ".join(string)
>>> len(string)
147636
>>> f.close()
>>> f = open("word.py","w")
>>> f.write("word = [\'")
>>> f.write(string)
>>> f.write("\']")
>>> f.close()
</code>```

However when I try to use import word
I get the following error

SyntaxError: EOF while scanning triple-quoted string literal

Is there any way I can save the list string at the checkpoint shown into .py file?

答:
pprint.pprint might help. pprint() uses repr() to take care of any string-escape requirements (for example, a lone ' embedded in the middle of the string.) It also takes a stream= parameter to redirect the output to a file.

You could equally well  use repr(string) instead of pprint(string). I chose pprint() to split the result onto multiple lines.

Note also the use of with open(...) as ...:. This automatically closes the file when the indent block is exited.

```<code>from pprint import pprint

with open('word.txt') as f:
    string = f.read().split('\n')
with open('word.py', 'w') as f:
    f.write('word = ')
    pprint(string, stream=f)
</code>```

Title: How do I save a list in a .py file?

Body:
I am reading the contents of a normal text file and then trying to save it in  a .py file as a list variable.

Initially what I tried was reading the contents of the file and then storing them in a list. Then I wrote them to a .py file by myself.

>>> f = open("word.txt","r+")
>>> string = f.read()
>>> string = (string.split("\n")) #checkpoint
>>> string = "\',\' ".join(string)
>>> len(string)
147636
>>> f.close()
>>> f = open("word.py","w")
>>> f.write("word = [\'")
>>> f.write(string)
>>> f.write("\']")
>>> f.close()

However when I try to use import word
I get the following error

SyntaxError: EOF while scanning triple-quoted string literal

Is there any way I can save the list string at the checkpoint shown into .py file?

Body:
pprint.pprint might help. pprint() uses repr() to take care of any string-escape requirements (for example, a lone ' embedded in the middle of the string.) It also takes a stream= parameter to redirect the output to a file.

You could equally well  use repr(string) instead of pprint(string). I chose pprint() to split the result onto multiple lines.

Note also the use of with open(...) as ...:. This automatically closes the file when the indent block is exited.

from pprint import pprint

with open('word.txt') as f:
    string = f.read().split('\n')
with open('word.py', 'w') as f:
    f.write('word = ')
    pprint(string, stream=f)


问:
how to parse html contents returned as a response from a webserver and show a specific tag value in a combobox in desktop application in vb.net
i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.

my code to get response from webserver is :

```<code>enter code here
</code>```

Imports System.IO

Imports System.Net

Imports System.Xml

Imports System.Text.Encoder

Public Class login

```<code>Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End
End Sub

Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

End Sub

Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
    Dim strId As String = txt_uid.Text
    Dim strPwd As String = txt_pwd.Text
    Dim oEncoder As New System.Text.ASCIIEncoding
    Dim postData As String = "UM_username=" + strId
    postData += ("&UM_password=" + strPwd)

    Dim data As Byte() = oEncoder.GetBytes(postData)
    MsgBox(postData)

    Dim webStream As Stream

    Dim webResponse As String = ""

    Dim req As HttpWebRequest

    Dim res As HttpWebResponse
    Dim Output As String
    'Dim Posit1 As Int32
    'Dim Posit2 As Int32

  req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)
</code>```

req.ContentType = "application/x-www-form-urlencoded"
        req.KeepAlive = False
        req.Method = "POST"
        res = req.GetResponse()

```<code>    webStream = res.GetResponseStream()

    Dim webStreamReader As New StreamReader(webStream)
    While webStreamReader.Peek >= 0
        Output = webStreamReader.ReadToEnd()
        RichTextBox1.Text = Output
</code>```

Msgbox(Output)

```<code>    End While

End Sub
</code>```

End Class

this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form

答: Well...if you can be sure that your request returns valid XHTML (which is XML indeed), you might be able to use an XPath expression.</p>

Body:
i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.

my code to get response from webserver is :

enter code here

Imports System.IO

Imports System.Net

Imports System.Xml

Imports System.Text.Encoder

Public Class login

Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End
End Sub

Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

End Sub

Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
    Dim strId As String = txt_uid.Text
    Dim strPwd As String = txt_pwd.Text
    Dim oEncoder As New System.Text.ASCIIEncoding
    Dim postData As String = "UM_username=" + strId
    postData += ("&UM_password=" + strPwd)

    Dim data As Byte() = oEncoder.GetBytes(postData)
    MsgBox(postData)

    Dim webStream As Stream

    Dim webResponse As String = ""

    Dim req As HttpWebRequest

    Dim res As HttpWebResponse
    Dim Output As String
    'Dim Posit1 As Int32
    'Dim Posit2 As Int32

  req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)

req.ContentType = "application/x-www-form-urlencoded"
        req.KeepAlive = False
        req.Method = "POST"
        res = req.GetResponse()

    webStream = res.GetResponseStream()

    Dim webStreamReader As New StreamReader(webStream)
    While webStreamReader.Peek >= 0
        Output = webStreamReader.ReadToEnd()
        RichTextBox1.Text = Output

Msgbox(Output)

    End While

End Sub

End Class

this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form


问:
Pagination using startAt() when ordering by child
I am trying to just retrieve a list of records, sorted by one of the fields in each record, and I would like to be able to retrieve the data in pages.

According to the Firebase documentation, the reference.startAt() method has an optional 2nd parameter, which is:

The child key to start at. This argument is only allowed if ordering by child, value, or priority.

First off, here is the data:

```<code>{
  "products" : {
    "-KlsqFgVWwUrA-j0VsZS" : {
      "name" : "Product 4",
      "price" : 666
    },
    "-Klst-cLSckuwAuNAJF8" : {
      "name" : "Product 1",
      "price" : 100
    },
    "-Klst7IINdt8YeMmauRz" : {
      "name" : "Product 2",
      "price" : 50
    },
    "-Klst9KfM2QWp8kXrOlR" : {
      "name" : "Product 6",
      "price" : 30
    },
    "-KlstB51ap1L2tcK8cL6" : {
      "name" : "Product 5",
      "price" : 99
    },
    "-KlstDR5cCayGH0XKtZ0" : {
      "name" : "Product 3",
      "price" : 500
    }
  }
}
</code>```

And here is the code which is able to retrieve Page 1 (lowest priced item + 2nd lowest priced + 3rd lowest priced):

(I am using Firebase JS SDK 4.1.1)

```<code>'use strict';
var firebase = require('firebase');

firebase.initializeApp({
    apiKey: "your-api-key",
    authDomain: "your-firebase-domain",
    databaseURL: "https://your-db.firebaseio.com",
    projectId: "your-project",
    storageBucket: "your-bucket.appspot.com",
    messagingSenderId: "your-sender-id"
})

firebase.database().ref('products')
.orderByChild('price')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})
</code>```

Output:

TJ:database tjwoon$ node test.js

```<code>-Klst9KfM2QWp8kXrOlR: {"name":"Product 6","price":30}
-Klst7IINdt8YeMmauRz: {"name":"Product 2","price":50}
-KlstB51ap1L2tcK8cL6: {"name":"Product 5","price":99}
</code>```

Page 2 should be the 3rd lowest, 4th lowest, and 5th lowest priced products, which means my code need one additional line:

```<code>firebase.database().ref('products')
.orderByChild('price')
.startAt(null, '-KlstB51ap1L2tcK8cL6')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})
</code>```

Output:

```<code>TJ:database tjwoon$ node test.js
-Klst9KfM2QWp8kXrOlR: {"name":"Product 6","price":30}
-Klst7IINdt8YeMmauRz: {"name":"Product 2","price":50}
-KlstB51ap1L2tcK8cL6: {"name":"Product 5","price":99}
</code>```

The problem is that it is returning Page 1 again. If the documentation is correct, the results should start at the record with key -KlstB51ap1L2tcK8cL6.

I have tried adding an .indexOn rule for the price field, but the results remained identical.

If I remove the orderByChild() line, then the results do start from the given key, but of course the sorting is incorrect, plus it behaves contrary to the documentation...

I found these other Stack Overflow posts which describe the same problem:

Firebase orderByChild with startAt()'s second argument w/ pagination not odering

(see comment below. I don't have enough reputation to include the link here)

However there are no answers to those questions and quite few responses. There are no issues in the Github repository which match the search term startat.

Is anyone else facing the same issue? This problem makes it impossible to retrieve a sorted list in a paginated manner...

答:
You're almost there!

The problem is in how you call startAt for the second page:

```<code>.startAt(null, '-KlstB51ap1L2tcK8cL6')
</code>```

To get the correct results you need to pass in both the price and the key of the so-called anchor item:

```<code>.startAt(99, '-KlstB51ap1L2tcK8cL6')
</code>```

With that Firebase will find all items with price 99 and then return items starting at key '-KlstB51ap1L2tcK8cL6'.

Body:
I am trying to just retrieve a list of records, sorted by one of the fields in each record, and I would like to be able to retrieve the data in pages.

According to the Firebase documentation, the reference.startAt() method has an optional 2nd parameter, which is:

The child key to start at. This argument is only allowed if ordering by child, value, or priority.

First off, here is the data:

{
  "products" : {
    "-KlsqFgVWwUrA-j0VsZS" : {
      "name" : "Product 4",
      "price" : 666
    },
    "-Klst-cLSckuwAuNAJF8" : {
      "name" : "Product 1",
      "price" : 100
    },
    "-Klst7IINdt8YeMmauRz" : {
      "name" : "Product 2",
      "price" : 50
    },
    "-Klst9KfM2QWp8kXrOlR" : {
      "name" : "Product 6",
      "price" : 30
    },
    "-KlstB51ap1L2tcK8cL6" : {
      "name" : "Product 5",
      "price" : 99
    },
    "-KlstDR5cCayGH0XKtZ0" : {
      "name" : "Product 3",
      "price" : 500
    }
  }
}

And here is the code which is able to retrieve Page 1 (lowest priced item + 2nd lowest priced + 3rd lowest priced):

(I am using Firebase JS SDK 4.1.1)

'use strict';
var firebase = require('firebase');

firebase.initializeApp({
    apiKey: "your-api-key",
    authDomain: "your-firebase-domain",
    databaseURL: "https://your-db.firebaseio.com",
    projectId: "your-project",
    storageBucket: "your-bucket.appspot.com",
    messagingSenderId: "your-sender-id"
})

firebase.database().ref('products')
.orderByChild('price')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})

Output:

TJ:database tjwoon$ node test.js

-Klst9KfM2QWp8kXrOlR: {"name":"Product 6","price":30}
-Klst7IINdt8YeMmauRz: {"name":"Product 2","price":50}
-KlstB51ap1L2tcK8cL6: {"name":"Product 5","price":99}

Page 2 should be the 3rd lowest, 4th lowest, and 5th lowest priced products, which means my code need one additional line:

firebase.database().ref('products')
.orderByChild('price')
.startAt(null, '-KlstB51ap1L2tcK8cL6')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})

Output:

TJ:database tjwoon$ node test.js
-Klst9KfM2QWp8kXrOlR: {"name":"Product 6","price":30}
-Klst7IINdt8YeMmauRz: {"name":"Product 2","price":50}
-KlstB51ap1L2tcK8cL6: {"name":"Product 5","price":99}

The problem is that it is returning Page 1 again. If the documentation is correct, the results should start at the record with key -KlstB51ap1L2tcK8cL6.

I have tried adding an .indexOn rule for the price field, but the results remained identical.

If I remove the orderByChild() line, then the results do start from the given key, but of course the sorting is incorrect, plus it behaves contrary to the documentation...

I found these other Stack Overflow posts which describe the same problem:

Firebase orderByChild with startAt()'s second argument w/ pagination not odering

(see comment below. I don't have enough reputation to include the link here)

However there are no answers to those questions and quite few responses. There are no issues in the Github repository which match the search term startat.

Is anyone else facing the same issue? This problem makes it impossible to retrieve a sorted list in a paginated manner...

Body:
You're almost there!

The problem is in how you call startAt for the second page:

.startAt(null, '-KlstB51ap1L2tcK8cL6')

To get the correct results you need to pass in both the price and the key of the so-called anchor item:

.startAt(99, '-KlstB51ap1L2tcK8cL6')

With that Firebase will find all items with price 99 and then return items starting at key '-KlstB51ap1L2tcK8cL6'.


问:
SOLR: Document is missing mandatory uniqueKey field: id
I have just started with the solr-6.5.1, trying to import data from Oracle DB.
My data does not have any Unique ID, searched through various forums and found out that using class="solr.UUIDUpdateProcessorFactory" this can be resolved. but stil getting the same error. below is the snippet of my managed-schema and solrconfig.xml.

solrconfig.xml

```<code><requestHandler name="/update" class="solr.UpdateRequestHandler">
        <lst name="defaults">
            <str name="update.chain">uuid</str>
        </lst>
    </requestHandler>

    <updateRequestProcessorChain name="uuid">
        <processor class="solr.UUIDUpdateProcessorFactory">
            <str name="fieldName">id</str>
        </processor>
        <processor class="solr.RunUpdateProcessorFactory" />
    </updateRequestProcessorChain>
</code>```

managed-schema

```<code><field name="id" type="uuid" indexed="true" stored="true" required="true" />
    <field name="SERVICEACCOUNTNUMBER" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="USERNAME" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="NAME" type="string" indexed="true" stored="true"  multiValued="false" />
    <field name="TRANSACTION_DATE" type="date" indexed="true" stored="true"  />
    <field name="PROCESSSTATUS" type="string" indexed="true" stored="true" />
    <field name="RECHARGE_MODE" type="string" indexed="true" stored="true"  />
    <field name="PROCESSRECHARGEREQUESTNO" type="string" indexed="true" stored="true"  />
    <field name="PACKAGE_ID" type="string" indexed="true" stored="true"  />
    <field name="PACKAGENAME" type="string" indexed="true" stored="true"  />
    <field name="AMOUNT" type="int" indexed="true" stored="true" multiValued="true" />
    <field name="CREDITDOCUMENTNUMBER" type="string" indexed="true" stored="true" multiValued="true" />
    <field name="DEBITDOCUMENTNUMBER" type="string" indexed="true" stored="true"   />
    <field name="SERVICE_TYPE" type="string" indexed="true" stored="true" multiValued="true" />
</code>```

Please help

答:
answer credits to post solr uuid with error document is missing mandatory uniquekey field id

updated the solrconfig.xml to

```<code><requestHandler name="/dataimport" class="solr.DataImportHandler">
    <lst name="defaults">
      <str name="config">data-config.xml</str>
      <str name="update.chain">uuid</str>
    </lst>
 </requestHandler>

<updateRequestProcessorChain name="uuid">
      <processor class="solr.UUIDUpdateProcessorFactory">
          <str name="fieldName">id</str>
      </processor>
      <processor class="solr.RunUpdateProcessorFactory"/>
</updateRequestProcessorChain>
</code>```

Body:
I have just started with the solr-6.5.1, trying to import data from Oracle DB.
My data does not have any Unique ID, searched through various forums and found out that using class="solr.UUIDUpdateProcessorFactory" this can be resolved. but stil getting the same error. below is the snippet of my managed-schema and solrconfig.xml.

solrconfig.xml

<requestHandler name="/update" class="solr.UpdateRequestHandler">
        <lst name="defaults">
            <str name="update.chain">uuid</str>
        </lst>
    </requestHandler>

    <updateRequestProcessorChain name="uuid">
        <processor class="solr.UUIDUpdateProcessorFactory">
            <str name="fieldName">id</str>
        </processor>
        <processor class="solr.RunUpdateProcessorFactory" />
    </updateRequestProcessorChain>

managed-schema

<field name="id" type="uuid" indexed="true" stored="true" required="true" />
    <field name="SERVICEACCOUNTNUMBER" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="USERNAME" type="string" indexed="true" stored="true" required="true" multiValued="false" />
    <field name="NAME" type="string" indexed="true" stored="true"  multiValued="false" />
    <field name="TRANSACTION_DATE" type="date" indexed="true" stored="true"  />
    <field name="PROCESSSTATUS" type="string" indexed="true" stored="true" />
    <field name="RECHARGE_MODE" type="string" indexed="true" stored="true"  />
    <field name="PROCESSRECHARGEREQUESTNO" type="string" indexed="true" stored="true"  />
    <field name="PACKAGE_ID" type="string" indexed="true" stored="true"  />
    <field name="PACKAGENAME" type="string" indexed="true" stored="true"  />
    <field name="AMOUNT" type="int" indexed="true" stored="true" multiValued="true" />
    <field name="CREDITDOCUMENTNUMBER" type="string" indexed="true" stored="true" multiValued="true" />
    <field name="DEBITDOCUMENTNUMBER" type="string" indexed="true" stored="true"   />
    <field name="SERVICE_TYPE" type="string" indexed="true" stored="true" multiValued="true" />

Please help

Body:
answer credits to post solr uuid with error document is missing mandatory uniquekey field id

updated the solrconfig.xml to

<requestHandler name="/dataimport" class="solr.DataImportHandler">
    <lst name="defaults">
      <str name="config">data-config.xml</str>
      <str name="update.chain">uuid</str>
    </lst>
 </requestHandler>

<updateRequestProcessorChain name="uuid">
      <processor class="solr.UUIDUpdateProcessorFactory">
          <str name="fieldName">id</str>
      </processor>
      <processor class="solr.RunUpdateProcessorFactory"/>
</updateRequestProcessorChain>


问:
How to Get the Correct Time Format When the InTime and OutTime Reaches after 12AM in SQL Server
I have tried to do punch in punch out time of the employees, I have tried the below query, it works fine when the punch in time is like 10:00am and punch out time like 6:00pm, and shows TotalDuration as 8hrs.

But it fails when the punch in time like 9:00pm and 5:00am.

About the problem, I have done calculation based on punch in and punch out which shows total hours.

But when the user punches after 12am it shows as 00:00 on both the punch in and punch out and TotalDuration as 0

The output that I get

```<code>    I:9:05AM\nO:5:32PM\nT:8:27 \nS :~Present On WeeklyOff - WeekOff,:Saturday,:
    I:12:00AM\nO:12:00AM\nT:0:0  \nS :~Present On WeeklyOff - WeekOff,:Saturday,:
</code>```

Here is my query :

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY e.EmployeeCode,AttendanceDate DESC) AS 'SNo',
    e.EmployeeCode AS 'EmpID',
    e.EmployeeName AS 'EmpName',
    d.DepartmentFName AS 'DeptName',
    CONVERT(VARCHAR, a.AttendanceDate, 110) AS 'AttendanceDate',
    'I:' + LTRIM (RIGHT(CONVERT(VARCHAR(50),+'I:'+CONVERT(VARCHAR(50),+CONVERT(DATETIME, a.InTime,0)),100),7))+'\n'+'O:'+LTRIM (RIGHT(CONVERT(VARCHAR(20),CONVERT(DATETIME, CASE WHEN a.OutTime LIKE '%(%' THEN LEFT(a.OutTime, CHARINDEX('(', a.OutTime + ')') - 1)
   ELSE a.OutTime END,0),100),7))+'\n'+ 'T:'+ CONVERT(CHAR(5),CAST(CAST(CASE WHEN  a.InTime> a.OutTime THEN DATEDIFF (MINUTE,CAST(a.InTime as datetime),DateAdd(day,1,CAST(a.OutTime AS datetime)))
 ELSE DATEDIFF(MINUTE, a.InTime , a.OutTime) END AS INTEGER)/60 AS VARCHAR)+':'+CAST(cast(CASE WHEN  a.InTime> a.OutTime THEN DATEDIFF (MINUTE,CAST(a.InTime as datetime),DateAdd(day,1,CAST(a.OutTime AS datetime)))
 ELSE DATEDIFF(MINUTE, a.InTime , a.OutTime) END AS INTEGER)%60 AS VARCHAR),108)+ '\n' + 'S :~' +  a.[Status]+ ' - ' + CASE WHEN a.[Status] = 'Present' THEN '' WHEN a.[Status] = 'On WeeklyOff' and la.LeaveType<>'' THEN la.LeaveType
   WHEN DATENAME(dw, a.AttendanceDate)='Sunday' THEN 'WeekOff' WHEN DATENAME(dw, a.AttendanceDate)='SaturDay'
   THEN 'WeekOff' ELSE la.LeaveType COLLATE SQL_Latin1_General_CP1_CI_AS   ENd + ',:'+DATENAME(dw, a.AttendanceDate) + ',:'+ CASE WHEN la.LeaveStatus is null THEN '' ELSE la.LeaveStatus END AS 'PunchDetails',
   '0LOP' AS 'NoOfLOP',
   '0WkEnd' AS 'NoOfWkEndWorked' ,ISNULL(la.LeaveStatus,'') AS 'LeaveStatus'

-- INTO #Result02
FROM
    esslsmartofficenew.dbo.Employees e (NOLOCK)
INNER JOIN
    esslsmartofficenew.dbo.AttendanceLogs a (NOLOCK) ON e.EmployeeId = a.EmployeeId
INNER JOIN
    esslsmartofficenew.dbo.Departments d (NOLOCK) ON d.DepartmentId = e.DepartmentId
INNER JOIN
    esslsmartofficenew.dbo.Shifts s (NOLOCK) ON s.ShiftId = a.ShiftId
LEFT JOIN
    IntranetReleaseNew.dbo.LeaveApplication la ON la.EmpId collate SQL_Latin1_General_CP1_CI_AS = e.employeecode collate SQL_Latin1_General_CP1_CI_AS
                                               AND a.AttendanceDate >= la.leavefromdate
                                               AND a.AttendanceDate <= la.leaveTodate
WHERE
    e.DepartmentId = '10' AND
    e.EmployeeName NOT LIKE '%del_%' AND
    e.EmployeeCode LIKE '%S%' AND
    e.EmployeeCode NOT LIKE '%Del_%' AND
    a.AttendanceDate = '2017-05-13'
</code>```

答:
I do not want to try and untangle your code, so I am just going to address the relevant calculations.

If we can assume that when the outtime is less than the intime, then the outtime occured the next day we can use something like this:

Note: I am using a common table expression to reduce repeating the code that converts the times to datetime with the above assumption, you could use a subquery/derived table to the same effect.

```<code>create table t (employeeid int, attendancedate date, intime time(0), outtime time(0));
insert into t values (1,'20170601','21:00:00','05:00:00'),(2,'20170603','05:00:00','21:00:00');

;with cte as (
select *
  , indatetime =dateadd(minute,datediff(minute,0,intime),convert(datetime2(0),attendancedate))
  , outdatetime=case when outtime > intime
      then dateadd(minute,datediff(minute,0,outtime),convert(datetime2(0),attendancedate))
      else dateadd(minute,datediff(minute,0,outtime),convert(datetime2(0),dateadd(day,1,attendancedate)))
      end
from t
)
select
    employeeid
  , attendancedate
  , intime = ltrim(right(convert(varchar(23),convert(datetime,intime ),100),7))
  , outtime= ltrim(right(convert(varchar(23),convert(datetime,outtime),100),7))
  /* if less than 24 hours we can use this simpler version: */
  , TotalDuration24 = convert(time(0),dateadd(minute,datediff(minute,indatetime,outdatetime),0))
  /* if values greater than 24 hours we would use this version: */
  , TotalDuration = convert(varchar(10),
      convert(varchar(4),(datediff(minute,indatetime,outdatetime)/60),2)+':'
     +right('00'+convert(varchar(2),datediff(minute,indatetime,outdatetime)%60),2)
    )
from cte
</code>```

rextester demo: http://rextester.com/OQFS42186

returns:

```<code>+------------+----------------+--------+---------+-----------------+---------------+
| employeeid | attendancedate | intime | outtime | TotalDuration24 | TotalDuration |
+------------+----------------+--------+---------+-----------------+---------------+
|          1 | 2017-06-01     | 9:00PM | 5:00AM  | 08:00:00        | 8:00          |
|          2 | 2017-06-03     | 5:00AM | 9:00PM  | 16:00:00        | 16:00         |
+------------+----------------+--------+---------+-----------------+---------------+
</code>```

Body:
I have tried to do punch in punch out time of the employees, I have tried the below query, it works fine when the punch in time is like 10:00am and punch out time like 6:00pm, and shows TotalDuration as 8hrs.

But it fails when the punch in time like 9:00pm and 5:00am.

About the problem, I have done calculation based on punch in and punch out which shows total hours.

But when the user punches after 12am it shows as 00:00 on both the punch in and punch out and TotalDuration as 0

The output that I get

    I:9:05AM\nO:5:32PM\nT:8:27 \nS :~Present On WeeklyOff - WeekOff,:Saturday,:
    I:12:00AM\nO:12:00AM\nT:0:0  \nS :~Present On WeeklyOff - WeekOff,:Saturday,:

Here is my query :

SELECT
    ROW_NUMBER() OVER (ORDER BY e.EmployeeCode,AttendanceDate DESC) AS 'SNo',
    e.EmployeeCode AS 'EmpID',
    e.EmployeeName AS 'EmpName',
    d.DepartmentFName AS 'DeptName',
    CONVERT(VARCHAR, a.AttendanceDate, 110) AS 'AttendanceDate',
    'I:' + LTRIM (RIGHT(CONVERT(VARCHAR(50),+'I:'+CONVERT(VARCHAR(50),+CONVERT(DATETIME, a.InTime,0)),100),7))+'\n'+'O:'+LTRIM (RIGHT(CONVERT(VARCHAR(20),CONVERT(DATETIME, CASE WHEN a.OutTime LIKE '%(%' THEN LEFT(a.OutTime, CHARINDEX('(', a.OutTime + ')') - 1)
   ELSE a.OutTime END,0),100),7))+'\n'+ 'T:'+ CONVERT(CHAR(5),CAST(CAST(CASE WHEN  a.InTime> a.OutTime THEN DATEDIFF (MINUTE,CAST(a.InTime as datetime),DateAdd(day,1,CAST(a.OutTime AS datetime)))
 ELSE DATEDIFF(MINUTE, a.InTime , a.OutTime) END AS INTEGER)/60 AS VARCHAR)+':'+CAST(cast(CASE WHEN  a.InTime> a.OutTime THEN DATEDIFF (MINUTE,CAST(a.InTime as datetime),DateAdd(day,1,CAST(a.OutTime AS datetime)))
 ELSE DATEDIFF(MINUTE, a.InTime , a.OutTime) END AS INTEGER)%60 AS VARCHAR),108)+ '\n' + 'S :~' +  a.[Status]+ ' - ' + CASE WHEN a.[Status] = 'Present' THEN '' WHEN a.[Status] = 'On WeeklyOff' and la.LeaveType<>'' THEN la.LeaveType
   WHEN DATENAME(dw, a.AttendanceDate)='Sunday' THEN 'WeekOff' WHEN DATENAME(dw, a.AttendanceDate)='SaturDay'
   THEN 'WeekOff' ELSE la.LeaveType COLLATE SQL_Latin1_General_CP1_CI_AS   ENd + ',:'+DATENAME(dw, a.AttendanceDate) + ',:'+ CASE WHEN la.LeaveStatus is null THEN '' ELSE la.LeaveStatus END AS 'PunchDetails',
   '0LOP' AS 'NoOfLOP',
   '0WkEnd' AS 'NoOfWkEndWorked' ,ISNULL(la.LeaveStatus,'') AS 'LeaveStatus'

-- INTO #Result02
FROM
    esslsmartofficenew.dbo.Employees e (NOLOCK)
INNER JOIN
    esslsmartofficenew.dbo.AttendanceLogs a (NOLOCK) ON e.EmployeeId = a.EmployeeId
INNER JOIN
    esslsmartofficenew.dbo.Departments d (NOLOCK) ON d.DepartmentId = e.DepartmentId
INNER JOIN
    esslsmartofficenew.dbo.Shifts s (NOLOCK) ON s.ShiftId = a.ShiftId
LEFT JOIN
    IntranetReleaseNew.dbo.LeaveApplication la ON la.EmpId collate SQL_Latin1_General_CP1_CI_AS = e.employeecode collate SQL_Latin1_General_CP1_CI_AS
                                               AND a.AttendanceDate >= la.leavefromdate
                                               AND a.AttendanceDate <= la.leaveTodate
WHERE
    e.DepartmentId = '10' AND
    e.EmployeeName NOT LIKE '%del_%' AND
    e.EmployeeCode LIKE '%S%' AND
    e.EmployeeCode NOT LIKE '%Del_%' AND
    a.AttendanceDate = '2017-05-13'

Body:
I do not want to try and untangle your code, so I am just going to address the relevant calculations.

If we can assume that when the outtime is less than the intime, then the outtime occured the next day we can use something like this:

Note: I am using a common table expression to reduce repeating the code that converts the times to datetime with the above assumption, you could use a subquery/derived table to the same effect.

create table t (employeeid int, attendancedate date, intime time(0), outtime time(0));
insert into t values (1,'20170601','21:00:00','05:00:00'),(2,'20170603','05:00:00','21:00:00');

;with cte as (
select *
  , indatetime =dateadd(minute,datediff(minute,0,intime),convert(datetime2(0),attendancedate))
  , outdatetime=case when outtime > intime
      then dateadd(minute,datediff(minute,0,outtime),convert(datetime2(0),attendancedate))
      else dateadd(minute,datediff(minute,0,outtime),convert(datetime2(0),dateadd(day,1,attendancedate)))
      end
from t
)
select
    employeeid
  , attendancedate
  , intime = ltrim(right(convert(varchar(23),convert(datetime,intime ),100),7))
  , outtime= ltrim(right(convert(varchar(23),convert(datetime,outtime),100),7))
  /* if less than 24 hours we can use this simpler version: */
  , TotalDuration24 = convert(time(0),dateadd(minute,datediff(minute,indatetime,outdatetime),0))
  /* if values greater than 24 hours we would use this version: */
  , TotalDuration = convert(varchar(10),
      convert(varchar(4),(datediff(minute,indatetime,outdatetime)/60),2)+':'
     +right('00'+convert(varchar(2),datediff(minute,indatetime,outdatetime)%60),2)
    )
from cte

rextester demo: http://rextester.com/OQFS42186

returns:

+------------+----------------+--------+---------+-----------------+---------------+
| employeeid | attendancedate | intime | outtime | TotalDuration24 | TotalDuration |
+------------+----------------+--------+---------+-----------------+---------------+
|          1 | 2017-06-01     | 9:00PM | 5:00AM  | 08:00:00        | 8:00          |
|          2 | 2017-06-03     | 5:00AM | 9:00PM  | 16:00:00        | 16:00         |
+------------+----------------+--------+---------+-----------------+---------------+


问:
Differences in execution behavior of Java program
I wrote a java program, which manipulates Word documents (docx) with Apache POI. It runs fine within Eclipse, and it runs fine as a runnable JAR on my computer (Windows 10).

I copied that JAR to another computer, and it is starting up normally. The GUI behaves like expected.

The problem is the Word document I write out (docx).

I am performing two types of changes. The first one is the addition of new paragraphs or concatenation of content to the runs. If I stay with this, the document gets written into the file system correctly. The second type is the simple replacement of content within the runs (changes of words and some grammatical changes). I would see that part as the "simpler" one, but if I stay with this or if I combine both change types, no document is written out at all. It does look like there is a bug, but there isn't one because it worked fine on my system.

I wrote myself a function to write out an error log (txt) to get information about that issue. This one worked on both systems. But the log didn't get any information, why the document was not written out.

I suppose there are some Windows security settings which interfer with my program or something like that. The computer that does not like to run my program has Win 7 installed on it, and there are some security domain settings, which affect all other computers in the local network.

Does anyone experienced something similar yet? Any suggestions what to check? Suggestions how to find out if an error happened are appreciated as well.

答:
OK, the problem got solved by simply updating the Java version. I saw that update icon in the system tray, which didn't open update the update dialog. So I wanted to update the Java-version at least.

When I wanted to de-install the current Java version first, I noticed that the Win7-machine hadn't a Java-update for three years now. It was just installed in 2014. As soon as the recent version was installed, everything worked like expected again.

The strange behavior that some parts of my program worked and some not, confused me. I hoped that the Java update would fix this, but I doubted that. I didn't knew that old versions make programs run unpredictably.


问:
Is it possible to stream music from Android/iOS devices to desktop devices?
I have a ucLinux microcontroller, which connects to loudspeakers. Now I want to stream music from Android/iOS devices to the microcontroller, and make the loudspeaker play music on my mobile devices. The microcontroller and mobile devices can connect via wi-fi. Is it possible to do so? Thanks.</p>

答: If you write your own music streaming server, or find somebody who has written one, sure. There is no music streaming server built into Android itself.</p>


问:
calculate the distance between two cities
I have a bit of what I think is an odd request.  What I need to do is calculate the distance between the two cities, given their city/state/zip input data.  This would be as the crow flies, rather than mileage via highways and such.  And I would need miles output, i.e. x mile radius, in USA miles.

Again, I have city/state/zip input.  Most solutions I have located are via latitude/longitude instead.  Absent a city/state/zip solution, might there be a utility of some sort to convert city/state/zip input data to latitude/longitude and calculate based off of that?

Looking to incorporate this functionality into a .NET C#, MS SQL Server application.

Thanks in advance for any insight.

答:
You will need to convert your address or partial address into valid latitude and longitude. There are several web services/APIs which can do this for you. Google has an API for this: https://developers.google.com/maps/documentation/geocoding/start?csw=1

You will then need to do some math to calculate the distance, something like the Haversine formula. If you google C# Haversine formula you'll find several articles, including some Stackoverflow questions about how to implement this.


问:
Assigning word from text file to array
```<code>person1 bob
person2 george
person3 tom
</code>```

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

```<code>bob
george
tom
</code>```

My current attempt is:

```<code>Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next
</code>```

I'm a total noob, please treat me well.

答:
I ended up using this and everything worked. Thanks heaps for your contributions guys.</p>

```<code>Dim resultArray = File.ReadLines(FileName).
    Select(Function(l) l.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Last().Trim()).
    ToArray()
</code>```

Title: Assigning word from text file to array

Body:
person1 bob
person2 george
person3 tom

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

bob
george
tom

My current attempt is:

Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next

I'm a total noob, please treat me well.

Body:
I ended up using this and everything worked. Thanks heaps for your contributions guys.

Dim resultArray = File.ReadLines(FileName).
    Select(Function(l) l.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Last().Trim()).
    ToArray()


问:
How do I reference a .NET 4.5.2 library from the .NET Core project (VS2017)
I have a .NET Core Class Library created in VS2017. I need to reference an assembly build against .NET 4.5.2. When I add the reference, I receive the following error:

```<code>Error   CS0012  The type 'Object' is defined in an assembly that is not
referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0
</code>```

When I try to add the reference via VS, I can see no sources to find it:

Similar question has been already asked here and described here but the answers described how extend the project.json file which is obsolete now and does not appear in VS2017.

答:
Directly referencing assemblies in .NET Core applications will be supported in the 2.0 tooling that ships with the upcoming VS 2017 15.3 update. Before that, even referencing seemingly compatible dll files does not work correctly.

Referencing dll files built for .NET Framework (<= 4.6.1) will only be supported in .NET Core 2.0. Lower versions do not support this scenario which is why you see this error. (In .NET Core, System.Object is not defined in mscorlib which is where .NET Framework dlls expect it to be. .NET Core 2.0 contains the necessary redirection logic.)

Body:
I have a .NET Core Class Library created in VS2017. I need to reference an assembly build against .NET 4.5.2. When I add the reference, I receive the following error:

Error   CS0012  The type 'Object' is defined in an assembly that is not
referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0

When I try to add the reference via VS, I can see no sources to find it:

Similar question has been already asked here and described here but the answers described how extend the project.json file which is obsolete now and does not appear in VS2017.


问:
Firebase Storage is giving StorageException while trying to upload images
I have been trying to upload images to the new firebase storage service . It is throwing StorageException

E/StorageException: StorageException has occurred.
                                                                          An unknown error occurred, please check the HTTP result code and inner
  exception for server response.
                                                                           Code: -13000 HttpResult: 400

E/StorageException: The server has terminated the upload session
                                                                          java.io.IOException: The server has terminated the upload session
                                                                              at com.google.firebase.storage.UploadTask.zzVi(Unknown Source)
                                                                              at com.google.firebase.storage.UploadTask.zzVh(Unknown Source)
                                                                              at com.google.firebase.storage.UploadTask.run(Unknown Source)
                                                                              at com.google.firebase.storage.StorageTask$5.run(Unknown Source)
                                                                              at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                              at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                              at java.lang.Thread.run(Thread.java:818)

答:
Don't forget to add

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</code>```

In your AndroidManifest.xml

Body:
Don't forget to add

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

In your AndroidManifest.xml