问:
ajax, Show modal if yes then continue with another ajax if not continue with the loop
I've been trying for a day to know how to solve this, I really tried to search an answer but i guess i couldn't or i didn't understand.

Here are the steps from my problem:

1.- I will do a for , so i have to process each record one by one using ajax (i saw that using async :false  will let me process one by one and not all at the same time, i mean it is like a fifo, am i right? cause i need that,because i'm using httpsession some vars need to be changed one by one, thats why i'm trying to process each record one by one, although in my example  i don't show this)

2.- if my validation is 1 i will call next ajax but if it is number 2 i have to ask the user to put somethig and then continue with another ajax and then this ajax will call the other ajax as number 1 (here is one of my problem because when i show the modal, the modal is displayed but it continues in the loop so i need to stop my ajax untill the user put something and when he clicks "Save changes" it must continue with the loop, although as i said this is not happening (i tried to use a while(true) but i didn't had a chance my browser stops the script), my program shows the modal and continue looping no matter what)

3.-If user see the modal and click close, well i won't continue with my ajax but i will continue with my loop or my for, because i need to process all things.

This is an example of the modal:

And now, as you can see, yeah my modal showed up but my loop continue no matter what :(

So as i said i need this:

1.- i'm doing a for in order to process all my stuff, but depending of the answer sometimes i have to show the modal, so when user click in savechanges it will call another ajax and then another ajax and continue the loop, but if user click in close well i have to stop the next ajax calls and continue with my for in the next position and do it again again and again untill my for stops.

2.-in other words i have to call my ajax number 1,2,4 if my result is 1 in ajax number 2, but if my result in ajax number 2 is == 2 then i have to show modal and stop the for because it continues looping, and depending of the answe if it is save changes then i have to call ajax3 and this will call ajax4 but if it is close then i have to continue in the next loop, and again, this could happen depending of the answer.

Here are my examples code:

JSP:

```<code><!DOCTYPE html>
<html>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
$(document).ready(function(){

  var positionNumber = 1;
  $(".clickme").click(function(){
    for(var i=0; i < 10; i++){
        ajaxOne();
    }

    $("body").on('click', '.btn-default', function(e) {
      console.log('ok we finish no more calls to servlets');
      $('#myModal').modal('hide')   ;
      console.log('BUT LETS CONTINUE WITH THE FOR.... WE HAVE TO CHECK ALL THE ITEMS')
    });

    $("body").on('click', '.btn-primary', function(e) {
      console.log('ok lets call now ajax three');
      ajaxThree();
    });
  });

  function ajaxOne(){
    $.ajax({
      type: "POST",
      url: "/Test/one",
      //contentType : "text/xml",
      async :false ,
      beforeSend: function () {
        console.log('CALLING POSITION: '+positionNumber);
        console.log('Call Servlet one')
      },
      success: function(data,status,xhr){
        console.log(data)
      },
      error: function(xhr, status, error){
        alert("Error!" + xhr.status);
      },
      complete: function(){
        positionNumber++;
        console.log('finish Call Servlet one')
        ajaxTwo();
      }
     });
  }

  function ajaxTwo(){
    var text;
    $.ajax({
      type: "POST",
      url: "/Test/two",
      //contentType : "text/xml",
      async :false ,
      beforeSend: function () {
        console.log('Call Servlet two')
      },
      success: function(data,status,xhr){
      console.log(data);
      text = data;
      },
      error: function(xhr, status, error){
        alert("Error!" + xhr.status);
      },
      complete: function(){
        console.log('finish Call Servlet two')
        if(parseInt(text)==2){
          $('#myModal').modal('show')   ; // I have to show the modal, and stop all processing,
                                          // if he select save changes I will call ajax 3 and then four, if he select cancel then
                                          // I have to continue with my loop again...
                                          // Here I need a little help :'( thank you so much
        }else{
          ajaxFour();
        }
      }
    });
  }

  function ajaxThree(){
    $.ajax({
      type: "POST",
      url: "/Test/three",
      //contentType : "text/xml",
      async :false ,
      beforeSend: function () {
        console.log('Call Servlet three')
      },
      success: function(data,status,xhr){
        console.log(data);
      },
      error: function(xhr, status, error){
        alert("Error!" + xhr.status);
      },
      complete: function(){
        console.log('finish Call Servlet three')
        ajaxFour();
      }
    });
  }

  function ajaxFour(){
    $.ajax({
      type: "POST",
      url: "/Test/four",
      //contentType : "text/xml",
      async :false ,
        beforeSend: function () {
        console.log('Call Servlet four')
      },
      success: function(data,status,xhr){
        console.log(data);
      },
      error: function(xhr, status, error){
        alert("Error!" + xhr.status);
      },
      complete: function(){
        console.log('finish Call Servlet four')
      }
    });
  }
});
</script>
</head>
<body>

<div class="clickme">click me </div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" >Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

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

Servlet one

```<code>package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "one", urlPatterns = { "/one" })
public class ServeletOne extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("one");
  }

}
</code>```

Servlet two

```<code>package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "two", urlPatterns = { "/two" })
public class ServeletOne2 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne2() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    int tmp = (int) ( Math.random() * 2 + 1);
    System.out.println(tmp);
     out.println(tmp);
  }

}
</code>```

Servlet three

```<code>package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "three", urlPatterns = { "/three" })
public class ServeletOne3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne3() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("three");
  }

}
</code>```

servlet four

```<code>package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "four", urlPatterns = { "/four" })
public class ServeletOne4 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne4() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("four");
  }

}
</code>```

答:
In order to solve my error I used some flags

```<code>var positionNumber = 0;
    var flagPressedButton = false;
</code>```

and in my for i used other way

```<code>for(i; i < 10;){

            ajaxOne();
                 i++;
                 if(continuar == false) break;
</code>```

and when my modal shows up if everything is ok i simulate a click again

$(".clickme").click();

Here is all my js code

```<code><script>
$(document).ready(function(){
    var continuar = true;
    var positionNumber = 0;
    var flagPressedButton = false;
    var i=0;
    $(".clickme").click(function(event){

        for(i; i < 10;){

            ajaxOne();
                 i++;
                 if(continuar == false) break;

        }

      $("body").on('click', '.btn-default', function(e) {
          console.log('ok we finish no more calls to servlets');
          $('#myModal').modal('hide')   ;
          console.log('BUT LETS CONTINUE WITH THE FOR.... WE HAVE TO CHECK ALL THE ITEMS')
        $(".clickme").click();
      });

      $("body").on('click', '.btn-primary', function(e) {
          console.log('ok lets call now ajax three');
          ajaxThree();
        $(".clickme").click();
      });

    });

function ajaxOne(){
    $.ajax({
           type: "POST",
             url: "/Test/one",
           //contentType : "text/xml",

           async :false ,
           beforeSend: function () {
               continuar =true;
                 positionNumber++;
               console.log('CALLING POSITION: '+positionNumber);
             console.log('Call Servlet one')
                },
             success: function(data,status,xhr){
                console.log('complete: ', JSON.parse(data));
                var statusCode = JSON.parse(data).responseCode;
                console.log('satusCode: ', statusCode);
                if (statusCode) {
                    ajaxTwo(statusCode);
                }
                                      },
                error: function(xhr, status, error){
                  alert("Error!" + xhr.status);
                         }

           });

}

    function ajaxTwo(){
        var text;
        $.ajax({
               type: "POST",
                 url: "/Test/two",
               //contentType : "text/xml",
               async :false ,
               beforeSend: function () {
                 console.log('Call Servlet two')
                    },
                 success: function(data,status,xhr){
                    console.log(data);
                    text = data;

                                          },
                    error: function(xhr, status, error){
                      alert("Error!" + xhr.status);
                             },
                         complete: function(){
                             console.log('finish Call Servlet two')

                            if(parseInt(text)==2){
                                console.error('LLAMARE A LA MODAL');
                                   $('#myModal').modal('show')   ;
                                   continuar = false;
                            }else{
                                ajaxFour();
                            }
                            }

               });

    }

    function ajaxThree(){
        $.ajax({
               type: "POST",
                 url: "/Test/three",
               //contentType : "text/xml",
               async :false ,
               beforeSend: function () {
                 console.log('Call Servlet three')
                    },
                 success: function(data,status,xhr){
                    console.log(data);

                                          },
                    error: function(xhr, status, error){
                      alert("Error!" + xhr.status);
                             },
                         complete: function(){
                             console.log('finish Call Servlet three')
                                                            console.error('CERRARE A LA MODALA Y CONTINUARE');
                             $('#myModal').modal('hide')   ;
                             ajaxFour();
                             continuar = true;
                            }

               });

    }

    function ajaxFour(){
        $.ajax({
               type: "POST",
                 url: "/Test/four",
               //contentType : "text/xml",
               async :false ,
               beforeSend: function () {
                 console.log('Call Servlet four')
                    },
                 success: function(data,status,xhr){
                    console.log(data);

                                          },
                    error: function(xhr, status, error){
                      alert("Error!" + xhr.status);
                             },
                         complete: function(){
                             console.log('finish Call Servlet four')
                            }

               });

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

As i Said, i neded to show a modal and then continue, well i solve it in this way and now it's working fine for me =) and do not forget use async :false , in order to make a petition by petition

Body:
I've been trying for a day to know how to solve this, I really tried to search an answer but i guess i couldn't or i didn't understand.

Here are the steps from my problem:

1.- I will do a for , so i have to process each record one by one using ajax (i saw that using async :false  will let me process one by one and not all at the same time, i mean it is like a fifo, am i right? cause i need that,because i'm using httpsession some vars need to be changed one by one, thats why i'm trying to process each record one by one, although in my example  i don't show this)

2.- if my validation is 1 i will call next ajax but if it is number 2 i have to ask the user to put somethig and then continue with another ajax and then this ajax will call the other ajax as number 1 (here is one of my problem because when i show the modal, the modal is displayed but it continues in the loop so i need to stop my ajax untill the user put something and when he clicks "Save changes" it must continue with the loop, although as i said this is not happening (i tried to use a while(true) but i didn't had a chance my browser stops the script), my program shows the modal and continue looping no matter what)

3.-If user see the modal and click close, well i won't continue with my ajax but i will continue with my loop or my for, because i need to process all things.

This is an example of the modal:

And now, as you can see, yeah my modal showed up but my loop continue no matter what :(

So as i said i need this:

1.- i'm doing a for in order to process all my stuff, but depending of the answer sometimes i have to show the modal, so when user click in savechanges it will call another ajax and then another ajax and continue the loop, but if user click in close well i have to stop the next ajax calls and continue with my for in the next position and do it again again and again untill my for stops.

2.-in other words i have to call my ajax number 1,2,4 if my result is 1 in ajax number 2, but if my result in ajax number 2 is == 2 then i have to show modal and stop the for because it continues looping, and depending of the answe if it is save changes then i have to call ajax3 and this will call ajax4 but if it is close then i have to continue in the next loop, and again, this could happen depending of the answer.

Here are my examples code:

JSP:

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

click me

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" >Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Servlet one

package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "one", urlPatterns = { "/one" })
public class ServeletOne extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("one");
  }

}

Servlet two

package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "two", urlPatterns = { "/two" })
public class ServeletOne2 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne2() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    int tmp = (int) ( Math.random() * 2 + 1);
    System.out.println(tmp);
     out.println(tmp);
  }

}

Servlet three

package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "three", urlPatterns = { "/three" })
public class ServeletOne3 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne3() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("three");
  }

}

servlet four

package com.dot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServeletOne
 */
@WebServlet(name = "four", urlPatterns = { "/four" })
public class ServeletOne4 extends HttpServlet {
  private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServeletOne4() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Yep i did a post");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("four");
  }

}

Body:
In order to solve my error I used some flags

var positionNumber = 0;
    var flagPressedButton = false;

and in my for i used other way

for(i; i < 10;){

            ajaxOne();
                 i++;
                 if(continuar == false) break;

and when my modal shows up if everything is ok i simulate a click again

$(".clickme").click();

Here is all my js code

<script>
$(document).ready(function(){
    var continuar = true;
    var positionNumber = 0;
    var flagPressedButton = false;
    var i=0;
    $(".clickme").click(function(event){

        for(i; i < 10;){

            ajaxOne();
                 i++;
                 if(continuar == false) break;

        }

      $("body").on('click', '.btn-default', function(e) {
          console.log('ok we finish no more calls to servlets');
          $('#myModal').modal('hide')   ;
          console.log('BUT LETS CONTINUE WITH THE FOR.... WE HAVE TO CHECK ALL THE ITEMS')
        $(".clickme").click();
      });

      $("body").on('click', '.btn-primary', function(e) {
          console.log('ok lets call now ajax three');
          ajaxThree();
        $(".clickme").click();
      });

    });

function ajaxOne(){
    $.ajax({
           type: "POST",
             url: "/Test/one",
           //contentType : "text/xml",

           async :false ,
           beforeSend: function () {
               continuar =true;
                 positionNumber++;
               console.log('CALLING POSITION: '+positionNumber);
             console.log('Call Servlet one')
                },
             success: function(data,status,xhr){
                console.log('complete: ', JSON.parse(data));
                var statusCode = JSON.parse(data).responseCode;
                console.log('satusCode: ', statusCode);
                if (statusCode) {
                    ajaxTwo(statusCode);
                }
                                      },
                error: function(xhr, status, error){
                  alert("Error!" + xhr.status);
                         }

           });

}

    function ajaxTwo(){
        var text;
        $.ajax({
               type: "POST",
                 url: "/Test/two",
               //contentType : "text/xml",
               async :false ,
               beforeSend: function () {
                 console.log('Call Servlet two')
                    },
                 success: function(data,status,xhr){
                    console.log(data);
                    text = data;

                                          },
                    error: function(xhr, status, error){
                      alert("Error!" + xhr.status);
                             },
                         complete: function(){
                             console.log('finish Call Servlet two')

                            if(parseInt(text)==2){
                                console.error('LLAMARE A LA MODAL');
                                   $('#myModal').modal('show')   ;
                                   continuar = false;
                            }else{
                                ajaxFour();
                            }
                            }

               });

    }

    function ajaxThree(){
        $.ajax({
               type: "POST",
                 url: "/Test/three",
               //contentType : "text/xml",
               async :false ,
               beforeSend: function () {
                 console.log('Call Servlet three')
                    },
                 success: function(data,status,xhr){
                    console.log(data);

                                          },
                    error: function(xhr, status, error){
                      alert("Error!" + xhr.status);
                             },
                         complete: function(){
                             console.log('finish Call Servlet three')
                                                            console.error('CERRARE A LA MODALA Y CONTINUARE');
                             $('#myModal').modal('hide')   ;
                             ajaxFour();
                             continuar = true;
                            }

               });

    }

    function ajaxFour(){
        $.ajax({
               type: "POST",
                 url: "/Test/four",
               //contentType : "text/xml",
               async :false ,
               beforeSend: function () {
                 console.log('Call Servlet four')
                    },
                 success: function(data,status,xhr){
                    console.log(data);

                                          },
                    error: function(xhr, status, error){
                      alert("Error!" + xhr.status);
                             },
                         complete: function(){
                             console.log('finish Call Servlet four')
                            }

               });

    }
});
</script>

As i Said, i neded to show a modal and then continue, well i solve it in this way and now it's working fine for me =) and do not forget use async :false , in order to make a petition by petition


来源: stackexchange

问:
Is there a Rails Gem for the Microsoft Cognitive Services Image Search API - V5?
I'm looking to use Bing's APIs to perform an image search. It seems the best image search option available is MSFT's Cognitive Services Image Search API - V5

https://dev.cognitive.microsoft.com/docs/services/56b43f0ccf5ff8098cef3808/operations/571fab09dbe2d933e891028f

Is there a Rails Gem available to interact with this API so it's easier?

答: https://rubygems.org/gems/cognitivebing/versions/0.2.1 works with the new Cognitive API.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Center text with images on the left and right
Im trying to create a small navigation using jquery and bootstrap. Im a bit stuck with aligning the images

i have 2 arrow images onto my left and right with the title in the center.

Below is my code

```<code><div class="row" style="text-align:center">
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_left_48px-128.png" style="float:left">
   <h2>Heading name or title</h2>
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_right_48px-128.png">
</div>
</code>```

i did manage to set some margins and paddings and get it working but when the title gets longer the layout breaks also it doesnt work property on responsive views.

Can someone please suggest me a proper way to do this?

Thanks

答:
If you have not any other css, This is not what you want, You can use flex:

```<code>.row {
   display: flex;
   justify-content: center;
}
</code>```

And remove the float: left from the image.

Also there is no need to text-align:center any more.

Body:
Im trying to create a small navigation using jquery and bootstrap. Im a bit stuck with aligning the images

i have 2 arrow images onto my left and right with the title in the center.

Below is my code

Heading name or title

i did manage to set some margins and paddings and get it working but when the title gets longer the layout breaks also it doesnt work property on responsive views.

Can someone please suggest me a proper way to do this?

Thanks

Body:
If you have not any other css, This is not what you want, You can use flex:

.row {
   display: flex;
   justify-content: center;
}

And remove the float: left from the image.

Also there is no need to text-align:center any more.


问:
Retrofit 1.9 with Proguard
I am using following libs in my project -

```<code>compile 'com.squareup.retrofit:retrofit:1.9.0'
</code>```

But when I am using Proguard, my app crashes with following error

```<code> Fatal Exception: java.lang.IllegalArgumentException: d.a: Last parameter must be of type Callback<X> or Callback<? super X>.
           at retrofit.RestMethodInfo.methodError(Unknown Source)
           at retrofit.RestMethodInfo.parseResponseType(Unknown Source)
           at retrofit.RestMethodInfo.(Unknown Source)
           at retrofit.RestAdapter.create(Unknown Source)
           at retrofit.RestAdapter$RestHandler.invoke(Unknown Source)
           at java.lang.reflect.Proxy.invoke(Proxy.java:393)
           at $Proxy2.a(Unknown Source)
           at in.wishup.assistant.activities.SplashActivity.fetchOneTouchDetails(Unknown Source)
           at in.wishup.assistant.activities.SplashActivity$1.done(Unknown Source)
           at in.wishup.assistant.activities.SplashActivity$1.done(Unknown Source)
           at com.parse.ParseTaskUtils$2$1.run(Unknown Source)
           at android.os.Handler.handleCallback(Handler.java:739)
           at android.os.Handler.dispatchMessage(Handler.java:95)
           at android.os.Looper.loop(Looper.java:148)
           at android.app.ActivityThread.main(ActivityThread.java:5417)
           at java.lang.reflect.Method.invoke(Method.java)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

I think Retrofit's Asynchronus calls doesn't work with Proguard. Has anybody faced similiar issue? I tried many links but nothing worked.

```<code>##proguard-rules.pro##

-keep class com.google.android.gms.* { *; } <br>  -keep class * extends android.app.Activity  <br>  -keepclassmembers class ** { <br>
     @com.squareup.otto.Subscribe public *;<br>
     @com.squareup.otto.Produce public *;<br>  }<br>  -keepnames class com.levelup.http.okhttp.** { *; }<br>  -keepnames interface com.levelup.http.okhttp.** { *; }<br>  -keepnames class com.squareup.okhttp.** { *; }<br>  -keepnames interface com.squareup.okhttp.** { *; }<br>

 -dontwarn com.squareup.okhttp.internal.http.*<br>
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement<br>

 -keepattributes Signature<br>
 -keepattributes *Annotation*<br>

 -dontwarn rx.**<br>
 -keep class com.google.gson.** { *; }<br>
 -keep class com.google.inject.* { *; }<br>
 -keep class org.apache.http.* { *; }<br>
 -keep class org.apache.james.mime4j.* { *; }<br>
 -keep class javax.inject.* { *; }<br>
 -keep class retrofit.* { *; }<br>
 -keep class sun.misc.Unsafe { *; }<br>
 -keep class in.wishup.assistant.testobfuscation.** { *; }<br>  -keep class retrofit.** { *; }<br>  -keepclasseswithmembers class * {<br>
     @retrofit.http.* <methods>;<br>  }<br>

 -keep class com.parse.* { *; }<br>  -dontwarn com.parse.*<br>

 -dontwarn retrofit.appengine.**<br>

 -keep class com.package.name.models.** { *; }<br>  -keepclassmembers class com.package.name.models.** { *; } <br>
</code>```

答:
Try this: https://github.com/krschultz/android-proguard-snippets/blob/master/libraries/proguard-square-retrofit.pro

If in your rest service interface you use methods with Callback
  argument.

```<code>-keepattributes Exceptions
</code>```

Title: Retrofit 1.9 with Proguard

Body:
I am using following libs in my project -

compile 'com.squareup.retrofit:retrofit:1.9.0'

But when I am using Proguard, my app crashes with following error

 Fatal Exception: java.lang.IllegalArgumentException: d.a: Last parameter must be of type Callback<X> or Callback<? super X>.
           at retrofit.RestMethodInfo.methodError(Unknown Source)
           at retrofit.RestMethodInfo.parseResponseType(Unknown Source)
           at retrofit.RestMethodInfo.(Unknown Source)
           at retrofit.RestAdapter.create(Unknown Source)
           at retrofit.RestAdapter$RestHandler.invoke(Unknown Source)
           at java.lang.reflect.Proxy.invoke(Proxy.java:393)
           at $Proxy2.a(Unknown Source)
           at in.wishup.assistant.activities.SplashActivity.fetchOneTouchDetails(Unknown Source)
           at in.wishup.assistant.activities.SplashActivity$1.done(Unknown Source)
           at in.wishup.assistant.activities.SplashActivity$1.done(Unknown Source)
           at com.parse.ParseTaskUtils$2$1.run(Unknown Source)
           at android.os.Handler.handleCallback(Handler.java:739)
           at android.os.Handler.dispatchMessage(Handler.java:95)
           at android.os.Looper.loop(Looper.java:148)
           at android.app.ActivityThread.main(ActivityThread.java:5417)
           at java.lang.reflect.Method.invoke(Method.java)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I think Retrofit's Asynchronus calls doesn't work with Proguard. Has anybody faced similiar issue? I tried many links but nothing worked.

##proguard-rules.pro##

-keep class com.google.android.gms.* { *; }
  -keep class * extends android.app.Activity
  -keepclassmembers class ** {

     @com.squareup.otto.Subscribe public *;

     @com.squareup.otto.Produce public *;
  }
  -keepnames class com.levelup.http.okhttp.** { *; }
  -keepnames interface com.levelup.http.okhttp.** { *; }
  -keepnames class com.squareup.okhttp.** { *; }
  -keepnames interface com.squareup.okhttp.** { *; }

 -dontwarn com.squareup.okhttp.internal.http.*

 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

 -keepattributes Signature

 -keepattributes *Annotation*

 -dontwarn rx.**

 -keep class com.google.gson.** { *; }

 -keep class com.google.inject.* { *; }

 -keep class org.apache.http.* { *; }

 -keep class org.apache.james.mime4j.* { *; }

 -keep class javax.inject.* { *; }

 -keep class retrofit.* { *; }

 -keep class sun.misc.Unsafe { *; }

 -keep class in.wishup.assistant.testobfuscation.** { *; }
  -keep class retrofit.** { *; }
  -keepclasseswithmembers class * {

     @retrofit.http.* <methods>;
  }

 -keep class com.parse.* { *; }
  -dontwarn com.parse.*

 -dontwarn retrofit.appengine.**

 -keep class com.package.name.models.** { *; }
  -keepclassmembers class com.package.name.models.** { *; }

Body:
Try this: https://github.com/krschultz/android-proguard-snippets/blob/master/libraries/proguard-square-retrofit.pro

If in your rest service interface you use methods with Callback
  argument.

-keepattributes Exceptions


问:
how to import c code to TwinCAT
I am quite new to TwinCAT 3.I am trying to import a C code from Dymola to TwinCAT 3.I have gone through BECKHOFF manual but it didn't help much.

It would be grateful,if you could help me.

答:
Ok, i understand. Beckhoff place restrictions on both how the code is put together and how much of the language / frameworks you can use. You can't use third party dlls either (so the wrapper idea is out). You can import modules that have been put together in the TwinCAT way.

To start with, you will need to port your code into TwinCAT C++ directly, following the method of putting modules together, as per the instructions you followed. How much you'll actually need to change depends on the complexity of the c code, of course. A lot is syntactically identical. You can Google "compile c code for c++" for the main differences.

I'm no expert on the c++ bit of TC3, but this is my understanding. All the best with it!

LazzMaTazz

Title: how to import c code to TwinCAT


问:
android dialogFragment "sometimes" not showing webview
I have a DialogFragment with a WebView inside it. If the webview does not load the page fast enough, the DialogFragment will shrink completely and not show the webview. Otherwise, if the loading was fast, the WebView is shown.</p>

答:
I tried in two devices.

In first device Nexus 6 worked like say David "I found the solution by myself. If you use LinearLayout as the root view for your DialogFragment this will happen, changing it to FrameLayout resolved the problem. I do not understand why, but it works". But i tried in second device (Galaxy Prime) and surprise, not worked. After tried make setVisible GONE WebView in my WebViewClient inside callback onPageStarted() and after setVisible VISIBLE inside callback onPageFinished() and worked for my.

public class MyWebClient extends WebViewClient {

    private static final String LOG_CAT = "NetPayWebClient";

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        Log.e(LOG_CAT, "onPageStarted(): " + url);
        view.setVisibility(View.GONE);
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        Log.e(LOG_CAT, "onPageFinished(): " + url);
        view.setVisibility(View.VISIBLE);
        super.onPageFinished(view, url);
    }

}```


问:
Multiline expanded title in CollapsingToolbarLayout Android?
How it is possible to make multiline title in CollapsingToolbarLayout like..
whatsapp

My XML file

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="16dp"
            app:expandedTitleMarginStart="16dp"
            app:expandedTitleTextAppearance="@style/HeaderTitleStyle"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

                    <ImageView
                        android:id="@+id/cover_image"
                        android:layout_width="match_parent"                             android:layout_height="@dimen/detail_backdrop_height"
                        android:background="@color/white"
                        android:fitsSystemWindows="true"
                        android:scaleType="fitXY"
                        android:src="@drawable/default_clg_image"
                        app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

expandedTitleTextAppearance

```<code>app:expandedTitleTextAppearance="@style/HeaderTitleStyle"
</code>```

This is my style.xml

```<code><style name="HeaderTitleStyle" parent="@android:style/TextAppearance">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:textSize">20sp</item>
    <item name="android:singleLine">false</item>
</style>
</code>```

答:
A simpler approach could be add a custom layout to your Collapsing toolbar and pin it when collapsing, this could be the final output:

Please take a look on my previews answer about this to see the full code

Body:
How it is possible to make multiline title in CollapsingToolbarLayout like..
whatsapp

My XML file

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/detail_backdrop_height"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="16dp"
            app:expandedTitleMarginStart="16dp"
            app:expandedTitleTextAppearance="@style/HeaderTitleStyle"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

                    <ImageView
                        android:id="@+id/cover_image"
                        android:layout_width="match_parent"                             android:layout_height="@dimen/detail_backdrop_height"
                        android:background="@color/white"
                        android:fitsSystemWindows="true"
                        android:scaleType="fitXY"
                        android:src="@drawable/default_clg_image"
                        app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

expandedTitleTextAppearance

app:expandedTitleTextAppearance="@style/HeaderTitleStyle"

This is my style.xml


问:
PHP read first item in object array
I have my code in PHP which is returning this Array of data:

```<code>GoCardlessPro\Core\ListResponse Object
(
    [records] => Array
        (
            [0] => GoCardlessPro\Resources\Mandate Object
                (
                    [model_name:protected] => Mandate
                    [created_at:protected] => 2017-04-01T16:49:09.642Z
                    [id:protected] => ID001
                    [links:protected] => stdClass Object
                        (
                            [customer_bank_account] => CB001
                            [creditor] => CR001
                            [customer] => CU001
                        )

                    [metadata:protected] => stdClass Object
                        (
                        )

                    [next_possible_charge_date:protected] => 2017-04-06
                    [payments_require_approval:protected] =>
                    [reference:protected] => RE001
                    [scheme:protected] => bacs
                    [status:protected] => active
                    [data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
                        (
                            [id] => 123
                            [created_at] => 2017-04-01T16:49:09.642Z
                            [reference] => RE001
                            [status] => active
                            [scheme] => bacs
                            [next_possible_charge_date] => 2017-04-06
                            [payments_require_approval] =>
                            [metadata] => stdClass Object
                                (
                                )

                            [links] => stdClass Object
                                (
                                    [customer_bank_account] => 001
                                    [creditor] => CR001
                                    [customer] => CU001
                                )

                        )

                    [api_response] =>
                )

        )
)
</code>```

I want to be able to read the ID of the first item in therecords array.

This data is contained inside a variable called $GC_Mandate;

I have tried these:

```<code>echo $GC_Mandate->records->{0}->id;

echo $GC_Mandate->records->0->id;

echo $GC_Mandate->records->[0]->id;

$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;
</code>```

But none will return the data

Title: PHP read first item in object array

Body:
I have my code in PHP which is returning this Array of data:

GoCardlessPro\Core\ListResponse Object
(
    [records] => Array
        (
            [0] => GoCardlessPro\Resources\Mandate Object
                (
                    [model_name:protected] => Mandate
                    [created_at:protected] => 2017-04-01T16:49:09.642Z
                    [id:protected] => ID001
                    [links:protected] => stdClass Object
                        (
                            [customer_bank_account] => CB001
                            [creditor] => CR001
                            [customer] => CU001
                        )

                    [metadata:protected] => stdClass Object
                        (
                        )

                    [next_possible_charge_date:protected] => 2017-04-06
                    [payments_require_approval:protected] =>
                    [reference:protected] => RE001
                    [scheme:protected] => bacs
                    [status:protected] => active
                    [data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
                        (
                            [id] => 123
                            [created_at] => 2017-04-01T16:49:09.642Z
                            [reference] => RE001
                            [status] => active
                            [scheme] => bacs
                            [next_possible_charge_date] => 2017-04-06
                            [payments_require_approval] =>
                            [metadata] => stdClass Object
                                (
                                )

                            [links] => stdClass Object
                                (
                                    [customer_bank_account] => 001
                                    [creditor] => CR001
                                    [customer] => CU001
                                )

                        )

                    [api_response] =>
                )

        )
)

I want to be able to read the ID of the first item in therecords array.

This data is contained inside a variable called $GC_Mandate;

I have tried these:

echo $GC_Mandate->records->{0}->id;

echo $GC_Mandate->records->0->id;

echo $GC_Mandate->records->[0]->id;

$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;

But none will return the data

Body: Try $GC_Mandate->records[0]->__get('id')


问:
Getting Game Score (Sub String) From String C#
What is the best way to extract the score from a string variable. For example extract 2-1 from "Match One 2-1 To Red Team".

I was going to add special characters around the score and do something like this

```<code>string in = "Match One |2-1| To Red Team";
string out = input.Split('|', '|')[1];
</code>```

But that would involve me adding two characters to hundreds of rows on a CSV file.

Could I split on the dash. The extract numbers into an array somehow?

```<code>scoreString.Split('-');
</code>```

Any help is appreciated.

EDIT: I have wrote this and it works, but doesnt seem very clean.

```<code>var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;
</code>```

答:
```<code>var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;
</code>```

<p>The above code works for me so Im going to mark this as the answer. Thanks to those that helped. </p>

Body:
What is the best way to extract the score from a string variable. For example extract 2-1 from "Match One 2-1 To Red Team".

I was going to add special characters around the score and do something like this

string in = "Match One |2-1| To Red Team";
string out = input.Split('|', '|')[1];

But that would involve me adding two characters to hundreds of rows on a CSV file.

Could I split on the dash. The extract numbers into an array somehow?

scoreString.Split('-');

Any help is appreciated.

EDIT: I have wrote this and it works, but doesnt seem very clean.

var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;

Body:
var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;

The above code works for me so Im going to mark this as the answer. Thanks to those that helped.


问:
Downloading dlib on Raspberry Pi, pip keeps outputting error when I try?
```<code>Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dhth2xud/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install
--record /tmp/pip-7p82qhms-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-dhth2xud/dlib/
</code>```

This is the error I keep getting, when simply running sudo pip3 install dlib.

答:
I ran into the same error. Turns out you need to install those prerequisits on the Raspberry Pi:

```<code>sudo apt-get install build-essential cmake
sudo apt-get install libgtk-3-dev
sudo apt-get install libboost-all-dev
</code>```

I read that it helps to free up RAM by disabling GUI start (sudo raspi-config and under Boot options change from GUI to Console) but that alone didn't help.
I then followed the Ubuntu installation instructions here (the 3 commands above) and then sudo pip3 install dlib stopped showing this error and started installation.

Body:
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dhth2xud/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install
--record /tmp/pip-7p82qhms-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-dhth2xud/dlib/

This is the error I keep getting, when simply running sudo pip3 install dlib.

Body:
I ran into the same error. Turns out you need to install those prerequisits on the Raspberry Pi:

sudo apt-get install build-essential cmake
sudo apt-get install libgtk-3-dev
sudo apt-get install libboost-all-dev

I read that it helps to free up RAM by disabling GUI start (sudo raspi-config and under Boot options change from GUI to Console) but that alone didn't help.
I then followed the Ubuntu installation instructions here (the 3 commands above) and then sudo pip3 install dlib stopped showing this error and started installation.


问:
How to get whole file of external css and js?
Like in subject. I can download whole HTML of a page but I need to download external CSS and JS files too (so I can modify/check them). Do I need to use some scrappers? When page is loaded in a browser it automatically load all css and js - I need something similar. Lets suppose I have access to server - apache or node - do I need to download all css/js files one by one? Any ideas how to get the code of all external css/js files?</p>

答: Scrapers like cherio and jsdom are not enought, you can try phantom.js but it's heavy. Easiest way is to just to request (http or request) each css/js file.</p>


问:
Posting FROM Node's hosted router to a remote API (not TO Node's hosted API)
Wanting a Node router that POST Json to some remote API?

I put a lot of effort into this issue this morning so I wanted to share this by offering some comprehensive examples for your benefit.

In each example the router has a GET method that when called, POSTS back to the same router.  I'm also showing, very clearly, how to send AND how to access the received data.

In Node.js, in a router, you might sometime what to post from the router to some remote api.

--- using npm install needle -save --- the file routes/nee.js ---

```<code>var express = require('express');
var router = express.Router();
var needle = require('needle');

router.get('/', function (req, resp) {
    var dat = { theGreatest: 'ChuckBerry' };
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    needle.post(lookbackURL, dat, { json: true });
    resp.redirect('/');
});

router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});

module.exports = router;
</code>```

--- using npm install request -save --- the file routes/req.js ---

```<code>var express = require('express');
var router = express.Router();
var request = require('request');

router.get('/', function (req, resp) {
    var dat = { theGreatest: 'ChuckBerry' };
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    request.post(lookbackURL, { json: dat });
    resp.redirect('/');
});

router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});

module.exports = router;
</code>```

--- using Node's very own http.request() -- the file routes/nodehttp.js ---

--- When you only want to POST some Json data make your life simpler by instead doing a PUT of the content-type=application/json -----

```<code>var express = require('express');
var router = express.Router();
var http = require('http');

router.get('/', function (req, resp) {

    var hst = req.headers.host.split(':');
    var dat = { theGreatest: 'ChuckBerry' };
    var bdy = JSON.stringify(dat);  // you have to take care of this for yourself
    var options = { host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'  //PUT!
        , headers: { 'Content-Type': 'application/json' }
    };

    var r = http.request(options);
    r.write(bdy);
    r.end();
    resp.sendStatus(200);
});

router.put('/', function (req, resp) { // PUT. it's a PUT not a POST
    console.log('body[\'theGreatest\']', req.body['theGreatest']); // But here you DON'T have to parse it for yourself.
                 // ^ I'm happy for that even if I am feeling the loss of symmetry.
                 // ^^ At the same this is why your life is easier in a PUT instead of a POST.
    resp.sendStatus(200);
});

module.exports = router;
</code>```

And perhaps the easiest of all

--- using npm install requestify -save --- the file routes/rify.js ---

```<code>var express = require('express');
var router = express.Router();
var requestify = require('requestify');

router.get('/', function (req, resp) {
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    requestify.post(lookbackURL, {
        theGreatest: 'ChuckBerry'
    })
    .then(function (res) {
        //res.getBody(); // JSON parsed or XML object
        //res.body; // or get the raw
        res.redirect('/');
    });
});

router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});

module.exports = router;
</code>```

Enjoy & I hope these more comprehensive demonstrations help you too.

答:
Looks good.  Quite a bit of effort documenting the different options.

A little later I'm going to add a Requestify.js example.  Stay tuned and look for it above

Body:
Wanting a Node router that POST Json to some remote API?

I put a lot of effort into this issue this morning so I wanted to share this by offering some comprehensive examples for your benefit.

In each example the router has a GET method that when called, POSTS back to the same router.  I'm also showing, very clearly, how to send AND how to access the received data.

In Node.js, in a router, you might sometime what to post from the router to some remote api.

--- using npm install needle -save --- the file routes/nee.js ---

var express = require('express');
var router = express.Router();
var needle = require('needle');

router.get('/', function (req, resp) {
    var dat = { theGreatest: 'ChuckBerry' };
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    needle.post(lookbackURL, dat, { json: true });
    resp.redirect('/');
});

router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});

module.exports = router;

--- using npm install request -save --- the file routes/req.js ---

var express = require('express');
var router = express.Router();
var request = require('request');

router.get('/', function (req, resp) {
    var dat = { theGreatest: 'ChuckBerry' };
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    request.post(lookbackURL, { json: dat });
    resp.redirect('/');
});

router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});

module.exports = router;

--- using Node's very own http.request() -- the file routes/nodehttp.js ---

--- When you only want to POST some Json data make your life simpler by instead doing a PUT of the content-type=application/json -----

var express = require('express');
var router = express.Router();
var http = require('http');

router.get('/', function (req, resp) {

    var hst = req.headers.host.split(':');
    var dat = { theGreatest: 'ChuckBerry' };
    var bdy = JSON.stringify(dat);  // you have to take care of this for yourself
    var options = { host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'  //PUT!
        , headers: { 'Content-Type': 'application/json' }
    };

    var r = http.request(options);
    r.write(bdy);
    r.end();
    resp.sendStatus(200);
});

router.put('/', function (req, resp) { // PUT. it's a PUT not a POST
    console.log('body[\'theGreatest\']', req.body['theGreatest']); // But here you DON'T have to parse it for yourself.
                 // ^ I'm happy for that even if I am feeling the loss of symmetry.
                 // ^^ At the same this is why your life is easier in a PUT instead of a POST.
    resp.sendStatus(200);
});

module.exports = router;

And perhaps the easiest of all

--- using npm install requestify -save --- the file routes/rify.js ---

var express = require('express');
var router = express.Router();
var requestify = require('requestify');

router.get('/', function (req, resp) {
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    requestify.post(lookbackURL, {
        theGreatest: 'ChuckBerry'
    })
    .then(function (res) {
        //res.getBody(); // JSON parsed or XML object
        //res.body; // or get the raw
        res.redirect('/');
    });
});

router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});

module.exports = router;

Enjoy & I hope these more comprehensive demonstrations help you too.


问:
How to do a tooltip on an SVG generated by Raphael
I'm doing a bit of a pedagogical exercise, converting XML to SVG with XSLT, Javascript and Raphael. I'm sure it's the hard way...but it's educational.

The problem I've run into is creating tooltips. So far, I've found three ways to do this:

The first way is to use .attr({title: "blah"{) on an object. This works, but it's not supported by Raphael officially, and the content I want to put in the tooltip might be somewhat long, which is a problem when people's OS times out the tooltip before people have finished reading it.

The second way I've found is the function here. It works OK for having a Raphael object popup when there is a mouseover, but, near as I can tell, getting a normal-looking tooltip to pop up isn't possible.

Using the jquery Tooltip plugin. This just doesn't seem to work. I can't get Raphael to add the title attribute to an object AND get this to select that title. Not sure why.

So, what I'd like to know is, what's an easy and reliable way to add tooltips to Raphael objects such that they popup when people mouseover the object, and disappear when they mouseout (but not before)?

答: One way to do this is to use a div tag on top of the Raphael paper. Then use Jquery mousevents along with fadeIn() and fadeOut(). I created an example on jsFiddle. Have a look</p>

ContentLicense: CC BY-SA 2.5


问:
Does PDO ever close persistent connections?
I switched to using PDO persistent connections. I encountered situations where MySQL (correctly) closes a connection on its end (due to inactivity) and PDO doesn't pick up on it, keeps the connection available in its cache, and from that point on - any attempt to use this connection results in a failure.

From what I've read this behavior is "by design" (to me it looks like PDO is going out of its way to not support persistent connections).

Either way, I would like to know if PDO would ever close a connection in its pool. I get it that it doesn't check the connection's state, but is there any kind of timer or periodic cleanup, configurable or hard-coded?

答:
One should not worry about the persistence of a connection.

If you are building a web page -- it should finish long before the connection times out.

If you have a long-running application that is not touching the database for huge time spans, then think about rearranging the code or closing and re-opening or discovering that it was closed and re-opening.

Note that a connection can close for any of a lot of reasons -- many related to hiccups in the network.  Therefore, your application should be ready to recover from a closed connection, regardless of how "persistent" it claims to be.

"Connection pooling" is handled at many levels -- in the client library, in the "proxy server", even in the MySQL server.  They all act differently.

Connection pooling is not all that useful.  Virtually every performance problem I have chased down did not have to do with the time it takes to [re]establish a connection.

Other RDBMS vendors have had horribly slow Connect times, leading the industry to invent connection pooling and persistent connections.  But MySQL has little need for such.

There are several timeouts that can trigger closing a connection; you are at the mercy of the DBA / SE / Cloud provider as to what values they are set to.

PDO is just one of many layers, so your question is too narrow.  I hope I have provided a broader answer.


问:
i want to remove string after colon in sql server
-- i need data like this F11.20,F13.20,F14.10 in sql server</p>

```<code>declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
select left(@S, charindex(':', @S, charindex(':', @S)+2)-2);
</code>```

答:
If the text you're extracting is always in the form of (letter, number, number, ., number, number) and there's always 3 instances of that text, then you could do this:

```<code>WITH
s1(string, ci) AS (SELECT @S, CHARINDEX(':', @S)),
s2(ci) AS (SELECT CHARINDEX(':', @S, ci+1) FROM s1),
s3(ci) AS (SELECT CHARINDEX(':', @S, ci+1) FROM s2)
SELECT
  SUBSTRING(string, s1.ci-6, 6)+','+
  SUBSTRING(string, s2.ci-6, 6)+','+
  SUBSTRING(string, s3.ci-6, 6)
FROM s1, s2, s3;
</code>```

Execution Plan:

It doesn't get any more efficient then that.

If its always the 6 characters before any instance of ":" you can grab a copy of NGrams8K and do this:

```<code>declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';

SELECT NewString = STUFF
  ((SELECT ','+SUBSTRING(@S, position-6, 6)
    FROM dbo.NGrams8k(@S, 1)
    WHERE token = ':'
    FOR XML PATH('')),1,1,'');
</code>```

Another way using NGrams8K and a variable:

```<code>declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
declare @newstring varchar(100)='';

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
declare @newstring varchar(100)='';

SELECT
  @newstring +=
    CASE @newstring WHEN '' THEN '' ELSE ',' END +SUBSTRING(@S, position-6, 6)
FROM dbo.NGrams8k(@S, 1)
WHERE token = ':';

SELECT @newstring;
</code>```

Body:
-- i need data like this F11.20,F13.20,F14.10 in sql server

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
select left(@S, charindex(':', @S, charindex(':', @S)+2)-2);

Body:
If the text you're extracting is always in the form of (letter, number, number, ., number, number) and there's always 3 instances of that text, then you could do this:

WITH
s1(string, ci) AS (SELECT @S, CHARINDEX(':', @S)),
s2(ci) AS (SELECT CHARINDEX(':', @S, ci+1) FROM s1),
s3(ci) AS (SELECT CHARINDEX(':', @S, ci+1) FROM s2)
SELECT
  SUBSTRING(string, s1.ci-6, 6)+','+
  SUBSTRING(string, s2.ci-6, 6)+','+
  SUBSTRING(string, s3.ci-6, 6)
FROM s1, s2, s3;

Execution Plan:

It doesn't get any more efficient then that.

If its always the 6 characters before any instance of ":" you can grab a copy of NGrams8K and do this:

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';

SELECT NewString = STUFF
  ((SELECT ','+SUBSTRING(@S, position-6, 6)
    FROM dbo.NGrams8k(@S, 1)
    WHERE token = ':'
    FOR XML PATH('')),1,1,'');

Another way using NGrams8K and a variable:

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
declare @newstring varchar(100)='';

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
declare @newstring varchar(100)='';

SELECT
  @newstring +=
    CASE @newstring WHEN '' THEN '' ELSE ',' END +SUBSTRING(@S, position-6, 6)
FROM dbo.NGrams8k(@S, 1)
WHERE token = ':';

SELECT @newstring;


问:
How can i make an ER Diagram for a Database which has single table in it
In my project, there are basically 3 different databases used. For example, the first database is for login sign up.

It contains only one table with one entity that is a user with two attributes that is email and password. So how can I make ER Diagram for a database having a single table and having no relationships?

答:
Simply use a rectangle for the User and two circles for email and password that are connected to the rectangle. Like the following image:

If the email is the primary key, you can underline it like the image shows.

This ER Diagram template of a Surgeon for instance has one entity as well. Of course an ER diagram is usually used to make a graphical representation of a complex database (with multiple entities, relations, etc.).


问:
MathJax : bad vertical alignment in table
When rendering math containing only letters and other symbols without ascenders (e.g. "x") inside a  tag, the text does not align on the baseline (tested with Chrome 56 and Firefox 52 on Windows 1.

Example:

```<code><html>
<head>
    <script src='https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>
    <style>
        td {border:1pt solid gray;}
        table {border-collapse: collapse;}
    </style>
</head>
<body>
<table><tr>
<td>reference</td>
<td>\(x\)</td>
<td>\(x\)x</td>
<td>\(xx\)</td>
<td>\(\cdot\)</td>
<td>\(\cdot t\)</td>
<td>\(=\)</td>
<td>\(=t\)</td>
</tr></table>
</body>
<html>
</code>```

Is there an easy way to correct this?

答:
You will get better results if you use

```<code>td {
  border:1pt solid gray;
  vertical-align: baseline;
}
</code>```

since the default vertical alignment for table cells is middle, and the mathematics produced by MathJax have tight bounding boxes, so center vertically based on those heights.

Body:
When rendering math containing only letters and other symbols without ascenders (e.g. "x") inside a  tag, the text does not align on the baseline (tested with Chrome 56 and Firefox 52 on Windows 1.

Example:

reference
\(x\)
\(x\)x
\(xx\)
\(\cdot\)
\(\cdot t\)
\(=\)
\(=t\)

Is there an easy way to correct this?

Body:
You will get better results if you use

td {
  border:1pt solid gray;
  vertical-align: baseline;
}

since the default vertical alignment for table cells is middle, and the mathematics produced by MathJax have tight bounding boxes, so center vertically based on those heights.


问:
XCODE 8.2 wrongly detects locked device
I get the "Xcode cannot launch MyApp on My iPad because the device is locked. Unlock device to continue" message upon hitting build&run on XCODE 8.2 on an Ipad Air 2 (actual device, not simulator), after "build succeeded" when the device is actually not locked. I tried doing it with locked device in order for it to detect the unlock as usual, to no avail. Clean project, nada. It is quite annoying and happens very often. Has it happened to anyone else, and does anyone know any work around? Seems to be an XCODE 8.2 bug?</p>

答:
I see it very often

Easiest solution:

```<code>Lock your device (e.g. click on side power button) and unlock again.
</code>```

Or you can restart Xcode, but this will take much more time.

Title: XCODE 8.2 wrongly detects locked device

Body:
I see it very often

Easiest solution:

Lock your device (e.g. click on side power button) and unlock again.

Or you can restart Xcode, but this will take much more time.


问:
template specialization for all iterators of std::map
I have traits class, saying:

```<code>template <class T>
struct KeyValueTraits
{
    typedef typename T::key_t key_t;
    typedef typename T::value_t value_t;
}
</code>```

Now I would like to declare specialization of this traits for all iterators of std::map

```<code>template < typename... Args >
struct KeyValueTraits<typename std::map<Args...>::iterator >
{
    typedef std::map<Args...> target_t;
    typedef typename target_t::key_type key_t;
    typedef typename target_t::mapped_type value_t;
};
</code>```

Compiler raises an error:

error C2764: 'Args': template parameter not used or deducible in partial specialization

So how to declare traits-type for all possible std::map<...>::iterator?

答:
You use variadic template parameters, so I suppose you can accept a C++11 solution.

I propose the following (not really great), based on template specialization, solution.

Take in count that the type of the key, in std::map<>, isn't key_t but key_type and that the type of the value isn't value_t but mapped_type.

```<code>#include <map>

template <typename X>
struct with_kt
 {
   template <typename Y = X>
   static constexpr bool getValue (int, typename Y::key_type * = nullptr)
    { return true; }

   static constexpr bool getValue (long)
    { return false; }

   static constexpr bool value { getValue(0) };
 };

template <typename T, bool = with_kt<T>::value>
struct KeyValueTraits;

template <typename T>
struct KeyValueTraits<T, true>
 {
   using key_t   = typename T::key_type;
   using value_t = typename T::mapped_type;
 };

template <typename T>
struct KeyValueTraits<T, false>
 {
   using pair_t  = decltype(* std::declval<T>());

   using key_t   = typename std::remove_const<
                      decltype(std::declval<pair_t>().first)>::type;
   using value_t = decltype(std::declval<pair_t>().second);
 };

using mil = std::map<int,long>;

int main()
 {
   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::iterator>::key_t
                              >::value, "!");

   static_assert(std::is_same<KeyValueTraits<mil>::value_t,
                              KeyValueTraits<mil::iterator>::value_t
                              >::value, "!!");

   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::const_iterator>::key_t
                              >::value, "!!!");

   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::reverse_iterator>::key_t
                              >::value, "!!!!");

   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::const_reverse_iterator>::key_t
                              >::value, "!!!!!");
 }
</code>```

Body:
I have traits class, saying:

template <class T>
struct KeyValueTraits
{
    typedef typename T::key_t key_t;
    typedef typename T::value_t value_t;
}

Now I would like to declare specialization of this traits for all iterators of std::map

template < typename... Args >
struct KeyValueTraits<typename std::map<Args...>::iterator >
{
    typedef std::map<Args...> target_t;
    typedef typename target_t::key_type key_t;
    typedef typename target_t::mapped_type value_t;
};

Compiler raises an error:

error C2764: 'Args': template parameter not used or deducible in partial specialization

So how to declare traits-type for all possible std::map<...>::iterator?

Body:
You use variadic template parameters, so I suppose you can accept a C++11 solution.

I propose the following (not really great), based on template specialization, solution.

Take in count that the type of the key, in std::map<>, isn't key_t but key_type and that the type of the value isn't value_t but mapped_type.

#include <map>

template <typename X>
struct with_kt
 {
   template <typename Y = X>
   static constexpr bool getValue (int, typename Y::key_type * = nullptr)
    { return true; }

   static constexpr bool getValue (long)
    { return false; }

   static constexpr bool value { getValue(0) };
 };

template <typename T, bool = with_kt<T>::value>
struct KeyValueTraits;

template <typename T>
struct KeyValueTraits<T, true>
 {
   using key_t   = typename T::key_type;
   using value_t = typename T::mapped_type;
 };

template <typename T>
struct KeyValueTraits<T, false>
 {
   using pair_t  = decltype(* std::declval<T>());

   using key_t   = typename std::remove_const<
                      decltype(std::declval<pair_t>().first)>::type;
   using value_t = decltype(std::declval<pair_t>().second);
 };

using mil = std::map<int,long>;

int main()
 {
   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::iterator>::key_t
                              >::value, "!");

   static_assert(std::is_same<KeyValueTraits<mil>::value_t,
                              KeyValueTraits<mil::iterator>::value_t
                              >::value, "!!");

   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::const_iterator>::key_t
                              >::value, "!!!");

   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::reverse_iterator>::key_t
                              >::value, "!!!!");

   static_assert(std::is_same<KeyValueTraits<mil>::key_t,
                              KeyValueTraits<mil::const_reverse_iterator>::key_t
                              >::value, "!!!!!");
 }


问:
Are there any way to set the UITableView section header color in iOS 7 directly rather creating a new UIView
UITableView's section headers are less identifiable in iOS 7. Are there any way to set the UITableView section header color in iOS 7 directly rather creating a new UIView.

Note: I found some solutions by creating a new UIView in,

```<code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
</code>```

but I really wanted to keep the Apple's properties except color. Are there any way to do it without this method.

答:
In the case of Swift 3 the way is to achieve it via UITableViewDelegate method:</p>

```<code>override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView  {
        headerView.backgroundColor = UIColor.gray
    }
}
</code>```

Body:
UITableView's section headers are less identifiable in iOS 7. Are there any way to set the UITableView section header color in iOS 7 directly rather creating a new UIView.

Note: I found some solutions by creating a new UIView in,

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

but I really wanted to keep the Apple's properties except color. Are there any way to do it without this method.

Body:
In the case of Swift 3 the way is to achieve it via UITableViewDelegate method:

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView  {
        headerView.backgroundColor = UIColor.gray
    }
}


问:
How to update and delete a Pending Intent and a Notification in android
whenever i attempt to update the notification or Intent a new one is created instead which i don't want. I think the problem is that the Intents are not being identified whenever i'm trying to update it. The link to the code is below:

https://gist.github.com/Kerron-Hutton/03799ac497128919225bbbd4efaffa25

答:
To update a PendingIntent, you should use the same REQUEST_CODE that you used before to create it.

```<code>PendingIntent pIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

To cancel/delete an existing PendingIntent, you can use PendingIntent.cancel() method.

```<code>PendingIntent.getBroadcast(context, REQUEST_CODE, intent,
                   PendingIntent.FLAG_UPDATE_CURRENT).cancel();
</code>```

To update a Notification, you can use NotificationManager.notify() method with the NOTIFICATION_ID that you want to update.

```<code>NotificationManager notificationManager= (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
</code>```

Notification id should be unique within your application. If a
  notification with the same id has already been posted by your
  application and has not yet been canceled, it will be replaced by the
  updated information.

To cancel/remove an existing Notification, use NotificationManager.Cancel() method with the NOTIFICATION_ID that you want to cancel.

```<code>notificationManager.cancel(NOTIFICATION_ID);
</code>```

Hope this will help~

Body:
To update a PendingIntent, you should use the same REQUEST_CODE that you used before to create it.

PendingIntent pIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

To cancel/delete an existing PendingIntent, you can use PendingIntent.cancel() method.

PendingIntent.getBroadcast(context, REQUEST_CODE, intent,
                   PendingIntent.FLAG_UPDATE_CURRENT).cancel();

To update a Notification, you can use NotificationManager.notify() method with the NOTIFICATION_ID that you want to update.

NotificationManager notificationManager= (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);

Notification id should be unique within your application. If a
  notification with the same id has already been posted by your
  application and has not yet been canceled, it will be replaced by the
  updated information.

To cancel/remove an existing Notification, use NotificationManager.Cancel() method with the NOTIFICATION_ID that you want to cancel.

notificationManager.cancel(NOTIFICATION_ID);

Hope this will help~


问:
Table not reload data until Scroll
I am calling webservice call . They load data in table until i am scrolling. I want reload data when response come . I am newer in Swift 2 Please help any help would be apperciated.

Here is my code:

```<code>  let url : String = String(format: "http://api.nytimes.com/svc/news/v3/content/nyt/all/720.json?api-key=%@",apiKey)

   t url1: NSURL = NSURL(string: url)!

  let session = NSURLSession.sharedSession()

    let task1 = session.dataTaskWithURL(url1, completionHandler: {
        (data, response, error) -> Void in

        do {
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary

            self.dict = jsonData;

            self.array1 = (self.dict.objectForKey("results") as? NSMutableArray)!
            print(self.array1)
        self.table.reloadData()

        } catch {
        }
    })
    task1.resume()

  extension ViewController1: UITableViewDelegate, UITableViewDataSource {

       }                      func tableView(tView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return self.array1.count
        }

        func tableView(tView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let identifier = "CustumCell"
            var cell: CustumCell! = tView.dequeueReusableCellWithIdentifier(identifier) as? CustumCell
            if cell == nil {
                var nib:Array = NSBundle.mainBundle().loadNibNamed("CustumCell", owner: self, options: nil)
                cell = nib[0] as? CustumCell
            }

                       cell.label.text = self.array1.objectAtIndex(indexPath.row).objectForKey("abstract") as? String

            return cell
        }

    }
</code>```

答:
What MirekE said, except updated for Swift 3, Xcode 8.2:</p>

```<code>DispatchQueue.main.async {
    self.table.reloadData()
}
</code>```

Title: Table not reload data until Scroll

Body:
I am calling webservice call . They load data in table until i am scrolling. I want reload data when response come . I am newer in Swift 2 Please help any help would be apperciated.

Here is my code:

  let url : String = String(format: "http://api.nytimes.com/svc/news/v3/content/nyt/all/720.json?api-key=%@",apiKey)

   t url1: NSURL = NSURL(string: url)!

  let session = NSURLSession.sharedSession()

    let task1 = session.dataTaskWithURL(url1, completionHandler: {
        (data, response, error) -> Void in

        do {
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary

            self.dict = jsonData;

            self.array1 = (self.dict.objectForKey("results") as? NSMutableArray)!
            print(self.array1)
        self.table.reloadData()

        } catch {
        }
    })
    task1.resume()

  extension ViewController1: UITableViewDelegate, UITableViewDataSource {

       }                      func tableView(tView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return self.array1.count
        }

        func tableView(tView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let identifier = "CustumCell"
            var cell: CustumCell! = tView.dequeueReusableCellWithIdentifier(identifier) as? CustumCell
            if cell == nil {
                var nib:Array = NSBundle.mainBundle().loadNibNamed("CustumCell", owner: self, options: nil)
                cell = nib[0] as? CustumCell
            }

                       cell.label.text = self.array1.objectAtIndex(indexPath.row).objectForKey("abstract") as? String

            return cell
        }

    }

Body:
What MirekE said, except updated for Swift 3, Xcode 8.2:

DispatchQueue.main.async {
    self.table.reloadData()
}


问:
Reverting a specific old commit
Hi I have a repository on Bitbucket. I am working with a partner on a project and he pushed some updates few commits ago, working on a file, I realized that he did wrong code. I want to revert that commit, particularly that file only so I can get back code of that file only. cartitems.blade.php

Is this possible?

Attached is the image of SourceTree tool. Uncommited changes are my new changes. I want to keep these and recover that specific file only.

答:
You can use git revert to reverse the effects for a specific commit and create a new commit with the changes reverted.

In this instance

```<code>git revert 797832c
</code>```

will automatically create a commit with the changes reversed.

Title: Reverting a specific old commit

Body:
You can use git revert to reverse the effects for a specific commit and create a new commit with the changes reverted.

In this instance

git revert 797832c

will automatically create a commit with the changes reversed.


答:
Courtesy code from https://regexone.com/references/csharp modified to suit your purpose.</p>

```<code>var s = "Match One 2-1 To Red Team";
s = "Strongholds on Eden 100-95 Supremacy";

string pattern = @"(\d+)-(\d+)";
MatchCollection matches = Regex.Matches(s, pattern);

// This will print the number of matches
Console.WriteLine("{0} matches", matches.Count);

foreach (Match match in matches) {
    GroupCollection data = match.Groups;
    // This will print the number of captured groups in this match
    Console.WriteLine("{0} groups captured in {1}", data.Count, match.Value);

    Console.WriteLine("score: " + data[1] + ", score2: " + data[2]);

    // Each Group in the collection also has an Index and Length member,
    // which stores where in the input string that the group was found.
    Console.WriteLine("score found at[{0}, {1})",
        data[1].Index,
        data[1].Index + data[1].Length);
}
</code>```

Title: Getting Game Score (Sub String) From String C#

Body:
What is the best way to extract the score from a string variable. For example extract 2-1 from "Match One 2-1 To Red Team".

I was going to add special characters around the score and do something like this

string in = "Match One |2-1| To Red Team";
string out = input.Split('|', '|')[1];

But that would involve me adding two characters to hundreds of rows on a CSV file.

Could I split on the dash. The extract numbers into an array somehow?

scoreString.Split('-');

Any help is appreciated.

EDIT: I have wrote this and it works, but doesnt seem very clean.

var splitScores = values[0].ToLower().Trim().Split('-');

var leftScore  = Regex.Match(splitScores[0], @"\d+").Value;
var rightScore = Regex.Match(splitScores[1], @"\d+").Value;

Body:
Courtesy code from https://regexone.com/references/csharp modified to suit your purpose.

var s = "Match One 2-1 To Red Team";
s = "Strongholds on Eden 100-95 Supremacy";

string pattern = @"(\d+)-(\d+)";
MatchCollection matches = Regex.Matches(s, pattern);

// This will print the number of matches
Console.WriteLine("{0} matches", matches.Count);

foreach (Match match in matches) {
    GroupCollection data = match.Groups;
    // This will print the number of captured groups in this match
    Console.WriteLine("{0} groups captured in {1}", data.Count, match.Value);

    Console.WriteLine("score: " + data[1] + ", score2: " + data[2]);

    // Each Group in the collection also has an Index and Length member,
    // which stores where in the input string that the group was found.
    Console.WriteLine("score found at[{0}, {1})",
        data[1].Index,
        data[1].Index + data[1].Length);
}


问:
Wordpress wp_list_pages: list parent page siblings
I'm trying to get this working for quite a while now. I get close but can't find a working solution.

My page structure is like this:

```<code>1 FIRST LEVEL
  2 SECOND LEVEL
    3 THIRD LEVEL
      4 CAR
         5 SUV
         5 MINIVAN
         5 FULLSIZE
      4 MOTORCYCLE
      4 BICYCLE
  2 SECOND LEVEL
  2 SECOND LEVEL
1 FIRST LEVEL
</code>```

I need a wp_list_pages statement that does the following: on 4th and 5th level pages (and ONLY on those) the navigation lists all 4th level pages.

(When i'm on page "CAR" the navigation should be CAR,MOTORCYCLE,BICYCLE. And also when i'm on page MINIVAN the navigation should be CAR,MOTORCYCLE,BICYCLE.)

Thank you very much for any help!

答:
```<code>$ancestors = get_post_ancestors($post);
if (count($ancestors) >= 3) {
    $parent = $ancestors[2]; // third level page ID
    wp_list_pages('depth=1&child_of=' . $parent);
}
</code>```

Feel free to ask if you're unsure of anything :)

Body:
I'm trying to get this working for quite a while now. I get close but can't find a working solution.

My page structure is like this:

1 FIRST LEVEL
  2 SECOND LEVEL
    3 THIRD LEVEL
      4 CAR
         5 SUV
         5 MINIVAN
         5 FULLSIZE
      4 MOTORCYCLE
      4 BICYCLE
  2 SECOND LEVEL
  2 SECOND LEVEL
1 FIRST LEVEL

I need a wp_list_pages statement that does the following: on 4th and 5th level pages (and ONLY on those) the navigation lists all 4th level pages.

(When i'm on page "CAR" the navigation should be CAR,MOTORCYCLE,BICYCLE. And also when i'm on page MINIVAN the navigation should be CAR,MOTORCYCLE,BICYCLE.)

Thank you very much for any help!

Body:
$ancestors = get_post_ancestors($post);
if (count($ancestors) >= 3) {
    $parent = $ancestors[2]; // third level page ID
    wp_list_pages('depth=1&child_of=' . $parent);
}

Feel free to ask if you're unsure of anything :)


问:
loop break not working inside switch block on array of strings
Please refer the below code in which loop break does not work inside the switch block, can you help?</p>

```<code>    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    //For loop is not breaking after getting the correct value
    for (int t = 0; t < Books.length; t++) {
      switch (Books[t]) {
        case "Harry Potter":
             System.out.println("Getting from switch case " + t + " " + Books[t]);
            break;
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
    }
</code>```

答:
Well, that break will only break out of the switch statement. You can try using a labeled break, e.g.

```<code>loop:
for (int t = 0; t < Books.length; t++ ) {
    // ...
    case:
        // ...
        break loop;
</code>```

Or, you could put the loop in its own method instead and use a return statement.

Body:
Please refer the below code in which loop break does not work inside the switch block, can you help?

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    //For loop is not breaking after getting the correct value
    for (int t = 0; t < Books.length; t++) {
      switch (Books[t]) {
        case "Harry Potter":
             System.out.println("Getting from switch case " + t + " " + Books[t]);
            break;
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
    }

Body:
Well, that break will only break out of the switch statement. You can try using a labeled break, e.g.

loop:
for (int t = 0; t < Books.length; t++ ) {
    // ...
    case:
        // ...
        break loop;

Or, you could put the loop in its own method instead and use a return statement.


问:
Xcode "Device Locked" When iPhone is unlocked
When I tried to build and run, Xcode said my device was locked. I looked at my iPhone, and it's not locked at all. How do I fix this?</p>

答:
Solution: Switch target device to some other (e.g. Generic iOS Device),

then unlock you physical device and switch back to it again.


问:
Type 'IntentHandler' does not conform to protocol 'INStartAudioCallIntentHandling'
I’m using INStartAudioCallIntentHandling in swift 2.3 and I’m getting this error :

```<code>Type ‘IntentHandler’ does not conform to protocol ‘INStartAudioCallIntentHandling’
</code>```

I’m using Xcode 8.2.1. I put the func handle(startAudioCall intent: INStartAudioCallIntent, completion: (INStartAudioCallIntentResponse) -> Void) method  into the class.Why i'm getting this error. Please help me.

答:
you should probably also add

```<code>func confirm(startAudioCall: INStartAudioCallIntent, completion: (INStartAudioCallIntentResponse) -> Void)
</code>```

and

```<code>func resolveContacts(forStartAudioCall: INStartAudioCallIntent, with: ([INPersonResolutionResult]) -> Void)
</code>```

Use the methods of the INStartAudioCallIntentHandling protocol to
  resolve, confirm, and handle requests to start an audio-only call with
  the designated users. Adopt this protocol in an object of your Intents
  extension that is capable of validating the call information.

source

Body:
I’m using INStartAudioCallIntentHandling in swift 2.3 and I’m getting this error :

Type ‘IntentHandler’ does not conform to protocol ‘INStartAudioCallIntentHandling’

I’m using Xcode 8.2.1. I put the func handle(startAudioCall intent: INStartAudioCallIntent, completion: (INStartAudioCallIntentResponse) -> Void) method  into the class.Why i'm getting this error. Please help me.

Body:
you should probably also add

func confirm(startAudioCall: INStartAudioCallIntent, completion: (INStartAudioCallIntentResponse) -> Void)

and

func resolveContacts(forStartAudioCall: INStartAudioCallIntent, with: ([INPersonResolutionResult]) -> Void)

Use the methods of the INStartAudioCallIntentHandling protocol to
  resolve, confirm, and handle requests to start an audio-only call with
  the designated users. Adopt this protocol in an object of your Intents
  extension that is capable of validating the call information.

source