问:
Session Tracking Login in spring mvc
I'm new using spring mvc in general. I'm generating login page and my problem is that it always redirects me to the notLoggedIn prompt after I've tried to log in.

The controller:

```<code>@RequestMapping(value="/login", method= RequestMethod.POST) //login
public String logIn(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
    HttpSession session= request.getSession();

    request.getSession().setAttribute("isLoggedIn", "true");

    String uname=request.getParameter("userid");
    String pword=request.getParameter("password");
    boolean exists=logInService.checkLogIn(uname, pword);

    if(exists){
      session.setAttribute("userid", uname);
      return "Users"; //return to next success login jsp
    } else {
        return "Interface2"; //return to Invalid username and password jsp
    }
}
</code>```

The interceptor:

```<code>@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    HttpSession session= request.getSession();

    if(session.getAttribute("userid")!=null && session.getAttribute("isLoggedIn")!=null ){
        System.out.println("Logged In");
    }
    else{
  response.sendRedirect(request.getContextPath()+"/modulename/notLoggedIn");
         System.out.println("Not logged in");
        return false;
    }

    return true;
}
</code>```

答:
Your interceptor blocks every http request and does some check but it should actually allow and not check for login http request. Following changes are just to get the use case work. Refer note at the bottom for suggestions.

```<code>   @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    HttpSession session= request.getSession();

    if(session.getAttribute("userid")!=null && session.getAttribute("isLoggedIn")!=null ){
        //user has already logged in . so therefore can access any resource
        System.out.println("Logged In");
        return true;
    }

    //if code reaches here means that user is not logged in

    //allow login http request. modify checks accordingly. like you can put strict equals.
    if (request.getRequestURI().endsWith("/login")){
        //user is not logged in but is trying to login. so allow only login requests
        return true;
    }
    else{
        //user is not logged in and is trying to access a resource. so redirect him to login page
        response.sendRedirect(request.getContextPath()+"/modulename/notLoggedIn");
        System.out.println("Not logged in");
        return false;
    }
}
</code>```

Note: You can reorder your login http request check to avoid login request for already logged in user.

Title: Session Tracking Login in spring mvc

Body:
I'm new using spring mvc in general. I'm generating login page and my problem is that it always redirects me to the notLoggedIn prompt after I've tried to log in.

The controller:

@RequestMapping(value="/login", method= RequestMethod.POST) //login
public String logIn(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
    HttpSession session= request.getSession();

    request.getSession().setAttribute("isLoggedIn", "true");

    String uname=request.getParameter("userid");
    String pword=request.getParameter("password");
    boolean exists=logInService.checkLogIn(uname, pword);

    if(exists){
      session.setAttribute("userid", uname);
      return "Users"; //return to next success login jsp
    } else {
        return "Interface2"; //return to Invalid username and password jsp
    }
}

The interceptor:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    HttpSession session= request.getSession();

    if(session.getAttribute("userid")!=null && session.getAttribute("isLoggedIn")!=null ){
        System.out.println("Logged In");
    }
    else{
  response.sendRedirect(request.getContextPath()+"/modulename/notLoggedIn");
         System.out.println("Not logged in");
        return false;
    }

    return true;
}

Body:
Your interceptor blocks every http request and does some check but it should actually allow and not check for login http request. Following changes are just to get the use case work. Refer note at the bottom for suggestions.

   @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    HttpSession session= request.getSession();

    if(session.getAttribute("userid")!=null && session.getAttribute("isLoggedIn")!=null ){
        //user has already logged in . so therefore can access any resource
        System.out.println("Logged In");
        return true;
    }

    //if code reaches here means that user is not logged in

    //allow login http request. modify checks accordingly. like you can put strict equals.
    if (request.getRequestURI().endsWith("/login")){
        //user is not logged in but is trying to login. so allow only login requests
        return true;
    }
    else{
        //user is not logged in and is trying to access a resource. so redirect him to login page
        response.sendRedirect(request.getContextPath()+"/modulename/notLoggedIn");
        System.out.println("Not logged in");
        return false;
    }
}

Note: You can reorder your login http request check to avoid login request for already logged in user.


来源: stackexchange

问:
Access div using JQuery
Anobody suggest me how to access DIV in td

```<code><table border="0" cellpadding="0" cellspacing="0" width="95%">
    <tr>
        <td valign="top" style="width:25%">
            <img src="../NewsImages/82010437713162453512.bmp" id="rptAllNewsContent__ctl1_imgNews" width="120" height="120" />
        </td>
        <td valign="top" align="left" style="width:*;padding-left:7px;">
            dsdsdsd
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td align="left" style="width:20%;"><a id="rptAllNewsContent__ctl1_lnkbtnTotalComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl1$lnkbtnTotalComments','')" style="color:#80C355;">2 Comments</a></td>
                    <td align="left"><a id="rptAllNewsContent__ctl1_lnkbtnAddComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl1$lnkbtnAddComments','')" style="color:#80C355;">Add Comments</a></td>
                </tr>
            </table>
        </td>
    </tr>
    <tr><td colspan="2" style="height:13px;"></td></tr>
    <tr>
        <td>
            <div id="rptAllNewsContent__ctl1_divComment">
            sdfasdasda
            sdsa
            d
            asdas
            </div>
        </td>
    </tr>
    <tr>
        <td valign="top" style="width:25%">
            <img src="../NewsImages/8201010976151655912.jpg" id="rptAllNewsContent__ctl2_imgNews" width="120" height="120" />
        </td>
        <td valign="top" align="left" style="width:*;padding-left:7px;">
            dasdasd
        </td>
        </tr>
        <tr>
            <td colspan="2">
                <table border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td align="left" style="width:20%;"><a id="rptAllNewsContent__ctl2_lnkbtnTotalComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl2$lnkbtnTotalComments','')" style="color:#80C355;">3 Comments</a></td>
                        <td align="left"><a id="rptAllNewsContent__ctl2_lnkbtnAddComments" href="javascript:__doPostBack('rptAllNewsContent$_ctl2$lnkbtnAddComments','')" style="color:#80C355;">Add Comments</a></td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr><td colspan="2" style="height:13px;"></td></tr>
        <tr>
            <td>
                <div id="rptAllNewsContent__ctl2_divComment">
                sdfasdasda
                sdsa
                d
                asdas
                </div>
            </td>
        </tr>
    </table>
</code>```

I tried in this way but doesn't work.

```<code>$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $(this).parent("td").parent("tr").next("tr").next("tr td").find("div").text();
        return false;
    });
    });
</code>```

答:
```<code>$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $("#rptAllNewsContent__ctl1_divComment").text();
        return false;
    });
    });
</code>```

ContentLicense: CC BY-SA 2.5

Title: Access div using JQuery

Body:
Anobody suggest me how to access DIV in td

            dsdsdsd

                    2 Comments
                    Add Comments

            sdfasdasda
            sdsa
            d
            asdas

            dasdasd

                        3 Comments
                        Add Comments

                sdfasdasda
                sdsa
                d
                asdas

I tried in this way but doesn't work.

$(document).ready(function(){
    $("a[id$='lnkbtnTotalComments']").click(function(){
        $(this).parent("td").parent("tr").next("tr").next("tr td").find("div").text();
        return false;
    });
    });


问:
How do I send POST Json and Image to php alamofire
I am able to send post data as json fine from swift using this code:

```<code>private func alamoFireAjax(url: String, parameters: Parameters, callback: @escaping (DataResponse<Any>) -> Void) {
    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: callback)
}
</code>```

But I want to send a image along with the data that this function is sending. How do I do that in alamofire, or do I need a different framework.

答: You need convert(encode) image to base64 and send to PHP as a string, after receiving post PHP can decode it and save in the storage or save base64 string.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am able to send post data as json fine from swift using this code:

private func alamoFireAjax(url: String, parameters: Parameters, callback: @escaping (DataResponse<Any>) -> Void) {
    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: callback)
}

But I want to send a image along with the data that this function is sending. How do I do that in alamofire, or do I need a different framework.


问:
Why do this() and super() have to be the first statement in a constructor?
Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?

For example:

```<code>public class MyClass {
    public MyClass(int x) {}
}

public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        int c = a + b;
        super(c);  // COMPILE ERROR
    }
}
</code>```

The Sun compiler says, call to super must be first statement in constructor. The Eclipse compiler says, Constructor call must be the first statement in a constructor.

However, you can get around this by re-arranging the code a little bit:

```<code>public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        super(a + b);  // OK
    }
}
</code>```

Here is another example:

```<code>public class MyClass {
    public MyClass(List list) {}
}

public class MySubClassA extends MyClass {
    public MySubClassA(Object item) {
        // Create a list that contains the item, and pass the list to super
        List list = new ArrayList();
        list.add(item);
        super(list);  // COMPILE ERROR
    }
}

public class MySubClassB extends MyClass {
    public MySubClassB(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(Arrays.asList(new Object[] { item }));  // OK
    }
}
</code>```

So, it is not stopping you from executing logic before the call to super(). It is just stopping you from executing logic that you can't fit into a single expression.

There are similar rules for calling this(). The compiler says, call to this must be first statement in constructor.

Why does the compiler have these restrictions? Can you give a code example where, if the compiler did not have this restriction, something bad would happen?

答:
It makes sense that constructors complete their execution in order of
  derivation. Because a superclass has no knowledge of any subclass, any
  initialization it needs to perform is separate from and possibly
  prerequisite to any initialization performed by the subclass.
  Therefore, it must complete its execution first.

A simple demonstration:

```<code>class A {
    A() {
        System.out.println("Inside A's constructor.");
    }
}

class B extends A {
    B() {
        System.out.println("Inside B's constructor.");
    }
}

class C extends B {
    C() {
        System.out.println("Inside C's constructor.");
    }
}

class CallingCons {
    public static void main(String args[]) {
        C c = new C();
    }
}
</code>```

The output from this program is:

```<code>Inside A's constructor
Inside B's constructor
Inside C's constructor
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?

For example:

public class MyClass {
    public MyClass(int x) {}
}

public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        int c = a + b;
        super(c);  // COMPILE ERROR
    }
}

The Sun compiler says, call to super must be first statement in constructor. The Eclipse compiler says, Constructor call must be the first statement in a constructor.

However, you can get around this by re-arranging the code a little bit:

public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        super(a + b);  // OK
    }
}

Here is another example:

public class MyClass {
    public MyClass(List list) {}
}

public class MySubClassA extends MyClass {
    public MySubClassA(Object item) {
        // Create a list that contains the item, and pass the list to super
        List list = new ArrayList();
        list.add(item);
        super(list);  // COMPILE ERROR
    }
}

public class MySubClassB extends MyClass {
    public MySubClassB(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(Arrays.asList(new Object[] { item }));  // OK
    }
}

So, it is not stopping you from executing logic before the call to super(). It is just stopping you from executing logic that you can't fit into a single expression.

There are similar rules for calling this(). The compiler says, call to this must be first statement in constructor.

Why does the compiler have these restrictions? Can you give a code example where, if the compiler did not have this restriction, something bad would happen?

Body:
It makes sense that constructors complete their execution in order of
  derivation. Because a superclass has no knowledge of any subclass, any
  initialization it needs to perform is separate from and possibly
  prerequisite to any initialization performed by the subclass.
  Therefore, it must complete its execution first.

A simple demonstration:

class A {
    A() {
        System.out.println("Inside A's constructor.");
    }
}

class B extends A {
    B() {
        System.out.println("Inside B's constructor.");
    }
}

class C extends B {
    C() {
        System.out.println("Inside C's constructor.");
    }
}

class CallingCons {
    public static void main(String args[]) {
        C c = new C();
    }
}

The output from this program is:

Inside A's constructor
Inside B's constructor
Inside C's constructor


问:
How to setup SSH port forwarding using Apache Reverse Proxy
we have setup a proxy server between the internet and the backend servers. The HTTP requests are well managed with the VirtualHost directive.

We have a git server sitting behind the proxy, and we would like to access the repository using ssh only, but get rid of the port number in the URL.

For example:
ssh://backend.server.com:7999 --> ssh://backend.server.com

Below is the configuration of apache proxy:

```<code>ProxyRequests
ProxyPreserveHost On
ProxyVia Full
AllowCONNECT 7999
</code>```

The AllowCONNECT directive is supposed to handle the port 7999 via ssh, but I'm not sure this configuration is enough.

What do I need to configure to manage the ssh protocol as we manage the http via ProxyPass and ProxyPassReverse?

Thanks.

答:
I might be misguided here because I don't know all the gory details of how Apache can take care of different kinds of traffic but, AFAIK:

ProxyPass and ProxyPassReverse take care of http request mappings, not ssh paths.

As a matter of fact, can Apache take care of ssh traffic... at all?

If you were using a GNU/Linux server, you could just set up some iptables nat rule to make traffic reaching this host in a certain port (say, port 22) to be "forwarded" to another host. If you would like to go that route, you will have to add a -t nat PREROUTING rule to ask the traffic to be directed to the other host and a -t nat POSTROUTING rule to make sure that responses for this traffic that will be sent to the originating host comes back this way to this very same host so that it can be "denatted" (unless this host is the route that the traffic will flow out when they come back from the ssh server to the host that created the ssh request).

If requests will reach a windows server, I have no idea of how this is done there.

Body:
we have setup a proxy server between the internet and the backend servers. The HTTP requests are well managed with the VirtualHost directive.

We have a git server sitting behind the proxy, and we would like to access the repository using ssh only, but get rid of the port number in the URL.

For example:
ssh://backend.server.com:7999 --> ssh://backend.server.com

Below is the configuration of apache proxy:

ProxyRequests
ProxyPreserveHost On
ProxyVia Full
AllowCONNECT 7999

The AllowCONNECT directive is supposed to handle the port 7999 via ssh, but I'm not sure this configuration is enough.

What do I need to configure to manage the ssh protocol as we manage the http via ProxyPass and ProxyPassReverse?

Thanks.


问:
How to use Camel Apache Timer Component
So currently, the only thing that we can work out is to simply transfer one file to another folder.
Like so:

```<code>from("file://C:/Users/Me/Desktop/FolderA?noop=true")
    .to("file://C:/Users/Me/Desktop/FolderB");
</code>```

However, when I try to add the complexity of the timer component, it just does not make sense to me. I keep getting "Cannot write null body to file" exception.

The code I try to write for the timer Component is like so:

```<code>from("timer://file://C:/Users/Me/Desktop/FolderA?period=30000")
    .to("file://C:/Users/Me/Desktop/FolderB");
</code>```

答:
Have you tried:

```<code>from("timer://file://C:/Users/Me/Desktop/FolderA?fixedRate=true&period=30s")
    .to("file://C:/Users/Me/Desktop/FolderB");
</code>```

And instead of using "30000" you could use "30s" which is more friendly to read.

Check this out.

Title: How to use Camel Apache Timer Component

Body:
So currently, the only thing that we can work out is to simply transfer one file to another folder.
Like so:

from("file://C:/Users/Me/Desktop/FolderA?noop=true")
    .to("file://C:/Users/Me/Desktop/FolderB");

However, when I try to add the complexity of the timer component, it just does not make sense to me. I keep getting "Cannot write null body to file" exception.

The code I try to write for the timer Component is like so:

from("timer://file://C:/Users/Me/Desktop/FolderA?period=30000")
    .to("file://C:/Users/Me/Desktop/FolderB");

Body:
Have you tried:

from("timer://file://C:/Users/Me/Desktop/FolderA?fixedRate=true&period=30s")
    .to("file://C:/Users/Me/Desktop/FolderB");

And instead of using "30000" you could use "30s" which is more friendly to read.

Check this out.


Title: Access div using JQuery

Body: try: $('#rptAllNewsContent__ctl1_divComment').text();


问:
Not reaching .then() after post
I am having troubles with my MEAN stack app, I don't know why after doing the post (used a factory for this) the .then() code is no being executed. Here is the controller:

```<code>angular.module('AcontecimientoCtrl', ['AcontecimientoService'])
  .controller('AcontecimientoController', function($scope, Acontecimiento) {
    var pls = this;
    $scope.agregarAcontecimiento = function() {
        pls.errorMsg = false;
        Acontecimiento
          .create($scope.acontecimiento)
          .then(function(data) {
            $scope.acontecimiento = {};
            console.log(data.data.success);
            console.log(data.data.message);
            if (data.data.success) {
              pls.successMsg = data.data.message;
            } else {
                pls.errorMsg = data.data.message;
            }
        })
    };
});
</code>```

this is the service:

```<code>angular.module('AcontecimientoService', [])
  .factory('Acontecimiento', function($http) {
    return {
        get : function() {
            return $http.get('/api/acontecimiento');
        },
        create : function(acontecimiento) {
            return $http.post('/api/acontecimiento', acontecimiento);
        },
        delete : function(id) {
            return $http.delete('/api/acontecimiento/' + id);
        }
    }
});
</code>```

here it is the post method:

```<code>app.post('/api/acontecimiento', function(req, res) {
         // create a todo, information comes from AJAX request from Angular
         if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
           res.json({success: false, message: 'Campo, titular, fecha y tipo de operacion deben especificarse'});
         } else {
           Acontecimiento.create({
             campo : req.body.campo,
             titular : req.body.titular,
             fecha : req.body.fecha,
             tipo : req.body.tipo,
             brucelosis : req.body.brucelosis,
             vacas : req.body.vacas,
             toros : req.body.toros,
             novillitos : req.body.novillitos,
             vaquillonas : req.body.vaquillonas,
             terneras : req.body.terneras,
             terneros : req.body.terneros,
           }, function(err, acontecimiento) {
           if (err)
              res.sendfile('./public/views/index.html');
           });
         }
       });
</code>```

And in case you need, this is my view:

```<code><div class="row show-hide-message" ng-show="successMsg">
  <div class="alert alert-success">Nueva operacion guardada</div>
</div>
<div class="row show-hide-message" ng-show="errorMsg">
  <div class="alert alert-danger">Campo, titular, fecha y tipo de operacion deben especificarse</div>
</div>
<div class="jumbotron text-center">
    <form ng-submit="agregarAcontecimiento()" class="form-horizontal">
      <div class="form-group">
        <label class="control-label col-sm-2" for="campo">Campo</label>
        <div class="col-sm-9">
          <select class="form-control" id="campo" ng-model="acontecimiento.campo" required />
            <option>GUARANIMINI</option>
            <option>TRES MARIAS</option>
            <option>ESPADAÑAL</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="titular">Titular</label>
        <div class="col-sm-9">
          <select class="form-control" id="titular" ng-model="acontecimiento.titular" required />
            <option>RUBEN CARLOS P.</option>
            <option>VICTOR HUGO P.</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="fecha">Fecha</label>
        <div class="col-sm-9">
          <input type="date" id="fecha" class="form-control" ng-model="acontecimiento.fecha" required />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="tipo">Tipo</label>
        <div class="col-sm-9">
          <select class="form-control" id="tipo" ng-model="acontecimiento.tipo" required />
            <option>VACUNA</option>
            <option>VENTA</option>
            <option>MUERTE</option>
            <option>TRANSLADO</option>
            <option>CONTAR STOCK ACTUAL</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="brucelosis">Brucelosis</label>
        <div class="col-sm-9">
          <input type="number" id="brucelosis" class="form-control" ng-model="acontecimiento.brucelosis"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="vacas">Vacas</label>
        <div class="col-sm-9">
          <input type="number" id="vacas" class="form-control" ng-model="acontecimiento.vacas"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="toros">Toros</label>
        <div class="col-sm-9">
          <input type="number" id="toros" class="form-control" ng-model="acontecimiento.toros"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="novillitos">Novillitos</label>
        <div class="col-sm-9">
          <input type="number" id="novillitos" class="form-control" ng-model="acontecimiento.novillitos"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="vaquillonas">Vaquillonas</label>
        <div class="col-sm-9">
          <input type="number" id="vaquillonas" class="form-control" ng-model="acontecimiento.vaquillonas"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="terneras">Terneras</label>
        <div class="col-sm-9">
          <input type="number" id="terneras" class="form-control" ng-model="acontecimiento.terneras"  />
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="terneros">Terneros</label>
        <div class="col-sm-9">
          <input type="number" id="terneros" class="form-control" ng-model="acontecimiento.terneros"  />
        </div>
      </div>
      <div class="pull-right">
        <button type="submit" class="btn btn-default">Aceptar</button>
      </div>
    </form>
</div>
</code>```

答:
The problem is on your node side, once you add the item to what I can only assume is the database and all is good, you never return a response.

Change your nodeJS code to be:

```<code>app.post('/api/acontecimiento', function (req, res) {
    // create a todo, information comes from AJAX request from Angular
    if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
        res.json({
            success: false,
            message: 'Campo, titular, fecha y tipo de operacion deben especificarse'
        });
    } else {
        Acontecimiento.create({
            campo: req.body.campo,
            titular: req.body.titular,
            fecha: req.body.fecha,
            tipo: req.body.tipo,
            brucelosis: req.body.brucelosis,
            vacas: req.body.vacas,
            toros: req.body.toros,
            novillitos: req.body.novillitos,
            vaquillonas: req.body.vaquillonas,
            terneras: req.body.terneras,
            terneros: req.body.terneros,
        }, function (err, acontecimiento) {
            if (err) {
                res.sendfile('./public/views/index.html');
            } else {
                res.json({
                    success: true,
                    message: 'All good!'
                });
            }
        });
    }
});
</code>```

and then it should hit the .then()

Title: Not reaching .then() after post

Body:
I am having troubles with my MEAN stack app, I don't know why after doing the post (used a factory for this) the .then() code is no being executed. Here is the controller:

angular.module('AcontecimientoCtrl', ['AcontecimientoService'])
  .controller('AcontecimientoController', function($scope, Acontecimiento) {
    var pls = this;
    $scope.agregarAcontecimiento = function() {
        pls.errorMsg = false;
        Acontecimiento
          .create($scope.acontecimiento)
          .then(function(data) {
            $scope.acontecimiento = {};
            console.log(data.data.success);
            console.log(data.data.message);
            if (data.data.success) {
              pls.successMsg = data.data.message;
            } else {
                pls.errorMsg = data.data.message;
            }
        })
    };
});

this is the service:

angular.module('AcontecimientoService', [])
  .factory('Acontecimiento', function($http) {
    return {
        get : function() {
            return $http.get('/api/acontecimiento');
        },
        create : function(acontecimiento) {
            return $http.post('/api/acontecimiento', acontecimiento);
        },
        delete : function(id) {
            return $http.delete('/api/acontecimiento/' + id);
        }
    }
});

here it is the post method:

app.post('/api/acontecimiento', function(req, res) {
         // create a todo, information comes from AJAX request from Angular
         if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
           res.json({success: false, message: 'Campo, titular, fecha y tipo de operacion deben especificarse'});
         } else {
           Acontecimiento.create({
             campo : req.body.campo,
             titular : req.body.titular,
             fecha : req.body.fecha,
             tipo : req.body.tipo,
             brucelosis : req.body.brucelosis,
             vacas : req.body.vacas,
             toros : req.body.toros,
             novillitos : req.body.novillitos,
             vaquillonas : req.body.vaquillonas,
             terneras : req.body.terneras,
             terneros : req.body.terneros,
           }, function(err, acontecimiento) {
           if (err)
              res.sendfile('./public/views/index.html');
           });
         }
       });

And in case you need, this is my view:

Nueva operacion guardada

Campo, titular, fecha y tipo de operacion deben especificarse

    <form ng-submit="agregarAcontecimiento()" class="form-horizontal">

        Campo

          <select class="form-control" id="campo" ng-model="acontecimiento.campo" required />
            <option>GUARANIMINI</option>
            <option>TRES MARIAS</option>
            <option>ESPADAÑAL</option>
          </select>

        Titular

          <select class="form-control" id="titular" ng-model="acontecimiento.titular" required />
            <option>RUBEN CARLOS P.</option>
            <option>VICTOR HUGO P.</option>
          </select>

        Fecha

          <input type="date" id="fecha" class="form-control" ng-model="acontecimiento.fecha" required />

        Tipo

          <select class="form-control" id="tipo" ng-model="acontecimiento.tipo" required />
            <option>VACUNA</option>
            <option>VENTA</option>
            <option>MUERTE</option>
            <option>TRANSLADO</option>
            <option>CONTAR STOCK ACTUAL</option>
          </select>

        Brucelosis

          <input type="number" id="brucelosis" class="form-control" ng-model="acontecimiento.brucelosis"  />

        Vacas

          <input type="number" id="vacas" class="form-control" ng-model="acontecimiento.vacas"  />

        Toros

          <input type="number" id="toros" class="form-control" ng-model="acontecimiento.toros"  />

        Novillitos

          <input type="number" id="novillitos" class="form-control" ng-model="acontecimiento.novillitos"  />

        Vaquillonas

          <input type="number" id="vaquillonas" class="form-control" ng-model="acontecimiento.vaquillonas"  />

        Terneras

          <input type="number" id="terneras" class="form-control" ng-model="acontecimiento.terneras"  />

        Terneros

          <input type="number" id="terneros" class="form-control" ng-model="acontecimiento.terneros"  />

        <button type="submit" class="btn btn-default">Aceptar</button>

    </form>

Body:
The problem is on your node side, once you add the item to what I can only assume is the database and all is good, you never return a response.

Change your nodeJS code to be:

app.post('/api/acontecimiento', function (req, res) {
    // create a todo, information comes from AJAX request from Angular
    if (req.body.campo == '' || req.body.titular == '' || req.body.fecha == '' || req.body.tipo == '') {
        res.json({
            success: false,
            message: 'Campo, titular, fecha y tipo de operacion deben especificarse'
        });
    } else {
        Acontecimiento.create({
            campo: req.body.campo,
            titular: req.body.titular,
            fecha: req.body.fecha,
            tipo: req.body.tipo,
            brucelosis: req.body.brucelosis,
            vacas: req.body.vacas,
            toros: req.body.toros,
            novillitos: req.body.novillitos,
            vaquillonas: req.body.vaquillonas,
            terneras: req.body.terneras,
            terneros: req.body.terneros,
        }, function (err, acontecimiento) {
            if (err) {
                res.sendfile('./public/views/index.html');
            } else {
                res.json({
                    success: true,
                    message: 'All good!'
                });
            }
        });
    }
});

and then it should hit the .then()


问:
Errors upon searching in Elasticsearch using PHP
I am trying to search through my index using PHP. I have downloaded the vendor files and I have built the connection successfully. However, I am receiving some errors. These errors don't always occur though. If I refresh the browser a couple of times, I will get the correct output. Here's my code:

```<code>require_once 'init.php';

$json = '{"aggs": { "group_by_date": { "terms": { "field": "arrivalDate" } } } }';

    $params = [
        'index' => 'pickups',
        'type' => 'external',
        'body' => $json
        ];

$results = $es->search($params);

echo $results['hits']['total'];
</code>```

The init.php is the connection file to Elasticsearch. There are 2 different outputs that may occur upon refreshing the screen. The first output is the correct output. The other is just errors. Here are the errors:

Fatal error: Uncaught Elasticsearch\Common\Exceptions\Missing404Exception: {"statusCode":404,"error":"Not Found"} in C:\wamp64\www\DataAggregation\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 602

Elasticsearch\Common\Exceptions\Missing404Exception: {"statusCode":404,"error":"Not Found"} in C:\wamp64\www\DataAggregation\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 602

Fatal error: Uncaught Elasticsearch\Common\Exceptions\BadRequest400Exception:   in C:\wamp64\www\DataAggregation\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 610

What are the cause of these errors and how can I fix them?

答: It seems you have not started web server, start ES web server to connect with php.</p>

Body:
I am trying to search through my index using PHP. I have downloaded the vendor files and I have built the connection successfully. However, I am receiving some errors. These errors don't always occur though. If I refresh the browser a couple of times, I will get the correct output. Here's my code:

require_once 'init.php';

$json = '{"aggs": { "group_by_date": { "terms": { "field": "arrivalDate" } } } }';

    $params = [
        'index' => 'pickups',
        'type' => 'external',
        'body' => $json
        ];

$results = $es->search($params);

echo $results['hits']['total'];

The init.php is the connection file to Elasticsearch. There are 2 different outputs that may occur upon refreshing the screen. The first output is the correct output. The other is just errors. Here are the errors:

Fatal error: Uncaught Elasticsearch\Common\Exceptions\Missing404Exception: {"statusCode":404,"error":"Not Found"} in C:\wamp64\www\DataAggregation\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 602

Elasticsearch\Common\Exceptions\Missing404Exception: {"statusCode":404,"error":"Not Found"} in C:\wamp64\www\DataAggregation\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 602

Fatal error: Uncaught Elasticsearch\Common\Exceptions\BadRequest400Exception:   in C:\wamp64\www\DataAggregation\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 610

What are the cause of these errors and how can I fix them?


问:
Some strings in a array match another array
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}
</code>```

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

答:
Is something like this what you're after?</p>

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

for user in usersInData {
    if verifiedUsers.contains(where: { $0 == user } )
        print("\(user) is a special user")
    } else {
        print("\(user) is a regular user")
    }
}
</code>```

Body:
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

Body:
Is something like this what you're after?

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

for user in usersInData {
    if verifiedUsers.contains(where: { $0 == user } )
        print("\(user) is a special user")
    } else {
        print("\(user) is a regular user")
    }
}


问:
Does a language-specific IDE have any advantages over a plugin for a multi-language IDE?
I do mostly Java and C/C++ development, but I'm starting to do more web development (PHP, Rails) and Eiffel (learning a new language is always good).

Currently, I use Eclipse for Java, C/C++, and Ruby (not Rails). Since I know the environment, I'm thinking that it would be easier for me to find a plugin and use Eclipse for all of my development languages. But are there cases where a language-specific IDE (EiffelStudio for Eiffel, as an example) would be better than Eclipse?

答: It entirely depends on the user and the language itself, if you are comfortable with the keyboard shortcuts then you can consider the plugin else you can go for a IDE . However most of the IDE comes with a cross-functional key maps so you use the key maps which u are more comfortable with.... </p>

OwnerDisplayName: Thomas Owens


问:
Error with time.sleep
I am new to Python3 and I have some problems. I've created a program like this:

x = input("Type a number: ")
time.sleep(x)

Every time I use this I get an error. I don't know what I am doing wrong, could someone help me?

答:
Console input is of type str by default:

Type cast it to int.

```<code>x = int(input("Type a number: "))
time.sleep(x)
</code>```

Title: Error with time.sleep

Body:
Console input is of type str by default:

Type cast it to int.

x = int(input("Type a number: "))
time.sleep(x)


问:
How can I change an input for a label without an error in value in Angular?
I tried to change the input for a label but it generates an error in value

This is my code

This is html

    Edad

    <input readonly type="text" [value]="CalculateAge()">

```
</div>
</div>
</p>

<p>This is how you changed by the seal as it should be?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small-6 columns">
  <label readonly for="text" [value]="CalculateAge()">
        </label>
</div></code>```

This is component

export class DatosPersonalesComponent implements OnInit {
  @Input()
  datosDTO: DatosDTO;

  public age: number;

  constructor() {}

  ngOnInit() {
    this.datosDTO = new DatosDTO();
  }
  CalculateAge(): void {
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }
}```

This is error

I would greatly appreciate your help.

答:
label is typically used with the for attribute like so

```<code><label for="age">{{ age }}</label>
<input type="text" id="age">
</code>```

The value should be between the tags, not in the value property

```<code>get age(){
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      return Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }
</code>```

Your functions inside class should typically not be capitalized

```<code>calculateAge()
</code>```

You are specifying datosDTO as @Input() yet you initialize it in ngOnInit(). You shouldn't do that.

Body:
I tried to change the input for a label but it generates an error in value

This is my code

This is html

    Edad

    <input readonly type="text" [value]="CalculateAge()">

This is how you changed by the seal as it should be?

This is component

export class DatosPersonalesComponent implements OnInit {
  @Input()
  datosDTO: DatosDTO;

  public age: number;

  constructor() {}

  ngOnInit() {
    this.datosDTO = new DatosDTO();
  }
  CalculateAge(): void {
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }
}

This is error

I would greatly appreciate your help.

Body:
label is typically used with the for attribute like so

<label for="age">{{ age }}</label>
<input type="text" id="age">

The value should be between the tags, not in the value property

get age(){
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      return Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }

Your functions inside class should typically not be capitalized

calculateAge()

You are specifying datosDTO as @Input() yet you initialize it in ngOnInit(). You shouldn't do that.


问:
Server.MapPath() wrong path on IIS
I am trying to upload image to a folder called
~/Avatars/.

My project is located in VS2010 projects folder
`C:/Projects/MyProject.

When i try to get physical path to Avatars folder by

```<code>Server.MapPath("/Avatars")
</code>```

it always returns

```<code>C:\inetpub\wwwroot\Avatars
</code>```

instead of

```<code>C:\Projects\MyProject\Avatars.
</code>```

It works fine when I run the project on VS2010 dev server.

Can anyone help me how to get actual path in IIS?

答:
Check whether virtual directory named  Avatars  is not created in IIS that points to the path: "C:\inetpub\wwwroot\Avatars".

In that case Server.Mappath returns the same path. In such case remove that Virtual Directory from IIS

Title: Server.MapPath() wrong path on IIS

Body:
I am trying to upload image to a folder called
~/Avatars/.

My project is located in VS2010 projects folder
`C:/Projects/MyProject.

When i try to get physical path to Avatars folder by

Server.MapPath("/Avatars")

it always returns

C:\inetpub\wwwroot\Avatars

instead of

C:\Projects\MyProject\Avatars.

It works fine when I run the project on VS2010 dev server.

Can anyone help me how to get actual path in IIS?


问:
Strange classification output with DNN
I try to classify images using fine tuned network CaffeNet. I followed tutorial from Caffe and changed number of outputs in train file to 3, also I turned off learning for first two convolutional layers. For some reason when I use classifier with trained model I'm getting 0.3 for all classes for each image from test set.

```<code>number of classes: 3
train set size: 6570 images (80%)
test set size: 1645 images (20%)
</code>```

Solver:

```<code>net: "train.prototxt"
test_iter: 100
test_interval: 1000
base_lr: 0.0001
lr_policy: "step"
gamma: 0.1
stepsize: 20000
display: 200
max_iter: 60000
momentum: 0.9
weight_decay: 0.0005
snapshot: 10000
snapshot_prefix: "snapshot"
solver_mode: GPU
</code>```

How I run training:

```<code>caffe train -solver solver.prototxt -weights bvlc_reference_caffenet.caffemodel
</code>```

some output:

```<code>I0531 00:35:52.622647  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:36:02.699782  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:36:03.900009  5528 solver.cpp:218] Iteration 3600 (10.1266 iter/s, 19.7499s/200 iters), loss = 0.679402
I0531 00:36:03.900009  5528 solver.cpp:237]     Train net output #0: loss = 0.679402 (* 1 = 0.679402 loss)
I0531 00:36:03.900009  5528 sgd_solver.cpp:105] Iteration 3600, lr = 0.0001

I0531 00:41:20.139937  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:30.934025  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:34.199774  5528 solver.cpp:218] Iteration 6800 (9.66881 iter/s, 20.6851s/200 iters), loss = 0.451174
I0531 00:41:34.199774  5528 solver.cpp:237]     Train net output #0: loss = 0.451174 (* 1 = 0.451174 loss)
I0531 00:41:34.199774  5528 sgd_solver.cpp:105] Iteration 6800, lr = 0.0001

I0531 00:41:41.794001  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:52.743448  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:55.126147  5528 solver.cpp:330] Iteration 7000, Testing net (#0)
I0531 00:41:55.891929  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:58.393698  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:58.862452  5528 solver.cpp:397]     Test net output #0: accuracy = 0.6952
I0531 00:41:58.862452  5528 solver.cpp:397]     Test net output #1: loss = 0.873388 (* 1 = 0.873388 loss)

I0531 00:43:08.320360  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:18.514559  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:18.920881  5528 solver.cpp:218] Iteration 7800 (10.0073 iter/s, 19.9854s/200 iters), loss = 0.196175
I0531 00:43:18.920881  5528 solver.cpp:237]     Train net output #0: loss = 0.196175 (* 1 = 0.196175 loss)
I0531 00:43:18.920881  5528 sgd_solver.cpp:105] Iteration 7800, lr = 0.0001
I0531 00:43:28.660408  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:38.561293  5528 solver.cpp:330] Iteration 8000, Testing net (#0)
I0531 00:43:40.405230  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:42.077230  5528 solver.cpp:397]     Test net output #0: accuracy = 0.7004
I0531 00:43:42.077230  5528 solver.cpp:397]     Test net output #1: loss = 0.991567 (* 1 = 0.991567 loss)

I0531 00:45:22.426592  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:45:24.761165  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:45:25.329238  5528 solver.cpp:397]     Test net output #0: accuracy = 0.6856
I0531 00:45:25.329238  5528 solver.cpp:397]     Test net output #1: loss = 1.08582 (* 1 = 1.08582 loss)
I0531 00:45:25.394567  5528 solver.cpp:218] Iteration 9000 (8.39955 iter/s, 23.8108s/200 iters), loss = 0.107816
I0531 00:45:25.394567  5528 solver.cpp:237]     Train net output #0: loss = 0.107816 (* 1 = 0.107816 loss)

I0531 00:46:49.099460  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:46:59.269830  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:47:03.997443  5528 solver.cpp:447] Snapshotting to binary proto file snapshot_iter_10000.caffemodel
I0531 00:47:05.185039  5528 sgd_solver.cpp:273] Snapshotting solver state to binary proto file snapshot_iter_10000.solverstate
I0531 00:47:05.403774  5528 solver.cpp:330] Iteration 10000, Testing net (#0)
I0531 00:47:07.122831  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:47:08.870923  5528 solver.cpp:397]     Test net output #0: accuracy = 0.7012
I0531 00:47:08.870923  5528 solver.cpp:397]     Test net output #1: loss = 1.18649 (* 1 = 1.18649 loss)
I0531 00:47:08.964664  5528 solver.cpp:218] Iteration 10000 (8.12416 iter/s, 24.6179s/200 iters), loss = 0.0347012
I0531 00:47:08.964664  5528 solver.cpp:237]     Train net output #0: loss = 0.0347012 (* 1 = 0.0347012 loss)
I0531 00:47:08.964664  5528 sgd_solver.cpp:105] Iteration 10000, lr = 0.0001
</code>```

How I run classification:

```<code>classification deploy.prototxt snapshot_iter_10000.caffemodel labels.txt ..\test
</code>```

some output:

```<code>"0.jpg",0.333333,0.333333,0.333333
"1.jpg",0.333333,0.333333,0.333333
"10.jpg",0.333333,0.333333,0.333333
"100.jpg",0.333333,0.333333,0.333333
"101.jpg",0.333333,0.333333,0.333333
"102.jpg",0.333333,0.333333,0.333333,
"103.jpg",0.333333,0.333333,0.333333
</code>```

For some reason with 70% accuracy I'm getting same result as with 50% - every class has 0.3.

答:
There's nothing strange with your classification output, it's just that you need to interpret it correctly. An accuracy of 0.333for 3 classes simply implies that your network isn't learning anything - it is random guessing. For N classes random guess will give you an accuracy of 1/N. So in your case it is 1/3, i.e., 0.333.

Now, there's no such standard rule for setting your hyperparameters but looking at the huge variations in your loss, I would suggest you to reduce your base learning rate to 0.00001.

Title: Strange classification output with DNN

Body:
I try to classify images using fine tuned network CaffeNet. I followed tutorial from Caffe and changed number of outputs in train file to 3, also I turned off learning for first two convolutional layers. For some reason when I use classifier with trained model I'm getting 0.3 for all classes for each image from test set.

number of classes: 3
train set size: 6570 images (80%)
test set size: 1645 images (20%)

Solver:

net: "train.prototxt"
test_iter: 100
test_interval: 1000
base_lr: 0.0001
lr_policy: "step"
gamma: 0.1
stepsize: 20000
display: 200
max_iter: 60000
momentum: 0.9
weight_decay: 0.0005
snapshot: 10000
snapshot_prefix: "snapshot"
solver_mode: GPU

How I run training:

caffe train -solver solver.prototxt -weights bvlc_reference_caffenet.caffemodel

some output:

I0531 00:35:52.622647  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:36:02.699782  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:36:03.900009  5528 solver.cpp:218] Iteration 3600 (10.1266 iter/s, 19.7499s/200 iters), loss = 0.679402
I0531 00:36:03.900009  5528 solver.cpp:237]     Train net output #0: loss = 0.679402 (* 1 = 0.679402 loss)
I0531 00:36:03.900009  5528 sgd_solver.cpp:105] Iteration 3600, lr = 0.0001

I0531 00:41:20.139937  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:30.934025  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:34.199774  5528 solver.cpp:218] Iteration 6800 (9.66881 iter/s, 20.6851s/200 iters), loss = 0.451174
I0531 00:41:34.199774  5528 solver.cpp:237]     Train net output #0: loss = 0.451174 (* 1 = 0.451174 loss)
I0531 00:41:34.199774  5528 sgd_solver.cpp:105] Iteration 6800, lr = 0.0001

I0531 00:41:41.794001  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:52.743448  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:55.126147  5528 solver.cpp:330] Iteration 7000, Testing net (#0)
I0531 00:41:55.891929  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:58.393698  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:41:58.862452  5528 solver.cpp:397]     Test net output #0: accuracy = 0.6952
I0531 00:41:58.862452  5528 solver.cpp:397]     Test net output #1: loss = 0.873388 (* 1 = 0.873388 loss)

I0531 00:43:08.320360  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:18.514559  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:18.920881  5528 solver.cpp:218] Iteration 7800 (10.0073 iter/s, 19.9854s/200 iters), loss = 0.196175
I0531 00:43:18.920881  5528 solver.cpp:237]     Train net output #0: loss = 0.196175 (* 1 = 0.196175 loss)
I0531 00:43:18.920881  5528 sgd_solver.cpp:105] Iteration 7800, lr = 0.0001
I0531 00:43:28.660408  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:38.561293  5528 solver.cpp:330] Iteration 8000, Testing net (#0)
I0531 00:43:40.405230  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:43:42.077230  5528 solver.cpp:397]     Test net output #0: accuracy = 0.7004
I0531 00:43:42.077230  5528 solver.cpp:397]     Test net output #1: loss = 0.991567 (* 1 = 0.991567 loss)

I0531 00:45:22.426592  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:45:24.761165  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:45:25.329238  5528 solver.cpp:397]     Test net output #0: accuracy = 0.6856
I0531 00:45:25.329238  5528 solver.cpp:397]     Test net output #1: loss = 1.08582 (* 1 = 1.08582 loss)
I0531 00:45:25.394567  5528 solver.cpp:218] Iteration 9000 (8.39955 iter/s, 23.8108s/200 iters), loss = 0.107816
I0531 00:45:25.394567  5528 solver.cpp:237]     Train net output #0: loss = 0.107816 (* 1 = 0.107816 loss)

I0531 00:46:49.099460  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:46:59.269830  2944 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:47:03.997443  5528 solver.cpp:447] Snapshotting to binary proto file snapshot_iter_10000.caffemodel
I0531 00:47:05.185039  5528 sgd_solver.cpp:273] Snapshotting solver state to binary proto file snapshot_iter_10000.solverstate
I0531 00:47:05.403774  5528 solver.cpp:330] Iteration 10000, Testing net (#0)
I0531 00:47:07.122831  3704 data_layer.cpp:73] Restarting data prefetching from start.
I0531 00:47:08.870923  5528 solver.cpp:397]     Test net output #0: accuracy = 0.7012
I0531 00:47:08.870923  5528 solver.cpp:397]     Test net output #1: loss = 1.18649 (* 1 = 1.18649 loss)
I0531 00:47:08.964664  5528 solver.cpp:218] Iteration 10000 (8.12416 iter/s, 24.6179s/200 iters), loss = 0.0347012
I0531 00:47:08.964664  5528 solver.cpp:237]     Train net output #0: loss = 0.0347012 (* 1 = 0.0347012 loss)
I0531 00:47:08.964664  5528 sgd_solver.cpp:105] Iteration 10000, lr = 0.0001

How I run classification:

classification deploy.prototxt snapshot_iter_10000.caffemodel labels.txt ..\test

some output:

"0.jpg",0.333333,0.333333,0.333333
"1.jpg",0.333333,0.333333,0.333333
"10.jpg",0.333333,0.333333,0.333333
"100.jpg",0.333333,0.333333,0.333333
"101.jpg",0.333333,0.333333,0.333333
"102.jpg",0.333333,0.333333,0.333333,
"103.jpg",0.333333,0.333333,0.333333

For some reason with 70% accuracy I'm getting same result as with 50% - every class has 0.3.


问:
Text content in listview not displaying C#
I have a listview control and the text will not show up. I have tried 3 different implementations and I get the same result in each. The rows for the associated number of items will highlight, but the text is nowhere. I am using WPF and the text contents look like the following in the file I am reading in:

```<code>string1::string2
</code>```

However, for testing purposes, I am not utilizing the file contents.

Tutorial I'm Using: http://www.wpf-tutorial.com/listview-control/listview-with-gridview/

"1" and "2" were in there just to test.

Code

```<code>        List<ServerData> items = new List<ServerData>();

        while ((line = file.ReadLine()) != null )
        {
            string[] serverData = Regex.Split(line, "::");
            items.Add(new ServerData() { IPAddress="1", ServerName="2" });
        }
        listServer.ItemsSource = items;
        file.Close();
</code>```

....

```<code>public class ServerData
{
    public string IPAddress { get; set; }
    public string ServerName { get; set; }
}
</code>```

XAML

```<code><ListView Margin="10,47,11,45.8" x:Name="listServer" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IP Address" Width="218.4" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Server Name" Width="218.4" DisplayMemberBinding="{Binding Name}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

答:
```<code><ListView Margin="10,47,11,45.8" x:Name="listServer" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IP Address" Width="218.4" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Server Name" Width="218.4" DisplayMemberBinding="{Binding Name}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

Here's your problem, you're binding the columns to Name, when instead it should be:

```<code><ListView Margin="10,47,11,45.8" x:Name="listServer" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IP Address" Width="218.4" DisplayMemberBinding="{Binding IPAddress}" />
            <GridViewColumn Header="Server Name" Width="218.4" DisplayMemberBinding="{Binding ServerName}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

Body:
I have a listview control and the text will not show up. I have tried 3 different implementations and I get the same result in each. The rows for the associated number of items will highlight, but the text is nowhere. I am using WPF and the text contents look like the following in the file I am reading in:

string1::string2

However, for testing purposes, I am not utilizing the file contents.

Tutorial I'm Using: http://www.wpf-tutorial.com/listview-control/listview-with-gridview/

"1" and "2" were in there just to test.

Code

        List<ServerData> items = new List<ServerData>();

        while ((line = file.ReadLine()) != null )
        {
            string[] serverData = Regex.Split(line, "::");
            items.Add(new ServerData() { IPAddress="1", ServerName="2" });
        }
        listServer.ItemsSource = items;
        file.Close();

....

public class ServerData
{
    public string IPAddress { get; set; }
    public string ServerName { get; set; }
}

XAML

<ListView Margin="10,47,11,45.8" x:Name="listServer" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IP Address" Width="218.4" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Server Name" Width="218.4" DisplayMemberBinding="{Binding Name}" />
        </GridView>
    </ListView.View>
</ListView>

Body:
<ListView Margin="10,47,11,45.8" x:Name="listServer" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IP Address" Width="218.4" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Server Name" Width="218.4" DisplayMemberBinding="{Binding Name}" />
        </GridView>
    </ListView.View>
</ListView>

Here's your problem, you're binding the columns to Name, when instead it should be:

<ListView Margin="10,47,11,45.8" x:Name="listServer" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IP Address" Width="218.4" DisplayMemberBinding="{Binding IPAddress}" />
            <GridViewColumn Header="Server Name" Width="218.4" DisplayMemberBinding="{Binding ServerName}" />
        </GridView>
    </ListView.View>
</ListView>


问:
Android phone code
I am struggling to get the attached layout on the screen, especially the dashes where they will act like a single digit text field and since it is a code the next number have to jump to the next , textfield, if that is what I have to use.
This is when the user recieves a code (4 digits) he have to enter it, but one number per field.

I think the picture is self explanatory. Thankyou.

答:
please Check below code that is working fine.just copy paste below code to your xml layout file.

```<code>  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_test"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:text="ENTER CODE"
        android:textSize="18sp"
        android:textColor="@android:color/holo_blue_dark"
        android:layout_gravity="center"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionNext"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionNext"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionNext"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionDone"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:text="00:32"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="Resend Code"
        android:textSize="15sp"
        android:textColor="@android:color/holo_blue_dark"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="match_parent"
        android:text="verify"
        android:layout_marginTop="10dp"
        android:background="@android:color/holo_blue_dark"
        android:layout_height="wrap_content" />

</LinearLayout>
</code>```

set MaxLength=1 in edittext that did the trick
     and please give margin according to your requirement.

Title: Android phone code

Body:
please Check below code that is working fine.just copy paste below code to your xml layout file.

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_test"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:text="ENTER CODE"
        android:textSize="18sp"
        android:textColor="@android:color/holo_blue_dark"
        android:layout_gravity="center"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionNext"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionNext"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionNext"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:imeOptions="actionDone"
            android:maxLength="1"
            android:inputType="number"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:text="00:32"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="Resend Code"
        android:textSize="15sp"
        android:textColor="@android:color/holo_blue_dark"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="match_parent"
        android:text="verify"
        android:layout_marginTop="10dp"
        android:background="@android:color/holo_blue_dark"
        android:layout_height="wrap_content" />

</LinearLayout>

set MaxLength=1 in edittext that did the trick
     and please give margin according to your requirement.


问:
make comma separated strings from multidimensional array
I have JavaScript multidimensional array like this:

```<code>a   1
b   2
c   3
</code>```

I want it converted into comma separated value like this:

```<code>function reg() {
    var result = [];
    var comma_value;

    for (var i = 0; i < arrc.length; i++) {
        if (parseInt(arrc[i].value)) {
            result.push([arrp[i].value, arrc[i].value]);
        }

        // result is an array
        // My desired result:
        // comma_value = "a,1;b,2;c,3"
    }

    $('#str').val(JSON.stringify(result));

    console.table(result);
    console.log(result.join(', '));
}
</code>```

答:
Given your comments I assume you are simply looking for Array.prototype.join(';'):

let array = [
  ['a', 1],
  ['b', 2],
  ['c', 3]
];

let comma_value = array.join(';');

console.log(comma_value); // 'a,1;b,2;c,3'```
</div>
</div>
</p>

<p>This works due to the implicit array element <code>['a', 1]</code> to string <code>'a,1'</code> conversion performed within the <code>array.join(';')</code> method call.</p>

<p>If you are curious <em>how</em> this works: When you call <code>array.join(';')</code>, the individual array elements are first converted to strings via the <code>Array.prototype.toString()</code> method:</p>

```['a', 1].toString() // returns 'a,1'
```

Subsequently, those strings are joined with the ';' separator in between.

However, I don't see how this and your comments relate to the given reg() function. That code features two one-dimensional arrays with {value: ...} objects as elements.

Body:
I have JavaScript multidimensional array like this:

a   1
b   2
c   3

I want it converted into comma separated value like this:

function reg() {
    var result = [];
    var comma_value;

    for (var i = 0; i < arrc.length; i++) {
        if (parseInt(arrc[i].value)) {
            result.push([arrp[i].value, arrc[i].value]);
        }

        // result is an array
        // My desired result:
        // comma_value = "a,1;b,2;c,3"
    }

    $('#str').val(JSON.stringify(result));

    console.table(result);
    console.log(result.join(', '));
}

Body:
Given your comments I assume you are simply looking for Array.prototype.join(';'):

let array = [
  ['a', 1],
  ['b', 2],
  ['c', 3]
];

let comma_value = array.join(';');

console.log(comma_value); // 'a,1;b,2;c,3'

This works due to the implicit array element ['a', 1] to string 'a,1' conversion performed within the array.join(';') method call.

If you are curious how this works: When you call array.join(';'), the individual array elements are first converted to strings via the Array.prototype.toString() method:

['a', 1].toString() // returns 'a,1'

Subsequently, those strings are joined with the ';' separator in between.

However, I don't see how this and your comments relate to the given reg() function. That code features two one-dimensional arrays with {value: ...} objects as elements.


问:
Retrofit 2 - POST request became GET?
My POST request keeps sending as GET & got rejected by API endpoint

MyService class

```<code>@FormUrlEncoded
@POST("api/users/")
Call<List<User>> getUsers(@FieldMap HashMap<String, String> parameters);
</code>```

Request code

```<code>Gson builder = new GsonBuilder().setLenient().create();
Retrofit client = new Retrofit.Builder()
        .baseUrl(Constants.API_ENDPOINT_TEST_URL)
        .addConverterFactory(GsonConverterFactory.create(builder))
        .build();
mApiService = client.create(MyService.class);
Call<List<User>> call = mApiService.getUsers(mParameters);
call.enqueue(new Callback<List<User>>() {
    @Override
    public void onResponse(Call<List<User>> call, Response<List<User>> response) {
        mResponse = response.body();
        mResponseObserver.onFinish(mResponse);
    }

    @Override
    public void onFailure(Call<List<User>> call, Throwable t) {
        mResponseObserver.onFailure();
    }
});
</code>```

But server rejects it as it reached the server in GET request form !? Having checked with debugger, I saw that:

rawResponse.request.method = GET

Here is screenshot of watch window showing the retrofit's request object:

As you can see, the request method was GET. But the weird part is in the tag, it shows a request object with POST method?

Am i miss something here?

UPDATE

I added logging interceptor & here is the log:

```<code>D/OkHttp: --> POST http://***/api/users/ http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 56
D/OkHttp: --> END POST
D/OkHttp: <-- 200 OK https://***/api/users/ (388ms)
D/OkHttp: Date: Thu, 01 Sep 2016 11:50:23 GMT
D/OkHttp: Server: Apache
D/OkHttp: X-Powered-By: PHP/5.4.34
D/OkHttp: Cache-Control: max-age=2592000
D/OkHttp: Expires: Sat, 01 Oct 2016 11:50:23 GMT
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: Set-Cookie: SESSION_DEFAULT=***; expires=Sun, 04-Sep-2016 11:50:24 GMT; path=/; HttpOnly
D/OkHttp: Set-Cookie: COOKIE[***]=***; path=/; httponly
D/OkHttp: Connection: close
D/OkHttp: <-- END HTTP
</code>```

looks like the request is a POST. But, the server still responds with error message, saying that the request method is a GET

Hmm, I'll dig a little bit more into it.

答:
That is partly correct a http client behavior. According to the HTTP spec

If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Sometime it is not possible to change backend API. So here a workaround you can add to you interceptor to manually redirect a request with correct method.

```<code>fun forceRedirectMethod(chain: Interceptor.Chain, originResponse: Response): Response {

    /* TODO
        one more request is made; disable followRedirect and make it manually?
      */
    if (originResponse.priorResponse()?.code() == 302) {
        val priorResponse: Response = originResponse.priorResponse() as Response
        val redirectRequest = priorResponse.request()
        val builder = originResponse.request().newBuilder()
                .method(redirectRequest.method(), redirectRequest.body())
        val newRequest = builder.build()
        return chain.proceed(newRequest)
    } else {
        return originResponse
    }
}
</code>```

Title: Retrofit 2 - POST request became GET?

Body:
My POST request keeps sending as GET & got rejected by API endpoint

MyService class

@FormUrlEncoded
@POST("api/users/")
Call<List<User>> getUsers(@FieldMap HashMap<String, String> parameters);

Request code

Gson builder = new GsonBuilder().setLenient().create();
Retrofit client = new Retrofit.Builder()
        .baseUrl(Constants.API_ENDPOINT_TEST_URL)
        .addConverterFactory(GsonConverterFactory.create(builder))
        .build();
mApiService = client.create(MyService.class);
Call<List<User>> call = mApiService.getUsers(mParameters);
call.enqueue(new Callback<List<User>>() {
    @Override
    public void onResponse(Call<List<User>> call, Response<List<User>> response) {
        mResponse = response.body();
        mResponseObserver.onFinish(mResponse);
    }

    @Override
    public void onFailure(Call<List<User>> call, Throwable t) {
        mResponseObserver.onFailure();
    }
});

But server rejects it as it reached the server in GET request form !? Having checked with debugger, I saw that:

rawResponse.request.method = GET

Here is screenshot of watch window showing the retrofit's request object:

As you can see, the request method was GET. But the weird part is in the tag, it shows a request object with POST method?

Am i miss something here?

UPDATE

I added logging interceptor & here is the log:

D/OkHttp: --> POST http://***/api/users/ http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 56
D/OkHttp: --> END POST
D/OkHttp: <-- 200 OK https://***/api/users/ (388ms)
D/OkHttp: Date: Thu, 01 Sep 2016 11:50:23 GMT
D/OkHttp: Server: Apache
D/OkHttp: X-Powered-By: PHP/5.4.34
D/OkHttp: Cache-Control: max-age=2592000
D/OkHttp: Expires: Sat, 01 Oct 2016 11:50:23 GMT
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: Set-Cookie: SESSION_DEFAULT=***; expires=Sun, 04-Sep-2016 11:50:24 GMT; path=/; HttpOnly
D/OkHttp: Set-Cookie: COOKIE[***]=***; path=/; httponly
D/OkHttp: Connection: close
D/OkHttp: <-- END HTTP

looks like the request is a POST. But, the server still responds with error message, saying that the request method is a GET

Hmm, I'll dig a little bit more into it.

Body:
That is partly correct a http client behavior. According to the HTTP spec

If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Sometime it is not possible to change backend API. So here a workaround you can add to you interceptor to manually redirect a request with correct method.

fun forceRedirectMethod(chain: Interceptor.Chain, originResponse: Response): Response {

    /* TODO
        one more request is made; disable followRedirect and make it manually?
      */
    if (originResponse.priorResponse()?.code() == 302) {
        val priorResponse: Response = originResponse.priorResponse() as Response
        val redirectRequest = priorResponse.request()
        val builder = originResponse.request().newBuilder()
                .method(redirectRequest.method(), redirectRequest.body())
        val newRequest = builder.build()
        return chain.proceed(newRequest)
    } else {
        return originResponse
    }
}


问:
Can't use WC_Order in admin-ajax.php
I'm trying to retrieve order information within the admin-ajax.php request, but it is returning protected objects with no data. Is there a way to access this?

I'm using this:

```<code>$data = new WC_Order($order_id);
var_dump($data);
</code>```

This works when it is run within this:

```<code>add_action('woocommerce_order_status_completed', 'send_documents_to_customer');
</code>```

But I also need to run this as an admin ajax request:

```<code>add_action('wp_ajax_send_documents_to_customer', 'send_documents_to_customer');
</code>```

But it returns protected:

object(WC_Order)#15861 (14) { ["status_transition":protected]=> bool(false) ["data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["items":protected]=> array(1) { ["line_items"]=> array(0) { } } ["items_to_delete":protected]=> array(0) { } ["cache_group":protected]=> string(6) "orders" ["data_store_name":protected]=> string(5) "order" ["object_type":protected]=> string(5) "order" ["id":protected]=> int(0) ["changes":protected]=> array(0) { } ["object_read":protected]=> bool(true) ["extra_data":protected]=> array(0) { } ["default_data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["data_store":protected]=> object(WC_Data_Store)#15862 (4) { ["instance":"WC_Data_Store":private]=> object(WC_Order_Data_Store_CPT)#15863 (3) { ["internal_meta_keys":protected]=> array(49) { [0]=> string(14) "_customer_user" [1]=> string(10) "_order_key" [2]=> string(15) "_order_currency" [3]=> string(19) "_billing_first_name" [4]=> string(18) "_billing_last_name" [5]=> string(16) "_billing_company" [6]=> string(18) "_billing_address_1" [7]=> string(18) "_billing_address_2" [8]=> string(13) "_billing_city" [9]=> string(14) "_billing_state" [10]=> string(17) "_billing_postcode" [11]=> string(16) "_billing_country" [12]=> string(14) "_billing_email" [13]=> string(14) "_billing_phone" [14]=> string(20) "_shipping_first_name" [15]=> string(19) "_shipping_last_name" [16]=> string(17) "_shipping_company" [17]=> string(19) "_shipping_address_1" [18]=> string(19) "_shipping_address_2" [19]=> string(14) "_shipping_city" [20]=> string(15) "_shipping_state" [21]=> string(18) "_shipping_postcode" [22]=> string(17) "_shipping_country" [23]=> string(15) "_completed_date" [24]=> string(10) "_paid_date" [25]=> string(10) "_edit_lock" [26]=> string(10) "_edit_last" [27]=> string(14) "_cart_discount" [28]=> string(18) "_cart_discount_tax" [29]=> string(15) "_order_shipping" [30]=> string(19) "_order_shipping_tax" [31]=> string(10) "_order_tax" [32]=> string(12) "_order_total" [33]=> string(15) "_payment_method" [34]=> string(21) "_payment_method_title" [35]=> string(15) "_transaction_id" [36]=> string(20) "_customer_ip_address" [37]=> string(20) "_customer_user_agent" [38]=> string(12) "_created_via" [39]=> string(14) "_order_version" [40]=> string(19) "_prices_include_tax" [41]=> string(15) "_date_completed" [42]=> string(10) "_date_paid" [43]=> string(15) "_payment_tokens" [44]=> string(22) "_billing_address_index" [45]=> string(23) "_shipping_address_index" [46]=> string(15) "_recorded_sales" [47]=> string(29) "_recorded_coupon_usage_counts" [48]=> string(16) "_shipping_method" } ["meta_type":protected]=> string(4) "post" ["object_id_field_for_meta":protected]=> string(0) "" } ["stores":"WC_Data_Store":private]=> array(18) { ["coupon"]=> string(24) "WC_Coupon_Data_Store_CPT" ["customer"]=> string(22) "WC_Customer_Data_Store" ["customer-download"]=> string(31) "WC_Customer_Download_Data_Store" ["customer-session"]=> string(30) "WC_Customer_Data_Store_Session" ["order"]=> string(23) "WC_Order_Data_Store_CPT" ["order-refund"]=> string(30) "WC_Order_Refund_Data_Store_CPT" ["order-item"]=> string(24) "WC_Order_Item_Data_Store" ["order-item-coupon"]=> string(31) "WC_Order_Item_Coupon_Data_Store" ["order-item-fee"]=> string(28) "WC_Order_Item_Fee_Data_Store" ["order-item-product"]=> string(32) "WC_Order_Item_Product_Data_Store" ["order-item-shipping"]=> string(33) "WC_Order_Item_Shipping_Data_Store" ["order-item-tax"]=> string(28) "WC_Order_Item_Tax_Data_Store" ["payment-token"]=> string(27) "WC_Payment_Token_Data_Store" ["product"]=> string(25) "WC_Product_Data_Store_CPT" ["product-grouped"]=> string(33) "WC_Product_Grouped_Data_Store_CPT" ["product-variable"]=> string(34) "WC_Product_Variable_Data_Store_CPT" ["product-variation"]=> string(35) "WC_Product_Variation_Data_Store_CPT" ["shipping-zone"]=> string(27) "WC_Shipping_Zone_Data_Store" } ["current_class_name":"WC_Data_Store":private]=> string(23) "WC_Order_Data_Store_CPT" ["object_type":"WC_Data_Store":private]=> string(5) "order" } ["meta_data":protected]=> NULL }

答:
It turned out that $order_id wasn't actually passing a value to admin-ajax.php:

function send_documents_to_customer($order_id) {

So I wrote the below in:

```<code>if(is_admin() && !$order_id > 0 && isset($_GET['order_id'])) {
    $order_id = $_GET['order_id'];
}
</code>```

This ensures a valid value is always set.

Title: Can't use WC_Order in admin-ajax.php

Body:
I'm trying to retrieve order information within the admin-ajax.php request, but it is returning protected objects with no data. Is there a way to access this?

I'm using this:

$data = new WC_Order($order_id);
var_dump($data);

This works when it is run within this:

add_action('woocommerce_order_status_completed', 'send_documents_to_customer');

But I also need to run this as an admin ajax request:

add_action('wp_ajax_send_documents_to_customer', 'send_documents_to_customer');

But it returns protected:

object(WC_Order)#15861 (14) { ["status_transition":protected]=> bool(false) ["data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["items":protected]=> array(1) { ["line_items"]=> array(0) { } } ["items_to_delete":protected]=> array(0) { } ["cache_group":protected]=> string(6) "orders" ["data_store_name":protected]=> string(5) "order" ["object_type":protected]=> string(5) "order" ["id":protected]=> int(0) ["changes":protected]=> array(0) { } ["object_read":protected]=> bool(true) ["extra_data":protected]=> array(0) { } ["default_data":protected]=> array(28) { ["parent_id"]=> int(0) ["status"]=> string(0) "" ["currency"]=> string(0) "" ["version"]=> string(0) "" ["prices_include_tax"]=> bool(false) ["date_created"]=> NULL ["date_modified"]=> NULL ["discount_total"]=> int(0) ["discount_tax"]=> int(0) ["shipping_total"]=> int(0) ["shipping_tax"]=> int(0) ["cart_tax"]=> int(0) ["total"]=> int(0) ["total_tax"]=> int(0) ["customer_id"]=> int(0) ["order_key"]=> string(0) "" ["billing"]=> array(11) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" ["email"]=> string(0) "" ["phone"]=> string(0) "" } ["shipping"]=> array(9) { ["first_name"]=> string(0) "" ["last_name"]=> string(0) "" ["company"]=> string(0) "" ["address_1"]=> string(0) "" ["address_2"]=> string(0) "" ["city"]=> string(0) "" ["state"]=> string(0) "" ["postcode"]=> string(0) "" ["country"]=> string(0) "" } ["payment_method"]=> string(0) "" ["payment_method_title"]=> string(0) "" ["transaction_id"]=> string(0) "" ["customer_ip_address"]=> string(0) "" ["customer_user_agent"]=> string(0) "" ["created_via"]=> string(0) "" ["customer_note"]=> string(0) "" ["date_completed"]=> NULL ["date_paid"]=> NULL ["cart_hash"]=> string(0) "" } ["data_store":protected]=> object(WC_Data_Store)#15862 (4) { ["instance":"WC_Data_Store":private]=> object(WC_Order_Data_Store_CPT)#15863 (3) { ["internal_meta_keys":protected]=> array(49) { [0]=> string(14) "_customer_user" [1]=> string(10) "_order_key" [2]=> string(15) "_order_currency" [3]=> string(19) "_billing_first_name" [4]=> string(18) "_billing_last_name" [5]=> string(16) "_billing_company" [6]=> string(18) "_billing_address_1" [7]=> string(18) "_billing_address_2" [8]=> string(13) "_billing_city" [9]=> string(14) "_billing_state" [10]=> string(17) "_billing_postcode" [11]=> string(16) "_billing_country" [12]=> string(14) "_billing_email" [13]=> string(14) "_billing_phone" [14]=> string(20) "_shipping_first_name" [15]=> string(19) "_shipping_last_name" [16]=> string(17) "_shipping_company" [17]=> string(19) "_shipping_address_1" [18]=> string(19) "_shipping_address_2" [19]=> string(14) "_shipping_city" [20]=> string(15) "_shipping_state" [21]=> string(18) "_shipping_postcode" [22]=> string(17) "_shipping_country" [23]=> string(15) "_completed_date" [24]=> string(10) "_paid_date" [25]=> string(10) "_edit_lock" [26]=> string(10) "_edit_last" [27]=> string(14) "_cart_discount" [28]=> string(18) "_cart_discount_tax" [29]=> string(15) "_order_shipping" [30]=> string(19) "_order_shipping_tax" [31]=> string(10) "_order_tax" [32]=> string(12) "_order_total" [33]=> string(15) "_payment_method" [34]=> string(21) "_payment_method_title" [35]=> string(15) "_transaction_id" [36]=> string(20) "_customer_ip_address" [37]=> string(20) "_customer_user_agent" [38]=> string(12) "_created_via" [39]=> string(14) "_order_version" [40]=> string(19) "_prices_include_tax" [41]=> string(15) "_date_completed" [42]=> string(10) "_date_paid" [43]=> string(15) "_payment_tokens" [44]=> string(22) "_billing_address_index" [45]=> string(23) "_shipping_address_index" [46]=> string(15) "_recorded_sales" [47]=> string(29) "_recorded_coupon_usage_counts" [48]=> string(16) "_shipping_method" } ["meta_type":protected]=> string(4) "post" ["object_id_field_for_meta":protected]=> string(0) "" } ["stores":"WC_Data_Store":private]=> array(18) { ["coupon"]=> string(24) "WC_Coupon_Data_Store_CPT" ["customer"]=> string(22) "WC_Customer_Data_Store" ["customer-download"]=> string(31) "WC_Customer_Download_Data_Store" ["customer-session"]=> string(30) "WC_Customer_Data_Store_Session" ["order"]=> string(23) "WC_Order_Data_Store_CPT" ["order-refund"]=> string(30) "WC_Order_Refund_Data_Store_CPT" ["order-item"]=> string(24) "WC_Order_Item_Data_Store" ["order-item-coupon"]=> string(31) "WC_Order_Item_Coupon_Data_Store" ["order-item-fee"]=> string(28) "WC_Order_Item_Fee_Data_Store" ["order-item-product"]=> string(32) "WC_Order_Item_Product_Data_Store" ["order-item-shipping"]=> string(33) "WC_Order_Item_Shipping_Data_Store" ["order-item-tax"]=> string(28) "WC_Order_Item_Tax_Data_Store" ["payment-token"]=> string(27) "WC_Payment_Token_Data_Store" ["product"]=> string(25) "WC_Product_Data_Store_CPT" ["product-grouped"]=> string(33) "WC_Product_Grouped_Data_Store_CPT" ["product-variable"]=> string(34) "WC_Product_Variable_Data_Store_CPT" ["product-variation"]=> string(35) "WC_Product_Variation_Data_Store_CPT" ["shipping-zone"]=> string(27) "WC_Shipping_Zone_Data_Store" } ["current_class_name":"WC_Data_Store":private]=> string(23) "WC_Order_Data_Store_CPT" ["object_type":"WC_Data_Store":private]=> string(5) "order" } ["meta_data":protected]=> NULL }

Body:
It turned out that $order_id wasn't actually passing a value to admin-ajax.php:

function send_documents_to_customer($order_id) {

So I wrote the below in:

if(is_admin() && !$order_id > 0 && isset($_GET['order_id'])) {
    $order_id = $_GET['order_id'];
}

This ensures a valid value is always set.


问:
Why isn't arr[-2] equivalent to -2[arr]?
```<code>#include <iostream>
using namespace std;

int main()
{
    int arr[3] = { 10, 20, 30 };
    cout << arr[-2] << endl;
    cout << -2[arr] << endl;
    return 0;
}
</code>```

Output:

```<code>4196160
-30
</code>```

Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?

答:
-2[arr] is equivalent to -(2[arr]), which is equivalent to -arr[2]. However, (-2)[arr] is equivalent to arr[-2].

This is because E1[E2] is identical to (*((E1)+(E2)))

Body:
#include <iostream>
using namespace std;

int main()
{
    int arr[3] = { 10, 20, 30 };
    cout << arr[-2] << endl;
    cout << -2[arr] << endl;
    return 0;
}

Output:

4196160
-30

Here arr[-2] is out of range and invalid, causing undefined behavior.
But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?


问:
MouseListener doesn't work the first time
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

```<code>private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });
</code>```

Does anyone know how to fix it in order to work from the first click and hide the current frame?

答:
Use n2.dispose() instead n2.setVisible(false);

This is a simple example for you but as others said multiple JFrame in same application is not good. Rather than try one JFrame and JPanel with with a appropriate layout.

```<code>import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
    JFrame MainFrame;
    JFrame ChildFrame;
    JLabel label;

    public Main(){
        MainFrame = new JFrame("Example");
        MainFrame.setSize(300, 300);

        label = new JLabel("Click me");
        labelMousePressed();
        MainFrame.add(label);
        MainFrame.setVisible(true);
    }
    private void labelMousePressed() {
        label.addMouseListener(new MouseAdapter(){

            public void mousePressed(MouseEvent e){
                System.out.println("It works.");

                MainFrame.dispose();

                ChildFrame = new JFrame("Child");
                ChildFrame.setSize(300, 300);
                ChildFrame.setVisible(true);
            }
        });
    }
    public static void main(String[] args) {
        Main m = new Main();
    }
}
</code>```

UPDATE

If you donot override the methods in JFrame, it is unnecessary to extends(inherit) JFrame class. Rather than that create a object from JFrame and use it. read this question to learn more about this.

Body:
I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }
    });

Does anyone know how to fix it in order to work from the first click and hide the current frame?

Body:
Use n2.dispose() instead n2.setVisible(false);

This is a simple example for you but as others said multiple JFrame in same application is not good. Rather than try one JFrame and JPanel with with a appropriate layout.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
    JFrame MainFrame;
    JFrame ChildFrame;
    JLabel label;

    public Main(){
        MainFrame = new JFrame("Example");
        MainFrame.setSize(300, 300);

        label = new JLabel("Click me");
        labelMousePressed();
        MainFrame.add(label);
        MainFrame.setVisible(true);
    }
    private void labelMousePressed() {
        label.addMouseListener(new MouseAdapter(){

            public void mousePressed(MouseEvent e){
                System.out.println("It works.");

                MainFrame.dispose();

                ChildFrame = new JFrame("Child");
                ChildFrame.setSize(300, 300);
                ChildFrame.setVisible(true);
            }
        });
    }
    public static void main(String[] args) {
        Main m = new Main();
    }
}

UPDATE

If you donot override the methods in JFrame, it is unnecessary to extends(inherit) JFrame class. Rather than that create a object from JFrame and use it. read this question to learn more about this.