问:
Getting undesired result in node/angularjs application
I am making a MEAN stack application. It is an online live test taking application where user has to face a multiple choice question with 4 options and has to choose one.
Now, the problem i'm getting is, suppose there are 2 questions:

 1. What is 1+0?

    a. 1

    b. 3

    c. 4

    d. 5

The answer to this question is at index 1,also the answer is 1. So my controller is sending 1 to the Submit button(it's sending the index, not the actual answer).

Take another question. What is 3+4?

a. 7

b. 8

c. 9

d. 10

Here, the controller sends 1 to the database, as the correct answer marked by user is at first index.

I want it to send 7.

This is my controller

liveController.js

examApp.controller('liveController', ['$scope', '$filter', '$http', '$location', '$routeParams', 'queryService', 'authenticationService', function($scope, $filter, $http, $location, $routeParams, queryService, authenticationService) {
  var main = this;
  var totalnoofQuestions;
  var user;
  main.questionsforTime = [];
  this.getsecurityQuestion = function() {
    var data = {
      _id: $routeParams.userId
    }
    queryService.getsecurityQuest(data)
      .then(function successCallback(response) {
        if (response.data.error === true) {
          alert(response.data.message);
        } else {
          var userId;
          var data = response.data.data;
          main.user = data.name;
          main.userId = data._id;
          authenticationService.setToken(response.data.token);
        }
      }, function errorCallback(response) {
        alert("There was a problem.");
      })
  }

  this.getsecurityQuestion();
  this.logged = function() {
    main.username = queryService.userName;
    if (queryService.log == 1 || queryService.userId !== 'undefined') {
      return 1;
    } else {
      $location.path('/');
    }
  }
  this.logged();
  this.userId = $routeParams.userId;
  main.heading = "Welcome To Exam App";
  $('.thisismodalforlivetestwarning').modal('show');
  $(document).on('click', '#returntotaketest', function() {
    $('.thisismodalforlivetestwarning').modal('hide');
    location.replace("#/taketheTest/" + main.userId);
  })

  this.getasingleTest = function() {
    var singletestId = $routeParams.testId;
    queryService.getasingleTest(singletestId)
      .then(function successCallback(response) {
        if (response.data.error === true) {
          alert(response.data.message);
          window.location.href = "#/taketheTest/" + main.userId;
        } else {
          if (response.data.data.questions.length == 0) {
            $location.path("/taketheTest/" + main.userId);
            alert("No questions present.");
          } else {
            main.totalnoofQuestions = response.data.data.questions.length;
            main.questionsforTime.push(response.data.data.questions.length);
            main.testHeading = "Test topic is " + response.data.data.testName;
            main.singletestArray = response.data.data.questions;
            main.time = response.data.data.testDuration;
          }
        }
      }, function errorCallback(response) {
        alert("There was a problem.");
      })
  }
  this.getasingleTest();
  var totalSeconds = 300;
  var minutes = parseInt(totalSeconds / 60);
  var seconds = parseInt(totalSeconds % 60);
  this.theTime = function() {
    totalSeconds = totalSeconds - 1;
    minutes = parseInt(totalSeconds / 60);
    seconds = parseInt(totalSeconds % 60);
    main.timetakeninTest = (300 - totalSeconds);
    document.getElementById('test-time-left').innerHTML = 'Time Left: ' + minutes + ' minutes ' + seconds + ' seconds';
    if (totalSeconds <= 0) {
      clearTimeout(main.counttime);
      main.timetakeninTest = 300;
      alert("Time Is Up!!");
      container.style.display = 'none';
      var testattemptData = {
        testgivenBy: main.user + " " + $routeParams.userId,
        testId: $routeParams.testId
      }
      queryService.testAttemptedBy(testattemptData)
        .then(function successCallback(response) {}, function errorCallback(response) {})

      var data = {
        userid: $routeParams.userId,
        testid: $routeParams.testId,
        score: score,
        timeTaken: main.timetakeninTest,
        totalCorrect: (score / 10),
        totalIncorrect: (10 - (score / 10))
      }
      queryService.submitTest(data)
        .then(function successCallback(response) {
          if (response.data.error === true) {
            alert(response.data.message);
          } else {
            main.performanceUserID = response.data.data.user;
            main.answerscorrect = response.data.data.totalCorrect;
            main.answerswrong = response.data.data.totalIncorrect;
            main.madeScore = response.data.data.score;
            main.timeTaken = response.data.data.timeTaken;
            $('.thisismodalforUserTestPerformance').modal('show');
          }
        }, function errorCallback(response) {
          alert("There was a problem.");
        })
    }
  }

  var currentQuestion = 0;
  var score = 0;
  var totalQuestionAsked = 0;
  var container = document.getElementById('quizContainer');
  var questionEl = document.getElementById('question');
  var opt1 = document.getElementById('opt1');
  var opt2 = document.getElementById('opt2');
  var opt3 = document.getElementById('opt3');
  var opt4 = document.getElementById('opt4');
  var nextButton = document.getElementById('nextButton');
  var resultCont = document.getElementById('result');
  this.loadQuestion = function(questionIndex) {
    if (questionIndex == 0) {
      totalQuestionAsked = main.totalnoofQuestions;
      $('.thisismodalforlivetestwarning').modal('hide');
      main.counttime = setInterval(this.theTime, 1000);
    }
    var q = main.singletestArray[questionIndex];
    questionEl.textContent = (questionIndex + 1) + '.' + q.question;
    opt1.textContent = q.optionA;
    opt2.textContent = q.optionB;
    opt3.textContent = q.optionC;
    opt4.textContent = q.optionD;
  };

  this.nextQuestion = function() {
    var selectedOption = document.querySelector('input[type=radio]:checked');
    if (!selectedOption) {
      alert("Select An Answer First.");
      return;
    }
    var answer = selectedOption.value; //This line
    console.log("this is problem " + answer);
    if (main.singletestArray[currentQuestion].answer == answer) {
      score += 10;
    }
    var data = {
      userid: $routeParams.userId,
      testid: $routeParams.testId,
      questionid: main.singletestArray[currentQuestion]._id,
      userAnswer: answer,
      correctAnswer: main.singletestArray[currentQuestion].answer,
      timetakenInsecs: main.timetakeninTest
    }
    queryService.submitAnswer(data)
      .then(function successCallback(response) {}, function errorCallback(response) {})
    selectedOption.checked = false;
    currentQuestion++;
    if (currentQuestion == totalQuestionAsked - 1) {
      nextButton.textContent = 'Finish';
    }
    if (currentQuestion == totalQuestionAsked) {
      container.style.display = 'none';
      clearTimeout(main.counttime);
      var testattemptData = {
        testgivenBy: main.user + " " + $routeParams.userId,
        testId: $routeParams.testId
      }
      queryService.testAttemptedBy(testattemptData)
        .then(function successCallback(response) {}, function errorCallback(response) {})

      var data = {
        userid: $routeParams.userId,
        testid: $routeParams.testId,
        score: score,
        timeTaken: main.timetakeninTest,
        totalCorrect: (score / 10),
        totalIncorrect: (10 - (score / 10))
      }
      queryService.submitTest(data)
        .then(function successCallback(response) {
          if (response.data.error === true) {
            alert(response.data.message);
          } else {
            main.performanceUserID = response.data.data.user;
            main.answerscorrect = response.data.data.totalCorrect;
            main.answerswrong = response.data.data.totalIncorrect;
            main.madeScore = response.data.data.score;
            main.timeTaken = response.data.data.timeTaken;
            $('.thisismodalforUserTestPerformance').modal('show');
          }
        }, function errorCallback(response) {
          alert("There was a problem");
        })
      return;
    }
    this.loadQuestion(currentQuestion);
  }

}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="../css/livetest.css">
<!-- W3 schools styles-->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
<div ng-controller="liveController as live">
  <nav class="navbar fixed-top navbar-toggleable-md navbar-inverse bg-inverse">
    <br/>
    <div class="container">

        <h2>
          <i class="fa fa-line-chart" aria-hidden="true"></i> Exam App Dashboard

    </div>
    <br/>
  </nav>
  <div Style="color:white;font-weight:bold;font-size:2em; text-align:center;" id="test-time-left"></div>
  <div style="background: #F2F2F2;" id="quizContainer" class="container">
    <div class="title" style="text-align: center; font-weight:bold; font-size: 1.5em;">{{live.testheading}}</div>
    <div id="question" class="question" style="font-size: 2em; font-weight: bold;"></div>
    <label class="option">
            <input type="radio" name="option" value="1" />
            <span id="opt1"></span>
        </label>
    <label class="option">
            <input type="radio" name="option" value="2" />
            <span id="opt2"></span>
        </label>
    <label class="option">
            <input type="radio" name="option" value="3" />
            <span id="opt3"></span>
        </label>
    <label class="option">
            <input type="radio" name="option" value="4" />
            <span id="opt4"></span>
        </label>
    <button id="nextButton" class="next-btn" ng-click="live.nextQuestion()">Next Question </button>
  </div>
  <br/>

  <!-- Place to keep all the modals -->

  <!-- Modal -->
  <div class="modal fade thisismodalforlivetestwarning" id="modalfortestwarning" role="dialog" data-backdrop="false">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div style="background-color: #4CAF50;" class="modal-header">
          <h4 align="center" class="modal-title">
            <span style="color:white;">: Please Read The instructions Carefully :</span>
          </h4>
        </div>
        <div class="modal-body">
          <ol>
            <li>You will be alloted 5 Minutes to Give Test, After which window will close Automatically.</li>
            <li>You can't go back after submitting the Answer for each Question.</li>
            <li>you can submit the Test before the finishing Time if you want but can't after the time finishes, It will Automatically be submitted.</li>
            <li>Please don't do cheating in test. Be fair to yourself for your true Assessment of skills.</li>
            <li>If you aggree with all the terms stated above you may proceed by clicking Start Button Below.</li>
          </ol>
          <h3 align="center">
            <strong>
                            <em>Best Of Luck!</em>
                        </strong>
          </h3>
        </div>
        <div style="background-color: #404549;" class="modal-footer">
          <button type="button" class="btn btn-success" ng-click="live.loadQuestion(0)">Start!</button>
          <button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
        </div>
      </div>
    </div>

  </div>

  <!-- MOdal for User Performance -->

  <!-- Modal -->
  <div class="modal fade thisismodalforUserTestPerformance" role="dialog" data-backdrop="false">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div style="background-color: #4CAF50;" class="modal-header">
          <h4 align="center" class="modal-title">
            <span style="color:white;">: Your Score Card for the Test :</span>
          </h4>
        </div>
        <div class="modal-body">
          <div style="background-color: #404549;" class="modal-body">
            User ID: {{live.performanceUserID}}
            Total Correct Answers: {{live.answerscorrect}}
            Total Wrong Answers: {{live.answerswrong}}
            Score Secured: {{live.madeScore}}
            Total Time Taken: {{live.timeTaken}} Seconds

          </div>
          <h3 align="center">
            <strong>
                            <em>Thank You! For giving the Test...</em>
                        </strong>
          </h3>
        </div>
        <div style="background-color: #404549;" class="modal-footer">

          <button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
        </div>
      </div>
    </div>

  </div></code>```

The action happens at nextQuestion function at the commented line (commented with '//This line'). I have tried my best to explain my problem and can upload more code if required.

Any help will be appreciated.

答:
You could do something like this</p>

```<code>var selectedOption = document.querySelector('input[type=radio]:checked');
    if (!selectedOption) {
      alert("Select An Answer First.");
      return;
    }
    //As selectedOption is actually an index we can use it to get the answer
    var answerValue = document.getElementById('opt'+ selectedOption);

    var answer = answerValue.textContent;
</code>```

Body:
I am making a MEAN stack application. It is an online live test taking application where user has to face a multiple choice question with 4 options and has to choose one.
Now, the problem i'm getting is, suppose there are 2 questions:

 1. What is 1+0?

    a. 1

    b. 3

    c. 4

    d. 5

The answer to this question is at index 1,also the answer is 1. So my controller is sending 1 to the Submit button(it's sending the index, not the actual answer).

Take another question. What is 3+4?

a. 7

b. 8

c. 9

d. 10

Here, the controller sends 1 to the database, as the correct answer marked by user is at first index.

I want it to send 7.

This is my controller

liveController.js

examApp.controller('liveController', ['$scope', '$filter', '$http', '$location', '$routeParams', 'queryService', 'authenticationService', function($scope, $filter, $http, $location, $routeParams, queryService, authenticationService) {
  var main = this;
  var totalnoofQuestions;
  var user;
  main.questionsforTime = [];
  this.getsecurityQuestion = function() {
    var data = {
      _id: $routeParams.userId
    }
    queryService.getsecurityQuest(data)
      .then(function successCallback(response) {
        if (response.data.error === true) {
          alert(response.data.message);
        } else {
          var userId;
          var data = response.data.data;
          main.user = data.name;
          main.userId = data._id;
          authenticationService.setToken(response.data.token);
        }
      }, function errorCallback(response) {
        alert("There was a problem.");
      })
  }

  this.getsecurityQuestion();
  this.logged = function() {
    main.username = queryService.userName;
    if (queryService.log == 1 || queryService.userId !== 'undefined') {
      return 1;
    } else {
      $location.path('/');
    }
  }
  this.logged();
  this.userId = $routeParams.userId;
  main.heading = "Welcome To Exam App";
  $('.thisismodalforlivetestwarning').modal('show');
  $(document).on('click', '#returntotaketest', function() {
    $('.thisismodalforlivetestwarning').modal('hide');
    location.replace("#/taketheTest/" + main.userId);
  })

  this.getasingleTest = function() {
    var singletestId = $routeParams.testId;
    queryService.getasingleTest(singletestId)
      .then(function successCallback(response) {
        if (response.data.error === true) {
          alert(response.data.message);
          window.location.href = "#/taketheTest/" + main.userId;
        } else {
          if (response.data.data.questions.length == 0) {
            $location.path("/taketheTest/" + main.userId);
            alert("No questions present.");
          } else {
            main.totalnoofQuestions = response.data.data.questions.length;
            main.questionsforTime.push(response.data.data.questions.length);
            main.testHeading = "Test topic is " + response.data.data.testName;
            main.singletestArray = response.data.data.questions;
            main.time = response.data.data.testDuration;
          }
        }
      }, function errorCallback(response) {
        alert("There was a problem.");
      })
  }
  this.getasingleTest();
  var totalSeconds = 300;
  var minutes = parseInt(totalSeconds / 60);
  var seconds = parseInt(totalSeconds % 60);
  this.theTime = function() {
    totalSeconds = totalSeconds - 1;
    minutes = parseInt(totalSeconds / 60);
    seconds = parseInt(totalSeconds % 60);
    main.timetakeninTest = (300 - totalSeconds);
    document.getElementById('test-time-left').innerHTML = 'Time Left: ' + minutes + ' minutes ' + seconds + ' seconds';
    if (totalSeconds <= 0) {
      clearTimeout(main.counttime);
      main.timetakeninTest = 300;
      alert("Time Is Up!!");
      container.style.display = 'none';
      var testattemptData = {
        testgivenBy: main.user + " " + $routeParams.userId,
        testId: $routeParams.testId
      }
      queryService.testAttemptedBy(testattemptData)
        .then(function successCallback(response) {}, function errorCallback(response) {})

      var data = {
        userid: $routeParams.userId,
        testid: $routeParams.testId,
        score: score,
        timeTaken: main.timetakeninTest,
        totalCorrect: (score / 10),
        totalIncorrect: (10 - (score / 10))
      }
      queryService.submitTest(data)
        .then(function successCallback(response) {
          if (response.data.error === true) {
            alert(response.data.message);
          } else {
            main.performanceUserID = response.data.data.user;
            main.answerscorrect = response.data.data.totalCorrect;
            main.answerswrong = response.data.data.totalIncorrect;
            main.madeScore = response.data.data.score;
            main.timeTaken = response.data.data.timeTaken;
            $('.thisismodalforUserTestPerformance').modal('show');
          }
        }, function errorCallback(response) {
          alert("There was a problem.");
        })
    }
  }

  var currentQuestion = 0;
  var score = 0;
  var totalQuestionAsked = 0;
  var container = document.getElementById('quizContainer');
  var questionEl = document.getElementById('question');
  var opt1 = document.getElementById('opt1');
  var opt2 = document.getElementById('opt2');
  var opt3 = document.getElementById('opt3');
  var opt4 = document.getElementById('opt4');
  var nextButton = document.getElementById('nextButton');
  var resultCont = document.getElementById('result');
  this.loadQuestion = function(questionIndex) {
    if (questionIndex == 0) {
      totalQuestionAsked = main.totalnoofQuestions;
      $('.thisismodalforlivetestwarning').modal('hide');
      main.counttime = setInterval(this.theTime, 1000);
    }
    var q = main.singletestArray[questionIndex];
    questionEl.textContent = (questionIndex + 1) + '.' + q.question;
    opt1.textContent = q.optionA;
    opt2.textContent = q.optionB;
    opt3.textContent = q.optionC;
    opt4.textContent = q.optionD;
  };

  this.nextQuestion = function() {
    var selectedOption = document.querySelector('input[type=radio]:checked');
    if (!selectedOption) {
      alert("Select An Answer First.");
      return;
    }
    var answer = selectedOption.value; //This line
    console.log("this is problem " + answer);
    if (main.singletestArray[currentQuestion].answer == answer) {
      score += 10;
    }
    var data = {
      userid: $routeParams.userId,
      testid: $routeParams.testId,
      questionid: main.singletestArray[currentQuestion]._id,
      userAnswer: answer,
      correctAnswer: main.singletestArray[currentQuestion].answer,
      timetakenInsecs: main.timetakeninTest
    }
    queryService.submitAnswer(data)
      .then(function successCallback(response) {}, function errorCallback(response) {})
    selectedOption.checked = false;
    currentQuestion++;
    if (currentQuestion == totalQuestionAsked - 1) {
      nextButton.textContent = 'Finish';
    }
    if (currentQuestion == totalQuestionAsked) {
      container.style.display = 'none';
      clearTimeout(main.counttime);
      var testattemptData = {
        testgivenBy: main.user + " " + $routeParams.userId,
        testId: $routeParams.testId
      }
      queryService.testAttemptedBy(testattemptData)
        .then(function successCallback(response) {}, function errorCallback(response) {})

      var data = {
        userid: $routeParams.userId,
        testid: $routeParams.testId,
        score: score,
        timeTaken: main.timetakeninTest,
        totalCorrect: (score / 10),
        totalIncorrect: (10 - (score / 10))
      }
      queryService.submitTest(data)
        .then(function successCallback(response) {
          if (response.data.error === true) {
            alert(response.data.message);
          } else {
            main.performanceUserID = response.data.data.user;
            main.answerscorrect = response.data.data.totalCorrect;
            main.answerswrong = response.data.data.totalIncorrect;
            main.madeScore = response.data.data.score;
            main.timeTaken = response.data.data.timeTaken;
            $('.thisismodalforUserTestPerformance').modal('show');
          }
        }, function errorCallback(response) {
          alert("There was a problem");
        })
      return;
    }
    this.loadQuestion(currentQuestion);
  }

}]);

<link rel="stylesheet" href="../css/livetest.css">

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">

           Exam App Dashboard

{{live.testheading}}

            <input type="radio" name="option" value="1" />

            <input type="radio" name="option" value="2" />

            <input type="radio" name="option" value="3" />

            <input type="radio" name="option" value="4" />

    <button id="nextButton" class="next-btn" ng-click="live.nextQuestion()">Next Question </button>

            : Please Read The instructions Carefully :

You will be alloted 5 Minutes to Give Test, After which window will close Automatically.

You can't go back after submitting the Answer for each Question.

you can submit the Test before the finishing Time if you want but can't after the time finishes, It will Automatically be submitted.

Please don't do cheating in test. Be fair to yourself for your true Assessment of skills.

If you aggree with all the terms stated above you may proceed by clicking Start Button Below.

                            Best Of Luck!

          <button type="button" class="btn btn-success" ng-click="live.loadQuestion(0)">Start!</button>
          <button type="button" class="btn btn-danger" id="returntotaketest">Return</button>

            : Your Score Card for the Test :

            User ID: {{live.performanceUserID}}
            Total Correct Answers: {{live.answerscorrect}}
            Total Wrong Answers: {{live.answerswrong}}
            Score Secured: {{live.madeScore}}
            Total Time Taken: {{live.timeTaken}} Seconds

                            Thank You! For giving the Test...

          <button type="button" class="btn btn-danger" id="returntotaketest">Return</button>

The action happens at nextQuestion function at the commented line (commented with '//This line'). I have tried my best to explain my problem and can upload more code if required.

Any help will be appreciated.

Body:
You could do something like this

var selectedOption = document.querySelector('input[type=radio]:checked');
    if (!selectedOption) {
      alert("Select An Answer First.");
      return;
    }
    //As selectedOption is actually an index we can use it to get the answer
    var answerValue = document.getElementById('opt'+ selectedOption);

    var answer = answerValue.textContent;


来源: stackexchange

问:
Data Table Classes in UML Sequence Diagrams
I've been struggling to understand the transition from a UML Class Design Diagram to a UML Sequence Diagram for a school assignment. My design class diagram contains a central DataManager class that connects the use case control classes to the data table classes (ie. user, product, employee), however, do I need to include the data table classes in my use cases' sequence diagrams?

Design Class Diagram

My Sequence Diagram Attempt

答: So, in the end, I didn't phrase my question as I wanted to. I was asking if communications between the database tables and the data manager class should also appear in the sequence diagram. The answer is, they should. The whole point of having a sequence diagram is to guide a developer in the "development" of a class. For my diagrams, all messages I used for this communication had a standard sql() operation for each message.

ContentLicense: CC BY-SA 3.0


问:
Catch an invalid HTTP request method globally
I would like to restrict my Web API endpoints to certain HTTP methods, such as GET and POST. I have searched the internet and I found out that you can add either [HttpGet] or [HttpPost] above your method as follows:

```<code>[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}
</code>```

Now I want to test if the example above with [HttpPost] really works so I use postman to send a HTTP request to my Web API. I fill in the URI and set the method to GET. The response I get is as follows:

```<code>{
    "message": "The requested resource does not support http method 'POST'."
}
</code>```

I'm able to verify that adding [HttpPost] prevents me from using HTTP GET requests.

What I would like to do now is log the event whenever an user tries to sent GET requests when the application is expecting POST, and vice versa. I could implement something for every single method but this would take a lot of time and it wouldn't be easy to make changes once it's been implemented. So I would like to filter it globally or something.

For example something like:

```<code>class MethodRequestFilter : SomeGlobalMethodFilter
    {
        public override void Filter(SomeRequestContext requestContext)
        {
            if (usedRequestMethod.isNotValid == true)
            {
                //implementation for logging
            }
        }
    }
</code>```

But ofcourse I haven't been able to find this yet within the libraries of .Net. How can I log the event globally whenever a user tries to make a request that isn't a supported method?

Greetings,

Damien.

答:
One way is to using common base controller, to implement you need to add one base controller which would inherited from ApiController

```<code>public class BaseController : ApiController
{
    public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
    {
        try
        {
            HttpResponseMessage response = await base.ExecuteAsync(controllerContext, cancellationToken);
            if (!response.IsSuccessStatusCode) // or if(response.StatusCode == HttpStatusCode.BadRequest)
            {
                //log here
            }
            return response;
        }
        catch(Exception ex)
        {
            return await InternalServerError(ex).ExecuteAsync(cancellationToken);
        }
    }
}
</code>```

Now, let's assume that you're having ValuesController and Login method and it supports only POST, here your all other controllers inherit from BaseController instead ApiController

```<code>public class ValuesController : BaseController
{
  [HttpPost]
  public void Login([FromBody]string value)
  {
  }
}
</code>```

So, once you call your login method, it'll call BaseController method first and you will get response there.

Hope this helps!

Body:
I would like to restrict my Web API endpoints to certain HTTP methods, such as GET and POST. I have searched the internet and I found out that you can add either [HttpGet] or [HttpPost] above your method as follows:

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

Now I want to test if the example above with [HttpPost] really works so I use postman to send a HTTP request to my Web API. I fill in the URI and set the method to GET. The response I get is as follows:

{
    "message": "The requested resource does not support http method 'POST'."
}

I'm able to verify that adding [HttpPost] prevents me from using HTTP GET requests.

What I would like to do now is log the event whenever an user tries to sent GET requests when the application is expecting POST, and vice versa. I could implement something for every single method but this would take a lot of time and it wouldn't be easy to make changes once it's been implemented. So I would like to filter it globally or something.

For example something like:

class MethodRequestFilter : SomeGlobalMethodFilter
    {
        public override void Filter(SomeRequestContext requestContext)
        {
            if (usedRequestMethod.isNotValid == true)
            {
                //implementation for logging
            }
        }
    }

But ofcourse I haven't been able to find this yet within the libraries of .Net. How can I log the event globally whenever a user tries to make a request that isn't a supported method?

Greetings,

Damien.

Body:
One way is to using common base controller, to implement you need to add one base controller which would inherited from ApiController

public class BaseController : ApiController
{
    public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
    {
        try
        {
            HttpResponseMessage response = await base.ExecuteAsync(controllerContext, cancellationToken);
            if (!response.IsSuccessStatusCode) // or if(response.StatusCode == HttpStatusCode.BadRequest)
            {
                //log here
            }
            return response;
        }
        catch(Exception ex)
        {
            return await InternalServerError(ex).ExecuteAsync(cancellationToken);
        }
    }
}

Now, let's assume that you're having ValuesController and Login method and it supports only POST, here your all other controllers inherit from BaseController instead ApiController

public class ValuesController : BaseController
{
  [HttpPost]
  public void Login([FromBody]string value)
  {
  }
}

So, once you call your login method, it'll call BaseController method first and you will get response there.

Hope this helps!


问:
Ace editor auto completion into Angular 2?
I am using ace editor and trying to achieve auto-completion in editor. I tried with options but its not working and I am getting warnings.Any idea?

Ace Editor Component

```<code>import {
    Component, EventEmitter, Input, OnInit, Output, ViewChild
} from '@angular/core';

@Component({
    selector: 'neon-ace-editor',
    templateUrl: './ace-editor.component.html',
    styleUrls: ['./ace-editor.component.scss']
})
export class AceEditorComponent implements OnInit {
    @Input() mode = 'html';
    @Input() autoUpdateContent = true;
    @Input() content: string;
    @Output() onContentChange: EventEmitter<string> = new EventEmitter();
    @ViewChild('editor') editor;
    options = {
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true
    };
    ngOnInit(): void {
        this.editor._editor.$blockScrolling = Infinity;
    }

    onContentChanging(): void {
        this.onContentChange.emit(this.content);
    }
}
</code>```

Ace Editor Html

```<code><ace-editor [(text)]="content"
            #editor
            (textChanged)="onContentChanging()"
            [options]="options"
            [autoUpdateContent]="autoUpdateContent"
            style="min-height: 500px; width:100%; font-size:18px;overflow: auto;"
            [mode]="mode"></ace-editor>
</code>```

Issue:

Auto-complete is not working.

Warning messages in console

答:
Try this
app.module.ts

```<code>imports: [
    ...,
    AceEditorModule // import AceEditorModule
  ]
</code>```

app.component.ts

```<code>import {Component, OnInit, ViewChild} from '@angular/core';

import 'brace';
import 'brace/ext/language_tools';
import 'ace-builds/src-min-noconflict/snippets/html';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  text = '';
  @ViewChild('editor') editor;
  options: any = {
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
  };

  ngOnInit() {
   // disable Automatically scrolling cursor into view after selection change warning
    this.editor.getEditor().$blockScrolling = Infinity;
  }
}
app.component.html

<ace-editor
  theme="monokai"
  mode="html"
  [options]="options"
  #editor
  style=" min-height: 600px; width:100%;overflow: auto;"
>
</ace-editor>
.angular-cli.json

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

for more discusstion

Body:
I am using ace editor and trying to achieve auto-completion in editor. I tried with options but its not working and I am getting warnings.Any idea?

Ace Editor Component

import {
    Component, EventEmitter, Input, OnInit, Output, ViewChild
} from '@angular/core';

@Component({
    selector: 'neon-ace-editor',
    templateUrl: './ace-editor.component.html',
    styleUrls: ['./ace-editor.component.scss']
})
export class AceEditorComponent implements OnInit {
    @Input() mode = 'html';
    @Input() autoUpdateContent = true;
    @Input() content: string;
    @Output() onContentChange: EventEmitter<string> = new EventEmitter();
    @ViewChild('editor') editor;
    options = {
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true
    };
    ngOnInit(): void {
        this.editor._editor.$blockScrolling = Infinity;
    }

    onContentChanging(): void {
        this.onContentChange.emit(this.content);
    }
}

Ace Editor Html

<ace-editor [(text)]="content"
            #editor
            (textChanged)="onContentChanging()"
            [options]="options"
            [autoUpdateContent]="autoUpdateContent"
            style="min-height: 500px; width:100%; font-size:18px;overflow: auto;"
            [mode]="mode"></ace-editor>

Issue:

Auto-complete is not working.

Warning messages in console

Body:
Try this
app.module.ts

imports: [
    ...,
    AceEditorModule // import AceEditorModule
  ]

app.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';

import 'brace';
import 'brace/ext/language_tools';
import 'ace-builds/src-min-noconflict/snippets/html';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  text = '';
  @ViewChild('editor') editor;
  options: any = {
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
  };

  ngOnInit() {
   // disable Automatically scrolling cursor into view after selection change warning
    this.editor.getEditor().$blockScrolling = Infinity;
  }
}
app.component.html

<ace-editor
  theme="monokai"
  mode="html"
  [options]="options"
  #editor
  style=" min-height: 600px; width:100%;overflow: auto;"
>
</ace-editor>
.angular-cli.json

"scripts": [],

for more discusstion


问:
Python pip py31compat import error
When I try to install any package via pip on MacOS Sierra, I encounter the following error:

```<code>  File "/usr/local/bin/pip", line 7, in <module>
    from pip import main
  File "/Library/Python/2.7/site-packages/pip/__init__.py", line 26, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 27, in <module>
    from pip._vendor import pkg_resources
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3018, in <module>
    @_call_aside
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3004, in _call_aside
    f(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3046, in _initialize_master_working_set
    dist.activate(replace=False)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2578, in activate
    declare_namespace(pkg)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2152, in declare_namespace
    _handle_ns(packageName, path_item)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2091, in _handle_ns
    loader.load_module(packageName)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 246, in load_module
    mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/PyObjCTools/__init__.py", line 1, in <module>
    __import__('pkg_resources').declare_namespace(__name__)
  File "/Users/jiaseny/Library/Python/2.7/lib/python/site-packages/pkg_resources/__init__.py", line 72, in <module>
    from . import py31compat
ImportError: cannot import name py31compat
</code>```

Trying sudo pip install pkg_resources, sudo pip install setuptools as suggested in ImportError: No module named py31compat
resulted in the same error.

Perhaps I should try uninstalling and reinstalling pip? But sudo pip uninstall pip and  sudo easy_install pip resulted in the same errors...

答:
Based on the path to your python, I can see you're not using the system python which is installed natively, nor are you using homebrew or pyenv, either of which I would highly recommend.

Pyenv is my preferred method of installation for development purposes. A manual install is straight forward and only mildly more difficult than with homebrew, and its one less thing relying on a relatively opaque box to function. The recommended install from the README is just:

```<code>git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
exec "$SHELL"
pyenv install 2.7.14
pyenv global 2.7.14
</code>```

Alternatively if you use homebrew you can just brew install pyenv, and I believe it will set everything up for you, before the pyenv install.

Or if all you want is a somewhat more up to date python than the system one, install homebrew and brew install python.

Title: Python pip py31compat import error

Body:
When I try to install any package via pip on MacOS Sierra, I encounter the following error:

  File "/usr/local/bin/pip", line 7, in <module>
    from pip import main
  File "/Library/Python/2.7/site-packages/pip/__init__.py", line 26, in <module>
    from pip.utils import get_installed_distributions, get_prog
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 27, in <module>
    from pip._vendor import pkg_resources
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3018, in <module>
    @_call_aside
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3004, in _call_aside
    f(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3046, in _initialize_master_working_set
    dist.activate(replace=False)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2578, in activate
    declare_namespace(pkg)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2152, in declare_namespace
    _handle_ns(packageName, path_item)
  File "/Library/Python/2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2091, in _handle_ns
    loader.load_module(packageName)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 246, in load_module
    mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/PyObjCTools/__init__.py", line 1, in <module>
    __import__('pkg_resources').declare_namespace(__name__)
  File "/Users/jiaseny/Library/Python/2.7/lib/python/site-packages/pkg_resources/__init__.py", line 72, in <module>
    from . import py31compat
ImportError: cannot import name py31compat

Trying sudo pip install pkg_resources, sudo pip install setuptools as suggested in ImportError: No module named py31compat
resulted in the same error.

Perhaps I should try uninstalling and reinstalling pip? But sudo pip uninstall pip and  sudo easy_install pip resulted in the same errors...

Body:
Based on the path to your python, I can see you're not using the system python which is installed natively, nor are you using homebrew or pyenv, either of which I would highly recommend.

Pyenv is my preferred method of installation for development purposes. A manual install is straight forward and only mildly more difficult than with homebrew, and its one less thing relying on a relatively opaque box to function. The recommended install from the README is just:

git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
exec "$SHELL"
pyenv install 2.7.14
pyenv global 2.7.14

Alternatively if you use homebrew you can just brew install pyenv, and I believe it will set everything up for you, before the pyenv install.

Or if all you want is a somewhat more up to date python than the system one, install homebrew and brew install python.


问:
How to consistently set EditText Selected Underline Color Programmatically
I'm trying to build a renderer for Xamarin Forms. The renderer needs to set the EditText underline color to "Active Color" when selected and "Hint Color" when deselected. My initial setup looks something like this.

note: here's the path to the full source file

https://github.com/XamFormsExtended/Xfx.Controls/blob/issue-%236/src/Xfx.Controls.Droid/Renderers/XfxEntryRendererDroid.cs

```<code>// called when control is created or when Colors are changed.
protected virtual void SetLabelAndUnderlineColor()
{
    var defaultColor = GetPlaceholderColor();
    var activeColor = GetActivePlaceholderColor();

    SetHintLabelDefaultColor(defaultColor);
    SetHintLabelActiveColor(activeColor);
    SetUnderlineColor(_hasFocus ? activeColor : defaultColor);
}

private void SetUnderlineColor(AColor color)
{
    var bg = ColorStateList.ValueOf(color);
    ViewCompat.SetBackgroundTintList(EditText,bg);
}

private void SetHintLabelActiveColor(AColor color)
{
    var hintText = Control.Class.GetDeclaredField("mFocusedTextColor");
    hintText.Accessible = true;
    hintText.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}

private void SetHintLabelDefaultColor(AColor color)
{
    var hint = Control.Class.GetDeclaredField("mDefaultTextColor");
    hint.Accessible = true;
    hint.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}
</code>```

Outside of this, I also have an OnClickListener that updates the underline only when the state changes

```<code>private void ControlOnFocusChange(object sender, FocusChangeEventArgs args)
{
    _hasFocus = args.HasFocus;
    SetUnderlineColor(args.HasFocus ? GetPlaceholderColor() : GetActivePlaceholderColor());
}
</code>```

The problem is that when I tap into the EditText, it's hit or miss as to what I'm going to see for an underline color.
I can pretty much guarantee that it'll be the default android:colorAccent the very first time. Then after that it switches between the "Hint Color" and the "Placeholder Color".

note: if I change the SetUnderlineColor method to this (below), it no longer uses the "Hint Color" in the mix, but I still get the android:colorAccent color as the initial underline color, after that it behaves as expected.

```<code>private void SetUnderlineColor(AColor color)
{
    var bg = EditText.Background;
    DrawableCompat.SetTint(bg,color);
    EditText.SetBackground(bg);
}
</code>```

What do I need to do to set the INITIAL selected color of the EditText to my chosen activeColor / 'focused color' (purple)?

In this animation I am simply selecting and deselecting the EditText

答:
You need to set the backgroundTintList or supportBackgroundTintList on the EditText to an instance of ColorStateList

```<code>ColorStateList colorStateList = ColorStateList.valueOf(color)
editText.setSupportBackgroundTintList(colorStateList)
</code>```

OR

I think that if you want to change a bottom line color, then you can change using this below line

```<code>editText.getBackground().mutate().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_ATOP);
</code>```

And Application theame like this:-

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="colorControlNormal">@color/colorAccent</item>
    <item name="colorControlActivated">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorAccent</item>

</style>
</code>```

Please check this Example

Hope this Link1 Link2 helps you.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build a renderer for Xamarin Forms. The renderer needs to set the EditText underline color to "Active Color" when selected and "Hint Color" when deselected. My initial setup looks something like this.

note: here's the path to the full source file

https://github.com/XamFormsExtended/Xfx.Controls/blob/issue-%236/src/Xfx.Controls.Droid/Renderers/XfxEntryRendererDroid.cs

// called when control is created or when Colors are changed.
protected virtual void SetLabelAndUnderlineColor()
{
    var defaultColor = GetPlaceholderColor();
    var activeColor = GetActivePlaceholderColor();

    SetHintLabelDefaultColor(defaultColor);
    SetHintLabelActiveColor(activeColor);
    SetUnderlineColor(_hasFocus ? activeColor : defaultColor);
}

private void SetUnderlineColor(AColor color)
{
    var bg = ColorStateList.ValueOf(color);
    ViewCompat.SetBackgroundTintList(EditText,bg);
}

private void SetHintLabelActiveColor(AColor color)
{
    var hintText = Control.Class.GetDeclaredField("mFocusedTextColor");
    hintText.Accessible = true;
    hintText.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}

private void SetHintLabelDefaultColor(AColor color)
{
    var hint = Control.Class.GetDeclaredField("mDefaultTextColor");
    hint.Accessible = true;
    hint.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}

Outside of this, I also have an OnClickListener that updates the underline only when the state changes

private void ControlOnFocusChange(object sender, FocusChangeEventArgs args)
{
    _hasFocus = args.HasFocus;
    SetUnderlineColor(args.HasFocus ? GetPlaceholderColor() : GetActivePlaceholderColor());
}

The problem is that when I tap into the EditText, it's hit or miss as to what I'm going to see for an underline color.
I can pretty much guarantee that it'll be the default android:colorAccent the very first time. Then after that it switches between the "Hint Color" and the "Placeholder Color".

note: if I change the SetUnderlineColor method to this (below), it no longer uses the "Hint Color" in the mix, but I still get the android:colorAccent color as the initial underline color, after that it behaves as expected.

private void SetUnderlineColor(AColor color)
{
    var bg = EditText.Background;
    DrawableCompat.SetTint(bg,color);
    EditText.SetBackground(bg);
}

What do I need to do to set the INITIAL selected color of the EditText to my chosen activeColor / 'focused color' (purple)?

In this animation I am simply selecting and deselecting the EditText

Body:
You need to set the backgroundTintList or supportBackgroundTintList on the EditText to an instance of ColorStateList

ColorStateList colorStateList = ColorStateList.valueOf(color)
editText.setSupportBackgroundTintList(colorStateList)

OR

I think that if you want to change a bottom line color, then you can change using this below line

editText.getBackground().mutate().setColorFilter(getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_ATOP);

And Application theame like this:-

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="colorControlNormal">@color/colorAccent</item>
    <item name="colorControlActivated">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorAccent</item>

</style>

Please check this Example

Hope this Link1 Link2 helps you.


问:
html pattern to parse in php
i have a following pattern, inside the html file, that i would like to parse in php to get a link but for now i dont see a solution as i am trying to use QueryPath and my case is simply not a common dom element:

```<code><script>
to.addVariable("site_name","http://www.sitename.com");
</script>
</code>```

I just would like to return a link part of that pattern in order to print it.

Hope someone could recommend how to.
Thank you.

UPDATE: I would like to get http://www.sitename.com as a value from the code above using php, maybe with phpQuery or QueryPath.

答:
Something like this I guess will work

```<code><?PHP
    $text = '
    <script>
    to.addVariable("site_name","http://www.sitename.com");
    </script>
    ';
    preg_match('#to\.addVariable\("site_name","([^"]+)"\);#', $text, $matches);
    echo $matches[1];
?>
</code>```

You can also use preg_match_all if you have more than one to.addVariable(... strings in your

ContentLicense: CC BY-SA 2.5

Title: html pattern to parse in php

Body:
i have a following pattern, inside the html file, that i would like to parse in php to get a link but for now i dont see a solution as i am trying to use QueryPath and my case is simply not a common dom element:

I just would like to return a link part of that pattern in order to print it.

Hope someone could recommend how to.
Thank you.

UPDATE: I would like to get http://www.sitename.com as a value from the code above using php, maybe with phpQuery or QueryPath.

Body:
Something like this I guess will work

<?PHP
    $text = '
    <script>
    to.addVariable("site_name","http://www.sitename.com");
    </script>
    ';
    preg_match('#to\.addVariable\("site_name","([^"]+)"\);#', $text, $matches);
    echo $matches[1];
?>

You can also use preg_match_all if you have more than one to.addVariable(... strings in your <script> section.


问:
Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\multiusers\users\user_Validate.php on line 13
It seem like the error in the if else statement but I can't trace that error.

Can anyone please help me to solve this error.

```<code><?php
    session_start();
    include("dbconfig.php");
    $table ="";
    $rurl="";
    extract($_REQUEST);
    if($role =="staff"){
        $table="multiusers_staff";
        $rurl="staff/trainer.php";
    }
    else($role=="student"){
        $table="multiusers_student";
        $rurl="student/suexecute.php";
    }
    $mail  = $role."_email";
    $uname = $role."_username";
    $pass  = $role."_password";
    echo $check1="SELECT * FROM $table WHERE $mail ='$uemail' AND $pass ='$upwd' ";
    $login1 = $con->query($check1);
    $login_result1 = $login1->num_rows;
    $row1 = mysqli_fetch_array($login1);
    if(is_array($row1)) {
        $_SESSION['s_usersid']      = $row1[0];
        $_SESSION['s_userrole']     = $role;
        $_SESSION['s_usersemail']   = $row1[$mail];
        $_SESSION['s_usersname']    = $row1[$uname];
    }
    else{
        echo $con->error;
    }
    if(isset($_SESSION["s_usersemail"])) {
        echo "<script>window.location.assign('".$rurl."')</script>";
    }
?>
</code>```

答:
Your error is in else

else never have condition and you put condition here.

You have two ways

use else only.

use elseif($role=="student").

Code is as follows

```<code>    <?php
    session_start();
    include("dbconfig.php");
    $table ="";
    $rurl="";
    extract($_REQUEST);
    if($role =="staff"){
        $table="multiusers_staff";
        $rurl="staff/trainer.php";
    }
    else{ //Or use elseif with condition `elseif($role=="student"){`
        $table="multiusers_student";
        $rurl="student/suexecute.php";
    }
    $mail  = $role."_email";
    $uname = $role."_username";
    $pass  = $role."_password";
    echo $check1="SELECT * FROM $table WHERE $mail ='$uemail' AND $pass ='$upwd' ";
    $login1 = $con->query($check1);
    $login_result1 = $login1->num_rows;
    $row1 = mysqli_fetch_array($login1);
    if(is_array($row1)) {
        $_SESSION['s_usersid']      = $row1[0];
        $_SESSION['s_userrole']     = $role;
        $_SESSION['s_usersemail']   = $row1[$mail];
        $_SESSION['s_usersname']    = $row1[$uname];
    }
    else{
        echo $con->error;
    }
    if(isset($_SESSION["s_usersemail"])) {
        echo "<script>window.location.assign('".$rurl."')</script>";
    }
?>
</code>```

Body:
It seem like the error in the if else statement but I can't trace that error.

Can anyone please help me to solve this error.

<?php
    session_start();
    include("dbconfig.php");
    $table ="";
    $rurl="";
    extract($_REQUEST);
    if($role =="staff"){
        $table="multiusers_staff";
        $rurl="staff/trainer.php";
    }
    else($role=="student"){
        $table="multiusers_student";
        $rurl="student/suexecute.php";
    }
    $mail  = $role."_email";
    $uname = $role."_username";
    $pass  = $role."_password";
    echo $check1="SELECT * FROM $table WHERE $mail ='$uemail' AND $pass ='$upwd' ";
    $login1 = $con->query($check1);
    $login_result1 = $login1->num_rows;
    $row1 = mysqli_fetch_array($login1);
    if(is_array($row1)) {
        $_SESSION['s_usersid']      = $row1[0];
        $_SESSION['s_userrole']     = $role;
        $_SESSION['s_usersemail']   = $row1[$mail];
        $_SESSION['s_usersname']    = $row1[$uname];
    }
    else{
        echo $con->error;
    }
    if(isset($_SESSION["s_usersemail"])) {
        echo "";
    }
?>

Body:
Your error is in else

else never have condition and you put condition here.

You have two ways

use else only.

use elseif($role=="student").

Code is as follows

    <?php
    session_start();
    include("dbconfig.php");
    $table ="";
    $rurl="";
    extract($_REQUEST);
    if($role =="staff"){
        $table="multiusers_staff";
        $rurl="staff/trainer.php";
    }
    else{ //Or use elseif with condition `elseif($role=="student"){`
        $table="multiusers_student";
        $rurl="student/suexecute.php";
    }
    $mail  = $role."_email";
    $uname = $role."_username";
    $pass  = $role."_password";
    echo $check1="SELECT * FROM $table WHERE $mail ='$uemail' AND $pass ='$upwd' ";
    $login1 = $con->query($check1);
    $login_result1 = $login1->num_rows;
    $row1 = mysqli_fetch_array($login1);
    if(is_array($row1)) {
        $_SESSION['s_usersid']      = $row1[0];
        $_SESSION['s_userrole']     = $role;
        $_SESSION['s_usersemail']   = $row1[$mail];
        $_SESSION['s_usersname']    = $row1[$uname];
    }
    else{
        echo $con->error;
    }
    if(isset($_SESSION["s_usersemail"])) {
        echo "<script>window.location.assign('".$rurl."')</script>";
    }
?>


问:
The conditional check dict object' has no attribute ansible error
I have a playbook which runs without issues in us-east-1 , but having issues in ap-southeast-1 in aws. Here is the part of playbook where it fails

```<code>- hosts: "tag_deployment_group_{{ env }}_{{ app }}"
  gather_facts: false
  remote_user: root
  tasks:
    - name: "wait for instances to be reachable"
  wait_for_connection:
    delay: 60
    timeout: 500
- ec2_remote_facts:
    region: ap-southeast-1
    aws_access_key: "{{ aws_access_key }}"
    aws_secret_key: "{{ aws_secret_key }}"
    filters:
      "tag:Env": "{{ env }}"
  register: instance_facts
- add_host:
    name: "{{ item.tags.Name }}"
    ansible_host: "{{ item.private_ip_address }}"
    group: "{{ env }}_{{app}}"
  with_items: "{{ instance_facts.instances }}"
- name: "copy cron script"
  copy: src=/etc/ansible/files/delete.sh dest=/root/scripts/delete.sh
  when: item.tags.app_type == 'platform'
  with_items: "{{ instance_facts.instances }}"
</code>```

The error I get is as follows

```<code>"failed": true,
"msg": "The conditional check 'item.tags.app_type == 'platform''
failed. The error was: error while evaluating conditional
(item.tags.app_type == 'platform'): 'dict object' has no attribute
'app_type'\n\nThe error appears to have been
ts.yml': line 80, column 7, but may\nbe elsewhere in the file depending
on the exact syntax problem.\n\nThe offending line appears to be:\n\n
with_items: \"{{ instance_facts.instances }}\"\n    - name: \"copy cron
script\"\n      ^ here\n"
</code>```

答:
Apparently app_type tag is missing for an instance.

P.S. But I suspect a design flaw in your playbook – if you expect delete.sh script to appear on instances with tag app_type == 'platform' , then your plabook is wrong.

Body:
I have a playbook which runs without issues in us-east-1 , but having issues in ap-southeast-1 in aws. Here is the part of playbook where it fails

- hosts: "tag_deployment_group_{{ env }}_{{ app }}"
  gather_facts: false
  remote_user: root
  tasks:
    - name: "wait for instances to be reachable"
  wait_for_connection:
    delay: 60
    timeout: 500
- ec2_remote_facts:
    region: ap-southeast-1
    aws_access_key: "{{ aws_access_key }}"
    aws_secret_key: "{{ aws_secret_key }}"
    filters:
      "tag:Env": "{{ env }}"
  register: instance_facts
- add_host:
    name: "{{ item.tags.Name }}"
    ansible_host: "{{ item.private_ip_address }}"
    group: "{{ env }}_{{app}}"
  with_items: "{{ instance_facts.instances }}"
- name: "copy cron script"
  copy: src=/etc/ansible/files/delete.sh dest=/root/scripts/delete.sh
  when: item.tags.app_type == 'platform'
  with_items: "{{ instance_facts.instances }}"

The error I get is as follows

"failed": true,
"msg": "The conditional check 'item.tags.app_type == 'platform''
failed. The error was: error while evaluating conditional
(item.tags.app_type == 'platform'): 'dict object' has no attribute
'app_type'\n\nThe error appears to have been
ts.yml': line 80, column 7, but may\nbe elsewhere in the file depending
on the exact syntax problem.\n\nThe offending line appears to be:\n\n
with_items: \"{{ instance_facts.instances }}\"\n    - name: \"copy cron
script\"\n      ^ here\n"


问:
How to escape special characters in PowerShell while creating json object
I have powershell script that I run in an installer while installation. I tried alot of examples to escape special characters, meaning if user choose username or password and that contains characters like slashes or commas, powershell fails to create json objects. Sometimes if user enters a comma, instead of taking it as a string, it breaks into json array. Following are my example and values for varibles are coming from installer, which are valid strings. Thank you for your insights. </p>

```<code>$pathToJson = $InstalledPath+"appsettings.json"
$a = Get-Content $pathToJson | ConvertFrom-Json
$a.SQLConnectionSettings.SqlServerIp=$GkDbIP
$a.SQLConnectionSettings.SqlInitialCatalog=$GkDbName
$a.SQLConnectionSettings.SqlIntegratedSecurity=$SqlAuthType
$a.SQLConnectionSettings.SqlUserId=$GkDbUsername
$a.SQLConnectionSettings.SqlPassword=$SQLPassword
$a | ConvertTo-Json | set-content $pathToJson
</code>```

答:
You can use Regex.Unescape to unscape the json content. For example:

```<code>$OBJECT = @{username="someone"; password="someone's \password"}
$OBJECT | ConvertTo-Json -depth 100 |
     % { [System.Text.RegularExpressions.Regex]::Unescape($_) } |
         Out-File "D:\somefile.json" -Encoding utf8
</code>```

And here is the result:

```<code>{
    "password":  "someone's \password",
    "username":  "someone"
}
</code>```

If you don't use unescape, the password will be saved as "someone\u0027s \\password".

Body:
I have powershell script that I run in an installer while installation. I tried alot of examples to escape special characters, meaning if user choose username or password and that contains characters like slashes or commas, powershell fails to create json objects. Sometimes if user enters a comma, instead of taking it as a string, it breaks into json array. Following are my example and values for varibles are coming from installer, which are valid strings. Thank you for your insights.

$pathToJson = $InstalledPath+"appsettings.json"
$a = Get-Content $pathToJson | ConvertFrom-Json
$a.SQLConnectionSettings.SqlServerIp=$GkDbIP
$a.SQLConnectionSettings.SqlInitialCatalog=$GkDbName
$a.SQLConnectionSettings.SqlIntegratedSecurity=$SqlAuthType
$a.SQLConnectionSettings.SqlUserId=$GkDbUsername
$a.SQLConnectionSettings.SqlPassword=$SQLPassword
$a | ConvertTo-Json | set-content $pathToJson

Body:
You can use Regex.Unescape to unscape the json content. For example:

$OBJECT = @{username="someone"; password="someone's \password"}
$OBJECT | ConvertTo-Json -depth 100 |
     % { [System.Text.RegularExpressions.Regex]::Unescape($_) } |
         Out-File "D:\somefile.json" -Encoding utf8

And here is the result:

{
    "password":  "someone's \password",
    "username":  "someone"
}

If you don't use unescape, the password will be saved as "someone\u0027s \\password".


问:
Angular 2 | *ngFor Loop create new arraylist upon execution
How can i change the index of my loop back to zero when i use same array?

in my ts file

```<code>data = [{name: 'A', group: 'one'},{name: 'B', group: 'one'},{name: 'C', group: 'two'},{name: 'D', group: 'two'},{name: 'E', group: 'two'}];
</code>```

in my html file

```<code><ng-container *ngFor="let apidata of data; let i = index">
   <span *ngIf="apidata.group == 'one'">{{apidata.name}} | {{i}}
<ng-container>

<ng-container *ngFor="let apidata of data; let i = index">
   <span *ngIf="apidata.group == 'two'">{{apidata.name}} | {{i}}
<ng-container>
</code>```

i want to display something like this. as you can see it reset back my index when being passed to a new ng-container

```<code><span>A | 1</span>
<span>B | 2</span>
<span>C | 1</span>
<span>D | 2</span>
<span>E | 3</span>
</code>```

so far i always get this actual result

```<code><span>A | 1</span>
<span>B | 2</span>
<span>C | 3</span>
<span>D | 4</span>
<span>E | 5</span>
</code>```

答:
Your problem can be solved simply using the below logic

1) Below code in component

```<code>export class AppComponent implements OnInit {
  public data = [{name: 'A', group: 'one'},{name: 'C', group: 'two'},{name: 'B', group: 'one'},{name: 'D', group: 'two'},{name: 'E', group: 'two'}];

  ngOnInit() {
    this.data = this.groupByData(this.data);
  }

  private groupByData(data): any {
    const groups = ['one', 'two'];
    return data.sort((item1, item2) => {
      if (item1.group === item2.group) {
        return 0;
      } else if (groups.indexOf(item1.group) < groups.indexOf(item2.group)) {
        return -1;
      } else {
        return 1;
      }
    });
  }
}
</code>```

2) Below in template

```<code><ng-container *ngFor="let apidata of data; let i = index">
  <span>{{apidata.name}} | {{i + 1}}</span>
</ng-container>
</code>```

Body:
How can i change the index of my loop back to zero when i use same array?

in my ts file

data = [{name: 'A', group: 'one'},{name: 'B', group: 'one'},{name: 'C', group: 'two'},{name: 'D', group: 'two'},{name: 'E', group: 'two'}];

in my html file

<ng-container *ngFor="let apidata of data; let i = index">
   {{apidata.name}} | {{i}}
<ng-container>

<ng-container *ngFor="let apidata of data; let i = index">
   {{apidata.name}} | {{i}}
<ng-container>

i want to display something like this. as you can see it reset back my index when being passed to a new ng-container

A | 1
B | 2
C | 1
D | 2
E | 3

so far i always get this actual result

A | 1
B | 2
C | 3
D | 4
E | 5

Body:
Your problem can be solved simply using the below logic

1) Below code in component

export class AppComponent implements OnInit {
  public data = [{name: 'A', group: 'one'},{name: 'C', group: 'two'},{name: 'B', group: 'one'},{name: 'D', group: 'two'},{name: 'E', group: 'two'}];

  ngOnInit() {
    this.data = this.groupByData(this.data);
  }

  private groupByData(data): any {
    const groups = ['one', 'two'];
    return data.sort((item1, item2) => {
      if (item1.group === item2.group) {
        return 0;
      } else if (groups.indexOf(item1.group) < groups.indexOf(item2.group)) {
        return -1;
      } else {
        return 1;
      }
    });
  }
}

2) Below in template

<ng-container *ngFor="let apidata of data; let i = index">
  <span>{{apidata.name}} | {{i + 1}}</span>
</ng-container>


问:
Concatenate character to __VA_ARGS__ in a macro redefining printf
I'm developing an embedded application that uses a library for interfacing with a SPI NAND memory chip.  The library provided uses a print function in which I, as the applications developer, must override for my specific platform.

For instance, they use the function printf_ extensively in their code.

I redefine it as such, to get the print function to print over the serial interface

```<code>#define printf_(...) serial.printf(__VA_ARGS__)
</code>```

It works fine, except that on this platform, you need to supply a carriage return ("\r") for a newline.  So right now, when the library is called, the formatting is horrible.

I'd like to append a "\r" to the end of whatever is supplied to the print function.  Like

```<code>#define printf_(...) serial.printf(__VA_ARGS__##"\r")
</code>```

Obviously that doesn't work.

I'm really not familiar with, and have sort of a hard time understanding variadic functions in C, so this would provide me with a little learning opportunity if I could figure this out, or at least I would learn if this is not possible.

I also can't just wrap the function using va_lists and vsprintfs because my platform does not support this (and I'd rather redefine it in a macro, as a performance/stylistic choice, personally).

Is there a way to do this?

答:
I agree with other users that your requirement of CR coming after LF is quite strange, and I have a strong suspicion you mean for it to be CRLF, not LFCR. Regardless, I will help you with your original requirement of appending CR to the string.

It is going to be incredibly difficult to perform this operation in a one-liner macro. Alternatively, you could use a nasty-looking multi-line macro:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define printf_(format, args...)                                        \
do {                                                                    \
    int _len_orig = strlen(format);                                     \
    /* strlen doesn't consider newline. Check for that. */              \
    if ( format[_len_orig] == '\n' )                                    \
        _len_orig++;                                                    \
                                                                        \
    /* len_orig + 2 to make space for null terminator and '\r' */       \
    unsigned _new_size = _len_orig + 2;                                 \
    char* _new_str  = calloc(_new_size, 1);                             \
    strncpy( _new_str, format, _len_orig );                             \
    _new_str[_new_size-2] = '\r';                                       \
                                                                        \
    /* Print out the raw hex of the string to prove it worked */        \
    int _i;                                                             \
    for( _i = 0; _i < _new_size; _i++)                                  \
        printf("%02x ", _new_str[_i]);                                  \
    printf("\n");                                                       \
    free(_new_str);                                                     \
} while(0)

int main(){

    char* str = "@@@@\n";
    printf_( str );

    return 0;
}
</code>```

In my macro, I have not used your serial.printf function but rather made some short code that prints out the hexidecimal values of the concatenated string for proof that the logic works.

Explanation

Macros are required to appear as a single line to the C Preprocessor. The additions of \ at the end of each macro line escape the newline character.

gcc allows for named arguments in your macro. Here, format describes the format string you would normally pass to printf, and args... is the variable argument name for "everything else" you would pass into printf. I do not reference args in this example, but you will certainly want to modify my example in your final code to include it. Your call to printf would look something like serial.printf( _new_str, args);

Multi-line macros are kind of nasty in that you need to do some trickery to get them to appear as normal functions to the human programmer. The need for enclosing the macro in a do-while is nicely discussed here. The linked page is meant for C++, but it applies to C as well.

If you copy my code, compile, and run it, this is the output:

```<code>[clipp@h2ologin3:~]$ ./a.out
40 40 40 40 0a 0d 00
</code>```

Here, this ASCII dump is showing us that 4 @ symbols were copied, followed by \n, \r, and finally \0.

There is also a strong case for instead writing this as an inline C function. You say that your system doesn't support va_list etc. so if that is true, then a  macro may be the only choice.

QED.

Body:
I'm developing an embedded application that uses a library for interfacing with a SPI NAND memory chip.  The library provided uses a print function in which I, as the applications developer, must override for my specific platform.

For instance, they use the function printf_ extensively in their code.

I redefine it as such, to get the print function to print over the serial interface

#define printf_(...) serial.printf(__VA_ARGS__)

It works fine, except that on this platform, you need to supply a carriage return ("\r") for a newline.  So right now, when the library is called, the formatting is horrible.

I'd like to append a "\r" to the end of whatever is supplied to the print function.  Like

#define printf_(...) serial.printf(__VA_ARGS__##"\r")

Obviously that doesn't work.

I'm really not familiar with, and have sort of a hard time understanding variadic functions in C, so this would provide me with a little learning opportunity if I could figure this out, or at least I would learn if this is not possible.

I also can't just wrap the function using va_lists and vsprintfs because my platform does not support this (and I'd rather redefine it in a macro, as a performance/stylistic choice, personally).

Is there a way to do this?

Body:
I agree with other users that your requirement of CR coming after LF is quite strange, and I have a strong suspicion you mean for it to be CRLF, not LFCR. Regardless, I will help you with your original requirement of appending CR to the string.

It is going to be incredibly difficult to perform this operation in a one-liner macro. Alternatively, you could use a nasty-looking multi-line macro:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define printf_(format, args...)                                        \
do {                                                                    \
    int _len_orig = strlen(format);                                     \
    /* strlen doesn't consider newline. Check for that. */              \
    if ( format[_len_orig] == '\n' )                                    \
        _len_orig++;                                                    \
                                                                        \
    /* len_orig + 2 to make space for null terminator and '\r' */       \
    unsigned _new_size = _len_orig + 2;                                 \
    char* _new_str  = calloc(_new_size, 1);                             \
    strncpy( _new_str, format, _len_orig );                             \
    _new_str[_new_size-2] = '\r';                                       \
                                                                        \
    /* Print out the raw hex of the string to prove it worked */        \
    int _i;                                                             \
    for( _i = 0; _i < _new_size; _i++)                                  \
        printf("%02x ", _new_str[_i]);                                  \
    printf("\n");                                                       \
    free(_new_str);                                                     \
} while(0)

int main(){

    char* str = "@@@@\n";
    printf_( str );

    return 0;
}

In my macro, I have not used your serial.printf function but rather made some short code that prints out the hexidecimal values of the concatenated string for proof that the logic works.

Explanation

Macros are required to appear as a single line to the C Preprocessor. The additions of \ at the end of each macro line escape the newline character.

gcc allows for named arguments in your macro. Here, format describes the format string you would normally pass to printf, and args... is the variable argument name for "everything else" you would pass into printf. I do not reference args in this example, but you will certainly want to modify my example in your final code to include it. Your call to printf would look something like serial.printf( _new_str, args);

Multi-line macros are kind of nasty in that you need to do some trickery to get them to appear as normal functions to the human programmer. The need for enclosing the macro in a do-while is nicely discussed here. The linked page is meant for C++, but it applies to C as well.

If you copy my code, compile, and run it, this is the output:

[clipp@h2ologin3:~]$ ./a.out
40 40 40 40 0a 0d 00

Here, this ASCII dump is showing us that 4 @ symbols were copied, followed by \n, \r, and finally \0.

There is also a strong case for instead writing this as an inline C function. You say that your system doesn't support va_list etc. so if that is true, then a  macro may be the only choice.

QED.


问:
npm install getting failed for angular 2
I'm newbie to angular 2. From reading some resources I had done with the following steps for my angular 2 application.
1)Create a folder named "DemoThree".
2)From the command prompt taken a hit over "ng new ThirdApp"
ThirdApp is my application name. Even It got succeded.
Find the image below for successfully creation of application.

3)When I hit the command "npm start" I'm facing an error list in command prompt as like below image

4)From the errors, I understood that I'm not getting package.json file. How could I get that file ?

I had seen lot of commands related to getting package.json file, of them one is one is by using npm init.
But when I tried with init. It's asking to provide me all the values of keys like description, version, name,script,dependencies.

How to resolve my error list from the prompt ?

5)After facing that error I thought that I need to install anguar cli which get all dependencies by using npm install -g @angular/cli
Got succeeded here.

6)Again I tried with npm install. No use faced the same poin 3 error image.

Please suggest me where I was doing mistake.

答:
$ npm init

then reprocess whole commands, after that use

$npm start

try it


问:
JQuery vs ExtJS
We are planning the development of completely new GUI. We were very happy with JQuery which we used in our old product. It was easy, classy and fast.

We have heard about ExtJS. It also has AJAX and a large list of other features.

We want to use only one of them.

Which is best based on your experience?

答:
Jared Farrish's answer is pretty extensive already.

I've used both on different projects.

ExtJS is a lot heavier in both size and what it allows you to do. It's excellent if you need a complex web application interface, it has great controls for windows, tables, etc, and it looks sleek.

The ext forum community is quite helpfull through their forum.

That said it a lot more "rigid" than jQuery, and there's a significantly longer learning curve to get started, but if you are looking at complex UIs it will pay off down the track.

The benefits of jQuery is therefore that it will get your project moving quicker, and it will be easier to "experiment" while implementing new features.

They're both good for their own type of applications. I've actually used both on a project, the extensive admin (lots of windows and sections) is built in ExtJS and the front end, which needs faster turn around to tweak things but has limited ui interaction is built in jQuery.

Hope this helps

Title: JQuery vs ExtJS


问:
AlertBuilder showing an exception. DialogBox is not opening
In the following code I want to open the dialog box when the mIndex is 0.

The code is going in the 'if' part. But is not opening the dialog Box instead showing the following exception.

Code:

```<code>mIndex = (mIndex+1)%mQuestionBank.length;
    if(mIndex == 0 )
    {
        Log.d("Quizzler", "Inside IF");
        AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
        alert.setTitle("Game Over");
        alert.setCancelable(false);
        alert.setMessage("Your score is "+mScore);
        alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
    }
</code>```

Exception:

```<code>FATAL EXCEPTION: main
                                                                  Process: com.londonappbrewery.quizzler, PID: 11560                                                                               android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                                                                               at android.view.ViewRootImpl.setView(ViewRootImpl.java:714)
                                                                               at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                               at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                               at android.app.Dialog.show(Dialog.java:316)
                                                                               at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
                                                                               at com.londonappbrewery.quizzler.MainActivity.updateQuestion(MainActivity.java:100)
                                                                               at com.londonappbrewery.quizzler.MainActivity.access$100(MainActivity.java:16)
                                                                               at com.londonappbrewery.quizzler.MainActivity$1.onClick(MainActivity.java:69)
                                                                               at android.view.View.performClick(View.java:5609)
                                                                               at android.view.View$PerformClick.run(View.java:22263)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
Instead of </p>

```<code>new AlertDialog.Builder(getApplicationContext());
</code>```

<p>Try using </p>

```<code>new AlertDialog.Builder(MainActivity.this);
</code>```

Body:
In the following code I want to open the dialog box when the mIndex is 0.

The code is going in the 'if' part. But is not opening the dialog Box instead showing the following exception.

Code:

mIndex = (mIndex+1)%mQuestionBank.length;
    if(mIndex == 0 )
    {
        Log.d("Quizzler", "Inside IF");
        AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
        alert.setTitle("Game Over");
        alert.setCancelable(false);
        alert.setMessage("Your score is "+mScore);
        alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
    }

Exception:

FATAL EXCEPTION: main
                                                                  Process: com.londonappbrewery.quizzler, PID: 11560                                                                               android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                                                                               at android.view.ViewRootImpl.setView(ViewRootImpl.java:714)
                                                                               at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                               at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                               at android.app.Dialog.show(Dialog.java:316)
                                                                               at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
                                                                               at com.londonappbrewery.quizzler.MainActivity.updateQuestion(MainActivity.java:100)
                                                                               at com.londonappbrewery.quizzler.MainActivity.access$100(MainActivity.java:16)
                                                                               at com.londonappbrewery.quizzler.MainActivity$1.onClick(MainActivity.java:69)
                                                                               at android.view.View.performClick(View.java:5609)
                                                                               at android.view.View$PerformClick.run(View.java:22263)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
Instead of

new AlertDialog.Builder(getApplicationContext());

Try using

new AlertDialog.Builder(MainActivity.this);


问:
Number which occurs only once in the array

Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

```<code>a[1..n] = [1,2,3,4,3,1,2]
</code>```

should return 4

答:
You could sort the array and then find the first element that doesn't have a pair. That would require several loops for sorting and a loop for finding the single element.

But a simplier method would be setting the double keys to zero or a value that is not possible in the current format. Depends on the programming language, as well, as you cannot change key types in c++ unlike c#.

Body:
Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

a[1..n] = [1,2,3,4,3,1,2]

should return 4


问:
window.location.reload(true) reloads page but page needs refreshing to show changes
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.

This is an example that adds the button and reloads page on click

```<code>if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li><a href="" onclick="window.location.reload(true);return toggleLive(this, ' . $post->ID . ');">' . $text . '</a></li>';
}
</code>```

So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.

Thanks in advance for your help

EDIT -
I have already tried
location.href = location.href; and
document.location.reload();

ADDITIONAL INFO -

Function

```<code>add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
    die( __('No post ID specified.') );
}

// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
    die( __('You attempted to edit an item that doesn’t exist. Perhaps it was deleted?') );
}

// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
    die( __('You are not allowed to edit this item.') );
}

// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));

// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );

$index = array_search($live, $terms);
if ($_REQUEST['value']) {
    if ($index === false) {
        $terms[] = $live;
    }
} else {
    if ($index !== false) {
        unset($terms[$index]);
    }
}

wp_set_object_terms( $post_id, 'live', 'campaign_action' );

die('1');
});
</code>```

JS

```<code>function toggleLive(caller, post_id)
{

var $ = jQuery;
var $caller = $(caller);

var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";

// Check there's no request in progress
if ($caller.text() == waitText) {
    return false;
}

// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);

// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);

// Ajax request
var data = {
    action: "toggle_live",
    post:   post_id,
    value:  value
};

jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
    if (response == "1") {

        // Success
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    } else {

        // Error
        alert("Error: " + response);

        // Reset the text
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    }

    // Reset the width
    $caller.width("auto");
});

// Prevent the link click happening
return false;
}
</code>```

IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR

答: Try using Live Query plug-in in jquery instead of live .</p>

Body:
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.

This is an example that adds the button and reloads page on click

if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '
ID . ');">' . $text . '
';
}

So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.

Thanks in advance for your help

EDIT -
I have already tried
location.href = location.href; and
document.location.reload();

ADDITIONAL INFO -

Function

add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
    die( __('No post ID specified.') );
}

// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
    die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?') );
}

// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
    die( __('You are not allowed to edit this item.') );
}

// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));

// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );

$index = array_search($live, $terms);
if ($_REQUEST['value']) {
    if ($index === false) {
        $terms[] = $live;
    }
} else {
    if ($index !== false) {
        unset($terms[$index]);
    }
}

wp_set_object_terms( $post_id, 'live', 'campaign_action' );

die('1');
});

JS

function toggleLive(caller, post_id)
{

var $ = jQuery;
var $caller = $(caller);

var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";

// Check there's no request in progress
if ($caller.text() == waitText) {
    return false;
}

// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);

// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);

// Ajax request
var data = {
    action: "toggle_live",
    post:   post_id,
    value:  value
};

jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
    if (response == "1") {

        // Success
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    } else {

        // Error
        alert("Error: " + response);

        // Reset the text
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    }

    // Reset the width
    $caller.width("auto");
});

// Prevent the link click happening
return false;
}

IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR


问:
Trying to copy all strings from char*[] but get segmentation fault
I am trying to figure out why I am getting a segmentation fault when trying to copy the arguments from one array of strings to another but just leaving out the > </p>

```<code>int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }
</code>```

答:
```<code>strcpy(temp[i],args[i]);
</code>```

This is undefined behavior. strcpy tries to access an indeterminate memory location resulting in undefined behavior.

You need to allocate memory to temp[i] or simply use

```<code>temp[i]=strdup(args[i])
</code>```

to copy the string to temp[i].

Also

```<code>int size = 4*sizeof(args)/sizeof(args);
</code>```

would be

```<code>int size = sizeof(args)/sizeof(*args);
</code>```

If you know the length of the array to be 4 then what's the use of doing all those calculation. You need to calculate it not put it like that.

Example code:-

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     size_t size = sizeof(args)/sizeof(*args);
     char *temp[size];
     size_t len = 0;
     printf("SIZE: %zu\n", size);
     for(size_t i = 0; i < size; ++i){
            if(strcmp(args[i], ">") != 0 ){
                temp[len++] = args[i];
            }
     }
     for(size_t i = 0; i < len; i++){
        printf("arg[%zu]: %s\n", i+1, temp[i]);
     }
     return 0;
 }
</code>```

Note that your comparison should be much more simpler as mentioned above.

What does strdup do?

Internally it allocates memory and then copies the target string using strcpy. This is not part of the standard library and implemented by POSIX.
For more detail look at this answer .

Body:
I am trying to figure out why I am getting a segmentation fault when trying to copy the arguments from one array of strings to another but just leaving out the >

int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }

Body:
strcpy(temp[i],args[i]);

This is undefined behavior. strcpy tries to access an indeterminate memory location resulting in undefined behavior.

You need to allocate memory to temp[i] or simply use

temp[i]=strdup(args[i])

to copy the string to temp[i].

Also

int size = 4*sizeof(args)/sizeof(args);

would be

int size = sizeof(args)/sizeof(*args);

If you know the length of the array to be 4 then what's the use of doing all those calculation. You need to calculate it not put it like that.

Example code:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     size_t size = sizeof(args)/sizeof(*args);
     char *temp[size];
     size_t len = 0;
     printf("SIZE: %zu\n", size);
     for(size_t i = 0; i < size; ++i){
            if(strcmp(args[i], ">") != 0 ){
                temp[len++] = args[i];
            }
     }
     for(size_t i = 0; i < len; i++){
        printf("arg[%zu]: %s\n", i+1, temp[i]);
     }
     return 0;
 }

Note that your comparison should be much more simpler as mentioned above.

What does strdup do?

Internally it allocates memory and then copies the target string using strcpy. This is not part of the standard library and implemented by POSIX.
For more detail look at this answer .